blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
a990ac133a7dc8d722ee88fac6bcb433ff01a70c
cd253cf36e5ae02453adadbc144438ef6b047bd6
/src/main/java/levantuan/quanlykaraoke/dto/PhongDTO.java
85ff426b9ffe7e9402a1c31c53b4514253f9f952
[]
no_license
phuongjsp/QLKaraoke
0c645b1c77d9d2af29ed7fd09e0573cb78507df5
0ae030015e1530deb00f89f28a0b3d7834db220e
refs/heads/master
2022-07-01T02:22:48.195984
2020-07-02T05:24:43
2020-07-02T05:24:43
184,918,522
0
2
null
2020-07-02T05:24:44
2019-05-04T16:23:50
JavaScript
UTF-8
Java
false
false
1,237
java
package levantuan.quanlykaraoke.dto; import levantuan.quanlykaraoke.entities.Phong; import levantuan.quanlykaraoke.entities.ChiTietVatTu; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @AllArgsConstructor @NoArgsConstructor @Data public class PhongDTO { private long id; private String maPhong; private int tinhTrangPhong; private Long idLoaiPhong; private String tenLoaiPhong; private int giaTrenGio; public PhongDTO(Phong phong) { this.id = phong.getId(); this.maPhong = phong.getMaPhong(); this.giaTrenGio = phong.getLoaiPhong().getTienPhongTrenGio(); this.tinhTrangPhong = phong.getTinhTrangPhong(); this.idLoaiPhong = phong.getLoaiPhong().getId(); this.tenLoaiPhong = phong.getLoaiPhong().getLoaiPhong(); } public void setPhong(Phong phong) { this.id = phong.getId(); this.maPhong = phong.getMaPhong(); this.tinhTrangPhong = phong.getTinhTrangPhong(); this.idLoaiPhong = phong.getLoaiPhong().getId(); this.tenLoaiPhong = phong.getLoaiPhong().getLoaiPhong(); } List<ChiTietVatTu> vatTus; List<UpdatePhongDTO> updatePhongDTOS; }
[ "phuong.jsp@gmail.com" ]
phuong.jsp@gmail.com
c77e267d46947ebf498a981e0a407ca90e5cd7ec
c5196e5b4403f1d807f3be3ad94a7a8d6269d66a
/src/main/java/me/perol/blog/service/RedisService.java
bebb99d9208d62b50a68bc03d32ad3a780fdcc2e
[]
no_license
Notsfsssf/neo-back-end
b52ce3a70586a4a950136e51a9df48a4c5f77857
5c4b8cd56e96cc240d7200a4c8c1c8e42130a4f6
refs/heads/master
2021-07-23T11:04:19.923998
2020-07-29T14:38:13
2020-07-29T14:38:13
202,300,173
2
0
null
null
null
null
UTF-8
Java
false
false
329
java
package me.perol.blog.service; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class RedisService { @Cacheable(value = "token", condition = "#age!=1") public String getit(int age) { return String.valueOf(System.currentTimeMillis()); } }
[ "asdplk3@live.com" ]
asdplk3@live.com
f54aad47c53ab7f9dd366b3c758db19520b78cd2
cc49e2302960153187e99a42baa235776019521e
/03_HelloGit/src/com/kh/git/Test1.java
b5d7557aa9cba9f59455226892ce0853410d1fb7
[]
no_license
heewoon1204/helloGit
3426e4f97e5520db917ff4f9627ddba1858df1e9
090ecacbf25e886ecd6abb4ea4bce1b773f141f4
refs/heads/master
2020-03-19T23:44:37.561581
2018-06-12T04:36:37
2018-06-12T04:36:37
137,017,991
0
0
null
null
null
null
UTF-8
Java
false
false
175
java
package com.kh.git; public class Test1 { public static void main(String[] args) { System.out.println("안녕 깃"); System.out.println("Hello, git"); } }
[ "heewoon1204@naver.com" ]
heewoon1204@naver.com
2c5f6a5f748e491da08e2df8e84cf769fb9ded99
04d8edf348d197b28aba1ae74591ce2d51f83d05
/src/main/java/com/smarthire/main/service/EmployerServiceImpl.java
3be56141944c78051f3e1fd5cf1ffbe8a1891ad1
[]
no_license
xanderLum/SMARTHire
0ccf2d9b4f3c20e13cae05e5a135dd672574fe0f
a23598392f67a34962b4e77dd69760d7016587fa
refs/heads/master
2022-12-28T13:39:48.355151
2019-10-24T18:42:13
2019-10-24T18:42:13
190,709,879
3
1
null
2022-12-16T04:32:57
2019-06-07T08:13:51
Java
UTF-8
Java
false
false
3,190
java
package com.smarthire.main.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.smarthire.main.dao.EmployerDao; import com.smarthire.main.models.Employer; @Service public class EmployerServiceImpl implements EmployerService{ @Autowired EmployerDao employerDao; @Override public ResponseEntity<Employer> create(Employer emp) { try{ employerDao.create(emp); System.out.println("Success in Employer Service Impl create"); return new ResponseEntity<Employer>(emp, HttpStatus.OK); } catch(Exception e){ System.out.println("Catch in Employer Service Impl create"); return new ResponseEntity<Employer>(HttpStatus.BAD_REQUEST); } } @Override public ResponseEntity<Employer> update(Employer emp) { try{ employerDao.update(emp); System.out.println("Success in Employer Service Impl update"); return new ResponseEntity<Employer>(emp, HttpStatus.OK); } catch(Exception e){ System.out.println("Catch in Employer Service Impl update"); return new ResponseEntity<Employer>(HttpStatus.BAD_REQUEST); } } @Override public ResponseEntity<Employer> delete(Long id) { try{ Employer emp = employerDao.delete(id); System.out.println("Success in Employer Service Impl delete"); return new ResponseEntity<Employer>(emp, HttpStatus.OK); } catch(Exception e){ System.out.println("Catch in Employer Service Impl delete"); return new ResponseEntity<Employer>(HttpStatus.BAD_REQUEST); } } @Override public ResponseEntity<List<Employer>> getList() { try{ List<Employer> lemp = employerDao.getList(); System.out.println("Success in Employer Service Impl getList"); return new ResponseEntity<List<Employer>>(lemp, HttpStatus.OK); } catch(Exception e){ System.out.println("Catch in Employer Service Impl getList"); return new ResponseEntity<List<Employer>>(HttpStatus.BAD_REQUEST); } } @Override public ResponseEntity<Employer> authenticate(String username, String password) { Employer flag = new Employer(); try{ flag = employerDao.authenticate(username, password); System.out.println("Success in Employer Service Impl "); if(flag != null){ System.out.println("There is a record Employer authenticate"); return new ResponseEntity<Employer>(flag, HttpStatus.OK); } else{ System.out.println("There is NO record Employer authenticate"); return new ResponseEntity<Employer>(HttpStatus.BAD_REQUEST); } } catch(Exception e){ System.out.println("Catch in Employer Service Impl authenticate"); return new ResponseEntity<Employer>(HttpStatus.BAD_REQUEST); } } @Override public ResponseEntity<Employer> read(String username) { try{ Employer emp = employerDao.read(username); System.out.println("Success in Employer Service Impl read"); return new ResponseEntity<Employer>(emp, HttpStatus.OK); } catch(Exception e){ System.out.println("Catch in Employer Service Impl read"); return new ResponseEntity<Employer>(HttpStatus.BAD_REQUEST); } } }
[ "xander.lumapac@gmail.com" ]
xander.lumapac@gmail.com
72f54383870a653dde7503bbb6b30c36b4d1a36e
7bd2d65d1adc6e7c47523f5dafc20d0fe857fab1
/tarea extra yasmany/concatenar/src/concatenar/InterfaceGrafo.java
3f35df269a0abf73632f1222404699f1d2d12c17
[]
no_license
ymadrazovalladares/java
d5d0d54508f3d50daa885d54f87f16b0735079a6
433446cb8f47feddc76caed8f2e1546fbee3279d
refs/heads/master
2020-04-01T02:51:12.816743
2019-02-18T18:32:43
2019-02-18T18:32:43
152,798,212
0
0
null
null
null
null
UTF-8
Java
false
false
412
java
package concatenar; import java.util.ArrayList; public interface InterfaceGrafo<T> { void addNodo(T valor); void addAdyacentes(T nodo, T esAdyacenteA); void addAdyacentes(T nodo, T esAdyacenteA, Integer ponderacion); Object[] getNodos(); Object[] getListadeNodosdeQuienEsAdyacente(T nodo); void eliminarAdyacentes(T nodo, T dejaDeSerAdyacenteA); void eliminaNodo(T nodo); }
[ "44099454+ymadrazovalladares@users.noreply.github.com" ]
44099454+ymadrazovalladares@users.noreply.github.com
aa52dedc88008e65196ee072463586b817136ed2
8d816548fa2fcf3ef501ca3fc379266333c729c6
/app/src/main/java/com/lalbhaibrokers/mobilepolicing/DocumentVerification.java
d0523bab6bb7ae6de8de166593e3d82a16b76f05
[]
no_license
hetsukhwani/MobilePolicing
418e0f2616c75d96d9cfa1f1e935e2f287cf2cb1
ecdba2b226b520f0daed1651c2311b0a6155813c
refs/heads/master
2023-03-02T18:21:44.707182
2021-02-16T07:13:34
2021-02-16T07:13:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
371
java
package com.lalbhaibrokers.mobilepolicing; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class DocumentVerification extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_document_verification); } }
[ "hardikt7999@gmail.com" ]
hardikt7999@gmail.com
3169a3790326529b6bb004f585196d8c2847018c
8aeaa60c93463b72799b8d0d108d1afd96a02731
/src/main/java/com/ds/springexample/service/ProductManagerService.java
8b87790834d00dbd49d851da3a3b18797b4699d8
[]
no_license
malathiarumugam/spring
77e85da5a989faac7ddefd434c7c703e2cbb456e
8cfe181d98eb1081983fae057252ab53085b2d92
refs/heads/master
2020-04-10T08:43:35.397174
2016-07-22T05:57:09
2016-07-22T05:57:09
50,033,054
1
8
null
null
null
null
UTF-8
Java
false
false
1,210
java
package com.ds.springexample.service; import com.ds.springexample.dao.ProductRepository; import com.ds.springexample.model.Product; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * @author Dogukan Sonmez */ @Service public class ProductManagerService { private static final Logger logger = LoggerFactory.getLogger(ProductManagerService.class); @Autowired private ProductRepository repository; public Product getProductById(Long id) { if (id != null) { return repository.get(id); } else { return new Product(); } } public List getAllProducts() { return repository.getAll(); } public void saveProduct(Product product) { logger.info("-------------Service product: " + product); repository.save(product); } public void updateProduct(Product product) { repository.update(product); } public void deleteProduct(Long id) { } }
[ "dogukansonmez@yahoo.com" ]
dogukansonmez@yahoo.com
bf5e50ac74fccaefdfadba96241f811870028ab8
4b25fdf8aefc6035df743141a4e14bbf33c28f47
/src/main/java/com/containers/SimpleHashMap.java
7756739729379a16eb6866cd87ac50b59934acde
[]
no_license
Linklmm/thinkInJava
5be0f014c6641ad522f93e816984b529ef08576a
644346757575d87cd35beb1f55d5835f7667d9eb
refs/heads/master
2020-03-26T16:18:02.950337
2019-11-29T03:00:17
2019-11-29T03:00:17
145,092,648
1
0
null
null
null
null
UTF-8
Java
false
false
2,099
java
package com.containers; import java.util.*; /** * @author lmm * @Title: SimpleHashMap * @ProjectName thinkInJava * @Description: TODO * @date 19-1-11上午10:13 */ public class SimpleHashMap<K, V> extends AbstractMap<K, V> { static final int SIZE = 997; @SuppressWarnings("unchecked") LinkedList<MapEntry<K, V>>[] buckets = new LinkedList[SIZE]; @Override public V put(K key, V value) { V oldValue = null; //abs函数返回参数的绝对值 int index = Math.abs(key.hashCode()) % SIZE; if (buckets[index] == null) { buckets[index] = new LinkedList<MapEntry<K, V>>(); } LinkedList<MapEntry<K, V>> bucket = buckets[index]; //创建传进来的mapEntry MapEntry<K, V> pair = new MapEntry<K, V>(key, value); boolean found = false; ListIterator<MapEntry<K, V>> it = bucket.listIterator(); while (it.hasNext()) { MapEntry<K, V> ipair = it.next(); //如果传进来的key已存在那么 if (ipair.getKey().equals(key)) { oldValue = ipair.getValue(); //将旧值换成新值 it.set(pair); found = true; break; } } if (!found) { buckets[index].add(pair); } return oldValue; } @Override public V get(Object key){ int index = Math.abs(key.hashCode())%SIZE; if (buckets[index] == null){ return null; } for (MapEntry<K,V> ipair : buckets[index]) { if (ipair.getKey().equals(key)){ return ipair.getValue(); } } return null; } @Override public Set<Entry<K, V>> entrySet() { Set<Map.Entry<K,V>> set = new HashSet<Entry<K, V>>(); for (LinkedList<MapEntry<K,V>> bucket : buckets){ if (bucket == null){ continue;} for (MapEntry<K,V> mpair : bucket){ set.add(mpair); } } return set; } }
[ "1248332941@qq.com" ]
1248332941@qq.com
3d647bd7b4e0b618324860cfd525295182e7bbcf
ad05c654b4c553e812021efc925e6541178cfd58
/src/test/java/com/oltruong/teamag/model/AbstractEntityIT.java
ab3852796923e42975f336a663c17ca5aaaf8306
[ "MIT" ]
permissive
oltruong/teamag
1d945541b4ad6423b9b3eb80080c73ae72b9701c
1550f891154a0d6359256dbe4b3fadb07bdf7854
refs/heads/master
2021-01-18T22:07:52.783839
2019-07-11T11:50:23
2019-07-11T11:50:28
5,967,421
5
2
null
2016-12-20T11:53:25
2012-09-26T14:55:35
Java
UTF-8
Java
false
false
1,297
java
package com.oltruong.teamag.model; import org.junit.After; import org.junit.Before; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public abstract class AbstractEntityIT { protected EntityManagerFactory entityManagerFactory; protected EntityManager entityManager; protected EntityTransaction transaction; @Before public void setup() { entityManagerFactory = Persistence.createEntityManagerFactory("testPersistence"); entityManager = entityManagerFactory.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); } @After public void tearDown() { entityManager.close(); entityManagerFactory.close(); } protected Object createWithoutCommit(Object object) { entityManager.persist(object); return object; } protected Object createWithCommit(Object object) { object = createWithoutCommit(object); transaction.commit(); return object; } protected void commit() { transaction.commit(); } protected void persist(Object object) { entityManager.persist(object); } }
[ "oliv.truong@gmail.com" ]
oliv.truong@gmail.com
0b31049d64c074bfb7d204cd4395961d1455b6e9
aa2ba134b14b214172de43f7d84c9f75a8d75151
/src/test/java/com/milfist/springbootservice/service/DataByIdTest.java
24af87dd3ddd87803735b39d0ee23728546e1e59
[]
no_license
Milfist/springboot-war-jar-keycloak-https
a057bdb25b56458bbaa5e4bacf596ea0dd02212c
339a04ee100d28980794fc5ef525fa3ba214bf08
refs/heads/master
2022-12-26T07:10:39.027106
2020-10-02T07:49:42
2020-10-02T07:49:42
298,254,817
0
0
null
null
null
null
UTF-8
Java
false
false
1,311
java
package com.milfist.springbootservice.service; import com.google.gson.Gson; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import java.io.FileNotFoundException; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @ActiveProfiles("local") @SpringBootTest class DataByIdTest { @Autowired DataById dataById; @Test void givenCorrectID_call_getOptionsById_thenReturn_OK() throws Exception { String json = dataById.getDataById("data"); Data data = new Gson().fromJson(json, Data.class); assertAll("data", ()-> assertEquals("Servicio", data.getTitle()), ()-> assertEquals(0, data.getOptions().size()) ); } @Test void givenWrongID_call_getOptionsById_thenReturn_FileNorFoundException() { assertThrows(FileNotFoundException.class, () -> dataById.getDataById("data2")); } @Test void givenCorrectID_withEmptyFile_thenReturnEmptyString() throws Exception { String json = dataById.getDataById("data_null"); assertEquals("", json); } } @lombok.Data class Data { private String title; private List<String> options; private Object security; }
[ "milfist@gmail.com" ]
milfist@gmail.com
b20b42b6477df0dcdc6165d8cdc5924c1463cf31
c3c26f2aa42dba0e78e09f8fdd330be21515566f
/app/src/main/java/com/example/mycalendar/Event.java
167a0a645aead8165c2a4b53e9a067a2104a8e09
[]
no_license
tmnguyen1403/AndroidCalendar
4f415b0bcf1ad803aff6258cc65d70551e138e36
1de5ba448a6b6ca96c6141c688f64cede991ce9a
refs/heads/main
2023-01-08T17:17:29.915645
2020-11-11T05:26:24
2020-11-11T05:26:24
311,789,337
1
0
null
null
null
null
UTF-8
Java
false
false
803
java
package com.example.mycalendar; import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; public class Event { public String id; public String name; public String description; public String location; public String startDate; public String endDate; public String startTime; public String endTime; public void setData(JSONObject data) throws JSONException { id = data.getString("id"); name = data.getString("name"); description = data.getString("description"); location = data.getString("location"); startDate = data.getString("startDate"); endDate = data.getString("endDate"); startTime = data.getString("startTime"); endTime = data.getString("endTime"); } }
[ "tmnguyen1403@gmail.com" ]
tmnguyen1403@gmail.com
164dfd672fd34751a98176c70be8b70054934a21
df88ba161d4572cbaf49df5db01736c97aa73123
/cloud-comsuer-order81/src/main/java/com/ys/demo/controller/OrderController.java
45a1659d06b7d8475b77b9a45b318acc437d100e
[]
no_license
dzy32/com.ys.clouddemo
89faaed2e5081cd68d98d82a2aeb2a48f349e2cd
5bc1b0f6bb12b15386c6728240bf5ad5d71cb588
refs/heads/master
2023-03-24T11:55:10.447340
2021-03-23T10:37:10
2021-03-23T10:37:10
327,865,648
0
0
null
null
null
null
UTF-8
Java
false
false
1,168
java
package com.ys.demo.controller; import com.ys.demo.VO.ResultVO; import com.ys.demo.entity.Payment; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; /** * @author ys * @date 2021/1/11 9:36 */ @RestController @RequestMapping("/order") @Slf4j public class OrderController { @Autowired private RestTemplate restTemplate; private static final String PAYMNET_URL= "http://payment-service"; @GetMapping("/get/{id}") public ResultVO<Payment> getPay(@PathVariable("id") String id){ return restTemplate.getForObject(PAYMNET_URL.concat("/payment/payment/get/").concat(id),ResultVO.class); } @PostMapping("/add") public ResultVO<Payment> addPay(@RequestBody Payment payment){ return restTemplate.postForObject(PAYMNET_URL.concat("/payment/payment/add"),payment,ResultVO.class); } @GetMapping("/get/zk") public ResultVO<Payment> getPay(){ return restTemplate.getForObject(PAYMNET_URL.concat("/payment/payment/get/zk"),ResultVO.class); } }
[ "1107857837@qq.com" ]
1107857837@qq.com
c2eb7f8394e9b806919605e00a14b591ff909d03
ebbd4e78b717ec83ca7ee55765ac8eb725ae869a
/app/src/main/java/com/gy/recyclerviewadapter/adapter/HomeAdapter.java
0a26f5c3237ef2d82c9791b2042214a9fa8e19a6
[]
no_license
newPersonKing/baseAdapter
9132593b80bb296435a156ac9fbbb502a7e75357
c1bdf08199e637786262c1a10ec54bbd49571d5b
refs/heads/master
2020-03-25T01:40:19.015129
2018-08-02T06:11:48
2018-08-02T06:11:48
143,250,223
0
0
null
null
null
null
UTF-8
Java
false
false
717
java
package com.gy.recyclerviewadapter.adapter; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.gy.recyclerviewadapter.R; import com.gy.recyclerviewadapter.entity.HomeItem; import java.util.List; /** * https://github.com/CymChad/BaseRecyclerViewAdapterHelper */ public class HomeAdapter extends BaseQuickAdapter<HomeItem, BaseViewHolder> { public HomeAdapter(int layoutResId, List data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, HomeItem item) { helper.setText(R.id.text, item.getTitle()); helper.setImageResource(R.id.icon, item.getImageResource()); } }
[ "guoyong@emcc.net.com" ]
guoyong@emcc.net.com
facc3c7cfa59d00722caadacdad98b87bd88b7f2
7091134f1825d13f4c6910933d2248528ebd21a8
/dd/src/com/bb/dd/util/PSOCryptography.java
765ceec64211a80e22d07fd2c175ad0e558cad82
[]
no_license
balancejia/balancejiaGit
365c235200de6f34478c4dbb719d5636efc1272c
3473518bb3d88c62e54f0575df08dfbc7252c3a5
refs/heads/master
2021-01-25T12:13:58.361133
2015-04-21T07:02:31
2015-04-21T07:02:31
27,327,756
0
0
null
null
null
null
UTF-8
Java
false
false
6,255
java
package com.bb.dd.util; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; public class PSOCryptography { private static String CodingType = "UTF-8"; private static String DigestAlgorithm = "SHA1"; private static String CryptAlgorithm = "DESede/CBC/PKCS5Padding"; private static String KeyAlgorithm = "DESede"; private static String strSeparator = "$"; private static byte[] defaultIV = {1,2,3,4,5,6,7,8}; public static String SPID = null; public PSOCryptography() { } static { java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE()); } /** * Function Description Base64���� * @param b ��ҪBase64������ַ����� * @return �������ַ����� * @throws Exception */ public static byte[] Base64Encode(byte[] b) throws Exception { return Base64.encode(b); } /** * Function Description BASE64������ * @param b ��ҪBase64��������ַ����� * @return ���������ַ����� * @throws Exception */ public static byte[] Base64Decode(byte[] b) throws Exception { return Base64.decode(b); } /** * Function Description BASE64������ * @param s ��ҪBase64��������ַ� * @return ���������ַ����� * @throws Exception */ public static byte[] Base64Decode(String s) throws Exception { return Base64.decode(s); } /** * Function Description URL���� * @param strToBeEncode ��ҪURL������ַ� * @return URL�������ַ� * @throws Exception */ public static String URLEncode(String strToBeEncode) throws Exception { return URLEncoder.encode(strToBeEncode); } /** * Function Description URL������ * @param strToBeDecode ��ҪURL��������ַ� * @return URL���������ַ� * @throws Exception */ public static String URLDecode(String strToBeDecode) throws Exception { return URLDecoder.decode(strToBeDecode); } /** * Function Description ���16�����ַ����IV * @param strIV 16�����ַ� * @return �ַ����� * @throws Exception */ public static byte[] IVGenerator(String strIV) throws Exception { return Hex.decode(strIV); } /** * Function Description 3DES���� * @param strTobeEnCrypted Ҫ���ܵ��ַ� * @param strKey ��Կ * @param byteIV ������ * @return ���ܺ���ַ� * @throws Exception */ public static String Encrypt(String strTobeEnCrypted, String strKey, byte[] byteIV) throws Exception { byte[] input = strTobeEnCrypted.getBytes(CodingType); Key k = KeyGenerator(strKey); IvParameterSpec IVSpec = (byteIV.length == 0)?IvGenerator(defaultIV):IvGenerator(byteIV); Cipher c = Cipher.getInstance(CryptAlgorithm); c.init(Cipher.ENCRYPT_MODE,k,IVSpec); byte[] output = c.doFinal(input); return new String(Base64Encode(output),CodingType); } /** * Function Description 3DES���� * @param strTobeDeCrypted Ҫ���ܵ��ַ� * @param strKey ��Կ * @param byteIV ������ * @return ���ܺ���ַ� * @throws Exception */ public static String Decrypt(String strTobeDeCrypted, String strKey, byte[] byteIV) throws Exception { byte[] input = Base64Decode(strTobeDeCrypted); Key k = KeyGenerator(strKey); IvParameterSpec IVSpec = (byteIV.length == 0)?IvGenerator(defaultIV):IvGenerator(byteIV); Cipher c = Cipher.getInstance(CryptAlgorithm); c.init(Cipher.DECRYPT_MODE,k,IVSpec); byte[] output = c.doFinal(input); return new String(output,CodingType); } /*------------------------------------------ * PSOCryptography���ڲ�ʹ�õĹ������� * Modified On: 2003-11-6 * * Modified On: 2005-04-18 * Content: ��ӷ���Hash��Encrypt -----------------------------------------*/ // ˵��: ��ɼӽ����� private static IvParameterSpec IvGenerator(byte[] b) throws Exception { IvParameterSpec IV = new IvParameterSpec(b); return IV; } // ˵��: ���16�����ַ������Կ private static Key KeyGenerator(String KeyStr) throws Exception { byte[] input = Hex.decode(KeyStr); DESedeKeySpec KeySpec = new DESedeKeySpec(input); SecretKeyFactory KeyFactory = SecretKeyFactory.getInstance(KeyAlgorithm); return KeyFactory.generateSecret(KeySpec); } /** * ˵�� ��������ַ����Ƿ����ƶ��ָ��� * ���� String s �����ַ� * char separator �ָ��� * ��� boolean �ǻ�� */ private static boolean hasMoreElement(String s, char separator) { int size = 0; for(int i=0; i<s.length(); i++) { if (s.charAt(i) == separator) size++; } return size>0?true:false; } /** * ˵��: �����ַ�����ij��� * ����: String s - Ҫ���㳤�ȵ��ַ� * ���: int ���� */ private static int length(String[] s) { int length = 0; for(int i=0; i<s.length; i++) { if (s[i] != null) length += s[i].length(); else length += 0; } return length; } }
[ "balancejia@qq.com" ]
balancejia@qq.com
0055469f22a19c199b7747e12798f8bcd7f34617
d41b84a45ef688b14752c0f3b9b07e3955bdbb8a
/android/Whos-Next/mobile/src/main/java/com/wesleyreisz/whos_next/model/Team.java
5c65ced82deb953f9d600ea0fbeb2cd7dfc45f9d
[]
no_license
12019/Android-Wear-Whos-Next
b70314d9ef00bfead52fa946fc57503341e8ff35
ac140333696e3ccad93b5a43b91c2ca35bd43ae7
refs/heads/master
2021-01-12T05:04:32.136017
2015-04-28T00:58:53
2015-04-28T00:58:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,744
java
package com.wesleyreisz.whos_next.model; import java.util.List; public class Team{ private String _id; private String helmet; private String hometown; private String logo; private String nickname; private List<Schedule> schedule; private String team; private String warcry; public String get_id(){ return this._id; } public void set_id(String _id){ this._id = _id; } public String getHelmet(){ return this.helmet; } public void setHelmet(String helmet){ this.helmet = helmet; } public String getHometown(){ return this.hometown; } public void setHometown(String hometown){ this.hometown = hometown; } public String getLogo(){ return this.logo; } public void setLogo(String logo){ this.logo = logo; } public String getNickname(){ return this.nickname; } public void setNickname(String nickname){ this.nickname = nickname; } public List<Schedule> getSchedule(){ return this.schedule; } public void setSchedule(List<Schedule> schedule){ this.schedule = schedule; } public String getTeam(){ return this.team; } public void setTeam(String team){ this.team = team; } public String getWarcry(){ return this.warcry; } public void setWarcry(String warcry){ this.warcry = warcry; } @Override public String toString() { return "Team{" + "_id='" + _id + '\'' + ", helmet='" + helmet + '\'' + ", hometown='" + hometown + '\'' + ", logo='" + logo + '\'' + ", nickname='" + nickname + '\'' + ", schedule=" + schedule + ", team='" + team + '\'' + ", warcry='" + warcry + '\'' + '}'; } }
[ "wes@wesleyreisz.com" ]
wes@wesleyreisz.com
baa66d3b57a9973be8c5061c6b6be745e245b98b
30e2c69e3007ba2e8a54eae66295e785063bc979
/src/main/java/com/demo/challenge/config/RedisConfig.java
6914868fef525a51aa8c90d643af70dfc91a8562
[]
no_license
prashant1982/challenge
83cfbf6de6b0d0f8e77b71156f14774f400b86a7
24d2d2696087c4082361f428e74739cbaeb93818
refs/heads/master
2021-07-14T08:51:46.291551
2017-10-17T09:14:05
2017-10-17T09:14:05
107,241,472
0
0
null
null
null
null
UTF-8
Java
false
false
2,036
java
package com.demo.challenge.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import com.demo.challenge.domain.UserSession; /** * Redis configuration class * * @author Prashant * */ @EnableAutoConfiguration @Configuration @EnableCaching public class RedisConfig /*extends CachingConfigurerSupport*/ { @Value("${spring.redis.host}") private String redisHost; @Value("${spring.redis.port}") private int redisPort; @Bean public JedisConnectionFactory redisConnectionFactory() { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(redisHost); jedisConnectionFactory.setPort(redisPort); jedisConnectionFactory.setUsePool(true); return jedisConnectionFactory; } /*@Bean public RedisSerializer redisStringSerializer() { StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); return stringRedisSerializer; }*/ @Bean//(name = "redisTemplate") public RedisTemplate<String, UserSession> redisTemplateUserSession() { RedisTemplate<String, UserSession> redisTemplate = new RedisTemplate<String, UserSession>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); // redisTemplate.setDefaultSerializer(redisSerializer); return redisTemplate; } @Bean public CacheManager cacheManager() { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplateUserSession()); cacheManager.setUsePrefix(true); return cacheManager; } }
[ "prashant.kumar7@cognizant.com" ]
prashant.kumar7@cognizant.com
81633ccfac2898410b0add0107eb181c03e04ee8
983a178278f21be26a3df50b7f59892cbb53fd1c
/src/structural/facade/subsystem/PhoneProducer.java
7712f3bb02f60048982e0763e02b1b0bbdeee779
[]
no_license
RenatKaitmazov/Design-Patterns
c7397c62cac5239794fcc195f179b98f633d0f81
1d43ed5e8efbb198e176a3c07b1a57d9c263591d
refs/heads/master
2021-01-01T18:24:47.412353
2017-07-28T14:56:56
2017-07-28T14:56:56
98,329,558
0
0
null
null
null
null
UTF-8
Java
false
false
131
java
package structural.facade.subsystem; /** * @author Renat Kaitmazov */ public enum PhoneProducer { APPLE, SAMSUNG, GOOGLE }
[ "renatkaitmazov@gmail.com" ]
renatkaitmazov@gmail.com
88dc73319ba6aec0e9914eaa57ca9396ac2757bf
edd5bb4e61347e8348a74fef9cb54da92384b07c
/simple/src/main/java/simple/common/controller/CommonController.java
b1cd424c2c99d4de8621c52cde221048d71dbf97
[]
no_license
broomy8/simple
2a4f8cb4565accc2347f94fdd564c218e40a6c34
05ae0b7df2fb9383f3883b09315919b81a60de35
refs/heads/master
2021-01-10T12:55:13.165308
2016-04-08T05:06:40
2016-04-08T05:06:40
55,198,384
0
0
null
null
null
null
UTF-8
Java
false
false
1,556
java
package simple.common.controller; import java.io.File; import java.net.URLEncoder; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import simple.common.common.CommandMap; import simple.common.service.CommonService; @Controller public class CommonController { Logger log = Logger.getLogger(this.getClass()); @Resource(name = "commonService") private CommonService commonService; @RequestMapping(value = "/common/downloadFile.do") public void downloadFile(CommandMap commandMap, HttpServletResponse response) throws Exception { Map<String, Object> map = commonService.selectFileInfo(commandMap.getMap()); String storedFileName = (String) map.get("STORED_FILE_NAME"); String originalFileName = (String) map.get("ORIGINAL_FILE_NAME"); byte fileByte[] = FileUtils.readFileToByteArray(new File("d:\\workspace\\file\\" + storedFileName)); response.setContentType("application/octet-stream"); response.setContentLength(fileByte.length); response.setHeader("Content-Disposition", "attachment; fileName=\"" + URLEncoder.encode(originalFileName, "UTF-8") + "\";"); response.setHeader("Content-Transfer-Encoding", "binary"); response.getOutputStream().write(fileByte); response.getOutputStream().flush(); response.getOutputStream().close(); } }
[ "ywpark@naver.com" ]
ywpark@naver.com
c249ca3face64f7d88c5fd16cd34130e121224ec
972549525373bddf7e1ba0f391bc954eed6043c4
/app/src/main/java/com/foodaclic/livraison/utils/event/NetworkOperationEvent.java
beb904d12f821e53fe7482db062f3ad2bdb4c24a
[]
no_license
cyrilleguipie/Livraison
d6b1194c15b045cbe952a79e29afc3a690454a8d
9425e70f899820a3f6a6d25ec698fa05cac85171
refs/heads/master
2020-03-22T15:41:19.912462
2018-07-12T09:39:39
2018-07-12T09:39:39
140,269,872
0
0
null
null
null
null
UTF-8
Java
false
false
3,083
java
package com.foodaclic.livraison.utils.event; public class NetworkOperationEvent { final public static int HAS_FAILED = -1; final public static int COST_UPDATED = 100; final public static int HAS_FINISHED_ALL = 10; final public static int HAS_FINISHED_ONE = 1; final public static int HAS_STARTED = 0; final public static int HAS_NOT_SYNCED = 3; final public static int PARAMS = 2; final public static int HAS_CONTACT_SYNC_STARTED = 200; final public static int HAS_NOTHING = 99; final public static int HAS_ROUTE = 90; final public static int HAS_CHANGED = 9000; final public static int HAS_BT_OK = 444; final public static int HAS_BT_NO = 555; private String mMessage; private int mStatus; private long mId; public int mPosition; private boolean isDataFetching; private boolean route; public NetworkOperationEvent(int status) { this.mStatus = status; } //public NetworkOperationEvent(int status, boolean isDataFetching) { // this(status); // this.isDataFetching = isDataFetching; //} /*public NetworkOperationEvent(int status, int position){ this.mStatus=status; this.mPosition=position; }*/ public NetworkOperationEvent(int status, String message) { this(status, true); this.mMessage = message; } public NetworkOperationEvent(int status, long id) { this(status); this.mId = id; } public NetworkOperationEvent(int status, boolean route) { this(status); this.route = route; } public NetworkOperationEvent(int status, String message, boolean isDataFetching) { this(status); this.mMessage = message; } public long getId() { return mId; } public void setId(long mId) { this.mId = mId; } public String getMessage() { return mMessage; } public boolean hasFailed() { return (mStatus == HAS_FAILED); } public boolean hasNothing() { return (mStatus == HAS_NOTHING); } public boolean hasParameters() { return (mStatus == PARAMS); } public boolean isDataFetching() { return isDataFetching; } public void setDataFetching(boolean dataFetching) { isDataFetching = dataFetching; } public boolean hasFinishedAll() { return (mStatus == HAS_FINISHED_ALL); } public boolean hasFinishedOne() { return (mStatus == HAS_FINISHED_ONE); } public boolean hasStarted() { return (mStatus == HAS_STARTED); } public boolean hasContactSyncStarted() { return (mStatus == HAS_CONTACT_SYNC_STARTED); } public boolean hasCostUpdated() { return (mStatus == COST_UPDATED); } public boolean hasNotSynced() { return (mStatus == HAS_NOT_SYNCED); } public void setMessage(String message) { this.mMessage = message; } public boolean isRoute() { return route; } public boolean hasRoute() { return (mStatus == HAS_ROUTE); } public boolean hasChanged() { return (mStatus == HAS_CHANGED); } public boolean hasBTOK() { return (mStatus == HAS_BT_OK); } public boolean hasBTNO() { return (mStatus == HAS_BT_NO); } }
[ "cyrilleguipie@gmail.com" ]
cyrilleguipie@gmail.com
f51667b48894860c3134f2fbfcf5de362a2f3025
2f79a91a0fa22d7fb321bc5d32f72d2d165e0863
/android/demo/gen/android/support/v7/appcompat/R.java
308c21dbd67682f98ca1b7c7e94d88e8c92b2834
[]
no_license
jiangzhen1984/SkyWorld
e057b02bf2d8f532f8e359bf580ea177689120f1
409c99453ece4247a9487fa99eaffcbb4a01d411
refs/heads/master
2021-01-21T13:56:59.718395
2016-05-29T06:54:12
2016-05-29T06:54:12
49,647,200
0
0
null
null
null
null
UTF-8
Java
false
false
41,086
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package android.support.v7.appcompat; public final class R { public static final class anim { public static final int abc_fade_in = 0x7f040000; public static final int abc_fade_out = 0x7f040001; public static final int abc_slide_in_bottom = 0x7f040002; public static final int abc_slide_in_top = 0x7f040003; public static final int abc_slide_out_bottom = 0x7f040004; public static final int abc_slide_out_top = 0x7f040005; } public static final class attr { public static final int actionBarDivider = 0x7f01000f; public static final int actionBarItemBackground = 0x7f010010; public static final int actionBarSize = 0x7f01000e; public static final int actionBarSplitStyle = 0x7f01000c; public static final int actionBarStyle = 0x7f01000b; public static final int actionBarTabBarStyle = 0x7f010008; public static final int actionBarTabStyle = 0x7f010007; public static final int actionBarTabTextStyle = 0x7f010009; public static final int actionBarWidgetTheme = 0x7f01000d; public static final int actionButtonStyle = 0x7f010016; public static final int actionDropDownStyle = 0x7f010047; public static final int actionLayout = 0x7f01004e; public static final int actionMenuTextAppearance = 0x7f010011; public static final int actionMenuTextColor = 0x7f010012; public static final int actionModeBackground = 0x7f01003c; public static final int actionModeCloseButtonStyle = 0x7f01003b; public static final int actionModeCloseDrawable = 0x7f01003e; public static final int actionModeCopyDrawable = 0x7f010040; public static final int actionModeCutDrawable = 0x7f01003f; public static final int actionModeFindDrawable = 0x7f010044; public static final int actionModePasteDrawable = 0x7f010041; public static final int actionModePopupWindowStyle = 0x7f010046; public static final int actionModeSelectAllDrawable = 0x7f010042; public static final int actionModeShareDrawable = 0x7f010043; public static final int actionModeSplitBackground = 0x7f01003d; public static final int actionModeStyle = 0x7f01003a; public static final int actionModeWebSearchDrawable = 0x7f010045; public static final int actionOverflowButtonStyle = 0x7f01000a; public static final int actionProviderClass = 0x7f010050; public static final int actionViewClass = 0x7f01004f; public static final int activityChooserViewStyle = 0x7f01006c; public static final int background = 0x7f01002f; public static final int backgroundSplit = 0x7f010031; public static final int backgroundStacked = 0x7f010030; public static final int buttonBarButtonStyle = 0x7f010018; public static final int buttonBarStyle = 0x7f010017; public static final int customNavigationLayout = 0x7f010032; public static final int disableChildrenWhenDisabled = 0x7f010054; public static final int displayOptions = 0x7f010028; public static final int divider = 0x7f01002e; public static final int dividerHorizontal = 0x7f01001b; public static final int dividerPadding = 0x7f010056; public static final int dividerVertical = 0x7f01001a; public static final int dropDownListViewStyle = 0x7f010021; public static final int dropdownListPreferredItemHeight = 0x7f010048; public static final int expandActivityOverflowButtonDrawable = 0x7f01006b; public static final int height = 0x7f010026; public static final int homeAsUpIndicator = 0x7f010013; public static final int homeLayout = 0x7f010033; public static final int icon = 0x7f01002c; public static final int iconifiedByDefault = 0x7f01005a; public static final int indeterminateProgressStyle = 0x7f010035; public static final int initialActivityCount = 0x7f01006a; public static final int isLightTheme = 0x7f010059; public static final int itemPadding = 0x7f010037; public static final int listChoiceBackgroundIndicator = 0x7f01004c; public static final int listPopupWindowStyle = 0x7f010022; public static final int listPreferredItemHeight = 0x7f01001c; public static final int listPreferredItemHeightLarge = 0x7f01001e; public static final int listPreferredItemHeightSmall = 0x7f01001d; public static final int listPreferredItemPaddingLeft = 0x7f01001f; public static final int listPreferredItemPaddingRight = 0x7f010020; public static final int logo = 0x7f01002d; public static final int navigationMode = 0x7f010027; public static final int paddingEnd = 0x7f010039; public static final int paddingStart = 0x7f010038; public static final int panelMenuListTheme = 0x7f01004b; public static final int panelMenuListWidth = 0x7f01004a; public static final int popupMenuStyle = 0x7f010049; public static final int popupPromptView = 0x7f010053; public static final int progressBarPadding = 0x7f010036; public static final int progressBarStyle = 0x7f010034; public static final int prompt = 0x7f010051; public static final int queryHint = 0x7f01005b; public static final int searchDropdownBackground = 0x7f01005c; public static final int searchResultListItemHeight = 0x7f010065; public static final int searchViewAutoCompleteTextView = 0x7f010069; public static final int searchViewCloseIcon = 0x7f01005d; public static final int searchViewEditQuery = 0x7f010061; public static final int searchViewEditQueryBackground = 0x7f010062; public static final int searchViewGoIcon = 0x7f01005e; public static final int searchViewSearchIcon = 0x7f01005f; public static final int searchViewTextField = 0x7f010063; public static final int searchViewTextFieldRight = 0x7f010064; public static final int searchViewVoiceIcon = 0x7f010060; public static final int selectableItemBackground = 0x7f010019; public static final int showAsAction = 0x7f01004d; public static final int showDividers = 0x7f010055; public static final int spinnerDropDownItemStyle = 0x7f010058; public static final int spinnerMode = 0x7f010052; public static final int spinnerStyle = 0x7f010057; public static final int subtitle = 0x7f010029; public static final int subtitleTextStyle = 0x7f01002b; public static final int textAllCaps = 0x7f01006d; public static final int textAppearanceLargePopupMenu = 0x7f010014; public static final int textAppearanceListItem = 0x7f010023; public static final int textAppearanceListItemSmall = 0x7f010024; public static final int textAppearanceSearchResultSubtitle = 0x7f010067; public static final int textAppearanceSearchResultTitle = 0x7f010066; public static final int textAppearanceSmallPopupMenu = 0x7f010015; public static final int textColorSearchUrl = 0x7f010068; public static final int title = 0x7f010025; public static final int titleTextStyle = 0x7f01002a; public static final int windowActionBar = 0x7f010000; public static final int windowActionBarOverlay = 0x7f010001; public static final int windowFixedHeightMajor = 0x7f010006; public static final int windowFixedHeightMinor = 0x7f010004; public static final int windowFixedWidthMajor = 0x7f010003; public static final int windowFixedWidthMinor = 0x7f010005; public static final int windowSplitActionBar = 0x7f010002; } public static final class bool { public static final int abc_action_bar_embed_tabs_pre_jb = 0x7f090000; public static final int abc_action_bar_expanded_action_views_exclusive = 0x7f090001; public static final int abc_config_actionMenuItemAllCaps = 0x7f090005; public static final int abc_config_allowActionMenuItemTextWithIcon = 0x7f090004; public static final int abc_config_showMenuShortcutsWhenKeyboardPresent = 0x7f090003; public static final int abc_split_action_bar_is_narrow = 0x7f090002; } public static final class color { public static final int abc_search_url_text_holo = 0x7f06007c; public static final int abc_search_url_text_normal = 0x7f060018; public static final int abc_search_url_text_pressed = 0x7f06001a; public static final int abc_search_url_text_selected = 0x7f060019; } public static final class dimen { public static final int abc_action_bar_default_height = 0x7f0a0002; public static final int abc_action_bar_icon_vertical_padding = 0x7f0a0003; public static final int abc_action_bar_progress_bar_size = 0x7f0a000a; public static final int abc_action_bar_stacked_max_height = 0x7f0a0009; public static final int abc_action_bar_stacked_tab_max_width = 0x7f0a0001; public static final int abc_action_bar_subtitle_bottom_margin = 0x7f0a0007; public static final int abc_action_bar_subtitle_text_size = 0x7f0a0005; public static final int abc_action_bar_subtitle_top_margin = 0x7f0a0006; public static final int abc_action_bar_title_text_size = 0x7f0a0004; public static final int abc_action_button_min_width = 0x7f0a0008; public static final int abc_config_prefDialogWidth = 0x7f0a0000; public static final int abc_dropdownitem_icon_width = 0x7f0a0010; public static final int abc_dropdownitem_text_padding_left = 0x7f0a000e; public static final int abc_dropdownitem_text_padding_right = 0x7f0a000f; public static final int abc_panel_menu_list_width = 0x7f0a000b; public static final int abc_search_view_preferred_width = 0x7f0a000d; public static final int abc_search_view_text_min_width = 0x7f0a000c; public static final int dialog_fixed_height_major = 0x7f0a0013; public static final int dialog_fixed_height_minor = 0x7f0a0014; public static final int dialog_fixed_width_major = 0x7f0a0011; public static final int dialog_fixed_width_minor = 0x7f0a0012; } public static final class drawable { public static final int abc_ab_bottom_solid_dark_holo = 0x7f020000; public static final int abc_ab_bottom_solid_light_holo = 0x7f020001; public static final int abc_ab_bottom_transparent_dark_holo = 0x7f020002; public static final int abc_ab_bottom_transparent_light_holo = 0x7f020003; public static final int abc_ab_share_pack_holo_dark = 0x7f020004; public static final int abc_ab_share_pack_holo_light = 0x7f020005; public static final int abc_ab_solid_dark_holo = 0x7f020006; public static final int abc_ab_solid_light_holo = 0x7f020007; public static final int abc_ab_stacked_solid_dark_holo = 0x7f020008; public static final int abc_ab_stacked_solid_light_holo = 0x7f020009; public static final int abc_ab_stacked_transparent_dark_holo = 0x7f02000a; public static final int abc_ab_stacked_transparent_light_holo = 0x7f02000b; public static final int abc_ab_transparent_dark_holo = 0x7f02000c; public static final int abc_ab_transparent_light_holo = 0x7f02000d; public static final int abc_cab_background_bottom_holo_dark = 0x7f02000e; public static final int abc_cab_background_bottom_holo_light = 0x7f02000f; public static final int abc_cab_background_top_holo_dark = 0x7f020010; public static final int abc_cab_background_top_holo_light = 0x7f020011; public static final int abc_ic_ab_back_holo_dark = 0x7f020012; public static final int abc_ic_ab_back_holo_light = 0x7f020013; public static final int abc_ic_cab_done_holo_dark = 0x7f020014; public static final int abc_ic_cab_done_holo_light = 0x7f020015; public static final int abc_ic_clear = 0x7f020016; public static final int abc_ic_clear_disabled = 0x7f020017; public static final int abc_ic_clear_holo_light = 0x7f020018; public static final int abc_ic_clear_normal = 0x7f020019; public static final int abc_ic_clear_search_api_disabled_holo_light = 0x7f02001a; public static final int abc_ic_clear_search_api_holo_light = 0x7f02001b; public static final int abc_ic_commit_search_api_holo_dark = 0x7f02001c; public static final int abc_ic_commit_search_api_holo_light = 0x7f02001d; public static final int abc_ic_go = 0x7f02001e; public static final int abc_ic_go_search_api_holo_light = 0x7f02001f; public static final int abc_ic_menu_moreoverflow_normal_holo_dark = 0x7f020020; public static final int abc_ic_menu_moreoverflow_normal_holo_light = 0x7f020021; public static final int abc_ic_menu_share_holo_dark = 0x7f020022; public static final int abc_ic_menu_share_holo_light = 0x7f020023; public static final int abc_ic_search = 0x7f020024; public static final int abc_ic_search_api_holo_light = 0x7f020025; public static final int abc_ic_voice_search = 0x7f020026; public static final int abc_ic_voice_search_api_holo_light = 0x7f020027; public static final int abc_item_background_holo_dark = 0x7f020028; public static final int abc_item_background_holo_light = 0x7f020029; public static final int abc_list_divider_holo_dark = 0x7f02002a; public static final int abc_list_divider_holo_light = 0x7f02002b; public static final int abc_list_focused_holo = 0x7f02002c; public static final int abc_list_longpressed_holo = 0x7f02002d; public static final int abc_list_pressed_holo_dark = 0x7f02002e; public static final int abc_list_pressed_holo_light = 0x7f02002f; public static final int abc_list_selector_background_transition_holo_dark = 0x7f020030; public static final int abc_list_selector_background_transition_holo_light = 0x7f020031; public static final int abc_list_selector_disabled_holo_dark = 0x7f020032; public static final int abc_list_selector_disabled_holo_light = 0x7f020033; public static final int abc_list_selector_holo_dark = 0x7f020034; public static final int abc_list_selector_holo_light = 0x7f020035; public static final int abc_menu_dropdown_panel_holo_dark = 0x7f020036; public static final int abc_menu_dropdown_panel_holo_light = 0x7f020037; public static final int abc_menu_hardkey_panel_holo_dark = 0x7f020038; public static final int abc_menu_hardkey_panel_holo_light = 0x7f020039; public static final int abc_search_dropdown_dark = 0x7f02003a; public static final int abc_search_dropdown_light = 0x7f02003b; public static final int abc_spinner_ab_default_holo_dark = 0x7f02003c; public static final int abc_spinner_ab_default_holo_light = 0x7f02003d; public static final int abc_spinner_ab_disabled_holo_dark = 0x7f02003e; public static final int abc_spinner_ab_disabled_holo_light = 0x7f02003f; public static final int abc_spinner_ab_focused_holo_dark = 0x7f020040; public static final int abc_spinner_ab_focused_holo_light = 0x7f020041; public static final int abc_spinner_ab_holo_dark = 0x7f020042; public static final int abc_spinner_ab_holo_light = 0x7f020043; public static final int abc_spinner_ab_pressed_holo_dark = 0x7f020044; public static final int abc_spinner_ab_pressed_holo_light = 0x7f020045; public static final int abc_tab_indicator_ab_holo = 0x7f020046; public static final int abc_tab_selected_focused_holo = 0x7f020047; public static final int abc_tab_selected_holo = 0x7f020048; public static final int abc_tab_selected_pressed_holo = 0x7f020049; public static final int abc_tab_unselected_pressed_holo = 0x7f02004a; public static final int abc_textfield_search_default_holo_dark = 0x7f02004b; public static final int abc_textfield_search_default_holo_light = 0x7f02004c; public static final int abc_textfield_search_right_default_holo_dark = 0x7f02004d; public static final int abc_textfield_search_right_default_holo_light = 0x7f02004e; public static final int abc_textfield_search_right_selected_holo_dark = 0x7f02004f; public static final int abc_textfield_search_right_selected_holo_light = 0x7f020050; public static final int abc_textfield_search_selected_holo_dark = 0x7f020051; public static final int abc_textfield_search_selected_holo_light = 0x7f020052; public static final int abc_textfield_searchview_holo_dark = 0x7f020053; public static final int abc_textfield_searchview_holo_light = 0x7f020054; public static final int abc_textfield_searchview_right_holo_dark = 0x7f020055; public static final int abc_textfield_searchview_right_holo_light = 0x7f020056; } public static final class id { public static final int action_bar = 0x7f070036; public static final int action_bar_activity_content = 0x7f070021; public static final int action_bar_container = 0x7f070035; public static final int action_bar_overlay_layout = 0x7f070039; public static final int action_bar_root = 0x7f070034; public static final int action_bar_subtitle = 0x7f07003d; public static final int action_bar_title = 0x7f07003c; public static final int action_context_bar = 0x7f070037; public static final int action_menu_divider = 0x7f070022; public static final int action_menu_presenter = 0x7f070023; public static final int action_mode_close_button = 0x7f07003e; public static final int activity_chooser_view_content = 0x7f07003f; public static final int always = 0x7f070017; public static final int beginning = 0x7f07001d; public static final int checkbox = 0x7f070047; public static final int collapseActionView = 0x7f070019; public static final int default_activity_button = 0x7f070042; public static final int dialog = 0x7f07001a; public static final int disableHome = 0x7f070014; public static final int dropdown = 0x7f07001b; public static final int edit_query = 0x7f07004a; public static final int end = 0x7f07001f; public static final int expand_activities_button = 0x7f070040; public static final int expanded_menu = 0x7f070046; public static final int home = 0x7f070020; public static final int homeAsUp = 0x7f070011; public static final int icon = 0x7f070044; public static final int ifRoom = 0x7f070016; public static final int image = 0x7f070041; public static final int listMode = 0x7f07000d; public static final int list_item = 0x7f070043; public static final int middle = 0x7f07001e; public static final int never = 0x7f070015; public static final int none = 0x7f07001c; public static final int normal = 0x7f07000c; public static final int progress_circular = 0x7f070024; public static final int progress_horizontal = 0x7f070025; public static final int radio = 0x7f070049; public static final int search_badge = 0x7f07004c; public static final int search_bar = 0x7f07004b; public static final int search_button = 0x7f07004d; public static final int search_close_btn = 0x7f070052; public static final int search_edit_frame = 0x7f07004e; public static final int search_go_btn = 0x7f070054; public static final int search_mag_icon = 0x7f07004f; public static final int search_plate = 0x7f070050; public static final int search_src_text = 0x7f070051; public static final int search_voice_btn = 0x7f070055; public static final int shortcut = 0x7f070048; public static final int showCustom = 0x7f070013; public static final int showHome = 0x7f070010; public static final int showTitle = 0x7f070012; public static final int split_action_bar = 0x7f070038; public static final int submit_area = 0x7f070053; public static final int tabMode = 0x7f07000e; public static final int title = 0x7f070045; public static final int top_action_bar = 0x7f07003a; public static final int up = 0x7f07003b; public static final int useLogo = 0x7f07000f; public static final int withText = 0x7f070018; } public static final class integer { public static final int abc_max_action_buttons = 0x7f0b0000; } public static final class layout { public static final int abc_action_bar_decor = 0x7f030000; public static final int abc_action_bar_decor_include = 0x7f030001; public static final int abc_action_bar_decor_overlay = 0x7f030002; public static final int abc_action_bar_home = 0x7f030003; public static final int abc_action_bar_tab = 0x7f030004; public static final int abc_action_bar_tabbar = 0x7f030005; public static final int abc_action_bar_title_item = 0x7f030006; public static final int abc_action_bar_view_list_nav_layout = 0x7f030007; public static final int abc_action_menu_item_layout = 0x7f030008; public static final int abc_action_menu_layout = 0x7f030009; public static final int abc_action_mode_bar = 0x7f03000a; public static final int abc_action_mode_close_item = 0x7f03000b; public static final int abc_activity_chooser_view = 0x7f03000c; public static final int abc_activity_chooser_view_include = 0x7f03000d; public static final int abc_activity_chooser_view_list_item = 0x7f03000e; public static final int abc_expanded_menu_layout = 0x7f03000f; public static final int abc_list_menu_item_checkbox = 0x7f030010; public static final int abc_list_menu_item_icon = 0x7f030011; public static final int abc_list_menu_item_layout = 0x7f030012; public static final int abc_list_menu_item_radio = 0x7f030013; public static final int abc_popup_menu_item_layout = 0x7f030014; public static final int abc_search_dropdown_item_icons_2line = 0x7f030015; public static final int abc_search_view = 0x7f030016; public static final int abc_simple_decor = 0x7f030017; public static final int support_simple_spinner_dropdown_item = 0x7f0300cc; } public static final class string { public static final int abc_action_bar_home_description = 0x7f080003; public static final int abc_action_bar_up_description = 0x7f080004; public static final int abc_action_menu_overflow_description = 0x7f080005; public static final int abc_action_mode_done = 0x7f080002; public static final int abc_activity_chooser_view_see_all = 0x7f08000c; public static final int abc_activitychooserview_choose_application = 0x7f08000b; public static final int abc_searchview_description_clear = 0x7f080008; public static final int abc_searchview_description_query = 0x7f080007; public static final int abc_searchview_description_search = 0x7f080006; public static final int abc_searchview_description_submit = 0x7f080009; public static final int abc_searchview_description_voice = 0x7f08000a; public static final int abc_shareactionprovider_share_with = 0x7f08000e; public static final int abc_shareactionprovider_share_with_application = 0x7f08000d; } public static final class style { public static final int TextAppearance_AppCompat_Base_CompactMenu_Dialog = 0x7f0c0063; public static final int TextAppearance_AppCompat_Base_SearchResult = 0x7f0c006d; public static final int TextAppearance_AppCompat_Base_SearchResult_Subtitle = 0x7f0c006f; public static final int TextAppearance_AppCompat_Base_SearchResult_Title = 0x7f0c006e; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Large = 0x7f0c0069; public static final int TextAppearance_AppCompat_Base_Widget_PopupMenu_Small = 0x7f0c006a; public static final int TextAppearance_AppCompat_Light_Base_SearchResult = 0x7f0c0070; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Subtitle = 0x7f0c0072; public static final int TextAppearance_AppCompat_Light_Base_SearchResult_Title = 0x7f0c0071; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Large = 0x7f0c006b; public static final int TextAppearance_AppCompat_Light_Base_Widget_PopupMenu_Small = 0x7f0c006c; public static final int TextAppearance_AppCompat_Light_SearchResult_Subtitle = 0x7f0c0035; public static final int TextAppearance_AppCompat_Light_SearchResult_Title = 0x7f0c0034; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Large = 0x7f0c0030; public static final int TextAppearance_AppCompat_Light_Widget_PopupMenu_Small = 0x7f0c0031; public static final int TextAppearance_AppCompat_SearchResult_Subtitle = 0x7f0c0033; public static final int TextAppearance_AppCompat_SearchResult_Title = 0x7f0c0032; public static final int TextAppearance_AppCompat_Widget_ActionBar_Menu = 0x7f0c001a; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle = 0x7f0c0006; public static final int TextAppearance_AppCompat_Widget_ActionBar_Subtitle_Inverse = 0x7f0c0008; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title = 0x7f0c0005; public static final int TextAppearance_AppCompat_Widget_ActionBar_Title_Inverse = 0x7f0c0007; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle = 0x7f0c001e; public static final int TextAppearance_AppCompat_Widget_ActionMode_Subtitle_Inverse = 0x7f0c0020; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title = 0x7f0c001d; public static final int TextAppearance_AppCompat_Widget_ActionMode_Title_Inverse = 0x7f0c001f; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Menu = 0x7f0c0054; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle = 0x7f0c0056; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Subtitle_Inverse = 0x7f0c0058; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title = 0x7f0c0055; public static final int TextAppearance_AppCompat_Widget_Base_ActionBar_Title_Inverse = 0x7f0c0057; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle = 0x7f0c0051; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Subtitle_Inverse = 0x7f0c0053; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title = 0x7f0c0050; public static final int TextAppearance_AppCompat_Widget_Base_ActionMode_Title_Inverse = 0x7f0c0052; public static final int TextAppearance_AppCompat_Widget_Base_DropDownItem = 0x7f0c0061; public static final int TextAppearance_AppCompat_Widget_DropDownItem = 0x7f0c0021; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Large = 0x7f0c002e; public static final int TextAppearance_AppCompat_Widget_PopupMenu_Small = 0x7f0c002f; public static final int TextAppearance_Widget_AppCompat_Base_ExpandedMenu_Item = 0x7f0c0062; public static final int TextAppearance_Widget_AppCompat_ExpandedMenu_Item = 0x7f0c0028; public static final int Theme_AppCompat = 0x7f0c0077; public static final int Theme_AppCompat_Base_CompactMenu = 0x7f0c0083; public static final int Theme_AppCompat_Base_CompactMenu_Dialog = 0x7f0c0084; public static final int Theme_AppCompat_CompactMenu = 0x7f0c007c; public static final int Theme_AppCompat_CompactMenu_Dialog = 0x7f0c007d; public static final int Theme_AppCompat_DialogWhenLarge = 0x7f0c007a; public static final int Theme_AppCompat_Light = 0x7f0c0078; public static final int Theme_AppCompat_Light_DarkActionBar = 0x7f0c0079; public static final int Theme_AppCompat_Light_DialogWhenLarge = 0x7f0c007b; public static final int Theme_Base = 0x7f0c007e; public static final int Theme_Base_AppCompat = 0x7f0c0080; public static final int Theme_Base_AppCompat_DialogWhenLarge = 0x7f0c0085; public static final int Theme_Base_AppCompat_DialogWhenLarge_Base = 0x7f0c0089; public static final int Theme_Base_AppCompat_Dialog_FixedSize = 0x7f0c0087; public static final int Theme_Base_AppCompat_Dialog_Light_FixedSize = 0x7f0c0088; public static final int Theme_Base_AppCompat_Light = 0x7f0c0081; public static final int Theme_Base_AppCompat_Light_DarkActionBar = 0x7f0c0082; public static final int Theme_Base_AppCompat_Light_DialogWhenLarge = 0x7f0c0086; public static final int Theme_Base_AppCompat_Light_DialogWhenLarge_Base = 0x7f0c008a; public static final int Theme_Base_Light = 0x7f0c007f; public static final int Widget_AppCompat_ActionBar = 0x7f0c0000; public static final int Widget_AppCompat_ActionBar_Solid = 0x7f0c0002; public static final int Widget_AppCompat_ActionBar_TabBar = 0x7f0c0011; public static final int Widget_AppCompat_ActionBar_TabText = 0x7f0c0017; public static final int Widget_AppCompat_ActionBar_TabView = 0x7f0c0014; public static final int Widget_AppCompat_ActionButton = 0x7f0c000b; public static final int Widget_AppCompat_ActionButton_CloseMode = 0x7f0c000d; public static final int Widget_AppCompat_ActionButton_Overflow = 0x7f0c000f; public static final int Widget_AppCompat_ActionMode = 0x7f0c001b; public static final int Widget_AppCompat_ActivityChooserView = 0x7f0c0038; public static final int Widget_AppCompat_AutoCompleteTextView = 0x7f0c0036; public static final int Widget_AppCompat_Base_ActionBar = 0x7f0c003a; public static final int Widget_AppCompat_Base_ActionBar_Solid = 0x7f0c003c; public static final int Widget_AppCompat_Base_ActionBar_TabBar = 0x7f0c0045; public static final int Widget_AppCompat_Base_ActionBar_TabText = 0x7f0c004b; public static final int Widget_AppCompat_Base_ActionBar_TabView = 0x7f0c0048; public static final int Widget_AppCompat_Base_ActionButton = 0x7f0c003f; public static final int Widget_AppCompat_Base_ActionButton_CloseMode = 0x7f0c0041; public static final int Widget_AppCompat_Base_ActionButton_Overflow = 0x7f0c0043; public static final int Widget_AppCompat_Base_ActionMode = 0x7f0c004e; public static final int Widget_AppCompat_Base_ActivityChooserView = 0x7f0c0075; public static final int Widget_AppCompat_Base_AutoCompleteTextView = 0x7f0c0073; public static final int Widget_AppCompat_Base_DropDownItem_Spinner = 0x7f0c005d; public static final int Widget_AppCompat_Base_ListPopupWindow = 0x7f0c0065; public static final int Widget_AppCompat_Base_ListView_DropDown = 0x7f0c005f; public static final int Widget_AppCompat_Base_ListView_Menu = 0x7f0c0064; public static final int Widget_AppCompat_Base_PopupMenu = 0x7f0c0067; public static final int Widget_AppCompat_Base_ProgressBar = 0x7f0c005a; public static final int Widget_AppCompat_Base_ProgressBar_Horizontal = 0x7f0c0059; public static final int Widget_AppCompat_Base_Spinner = 0x7f0c005b; public static final int Widget_AppCompat_DropDownItem_Spinner = 0x7f0c0024; public static final int Widget_AppCompat_Light_ActionBar = 0x7f0c0001; public static final int Widget_AppCompat_Light_ActionBar_Solid = 0x7f0c0003; public static final int Widget_AppCompat_Light_ActionBar_Solid_Inverse = 0x7f0c0004; public static final int Widget_AppCompat_Light_ActionBar_TabBar = 0x7f0c0012; public static final int Widget_AppCompat_Light_ActionBar_TabBar_Inverse = 0x7f0c0013; public static final int Widget_AppCompat_Light_ActionBar_TabText = 0x7f0c0018; public static final int Widget_AppCompat_Light_ActionBar_TabText_Inverse = 0x7f0c0019; public static final int Widget_AppCompat_Light_ActionBar_TabView = 0x7f0c0015; public static final int Widget_AppCompat_Light_ActionBar_TabView_Inverse = 0x7f0c0016; public static final int Widget_AppCompat_Light_ActionButton = 0x7f0c000c; public static final int Widget_AppCompat_Light_ActionButton_CloseMode = 0x7f0c000e; public static final int Widget_AppCompat_Light_ActionButton_Overflow = 0x7f0c0010; public static final int Widget_AppCompat_Light_ActionMode_Inverse = 0x7f0c001c; public static final int Widget_AppCompat_Light_ActivityChooserView = 0x7f0c0039; public static final int Widget_AppCompat_Light_AutoCompleteTextView = 0x7f0c0037; public static final int Widget_AppCompat_Light_Base_ActionBar = 0x7f0c003b; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid = 0x7f0c003d; public static final int Widget_AppCompat_Light_Base_ActionBar_Solid_Inverse = 0x7f0c003e; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar = 0x7f0c0046; public static final int Widget_AppCompat_Light_Base_ActionBar_TabBar_Inverse = 0x7f0c0047; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText = 0x7f0c004c; public static final int Widget_AppCompat_Light_Base_ActionBar_TabText_Inverse = 0x7f0c004d; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView = 0x7f0c0049; public static final int Widget_AppCompat_Light_Base_ActionBar_TabView_Inverse = 0x7f0c004a; public static final int Widget_AppCompat_Light_Base_ActionButton = 0x7f0c0040; public static final int Widget_AppCompat_Light_Base_ActionButton_CloseMode = 0x7f0c0042; public static final int Widget_AppCompat_Light_Base_ActionButton_Overflow = 0x7f0c0044; public static final int Widget_AppCompat_Light_Base_ActionMode_Inverse = 0x7f0c004f; public static final int Widget_AppCompat_Light_Base_ActivityChooserView = 0x7f0c0076; public static final int Widget_AppCompat_Light_Base_AutoCompleteTextView = 0x7f0c0074; public static final int Widget_AppCompat_Light_Base_DropDownItem_Spinner = 0x7f0c005e; public static final int Widget_AppCompat_Light_Base_ListPopupWindow = 0x7f0c0066; public static final int Widget_AppCompat_Light_Base_ListView_DropDown = 0x7f0c0060; public static final int Widget_AppCompat_Light_Base_PopupMenu = 0x7f0c0068; public static final int Widget_AppCompat_Light_Base_Spinner = 0x7f0c005c; public static final int Widget_AppCompat_Light_DropDownItem_Spinner = 0x7f0c0025; public static final int Widget_AppCompat_Light_ListPopupWindow = 0x7f0c002a; public static final int Widget_AppCompat_Light_ListView_DropDown = 0x7f0c0027; public static final int Widget_AppCompat_Light_PopupMenu = 0x7f0c002c; public static final int Widget_AppCompat_Light_Spinner_DropDown_ActionBar = 0x7f0c0023; public static final int Widget_AppCompat_ListPopupWindow = 0x7f0c0029; public static final int Widget_AppCompat_ListView_DropDown = 0x7f0c0026; public static final int Widget_AppCompat_ListView_Menu = 0x7f0c002d; public static final int Widget_AppCompat_PopupMenu = 0x7f0c002b; public static final int Widget_AppCompat_ProgressBar = 0x7f0c000a; public static final int Widget_AppCompat_ProgressBar_Horizontal = 0x7f0c0009; public static final int Widget_AppCompat_Spinner_DropDown_ActionBar = 0x7f0c0022; } public static final class styleable { public static final int[] ActionBar = { 0x7f010025, 0x7f010026, 0x7f010027, 0x7f010028, 0x7f010029, 0x7f01002a, 0x7f01002b, 0x7f01002c, 0x7f01002d, 0x7f01002e, 0x7f01002f, 0x7f010030, 0x7f010031, 0x7f010032, 0x7f010033, 0x7f010034, 0x7f010035, 0x7f010036, 0x7f010037 }; public static final int[] ActionBarLayout = { 0x010100b3 }; public static final int ActionBarLayout_android_layout_gravity = 0; public static final int[] ActionBarWindow = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006 }; public static final int ActionBarWindow_windowActionBar = 0; public static final int ActionBarWindow_windowActionBarOverlay = 1; public static final int ActionBarWindow_windowFixedHeightMajor = 6; public static final int ActionBarWindow_windowFixedHeightMinor = 4; public static final int ActionBarWindow_windowFixedWidthMajor = 3; public static final int ActionBarWindow_windowFixedWidthMinor = 5; public static final int ActionBarWindow_windowSplitActionBar = 2; public static final int ActionBar_background = 10; public static final int ActionBar_backgroundSplit = 12; public static final int ActionBar_backgroundStacked = 11; public static final int ActionBar_customNavigationLayout = 13; public static final int ActionBar_displayOptions = 3; public static final int ActionBar_divider = 9; public static final int ActionBar_height = 1; public static final int ActionBar_homeLayout = 14; public static final int ActionBar_icon = 7; public static final int ActionBar_indeterminateProgressStyle = 16; public static final int ActionBar_itemPadding = 18; public static final int ActionBar_logo = 8; public static final int ActionBar_navigationMode = 2; public static final int ActionBar_progressBarPadding = 17; public static final int ActionBar_progressBarStyle = 15; public static final int ActionBar_subtitle = 4; public static final int ActionBar_subtitleTextStyle = 6; public static final int ActionBar_title = 0; public static final int ActionBar_titleTextStyle = 5; public static final int[] ActionMenuItemView = { 0x0101013f }; public static final int ActionMenuItemView_android_minWidth = 0; public static final int[] ActionMenuView = { }; public static final int[] ActionMode = { 0x7f010026, 0x7f01002a, 0x7f01002b, 0x7f01002f, 0x7f010031 }; public static final int ActionMode_background = 3; public static final int ActionMode_backgroundSplit = 4; public static final int ActionMode_height = 0; public static final int ActionMode_subtitleTextStyle = 2; public static final int ActionMode_titleTextStyle = 1; public static final int[] ActivityChooserView = { 0x7f01006a, 0x7f01006b }; public static final int ActivityChooserView_expandActivityOverflowButtonDrawable = 1; public static final int ActivityChooserView_initialActivityCount = 0; public static final int[] CompatTextView = { 0x7f01006d }; public static final int CompatTextView_textAllCaps = 0; public static final int[] LinearLayoutICS = { 0x7f01002e, 0x7f010055, 0x7f010056 }; public static final int LinearLayoutICS_divider = 0; public static final int LinearLayoutICS_dividerPadding = 2; public static final int LinearLayoutICS_showDividers = 1; public static final int[] MenuGroup = { 0x0101000e, 0x010100d0, 0x01010194, 0x010101de, 0x010101df, 0x010101e0 }; public static final int MenuGroup_android_checkableBehavior = 5; public static final int MenuGroup_android_enabled = 0; public static final int MenuGroup_android_id = 1; public static final int MenuGroup_android_menuCategory = 3; public static final int MenuGroup_android_orderInCategory = 4; public static final int MenuGroup_android_visible = 2; public static final int[] MenuItem = { 0x01010002, 0x0101000e, 0x010100d0, 0x01010106, 0x01010194, 0x010101de, 0x010101df, 0x010101e1, 0x010101e2, 0x010101e3, 0x010101e4, 0x010101e5, 0x0101026f, 0x7f01004d, 0x7f01004e, 0x7f01004f, 0x7f010050 }; public static final int MenuItem_actionLayout = 14; public static final int MenuItem_actionProviderClass = 16; public static final int MenuItem_actionViewClass = 15; public static final int MenuItem_android_alphabeticShortcut = 9; public static final int MenuItem_android_checkable = 11; public static final int MenuItem_android_checked = 3; public static final int MenuItem_android_enabled = 1; public static final int MenuItem_android_icon = 0; public static final int MenuItem_android_id = 2; public static final int MenuItem_android_menuCategory = 5; public static final int MenuItem_android_numericShortcut = 10; public static final int MenuItem_android_onClick = 12; public static final int MenuItem_android_orderInCategory = 6; public static final int MenuItem_android_title = 7; public static final int MenuItem_android_titleCondensed = 8; public static final int MenuItem_android_visible = 4; public static final int MenuItem_showAsAction = 13; public static final int[] MenuView = { 0x010100ae, 0x0101012c, 0x0101012d, 0x0101012e, 0x0101012f, 0x01010130, 0x01010131, 0x01010438 }; public static final int MenuView_android_headerBackground = 4; public static final int MenuView_android_horizontalDivider = 2; public static final int MenuView_android_itemBackground = 5; public static final int MenuView_android_itemIconDisabledAlpha = 6; public static final int MenuView_android_itemTextAppearance = 1; public static final int MenuView_android_preserveIconSpacing = 7; public static final int MenuView_android_verticalDivider = 3; public static final int MenuView_android_windowAnimationStyle = 0; public static final int[] SearchView = { 0x0101011f, 0x01010220, 0x01010264, 0x7f01005a, 0x7f01005b }; public static final int SearchView_android_imeOptions = 2; public static final int SearchView_android_inputType = 1; public static final int SearchView_android_maxWidth = 0; public static final int SearchView_iconifiedByDefault = 3; public static final int SearchView_queryHint = 4; public static final int[] Spinner = { 0x010100af, 0x01010175, 0x01010176, 0x01010262, 0x010102ac, 0x010102ad, 0x7f010051, 0x7f010052, 0x7f010053, 0x7f010054 }; public static final int Spinner_android_dropDownHorizontalOffset = 4; public static final int Spinner_android_dropDownSelector = 1; public static final int Spinner_android_dropDownVerticalOffset = 5; public static final int Spinner_android_dropDownWidth = 3; public static final int Spinner_android_gravity = 0; public static final int Spinner_android_popupBackground = 2; public static final int Spinner_disableChildrenWhenDisabled = 9; public static final int Spinner_popupPromptView = 8; public static final int Spinner_prompt = 6; public static final int Spinner_spinnerMode = 7; public static final int[] Theme = { 0x7f010047, 0x7f010048, 0x7f010049, 0x7f01004a, 0x7f01004b, 0x7f01004c }; public static final int Theme_actionDropDownStyle = 0; public static final int Theme_dropdownListPreferredItemHeight = 1; public static final int Theme_listChoiceBackgroundIndicator = 5; public static final int Theme_panelMenuListTheme = 4; public static final int Theme_panelMenuListWidth = 3; public static final int Theme_popupMenuStyle = 2; public static final int[] View = { 0x010100da, 0x7f010038, 0x7f010039 }; public static final int View_android_focusable = 0; public static final int View_paddingEnd = 2; public static final int View_paddingStart = 1; } }
[ "kevin.dong@sonymobile.com" ]
kevin.dong@sonymobile.com
fb8f1bc215aa4d8f1b67c6baf75c01739dcd2c2e
a5d1586973c8edcaddcde50eee732bd0652f4642
/cms-extjs/src/main/java/kr/co/d2net/controller/EquipmentController.java
f8da36050ebf3ba2305ecd3d0178e3f33859e8b9
[]
no_license
inviss/netbro
c0a3a875b0ea98cb7e44864c8944bc003f2fde79
2b266e41f74831724268ca56d3d244d65905c8db
refs/heads/master
2020-07-11T16:04:03.577998
2016-10-03T13:38:35
2016-10-03T13:38:35
74,000,941
0
1
null
null
null
null
UTF-8
Java
false
false
6,631
java
package kr.co.d2net.controller; import java.util.List; import javax.servlet.ServletContext; import kr.co.d2net.dao.TraDao; import kr.co.d2net.dto.EquipmentTbl; import kr.co.d2net.dto.search.Search; import kr.co.d2net.dto.search.SearchControls; import kr.co.d2net.dto.vo.Equip; import kr.co.d2net.exception.ServiceException; import kr.co.d2net.service.AttachServices; import kr.co.d2net.service.AuthServices; import kr.co.d2net.service.CategoryServices; import kr.co.d2net.service.ContentsInstServices; import kr.co.d2net.service.ContentsServices; import kr.co.d2net.service.EquipmentServices; import kr.co.d2net.service.RoleAuthServices; import kr.co.d2net.service.TraServices; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; /** * EquipmentTbl 관련된 업무로직이 구현된 class * @author vayne * */ @Controller public class EquipmentController { final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private ServletContext servletContext; @Autowired private ContentsServices contentsServices; @Autowired private ContentsInstServices contentsInstServices; @Autowired private EquipmentServices equipmentServices; @Autowired private AuthServices authServices; @Autowired private RoleAuthServices roleAuthServices; @Autowired private CategoryServices categoryServices; @Autowired private AttachServices attachServices; @Autowired private MessageSource messageSource; @Autowired private TraServices traServices; @Autowired private TraDao traDao; /** * 장비 화면 로딩시 필요한 코드값을 불러온다(사용기능 없음.) * @param map * @return */ @RequestMapping(value="/admin/equipment/equipment.ssc", method = RequestMethod.GET) public ModelMap equipment(ModelMap map){ map.addAttribute("search", new Search()); map.addAttribute("equipTbl", new EquipmentTbl()); return map; } /** * Equipment리스트 정보를 가져온다. * @param search * @return */ @RequestMapping(value = "/admin/equipment/findEquipmentList.ssc", method = RequestMethod.GET) public ModelAndView findEquipmentList(@ModelAttribute("search") Search search) { ModelAndView view = new ModelAndView(); Long totalCount = null; try{ if(search.getPageNo() == null){ search.setPageNo(0); } List<Equip> equipmentTbls = equipmentServices.findEquipList(search); totalCount = equipmentServices.count(search); if(totalCount == -1){ view.addObject("result","N"); view.addObject("reason","DB조회중 오류가 발생하였습니다 담당자에게 문의하십시오"); view.setViewName("jsonView"); return view; } view.addObject("search", search); view.addObject("result","Y"); view.addObject("equipmentTbls", equipmentTbls); view.addObject("totalCount",totalCount); view.addObject("pageSize",SearchControls.USER_LIST_COUNT); view.setViewName("jsonView"); return view; } catch (ServiceException e) { view.addObject("result","N"); view.addObject("reason", e.getMessage()); view.setViewName("jsonView"); return view; } } /** * Equipment리스트 정보를 가져온다. * @param search * @return */ @RequestMapping(value = "/admin/equipment/getEquipmentInfo.ssc", method = RequestMethod.GET) public ModelAndView getEquipmentInfo(@ModelAttribute("search") Search search) { ModelAndView view = new ModelAndView(); try{ if (search.getPageNo() == null || search.getPageNo() == 0) { search.setPageNo(1); }else{ search.setPageNo(search.getPageNo()+1); } //List<Equip> equipmentTbl = equipmentServices.getEquipInfo(search); Equip equip = equipmentServices.getEquipInfo(search); view.addObject("search", search); view.addObject("result","Y"); view.addObject("equipmentTbl", equip); view.setViewName("jsonView"); return view; } catch (ServiceException e) { view.addObject("result","N"); view.addObject("reason", e.getMessage()); view.setViewName("jsonView"); return view; } } /** * 장비정보를 save한다. * @param search * @return */ @RequestMapping(value = "/admin/equipment/saveEquipInfo.ssc", method = RequestMethod.POST) public ModelAndView saveEquipInfo(@ModelAttribute("equip")Equip equip) { ModelAndView view = new ModelAndView(); try{ //장비 정보를 저장하는 함수. equipmentServices.saveEquipInfo(equip); view.addObject("result","Y"); view.setViewName("jsonView"); return view; } catch (ServiceException e) { view.addObject("result","N"); view.addObject("reason", e.getMessage()); view.setViewName("jsonView"); return view; } } /** * 장비정보를 save한다. * @param search * @return */ @RequestMapping(value = "/admin/equipment/updateEquipInfo.ssc", method = RequestMethod.POST) public ModelAndView updateEquipInfo(@ModelAttribute("equipTbl")Equip eqTbl) { ModelAndView view = new ModelAndView(); try{ equipmentServices.updateEquipInfo(eqTbl); view.addObject("result","Y"); view.setViewName("jsonView"); return view; } catch (ServiceException e) { view.addObject("result","N"); view.addObject("reason", e.getMessage()); view.setViewName("jsonView"); return view; } } /** * 장비정보의 인스턴스(ex:장비1번 --> 장비1-1번,1-2번,1-3번 이런식으로) * @param eqTbl * @return */ @RequestMapping(value = "/admin/equipment/saveEquipInstance.ssc", method = RequestMethod.POST) public ModelAndView saveEquipInstance(@ModelAttribute("equip")Equip equip) { ModelAndView view = new ModelAndView(); try{ equipmentServices.saveEquipInstance(equip); view.addObject("result","Y"); view.setViewName("jsonView"); return view; } catch (ServiceException e) { view.addObject("result","N"); view.addObject("reason", e.getMessage()); view.setViewName("jsonView"); return view; } } }
[ "mskang0916@4846aee8-341f-0510-a8c2-a716f2a042e0" ]
mskang0916@4846aee8-341f-0510-a8c2-a716f2a042e0
5bca6dcd4a814d19bf41fc6b951533af4f6e2f31
4f6ab6ed5008988d9127b2794bc8cf659664774e
/hadoop/src/main/java/FullText_DocLen.java
25ed520913e7844df491151fb055b01a4b239ea6
[]
no_license
pariirap/javastuff
4b3ddfbb5cf4666a9d7726cb94794eccea1a14ba
37cb19fc3ebd8e269641501141c8211687194531
refs/heads/master
2021-01-17T15:20:36.551137
2017-07-16T20:05:59
2017-07-16T20:05:59
84,107,222
0
0
null
null
null
null
UTF-8
Java
false
false
2,845
java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Mapper.Context; public class FullText_DocLen { public static class DocLen_Mapper extends Mapper<LongWritable, /* Input key Type */ Text, /* Input value Type */ Text, /* Output key Type */ IntWritable> /* Output value Type */ { Set<String> stopWords; public static final String HDFS_STOPWORD_LIST = "/users/PariRajaram/local/stop_words.txt"; public static final String LOCAL_STOPWORD_LIST = "/Users/PariRajaram/stopwords.txt"; protected void setup(Context context) throws IOException, InterruptedException { try { String stopwordCacheName = new Path(HDFS_STOPWORD_LIST).getName(); Path[] cacheFiles = DistributedCache.getLocalCacheFiles(context.getConfiguration()); if (null != cacheFiles && cacheFiles.length > 0) { for (Path cachePath : cacheFiles) { if (cachePath.getName().equals(stopwordCacheName)) { loadStopWords(cachePath); break; } } } } catch (IOException ioe) { System.err.println("IOException reading from distributed cache"); System.err.println(ioe.toString()); } } void loadStopWords(Path cachePath) throws IOException { // note use of regular java.io methods here - this is a local file // now BufferedReader wordReader = new BufferedReader(new FileReader(cachePath.toString())); try { String line; System.out.println("stopword init"); stopWords = new HashSet<String>(); while ((line = wordReader.readLine()) != null) { stopWords.add(line); } } finally { wordReader.close(); } } // Map function public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { int fieldLen = 0; // static Map<String, Integer> wordMap = new HashMap(); // reporter.incrCounter(RecordCounters.DOCLEN, 1); String line = value.toString(); // StringTokenizer strToken = new StringTokenizer(line, " , "); // String token; // String docId = strToken.nextToken(); int count=0; while (strToken.hasMoreTokens()) { token = strToken.nextToken(); StringTokenizer strToken2 = new StringTokenizer(token, "\";/ -\'"); while (strToken2.hasMoreTokens()) { String word = strToken2.nextToken(); if (!stopWords.contains(word)) { count++; } } } context.write(new Text(docId), new IntWritable(count)); } } }
[ "PariRajaram@Jyos-Computer.home" ]
PariRajaram@Jyos-Computer.home
95425138bcb114befb5fb0358eb1fa94d5edf8e9
dcb97569f10a7457b9c4bb27bf7b79b59e8a9198
/src/test/java/com/google/devtools/build/lib/rules/android/AndroidBinaryTest.java
e609777ab41b0f3d0fa0116da973ff62788fa4dc
[ "Apache-2.0" ]
permissive
eric0755/bazel1
02a0fda2a9ec89f78d82d7de627930ead2d348f5
1d1563372d940965d9304e26772a3688eb31226d
refs/heads/master
2020-06-04T07:25:16.754843
2019-06-14T12:09:08
2019-06-14T12:09:08
191,923,464
0
0
null
null
null
null
UTF-8
Java
false
false
196,816
java
// Copyright 2017 The Bazel Authors. 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.devtools.build.lib.rules.android; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.getFirstArtifactEndingWith; import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.prettyArtifactNames; import static com.google.devtools.build.lib.rules.java.JavaCompileActionTestHelper.getJavacArguments; import static com.google.devtools.build.lib.rules.java.JavaCompileActionTestHelper.getProcessorpath; import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows; import com.google.common.base.Ascii; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Streams; import com.google.common.truth.Truth; import com.google.devtools.build.lib.actions.Action; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.util.ActionsTestUtil; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.FilesToRunProvider; import com.google.devtools.build.lib.analysis.OutputGroupInfo; import com.google.devtools.build.lib.analysis.actions.FileWriteAction; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.cmdline.RepositoryName; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.packages.BuildType; import com.google.devtools.build.lib.packages.FileTarget; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.util.BazelMockAndroidSupport; import com.google.devtools.build.lib.rules.android.AndroidRuleClasses.MultidexMode; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.AndroidDeployInfo; import com.google.devtools.build.lib.rules.cpp.CppFileTypes; import com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider; import com.google.devtools.build.lib.rules.java.JavaCompileAction; import com.google.devtools.build.lib.rules.java.JavaInfo; import com.google.devtools.build.lib.rules.java.JavaSemantics; import com.google.devtools.build.lib.skyframe.ConfiguredTargetAndData; import com.google.devtools.build.lib.testutil.MoreAsserts; import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * A test for {@link com.google.devtools.build.lib.rules.android.AndroidBinary}. */ @RunWith(JUnit4.class) public class AndroidBinaryTest extends AndroidBuildViewTestCase { @Before public void setupCcToolchain() throws Exception { getAnalysisMock().ccSupport().setupCcToolchainConfigForCpu(mockToolsConfig, "armeabi-v7a"); } @Before public void createFiles() throws Exception { scratch.file("java/android/BUILD", "android_binary(name = 'app',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " )"); scratch.file("java/android/res/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); scratch.file("java/android/A.java", "package android; public class A {};"); } @Test public void testAndroidSplitTransitionWithInvalidCpu() throws Exception { scratch.file( "test/skylark/my_rule.bzl", "def impl(ctx): ", " return []", "my_rule = rule(", " implementation = impl,", " attrs = {", " 'deps': attr.label_list(cfg = android_common.multi_cpu_configuration),", " 'dep': attr.label(cfg = android_common.multi_cpu_configuration),", " })"); scratch.file( "test/skylark/BUILD", "load('//test/skylark:my_rule.bzl', 'my_rule')", "my_rule(name = 'test', deps = [':main'], dep = ':main')", "cc_binary(name = 'main', srcs = ['main.c'])"); BazelMockAndroidSupport.setupNdk(mockToolsConfig); // --android_cpu with --android_crosstool_top also triggers the split transition. useConfiguration("--fat_apk_cpu=doesnotexist", "--android_crosstool_top=//android/crosstool:everything"); AssertionError noToolchainError = assertThrows(AssertionError.class, () -> getConfiguredTarget("//test/skylark:test")); assertThat(noToolchainError) .hasMessageThat() .contains("does not contain a toolchain for cpu 'doesnotexist'"); } @Test public void testAssetsInExternalRepository() throws Exception { FileSystemUtils.appendIsoLatin1( scratch.resolve("WORKSPACE"), "local_repository(name='r', path='/r')"); scratch.file("/r/WORKSPACE"); scratch.file("/r/p/BUILD", "filegroup(name='assets', srcs=['a/b'])"); scratch.file("/r/p/a/b"); invalidatePackages(); scratchConfiguredTarget("java/a", "a", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " assets = ['@r//p:assets'],", " assets_dir = '')"); } @Test public void testMultidexModeAndMainDexProguardSpecs() throws Exception { checkError("java/a", "a", "only allowed if 'multidex' is set to 'legacy'", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " main_dex_proguard_specs = ['foo'])"); } @Test public void testAndroidManifestWithCustomName() throws Exception { scratchConfiguredTarget( "java/a", "a", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'SomeOtherAndroidManifest.xml')"); assertNoEvents(); } @Test public void testMainDexProguardSpecs() throws Exception { useConfiguration("--noincremental_dexing"); ConfiguredTarget ct = scratchConfiguredTarget("java/a", "a", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'legacy',", " main_dex_proguard_specs = ['a.spec'])"); Artifact intermediateJar = artifactByPath(ImmutableList.of(getCompressedUnsignedApk(ct)), ".apk", ".dex.zip", ".dex.zip", "main_dex_list.txt", "_intermediate.jar"); List<String> args = getGeneratingSpawnActionArgs(intermediateJar); MoreAsserts.assertContainsSublist(args, "-include", "java/a/a.spec"); assertThat(Joiner.on(" ").join(args)).doesNotContain("mainDexClasses.rules"); } @Test public void testMainDexListObfuscation() throws Exception { useConfiguration("--noincremental_dexing"); scratch.file("/java/a/list.txt"); ConfiguredTarget ct = scratchConfiguredTarget( "java/a", "a", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'manual_main_dex',", " proguard_generate_mapping = 1,", " main_dex_list = 'list.txt')"); Artifact obfuscatedDexList = artifactByPath( ImmutableList.of(getCompressedUnsignedApk(ct)), ".apk", ".dex.zip", ".dex.zip", "main_dex_list_obfuscated.txt"); List<String> args = getGeneratingSpawnActionArgs(obfuscatedDexList); assertThat(args.get(0)).contains("dex_list_obfuscator"); MoreAsserts.assertContainsSublist(args, "--input", "java/a/list.txt"); } @Test public void testNonLegacyNativeDepsDoesNotPolluteDexSharding() throws Exception { scratch.file("java/a/BUILD", "android_binary(name = 'a',", " manifest = 'AndroidManifest.xml',", " multidex = 'native',", " deps = [':cc'],", " dex_shards = 2)", "cc_library(name = 'cc',", " srcs = ['cc.cc'])"); Artifact jarShard = artifactByPath( ImmutableList.of(getCompressedUnsignedApk(getConfiguredTarget("//java/a:a"))), ".apk", "classes.dex.zip", "shard1.dex.zip", "shard1.jar.dex.zip"); Iterable<Artifact> shardInputs = getGeneratingAction(jarShard).getInputs(); assertThat(getFirstArtifactEndingWith(shardInputs, ".txt")).isNull(); } @Test public void testJavaPluginProcessorPath() throws Exception { scratch.file("java/test/BUILD", "java_library(name = 'plugin_dep',", " srcs = [ 'ProcessorDep.java'])", "java_plugin(name = 'plugin',", " srcs = ['AnnotationProcessor.java'],", " processor_class = 'com.google.process.stuff',", " deps = [ ':plugin_dep' ])", "android_binary(name = 'to_be_processed',", " manifest = 'AndroidManifest.xml',", " plugins = [':plugin'],", " srcs = ['ToBeProcessed.java'])"); ConfiguredTarget target = getConfiguredTarget("//java/test:to_be_processed"); JavaCompileAction javacAction = (JavaCompileAction) getGeneratingAction(getBinArtifact("libto_be_processed.jar", target)); assertThat(getProcessorNames(javacAction)).contains("com.google.process.stuff"); assertThat(getProcessorNames(javacAction)).hasSize(1); assertThat( ActionsTestUtil.baseArtifactNames( getInputs(javacAction, getProcessorpath(javacAction)))) .containsExactly("libplugin.jar", "libplugin_dep.jar"); assertThat( actionsTestUtil() .predecessorClosureOf(getFilesToBuild(target), JavaSemantics.JAVA_SOURCE)) .isEqualTo("ToBeProcessed.java AnnotationProcessor.java ProcessorDep.java"); } // Same test as above, enabling the plugin through the command line. @Test public void testPluginCommandLine() throws Exception { scratch.file("java/test/BUILD", "java_library(name = 'plugin_dep',", " srcs = [ 'ProcessorDep.java'])", "java_plugin(name = 'plugin',", " srcs = ['AnnotationProcessor.java'],", " processor_class = 'com.google.process.stuff',", " deps = [ ':plugin_dep' ])", "android_binary(name = 'to_be_processed',", " manifest = 'AndroidManifest.xml',", " srcs = ['ToBeProcessed.java'])"); useConfiguration("--plugin=//java/test:plugin"); ConfiguredTarget target = getConfiguredTarget("//java/test:to_be_processed"); JavaCompileAction javacAction = (JavaCompileAction) getGeneratingAction(getBinArtifact("libto_be_processed.jar", target)); assertThat(getProcessorNames(javacAction)).contains("com.google.process.stuff"); assertThat(getProcessorNames(javacAction)).hasSize(1); assertThat( ActionsTestUtil.baseArtifactNames( getInputs(javacAction, getProcessorpath(javacAction)))) .containsExactly("libplugin.jar", "libplugin_dep.jar"); assertThat( actionsTestUtil() .predecessorClosureOf(getFilesToBuild(target), JavaSemantics.JAVA_SOURCE)) .isEqualTo("ToBeProcessed.java AnnotationProcessor.java ProcessorDep.java"); } @Test public void testInvalidPlugin() throws Exception { checkError("java/test", "lib", // error: getErrorMsgMisplacedRules("plugins", "android_binary", "//java/test:lib", "java_library", "//java/test:not_a_plugin"), // BUILD file: "java_library(name = 'not_a_plugin',", " srcs = [ 'NotAPlugin.java'])", "android_binary(name = 'lib',", " plugins = [':not_a_plugin'],", " manifest = 'AndroidManifest.xml',", " srcs = ['Lib.java'])"); } @Test public void testBaselineCoverageArtifacts() throws Exception { useConfiguration("--collect_code_coverage"); ConfiguredTarget target = scratchConfiguredTarget("java/com/google/a", "bin", "android_binary(name='bin', srcs=['Main.java'], manifest='AndroidManifest.xml')"); assertThat(baselineCoverageArtifactBasenames(target)).containsExactly("Main.java"); } @Test public void testSameSoFromMultipleDeps() throws Exception { scratch.file("java/d/BUILD", "genrule(name='genrule', srcs=[], outs=['genrule.so'], cmd='')", "cc_library(name='cc1', srcs=[':genrule.so'])", "cc_library(name='cc2', srcs=[':genrule.so'])", "android_binary(name='ab', deps=[':cc1', ':cc2'], manifest='AndroidManifest.xml')"); getConfiguredTarget("//java/d:ab"); } @Test public void testSimpleBinary_desugarJava8() throws Exception { useConfiguration("--experimental_desugar_for_android"); ConfiguredTarget binary = getConfiguredTarget("//java/android:app"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)), "_deploy.jar"); assertThat(ActionsTestUtil.baseArtifactNames(action.getInputs())) .contains("libapp.jar_desugared.jar"); assertThat(ActionsTestUtil.baseArtifactNames(action.getInputs())) .doesNotContain("libapp.jar"); } /** * Tests that --experimental_check_desugar_deps causes the relevant flags to be set on desugaring * and singlejar actions, and makes sure the deploy jar is built even when just building an APK. */ @Test public void testSimpleBinary_checkDesugarDepsAlwaysHappens() throws Exception { useConfiguration("--experimental_check_desugar_deps"); ConfiguredTarget binary = getConfiguredTarget("//java/android:app"); assertNoEvents(); // 1. Find app's deploy jar and make sure checking flags are set for it and its inputs SpawnAction singlejar = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(binary), "/app_deploy.jar"); assertThat(getGeneratingSpawnActionArgs(singlejar.getPrimaryOutput())) .contains("--check_desugar_deps"); SpawnAction desugar = (SpawnAction) actionsTestUtil() .getActionForArtifactEndingWith(singlejar.getInputs(), "/libapp.jar_desugared.jar"); assertThat(desugar).isNotNull(); assertThat(getGeneratingSpawnActionArgs(desugar.getPrimaryOutput())) .contains("--emit_dependency_metadata_as_needed"); // 2. Make sure all APK outputs depend on the deploy Jar. int found = 0; for (Artifact built : getFilesToBuild(binary)) { if (built.getExtension().equals("apk")) { // If this assertion breaks then APK artifacts have stopped depending on deploy jars. // If that's desired then we'll need to make sure dependency checking is done in another // action that APK artifacts depend on, in addition to the check that happens when building // deploy.jars, which we assert above. assertWithMessage("%s dependency on deploy.jar", built.getFilename()) .that(actionsTestUtil().artifactClosureOf(built)) .contains(singlejar.getPrimaryOutput()); ++found; } } assertThat(found).isEqualTo(2 /* signed and unsigned apks */); } // regression test for #3169099 @Test public void testBinarySrcs() throws Exception { scratch.file("java/srcs/a.foo", "foo"); scratch.file("java/srcs/BUILD", "android_binary(name = 'valid', manifest = 'AndroidManifest.xml', " + "srcs = ['a.java', 'b.srcjar', ':gvalid', ':gmix'])", "android_binary(name = 'invalid', manifest = 'AndroidManifest.xml', " + "srcs = ['a.foo', ':ginvalid'])", "android_binary(name = 'mix', manifest = 'AndroidManifest.xml', " + "srcs = ['a.java', 'a.foo'])", "genrule(name = 'gvalid', srcs = ['a.java'], outs = ['b.java'], cmd = '')", "genrule(name = 'ginvalid', srcs = ['a.java'], outs = ['b.foo'], cmd = '')", "genrule(name = 'gmix', srcs = ['a.java'], outs = ['c.java', 'c.foo'], cmd = '')" ); assertSrcsValidityForRuleType("//java/srcs", "android_binary", ".java or .srcjar"); } // regression test for #3169095 @Test public void testXmbInSrcs_NotPermittedButDoesNotThrow() throws Exception { reporter.removeHandler(failFastHandler); scratchConfiguredTarget("java/xmb", "a", "android_binary(name = 'a', manifest = 'AndroidManifest.xml', srcs = ['a.xmb'])"); // We expect there to be an error here because a.xmb is not a valid src, // and more importantly, no exception to have been thrown. assertContainsEvent("in srcs attribute of android_binary rule //java/xmb:a: " + "target '//java/xmb:a.xmb' does not exist"); } @Test public void testNativeLibraryBasenameCollision() throws Exception { reporter.removeHandler(failFastHandler); // expect errors scratch.file("java/android/common/BUILD", "cc_library(name = 'libcommon_armeabi',", " srcs = ['armeabi/native.so'],)"); scratch.file("java/android/app/BUILD", "cc_library(name = 'libnative',", " srcs = ['native.so'],)", "android_binary(name = 'b',", " srcs = ['A.java'],", " deps = [':libnative', '//java/android/common:libcommon_armeabi'],", " manifest = 'AndroidManifest.xml',", " )"); getConfiguredTarget("//java/android/app:b"); assertContainsEvent("Each library in the transitive closure must have a unique basename to " + "avoid name collisions when packaged into an apk, but two libraries have the basename " + "'native.so': java/android/common/armeabi/native.so and java/android/app/native.so"); } private void setupNativeLibrariesForLinking() throws Exception { scratch.file("java/android/common/BUILD", "cc_library(name = 'common_native',", " srcs = ['common.cc'],)", "android_library(name = 'common',", " exports = [':common_native'],)"); scratch.file("java/android/app/BUILD", "cc_library(name = 'native',", " srcs = ['native.cc'],)", "android_binary(name = 'auto',", " srcs = ['A.java'],", " deps = [':native', '//java/android/common:common'],", " manifest = 'AndroidManifest.xml',", " )", "android_binary(name = 'off',", " srcs = ['A.java'],", " deps = [':native', '//java/android/common:common'],", " manifest = 'AndroidManifest.xml',", " )"); } private void assertNativeLibraryLinked(ConfiguredTarget target, String... srcNames) { Artifact linkedLib = getOnlyElement(getNativeLibrariesInApk(target)); assertThat(linkedLib.getFilename()) .isEqualTo("lib" + target.getLabel().toPathFragment().getBaseName() + ".so"); assertThat(linkedLib.isSourceArtifact()).isFalse(); assertWithMessage("Native libraries were not linked to produce " + linkedLib) .that(getGeneratingLabelForArtifact(linkedLib)) .isEqualTo(target.getLabel()); assertThat(artifactsToStrings(actionsTestUtil().artifactClosureOf(linkedLib))) .containsAtLeastElementsIn(ImmutableSet.copyOf(Arrays.asList(srcNames))); } @Test public void testNativeLibrary_LinksLibrariesWhenCodeIsPresent() throws Exception { setupNativeLibrariesForLinking(); assertNativeLibraryLinked(getConfiguredTarget("//java/android/app:auto"), "src java/android/common/common.cc", "src java/android/app/native.cc"); assertNativeLibraryLinked(getConfiguredTarget("//java/android/app:off"), "src java/android/common/common.cc", "src java/android/app/native.cc"); } @Test public void testNativeLibrary_CopiesLibrariesDespiteExtraLayersOfIndirection() throws Exception { scratch.file("java/android/app/BUILD", "cc_library(name = 'native_dep',", " srcs = ['dep.so'])", "cc_library(name = 'native',", " srcs = ['native_prebuilt.so'],", " deps = [':native_dep'])", "cc_library(name = 'native_wrapper',", " deps = [':native'])", "android_binary(name = 'app',", " srcs = ['A.java'],", " deps = [':native_wrapper'],", " manifest = 'AndroidManifest.xml',", " )"); assertNativeLibrariesCopiedNotLinked(getConfiguredTarget("//java/android/app:app"), "src java/android/app/dep.so", "src java/android/app/native_prebuilt.so"); } @Test public void testNativeLibrary_CopiesLibrariesWrappedInCcLibraryWithSameName() throws Exception { scratch.file("java/android/app/BUILD", "cc_library(name = 'native',", " srcs = ['libnative.so'])", "android_binary(name = 'app',", " srcs = ['A.java'],", " deps = [':native'],", " manifest = 'AndroidManifest.xml',", " )"); assertNativeLibrariesCopiedNotLinked(getConfiguredTarget("//java/android/app:app"), "src java/android/app/libnative.so"); } @Test public void testNativeLibrary_LinksWhenPrebuiltArchiveIsSupplied() throws Exception { scratch.file("java/android/app/BUILD", "cc_library(name = 'native_dep',", " srcs = ['dep.lo'])", "cc_library(name = 'native',", " srcs = ['native_prebuilt.a'],", " deps = [':native_dep'])", "cc_library(name = 'native_wrapper',", " deps = [':native'])", "android_binary(name = 'app',", " srcs = ['A.java'],", " deps = [':native_wrapper'],", " manifest = 'AndroidManifest.xml',", " )"); assertNativeLibraryLinked(getConfiguredTarget("//java/android/app:app"), "src java/android/app/native_prebuilt.a"); } @Test public void testNativeLibrary_CopiesFullLibrariesInIfsoMode() throws Exception { useConfiguration("--interface_shared_objects"); scratch.file("java/android/app/BUILD", "cc_library(name = 'native_dep',", " srcs = ['dep.so'])", "cc_library(name = 'native',", " srcs = ['native.cc', 'native_prebuilt.so'],", " deps = [':native_dep'])", "android_binary(name = 'app',", " srcs = ['A.java'],", " deps = [':native'],", " manifest = 'AndroidManifest.xml',", " )"); ConfiguredTarget app = getConfiguredTarget("//java/android/app:app"); Iterable<Artifact> nativeLibraries = getNativeLibrariesInApk(app); assertThat(artifactsToStrings(nativeLibraries)) .containsAtLeast("src java/android/app/native_prebuilt.so", "src java/android/app/dep.so"); assertThat(FileType.filter(nativeLibraries, CppFileTypes.INTERFACE_SHARED_LIBRARY)) .isEmpty(); } @Test public void testNativeLibrary_ProvidesLinkerScriptToLinkAction() throws Exception { scratch.file("java/android/app/BUILD", "cc_library(name = 'native',", " srcs = ['native.cc'],", " linkopts = ['-Wl,-version-script', '$(location jni.lds)'],", " deps = ['jni.lds'],)", "android_binary(name = 'app',", " srcs = ['A.java'],", " deps = [':native'],", " manifest = 'AndroidManifest.xml',", " )"); ConfiguredTarget app = getConfiguredTarget("//java/android/app:app"); Artifact copiedLib = getOnlyElement(getNativeLibrariesInApk(app)); Artifact linkedLib = getOnlyElement(getGeneratingAction(copiedLib).getInputs()); Iterable<Artifact> linkInputs = getGeneratingAction(linkedLib).getInputs(); assertThat(ActionsTestUtil.baseArtifactNames(linkInputs)).contains("jni.lds"); } /** Regression test for http://b/33173461. */ @Test public void testIncrementalDexingUsesDexArchives_binaryDependingOnAliasTarget() throws Exception { scratch.file( "java/com/google/android/BUILD", "android_library(", " name = 'dep',", " srcs = ['dep.java'],", " resource_files = glob(['res/**']),", " manifest = 'AndroidManifest.xml',", ")", "alias(", " name = 'alt',", " actual = ':dep',", ")", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " multidex = 'native',", " manifest = 'AndroidManifest.xml',", " deps = [':alt',],", ")"); ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); Action shardAction = getGeneratingAction(getBinArtifact("_dx/top/classes.jar", topTarget)); for (Artifact input : getNonToolInputs(shardAction)) { String basename = input.getFilename(); // all jars are converted to dex archives assertWithMessage(basename) .that(!basename.contains(".jar") || basename.endsWith(".jar.dex.zip")) .isTrue(); // all jars are desugared before being converted if (basename.endsWith(".jar.dex.zip")) { assertThat(getGeneratingAction(input).getPrimaryInput().getFilename()) .isEqualTo(basename.substring(0, basename.length() - ".jar.dex.zip".length()) + ".jar_desugared.jar"); } } // Make sure exactly the dex archives generated for top and dependents appear. We also *don't* // want neverlink and unused_dep to appear, and to be safe we do so by explicitly enumerating // *all* expected input dex archives. assertThat( Iterables.filter( ActionsTestUtil.baseArtifactNames(getNonToolInputs(shardAction)), Predicates.containsPattern("\\.jar"))) .containsExactly( // top's dex archives "libtop.jar.dex.zip", "top_resources.jar.dex.zip", // dep's dex archives "libdep.jar.dex.zip"); } @Test public void testIncrementalDexingDisabledWithBlacklistedDexopts() throws Exception { // Even if we mark a dx flag as supported, incremental dexing isn't used with blacklisted // dexopts (unless incremental_dexing attribute is set, which a different test covers) useConfiguration("--incremental_dexing", "--non_incremental_per_target_dexopts=--no-locals", "--dexopts_supported_in_incremental_dexing=--no-locals"); scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " dexopts = ['--no-locals'],", " dex_shards = 2,", " multidex = 'native',", ")"); ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); Action shardAction = getGeneratingAction(getBinArtifact("_dx/top/shard1.jar", topTarget)); assertThat( Iterables.filter( ActionsTestUtil.baseArtifactNames(getNonToolInputs(shardAction)), Predicates.containsPattern("\\.jar\\.dex\\.zip"))) .isEmpty(); // no dex archives are used } @Test public void testIncrementalDexingDisabledWithProguard() throws Exception { scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard.cfg'],", ")"); ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); Action dexAction = getGeneratingAction(getBinArtifact("_dx/top/classes.dex", topTarget)); assertThat( Iterables.filter( ActionsTestUtil.baseArtifactNames(dexAction.getInputs()), Predicates.containsPattern("\\.jar"))) .containsExactly("top_proguard.jar", "dx_binary.jar"); // proguard output is used directly } @Test public void testIncrementalDexing_incompatibleWithProguardWhenDisabled() throws Exception { useConfiguration("--experimental_incremental_dexing_after_proguard=0"); // disable with Proguard checkError("java/com/google/android", "top", "target cannot be incrementally dexed", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard.cfg'],", " incremental_dexing = 1,", ")"); } @Test public void testIncrementalDexingAfterProguard_unsharded() throws Exception { useConfiguration("--experimental_incremental_dexing_after_proguard=1"); // Use "legacy" multidex mode so we get a main dex list file and can test that it's passed to // the splitter action (similar to _withDexShards below), unlike without the dex splitter where // the main dex list goes to the merging action. scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " incremental_dexing = 1,", " multidex = 'legacy',", " dexopts = ['--minimal-main-dex', '--positions=none'],", " proguard_specs = ['b.pro'],", ")"); ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); SpawnAction shardAction = getGeneratingSpawnAction(getBinArtifact("_dx/top/classes.dex.zip", topTarget)); assertThat(shardAction.getArguments()).contains("--main-dex-list"); assertThat(shardAction.getArguments()).contains("--minimal-main-dex"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(shardAction))) .containsExactly("classes.jar", "main_dex_list.txt"); // --positions dexopt is supported after Proguard, even though not normally otherwise assertThat( paramFileArgsForAction( getGeneratingSpawnAction(getBinArtifact("_dx/top/classes.jar", topTarget)))) .contains("--positions=none"); } @Test public void testIncrementalDexingAfterProguard_autoShardedMultidexAutoOptIn() throws Exception { useConfiguration("--experimental_incremental_dexing_after_proguard=3", "--experimental_incremental_dexing_after_proguard_by_default"); // Use "legacy" multidex mode so we get a main dex list file and can test that it's passed to // the splitter action (similar to _withDexShards below), unlike without the dex splitter where // the main dex list goes to the merging action. scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " multidex = 'legacy',", " dexopts = ['--minimal-main-dex', '--positions=none'],", " proguard_specs = ['b.pro'],", ")"); // incremental_dexing = 1 attribute not needed ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); SpawnAction splitAction = getGeneratingSpawnAction(getTreeArtifact("dexsplits/top", topTarget)); assertThat(splitAction.getArguments()).contains("--main-dex-list"); assertThat(splitAction.getArguments()).contains("--minimal-main-dex"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(splitAction))) .containsExactly("shard1.jar.dex.zip", "shard2.jar.dex.zip", "shard3.jar.dex.zip", "main_dex_list.txt"); SpawnAction shuffleAction = getGeneratingSpawnAction(getBinArtifact("_dx/top/shard1.jar", topTarget)); assertThat(shuffleAction.getArguments()).doesNotContain("--main-dex-list"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(shuffleAction))) .containsExactly("top_proguard.jar"); // --positions dexopt is supported after Proguard, even though not normally otherwise assertThat( paramFileArgsForAction( getGeneratingSpawnAction(getBinArtifact("_dx/top/shard3.jar.dex.zip", topTarget)))) .contains("--positions=none"); } @Test public void testIncrementalDexingAfterProguard_explicitDexShards() throws Exception { useConfiguration("--experimental_incremental_dexing_after_proguard=2"); // Use "legacy" multidex mode so we get a main dex list file and can test that it's passed to // the shardAction, not to the subsequent dexMerger action. Without dex_shards, main dex list // file goes to the dexMerger instead (see _multidex test). scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " dex_shards = 25,", " incremental_dexing = 1,", " multidex = 'legacy',", " proguard_specs = ['b.pro'],", ")"); ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); SpawnAction shardAction = getGeneratingSpawnAction(getBinArtifact("_dx/top/shard25.jar", topTarget)); assertThat(shardAction.getArguments()).contains("--main_dex_filter"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(shardAction))) .containsExactly("top_proguard.jar", "main_dex_list.txt"); SpawnAction mergeAction = getGeneratingSpawnAction(getBinArtifact("_dx/top/shard1.jar.dex.zip", topTarget)); assertThat(mergeAction.getArguments()).doesNotContain("--main-dex-list"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(mergeAction))) .contains("shard1.jar"); } @Test public void testIncrementalDexingAfterProguard_autoShardedMonodex() throws Exception { useConfiguration("--experimental_incremental_dexing_after_proguard=3"); // Use "legacy" multidex mode so we get a main dex list file and can test that it's passed to // the splitter action (similar to _withDexShards below), unlike without the dex splitter where // the main dex list goes to the merging action. scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'top',", " srcs = ['foo.java', 'bar.srcjar'],", " manifest = 'AndroidManifest.xml',", " incremental_dexing = 1,", " multidex = 'off',", " proguard_specs = ['b.pro'],", ")"); ConfiguredTarget topTarget = getConfiguredTarget("//java/com/google/android:top"); assertNoEvents(); SpawnAction mergeAction = getGeneratingSpawnAction(getBinArtifact("_dx/top/classes.dex.zip", topTarget)); assertThat(mergeAction.getArguments()).doesNotContain("--main-dex-list"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(mergeAction))) .containsExactly("shard1.jar.dex.zip", "shard2.jar.dex.zip", "shard3.jar.dex.zip"); SpawnAction shuffleAction = getGeneratingSpawnAction(getBinArtifact("_dx/top/shard1.jar", topTarget)); assertThat(shuffleAction.getArguments()).doesNotContain("--main-dex-list"); assertThat(ActionsTestUtil.baseArtifactNames(getNonToolInputs(shuffleAction))) .containsExactly("top_proguard.jar"); } @Test public void testV1SigningMethod() throws Exception { actualSignerToolTests("v1", "true", "false"); } @Test public void testV2SigningMethod() throws Exception { actualSignerToolTests("v2", "false", "true"); } @Test public void testV1V2SigningMethod() throws Exception { actualSignerToolTests("v1_v2", "true", "true"); } private void actualSignerToolTests(String apkSigningMethod, String signV1, String signV2) throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'hello',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',)"); useConfiguration("--apk_signing_method=" + apkSigningMethod); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:hello"); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)); assertThat(getFirstArtifactEndingWith(artifacts, "signed_hello.apk")).isNull(); SpawnAction unsignedApkAction = (SpawnAction) actionsTestUtil() .getActionForArtifactEndingWith(artifacts, "/hello_unsigned.apk"); assertThat( Streams.stream(unsignedApkAction.getInputs()) .map(Artifact::getFilename) .anyMatch(filename -> Ascii.toLowerCase(filename).contains("singlejar"))) .isTrue(); SpawnAction compressedUnsignedApkAction = (SpawnAction) actionsTestUtil() .getActionForArtifactEndingWith(artifacts, "compressed_hello_unsigned.apk"); assertThat( Streams.stream(compressedUnsignedApkAction.getInputs()) .map(Artifact::getFilename) .anyMatch(filename -> Ascii.toLowerCase(filename).contains("singlejar"))) .isTrue(); SpawnAction zipalignAction = (SpawnAction) actionsTestUtil() .getActionForArtifactEndingWith(artifacts, "zipaligned_hello.apk"); assertThat(zipalignAction.getCommandFilename()).endsWith("zipalign"); Artifact a = ActionsTestUtil.getFirstArtifactEndingWith(artifacts, "hello.apk"); assertThat(getGeneratingSpawnAction(a).getCommandFilename()).endsWith("ApkSignerBinary"); List<String> args = getGeneratingSpawnActionArgs(a); assertThat(flagValue("--v1-signing-enabled", args)).isEqualTo(signV1); assertThat(flagValue("--v2-signing-enabled", args)).isEqualTo(signV2); } @Test public void testResourceShrinkingAction() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'hello',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " inline_constants = 0,", " resource_files = ['res/values/strings.xml'],", " shrink_resources = 1,", " resource_configuration_filters = ['en'],", " proguard_specs = ['proguard-spec.pro'],)"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:hello"); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)); assertThat(artifacts) .containsAtLeast( getFirstArtifactEndingWith(artifacts, "resource_files.zip"), getFirstArtifactEndingWith(artifacts, "proguard.jar"), getFirstArtifactEndingWith(artifacts, "shrunk.ap_")); List<String> processingArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "resource_files.zip")); assertThat(flagValue("--resourcesOutput", processingArgs)) .endsWith("hello_files/resource_files.zip"); List<String> proguardArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "proguard.jar")); assertThat(flagValue("-outjars", proguardArgs)).endsWith("hello_proguard.jar"); List<String> shrinkingArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "shrunk.ap_")); assertThat(flagValue("--resources", shrinkingArgs)) .isEqualTo(flagValue("--resourcesOutput", processingArgs)); assertThat(flagValue("--shrunkJar", shrinkingArgs)) .isEqualTo(flagValue("-outjars", proguardArgs)); assertThat(flagValue("--proguardMapping", shrinkingArgs)) .isEqualTo(flagValue("-printmapping", proguardArgs)); assertThat(flagValue("--rTxt", shrinkingArgs)) .isEqualTo(flagValue("--rOutput", processingArgs)); assertThat(flagValue("--primaryManifest", shrinkingArgs)) .isEqualTo(flagValue("--manifestOutput", processingArgs)); assertThat(flagValue("--resourceConfigs", shrinkingArgs)) .isEqualTo(flagValue("--resourceConfigs", processingArgs)); List<String> packageArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "_hello_proguard.cfg")); assertThat(flagValue("--tool", packageArgs)).isEqualTo("PACKAGE"); assertThat(packageArgs).doesNotContain("--conditionalKeepRules"); } @Test public void testResourceCycleShrinking() throws Exception { useConfiguration("--experimental_android_resource_cycle_shrinking=true"); checkError( "java/a", "a", "resource cycle shrinking can only be enabled for builds with aapt2", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", " shrink_resources = 1,", ")"); } @Test public void testResourceCycleShrinkingWithoutResourceShinking() throws Exception { useConfiguration("--experimental_android_resource_cycle_shrinking=true"); checkError( "java/a", "a", "resource cycle shrinking can only be enabled when resource shrinking is enabled", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", " shrink_resources = 0,", ")"); } @Test public void testResourceShrinking_RequiresProguard() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'hello',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " inline_constants = 0,", " resource_files = ['res/values/strings.xml'],", " shrink_resources = 1,)"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:hello"); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)); assertThat(artifacts).containsNoneOf( getFirstArtifactEndingWith(artifacts, "shrunk.jar"), getFirstArtifactEndingWith(artifacts, "shrunk.ap_")); } @Test public void testProguardExtraOutputs() throws Exception { scratch.file( "java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro'])"); ConfiguredTarget output = getConfiguredTarget("//java/com/google/android/hello:b"); // Checks that ProGuard is called with the appropriate options. Artifact a = getFirstArtifactEndingWith(getFilesToBuild(output), "_proguard.jar"); SpawnAction action = getGeneratingSpawnAction(a); List<String> args = getGeneratingSpawnActionArgs(a); // Assert that the ProGuard executable set in the android_sdk rule appeared in the command-line // of the SpawnAction that generated the _proguard.jar. assertThat( Iterables.any( args, new Predicate<String>() { @Override public boolean apply(String s) { return s.endsWith("ProGuard"); } })) .isTrue(); assertThat(args) .containsAtLeast( "-injars", execPathEndingWith(action.getInputs(), "b_deploy.jar"), "-printseeds", execPathEndingWith(action.getOutputs(), "b_proguard.seeds"), "-printusage", execPathEndingWith(action.getOutputs(), "b_proguard.usage")) .inOrder(); // Checks that the output files are produced. assertProguardUsed(output); assertThat(getBinArtifact("b_proguard.usage", output)).isNotNull(); assertThat(getBinArtifact("b_proguard.seeds", output)).isNotNull(); } @Test public void testProGuardExecutableMatchesConfiguration() throws Exception { scratch.file("java/com/google/devtools/build/jkrunchy/BUILD", "package(default_visibility=['//visibility:public'])", "java_binary(name = 'jkrunchy',", " srcs = glob(['*.java']),", " main_class = 'com.google.devtools.build.jkrunchy.JKrunchyMain')"); useConfiguration("--proguard_top=//java/com/google/devtools/build/jkrunchy:jkrunchy"); scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro'])"); ConfiguredTarget output = getConfiguredTarget("//java/com/google/android/hello:b_proguard.jar"); assertProguardUsed(output); SpawnAction proguardAction = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(output), "_proguard.jar"); Artifact jkrunchyExecutable = getHostConfiguredTarget("//java/com/google/devtools/build/jkrunchy") .getProvider(FilesToRunProvider.class) .getExecutable(); assertWithMessage("ProGuard implementation was not correctly taken from the configuration") .that(proguardAction.getCommandFilename()) .isEqualTo(jkrunchyExecutable.getExecPathString()); } @Test public void testNeverlinkTransitivity() throws Exception { useConfiguration("--android_fixed_resource_neverlinking"); scratch.file( "java/com/google/android/neversayneveragain/BUILD", "android_library(name = 'l1',", " srcs = ['l1.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/resource.xml'])", "android_library(name = 'l2',", " srcs = ['l2.java'],", " deps = [':l1'],", " neverlink = 1)", "android_library(name = 'l3',", " srcs = ['l3.java'],", " deps = [':l2'])", "android_library(name = 'l4',", " srcs = ['l4.java'],", " deps = [':l1'])", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " deps = [':l2'],", " manifest = 'AndroidManifest.xml')", "android_binary(name = 'b2',", " srcs = ['b2.java'],", " deps = [':l3'],", " manifest = 'AndroidManifest.xml')", "android_binary(name = 'b3',", " srcs = ['b3.java'],", " deps = [':l3', ':l4'],", " manifest = 'AndroidManifest.xml')"); ConfiguredTarget b1 = getConfiguredTarget("//java/com/google/android/neversayneveragain:b1"); Action b1DeployAction = actionsTestUtil().getActionForArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(b1)), "b1_deploy.jar"); List<String> b1Inputs = prettyArtifactNames(b1DeployAction.getInputs()); assertThat(b1Inputs).containsNoneOf( "java/com/google/android/neversayneveragain/libl1.jar_desugared.jar", "java/com/google/android/neversayneveragain/libl2.jar_desugared.jar", "java/com/google/android/neversayneveragain/libl3.jar_desugared.jar", "java/com/google/android/neversayneveragain/libl4.jar_desugared.jar"); assertThat(b1Inputs).contains( "java/com/google/android/neversayneveragain/libb1.jar_desugared.jar"); assertThat( resourceInputPaths( "java/com/google/android/neversayneveragain", getValidatedResources(b1))) .doesNotContain("res/values/resource.xml"); ConfiguredTarget b2 = getConfiguredTarget("//java/com/google/android/neversayneveragain:b2"); Action b2DeployAction = actionsTestUtil().getActionForArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(b2)), "b2_deploy.jar"); List<String> b2Inputs = prettyArtifactNames(b2DeployAction.getInputs()); assertThat(b2Inputs).containsNoneOf( "java/com/google/android/neversayneveragain/libl1.jar_desugared.jar", "java/com/google/android/neversayneveragain/libl2.jar_desugared.jar", "java/com/google/android/neversayneveragain/libl4.jar_desugared.jar"); assertThat(b2Inputs) .containsAtLeast( "java/com/google/android/neversayneveragain/_dx/l3/libl3.jar_desugared.jar", "java/com/google/android/neversayneveragain/libb2.jar_desugared.jar"); assertThat( resourceInputPaths( "java/com/google/android/neversayneveragain", getValidatedResources(b2))) .doesNotContain("res/values/resource.xml"); ConfiguredTarget b3 = getConfiguredTarget("//java/com/google/android/neversayneveragain:b3"); Action b3DeployAction = actionsTestUtil().getActionForArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(b3)), "b3_deploy.jar"); List<String> b3Inputs = prettyArtifactNames(b3DeployAction.getInputs()); assertThat(b3Inputs) .containsAtLeast( "java/com/google/android/neversayneveragain/_dx/l1/libl1.jar_desugared.jar", "java/com/google/android/neversayneveragain/_dx/l3/libl3.jar_desugared.jar", "java/com/google/android/neversayneveragain/_dx/l4/libl4.jar_desugared.jar", "java/com/google/android/neversayneveragain/libb3.jar_desugared.jar"); assertThat(b3Inputs) .doesNotContain("java/com/google/android/neversayneveragain/libl2.jar_desugared.jar"); assertThat( resourceInputPaths( "java/com/google/android/neversayneveragain", getValidatedResources(b3))) .contains("res/values/resource.xml"); } @Test public void testDexopts() throws Exception { useConfiguration("--noincremental_dexing"); checkDexopts("[ '--opt1', '--opt2' ]", ImmutableList.of("--opt1", "--opt2")); } @Test public void testDexoptsTokenization() throws Exception { useConfiguration("--noincremental_dexing"); checkDexopts("[ '--opt1', '--opt2 tokenized' ]", ImmutableList.of("--opt1", "--opt2", "tokenized")); } @Test public void testDexoptsMakeVariableSubstitution() throws Exception { useConfiguration("--noincremental_dexing"); checkDexopts("[ '--opt1', '$(COMPILATION_MODE)' ]", ImmutableList.of("--opt1", "fastbuild")); } private void checkDexopts(String dexopts, List<String> expectedArgs) throws Exception { scratch.file("java/com/google/android/BUILD", "android_binary(name = 'b',", " srcs = ['dummy1.java'],", " dexopts = " + dexopts + ",", " manifest = 'AndroidManifest.xml')"); // Include arguments that are always included. List<String> fixedArgs = ImmutableList.of("--num-threads=5"); expectedArgs = new ImmutableList.Builder<String>() .addAll(fixedArgs).addAll(expectedArgs).build(); // Ensure that the args that immediately follow "--dex" match the expectation. ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android:b"); List<String> args = getGeneratingSpawnActionArgs( ActionsTestUtil.getFirstArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)), "classes.dex")); int start = args.indexOf("--dex") + 1; assertThat(start).isNotEqualTo(0); int end = Math.min(args.size(), start + expectedArgs.size()); assertThat(args.subList(start, end)).isEqualTo(expectedArgs); } @Test public void testDexMainListOpts() throws Exception { checkDexMainListOpts("[ '--opt1', '--opt2' ]", "--opt1", "--opt2"); } @Test public void testDexMainListOptsTokenization() throws Exception { checkDexMainListOpts("[ '--opt1', '--opt2 tokenized' ]", "--opt1", "--opt2", "tokenized"); } @Test public void testDexMainListOptsMakeVariableSubstitution() throws Exception { checkDexMainListOpts("[ '--opt1', '$(COMPILATION_MODE)' ]", "--opt1", "fastbuild"); } private void checkDexMainListOpts(String mainDexListOpts, String... expectedArgs) throws Exception { scratch.file("java/com/google/android/BUILD", "android_binary(name = 'b',", " srcs = ['dummy1.java'],", " multidex = \"legacy\",", " main_dex_list_opts = " + mainDexListOpts + ",", " manifest = 'AndroidManifest.xml')"); // Ensure that the args that immediately follow the main class in the shell command // match the expectation. ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android:b"); List<String> args = getGeneratingSpawnActionArgs( ActionsTestUtil.getFirstArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)), "main_dex_list.txt")); // args: [ "bash", "-c", "java -cp dx.jar main opts other" ] MoreAsserts.assertContainsSublist(args, expectedArgs); } @Test public void testResourceConfigurationFilters() throws Exception { scratch.file("java/com/google/android/BUILD", "android_binary(name = 'b',", " srcs = ['dummy1.java'],", " manifest = 'AndroidManifest.xml',", " resource_configuration_filters = [ 'en', 'fr'],)"); // Ensure that the args are present ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android:b"); List<String> args = resourceArguments(getValidatedResources(binary)); assertThat(flagValue("--resourceConfigs", args)).contains("en,fr"); } @Test public void testFilteredResourcesInvalidFilter() throws Exception { String badQualifier = "invalid-qualifier"; checkError( "java/r/android", "r", badQualifier, "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/foo.xml'],", " resource_configuration_filters = ['" + badQualifier + "'])"); } @Test public void testFilteredResourcesInvalidResourceDir() throws Exception { String badQualifierDir = "values-invalid-qualifier"; checkError( "java/r/android", "r", badQualifierDir, "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/" + badQualifierDir + "/foo.xml'],", " resource_configuration_filters = ['en'])"); } /** Test that resources are not filtered in analysis under aapt2. */ @Test public void testFilteredResourcesFilteringAapt2() throws Exception { List<String> resources = ImmutableList.of("res/values/foo.xml", "res/values-en/foo.xml", "res/values-fr/foo.xml"); String dir = "java/r/android"; mockAndroidSdkWithAapt2(); useConfiguration("--android_sdk=//sdk:sdk"); ConfiguredTarget binary = scratchConfiguredTarget( dir, "r", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_configuration_filters = ['', 'en, es, '],", " aapt_version = 'aapt2',", " densities = ['hdpi, , ', 'xhdpi'],", " resource_files = ['" + Joiner.on("', '").join(resources) + "'])"); ValidatedAndroidResources directResources = getValidatedResources(binary, /* transitive= */ false); // Validate that the AndroidResourceProvider for this binary contains all values. assertThat(resourceContentsPaths(dir, directResources)).containsExactlyElementsIn(resources); // Validate that the input to resource processing contains all values. assertThat(resourceInputPaths(dir, directResources)).containsAtLeastElementsIn(resources); // Validate that the filters are correctly passed to the resource processing action // This includes trimming whitespace and ignoring empty filters. assertThat(resourceArguments(directResources)).contains("en,es"); assertThat(resourceArguments(directResources)).contains("hdpi,xhdpi"); } @Test public void testFilteredResourcesSimple() throws Exception { testDirectResourceFiltering( "en", /* unexpectedQualifiers= */ ImmutableList.of("fr"), /* expectedQualifiers= */ ImmutableList.of("en")); } @Test public void testFilteredResourcesNoopFilter() throws Exception { testDirectResourceFiltering( /* filters= */ "", /* unexpectedQualifiers= */ ImmutableList.<String>of(), /* expectedQualifiers= */ ImmutableList.of("en", "fr")); } @Test public void testFilteredResourcesMultipleFilters() throws Exception { testDirectResourceFiltering( "en,es", /* unexpectedQualifiers= */ ImmutableList.of("fr"), /* expectedQualifiers= */ ImmutableList.of("en", "es")); } @Test public void testFilteredResourcesMultipleFiltersWithWhitespace() throws Exception { testDirectResourceFiltering( " en , es ", /* unexpectedQualifiers= */ ImmutableList.of("fr"), /* expectedQualifiers= */ ImmutableList.of("en", "es")); } @Test public void testFilteredResourcesMultipleFilterStrings() throws Exception { testDirectResourceFiltering( "en', 'es", /* unexpectedQualifiers= */ ImmutableList.of("fr"), /* expectedQualifiers= */ ImmutableList.of("en", "es")); } @Test public void testFilteredResourcesLocaleWithoutRegion() throws Exception { testDirectResourceFiltering( "en", /* unexpectedQualifiers= */ ImmutableList.of("fr-rCA"), /* expectedQualifiers= */ ImmutableList.of("en-rCA", "en-rUS", "en")); } @Test public void testFilteredResourcesLocaleWithRegion() throws Exception { testDirectResourceFiltering( "en-rUS", /* unexpectedQualifiers= */ ImmutableList.of("en-rGB"), /* expectedQualifiers= */ ImmutableList.of("en-rUS", "en")); } @Test public void testFilteredResourcesOldAaptLocale() throws Exception { testDirectResourceFiltering( "en_US,fr_CA", /* unexpectedQualifiers= */ ImmutableList.of("en-rCA"), /* expectedQualifiers = */ ImmutableList.of("en-rUS", "fr-rCA")); } @Test public void testFilteredResourcesOldAaptLocaleOtherQualifiers() throws Exception { testDirectResourceFiltering( "mcc310-en_US-ldrtl,mcc311-mnc312-fr_CA", /* unexpectedQualifiers= */ ImmutableList.of("en-rCA", "mcc312", "mcc311-mnc311"), /* expectedQualifiers = */ ImmutableList.of("en-rUS", "fr-rCA", "mcc310", "mcc311-mnc312")); } @Test public void testFilteredResourcesSmallestScreenWidth() throws Exception { testDirectResourceFiltering( "sw600dp", /* unexpectedQualifiers= */ ImmutableList.of("sw700dp"), /* expectedQualifiers= */ ImmutableList.of("sw500dp", "sw600dp")); } @Test public void testFilteredResourcesScreenWidth() throws Exception { testDirectResourceFiltering( "w600dp", /* unexpectedQualifiers= */ ImmutableList.of("w700dp"), /* expectedQualifiers= */ ImmutableList.of("w500dp", "w600dp")); } @Test public void testFilteredResourcesScreenHeight() throws Exception { testDirectResourceFiltering( "h600dp", /* unexpectedQualifiers= */ ImmutableList.of("h700dp"), /* expectedQualifiers= */ ImmutableList.of("h500dp", "h600dp")); } @Test public void testFilteredResourcesScreenSize() throws Exception { testDirectResourceFiltering( "normal", /* unexpectedQualifiers= */ ImmutableList.of("large", "xlarge"), /* expectedQualifiers= */ ImmutableList.of("small", "normal")); } /** Tests that filtering on density is ignored to match aapt behavior. */ @Test public void testFilteredResourcesDensity() throws Exception { testDirectResourceFiltering( "hdpi", /* unexpectedQualifiers= */ ImmutableList.<String>of(), /* expectedQualifiers= */ ImmutableList.of("ldpi", "mdpi", "hdpi", "xhdpi", "xxhdpi")); } /** Tests that filtering on API version is ignored to match aapt behavior. */ @Test public void testFilteredResourcesApiVersion() throws Exception { testDirectResourceFiltering( "v4", /* unexpectedQualifiers= */ ImmutableList.<String>of(), /* expectedQualifiers= */ ImmutableList.of("v3", "v4", "v5")); } @Test public void testFilteredResourcesRegularQualifiers() throws Exception { // Include one value for each qualifier not tested above String filters = "mcc310-mnc004-ldrtl-long-round-port-car-night-notouch-keysexposed-nokeys-navexposed-nonav"; // In the qualifiers we expect to be removed, include one value that contradicts each qualifier // of the filter testDirectResourceFiltering( filters, /* unexpectedQualifiers= */ ImmutableList.of( "mcc309", "mnc03", "ldltr", "notlong", "notround", "land", "watch", "notnight", "finger", "keyshidden", "qwerty", "navhidden", "dpad"), /* expectedQualifiers= */ ImmutableList.of(filters)); } @Test public void testDensityFilteredResourcesSingleDensity() throws Exception { testDensityResourceFiltering( "hdpi", ImmutableList.of("ldpi", "mdpi", "xhdpi"), ImmutableList.of("hdpi")); } @Test public void testDensityFilteredResourcesSingleClosestDensity() throws Exception { testDensityResourceFiltering( "hdpi", ImmutableList.of("ldpi", "mdpi"), ImmutableList.of("xhdpi")); } @Test public void testDensityFilteredResourcesDifferingQualifiers() throws Exception { testDensityResourceFiltering( "hdpi", ImmutableList.of("en-xhdpi", "fr"), ImmutableList.of("en-hdpi", "fr-mdpi", "xhdpi")); } @Test public void testDensityFilteredResourcesMultipleDensities() throws Exception { testDensityResourceFiltering( "hdpi,ldpi,xhdpi", ImmutableList.of("mdpi", "xxhdpi"), ImmutableList.of("ldpi", "hdpi", "xhdpi")); } @Test public void testDensityFilteredResourcesDoubledDensity() throws Exception { testDensityResourceFiltering( "hdpi", ImmutableList.of("ldpi", "mdpi", "xhdpi"), ImmutableList.of("xxhdpi")); } @Test public void testDensityFilteredResourcesDifferentRatiosSmallerCloser() throws Exception { testDensityResourceFiltering("mdpi", ImmutableList.of("hdpi"), ImmutableList.of("ldpi")); } @Test public void testDensityFilteredResourcesDifferentRatiosLargerCloser() throws Exception { testDensityResourceFiltering("hdpi", ImmutableList.of("mdpi"), ImmutableList.of("xhdpi")); } @Test public void testDensityFilteredResourcesSameRatioPreferLarger() throws Exception { // xxhdpi is 480dpi and xxxhdpi is 640dpi. // The ratios between 360dpi and 480dpi and between 480dpi and 640dpi are both 3:4. testDensityResourceFiltering("xxhdpi", ImmutableList.of("360dpi"), ImmutableList.of("xxxhdpi")); } @Test public void testDensityFilteredResourcesOptionsSmallerThanDesired() throws Exception { testDensityResourceFiltering( "xxxhdpi", ImmutableList.of("xhdpi", "mdpi", "ldpi"), ImmutableList.of("xxhdpi")); } @Test public void testDensityFilteredResourcesOptionsLargerThanDesired() throws Exception { testDensityResourceFiltering( "ldpi", ImmutableList.of("xxxhdpi", "xxhdpi", "xhdpi"), ImmutableList.of("mdpi")); } @Test public void testDensityFilteredResourcesSpecialValues() throws Exception { testDensityResourceFiltering( "xxxhdpi", ImmutableList.of("anydpi", "nodpi"), ImmutableList.of("ldpi")); } @Test public void testDensityFilteredResourcesXml() throws Exception { testDirectResourceFiltering( /* resourceConfigurationFilters= */ "", "hdpi", ImmutableList.<String>of(), ImmutableList.of("ldpi", "mdpi", "hdpi", "xhdpi"), /* expectUnqualifiedResource= */ true, "drawable", "xml"); } @Test public void testDensityFilteredResourcesNotDrawable() throws Exception { testDirectResourceFiltering( /* resourceConfigurationFilters= */ "", "hdpi", ImmutableList.<String>of(), ImmutableList.of("ldpi", "mdpi", "hdpi", "xhdpi"), /* expectUnqualifiedResource= */ true, "layout", "png"); } @Test public void testQualifierAndDensityFilteredResources() throws Exception { testDirectResourceFiltering( "en,fr-mdpi", "hdpi,ldpi", ImmutableList.of("mdpi", "es-ldpi", "en-xxxhdpi", "fr-mdpi"), ImmutableList.of("ldpi", "hdpi", "en-xhdpi", "fr-hdpi"), /* expectUnqualifiedResource= */ false, "drawable", "png"); } private void testDensityResourceFiltering( String densities, List<String> unexpectedQualifiers, List<String> expectedQualifiers) throws Exception { testDirectResourceFiltering( /* resourceConfigurationFilters= */ "", densities, unexpectedQualifiers, expectedQualifiers, /* expectUnqualifiedResource= */ false, "drawable", "png"); } private void testDirectResourceFiltering( String filters, List<String> unexpectedQualifiers, ImmutableList<String> expectedQualifiers) throws Exception { testDirectResourceFiltering( filters, /* densities= */ "", unexpectedQualifiers, expectedQualifiers, /* expectUnqualifiedResource= */ true, "drawable", "png"); } private void testDirectResourceFiltering( String resourceConfigurationFilters, String densities, List<String> unexpectedQualifiers, List<String> expectedQualifiers, boolean expectUnqualifiedResource, String folderType, String suffix) throws Exception { List<String> unexpectedResources = new ArrayList<>(); for (String qualifier : unexpectedQualifiers) { unexpectedResources.add("res/" + folderType + "-" + qualifier + "/foo." + suffix); } List<String> expectedResources = new ArrayList<>(); for (String qualifier : expectedQualifiers) { expectedResources.add("res/" + folderType + "-" + qualifier + "/foo." + suffix); } String unqualifiedResource = "res/" + folderType + "/foo." + suffix; if (expectUnqualifiedResource) { expectedResources.add(unqualifiedResource); } else { unexpectedResources.add(unqualifiedResource); } // Default resources should never be filtered expectedResources.add("res/values/foo.xml"); Iterable<String> allResources = Iterables.concat(unexpectedResources, expectedResources); String dir = "java/r/android"; ConfiguredTarget binary = scratchConfiguredTarget( dir, "r", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_configuration_filters = ['" + resourceConfigurationFilters + "'],", " densities = ['" + densities + "'],", " resource_files = ['" + Joiner.on("', '").join(allResources) + "'])"); // No prefix should be added because of resource filtering. assertThat( getConfiguration(binary) .getFragment(AndroidConfiguration.class) .getOutputDirectoryName()) .isNull(); ValidatedAndroidResources directResources = getValidatedResources(binary, /* transitive= */ false); // Validate that the AndroidResourceProvider for this binary contains only the filtered values. assertThat(resourceContentsPaths(dir, directResources)) .containsExactlyElementsIn(expectedResources); // Validate that the input to resource processing contains only the filtered values. assertThat(resourceInputPaths(dir, directResources)) .containsAtLeastElementsIn(expectedResources); assertThat(resourceInputPaths(dir, directResources)).containsNoneIn(unexpectedResources); // Only transitive resources need to be ignored when filtered,, and there aren't any here. assertThat(resourceArguments(directResources)).doesNotContain("--prefilteredResources"); // Validate resource filters are passed to execution List<String> args = resourceArguments(directResources); // Remove whitespace and quotes from the resourceConfigurationFilters attribute value to get the // value we expect to pass to the resource processing action String fixedResourceConfigFilters = resourceConfigurationFilters.replaceAll("[ ']", ""); if (resourceConfigurationFilters.isEmpty()) { assertThat(args).containsNoneOf("--resourceConfigs", fixedResourceConfigFilters); } else { assertThat(args).containsAtLeast("--resourceConfigs", fixedResourceConfigFilters).inOrder(); } if (densities.isEmpty()) { assertThat(args).containsNoneOf("--densities", densities); } else { // We still expect densities only for the purposes of adding information to manifests assertThat(args).containsAtLeast("--densities", densities).inOrder(); } } @Test public void testFilteredTransitiveResources() throws Exception { String matchingResource = "res/values-en/foo.xml"; String unqualifiedResource = "res/values/foo.xml"; String notMatchingResource = "res/values-fr/foo.xml"; String dir = "java/r/android"; ConfiguredTarget binary = scratchConfiguredTarget( dir, "r", "android_library(name = 'lib',", " manifest = 'AndroidManifest.xml',", " resource_files = [", " '" + matchingResource + "',", " '" + unqualifiedResource + "',", " '" + notMatchingResource + "'", " ])", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " deps = [':lib'],", " resource_configuration_filters = ['en'])"); ValidatedAndroidResources directResources = getValidatedResources(binary, /* transitive= */ false); ValidatedAndroidResources transitiveResources = getValidatedResources(binary, /* transitive= */ true); assertThat(resourceContentsPaths(dir, directResources)).isEmpty(); assertThat(resourceContentsPaths(dir, transitiveResources)) .containsExactly(matchingResource, unqualifiedResource); assertThat(resourceInputPaths(dir, directResources)) .containsExactly(matchingResource, unqualifiedResource); String[] flagValues = flagValue("--prefilteredResources", resourceArguments(directResources)).split(","); assertThat(flagValues).asList().containsExactly("values-fr/foo.xml"); } @Test public void testFilteredTransitiveResourcesDifferentDensities() throws Exception { String dir = "java/r/android"; ConfiguredTarget binary = scratchConfiguredTarget( dir, "bin", "android_binary(name = 'bin',", " manifest = 'AndroidManifest.xml',", " resource_configuration_filters = ['en'],", " densities = ['hdpi'],", " deps = [':invalid', ':best', ':other', ':multiple'],", ")", "android_library(name = 'invalid',", " manifest = 'AndroidManifest.xml',", " resource_files = ['invalid/res/drawable-fr-hdpi/foo.png'],", ")", "android_library(name = 'best',", " manifest = 'AndroidManifest.xml',", " resource_files = ['best/res/drawable-en-hdpi/foo.png'],", ")", "android_library(name = 'other',", " manifest = 'AndroidManifest.xml',", " resource_files = ['other/res/drawable-en-mdpi/foo.png'],", ")", "android_library(name = 'multiple',", " manifest = 'AndroidManifest.xml',", " resource_files = [", " 'multiple/res/drawable-en-hdpi/foo.png',", " 'multiple/res/drawable-en-mdpi/foo.png'],", ")"); ValidatedAndroidResources directResources = getValidatedResources(binary, /* transitive= */ false); // All of the resources are transitive assertThat(resourceContentsPaths(dir, directResources)).isEmpty(); // Only the best matches should be used. This includes multiple best matches, even given a // single density filter, since they are each from a different dependency. This duplication // would be resolved during merging. assertThat(resourceInputPaths(dir, directResources)) .containsExactly( "best/res/drawable-en-hdpi/foo.png", "multiple/res/drawable-en-hdpi/foo.png"); } @Test public void testFilteredResourcesAllFilteredOut() throws Exception { String dir = "java/r/android"; final String keptBaseDir = "partly_filtered_dir"; String removedLibraryDir = "fully_filtered_library_dir"; String removedBinaryDir = "fully_filtered_binary_dir"; ConfiguredTarget binary = scratchConfiguredTarget( dir, "bin", "android_library(name = 'not_fully_filtered_lib',", " manifest = 'AndroidManifest.xml',", " resource_files = [", // Some of the resources in this directory are kept: " '" + keptBaseDir + "/values-es/foo.xml',", " '" + keptBaseDir + "/values-fr/foo.xml',", " '" + keptBaseDir + "/values-en/foo.xml',", " ])", "android_library(name = 'fully_filtered_lib',", " manifest = 'AndroidManifest.xml',", " resource_files = [", // All of the resources in this directory are filtered out: " '" + removedLibraryDir + "/values-es/foo.xml',", " '" + removedLibraryDir + "/values-fr/foo.xml',", " ])", "android_binary(name = 'bin',", " manifest = 'AndroidManifest.xml',", " resource_configuration_filters = ['en'],", " resource_files = [", // All of the resources in this directory are filtered out: " '" + removedBinaryDir + "/values-es/foo.xml',", " '" + removedBinaryDir + "/values-fr/foo.xml',", " ],", " deps = [", " ':fully_filtered_lib',", " ':not_fully_filtered_lib',", " ])"); List<String> resourceProcessingArgs = getGeneratingSpawnActionArgs(getValidatedResources(binary).getRTxt()); assertThat( Iterables.filter( resourceProcessingArgs, new Predicate<String>() { @Override public boolean apply(String input) { return input.contains(keptBaseDir); } })) .isNotEmpty(); for (String arg : resourceProcessingArgs) { assertThat(arg).doesNotContain(removedLibraryDir); assertThat(arg).doesNotContain(removedBinaryDir); } } @Test public void testFilterResourcesPseudolocalesPropagated() throws Exception { String dir = "java/r/android"; ConfiguredTarget binary = scratchConfiguredTarget( dir, "bin", "android_binary(name = 'bin',", " resource_files = glob(['res/**']),", " resource_configuration_filters = ['en', 'en-rXA', 'ar-rXB'],", " manifest = 'AndroidManifest.xml')"); List<String> resourceProcessingArgs = getGeneratingSpawnActionArgs(getValidatedResources(binary).getRTxt()); assertThat(resourceProcessingArgs).containsAtLeast("--resourceConfigs", "ar-rXB,en,en-rXA"); } @Test public void testThrowOnResourceConflictFlagGetsPropagated() throws Exception { scratch.file( "java/r/android/BUILD", "android_binary(", " name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/foo.xml'],", ")"); useConfiguration("--experimental_android_throw_on_resource_conflict"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); List<String> resourceProcessingArgs = resourceArguments(getValidatedResources(binary)); assertThat(resourceProcessingArgs).contains("--throwOnResourceConflict"); } /** * Gets the paths of matching artifacts contained within a resource container * * @param dir the directory to look for artifacts in * @param resource the container that contains eligible artifacts * @return the paths to all artifacts from the input that are contained within the given * directory, relative to that directory. */ private List<String> resourceContentsPaths(String dir, ValidatedAndroidResources resource) { return pathsToArtifacts(dir, resource.getArtifacts()); } /** * Gets the paths of matching artifacts that are used as input to resource processing * * @param dir the directory to look for artifacts in * @param resource the output from the resource processing that uses these artifacts as inputs * @return the paths to all artifacts used as inputs to resource processing that are contained * within the given directory, relative to that directory. */ private List<String> resourceInputPaths(String dir, ValidatedAndroidResources resource) { return pathsToArtifacts(dir, resourceGeneratingAction(resource).getInputs()); } /** * Gets the paths of matching artifacts from an iterable * * @param dir the directory to look for artifacts in * @param artifacts all available artifacts * @return the paths to all artifacts from the input that are contained within the given * directory, relative to that directory. */ private List<String> pathsToArtifacts(String dir, Iterable<Artifact> artifacts) { List<String> paths = new ArrayList<>(); Path containingDir = rootDirectory; for (String part : dir.split("/")) { containingDir = containingDir.getChild(part); } for (Artifact a : artifacts) { if (a.getPath().startsWith(containingDir)) { paths.add(a.getPath().relativeTo(containingDir).toString()); } } return paths; } @Test public void testInheritedRNotInRuntimeJars() throws Exception { String dir = "java/r/android/"; scratch.file( dir + "BUILD", "android_library(name = 'sublib',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res3/**']),", " srcs =['sublib.java'],", " )", "android_library(name = 'lib',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res2/**']),", " deps = [':sublib'],", " srcs =['lib.java'],", " )", "android_binary(name = 'bin',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " deps = [':lib'],", " srcs =['bin.java'],", " )"); Action deployJarAction = getGeneratingAction( getFileConfiguredTarget("//java/r/android:bin_deploy.jar").getArtifact()); List<String> inputs = ActionsTestUtil.baseArtifactNames(deployJarAction.getInputs()); assertThat(inputs) .containsAtLeast( "libsublib.jar_desugared.jar", "liblib.jar_desugared.jar", "libbin.jar_desugared.jar", "bin_resources.jar_desugared.jar"); assertThat(inputs) .containsNoneOf("lib_resources.jar_desugared.jar", "sublib_resources.jar_desugared.jar"); } @Test public void testLocalResourcesUseRClassGenerator() throws Exception { scratch.file("java/r/android/BUILD", "android_library(name = 'lib',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res2/**']),", " )", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " deps = [':lib'],", " )"); scratch.file("java/r/android/res2/values/strings.xml", "<resources><string name = 'lib_string'>Libs!</string></resources>"); scratch.file("java/r/android/res/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); Artifact jar = getResourceClassJar(getConfiguredTargetAndData("//java/r/android:r")); assertThat(getGeneratingAction(jar).getMnemonic()).isEqualTo("RClassGenerator"); assertThat(getGeneratingSpawnActionArgs(jar)) .containsAtLeast("--primaryRTxt", "--primaryManifest", "--library", "--classJarOutput"); } @Test public void testLocalResourcesUseRClassGeneratorNoLibraries() throws Exception { scratch.file("java/r/android/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " )"); scratch.file("java/r/android/res/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); Artifact jar = getResourceClassJar(getConfiguredTargetAndData("//java/r/android:r")); assertThat(getGeneratingAction(jar).getMnemonic()).isEqualTo("RClassGenerator"); List<String> args = getGeneratingSpawnActionArgs(jar); assertThat(args).containsAtLeast("--primaryRTxt", "--primaryManifest", "--classJarOutput"); assertThat(args).doesNotContain("--libraries"); } @Test public void testUseRClassGeneratorCustomPackage() throws Exception { scratch.file("java/r/android/BUILD", "android_library(name = 'lib',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res2/**']),", " custom_package = 'com.lib.custom',", " )", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " custom_package = 'com.binary.custom',", " deps = [':lib'],", " )"); scratch.file("java/r/android/res2/values/strings.xml", "<resources><string name = 'lib_string'>Libs!</string></resources>"); scratch.file("java/r/android/res/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); ConfiguredTargetAndData binary = getConfiguredTargetAndData("//java/r/android:r"); Artifact jar = getResourceClassJar(binary); assertThat(getGeneratingAction(jar).getMnemonic()).isEqualTo("RClassGenerator"); List<String> args = getGeneratingSpawnActionArgs(jar); assertThat(args) .containsAtLeast( "--primaryRTxt", "--primaryManifest", "--library", "--classJarOutput", "--packageForR", "com.binary.custom"); } @Test public void testUseRClassGeneratorMultipleDeps() throws Exception { scratch.file( "java/r/android/BUILD", "android_library(name = 'lib1',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res1/**']),", " )", "android_library(name = 'lib2',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res2/**']),", " )", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " deps = [':lib1', ':lib2'],", " )"); ConfiguredTargetAndData binary = getConfiguredTargetAndData("//java/r/android:r"); Artifact jar = getResourceClassJar(binary); assertThat(getGeneratingAction(jar).getMnemonic()).isEqualTo("RClassGenerator"); List<String> args = getGeneratingSpawnActionArgs(jar); AndroidResourcesInfo resourcesInfo = binary.getConfiguredTarget().get(AndroidResourcesInfo.PROVIDER); assertThat(resourcesInfo.getTransitiveAndroidResources()).hasSize(2); ValidatedAndroidResources firstDep = resourcesInfo.getTransitiveAndroidResources().toList().get(0); ValidatedAndroidResources secondDep = resourcesInfo.getTransitiveAndroidResources().toList().get(1); assertThat(args) .containsAtLeast( "--primaryRTxt", "--primaryManifest", "--library", firstDep.getRTxt().getExecPathString() + "," + firstDep.getManifest().getExecPathString(), "--library", secondDep.getRTxt().getExecPathString() + "," + secondDep.getManifest().getExecPathString(), "--classJarOutput") .inOrder(); } @Test public void testNoCrunchBinaryOnly() throws Exception { scratch.file("java/r/android/BUILD", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/drawable-hdpi-v4/foo.png',", " 'res/drawable-hdpi-v4/bar.9.png'],", " crunch_png = 0,", " )"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(binary)); assertThat(args).contains("--useAaptCruncher=no"); } @Test public void testDoCrunch() throws Exception { scratch.file("java/r/android/BUILD", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/drawable-hdpi-v4/foo.png',", " 'res/drawable-hdpi-v4/bar.9.png'],", " crunch_png = 1,", " )"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(binary)); assertThat(args).doesNotContain("--useAaptCruncher=no"); } @Test public void testDoCrunchDefault() throws Exception { scratch.file("java/r/android/BUILD", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/drawable-hdpi-v4/foo.png',", " 'res/drawable-hdpi-v4/bar.9.png'],", " )"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(binary)); assertThat(args).doesNotContain("--useAaptCruncher=no"); } @Test public void testNoCrunchWithAndroidLibraryNoBinaryResources() throws Exception { scratch.file("java/r/android/BUILD", "android_library(name = 'resources',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/strings.xml',", " 'res/drawable-hdpi-v4/foo.png',", " 'res/drawable-hdpi-v4/bar.9.png'],", " )", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " deps = [':resources'],", " crunch_png = 0,", " )"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(binary)); assertThat(args).contains("--useAaptCruncher=no"); } @Test public void testNoCrunchWithMultidexNative() throws Exception { scratch.file("java/r/android/BUILD", "android_library(name = 'resources',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/strings.xml',", " 'res/drawable-hdpi-v4/foo.png',", " 'res/drawable-hdpi-v4/bar.9.png'],", " )", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " deps = [':resources'],", " multidex = 'native',", " crunch_png = 0,", " )"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(binary)); assertThat(args).contains("--useAaptCruncher=no"); } @Test public void testZipaligned() throws Exception { ConfiguredTarget binary = getConfiguredTarget("//java/android:app"); Artifact a = ActionsTestUtil.getFirstArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)), "zipaligned_app.apk"); SpawnAction action = getGeneratingSpawnAction(a); assertThat(action.getMnemonic()).isEqualTo("AndroidZipAlign"); List<String> arguments = getGeneratingSpawnActionArgs(a); assertThat(arguments).contains("-p"); assertThat(arguments).contains("4"); Artifact zipAlignTool = getFirstArtifactEndingWith(action.getInputs(), "/zipalign"); assertThat(arguments).contains(zipAlignTool.getExecPathString()); Artifact unsignedApk = getFirstArtifactEndingWith(action.getInputs(), "/app_unsigned.apk"); assertThat(arguments).contains(unsignedApk.getExecPathString()); Artifact zipalignedApk = getFirstArtifactEndingWith(action.getOutputs(), "/zipaligned_app.apk"); assertThat(arguments).contains(zipalignedApk.getExecPathString()); } @Test public void testDeployInfo() throws Exception { ConfiguredTarget binary = getConfiguredTarget("//java/android:app"); NestedSet<Artifact> outputGroup = getOutputGroup(binary, "android_deploy_info"); Artifact deployInfoArtifact = ActionsTestUtil .getFirstArtifactEndingWith(outputGroup, "/deploy_info.deployinfo.pb"); assertThat(deployInfoArtifact).isNotNull(); AndroidDeployInfo deployInfo = getAndroidDeployInfo(deployInfoArtifact); assertThat(deployInfo).isNotNull(); assertThat(deployInfo.getMergedManifest().getExecRootPath()).endsWith( "/AndroidManifest.xml"); assertThat(deployInfo.getAdditionalMergedManifestsList()).isEmpty(); assertThat(deployInfo.getApksToDeploy(0).getExecRootPath()).endsWith("/app.apk"); } /** * Internal helper method: checks that dex sharding input and output is correct for * different combinations of multidex mode and build with and without proguard. */ private void internalTestDexShardStructure(MultidexMode multidexMode, boolean proguard, String nonProguardSuffix) throws Exception { ConfiguredTarget target = getConfiguredTarget("//java/a:a"); assertNoEvents(); Action shardAction = getGeneratingAction(getBinArtifact("_dx/a/shard1.jar", target)); // Verify command line arguments List<String> arguments = ((SpawnAction) shardAction).getRemainingArguments(); List<String> expectedArguments = new ArrayList<>(); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(target)); Artifact shard1 = getFirstArtifactEndingWith(artifacts, "shard1.jar"); Artifact shard2 = getFirstArtifactEndingWith(artifacts, "shard2.jar"); Artifact resourceJar = getFirstArtifactEndingWith(artifacts, "/java_resources.jar"); expectedArguments.add("--output_jar"); expectedArguments.add(shard1.getExecPathString()); expectedArguments.add("--output_jar"); expectedArguments.add(shard2.getExecPathString()); expectedArguments.add("--output_resources"); expectedArguments.add(resourceJar.getExecPathString()); if (multidexMode == MultidexMode.LEGACY) { Artifact mainDexList = getFirstArtifactEndingWith(artifacts, "main_dex_list.txt"); expectedArguments.add("--main_dex_filter"); expectedArguments.add(mainDexList.getExecPathString()); } if (!proguard) { expectedArguments.add("--input_jar"); expectedArguments.add( getFirstArtifactEndingWith(artifacts, "a_resources.jar" + nonProguardSuffix) .getExecPathString()); } Artifact inputJar; if (proguard) { inputJar = getFirstArtifactEndingWith(artifacts, "a_proguard.jar"); } else { inputJar = getFirstArtifactEndingWith(artifacts, "liba.jar" + nonProguardSuffix); } expectedArguments.add("--input_jar"); expectedArguments.add(inputJar.getExecPathString()); assertThat(arguments).containsExactlyElementsIn(expectedArguments).inOrder(); // Verify input and output artifacts List<String> shardOutputs = ActionsTestUtil.baseArtifactNames(shardAction.getOutputs()); List<String> shardInputs = ActionsTestUtil.baseArtifactNames(shardAction.getInputs()); assertThat(shardOutputs) .containsExactly("shard1.jar", "shard2.jar", "java_resources.jar"); if (multidexMode == MultidexMode.LEGACY) { assertThat(shardInputs).contains("main_dex_list.txt"); } else { assertThat(shardInputs).doesNotContain("main_dex_list.txt"); } if (proguard) { assertThat(shardInputs).contains("a_proguard.jar"); assertThat(shardInputs).doesNotContain("liba.jar" + nonProguardSuffix); } else { assertThat(shardInputs).contains("liba.jar" + nonProguardSuffix); assertThat(shardInputs).doesNotContain("a_proguard.jar"); } assertThat(shardInputs).doesNotContain("a_deploy.jar"); // Verify that dex compilation is followed by the correct merge operation Action apkAction = getGeneratingAction(getFirstArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(target)), "compressed_a_unsigned.apk")); Action mergeAction = getGeneratingAction(getFirstArtifactEndingWith( apkAction.getInputs(), "classes.dex.zip")); Iterable<Artifact> dexShards = Iterables.filter( mergeAction.getInputs(), ActionsTestUtil.getArtifactSuffixMatcher(".dex.zip")); assertThat(ActionsTestUtil.baseArtifactNames(dexShards)) .containsExactly("shard1.dex.zip", "shard2.dex.zip"); } @Test public void testDexShardingNeedsMultidex() throws Exception { scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " manifest='AndroidManifest.xml')"); reporter.removeHandler(failFastHandler); getConfiguredTarget("//java/a:a"); assertContainsEvent(".dex sharding is only available in multidex mode"); } @Test public void testDexShardingDoesNotWorkWithManualMultidex() throws Exception { scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='manual_main_dex',", " main_dex_list='main_dex_list.txt',", " manifest='AndroidManifest.xml')"); reporter.removeHandler(failFastHandler); getConfiguredTarget("//java/a:a"); assertContainsEvent(".dex sharding is not available in manual multidex mode"); } @Test public void testDexShardingLegacyStructure() throws Exception { useConfiguration("--noincremental_dexing"); scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='legacy',", " manifest='AndroidManifest.xml')"); internalTestDexShardStructure(MultidexMode.LEGACY, false, "_desugared.jar"); } @Test public void testDexShardingNativeStructure_withNoDesugaring() throws Exception { useConfiguration("--noexperimental_desugar_for_android", "--noincremental_dexing"); scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='native',", " manifest='AndroidManifest.xml')"); internalTestDexShardStructure(MultidexMode.NATIVE, false, ""); } @Test public void testDexShardingNativeStructure() throws Exception { useConfiguration("--noincremental_dexing"); scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='native',", " manifest='AndroidManifest.xml')"); internalTestDexShardStructure(MultidexMode.NATIVE, false, "_desugared.jar"); } @Test public void testDexShardingLegacyAndProguardStructure_withNoDesugaring() throws Exception { useConfiguration("--noexperimental_desugar_for_android"); scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='legacy',", " manifest='AndroidManifest.xml',", " proguard_specs=['proguard.cfg'])"); internalTestDexShardStructure(MultidexMode.LEGACY, true, ""); } @Test public void testDexShardingLegacyAndProguardStructure() throws Exception { scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='legacy',", " manifest='AndroidManifest.xml',", " proguard_specs=['proguard.cfg'])"); internalTestDexShardStructure(MultidexMode.LEGACY, true, "_desugared.jar"); } @Test public void testDexShardingNativeAndProguardStructure() throws Exception { scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='native',", " manifest='AndroidManifest.xml',", " proguard_specs=['proguard.cfg'])"); internalTestDexShardStructure(MultidexMode.NATIVE, true, ""); } @Test public void testIncrementalApkAndProguardBuildStructure() throws Exception { scratch.file("java/a/BUILD", "android_binary(", " name='a',", " srcs=['A.java'],", " dex_shards=2,", " multidex='native',", " manifest='AndroidManifest.xml',", " proguard_specs=['proguard.cfg'])"); ConfiguredTarget target = getConfiguredTarget("//java/a:a"); Action shardAction = getGeneratingAction(getBinArtifact("_dx/a/shard1.jar", target)); List<String> shardOutputs = ActionsTestUtil.baseArtifactNames(shardAction.getOutputs()); assertThat(shardOutputs).contains("java_resources.jar"); assertThat(shardOutputs).doesNotContain("a_deploy.jar"); } @Test public void testManualMainDexBuildStructure() throws Exception { checkError("java/foo", "maindex_nomultidex", "Both \"main_dex_list\" and \"multidex='manual_main_dex'\" must be specified", "android_binary(", " name = 'maindex_nomultidex',", " srcs = ['a.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'manual_main_dex')"); } @Test public void testMainDexListLegacyMultidex() throws Exception { checkError("java/foo", "maindex_nomultidex", "Both \"main_dex_list\" and \"multidex='manual_main_dex'\" must be specified", "android_binary(", " name = 'maindex_nomultidex',", " srcs = ['a.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'legacy',", " main_dex_list = 'main_dex_list.txt')"); } @Test public void testMainDexListNativeMultidex() throws Exception { checkError("java/foo", "maindex_nomultidex", "Both \"main_dex_list\" and \"multidex='manual_main_dex'\" must be specified", "android_binary(", " name = 'maindex_nomultidex',", " srcs = ['a.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'native',", " main_dex_list = 'main_dex_list.txt')"); } @Test public void testMainDexListNoMultidex() throws Exception { checkError("java/foo", "maindex_nomultidex", "Both \"main_dex_list\" and \"multidex='manual_main_dex'\" must be specified", "android_binary(", " name = 'maindex_nomultidex',", " srcs = ['a.java'],", " manifest = 'AndroidManifest.xml',", " main_dex_list = 'main_dex_list.txt')"); } @Test public void testMainDexListWithAndroidSdk() throws Exception { scratch.file( "sdk/BUILD", "android_sdk(", " name = 'sdk',", " aapt = 'aapt',", " adb = 'adb',", " aidl = 'aidl',", " android_jar = 'android.jar',", " apksigner = 'apksigner',", " dx = 'dx',", " framework_aidl = 'framework_aidl',", " main_dex_classes = 'main_dex_classes',", " main_dex_list_creator = 'main_dex_list_creator',", " proguard = 'proguard',", " shrinked_android_jar = 'shrinked_android_jar',", " zipalign = 'zipalign',", " tags = ['__ANDROID_RULES_MIGRATION__'])"); scratch.file("java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'legacy',", " main_dex_list_opts = ['--hello', '--world'])"); useConfiguration("--android_sdk=//sdk:sdk"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); Artifact mainDexList = ActionsTestUtil.getFirstArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(a)), "main_dex_list.txt"); List<String> args = getGeneratingSpawnActionArgs(mainDexList); assertThat(args).containsAtLeast("--hello", "--world"); } @Test public void testMainDexAaptGenerationSupported() throws Exception { useConfiguration("--android_sdk=//sdk:sdk", "--noincremental_dexing"); scratch.file( "sdk/BUILD", "android_sdk(", " name = 'sdk',", " build_tools_version = '24.0.0',", " aapt = 'aapt',", " adb = 'adb',", " aidl = 'aidl',", " android_jar = 'android.jar',", " apksigner = 'apksigner',", " dx = 'dx',", " framework_aidl = 'framework_aidl',", " main_dex_classes = 'main_dex_classes',", " main_dex_list_creator = 'main_dex_list_creator',", " proguard = 'proguard',", " shrinked_android_jar = 'shrinked_android_jar',", " zipalign = 'zipalign',", " tags = ['__ANDROID_RULES_MIGRATION__'])"); scratch.file("java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'legacy')"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); Artifact intermediateJar = artifactByPath(ImmutableList.of(getCompressedUnsignedApk(a)), ".apk", ".dex.zip", ".dex.zip", "main_dex_list.txt", "_intermediate.jar"); List<String> args = getGeneratingSpawnActionArgs(intermediateJar); assertContainsSublist( args, ImmutableList.of( "-include", targetConfig.getBinFragment() + "/java/a/proguard/a/main_dex_a_proguard.cfg")); } @Test public void testMainDexGenerationWithoutProguardMap() throws Exception { useConfiguration("--noincremental_dexing"); scratchConfiguredTarget("java/foo", "abin", "android_binary(", " name = 'abin',", " srcs = ['a.java'],", " proguard_specs = [],", " manifest = 'AndroidManifest.xml',", " multidex = 'legacy',)"); ConfiguredTarget a = getConfiguredTarget("//java/foo:abin"); Artifact intermediateJar = artifactByPath(ImmutableList.of(getCompressedUnsignedApk(a)), ".apk", ".dex.zip", ".dex.zip", "main_dex_list.txt", "_intermediate.jar"); List<String> args = getGeneratingSpawnActionArgs(intermediateJar); MoreAsserts.assertDoesNotContainSublist( args, "-previousobfuscationmap"); } // regression test for b/14288948 @Test public void testEmptyListAsProguardSpec() throws Exception { scratch.file( "java/foo/BUILD", "android_binary(", " name = 'abin',", " srcs = ['a.java'],", " proguard_specs = [],", " manifest = 'AndroidManifest.xml')"); Rule rule = getTarget("//java/foo:abin").getAssociatedRule(); assertNoEvents(); ImmutableList<String> implicitOutputFilenames = rule.getOutputFiles().stream().map(FileTarget::getName).collect(toImmutableList()); assertThat(implicitOutputFilenames).doesNotContain("abin_proguard.jar"); } @Test public void testConfigurableProguardSpecsEmptyList() throws Exception { scratch.file( "java/foo/BUILD", "android_binary(", " name = 'abin',", " srcs = ['a.java'],", " proguard_specs = select({", " '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [],", " }),", " manifest = 'AndroidManifest.xml')"); Rule rule = getTarget("//java/foo:abin").getAssociatedRule(); assertNoEvents(); ImmutableList<String> implicitOutputFilenames = rule.getOutputFiles().stream().map(FileTarget::getName).collect(toImmutableList()); assertThat(implicitOutputFilenames).contains("abin_proguard.jar"); } @Test public void testConfigurableProguardSpecsEmptyListWithMapping() throws Exception { scratchConfiguredTarget("java/foo", "abin", "android_binary(", " name = 'abin',", " srcs = ['a.java'],", " proguard_specs = select({", " '" + BuildType.Selector.DEFAULT_CONDITION_KEY + "': [],", " }),", " proguard_generate_mapping = 1,", " manifest = 'AndroidManifest.xml')"); assertNoEvents(); } @Test public void testResourcesWithConfigurationQualifier_LocalResources() throws Exception { scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = glob(['res/**']),", " )"); scratch.file("java/android/resources/res/values-en/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); scratch.file("java/android/resources/res/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); ConfiguredTarget resource = getConfiguredTarget("//java/android/resources:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(resource)); assertPrimaryResourceDirs(ImmutableList.of("java/android/resources/res"), args); } @Test public void testResourcesInOtherPackage_exported_LocalResources() throws Exception { scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['//java/resources/other:res/values/strings.xml'],", " )"); scratch.file("java/resources/other/BUILD", "exports_files(['res/values/strings.xml'])"); ConfiguredTarget resource = getConfiguredTarget("//java/android/resources:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(resource)); assertPrimaryResourceDirs(ImmutableList.of("java/resources/other/res"), args); assertNoEvents(); } @Test public void testResourcesInOtherPackage_filegroup_LocalResources() throws Exception { scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['//java/other/resources:fg'],", " )"); scratch.file("java/other/resources/BUILD", "filegroup(name = 'fg',", " srcs = ['res/values/strings.xml'],", ")"); ConfiguredTarget resource = getConfiguredTarget("//java/android/resources:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(resource)); assertPrimaryResourceDirs(ImmutableList.of("java/other/resources/res"), args); assertNoEvents(); } @Test public void testResourcesInOtherPackage_filegroupWithExternalSources_LocalResources() throws Exception { scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = [':fg'],", " )", "filegroup(name = 'fg',", " srcs = ['//java/other/resources:res/values/strings.xml'])"); scratch.file("java/other/resources/BUILD", "exports_files(['res/values/strings.xml'])"); ConfiguredTarget resource = getConfiguredTarget("//java/android/resources:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(resource)); assertPrimaryResourceDirs(ImmutableList.of("java/other/resources/res"), args); assertNoEvents(); } @Test public void testMultipleDependentResourceDirectories_LocalResources() throws Exception { scratch.file("java/android/resources/d1/BUILD", "android_library(name = 'd1',", " manifest = 'AndroidManifest.xml',", " resource_files = ['d1-res/values/strings.xml'],", " )"); scratch.file("java/android/resources/d2/BUILD", "android_library(name = 'd2',", " manifest = 'AndroidManifest.xml',", " resource_files = ['d2-res/values/strings.xml'],", " )"); scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['bin-res/values/strings.xml'],", " deps = [", " '//java/android/resources/d1:d1','//java/android/resources/d2:d2'", " ])"); ConfiguredTarget resource = getConfiguredTarget("//java/android/resources:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(resource)); assertPrimaryResourceDirs(ImmutableList.of("java/android/resources/bin-res"), args); assertThat(getDirectDependentResourceDirs(args)) .containsAtLeast("java/android/resources/d1/d1-res", "java/android/resources/d2/d2-res"); assertNoEvents(); } // Regression test for b/11924769 @Test public void testResourcesInOtherPackage_doubleFilegroup_LocalResources() throws Exception { scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = [':fg'],", " )", "filegroup(name = 'fg',", " srcs = ['//java/other/resources:fg'])"); scratch.file("java/other/resources/BUILD", "filegroup(name = 'fg',", " srcs = ['res/values/strings.xml'],", ")"); ConfiguredTarget resource = getConfiguredTarget("//java/android/resources:r"); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(resource)); assertPrimaryResourceDirs(ImmutableList.of("java/other/resources/res"), args); assertNoEvents(); } @Test public void testManifestMissingFails_LocalResources() throws Exception { checkError("java/android/resources", "r", "manifest attribute of android_library rule //java/android/resources:r: manifest is " + "required when resource_files or assets are defined.", "filegroup(name = 'b')", "android_library(name = 'r',", " resource_files = [':b'],", " )"); } @Test public void testResourcesDoesNotMatchDirectoryLayout_BadFile_LocalResources() throws Exception { checkError("java/android/resources", "r", "'java/android/resources/res/somefile.xml' is not in the expected resource directory " + "structure of <resource directory>/{" + Joiner.on(',').join(AndroidResources.RESOURCE_DIRECTORY_TYPES) + "}", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/somefile.xml', 'r/t/f/m/raw/fold']", " )"); } @Test public void testResourcesDoesNotMatchDirectoryLayout_BadDirectory_LocalResources() throws Exception { checkError("java/android/resources", "r", "'java/android/resources/res/other/somefile.xml' is not in the expected resource directory " + "structure of <resource directory>/{" + Joiner.on(',').join(AndroidResources.RESOURCE_DIRECTORY_TYPES) + "}", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/other/somefile.xml', 'r/t/f/m/raw/fold']", " )"); } @Test public void testResourcesNotUnderCommonDirectoryFails_LocalResources() throws Exception { checkError("java/android/resources", "r", "'java/android/resources/r/t/f/m/raw/fold' (generated by '//java/android/resources:r/t/f/m/" + "raw/fold') is not in the same directory 'res' " + "(derived from java/android/resources/res/raw/speed). " + "All resources must share a common directory", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/raw/speed', 'r/t/f/m/raw/fold']", " )"); } @Test public void testAssetsAndNoAssetsDirFails_LocalResources() throws Exception { scratch.file("java/android/resources/assets/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); checkError("java/android/resources", "r", "'assets' and 'assets_dir' should be either both empty or both non-empty", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " assets = glob(['assets/**']),", " )"); } @Test public void testAssetsDirAndNoAssetsFails_LocalResources() throws Exception { checkError("java/cpp/android", "r", "'assets' and 'assets_dir' should be either both empty or both non-empty", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " assets_dir = 'assets',", " )"); } @Test public void testAssetsNotUnderAssetsDirFails_LocalResources() throws Exception { checkError("java/android/resources", "r", "'java/android/resources/r/t/f/m' (generated by '//java/android/resources:r/t/f/m') " + "is not beneath 'assets'", "android_binary(name = 'r',", " manifest = 'AndroidManifest.xml',", " assets_dir = 'assets',", " assets = ['assets/valuable', 'r/t/f/m']", " )"); } @Test public void testFileLocation_LocalResources() throws Exception { scratch.file("java/android/resources/BUILD", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/strings.xml'],", " )"); ConfiguredTarget r = getConfiguredTarget("//java/android/resources:r"); assertThat(getFirstArtifactEndingWith(getFilesToBuild(r), ".apk").getRoot()) .isEqualTo(getTargetConfiguration().getBinDirectory(RepositoryName.MAIN)); } @Test public void testCustomPackage_LocalResources() throws Exception { scratch.file("a/r/BUILD", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " custom_package = 'com.google.android.bar',", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/strings.xml'],", " )"); ConfiguredTarget r = getConfiguredTarget("//a/r:r"); assertNoEvents(); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(r)); assertContainsSublist(args, ImmutableList.of("--packageForR", "com.google.android.bar")); } @Test public void testCustomJavacopts() throws Exception { scratch.file("java/foo/A.java", "foo"); scratch.file("java/foo/BUILD", "android_binary(name = 'a', manifest = 'AndroidManifest.xml', ", " srcs = ['A.java'], javacopts = ['-g:lines,source'])"); Artifact deployJar = getFileConfiguredTarget("//java/foo:a_deploy.jar").getArtifact(); Action deployAction = getGeneratingAction(deployJar); JavaCompileAction javacAction = (JavaCompileAction) actionsTestUtil() .getActionForArtifactEndingWith( actionsTestUtil().artifactClosureOf(deployAction.getInputs()), "liba.jar"); assertThat(getJavacArguments(javacAction)).contains("-g:lines,source"); } @Test public void testFixDepsToolFlag() throws Exception { useConfiguration("--experimental_fix_deps_tool=autofixer"); scratch.file("java/foo/A.java", "foo"); scratch.file( "java/foo/BUILD", "android_binary(name = 'a', manifest = 'AndroidManifest.xml', ", " srcs = ['A.java'])"); Iterable<String> commandLine = getJavacArguments( ((JavaCompileAction) actionsTestUtil() .getActionForArtifactEndingWith( actionsTestUtil() .artifactClosureOf( getGeneratingAction( getFileConfiguredTarget("//java/foo:a_deploy.jar") .getArtifact()) .getInputs()), "liba.jar"))); assertThat(commandLine).containsAtLeast("--experimental_fix_deps_tool", "autofixer").inOrder(); } @Test public void testFixDepsToolFlagEmpty() throws Exception { scratch.file("java/foo/A.java", "foo"); scratch.file( "java/foo/BUILD", "android_binary(name = 'a', manifest = 'AndroidManifest.xml', ", " srcs = ['A.java'])"); Iterable<String> commandLine = getJavacArguments( ((JavaCompileAction) actionsTestUtil() .getActionForArtifactEndingWith( actionsTestUtil() .artifactClosureOf( getGeneratingAction( getFileConfiguredTarget("//java/foo:a_deploy.jar") .getArtifact()) .getInputs()), "liba.jar"))); assertThat(commandLine).containsAtLeast("--experimental_fix_deps_tool", "add_dep").inOrder(); } @Test public void testAndroidBinaryExportsJavaCompilationArgsProvider() throws Exception { scratch.file("java/foo/A.java", "foo"); scratch.file("java/foo/BUILD", "android_binary(name = 'a', manifest = 'AndroidManifest.xml', ", " srcs = ['A.java'], javacopts = ['-g:lines,source'])"); final JavaCompilationArgsProvider provider = JavaInfo .getProvider(JavaCompilationArgsProvider.class, getConfiguredTarget("//java/foo:a")); assertThat(provider).isNotNull(); } @Test public void testNoApplicationId_LocalResources() throws Exception { scratch.file("java/a/r/BUILD", "android_binary(name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/strings.xml'],", " )"); ConfiguredTarget r = getConfiguredTarget("//java/a/r:r"); assertNoEvents(); List<String> args = getGeneratingSpawnActionArgs(getResourceApk(r)); Truth.assertThat(args).doesNotContain("--applicationId"); } @Test public void testDisallowPrecompiledJars() throws Exception { checkError("java/precompiled", "binary", // messages: "does not produce any android_binary srcs files (expected .java or .srcjar)", // build file: "android_binary(name = 'binary',", " manifest='AndroidManifest.xml',", " srcs = [':jar'])", "filegroup(name = 'jar',", " srcs = ['lib.jar'])"); } @Test public void testDesugarJava8Libs_noProguard() throws Exception { useConfiguration("--experimental_desugar_java8_libs"); scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'native',", ")"); ConfiguredTarget top = getConfiguredTarget("//java/com/google/android:foo"); Artifact artifact = getBinArtifact("_dx/foo/_final_classes.dex.zip", top); assertWithMessage("_final_classes.dex.zip").that(artifact).isNotNull(); Action generatingAction = getGeneratingAction(artifact); assertThat(ActionsTestUtil.baseArtifactNames(generatingAction.getInputs())) .containsAtLeast("classes.dex.zip", /*canned*/ "java8_legacy.dex.zip"); } @Test public void testDesugarJava8Libs_withProguard() throws Exception { useConfiguration("--experimental_desugar_java8_libs"); scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " manifest = 'AndroidManifest.xml',", " multidex = 'native',", " proguard_specs = ['foo.cfg'],", ")"); ConfiguredTarget top = getConfiguredTarget("//java/com/google/android:foo"); Artifact artifact = getBinArtifact("_dx/foo/_final_classes.dex.zip", top); assertWithMessage("_final_classes.dex.zip").that(artifact).isNotNull(); Action generatingAction = getGeneratingAction(artifact); assertThat(ActionsTestUtil.baseArtifactNames(generatingAction.getInputs())) .containsAtLeast("classes.dex.zip", /*built*/ "_java8_legacy.dex.zip"); } @Test public void testDesugarJava8Libs_noMultidexError() throws Exception { useConfiguration("--experimental_desugar_java8_libs"); checkError(/*packageName=*/ "java/com/google/android", /*ruleName=*/ "foo", /*expectedErrorMessage=*/ "multidex", "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " manifest = 'AndroidManifest.xml',", ")"); } @Test public void testApplyProguardMapping() throws Exception { scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " proguard_apply_mapping = 'proguard.map',", " proguard_specs = ['foo.pro'],", " manifest = 'AndroidManifest.xml',", ")"); ConfiguredTarget ct = getConfiguredTarget("//java/com/google/android:foo"); Artifact artifact = artifactByPath(getFilesToBuild(ct), "_proguard.jar"); Action generatingAction = getGeneratingAction(artifact); assertThat(Artifact.toExecPaths(generatingAction.getInputs())) .contains("java/com/google/android/proguard.map"); // Cannot use assertThat().containsAllOf().inOrder() as that does not assert that the elements // are consecutive. MoreAsserts.assertContainsSublist(getGeneratingSpawnActionArgs(artifact), "-applymapping", "java/com/google/android/proguard.map"); } @Test public void testApplyProguardMappingWithNoSpec() throws Exception { checkError( "java/com/google/android", "foo", // messages: "'proguard_apply_mapping' can only be used when 'proguard_specs' is also set", // build file: "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " proguard_apply_mapping = 'proguard.map',", " manifest = 'AndroidManifest.xml',", ")"); } @Test public void testApplyProguardDictionary() throws Exception { scratch.file( "java/com/google/android/BUILD", "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " proguard_apply_dictionary = 'dictionary.txt',", " proguard_specs = ['foo.pro'],", " manifest = 'AndroidManifest.xml',", ")"); ConfiguredTarget ct = getConfiguredTarget("//java/com/google/android:foo"); Artifact artifact = artifactByPath(getFilesToBuild(ct), "_proguard.jar"); Action generatingAction = getGeneratingAction(artifact); assertThat(Artifact.toExecPaths(generatingAction.getInputs())) .contains("java/com/google/android/dictionary.txt"); // Cannot use assertThat().containsAllOf().inOrder() as that does not assert that the elements // are consecutive. MoreAsserts.assertContainsSublist(getGeneratingSpawnActionArgs(artifact), "-obfuscationdictionary", "java/com/google/android/dictionary.txt"); MoreAsserts.assertContainsSublist(getGeneratingSpawnActionArgs(artifact), "-classobfuscationdictionary", "java/com/google/android/dictionary.txt"); MoreAsserts.assertContainsSublist(getGeneratingSpawnActionArgs(artifact), "-packageobfuscationdictionary", "java/com/google/android/dictionary.txt"); } @Test public void testApplyProguardDictionaryWithNoSpec() throws Exception { checkError( "java/com/google/android", "foo", // messages: "'proguard_apply_dictionary' can only be used when 'proguard_specs' is also set", // build file: "android_binary(", " name = 'foo',", " srcs = ['foo.java'],", " proguard_apply_dictionary = 'dictionary.txt',", " manifest = 'AndroidManifest.xml',", ")"); } @Test public void testFeatureFlagsAttributeSetsSelectInDependency() throws Exception { useConfiguration( "--experimental_dynamic_configs=notrim", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/BUILD", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag1@on',", " flag_values = {':flag1': 'on'},", " transitive_configs = [':flag1'],", ")", "config_feature_flag(", " name = 'flag2',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag2@on',", " flag_values = {':flag2': 'on'},", " transitive_configs = [':flag2'],", ")", "android_library(", " name = 'lib',", " srcs = select({", " ':flag1@on': ['Flag1On.java'],", " '//conditions:default': ['Flag1Off.java'],", " }) + select({", " ':flag2@on': ['Flag2On.java'],", " '//conditions:default': ['Flag2Off.java'],", " }),", " transitive_configs = [':flag1', ':flag2'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " deps = [':lib'],", " feature_flags = {", " 'flag1': 'on',", " },", " transitive_configs = [':flag1', ':flag2'],", ")"); ConfiguredTarget binary = getConfiguredTarget("//java/com/foo"); List<String> inputs = prettyArtifactNames(actionsTestUtil().artifactClosureOf(getFinalUnsignedApk(binary))); assertThat(inputs).containsAtLeast("java/com/foo/Flag1On.java", "java/com/foo/Flag2Off.java"); assertThat(inputs).containsNoneOf("java/com/foo/Flag1Off.java", "java/com/foo/Flag2On.java"); } @Test public void testFeatureFlagsAttributeSetsSelectInBinary() throws Exception { useConfiguration( "--experimental_dynamic_configs=notrim", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/BUILD", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag1@on',", " flag_values = {':flag1': 'on'},", " transitive_configs = [':flag1'],", ")", "config_feature_flag(", " name = 'flag2',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag2@on',", " flag_values = {':flag2': 'on'},", " transitive_configs = [':flag2'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " srcs = select({", " ':flag1@on': ['Flag1On.java'],", " '//conditions:default': ['Flag1Off.java'],", " }) + select({", " ':flag2@on': ['Flag2On.java'],", " '//conditions:default': ['Flag2Off.java'],", " }),", " feature_flags = {", " 'flag1': 'on',", " },", " transitive_configs = [':flag1', ':flag2'],", ")"); ConfiguredTarget binary = getConfiguredTarget("//java/com/foo"); List<String> inputs = prettyArtifactNames(actionsTestUtil().artifactClosureOf(getFinalUnsignedApk(binary))); assertThat(inputs).containsAtLeast("java/com/foo/Flag1On.java", "java/com/foo/Flag2Off.java"); assertThat(inputs).containsNoneOf("java/com/foo/Flag1Off.java", "java/com/foo/Flag2On.java"); } @Test public void testFeatureFlagsAttributeSetsSelectInBinaryAlias() throws Exception { useConfiguration( "--experimental_dynamic_configs=notrim", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/BUILD", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag1@on',", " flag_values = {':flag1': 'on'},", " transitive_configs = [':flag1'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " srcs = select({", " ':flag1@on': ['Flag1On.java'],", " '//conditions:default': ['Flag1Off.java'],", " }),", " feature_flags = {", " 'flag1': 'on',", " },", " transitive_configs = [':flag1'],", ")", "alias(", " name = 'alias',", " actual = ':foo',", ")"); ConfiguredTarget binary = getConfiguredTarget("//java/com/foo:alias"); List<String> inputs = prettyArtifactNames(actionsTestUtil().artifactClosureOf(getFinalUnsignedApk(binary))); assertThat(inputs).contains("java/com/foo/Flag1On.java"); assertThat(inputs).doesNotContain("java/com/foo/Flag1Off.java"); } @Test public void testFeatureFlagsAttributeFailsAnalysisIfFlagValueIsInvalid() throws Exception { reporter.removeHandler(failFastHandler); useConfiguration( "--experimental_dynamic_configs=on", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/BUILD", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag1@on',", " flag_values = {':flag1': 'on'},", " transitive_configs = [':flag1'],", ")", "android_library(", " name = 'lib',", " srcs = select({", " ':flag1@on': ['Flag1On.java'],", " '//conditions:default': ['Flag1Off.java'],", " }),", " transitive_configs = [':flag1'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " deps = [':lib'],", " feature_flags = {", " 'flag1': 'invalid',", " },", " transitive_configs = [':flag1'],", ")"); assertThat(getConfiguredTarget("//java/com/foo")).isNull(); assertContainsEvent( "in config_feature_flag rule //java/com/foo:flag1: " + "value must be one of [\"off\", \"on\"], but was \"invalid\""); } @Test public void testFeatureFlagsAttributeFailsAnalysisIfFlagValueIsInvalidEvenIfNotUsed() throws Exception { reporter.removeHandler(failFastHandler); useConfiguration( "--experimental_dynamic_configs=on", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/BUILD", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_setting(", " name = 'flag1@on',", " flag_values = {':flag1': 'on'},", " transitive_configs = [':flag1'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " feature_flags = {", " 'flag1': 'invalid',", " },", " transitive_configs = [':flag1'],", ")"); assertThat(getConfiguredTarget("//java/com/foo")).isNull(); assertContainsEvent( "in config_feature_flag rule //java/com/foo:flag1: " + "value must be one of [\"off\", \"on\"], but was \"invalid\""); } @Test public void testFeatureFlagsAttributeFailsAnalysisIfFlagIsAliased() throws Exception { reporter.removeHandler(failFastHandler); useConfiguration( "--experimental_dynamic_configs=notrim", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/BUILD", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "alias(", " name = 'alias',", " actual = 'flag1',", " transitive_configs = [':flag1'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " feature_flags = {", " 'alias': 'on',", " },", " transitive_configs = [':flag1'],", ")"); assertThat(getConfiguredTarget("//java/com/foo")).isNull(); assertContainsEvent( "in feature_flags attribute of android_binary rule //java/com/foo:foo: " + "Feature flags must be named directly, not through aliases; " + "use '//java/com/foo:flag1', not '//java/com/foo:alias'"); } @Test public void testFeatureFlagsAttributeSetsFeatureFlagProviderValues() throws Exception { useConfiguration( "--experimental_dynamic_configs=notrim", "--enforce_transitive_configs_for_config_feature_flag"); scratch.file( "java/com/foo/reader.bzl", "def _impl(ctx):", " ctx.actions.write(", " ctx.outputs.java,", " '\\n'.join([", " str(target.label) + ': ' + target[config_common.FeatureFlagInfo].value", " for target in ctx.attr.flags]))", " return [DefaultInfo(files=depset([ctx.outputs.java]))]", "flag_reader = rule(", " implementation=_impl,", " attrs={'flags': attr.label_list(providers=[config_common.FeatureFlagInfo])},", " outputs={'java': '%{name}.java'},", ")"); scratch.file( "java/com/foo/BUILD", "load('//java/com/foo:reader.bzl', 'flag_reader')", "config_feature_flag(", " name = 'flag1',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_feature_flag(", " name = 'flag2',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "flag_reader(", " name = 'FooFlags',", " flags = [':flag1', ':flag2'],", " transitive_configs = [':flag1', ':flag2'],", ")", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " srcs = [':FooFlags.java'],", " feature_flags = {", " 'flag1': 'on',", " },", " transitive_configs = [':flag1', ':flag2'],", ")"); Artifact flagList = getFirstArtifactEndingWith( actionsTestUtil() .artifactClosureOf(getFinalUnsignedApk(getConfiguredTarget("//java/com/foo"))), "/FooFlags.java"); FileWriteAction action = (FileWriteAction) getGeneratingAction(flagList); assertThat(action.getFileContents()) .isEqualTo("//java/com/foo:flag1: on\n//java/com/foo:flag2: off"); } @Test public void testNocompressExtensions() throws Exception { scratch.file( "java/r/android/BUILD", "android_binary(", " name = 'r',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/raw/foo.apk'],", " nocompress_extensions = ['.apk', '.so'],", ")"); ConfiguredTarget binary = getConfiguredTarget("//java/r/android:r"); ValidatedAndroidResources resource = getValidatedResources(binary); List<String> args = resourceArguments(resource); Artifact inputManifest = getFirstArtifactEndingWith( getGeneratingSpawnAction(resource.getManifest()).getInputs(), "AndroidManifest.xml"); assertContainsSublist( args, ImmutableList.of( "--primaryData", "java/r/android/res::" + inputManifest.getExecPathString())); assertThat(args).contains("--uncompressedExtensions"); assertThat(args.get(args.indexOf("--uncompressedExtensions") + 1)).isEqualTo(".apk,.so"); assertThat(getGeneratingSpawnActionArgs(getCompressedUnsignedApk(binary))) .containsAtLeast("--nocompress_suffixes", ".apk", ".so") .inOrder(); assertThat(getGeneratingSpawnActionArgs(getFinalUnsignedApk(binary))) .containsAtLeast("--nocompress_suffixes", ".apk", ".so") .inOrder(); } @Test public void testFeatureFlagPolicyMustContainRuleToUseFeatureFlags() throws Exception { reporter.removeHandler(failFastHandler); // expecting an error useConfiguration("--enforce_transitive_configs_for_config_feature_flag"); scratch.overwriteFile( "tools/whitelists/config_feature_flag/BUILD", "package_group(", " name = 'config_feature_flag',", " packages = ['//flag'])"); scratch.file( "flag/BUILD", "config_feature_flag(", " name = 'flag',", " allowed_values = ['right', 'wrong'],", " default_value = 'right',", " visibility = ['//java/com/google/android/foo:__pkg__'],", ")"); scratch.file( "java/com/google/android/foo/BUILD", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " srcs = [':FooFlags.java'],", " feature_flags = {", " '//flag:flag': 'right',", " },", " transitive_configs = ['//flag:flag'],", ")"); assertThat(getConfiguredTarget("//java/com/google/android/foo:foo")).isNull(); assertContainsEvent( "in feature_flags attribute of android_binary rule //java/com/google/android/foo:foo: " + "the feature_flags attribute is not available in package " + "'java/com/google/android/foo'"); } @Test public void testFeatureFlagPolicyDoesNotBlockRuleIfInPolicy() throws Exception { useConfiguration("--enforce_transitive_configs_for_config_feature_flag"); scratch.overwriteFile( "tools/whitelists/config_feature_flag/BUILD", "package_group(", " name = 'config_feature_flag',", " packages = ['//flag', '//java/com/google/android/foo'])"); scratch.file( "flag/BUILD", "config_feature_flag(", " name = 'flag',", " allowed_values = ['right', 'wrong'],", " default_value = 'right',", " visibility = ['//java/com/google/android/foo:__pkg__'],", ")"); scratch.file( "java/com/google/android/foo/BUILD", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " srcs = [':FooFlags.java'],", " feature_flags = {", " '//flag:flag': 'right',", " },", " transitive_configs = ['//flag:flag'],", ")"); assertThat(getConfiguredTarget("//java/com/google/android/foo:foo")).isNotNull(); assertNoEvents(); } @Test public void testFeatureFlagPolicyIsNotUsedIfFlagValuesNotUsed() throws Exception { scratch.overwriteFile( "tools/whitelists/config_feature_flag/BUILD", "package_group(", " name = 'config_feature_flag',", " packages = ['*super* busted package group'])"); scratch.file( "java/com/google/android/foo/BUILD", "android_binary(", " name = 'foo',", " manifest = 'AndroidManifest.xml',", " srcs = [':FooFlags.java'],", ")"); assertThat(getConfiguredTarget("//java/com/google/android/foo:foo")).isNotNull(); // the package_group is busted, so we would have failed to get this far if we depended on it assertNoEvents(); // sanity check time: does this test actually test what we're testing for? reporter.removeHandler(failFastHandler); assertThat(getConfiguredTarget("//tools/whitelists/config_feature_flag:config_feature_flag")) .isNull(); assertContainsEvent("*super* busted package group"); } @Test public void testAapt2WithoutAndroidSdk() throws Exception { checkError( "java/a", "a", "aapt2 processing requested but not available on the android_sdk", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", " aapt_version = 'aapt2'", ")"); } @Test public void testAapt2FlagWithoutAndroidSdk() throws Exception { useConfiguration("--android_aapt=aapt2"); checkError( "java/a", "a", "aapt2 processing requested but not available on the android_sdk", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", ")"); } @Test public void testAapt2WithAndroidSdk() throws Exception { mockAndroidSdkWithAapt2(); scratch.file( "java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", " aapt_version = 'aapt2'", ")"); useConfiguration("--android_sdk=//sdk:sdk"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); Artifact apk = getImplicitOutputArtifact(a, AndroidRuleClasses.ANDROID_RESOURCES_APK); assertThat(getGeneratingSpawnActionArgs(apk)) .containsAtLeast("--aapt2", "sdk/aapt2", "--tool", "AAPT2_PACKAGE"); } @Test public void testAapt2WithAndroidSdkAndDependencies() throws Exception { mockAndroidSdkWithAapt2(); scratch.file( "java/b/BUILD", "android_library(", " name = 'b',", " srcs = ['B.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", ")"); scratch.file( "java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " deps = [ '//java/b:b' ],", " resource_files = [ 'res/values/values.xml' ], ", " aapt_version = 'aapt2'", ")"); useConfiguration("--android_sdk=//sdk:sdk"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); ConfiguredTarget b = getDirectPrerequisite(a, "//java/b:b"); Artifact classJar = getImplicitOutputArtifact(a, AndroidRuleClasses.ANDROID_RESOURCES_CLASS_JAR); Artifact rTxt = getImplicitOutputArtifact(a, AndroidRuleClasses.ANDROID_R_TXT); Artifact apk = getImplicitOutputArtifact(a, AndroidRuleClasses.ANDROID_RESOURCES_APK); SpawnAction apkAction = getGeneratingSpawnAction(apk); assertThat(getGeneratingSpawnActionArgs(apk)) .containsAtLeast("--aapt2", "sdk/aapt2", "--tool", "AAPT2_PACKAGE"); assertThat(apkAction.getInputs()) .contains( getImplicitOutputArtifact(b, AndroidRuleClasses.ANDROID_COMPILED_SYMBOLS)); SpawnAction classAction = getGeneratingSpawnAction(classJar); assertThat(classAction.getInputs()) .containsAtLeast( rTxt, getImplicitOutputArtifact(b, AndroidRuleClasses.ANDROID_RESOURCES_AAPT2_R_TXT)); } @Test public void testAapt2ResourceShrinkingAction() throws Exception { mockAndroidSdkWithAapt2(); scratch.file( "java/com/google/android/hello/BUILD", "android_binary(name = 'hello',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " inline_constants = 0,", " aapt_version='aapt2',", " resource_files = ['res/values/strings.xml'],", " shrink_resources = 1,", " proguard_specs = ['proguard-spec.pro'],)"); useConfiguration("--android_sdk=//sdk:sdk"); ConfiguredTargetAndData targetAndData = getConfiguredTargetAndData("//java/com/google/android/hello:hello"); ConfiguredTarget binary = targetAndData.getConfiguredTarget(); Artifact jar = getResourceClassJar(targetAndData); assertThat(getGeneratingAction(jar).getMnemonic()).isEqualTo("RClassGenerator"); assertThat(getGeneratingSpawnActionArgs(jar)).contains("--finalFields"); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)); assertThat(artifacts) .containsAtLeast( getFirstArtifactEndingWith(artifacts, "resource_files.zip"), getFirstArtifactEndingWith(artifacts, "proguard.jar"), getFirstArtifactEndingWith(artifacts, "shrunk.ap_")); List<String> processingArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "resource_files.zip")); assertThat(flagValue("--resourcesOutput", processingArgs)) .endsWith("hello_files/resource_files.zip"); List<String> proguardArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "proguard.jar")); assertThat(flagValue("-outjars", proguardArgs)).endsWith("hello_proguard.jar"); List<String> shrinkingArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "shrunk.ap_")); assertThat(flagValue("--tool", shrinkingArgs)).isEqualTo("SHRINK_AAPT2"); assertThat(flagValue("--aapt2", shrinkingArgs)).isEqualTo(flagValue("--aapt2", processingArgs)); assertThat(flagValue("--resources", shrinkingArgs)) .isEqualTo(flagValue("--resourcesOutput", processingArgs)); assertThat(flagValue("--shrunkJar", shrinkingArgs)) .isEqualTo(flagValue("-outjars", proguardArgs)); assertThat(flagValue("--proguardMapping", shrinkingArgs)) .isEqualTo(flagValue("-printmapping", proguardArgs)); assertThat(flagValue("--rTxt", shrinkingArgs)) .isEqualTo(flagValue("--rOutput", processingArgs)); List<String> packageArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "_hello_proguard.cfg")); assertThat(flagValue("--tool", packageArgs)).isEqualTo("AAPT2_PACKAGE"); assertThat(packageArgs).doesNotContain("--conditionalKeepRules"); } @Test public void testAapt2ResourceCycleShrinking() throws Exception { mockAndroidSdkWithAapt2(); useConfiguration( "--android_sdk=//sdk:sdk", "--experimental_android_resource_cycle_shrinking=true"); scratch.file( "java/com/google/android/hello/BUILD", "android_binary(name = 'hello',", " srcs = ['Foo.java'],", " manifest = 'AndroidManifest.xml',", " inline_constants = 0,", " aapt_version='aapt2',", " resource_files = ['res/values/strings.xml'],", " shrink_resources = 1,", " proguard_specs = ['proguard-spec.pro'],)"); ConfiguredTargetAndData targetAndData = getConfiguredTargetAndData("//java/com/google/android/hello:hello"); ConfiguredTarget binary = targetAndData.getConfiguredTarget(); Artifact jar = getResourceClassJar(targetAndData); assertThat(getGeneratingAction(jar).getMnemonic()).isEqualTo("RClassGenerator"); assertThat(getGeneratingSpawnActionArgs(jar)).contains("--nofinalFields"); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)); List<String> packageArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "_hello_proguard.cfg")); assertThat(flagValue("--tool", packageArgs)).isEqualTo("AAPT2_PACKAGE"); assertThat(packageArgs).contains("--conditionalKeepRules"); } @Test public void testAapt2ResourceCycleShinkingWithoutResourceShrinking() throws Exception { mockAndroidSdkWithAapt2(); useConfiguration( "--android_sdk=//sdk:sdk", "--experimental_android_resource_cycle_shrinking=true"); checkError( "java/a", "a", "resource cycle shrinking can only be enabled when resource shrinking is enabled", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", " shrink_resources = 0,", " aapt_version = 'aapt2'", ")"); } @Test public void testDebugKeyExistsBinary() throws Exception { String debugKeyTarget = "//java/com/google/android/hello:debug_keystore"; scratch.file("java/com/google/android/hello/debug_keystore", "A debug key"); scratch.file( "java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " debug_key = '" + debugKeyTarget + "')"); checkDebugKey(debugKeyTarget, true); } @Test public void testDebugKeyNotExistsBinary() throws Exception { String debugKeyTarget = "//java/com/google/android/hello:debug_keystore"; scratch.file( "java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml')"); checkDebugKey(debugKeyTarget, false); } @Test public void testOnlyProguardSpecs() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l2',", " srcs = ['MoreMaps.java'],", " neverlink = 1)", "android_library(name = 'l3',", " idl_srcs = ['A.aidl'],", " deps = [':l2'])", "android_library(name = 'l4',", " srcs = ['SubMoreMaps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l3', ':l4'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); checkProguardUse( "//java/com/google/android/hello:b", "b_proguard.jar", false, null, targetConfig.getBinFragment() + "/java/com/google/android/hello/proguard/b/legacy_b_combined_library_jars.jar"); } @Test public void testOnlyProguardSpecsProguardJar() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l2',", " srcs = ['MoreMaps.java'],", " neverlink = 1)", "android_library(name = 'l3',", " idl_srcs = ['A.aidl'],", " deps = [':l2'])", "android_library(name = 'l4',", " srcs = ['SubMoreMaps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l3', ':l4'],", " manifest = 'AndroidManifest.xml',", " proguard_generate_mapping = 1,", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); ConfiguredTarget output = getConfiguredTarget("//java/com/google/android/hello:b_proguard.jar"); assertProguardUsed(output); output = getConfiguredTarget("//java/com/google/android/hello:b_proguard.map"); assertWithMessage("proguard.map is not in the rule output") .that( actionsTestUtil() .getActionForArtifactEndingWith(getFilesToBuild(output), "_proguard.map")) .isNotNull(); } @Test public void testCommandLineForMultipleProguardSpecs() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l1',", " srcs = ['Maps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l1'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:b"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(binary), "_proguard.jar"); assertWithMessage("Proguard action does not contain expected inputs.") .that(prettyArtifactNames(action.getInputs())) .containsAtLeast( "java/com/google/android/hello/proguard-spec.pro", "java/com/google/android/hello/proguard-spec1.pro", "java/com/google/android/hello/proguard-spec2.pro"); assertThat(action.getArguments()) .containsExactly( getProguardBinary().getExecPathString(), "-forceprocessing", "-injars", execPathEndingWith(action.getInputs(), "b_deploy.jar"), "-outjars", execPathEndingWith(action.getOutputs(), "b_proguard.jar"), // Only one combined library jar "-libraryjars", execPathEndingWith(action.getInputs(), "legacy_b_combined_library_jars.jar"), "@" + execPathEndingWith(action.getInputs(), "b_proguard.cfg"), "@java/com/google/android/hello/proguard-spec.pro", "@java/com/google/android/hello/proguard-spec1.pro", "@java/com/google/android/hello/proguard-spec2.pro", "-printseeds", execPathEndingWith(action.getOutputs(), "_proguard.seeds"), "-printusage", execPathEndingWith(action.getOutputs(), "_proguard.usage"), "-printconfiguration", execPathEndingWith(action.getOutputs(), "_proguard.config")) .inOrder(); } /** Regression test for b/17790639 */ @Test public void testNoDuplicatesInProguardCommand() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l1',", " srcs = ['Maps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l1'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:b"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(binary), "_proguard.jar"); assertThat(action.getArguments()) .containsExactly( getProguardBinary().getExecPathString(), "-forceprocessing", "-injars", execPathEndingWith(action.getInputs(), "b_deploy.jar"), "-outjars", execPathEndingWith(action.getOutputs(), "b_proguard.jar"), // Only one combined library jar "-libraryjars", execPathEndingWith(action.getInputs(), "legacy_b_combined_library_jars.jar"), "@" + execPathEndingWith(action.getInputs(), "b_proguard.cfg"), "@java/com/google/android/hello/proguard-spec.pro", "@java/com/google/android/hello/proguard-spec1.pro", "@java/com/google/android/hello/proguard-spec2.pro", "-printseeds", execPathEndingWith(action.getOutputs(), "_proguard.seeds"), "-printusage", execPathEndingWith(action.getOutputs(), "_proguard.usage"), "-printconfiguration", execPathEndingWith(action.getOutputs(), "_proguard.config")) .inOrder(); } @Test public void testProguardMapping() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro'],", " proguard_generate_mapping = 1)"); checkProguardUse( "//java/com/google/android/hello:b", "b_proguard.jar", true, null, getAndroidJarPath()); } @Test public void testProguardMappingProvider() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l2',", " srcs = ['MoreMaps.java'],", " neverlink = 1)", "android_library(name = 'l3',", " idl_srcs = ['A.aidl'],", " deps = [':l2'])", "android_library(name = 'l4',", " srcs = ['SubMoreMaps.java'],", " neverlink = 1)", "android_binary(name = 'b1',", " srcs = ['HelloApp.java'],", " deps = [':l3', ':l4'],", " manifest = 'AndroidManifest.xml',", " proguard_generate_mapping = 1,", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])", "android_binary(name = 'b2',", " srcs = ['HelloApp.java'],", " deps = [':l3', ':l4'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); ConfiguredTarget output = getConfiguredTarget("//java/com/google/android/hello:b1"); assertProguardUsed(output); Artifact mappingArtifact = getBinArtifact("b1_proguard.map", output); ProguardMappingProvider mappingProvider = output.get(ProguardMappingProvider.PROVIDER); assertThat(mappingProvider.getProguardMapping()).isEqualTo(mappingArtifact); output = getConfiguredTarget("//java/com/google/android/hello:b2"); assertProguardUsed(output); assertThat(output.get(ProguardMappingProvider.PROVIDER)).isNull(); } @Test public void testLegacyOptimizationModeUsesExtraProguardSpecs() throws Exception { useConfiguration("--extra_proguard_specs=java/com/google/android/hello:extra.pro"); scratch.file("java/com/google/android/hello/BUILD", "exports_files(['extra.pro'])", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro'])"); checkProguardUse( "//java/com/google/android/hello:b", "b_proguard.jar", false, null, getAndroidJarPath()); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(getConfiguredTarget("//java/com/google/android/hello:b")), "_proguard.jar"); assertThat(prettyArtifactNames(action.getInputs())).containsNoDuplicates(); assertThat(Collections2.filter(action.getArguments(), arg -> arg.startsWith("@"))) .containsExactly( "@" + execPathEndingWith(action.getInputs(), "/proguard-spec.pro"), "@" + execPathEndingWith(action.getInputs(), "/_b_proguard.cfg"), "@java/com/google/android/hello/extra.pro"); } @Test public void testExtraProguardSpecsDontDuplicateProguardInputFiles() throws Exception { useConfiguration("--extra_proguard_specs=java/com/google/android/hello:proguard-spec.pro"); scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro'])"); checkProguardUse( "//java/com/google/android/hello:b", "b_proguard.jar", false, null, getAndroidJarPath()); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(getConfiguredTarget("//java/com/google/android/hello:b")), "_proguard.jar"); assertThat(prettyArtifactNames(action.getInputs())).containsNoDuplicates(); assertThat(Collections2.filter(action.getArguments(), arg -> arg.startsWith("@"))) .containsExactly( "@java/com/google/android/hello/proguard-spec.pro", "@" + execPathEndingWith(action.getInputs(), "/_b_proguard.cfg")); } @Test public void testLegacyLinkingProguardNotUsedWithoutSpecOnBinary() throws Exception { useConfiguration( "--java_optimization_mode=legacy", "--extra_proguard_specs=//java/com/google/android/hello:ignored.pro"); scratch.file("java/com/google/android/hello/BUILD", "exports_files(['ignored.pro'])", "android_library(name = 'l2',", " srcs = ['MoreMaps.java'],", " neverlink = 1)", "android_library(name = 'l3',", " idl_srcs = ['A.aidl'],", // Having a library spec should not trigger proguard on the binary target. " proguard_specs = ['library_spec.cfg'],", " deps = [':l2'])", "android_library(name = 'l4',", " srcs = ['SubMoreMaps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l3', ':l4'],", " manifest = 'AndroidManifest.xml',)"); assertProguardNotUsed(getConfiguredTarget("//java/com/google/android/hello:b")); } @Test public void testFullOptimizationModeForcesProguard() throws Exception { useConfiguration("--java_optimization_mode=optimize_minify"); SpawnAction action = testProguardOptimizationMode(); // Expect spec generated from resources as well as library's (validated) spec as usual assertThat(Collections2.filter(action.getArguments(), arg -> arg.startsWith("@"))) .containsExactly( "@" + execPathEndingWith(action.getInputs(), "/_b_proguard.cfg"), "@" + execPathEndingWith(action.getInputs(), "library_spec.cfg_valid")); } @Test public void testOptimizingModesIncludeExtraProguardSpecs() throws Exception { useConfiguration( "--java_optimization_mode=fast_minify", "--extra_proguard_specs=//java/com/google/android/hello:extra.pro"); SpawnAction action = testProguardOptimizationMode(); assertThat(action.getArguments()).contains("@java/com/google/android/hello/extra.pro"); } @Test public void testRenameModeForcesProguardWithSpecForMode() throws Exception { testProguardPartialOptimizationMode("rename", "-dontshrink\n-dontoptimize\n"); } @Test public void testMinimizingModeForcesProguardWithSpecForMode() throws Exception { testProguardPartialOptimizationMode("fast_minify", "-dontoptimize\n"); } public void testProguardPartialOptimizationMode(String mode, String expectedSpecForMode) throws Exception { useConfiguration("--java_optimization_mode=" + mode); SpawnAction action = testProguardOptimizationMode(); // Expect spec generated from resources, library's (validated) spec, and spec for mode String modeSpecFileSuffix = "/" + mode + "_b_proguard.cfg"; assertThat(Collections2.filter(action.getArguments(), arg -> arg.startsWith("@"))) .containsExactly( "@" + execPathEndingWith(action.getInputs(), modeSpecFileSuffix), "@" + execPathEndingWith(action.getInputs(), "/_b_proguard.cfg"), "@" + execPathEndingWith(action.getInputs(), "library_spec.cfg_valid")); FileWriteAction modeSpec = (FileWriteAction) actionsTestUtil().getActionForArtifactEndingWith( action.getInputs(), modeSpecFileSuffix); assertThat(modeSpec.getFileContents()).isEqualTo(expectedSpecForMode); } public SpawnAction testProguardOptimizationMode() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "exports_files(['extra.pro'])", "android_library(name = 'l',", " idl_srcs = ['A.aidl'],", " proguard_specs = ['library_spec.cfg'])", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l'],", " manifest = 'AndroidManifest.xml',)"); checkProguardUse( "//java/com/google/android/hello:b", "b_proguard.jar", /*expectMapping*/ true, /*passes*/ null, getAndroidJarPath()); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(getConfiguredTarget("//java/com/google/android/hello:b")), "_proguard.jar"); assertThat(prettyArtifactNames(action.getInputs())).containsNoDuplicates(); return action; } @Test public void testProguardSpecFromLibraryUsedInBinary() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l2',", " srcs = ['MoreMaps.java'],", " proguard_specs = ['library_spec.cfg'])", "android_library(name = 'l3',", " idl_srcs = ['A.aidl'],", " proguard_specs = ['library_spec.cfg'],", " deps = [':l2'])", "android_library(name = 'l4',", " srcs = ['SubMoreMaps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l3', ':l4'],", " proguard_specs = ['proguard-spec.pro'],", " manifest = 'AndroidManifest.xml',)"); assertProguardUsed(getConfiguredTarget("//java/com/google/android/hello:b")); assertProguardGenerated(getConfiguredTarget("//java/com/google/android/hello:b")); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(getConfiguredTarget("//java/com/google/android/hello:b")), "_proguard.jar"); assertThat(prettyArtifactNames(action.getInputs())) .contains("java/com/google/android/hello/proguard-spec.pro"); assertThat(prettyArtifactNames(action.getInputs())) .contains( "java/com/google/android/hello/validated_proguard/l2/java/com/google/android/hello/library_spec.cfg_valid"); assertThat(prettyArtifactNames(action.getInputs())).containsNoDuplicates(); } @Test public void testResourcesUsedInProguardGenerate() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = ['res/values/strings.xml'],", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); scratch.file("java/com/google/android/hello/res/values/strings.xml", "<resources><string name = 'hello'>Hello Android!</string></resources>"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:b"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( actionsTestUtil().artifactClosureOf(getFilesToBuild(binary)), "_proguard.cfg"); assertProguardGenerated(binary); assertWithMessage("Generate proguard action does not contain expected input.") .that(prettyArtifactNames(action.getInputs())) .contains("java/com/google/android/hello/res/values/strings.xml"); } @Test public void testUseSingleJarForLibraryJars() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_library(name = 'l1',", " srcs = ['Maps.java'],", " neverlink = 1)", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " deps = [':l1'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro', 'proguard-spec1.pro',", " 'proguard-spec2.pro'])"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:b"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(binary), "_proguard.jar"); checkProguardLibJars(action, targetConfig.getBinFragment() + "/java/com/google/android/hello/proguard/b/legacy_b_combined_library_jars.jar"); } @Test public void testOnlyOneLibraryJar() throws Exception { scratch.file("java/com/google/android/hello/BUILD", "android_binary(name = 'b',", " srcs = ['HelloApp.java'],", " manifest = 'AndroidManifest.xml',", " proguard_specs = ['proguard-spec.pro'],", " proguard_generate_mapping = 1)"); ConfiguredTarget binary = getConfiguredTarget("//java/com/google/android/hello:b"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith( getFilesToBuild(binary), "_proguard.jar"); checkProguardLibJars(action, getAndroidJarPath()); } @Test public void testApkInfoAccessibleFromSkylark() throws Exception { scratch.file( "java/com/google/android/BUILD", "load(':postprocess.bzl', 'postprocess')", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " manifest = 'AndroidManifest.xml')", "postprocess(name = 'postprocess', dep = ':b1')"); scratch.file( "java/com/google/android/postprocess.bzl", "def _impl(ctx):", " return [DefaultInfo(files=depset([ctx.attr.dep[ApkInfo].signed_apk]))]", "postprocess = rule(implementation=_impl,", " attrs={'dep': attr.label(providers=[ApkInfo])})"); ConfiguredTarget postprocess = getConfiguredTarget("//java/com/google/android:postprocess"); assertThat(postprocess).isNotNull(); assertThat( prettyArtifactNames(postprocess.getProvider(FilesToRunProvider.class).getFilesToRun())) .containsExactly("java/com/google/android/b1.apk"); } @Test public void testInstrumentationInfoAccessibleFromSkylark() throws Exception { scratch.file( "java/com/google/android/instr/BUILD", "load(':instr.bzl', 'instr')", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " instruments = ':b2',", " manifest = 'AndroidManifest.xml')", "android_binary(name = 'b2',", " srcs = ['b2.java'],", " manifest = 'AndroidManifest.xml')", "instr(name = 'instr', dep = ':b1')"); scratch.file( "java/com/google/android/instr/instr.bzl", "def _impl(ctx):", " target = ctx.attr.dep[AndroidInstrumentationInfo].target_apk", " instr = ctx.attr.dep[AndroidInstrumentationInfo].instrumentation_apk", " return [DefaultInfo(files=depset([target,instr]))]", "instr = rule(implementation=_impl,", " attrs={'dep': attr.label(providers=[AndroidInstrumentationInfo])})"); ConfiguredTarget instr = getConfiguredTarget("//java/com/google/android/instr"); assertThat(instr).isNotNull(); assertThat(prettyArtifactNames(instr.getProvider(FilesToRunProvider.class).getFilesToRun())) .containsExactly( "java/com/google/android/instr/b1.apk", "java/com/google/android/instr/b2.apk"); } @Test public void testInstrumentationInfoCreatableFromSkylark() throws Exception { scratch.file( "java/com/google/android/instr/BUILD", "load(':instr.bzl', 'instr')", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " instruments = ':b2',", " manifest = 'AndroidManifest.xml')", "android_binary(name = 'b2',", " srcs = ['b2.java'],", " manifest = 'AndroidManifest.xml')", "instr(name = 'instr', dep = ':b1')"); scratch.file( "java/com/google/android/instr/instr.bzl", "def _impl(ctx):", " target = ctx.attr.dep[AndroidInstrumentationInfo].target_apk", " instr = ctx.attr.dep[AndroidInstrumentationInfo].instrumentation_apk", " return [AndroidInstrumentationInfo(target_apk=target,instrumentation_apk=instr)]", "instr = rule(implementation=_impl,", " attrs={'dep': attr.label(providers=[AndroidInstrumentationInfo])})"); ConfiguredTarget instr = getConfiguredTarget("//java/com/google/android/instr"); assertThat(instr).isNotNull(); assertThat(instr.get(AndroidInstrumentationInfo.PROVIDER).getTargetApk().prettyPrint()) .isEqualTo("java/com/google/android/instr/b2.apk"); assertThat(instr.get(AndroidInstrumentationInfo.PROVIDER).getInstrumentationApk().prettyPrint()) .isEqualTo("java/com/google/android/instr/b1.apk"); } @Test public void testInstrumentationInfoProviderHasApks() throws Exception { scratch.file( "java/com/google/android/instr/BUILD", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " instruments = ':b2',", " manifest = 'AndroidManifest.xml')", "android_binary(name = 'b2',", " srcs = ['b2.java'],", " manifest = 'AndroidManifest.xml')"); ConfiguredTarget b1 = getConfiguredTarget("//java/com/google/android/instr:b1"); AndroidInstrumentationInfo provider = b1.get(AndroidInstrumentationInfo.PROVIDER); assertThat(provider.getTargetApk()).isNotNull(); assertThat(provider.getTargetApk().prettyPrint()) .isEqualTo("java/com/google/android/instr/b2.apk"); assertThat(provider.getInstrumentationApk()).isNotNull(); assertThat(provider.getInstrumentationApk().prettyPrint()) .isEqualTo("java/com/google/android/instr/b1.apk"); } @Test public void testNoInstrumentationInfoProviderIfNotInstrumenting() throws Exception { scratch.file( "java/com/google/android/instr/BUILD", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " manifest = 'AndroidManifest.xml')"); ConfiguredTarget b1 = getConfiguredTarget("//java/com/google/android/instr:b1"); AndroidInstrumentationInfo provider = b1.get(AndroidInstrumentationInfo.PROVIDER); assertThat(provider).isNull(); } @Test public void testFilterActionWithInstrumentedBinary() throws Exception { scratch.file( "java/com/google/android/instr/BUILD", "android_binary(name = 'b1',", " srcs = ['b1.java'],", " instruments = ':b2',", " manifest = 'AndroidManifest.xml')", "android_binary(name = 'b2',", " srcs = ['b2.java'],", " manifest = 'AndroidManifest.xml')"); ConfiguredTarget b1 = getConfiguredTarget("//java/com/google/android/instr:b1"); SpawnAction action = (SpawnAction) actionsTestUtil().getActionForArtifactEndingWith(getFilesToBuild(b1), "_filtered.jar"); assertThat(action.getArguments()) .containsAtLeast( "--inputZip", getFirstArtifactEndingWith(action.getInputs(), "b1_deploy.jar").getExecPathString(), "--filterZips", getFirstArtifactEndingWith(action.getInputs(), "b2_deploy.jar").getExecPathString(), "--outputZip", getFirstArtifactEndingWith(action.getOutputs(), "b1_filtered.jar").getExecPathString(), "--filterTypes", ".class", "--checkHashMismatch", "IGNORE", "--explicitFilters", "/BR\\.class$,/databinding/[^/]+Binding\\.class$,R\\.class,R\\$.*\\.class", "--outputMode", "DONT_CARE"); } /** * 'proguard_specs' attribute gets read by an implicit outputs function: the * current heuristic is that if this attribute is configurable, we assume its * contents are non-empty and thus create the mybinary_proguard.jar output. * Test that here. */ @Test public void testConfigurableProguardSpecs() throws Exception { scratch.file("conditions/BUILD", "config_setting(", " name = 'a',", " values = {'test_arg': 'a'})", "config_setting(", " name = 'b',", " values = {'test_arg': 'b'})"); scratchConfiguredTarget("java/foo", "abin", "android_binary(", " name = 'abin',", " srcs = ['a.java'],", " proguard_specs = select({", " '//conditions:a': [':file1.pro'],", " '//conditions:b': [],", " '//conditions:default': [':file3.pro'],", " }) + [", // Add a long list here as a regression test for b/68238721 " 'file4.pro',", " 'file5.pro',", " 'file6.pro',", " 'file7.pro',", " 'file8.pro',", " ],", " manifest = 'AndroidManifest.xml')"); checkProguardUse( "//java/foo:abin", "abin_proguard.jar", /*expectMapping=*/ false, /*passes=*/ null, getAndroidJarPath()); } @Test public void testSkipParsingActionFlagGetsPropagated() throws Exception { mockAndroidSdkWithAapt2(); scratch.file( "java/b/BUILD", "android_library(", " name = 'b',", " srcs = ['B.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", ")"); scratch.file( "java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " deps = [ '//java/b:b' ],", " resource_files = [ 'res/values/values.xml' ], ", " aapt_version = 'aapt2'", ")"); useConfiguration("--android_sdk=//sdk:sdk", "--experimental_skip_parsing_action"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); ConfiguredTarget b = getDirectPrerequisite(a, "//java/b:b"); List<String> resourceProcessingArgs = getGeneratingSpawnActionArgs(getValidatedResources(a).getApk()); assertThat(resourceProcessingArgs).contains("AAPT2_PACKAGE"); String directData = resourceProcessingArgs.get( resourceProcessingArgs.indexOf("--directData") + 1); assertThat(directData).contains("symbols.zip"); assertThat(directData).doesNotContain("merged.bin"); assertThat(resourceProcessingArgs).contains("--useCompiledResourcesForMerge"); List<String> resourceMergingArgs = getGeneratingSpawnActionArgs(getValidatedResources(b).getJavaClassJar()); assertThat(resourceMergingArgs).contains("MERGE_COMPILED"); } @Test public void alwaysSkipParsingActionWithAapt2() throws Exception { mockAndroidSdkWithAapt2(); scratch.file( "java/b/BUILD", "android_library(", " name = 'b',", " srcs = ['B.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", ")"); scratch.file( "java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " deps = [ '//java/b:b' ],", " resource_files = [ 'res/values/values.xml' ], ", " aapt_version = 'aapt2'", ")"); useConfiguration("--android_sdk=//sdk:sdk"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); ConfiguredTarget b = getDirectPrerequisite(a, "//java/b:b"); List<String> resourceProcessingArgs = getGeneratingSpawnActionArgs(getValidatedResources(a).getApk()); assertThat(resourceProcessingArgs).contains("AAPT2_PACKAGE"); String directData = resourceProcessingArgs.get(resourceProcessingArgs.indexOf("--directData") + 1); assertThat(directData).contains("symbols.zip"); assertThat(directData).doesNotContain("merged.bin"); assertThat(resourceProcessingArgs).contains("--useCompiledResourcesForMerge"); // Libraries will still need to merge the xml until skip parsing is on by default. List<String> resourceMergingArgs = getGeneratingSpawnActionArgs(getValidatedResources(b).getJavaClassJar()); assertThat(resourceMergingArgs).contains("MERGE"); } @Test public void testAapt1BuildsWithAapt2Sdk() throws Exception { mockAndroidSdkWithAapt2(); scratch.file( "java/b/BUILD", "android_library(", " name = 'b',", " srcs = ['B.java'],", " manifest = 'AndroidManifest.xml',", " resource_files = [ 'res/values/values.xml' ], ", ")"); scratch.file( "java/a/BUILD", "android_binary(", " name = 'a',", " srcs = ['A.java'],", " manifest = 'AndroidManifest.xml',", " deps = [ '//java/b:b' ],", " resource_files = [ 'res/values/values.xml' ], ", " aapt_version = 'aapt'", ")"); useConfiguration("--android_sdk=//sdk:sdk", "--experimental_skip_parsing_action"); ConfiguredTarget a = getConfiguredTarget("//java/a:a"); ConfiguredTarget b = getDirectPrerequisite(a, "//java/b:b"); List<String> resourceProcessingArgs = getGeneratingSpawnActionArgs(getValidatedResources(a).getRTxt()); assertThat(resourceProcessingArgs).contains("PACKAGE"); String directData = resourceProcessingArgs.get( resourceProcessingArgs.indexOf("--directData") + 1); assertThat(directData).doesNotContain("symbols.zip"); assertThat(directData).contains("merged.bin"); List<String> compiledResourceMergingArgs = getGeneratingSpawnActionArgs(getValidatedResources(b).getJavaClassJar()); assertThat(compiledResourceMergingArgs).contains("MERGE_COMPILED"); Set<Artifact> artifacts = actionsTestUtil().artifactClosureOf(getFilesToBuild(b)); List<String> parsedResourceMergingArgs = getGeneratingSpawnActionArgs(getFirstArtifactEndingWith(artifacts, "resource_files.zip")); assertThat(parsedResourceMergingArgs).contains("MERGE"); } @Test public void skylarkJavaInfoToAndroidBinaryAttributes() throws Exception { scratch.file( "java/r/android/extension.bzl", "def _impl(ctx):", " dep_params = ctx.attr.dep[JavaInfo]", " return [dep_params]", "my_rule = rule(", " _impl,", " attrs = {", " 'dep': attr.label(),", " },", ")"); scratch.file( "java/r/android/BUILD", "load(':extension.bzl', 'my_rule')", "android_library(", " name = 'al_bottom_for_deps',", " srcs = ['java/A.java'],", ")", "my_rule(", " name = 'mya',", " dep = ':al_bottom_for_deps',", ")", "android_binary(", " name = 'foo_app',", " srcs = ['java/B.java'],", " deps = [':mya'],", " manifest = 'AndroidManifest.xml',", // TODO(b/75051107): Remove the following line when fixed. " incremental_dexing = 0,", ")"); // Test that all bottom jars are on the runtime classpath of the app. ConfiguredTarget target = getConfiguredTarget("//java/r/android:foo_app"); Collection<Artifact> transitiveSrcJars = OutputGroupInfo.get(target).getOutputGroup(JavaSemantics.SOURCE_JARS_OUTPUT_GROUP) .toCollection(); assertThat(ActionsTestUtil.baseArtifactNames(transitiveSrcJars)).containsExactly( "libal_bottom_for_deps-src.jar", "libfoo_app-src.jar"); } @Test public void androidManifestMergerOrderAlphabetical_MergeesSortedByExecPath() throws Exception { // Hack: Avoid the Android split transition by turning off fat_apk_cpu/android_cpu. // This is necessary because the transition would change the configuration directory, causing // the manifest paths in the assertion not to match. // TODO(mstaib): Get the library manifests in the same configuration as the binary gets them. useConfiguration( "--fat_apk_cpu=", "--android_cpu=", "--android_manifest_merger_order=alphabetical"); scratch.overwriteFile( "java/android/BUILD", "android_library(", " name = 'core',", " manifest = 'core/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['core/res/values/strings.xml'],", ")", "android_library(", " name = 'utility',", " manifest = 'utility/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['utility/res/values/values.xml'],", " deps = ['//java/common:common'],", ")"); scratch.file( "java/binary/BUILD", "android_binary(", " name = 'application',", " srcs = ['App.java'],", " manifest = 'app/AndroidManifest.xml',", " deps = [':library'],", ")", "android_library(", " name = 'library',", " manifest = 'library/AndroidManifest.xml',", " exports_manifest = 1,", " deps = ['//java/common:theme', '//java/android:utility'],", ")"); scratch.file( "java/common/BUILD", "android_library(", " name = 'common',", " manifest = 'common/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['common/res/values/common.xml'],", " deps = ['//java/android:core'],", ")", "android_library(", " name = 'theme',", " manifest = 'theme/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['theme/res/values/values.xml'],", ")"); Artifact androidCoreManifest = getLibraryManifest(getConfiguredTarget("//java/android:core")); Artifact androidUtilityManifest = getLibraryManifest(getConfiguredTarget("//java/android:utility")); Artifact binaryLibraryManifest = getLibraryManifest(getConfiguredTarget("//java/binary:library")); Artifact commonManifest = getLibraryManifest(getConfiguredTarget("//java/common:common")); Artifact commonThemeManifest = getLibraryManifest(getConfiguredTarget("//java/common:theme")); assertThat(getBinaryMergeeManifests(getConfiguredTarget("//java/binary:application"))) .containsExactlyEntriesIn( ImmutableMap.of( androidCoreManifest.getExecPath().toString(), "//java/android:core", androidUtilityManifest.getExecPath().toString(), "//java/android:utility", binaryLibraryManifest.getExecPath().toString(), "//java/binary:library", commonManifest.getExecPath().toString(), "//java/common:common", commonThemeManifest.getExecPath().toString(), "//java/common:theme")) .inOrder(); } @Test public void androidManifestMergerOrderAlphabeticalByConfiguration_MergeesSortedByPathInBinOrGen() throws Exception { // Hack: Avoid the Android split transition by turning off fat_apk_cpu/android_cpu. // This is necessary because the transition would change the configuration directory, causing // the manifest paths in the assertion not to match. // TODO(mstaib): Get the library manifests in the same configuration as the binary gets them. useConfiguration( "--fat_apk_cpu=", "--android_cpu=", "--android_manifest_merger_order=alphabetical_by_configuration"); scratch.overwriteFile( "java/android/BUILD", "android_library(", " name = 'core',", " manifest = 'core/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['core/res/values/strings.xml'],", ")", "android_library(", " name = 'utility',", " manifest = 'utility/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['utility/res/values/values.xml'],", " deps = ['//java/common:common'],", " transitive_configs = ['//flags:a', '//flags:b'],", ")"); scratch.file( "java/binary/BUILD", "android_binary(", " name = 'application',", " srcs = ['App.java'],", " manifest = 'app/AndroidManifest.xml',", " deps = [':library'],", " feature_flags = {", " '//flags:a': 'on',", " '//flags:b': 'on',", " '//flags:c': 'on',", " },", " transitive_configs = ['//flags:a', '//flags:b', '//flags:c'],", ")", "android_library(", " name = 'library',", " manifest = 'library/AndroidManifest.xml',", " exports_manifest = 1,", " deps = ['//java/common:theme', '//java/android:utility'],", " transitive_configs = ['//flags:a', '//flags:b', '//flags:c'],", ")"); scratch.file( "java/common/BUILD", "android_library(", " name = 'common',", " manifest = 'common/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['common/res/values/common.xml'],", " deps = ['//java/android:core'],", " transitive_configs = ['//flags:a'],", ")", "android_library(", " name = 'theme',", " manifest = 'theme/AndroidManifest.xml',", " exports_manifest = 1,", " resource_files = ['theme/res/values/values.xml'],", " transitive_configs = ['//flags:a', '//flags:b', '//flags:c'],", ")"); scratch.file( "flags/BUILD", "config_feature_flag(", " name = 'a',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_feature_flag(", " name = 'b',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")", "config_feature_flag(", " name = 'c',", " allowed_values = ['on', 'off'],", " default_value = 'off',", ")"); assertThat(getBinaryMergeeManifests(getConfiguredTarget("//java/binary:application")).values()) .containsExactly( "//java/android:core", "//java/android:utility", "//java/binary:library", "//java/common:common", "//java/common:theme") .inOrder(); } // DEPENDENCY order is not tested; the incorrect order of dependencies means the test would // have to enforce incorrect behavior. // TODO(b/117338320): Add a test when dependency order is fixed. }
[ "huangni@21cn.com" ]
huangni@21cn.com
3e44b22a24e8a9ce5783aaae94391a4d2e9de450
6aceef303358fd1effd59d8fbd68817f45a84978
/src/main/java/com/ciwise/contacts/web/rest/errors/FieldErrorDTO.java
a8c9028ff48dbdccca6cd445057582694960c821
[]
no_license
ciwise/contacts
ded3bfb94aeba7b47a98bceb01140e82a24674db
9ac72aadd877f99f63294bde81489fa7457c6d89
refs/heads/master
2020-12-31T07:20:42.291276
2016-05-16T05:15:20
2016-05-16T05:15:20
58,841,974
0
0
null
null
null
null
UTF-8
Java
false
false
653
java
package com.ciwise.contacts.web.rest.errors; import java.io.Serializable; public class FieldErrorDTO implements Serializable { private static final long serialVersionUID = 1L; private final String objectName; private final String field; private final String message; public FieldErrorDTO(String dto, String field, String message) { this.objectName = dto; this.field = field; this.message = message; } public String getObjectName() { return objectName; } public String getField() { return field; } public String getMessage() { return message; } }
[ "david@ciwise.com" ]
david@ciwise.com
5a1ac5cf01fe4df0c37f2d4522acf9fa9441c7fb
723679b44280cbd73108e89a8100397971f8f09d
/src/main/java/com/codesignal/csbot/listeners/BotCommand.java
5581fa4a722c0b44c52440d62aecd778971ed428
[]
no_license
baodvu/csbot
f69466d0d628c2f0a4529bbae94b6016664aefa6
a36305f17b924b5b4cbe66cac057beb165f9ecf3
refs/heads/main
2021-07-03T07:54:04.732196
2020-11-10T17:13:10
2020-11-10T17:13:10
193,787,395
0
0
null
null
null
null
UTF-8
Java
false
false
779
java
package com.codesignal.csbot.listeners; public class BotCommand { private String rawCommandName; private String commandName; private String commandParams; public String getRawCommandName() { return rawCommandName; } BotCommand withRawCommandName(String rawCommandName) { this.rawCommandName = rawCommandName; return this; } public String getCommandName() { return commandName; } BotCommand withCommandName(String commandName) { this.commandName = commandName; return this; } public String getCommandParams() { return commandParams; } BotCommand withCommandParams(String commandParams) { this.commandParams = commandParams; return this; } }
[ "Inc6WJR1pd2h" ]
Inc6WJR1pd2h
1b7d747815fece3da899ecc156ab70263efd3078
2781b87f0c4b63a1f9005e58b62e4a84d4fc2b66
/src/com/ryanworks/fishery/server/dao/DaoFactory.java
fa4b730e313a816658fd20a280355555642f66be
[]
no_license
ryankschee/fishery
ae5294083754401466d74e48bf183d16bf13c712
44e45d7568b0ce3d891b07672ac9c045fec36c56
refs/heads/master
2021-07-04T16:27:29.449384
2020-01-01T03:38:59
2020-01-01T03:38:59
231,076,668
0
0
null
2021-04-26T19:50:32
2019-12-31T11:16:27
TSQL
UTF-8
Java
false
false
5,644
java
package com.ryanworks.fishery.server.dao; import com.ryanworks.fishery.server.dao.impl.*; import com.ryanworks.fishery.shared.util.MyLogger; import java.util.Collections; import java.util.HashMap; import java.util.Map; public abstract class DaoFactory { public static final int MYSQL = 1; static Map cachedDAO; public static DaoFactory getDAOFactory(int whichFactory) { switch (whichFactory) { case MYSQL: return new MySQLDaoFactory(); default: return null; } } protected Object createDAO(Class classObj) throws DaoException { // Check if pool of DAO is available if (cachedDAO == null) { cachedDAO = Collections.synchronizedMap(new HashMap()); } // Check if pool contain the respective DAO object, if YES, then reuse Object daoObj = cachedDAO.get(classObj.getName()); if (daoObj != null) { return daoObj; } // No cached DAO object, so create a new one and insert it into pool of // cache for reuse purpose. try { daoObj = classObj.newInstance(); cachedDAO.put(classObj.getName(), daoObj); return daoObj; } catch (InstantiationException e) { MyLogger.logError(getClass(), "exception: " + e.getMessage()); throw new DaoException(e); } catch (IllegalAccessException e) { MyLogger.logError(getClass(), "exception: " + e.getMessage()); throw new DaoException(e); } finally { return daoObj; } } public MySQLUserDaoImpl getUserDao() throws DaoException { return (MySQLUserDaoImpl) createDAO(MySQLUserDaoImpl.class); } public MySQLCustomerDaoImpl getCustomerDao() throws DaoException { return (MySQLCustomerDaoImpl) createDAO(MySQLCustomerDaoImpl.class); } public MySQLCustomerPaymentDaoImpl getCustomerPaymentDao() throws DaoException { return (MySQLCustomerPaymentDaoImpl) createDAO(MySQLCustomerPaymentDaoImpl.class); } public MySQLCustomerSummaryDaoImpl getCustomerSummaryDao() throws DaoException { return (MySQLCustomerSummaryDaoImpl) createDAO(MySQLCustomerSummaryDaoImpl.class); } public MySQLCategoryDaoImpl getCategoryDao() throws DaoException { return (MySQLCategoryDaoImpl) createDAO(MySQLCategoryDaoImpl.class); } public MySQLItemDaoImpl getItemDao() throws DaoException { return (MySQLItemDaoImpl) createDAO(MySQLItemDaoImpl.class); } public MySQLSupplierDaoImpl getSupplierDao() throws DaoException { return (MySQLSupplierDaoImpl) createDAO(MySQLSupplierDaoImpl.class); } public MySQLSupplierChequeDaoImpl getSupplierChequeDao() throws DaoException { return (MySQLSupplierChequeDaoImpl) createDAO(MySQLSupplierChequeDaoImpl.class); } public MySQLSupplierFuelDaoImpl getSupplierFuelDao() throws DaoException { return (MySQLSupplierFuelDaoImpl) createDAO(MySQLSupplierFuelDaoImpl.class); } public MySQLSupplierMiscDaoImpl getSupplierMiscDao() throws DaoException { return (MySQLSupplierMiscDaoImpl) createDAO(MySQLSupplierMiscDaoImpl.class); } public MySQLSupplierCashDaoImpl getSupplierCashDao() throws DaoException { return (MySQLSupplierCashDaoImpl) createDAO(MySQLSupplierCashDaoImpl.class); } public MySQLSupplierWithdrawalDaoImpl getSupplierWithdrawalDao() throws DaoException { return (MySQLSupplierWithdrawalDaoImpl) createDAO(MySQLSupplierWithdrawalDaoImpl.class); } public MySQLInTransactionDaoImpl getInTransactionDao() throws DaoException { return (MySQLInTransactionDaoImpl) createDAO(MySQLInTransactionDaoImpl.class); } public MySQLInTransactionLineDaoImpl getInTransactionLineDao() throws DaoException { return (MySQLInTransactionLineDaoImpl) createDAO(MySQLInTransactionLineDaoImpl.class); } public MySQLSalesDaoImpl getSalesDao() throws DaoException { return (MySQLSalesDaoImpl) createDAO(MySQLSalesDaoImpl.class); } public MySQLSalesLineDaoImpl getSalesLineDao() throws DaoException { return (MySQLSalesLineDaoImpl) createDAO(MySQLSalesLineDaoImpl.class); } public MySQLSalesBucketDaoImpl getSalesBucketDao() throws DaoException { return (MySQLSalesBucketDaoImpl) createDAO(MySQLSalesBucketDaoImpl.class); } public MySQLSupplierSummaryDaoImpl getSupplierSummaryDao() throws DaoException { return (MySQLSupplierSummaryDaoImpl) createDAO(MySQLSupplierSummaryDaoImpl.class); } public MySQLSupplierSummarySavingDaoImpl getSupplierSummarySavingDao() throws DaoException { return (MySQLSupplierSummarySavingDaoImpl) createDAO(MySQLSupplierSummarySavingDaoImpl.class); } public MySQLSystemDaoImpl getSystemDao() throws DaoException { return (MySQLSystemDaoImpl) createDAO(MySQLSystemDaoImpl.class); } }
[ "ivyyip@IVYs-MacBook-Pro.local" ]
ivyyip@IVYs-MacBook-Pro.local
6feeac085ae07179af6f2af173d1d1db23bb31f0
a1a15238fc09c8b19504deb6d2610d3d315e7430
/SequenceEquation.java
fb19c90fd9fd6f1bd8e48c60b4765a92f50a702a
[]
no_license
Mrd278/Codeforces_Java
d84b53e1afe66dd468cb4b878be31e8e8c779e65
b0984f2b74e3a1c75d7de3ef0b33c86dc39e8d91
refs/heads/master
2020-12-27T15:45:13.641177
2020-07-15T10:19:34
2020-07-15T10:19:34
237,956,866
2
0
null
null
null
null
UTF-8
Java
false
false
1,238
java
import java.util.Arrays; import java.util.Scanner; public class SequenceEquation { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] p = new int[n]; for(int i = 0; i < n; i++) p[i] = sc.nextInt(); int[] result = solve(p); for(int value:result) System.out.println(value); //System.out.print(Arrays.binarySearch(p, 4)); sc.close(); } public static int findIndex(int arr[], int t) { // if array is Null if (arr == null) { return -1; } // find length of array int len = arr.length; int i = 0; // traverse in the array while (i < len) { // if the i-th element is t // then return the index if (arr[i] == t) { return i; } else { i = i + 1; } } return -1; } public static int[] solve(int[] p) { int[] res = new int[p.length]; for(int i = 0; i < p.length; i++) res[i] = findIndex(p, findIndex(p, i+1) + 1) + 1; return res; } }
[ "mridul27gupta@gmail.com" ]
mridul27gupta@gmail.com
15c687946b8e07767ff87ff6cbd4acc494029df1
e4f358f1cb33855f4d1a87810c17611f63fb0523
/src/main/java/cl/accenture/curso_java/playlist/dao/UsuarioDAO.java
56fc5a9a143866f7fae18e42ad57a64c66a6d782
[]
no_license
juannfrancisco/playlist-web
1ee6c2bd9c41398d7b0132329351d3f7045d8f0f
a26ce3794d1598e9b1c3e1e903a249b1e02a0d6b
refs/heads/master
2021-08-20T08:48:40.424315
2017-11-28T16:53:27
2017-11-28T16:53:27
109,014,240
0
3
null
null
null
null
UTF-8
Java
false
false
3,612
java
/** * */ package cl.accenture.curso_java.playlist.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import cl.accenture.curso_java.playlist.modelo.Conexion; import cl.accenture.curso_java.playlist.modelo.ObjetoNoEncontradoException; import cl.accenture.curso_java.playlist.modelo.Perfil; import cl.accenture.curso_java.playlist.modelo.SinConexionException; import cl.accenture.curso_java.playlist.modelo.Usuario; /** * @author jmaldonado * */ public class UsuarioDAO { /** * * @param usuario * @return * @throws SQLException * @throws SinConexionException */ public static Usuario validar(Usuario usuario) throws SQLException, SinConexionException { PreparedStatement st = Conexion.getInstancia().prepareStatement( "select * from usuario where "+ "userName =? AND "+ "password = ?;"); st.setString(1, usuario.getNombreUsuario() ); st.setString(2, usuario.getPassword() ); ResultSet rs = st.executeQuery(); if( rs.next() ){ Perfil perfil =PerfilDAO.obtenerPerfil( rs.getInt("id_perfil") ) ; usuario.setPerfil(perfil); usuario.setUltimoIngreso( rs.getDate("ultimoIngreso") ); usuario.setIntentosFallidos( rs.getInt("intentosFallidos" ) ); return usuario; } throw new ObjetoNoEncontradoException("Usuario y/o password incorrectos"); } /** * * @return * @throws SinConexionException * @throws SQLException */ public static List<Usuario> obtenerUsuarios() throws SQLException, SinConexionException { List<Usuario> usuarios = new ArrayList<Usuario>(); PreparedStatement st = Conexion.getInstancia().prepareStatement( "select * from usuario"); ResultSet rs = st.executeQuery(); while( rs.next() ){ Usuario usuario = new Usuario(); Perfil perfil =PerfilDAO.obtenerPerfil( rs.getInt("id_perfil") ) ; usuario.setPerfil(perfil); usuario.setNombreUsuario( rs.getString("userName") ); usuario.setUltimoIngreso( rs.getTimestamp("ultimoIngreso") ); usuario.setIntentosFallidos( rs.getInt("intentosFallidos" ) ); usuarios.add( usuario ); } return usuarios; } /** * * @param usuario * @throws SinConexionException * @throws SQLException */ public static void eliminarUsuario(Usuario usuario) throws SQLException, SinConexionException { PreparedStatement st = Conexion.getInstancia().prepareStatement( "delete from usuario where userName = ?;"); st.setString(1, usuario.getNombreUsuario() ); st.executeUpdate(); } /** * * @param usuario * @throws SQLException * @throws SinConexionException */ public static void actualizarUltimoIngreso( Usuario usuario ) throws SQLException, SinConexionException{ PreparedStatement st = Conexion.getInstancia().prepareStatement( "update usuario set ultimoIngreso=? where userName = ?;"); st.setTimestamp(1, new Timestamp( new java.util.Date().getTime() )); // st.setDate(1, new Date( new java.util.Date().getTime() )); st.setString( 2, usuario.getNombreUsuario()); st.executeUpdate(); } /** * * @param usuario * @throws SQLException * @throws SinConexionException */ public static void agregarUsuario(Usuario usuario) throws SQLException, SinConexionException { PreparedStatement st = Conexion.getInstancia().prepareStatement( "insert into usuario (userName, password, id_perfil ) values(?,?, ?);"); st.setString(1,usuario.getNombreUsuario() ); st.setString(2,usuario.getPassword() ); st.setInt(3, usuario.getPerfil().getId()); st.executeUpdate(); } }
[ "juan.maldonado.leon@gmail.com" ]
juan.maldonado.leon@gmail.com
434738889287bd8c7046ff6b9b4e414b14794181
19a7d4f2ed3122464a50165612803ee088880346
/Prueba/Ejercicio_Operadores.java
74571076dc2d2216d16e852485eee04b0fdc146a
[]
no_license
JoseRicardoJimenez/Java_Exercise
06a1969c3af4f0e46da0bf850488dedf0b13aaa8
770f5e642acbf2379f9ec84fb2cb9869149c3c44
refs/heads/master
2023-05-13T22:28:29.354674
2021-05-28T04:45:19
2021-05-28T04:45:19
69,976,417
0
0
null
null
null
null
UTF-8
Java
false
false
3,975
java
package Prueba; import java.util.Scanner; public class Ejercicio_Operadores { Scanner ing = new Scanner(System.in); public float Ejercicio_2() { //Salario semanal de un empleado int Htrabajadas; float Shora, Stotal; System.out.println("Horas trabajadas por el empleado: "); Htrabajadas = ing.nextInt(); System.out.println("Salario por hora del trabajador: "); Shora = ing.nextFloat(); Stotal = Htrabajadas * Shora; System.out.println("El salario total del empleado es de: " + Stotal); return 0; } public int Ejercicio_3() { //Averiguar la cantidad de dinero float guillermo, luis, juan, tres; System.out.println("Ingresar Dinero de Guillermo"); guillermo = ing.nextFloat(); luis = guillermo / 2; juan = (luis + guillermo) / 2; tres = luis + guillermo + juan; System.out.println("Guillermo tiene: " + guillermo + " Luis tiene: " + luis + " Juan tiene: " + juan + " Total: " + tres); return 0; } public double Ejercicio_4(){ //Salario mensual de un vendedor final int Smensual=1000; int Avendidos,Vauto; double Comision,Stotal; System.out.println("Autos vendidos: "); Avendidos = ing.nextInt(); Comision = 150*Avendidos; for(int x=0; x<Avendidos; x++){ System.out.println("Valor del auto "+x+1+": "); Vauto=ing.nextInt(); Comision = Comision+(Vauto*.05); } Stotal=Smensual+Comision; System.out.println("El salario total es de: "+Stotal); return 0; } public int Ejercicio_5(){ //Calificacion final de un estudiante double Participacion, Eparcial1, Eparcial2, Efinal, Cfinal; System.out.println("Participacion: "); Participacion=ing.nextDouble(); System.out.println("Examen Parcial 1: "); Eparcial1=ing.nextDouble(); System.out.println("Examen parcial 2: "); Eparcial2=ing.nextDouble(); System.out.println("Examen final: "); Efinal=ing.nextDouble(); Participacion = Participacion*.10; Eparcial1 = Eparcial1*.25; Eparcial2 = Eparcial2*.25; Efinal = Efinal*.40; Cfinal = Participacion+Eparcial1+Eparcial2+Efinal; System.out.println("La calificacion final del estudiante es: "+Cfinal); return 0; } public int Ejercicio_6(){ double a, b, resultado; System.out.println("Ingrese el valor de a: "); a=ing.nextDouble(); System.out.println("Ingrese el valor de b: "); b=ing.nextDouble(); resultado = Math.pow(a, 2) + Math.pow(b, 2) + (2*a*b); System.out.println("El resultado es: "+resultado); return 0; } public int Ejercicio_7(){ int Thoras,Semana,dia,hora; System.out.println("Ingrese una cantidad de horas: "); Thoras = ing.nextInt(); Semana=Thoras/168; dia = Thoras%168/24; hora = Thoras%24; System.out.println("Semanas: "+Semana+" Días: "+dia+" Horas: "+hora); return 0; } public int Ejercicio_8(){ double a,b,c,resultado1,resultado2; System.out.println("Dame el valor de a: "); a = ing.nextDouble(); System.out.println("Dame el valor de b: "); b = ing.nextDouble(); System.out.println("Dame el valor de c: "); c = ing.nextDouble(); resultado1 = (-b+Math.sqrt(Math.pow(b, 2) - (4*a*c)))/(2*a); resultado2 = (-b-Math.sqrt(Math.pow(b, 2) - (4*a*c)))/(2*a); System.out.println("\nLa raiz 1 es: "+resultado1); System.out.println("\nLa raiz 2 es: "+resultado2); return 0; } }
[ "joserjc.96@gmail.com" ]
joserjc.96@gmail.com
ecf18f9c2fcd94c51d03c95e31ee4ba5962ee1c3
aa10edf2189da5e9918d672da7800458dc2cb816
/HackerRank/src/interviewkit/warmup/SockMerchant.java
475d5cec2c6a97d9052f19a9e66ff82976ea8fcd
[]
no_license
Hemalatha09/Coding
28e9247fa767d47e663700230c7e474e526ab1eb
5296e17445618cdf7184ec2417de2b4a42dc7a68
refs/heads/master
2020-08-09T12:36:14.638441
2019-10-09T16:39:27
2019-10-09T16:39:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,827
java
package interviewkit.warmup; import java.util.*; public class SockMerchant { // Complete the sockMerchant function below. static int sockMerchant(int n, int[] ar) { Set<Integer> sockMap = new HashSet<>(); int pairs = 0; for (int i=0;i <n; i++){ if (sockMap.contains(ar[i])) { pairs++; sockMap.remove(ar[i]); } else { sockMap.add(ar[i]); } } return pairs; } public static void sockMerchant(String[] args) { int n = 9; int[] ar = {10,20,20,10,10,30,50,10,20}; int result = sockMerchant(n, ar); System.out.println(result); } } /* John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is . Function Description Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. sockMerchant has the following parameter(s): n: the number of socks in the pile ar: the colors of each sock Input Format The first line contains an integer , the number of socks represented in . The second line contains space-separated integers describing the colors of the socks in the pile. Constraints where Output Format Return the total number of matching pairs of socks that John can sell. Sample Input 9 10 20 20 10 10 30 50 10 20 Sample Output 3 Explanation sock.png John can match three pairs of socks. */
[ "anjanashankar9@gmail.com" ]
anjanashankar9@gmail.com
d8ac84be6bbce7ac3d5f5a1f0e0fba655e66b6dc
ec67ea62dbc0fa30ee42065aa92ca53ee4b25a04
/FCMDemo/app/src/main/java/com/adityadua/fcmdemo/MyFirebaseMessagingService.java
c31d796608d4c08c560851a071483431ee64854a
[]
no_license
aditya-dua/Android28July
6de5004e0e494dadd896186cd866eed878e5abf0
18781fd19fcd31be8ebd70bff48f21812dff7526
refs/heads/master
2021-07-17T05:16:47.517747
2017-10-24T17:25:56
2017-10-24T17:25:56
100,294,024
0
0
null
null
null
null
UTF-8
Java
false
false
1,910
java
package com.adityadua.fcmdemo; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; /** * Created by AdityaDua on 12/10/17. */ public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMessaging"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // Fire a notification Log.d(TAG,"From ::"+remoteMessage.getFrom()); Log.d(TAG,"Notification / Message Body :"+remoteMessage.getNotification().getBody()); sendNotification(remoteMessage.getNotification().getBody()); } private void sendNotification(String body){ Intent intent = new Intent(this,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificaBuilder= new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Push Notification") .setContentText(body) .setAutoCancel(true) .setSound(soundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0,notificaBuilder.build()); } }
[ "adityaduatechm@gmail.com" ]
adityaduatechm@gmail.com
82ed972ff9f02787050fff1c4891f735eb3f964f
9603aec554b90f3dd56f6b65b5f9812a1ddb8f58
/01_java/src/ch04_repetition/exam/Quiz15.java
891f7293c8093d5bad090881f5b4ad0cb39767c4
[]
no_license
kimtrue/verita
90700d848ab7d2051f3b89c9a9ba8cbcf1cbc16b
fb85fb54937f5882652b198a5e7454d02d4e2bf9
refs/heads/master
2022-12-14T10:28:25.884166
2019-10-29T11:19:27
2019-10-29T11:19:27
210,785,743
0
0
null
2022-12-04T15:07:08
2019-09-25T07:44:51
HTML
UTF-8
Java
false
false
1,354
java
/** 화면에서 행의 수와 열의 수를 입력 받아 아래와 같은 형식으로 출력되는 프로그램을 작성하시오 주의 사항 : 출력 행이 홀수일 경우 문자( "<" )를 먼저 출력, 짝수일 경우 문자( ">" )를 먼저 출력 출력형식 > 출력할 행의 수를 입력하세요(1-10) : 4 출력할 열의 수를 입력하세요(1-10) : 3 >>> <<< >>> <<< 출력형식 > 출력할 행의 수를 입력하세요(1-10) : 3 출력할 열의 수를 입력하세요(1-10) : 3 <<< >>> <<< */ package ch04_repetition.exam; import java.util.Scanner; public class Quiz15 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("출력할 행의 수를 입력하세요(1-10) : "); int num1 = sc.nextInt(); System.out.print("출력할 열의 수를 입력하세요(1-10) : "); int num2 = sc.nextInt(); // String hol = "<"; // String jjak = ">"; for(int i = 1; i <= num1; i++) { for(int j = 0; j < num2; j++) { if (num1 % 2 == 0) System.out.print(">"); System.out.print("<"); } System.out.println(); } // for(int j = 1; j < num2; j++) // //System.out.print(j); // // { if(j % 2 == 0) { // System.out.printf("%s", jjak); // } // else // System.out.printf("%s",hol); // } } }
[ "kjs3597@naver.com" ]
kjs3597@naver.com
c55740c1d221aca7164d94a84c58a4aa4a21f762
708148e391d38875da09716fd6062c0059e164f9
/GuruxXML2PDU/gurux.dlms.java/development/src/main/java/gurux/dlms/objects/GXDLMSModemInitialisation.java
571667383adaf499979d107f6ca87f0041f9d7e4
[]
no_license
BlockWorksCo/Playground
87bf2cdadbc33f020e5d8fb7f3ff875f054ad77d
c968e22cd923ee184fe9362905a4d58e9f69cb27
refs/heads/master
2021-01-23T14:39:05.530058
2020-05-13T22:21:54
2020-05-13T22:21:54
22,513,247
1
0
null
2021-01-04T22:59:52
2014-08-01T14:25:57
C
UTF-8
Java
false
false
1,900
java
// // -------------------------------------------------------------------------- // Gurux Ltd // // // // Filename: $HeadURL$ // // Version: $Revision$, // $Date$ // $Author$ // // Copyright (c) Gurux Ltd // //--------------------------------------------------------------------------- // // DESCRIPTION // // This file is a part of Gurux Device Framework. // // Gurux Device Framework is Open Source 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; version 2 of the License. // Gurux Device Framework 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. // // More information of Gurux products: http://www.gurux.org // // This code is licensed under the GNU General Public License v2. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt //--------------------------------------------------------------------------- package gurux.dlms.objects; public class GXDLMSModemInitialisation { private String request; private String response; private int delay; public final String getRequest() { return request; } public final void setRequest(final String value) { request = value; } public final String getResponse() { return response; } public final void setResponse(final String value) { response = value; } public final int getDelay() { return delay; } public final void setDelay(final int value) { delay = value; } @Override public final String toString() { return request + " " + response + " " + delay; } }
[ "Steve@BlockWorks.co" ]
Steve@BlockWorks.co
6bea7a23bd68e106cd0637284eab194210db54ff
a5d4fdafa9a90d01282a2db0f954329e01de5836
/alfresco-dropbox-repo/src/main/java/org/alfresco/dropbox/service/polling/DropboxPollerImpl.java
124d3697b56db5a91e39a8f02ad3fcf8dd0e7041
[ "Apache-2.0" ]
permissive
jottley/alfresco-dropbox-integration
acd675e1eaef6c65be90fbb1cdabae5099741fbf
f9fac13b7a7a0f2969f1f959641e24749fb49294
refs/heads/master
2020-04-09T04:04:39.328430
2012-08-19T03:43:13
2012-08-19T03:43:13
32,124,745
0
1
null
null
null
null
UTF-8
Java
false
false
24,207
java
/* * Copyright 2011-2012 Alfresco Software 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. * * This file is part of an unsupported extension to Alfresco. */ package org.alfresco.dropbox.service.polling; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import org.alfresco.dropbox.DropboxConstants; import org.alfresco.dropbox.exceptions.NotModifiedException; import org.alfresco.dropbox.service.DropboxService; import org.alfresco.model.ContentModel; import org.alfresco.repo.search.impl.lucene.LuceneQueryParserException; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.service.cmr.model.FileFolderService; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ContentIOException; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.cmr.search.ResultSet; import org.alfresco.service.cmr.search.SearchService; import org.alfresco.service.transaction.TransactionService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.extensions.webscripts.Status; import org.springframework.extensions.webscripts.WebScriptException; import org.springframework.social.dropbox.api.Metadata; /** * * * @author Jared Ottley */ public class DropboxPollerImpl implements DropboxPoller { private static final Log log = LogFactory.getLog(DropboxPollerImpl.class); private SearchService searchService; private NodeService nodeService; private FileFolderService fileFolderService; private TransactionService transactionService; private DropboxService dropboxService; private static final String CMIS_DROPBOX_SITES_QUERY = "SELECT * FROM st:site AS S JOIN db:syncable AS O ON S.cmis:objectId = O.cmis:objectId"; private static final String CMIS_DROPBOX_DOCUMENTS_QUERY = "SELECT D.* FROM cmis:document AS D JOIN db:dropbox AS O ON D.cmis:objectId = O.cmis:objectId"; private static final String CMIS_DROPBOX_FOLDERS_QUERY = "SELECT F.* FROM cmis:folder AS F JOIN db:dropbox AS O ON F.cmis:objectId = O.cmis:objectId"; private static final NodeRef MISSING_NODE = new NodeRef("missing://missing/missing"); public void setSearchService(SearchService searchService) { this.searchService = searchService; } public void setNodeService(NodeService nodeService) { this.nodeService = nodeService; } public void setFileFolderService(FileFolderService fileFolderService) { this.fileFolderService = fileFolderService; } public void setTransactionService(TransactionService transactionService) { this.transactionService = transactionService; } public void setDropboxService(DropboxService dropboxService) { this.dropboxService = dropboxService; } public void execute() { log.debug("Dropbox poller initiated."); // TODO where should the authentication and transactions go? AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() { public Object doWork() throws Exception { RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { List<NodeRef> sites = getSites(); List<NodeRef> folders = null; List<NodeRef> documents = null; if (sites != null) { for (NodeRef site : sites) { if (!isSyncing(site)) { log.debug("Processing Content in " + nodeService.getProperty(site, ContentModel.PROP_NAME)); try { syncOn(site); folders = getFolders(site); documents = getDocuments(site); if (documents != null) { // If the document is the child of a synced folder...we want to work on the folder as a // full collection and not the document as an independent element Iterator<NodeRef> i = documents.iterator(); while (i.hasNext()) { NodeRef document = i.next(); if (folders.contains(nodeService.getPrimaryParent(document).getParentRef())) { i.remove(); } } if (documents.size() > 0) { for (NodeRef document : documents) { updateNode(document); } } } if (folders.size() > 0) { for (NodeRef folder : folders) { log.debug("Looking for updates/new content in " + nodeService.getProperty(folder, ContentModel.PROP_NAME)); try { Metadata metadata = dropboxService.getMetadata(folder); // Get the list of the content returned. List<Metadata> list = metadata.getContents(); for (Metadata child : list) { String name = child.getPath().replaceAll(Matcher.quoteReplacement(metadata.getPath() + "/"), ""); NodeRef childNodeRef = fileFolderService.searchSimple(folder, name); if (childNodeRef == null) { addNode(folder, child, name); } else { updateNode(childNodeRef, child); } } metadata = dropboxService.getMetadata(folder); dropboxService.persistMetadata(metadata, folder); } catch (NotModifiedException nme) { // TODO } } } } finally { syncOff(site); log.debug("End processing " + nodeService.getProperty(site, ContentModel.PROP_NAME)); documents = null; folders = null; } } } } return null; } }; transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false); return null; } }, AuthenticationUtil.getAdminUserName()); } private List<NodeRef> getSites() { List<NodeRef> sites = new ArrayList<NodeRef>(); ResultSet resultSet = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<ResultSet>() { public ResultSet doWork() throws Exception { ResultSet resultSet = null; try { resultSet = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_CMIS_ALFRESCO, CMIS_DROPBOX_SITES_QUERY); } catch (LuceneQueryParserException lqpe) { // This is primarily to handle the case where the dropbox model has not been added to solr yet. Incidentally it // catches other failures too ;) log.info("Unable to perform site query: " + lqpe.getMessage()); } return resultSet; } }, AuthenticationUtil.getAdminUserName()); // TODO Hopefully one day this will go away --Open Bug?? try { if (resultSet.length() > 0) { if (!resultSet.getNodeRef(0).equals(MISSING_NODE)) { sites = resultSet.getNodeRefs(); log.debug("Sites with Dropbox content: " + sites); } } } finally { resultSet.close(); } return sites; } private List<NodeRef> getDocuments(final NodeRef nodeRef) { List<NodeRef> documents = Collections.synchronizedList(new ArrayList<NodeRef>()); ResultSet resultSet = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<ResultSet>() { public ResultSet doWork() throws Exception { ResultSet resultSet = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_CMIS_ALFRESCO, CMIS_DROPBOX_DOCUMENTS_QUERY + " WHERE IN_TREE(D, '" + nodeRef + "')"); return resultSet; } }, AuthenticationUtil.getAdminUserName()); try { // TODO Hopefully one day this will go away --Open Bug?? if (resultSet.length() > 0) { if (!resultSet.getNodeRef(0).equals(MISSING_NODE)) { documents = resultSet.getNodeRefs(); log.debug("Documents synced to Dropbox: " + documents); } } } finally { resultSet.close(); } return documents; } private List<NodeRef> getFolders(final NodeRef nodeRef) { List<NodeRef> folders = Collections.synchronizedList(new ArrayList<NodeRef>()); ResultSet resultSet = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<ResultSet>() { public ResultSet doWork() throws Exception { ResultSet resultSet = searchService.query(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, SearchService.LANGUAGE_CMIS_ALFRESCO, CMIS_DROPBOX_FOLDERS_QUERY + " WHERE IN_TREE(F, '" + nodeRef + "')"); return resultSet; } }, AuthenticationUtil.getAdminUserName()); try { // TODO Hopefully one day this will go away --Open Bug?? if (resultSet.length() > 0) { if (!resultSet.getNodeRef(0).equals(MISSING_NODE)) { folders = resultSet.getNodeRefs(); log.debug("Folders synced to Dropbox: " + folders); } } } finally { resultSet.close(); } return folders; } private void updateNode(final NodeRef nodeRef) { Metadata metadata = dropboxService.getMetadata(nodeRef); updateNode(nodeRef, metadata); } private void updateNode(final NodeRef nodeRef, final Metadata metadata) { AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() { public Object doWork() throws Exception { RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { if (nodeService.getType(nodeRef).equals(ContentModel.TYPE_FOLDER)) { try { Metadata metadata = dropboxService.getMetadata(nodeRef); // Get the list of the content returned. List<Metadata> list = metadata.getContents(); for (Metadata child : list) { String name = child.getPath().replaceAll(Matcher.quoteReplacement(metadata.getPath() + "/"), ""); NodeRef childNodeRef = fileFolderService.searchSimple(nodeRef, name); if (childNodeRef == null) { addNode(nodeRef, child, name); } else { updateNode(childNodeRef, child); } } metadata = dropboxService.getMetadata(nodeRef); dropboxService.persistMetadata(metadata, nodeRef); } catch (NotModifiedException nme) { } } else { Serializable rev = nodeService.getProperty(nodeRef, DropboxConstants.Model.PROP_REV); if (!metadata.getRev().equals(rev)) { Metadata metadata = null; try { metadata = dropboxService.getFile(nodeRef); } catch (ContentIOException cio) { cio.printStackTrace(); } if (metadata != null) { dropboxService.persistMetadata(metadata, nodeRef); } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Dropbox metadata maybe out of sync for " + nodeRef); } } } return null; } }; transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false); return null; } }, AuthenticationUtil.getAdminUserName()); } private void addNode(final NodeRef parentNodeRef, final Metadata metadata, final String name) { AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() { public Object doWork() throws Exception { NodeRef nodeRef = null; if (metadata.isDir()) { RetryingTransactionCallback<NodeRef> txnWork = new RetryingTransactionCallback<NodeRef>() { public NodeRef execute() throws Exception { NodeRef nodeRef = null; nodeRef = fileFolderService.create(parentNodeRef, name, ContentModel.TYPE_FOLDER).getNodeRef(); Metadata metadata = dropboxService.getMetadata(nodeRef); List<Metadata> list = metadata.getContents(); for (Metadata child : list) { String name = child.getPath().replaceAll(Matcher.quoteReplacement(metadata.getPath() + "/"), ""); addNode(nodeRef, child, name); } return nodeRef; } }; nodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false); } else { log.debug("Adding " + metadata.getPath() + " to Alfresco"); RetryingTransactionCallback<NodeRef> txnWork = new RetryingTransactionCallback<NodeRef>() { public NodeRef execute() throws Exception { NodeRef nodeRef = null; try { nodeRef = fileFolderService.create(parentNodeRef, name, ContentModel.TYPE_CONTENT).getNodeRef(); Metadata metadata = dropboxService.getFile(nodeRef); dropboxService.persistMetadata(metadata, parentNodeRef); } catch (ContentIOException cio) { cio.printStackTrace(); } return nodeRef; } }; nodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false); } dropboxService.persistMetadata(metadata, nodeRef); return null; } }, AuthenticationUtil.getAdminUserName()); } private boolean isSyncing(final NodeRef nodeRef) { Boolean syncing = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Boolean>() { public Boolean doWork() throws Exception { RetryingTransactionCallback<Boolean> txnWork = new RetryingTransactionCallback<Boolean>() { public Boolean execute() throws Exception { boolean syncing = false; if (nodeRef != null) { List<ChildAssociationRef> childAssoc = nodeService.getChildAssocs(nodeRef, DropboxConstants.Model.ASSOC_SYNC_DETAILS, DropboxConstants.Model.DROPBOX); if (childAssoc.size() == 1) { syncing = Boolean.valueOf(nodeService.getProperty(childAssoc.get(0).getChildRef(), DropboxConstants.Model.PROP_SYNCING).toString()); } } return syncing; } }; boolean syncing = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false); return syncing; } }, AuthenticationUtil.getAdminUserName()); return syncing; } private void syncOn(NodeRef site) { sync(site, true); } private void syncOff(NodeRef site) { sync(site, false); } private void sync(final NodeRef site, final boolean sync) { AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>() { public Object doWork() throws Exception { RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { if (nodeService.hasAspect(site, DropboxConstants.Model.ASPECT_SYNCABLE)) { List<ChildAssociationRef> childAssoc = nodeService.getChildAssocs(site, DropboxConstants.Model.ASSOC_SYNC_DETAILS, DropboxConstants.Model.DROPBOX); if (childAssoc.size() == 1) { nodeService.setProperty(childAssoc.get(0).getChildRef(), DropboxConstants.Model.PROP_SYNCING, sync); } } return null; } }; transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false); return null; } }, AuthenticationUtil.getAdminUserName()); } }
[ "jared.ottley@alfresco.com" ]
jared.ottley@alfresco.com
ae82efff42f5ec8ea3fd39da7f6e4e3d7ef1f99b
40c419c31b0f0ed392ee9d9d41973b6a777a8efb
/tags/start/JOpenPlatformManager/src/org/dyndns/widerstand/openplatformmanager/DeleteJPanel.java
18e398de3d7cfdd3213acf0564559b83314d6d07
[ "BSD-3-Clause" ]
permissive
pradeepk/globalplatform
c62e5b5711e8b96d5be98fa6aa7028dc821870ce
839afc6381ea7217721116aed8ef7df4086930dc
refs/heads/master
2021-01-10T04:36:14.314098
2013-03-04T18:24:59
2013-03-04T18:24:59
8,510,372
0
1
null
null
null
null
UTF-8
Java
false
false
12,174
java
/* * DeleteJPanel.java * * Created on 21. Februar 2005, 09:26 */ package org.dyndns.widerstand.openplatformmanager; import java.io.File; import java.io.IOException; import javax.swing.*; import org.dyndns.widerstand.OpenPlatform.*; import java.util.*; /** * * @author Widerstand */ public class DeleteJPanel extends javax.swing.JPanel { private MainJFrame parent; private ArrayList<JCheckBox> checkBoxList = new ArrayList<JCheckBox>(10); /** Creates new form DeleteJPanel */ public DeleteJPanel(MainJFrame parent) { this.parent = parent; 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. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jScrollPane1 = new javax.swing.JScrollPane(); jPanel8 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); setBorder(new javax.swing.border.CompoundBorder(null, new javax.swing.border.CompoundBorder(new javax.swing.border.TitledBorder("Delete Application"), new javax.swing.border.EmptyBorder(new java.awt.Insets(5, 5, 5, 5))))); jPanel8.setLayout(new java.awt.GridBagLayout()); jPanel7.setLayout(new javax.swing.BoxLayout(jPanel7, javax.swing.BoxLayout.Y_AXIS)); jPanel2.setLayout(new java.awt.GridLayout(0, 5)); jPanel2.setBorder(new javax.swing.border.CompoundBorder(new javax.swing.border.TitledBorder("Card Manager"), new javax.swing.border.EmptyBorder(new java.awt.Insets(5, 5, 5, 5)))); jPanel2.setMinimumSize(new java.awt.Dimension(600, 36)); jPanel2.setPreferredSize(new java.awt.Dimension(600, 36)); jPanel7.add(jPanel2); jPanel1.setLayout(new java.awt.GridLayout(0, 5)); jPanel1.setBorder(new javax.swing.border.CompoundBorder(new javax.swing.border.TitledBorder("Executable Load Files"), new javax.swing.border.EmptyBorder(new java.awt.Insets(5, 5, 5, 5)))); jPanel7.add(jPanel1); jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.Y_AXIS)); jPanel3.setBorder(new javax.swing.border.CompoundBorder(new javax.swing.border.TitledBorder("Applications"), new javax.swing.border.EmptyBorder(new java.awt.Insets(5, 5, 5, 5)))); jPanel4.setLayout(new java.awt.GridLayout(0, 5)); jPanel4.setBorder(new javax.swing.border.CompoundBorder(new javax.swing.border.TitledBorder("Security Domains"), new javax.swing.border.EmptyBorder(new java.awt.Insets(5, 5, 5, 5)))); jPanel3.add(jPanel4); jPanel5.setLayout(new java.awt.GridLayout(0, 5)); jPanel5.setBorder(new javax.swing.border.CompoundBorder(new javax.swing.border.TitledBorder("Applications"), new javax.swing.border.EmptyBorder(new java.awt.Insets(5, 5, 5, 5)))); jPanel3.add(jPanel5); jPanel7.add(jPanel3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel8.add(jPanel7, gridBagConstraints); jPanel6.setLayout(new java.awt.GridBagLayout()); jPanel6.setAlignmentY(0.0F); jButton1.setText("Delete Application(s)"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel6.add(jButton1, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); jPanel8.add(jPanel6, gridBagConstraints); jScrollPane1.setViewportView(jPanel8); add(jScrollPane1, java.awt.BorderLayout.CENTER); } // </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed byte[][] AIDs; int i=0; for (int j=0; j<checkBoxList.size(); j++) { if (((JCheckBox)checkBoxList.get(j)).isSelected()) i++; } AIDs = new byte[i][]; i=0; byte[] AID; for (int j=0; j<checkBoxList.size(); j++) { JCheckBox checkBox = (JCheckBox)checkBoxList.get(j); if (checkBox.isSelected()) { AID = OPSPUtil.bytesFromHexString(checkBox.getText()); AIDs[i++] = AID; } } int approve = javax.swing.JOptionPane.showConfirmDialog(this, "Do you really want delete the application(s)?", "Delete confirmation", javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE); if (approve != javax.swing.JOptionPane.YES_OPTION) return; try { Class parameterTypes[] = new Class[] {Long.TYPE, OPSPSecurityInfo.class, OPSPCardConnectionInfo.class, byte[][].class}; Object parameters[] = new Object[] {parent.session.cardHandle, parent.session.secInfo, parent.session.cardInfo, AIDs}; OPSPReceiptData receiptData[] = (OPSPReceiptData[])WaitForMethodJDialog.showDialog(parent, "org.dyndns.widerstand.OpenPlatform.OPSPWrapper", "deleteApplet", null, parameterTypes, parameters); if (receiptData != null) { for (int j=0; j < receiptData.length; j++) { final JFileChooser fc = new JFileChooser(); int ret = fc.showSaveDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { try { File file = fc.getSelectedFile(); OPSPUtil.saveOPSPReceiptData(file, receiptData[j]); } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(this, e.getMessage(), "I/O Error", javax.swing.JOptionPane.ERROR_MESSAGE); parent.refreshStatus(); return; } } } } } catch (Exception e) { for (int j=0; j<AIDs.length; j++) { byte[][] AIDsTemp = new byte[1][]; AIDsTemp[0] = AIDs[j]; try { Class parameterTypes[] = new Class[] {Long.TYPE, OPSPSecurityInfo.class, OPSPCardConnectionInfo.class, byte[][].class}; Object parameters[] = new Object[] {parent.session.cardHandle, parent.session.secInfo, parent.session.cardInfo, AIDsTemp}; OPSPReceiptData receiptData[] = (OPSPReceiptData[])WaitForMethodJDialog.showDialog(parent, "org.dyndns.widerstand.OpenPlatform.OPSPWrapper", "deleteApplet", null, parameterTypes, parameters); if (receiptData != null) { for (int k=0; k < receiptData.length; k++) { final JFileChooser fc = new JFileChooser(); int ret = fc.showSaveDialog(this); if (ret == JFileChooser.APPROVE_OPTION) { try { File file = fc.getSelectedFile(); OPSPUtil.saveOPSPReceiptData(file, receiptData[k]); } catch (IOException ex) { javax.swing.JOptionPane.showMessageDialog(this, ex.getMessage(), "I/O Error", javax.swing.JOptionPane.ERROR_MESSAGE); parent.refreshStatus(); return; } } } } } catch (OPSPException ex) { javax.swing.JOptionPane.showMessageDialog(this, ex.getMessage(), "Open Platform Error", javax.swing.JOptionPane.ERROR_MESSAGE); parent.refreshStatus(); return; } catch (Exception ex) { javax.swing.JOptionPane.showMessageDialog(this, ex.getMessage(), "Generel Error", javax.swing.JOptionPane.ERROR_MESSAGE); parent.refreshStatus(); return; } } } parent.refreshStatus(); }//GEN-LAST:event_jButton1ActionPerformed public void refresh() { JCheckBox checkBox; jPanel2.removeAll(); jPanel1.removeAll(); jPanel4.removeAll(); jPanel5.removeAll(); checkBoxList.clear(); for (OPSPApplicationData appData : parent.session.cardManager) { checkBox = new JCheckBox(OPSPUtil.toHexString(appData.getAID())); jPanel2.add(checkBox); checkBoxList.add(checkBox); } for (OPSPApplicationData appData : parent.session.loadFiles) { checkBox = new JCheckBox(OPSPUtil.toHexString(appData.getAID())); jPanel1.add(checkBox); checkBoxList.add(checkBox); } for (OPSPApplicationData appData : parent.session.securityDomains) { checkBox = new JCheckBox(OPSPUtil.toHexString(appData.getAID())); jPanel4.add(checkBox); checkBoxList.add(checkBox); } for (OPSPApplicationData appData : parent.session.applications) { checkBox = new JCheckBox(OPSPUtil.toHexString(appData.getAID())); jPanel5.add(checkBox); checkBoxList.add(checkBox); } jPanel8.revalidate(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
[ "(no author)@f4f2cb91-632f-4d2c-bd03-4b3085b5da43" ]
(no author)@f4f2cb91-632f-4d2c-bd03-4b3085b5da43
5c7cf67b5a8bbcd25b2bd74873f00107132859ed
2ae93957b9ff9471551b5834e7ed21e71c20abba
/app/src/main/java/com/sit/kaikiliService/activity/HomeScreenActivity.java
311cea670f6c3d872dfc083ef0fed7a2852b079d
[]
no_license
syerragunta/Kaikili_Android_App
73e8302d095de41248dbbc3624bce557e7f18340
0490c49c7744e80651ab14de4ca16443a2555c04
refs/heads/master
2020-04-23T05:42:47.471056
2019-02-28T20:38:39
2019-02-28T20:38:44
170,926,802
0
0
null
null
null
null
UTF-8
Java
false
false
35,561
java
package com.sit.kaikiliService.activity; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import com.sit.kaikiliService.R; import com.sit.kaikiliService.comman.CircularImageView; import com.sit.kaikiliService.font.TextViewEuphemiaUCASBola; import com.sit.kaikiliService.font.TextViewEuphemiaUCASRegular; ======= ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 ======= >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/2/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/9/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/14/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/15/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/16/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/16/2019 V1 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/16/2019 V2 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/16/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/18/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/21/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/22/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/23/2019 ======= import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/25/2019 import android.support.design.widget.TabLayout; ======= import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; >>>>>>> 2/26/2019 ======= ======= >>>>>>> 2/28/2019 import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; <<<<<<< HEAD >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD import android.view.LayoutInflater; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD ======= import android.view.MenuItem; >>>>>>> 2/2/2019 ======= import android.view.MenuItem; >>>>>>> 2/9/2019 ======= import android.view.MenuItem; >>>>>>> 2/14/2019 ======= import android.view.MenuItem; >>>>>>> 2/15/2019 ======= import android.view.MenuItem; >>>>>>> 2/16/2019 ======= import android.view.MenuItem; >>>>>>> 2/16/2019 V1 ======= import android.view.MenuItem; >>>>>>> 2/16/2019 V2 ======= import android.view.MenuItem; >>>>>>> 2/16/2019 ======= import android.view.MenuItem; >>>>>>> 2/18/2019 ======= import android.view.MenuItem; >>>>>>> 2/21/2019 ======= import android.view.MenuItem; >>>>>>> 2/22/2019 ======= import android.view.MenuItem; >>>>>>> 2/23/2019 ======= import android.view.MenuItem; >>>>>>> 2/25/2019 ======= import android.view.MenuItem; >>>>>>> 2/26/2019 import android.view.View; ======= ======= >>>>>>> 2/28/2019 import android.view.MenuItem; import android.view.View; import com.sit.kaikiliService.KaikiliApplication; <<<<<<< HEAD >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 import com.sit.kaikiliService.R; import com.sit.kaikiliService.font.TextViewEuphemiaUCASRegular; import com.sit.kaikiliService.fragment.EarningsFragment; import com.sit.kaikiliService.fragment.NotificationFragment; import com.sit.kaikiliService.fragment.ProfileFragment; import com.sit.kaikiliService.fragment.ScheduledServicesFragment; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 1/29/2019 ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 ======= >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 import butterknife.Bind; import butterknife.ButterKnife; /** * Created by ketan patel on 28/1/2019. * ketan_patel25@yahoo.com * Sharva Infotech PVT LTD */ public class HomeScreenActivity extends BaseActivity { // implements NavigationView.OnNavigationItemSelectedListener { <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD // @Bind(R.id.menu_top_civ_profile) CircularImageView menu_top_civ_profile; // @Bind(R.id.menu_tv_top_userName) TextViewEuphemiaUCASRegular menu_tv_top_userName; // @Bind(R.id.menu_tv_top_ratingCount) TextViewEuphemiaUCASBola menu_tv_top_ratingCount; // @Bind(R.id.menu_tv_top_serviceCount) TextViewEuphemiaUCASBola menu_tv_top_serviceCount; // // // @Bind(R.id.menu_tv_addService) TextViewEuphemiaUCASRegular menu_tv_addService; // @Bind(R.id.menu_tv_serviceCatalogue) TextViewEuphemiaUCASRegular menu_tv_serviceCatalogue; // @Bind(R.id.menu_tv_serviceHistory) TextViewEuphemiaUCASRegular menu_tv_serviceHistory; // @Bind(R.id.menu_tv_payment) TextViewEuphemiaUCASRegular menu_tv_payment; // @Bind(R.id.menu_tv_profile) TextViewEuphemiaUCASRegular menu_tv_profile; // @Bind(R.id.menu_tv_contactUs) TextViewEuphemiaUCASRegular menu_tv_contactUs; // @Bind(R.id.menu_tv_logout) TextViewEuphemiaUCASRegular menu_tv_logout; ======= ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 @Bind(R.id.home_viewpager)ViewPager home_viewpager; @Bind(R.id.top_title)TextViewEuphemiaUCASRegular top_title; private Toolbar toolbar; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 1/29/2019 ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 ======= ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 @Bind(R.id.home_viewpager) ViewPager home_viewpager; @Bind(R.id.top_title) TextViewEuphemiaUCASRegular top_title; private Toolbar toolbar; private BottomNavigationView navigation; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= private DrawerLayout drawer ; >>>>>>> 2/22/2019 ======= private DrawerLayout drawer ; >>>>>>> 2/23/2019 ======= private DrawerLayout drawer ; >>>>>>> 2/25/2019 ======= private DrawerLayout drawer ; >>>>>>> 2/26/2019 ======= private DrawerLayout drawer ; private KaikiliApplication application; private SharedPreferences preferences; >>>>>>> 2/27/2019 ======= private DrawerLayout drawer ; private KaikiliApplication application; private SharedPreferences preferences; >>>>>>> 2/28/2019 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_home_screen ); ButterKnife.bind( this, this ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD Toolbar toolbar = (Toolbar) findViewById( R.id.toolbar ); ======= toolbar = (Toolbar) findViewById( R.id.toolbar ); >>>>>>> 1/29/2019 ======= toolbar = (Toolbar) findViewById( R.id.toolbar ); >>>>>>> 1/30/2019 ======= toolbar = (Toolbar) findViewById( R.id.toolbar ); >>>>>>> 1/31/2019 ======= toolbar = (Toolbar) findViewById( R.id.toolbar ); >>>>>>> 2/1/2019 setSupportActionBar( toolbar ); ======= ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 toolbar = (Toolbar) findViewById( R.id.toolbar ); setSupportActionBar( toolbar ); navigation = (BottomNavigationView) findViewById( R.id.navigation ); navigation.setOnNavigationItemSelectedListener( mOnNavigationItemSelectedListener ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 DrawerLayout drawer = (DrawerLayout) findViewById( R.id.drawer_layout ); ======= ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 toolbar = (Toolbar) findViewById( R.id.toolbar ); setSupportActionBar( toolbar ); ======= ======= >>>>>>> 2/28/2019 toolbar = (Toolbar) findViewById( R.id.toolbar ); setSupportActionBar( toolbar ); application = (KaikiliApplication) getApplicationContext(); preferences = application.getSharedPreferences(); <<<<<<< HEAD >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 navigation = (BottomNavigationView) findViewById( R.id.navigation ); navigation.setOnNavigationItemSelectedListener( mOnNavigationItemSelectedListener ); drawer = (DrawerLayout) findViewById( R.id.drawer_layout ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ); drawer.addDrawerListener( toggle ); toggle.syncState(); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD // NavigationView navigationView = (NavigationView) findViewById( R.id.nav_view ); // navigationView.setNavigationItemSelectedListener( this ); } ======= ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 // Create an adapter that knows which fragment should be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager()); home_viewpager.setAdapter(adapter); home_viewpager.setCurrentItem( 0 ); setUpToolbar("Home"); } public void setUpToolbar(final String title) { top_title.setText(title); ======= ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 // Create an adapter that knows which fragment should be shown on each page SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter( this, getSupportFragmentManager() ); home_viewpager.setAdapter( adapter ); home_viewpager.setCurrentItem( 0 ); setUpToolbar( "Schedule Service" ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD home_viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { public void onPageScrollStateChanged(int state) {} ======= ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 home_viewpager.addOnPageChangeListener( new ViewPager.OnPageChangeListener() { public void onPageScrollStateChanged(int state) { } <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } public void onPageSelected(int position) { // Check if this is the page you want. <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD if(position == 0){ navigation.setSelectedItemId(R.id.navigation_home); }else if (position ==1){ navigation.setSelectedItemId(R.id.navigation_notification); }else if (position ==2){ navigation.setSelectedItemId(R.id.navigation_earnings); }else if (position ==3){ navigation.setSelectedItemId(R.id.navigation_profile); } } }); ======= ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 if (position == 0) { navigation.setSelectedItemId( R.id.navigation_home ); } else if (position == 1) { navigation.setSelectedItemId( R.id.navigation_notification ); } else if (position == 2) { navigation.setSelectedItemId( R.id.navigation_earnings ); } else if (position == 3) { navigation.setSelectedItemId( R.id.navigation_profile ); } } } ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 } public void setUpToolbar(final String title) { top_title.setText( title ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 } <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD ======= >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 // private void setupTabIcons() { // // TextViewEuphemiaUCASRegular tabOne = (TextViewEuphemiaUCASRegular) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); // tabOne.setText("Home"); // tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_home, 0, 0); // home_sliding_tabs.getTabAt(0).setCustomView(tabOne); // // TextViewEuphemiaUCASRegular tabTwo = (TextViewEuphemiaUCASRegular) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); // tabTwo.setText("Notification"); // tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_notification, 0, 0); // home_sliding_tabs.getTabAt(1).setCustomView(tabTwo); // // TextViewEuphemiaUCASRegular tabThree = (TextViewEuphemiaUCASRegular) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); // tabThree.setText("Earnings"); // tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.earnings, 0, 0); // home_sliding_tabs.getTabAt(2).setCustomView(tabThree); // // TextViewEuphemiaUCASRegular tabFore = (TextViewEuphemiaUCASRegular) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); // tabFore.setText("Profile"); // tabFore.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.profile, 0, 0); // home_sliding_tabs.getTabAt(3).setCustomView(tabFore); // } <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 1/29/2019 ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 ======= >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById( R.id.drawer_layout ); if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } else { super.onBackPressed(); } } public void callAddService(View view) { <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/22/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/23/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/25/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/26/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/27/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/28/2019 Intent intent = new Intent( this, AddServiceActivity.class ); startActivity( intent ); } public void callServiceCatalogue(View view) { <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/22/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/23/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/25/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/26/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/27/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/28/2019 Intent intent = new Intent( this, ServiceCatalogueActivity.class ); startActivity( intent ); } <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // return super.onOptionsItemSelected( item ); // } // // @SuppressWarnings("StatementWithEmptyBody") // @Override // public boolean onNavigationItemSelected(MenuItem item) { // // Handle navigation view item clicks here. // int id = item.getItemId(); // DrawerLayout drawer = (DrawerLayout) findViewById( R.id.drawer_layout ); // drawer.closeDrawer( GravityCompat.START ); // return true; // } ======= ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 public void callTabHome(View view) { home_viewpager.setCurrentItem( 0 ); top_title.setText("Home"); } public void callTabNotification(View view) { home_viewpager.setCurrentItem(1); top_title.setText("Notification"); } public void callTabEarnings(View view) { home_viewpager.setCurrentItem(2); top_title.setText("Earnings"); } public void callTabProfile(View view) { home_viewpager.setCurrentItem(3); top_title.setText("Profile"); } ======= >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 public void callServiceHistory(View view) { // Intent intent = new Intent( this, ServiceCatalogueActivity.class ); // startActivity( intent ); ======= public void callServiceHistory(View view) { Intent intent = new Intent( this, ServiceHistoryActivity.class ); startActivity( intent ); >>>>>>> 2/21/2019 } public void callPaymentInfo(View view) { // Intent intent = new Intent( this, .class ); // startActivity( intent ); ======= ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 public void callServiceHistory(View view) { if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } Intent intent = new Intent( this, ServiceHistoryActivity.class ); startActivity( intent ); } public void callPaymentInfo(View view) { if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } Intent intent = new Intent( this, BankDetailsActivity.class ); startActivity( intent ); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 } public void callProfile(View view) { <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/22/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/23/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/25/2019 ======= if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } >>>>>>> 2/26/2019 ======= ======= >>>>>>> 2/28/2019 } public void callLogout(View view) { if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } SharedPreferences.Editor editor = preferences.edit(); editor.putString( "sp_id", "" ); editor.putString( "first_name", "" ); editor.putString( "last_name", "" ); editor.putString( "email", "" ); editor.putString( "dob", "" ); editor.putString( "gender", ""); editor.putString( "mobile_no", "" ); editor.commit(); Intent intent = new Intent(this,PhoneNoValidationActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); finish(); } public void callProfile(View view) { if (drawer.isDrawerOpen( GravityCompat.START )) { drawer.closeDrawer( GravityCompat.START ); } <<<<<<< HEAD >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 Intent intent = new Intent( this, ProfileEditActivity.class ); startActivity( intent ); } <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { private Context mContext; public SimpleFragmentPagerAdapter(Context context, FragmentManager fm) { <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD super(fm); ======= super( fm ); >>>>>>> 2/2/2019 ======= super( fm ); >>>>>>> 2/9/2019 ======= super( fm ); >>>>>>> 2/14/2019 ======= super( fm ); >>>>>>> 2/15/2019 ======= super( fm ); >>>>>>> 2/16/2019 ======= super( fm ); >>>>>>> 2/16/2019 V1 ======= super( fm ); >>>>>>> 2/16/2019 V2 ======= super( fm ); >>>>>>> 2/16/2019 ======= super( fm ); >>>>>>> 2/18/2019 ======= super( fm ); >>>>>>> 2/21/2019 ======= super( fm ); >>>>>>> 2/22/2019 ======= super( fm ); >>>>>>> 2/23/2019 ======= super( fm ); >>>>>>> 2/25/2019 ======= super( fm ); >>>>>>> 2/26/2019 ======= super( fm ); >>>>>>> 2/27/2019 ======= super( fm ); >>>>>>> 2/28/2019 mContext = context; } // This determines the fragment for each tab @Override public android.support.v4.app.Fragment getItem(int position) { if (position == 0) { return new ScheduledServicesFragment(); <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD } else if (position == 1){ return new NotificationFragment(); } else if (position == 2){ return new EarningsFragment(); } else if (position == 3){ ======= ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 } else if (position == 1) { return new NotificationFragment(); } else if (position == 2) { return new EarningsFragment(); } else if (position == 3) { <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 return new ProfileFragment(); } else { return new ScheduledServicesFragment(); } } // This determines the number of tabs @Override public int getCount() { return 4; } } <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 1/29/2019 ======= >>>>>>> 1/30/2019 ======= >>>>>>> 1/31/2019 ======= >>>>>>> 2/1/2019 ======= ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: if (home_viewpager.getCurrentItem() != 0) { home_viewpager.setCurrentItem( 0 ); top_title.setText( "Schedule Service" ); } return true; case R.id.navigation_notification: if (home_viewpager.getCurrentItem() != 1) { home_viewpager.setCurrentItem( 1 ); top_title.setText( "Notification" ); } return true; case R.id.navigation_earnings: if (home_viewpager.getCurrentItem() != 2) { home_viewpager.setCurrentItem( 2 ); top_title.setText( "Earnings" ); } return true; case R.id.navigation_profile: if (home_viewpager.getCurrentItem() != 3) { home_viewpager.setCurrentItem( 3 ); top_title.setText( "Profile" ); } return true; } return false; } }; <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD <<<<<<< HEAD >>>>>>> 2/2/2019 ======= >>>>>>> 2/9/2019 ======= >>>>>>> 2/14/2019 ======= >>>>>>> 2/15/2019 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/16/2019 V1 ======= >>>>>>> 2/16/2019 V2 ======= >>>>>>> 2/16/2019 ======= >>>>>>> 2/18/2019 ======= >>>>>>> 2/21/2019 ======= >>>>>>> 2/22/2019 ======= >>>>>>> 2/23/2019 ======= >>>>>>> 2/25/2019 ======= >>>>>>> 2/26/2019 ======= >>>>>>> 2/27/2019 ======= >>>>>>> 2/28/2019 }
[ "y.sreedhar@gmail.com" ]
y.sreedhar@gmail.com
e220e862c9be523f8a4a5e323ea7860dae948ccb
d5f09c7b0e954cd20dd613af600afd91b039c48a
/sources/com/facebook/stetho/inspector/elements/android/AndroidDocumentProviderFactory.java
87310d32bfcd4e63dc43e60773eef58f9fb8d84b
[]
no_license
t0HiiBwn/CoolapkRelease
af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3
a6a2b03e32cde0e5163016e0078391271a8d33ab
refs/heads/main
2022-07-29T23:28:35.867734
2021-03-26T11:41:18
2021-03-26T11:41:18
345,290,891
5
2
null
null
null
null
UTF-8
Java
false
false
2,450
java
package com.facebook.stetho.inspector.elements.android; import android.app.Application; import android.os.Handler; import android.os.Looper; import com.facebook.stetho.common.ThreadBound; import com.facebook.stetho.common.UncheckedCallable; import com.facebook.stetho.common.Util; import com.facebook.stetho.common.android.HandlerUtil; import com.facebook.stetho.inspector.elements.DescriptorProvider; import com.facebook.stetho.inspector.elements.DocumentProvider; import com.facebook.stetho.inspector.elements.DocumentProviderFactory; import java.util.List; public final class AndroidDocumentProviderFactory implements DocumentProviderFactory, ThreadBound { private final Application mApplication; private final List<DescriptorProvider> mDescriptorProviders; private final Handler mHandler = new Handler(Looper.getMainLooper()); public AndroidDocumentProviderFactory(Application application, List<DescriptorProvider> list) { this.mApplication = (Application) Util.throwIfNull(application); this.mDescriptorProviders = (List) Util.throwIfNull(list); } @Override // com.facebook.stetho.inspector.elements.DocumentProviderFactory public DocumentProvider create() { return new AndroidDocumentProvider(this.mApplication, this.mDescriptorProviders, this); } @Override // com.facebook.stetho.common.ThreadBound public boolean checkThreadAccess() { return HandlerUtil.checkThreadAccess(this.mHandler); } @Override // com.facebook.stetho.common.ThreadBound public void verifyThreadAccess() { HandlerUtil.verifyThreadAccess(this.mHandler); } @Override // com.facebook.stetho.common.ThreadBound public <V> V postAndWait(UncheckedCallable<V> uncheckedCallable) { return (V) HandlerUtil.postAndWait(this.mHandler, uncheckedCallable); } @Override // com.facebook.stetho.common.ThreadBound public void postAndWait(Runnable runnable) { HandlerUtil.postAndWait(this.mHandler, runnable); } @Override // com.facebook.stetho.common.ThreadBound public void postDelayed(Runnable runnable, long j) { if (!this.mHandler.postDelayed(runnable, j)) { throw new RuntimeException("Handler.postDelayed() returned false"); } } @Override // com.facebook.stetho.common.ThreadBound public void removeCallbacks(Runnable runnable) { this.mHandler.removeCallbacks(runnable); } }
[ "test@gmail.com" ]
test@gmail.com
b81dd271bb77249e2edf7fae34aed807c3914d51
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_79d5a8f82f78a42fe64c9077a3b810f9c15f2d9d/MyMediaPlayerActivity/2_79d5a8f82f78a42fe64c9077a3b810f9c15f2d9d_MyMediaPlayerActivity_s.java
2ea333f7932d7eabaade0f842de7cc0b4978fa65
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
8,108
java
package com.example.testapplication; import android.app.Activity; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.media.AudioManager; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MyMediaPlayerActivity extends Activity { WakeLock wakeLock; private static final String[] EXTENSIONS = {".mp3", ".mid", ".wav", ".ogg", ".mp4"}; //Playable Extensions List<String> trackNames; //Playable Track Titles List<String> trackArtworks; //Track artwork names AssetManager assets; //Assets (Compiled with APK) Music track; //currently loaded track Button btnPlay; //The play button will need to change from 'play' to 'pause', so we need an instance of it boolean isTuning; //is user currently jammin out, if so automatically start playing the next track int currentTrack; //index of current track selected int type; //0 for loading from assets, 1 for loading from SD card @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setVolumeControlStream(AudioManager.STREAM_MUSIC); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Lexiconda"); setContentView(R.layout.musicplayer); initialize(0); } @Override public void onResume() { super.onResume(); wakeLock.acquire(); } @Override public void onPause() { super.onPause(); wakeLock.release(); if (track != null) { if (track.isPlaying()) { track.pause(); isTuning = false; btnPlay.setBackgroundResource(R.drawable.play); } if (isFinishing()) { track.dispose(); finish(); } } else { if (isFinishing()) { finish(); } } } private void initialize(int type) { btnPlay = (Button) findViewById(R.id.btnPlay); btnPlay.setBackgroundResource(R.drawable.play); trackNames = new ArrayList<String>(); trackArtworks = new ArrayList<String>(); assets = getAssets(); currentTrack = 0; isTuning = false; this.type = type; addTracks(getTracks()); loadTrack(); } //Generate a String Array that represents all of the files found private String[] getTracks() { try { String[] temp = getAssets().list(""); return temp; } catch (IOException e) { e.printStackTrace(); } return null; } //Adds the playable files to the trackNames List private void addTracks(String[] temp) { if (temp != null) { for (int i = 0; i < temp.length; i++) { //Only accept files that have one of the extensions in the EXTENSIONS array if (trackChecker(temp[i])) { trackNames.add(temp[i]); trackArtworks.add(temp[i].substring(0, temp[i].length() - 4)); } } } } //Checks to make sure that the track to be loaded has a correct extenson private boolean trackChecker(String trackToTest) { for (int j = 0; j < EXTENSIONS.length; j++) { if (trackToTest.contains(EXTENSIONS[j])) { return true; } } return false; } //Loads the track by calling loadMusic private void loadTrack() { if (track != null) { track.dispose(); } if (trackNames.size() > 0) { track = loadMusic(type); } } //loads a Music instance using either a built in asset or an external resource private Music loadMusic(int type) { switch (type) { case 0: try { AssetFileDescriptor assetDescriptor = assets.openFd(trackNames.get(currentTrack)); return new Music(assetDescriptor); } catch (IOException e) { e.printStackTrace(); } return null; case 1: try { FileInputStream fis = new FileInputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), trackNames.get(currentTrack))); FileDescriptor fileDescriptor = fis.getFD(); return new Music(fileDescriptor); } catch (IOException e) { e.printStackTrace(); } return null; default: return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); createMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0: //Set Looping synchronized (this) { if (track.isLooping()) { track.setLooping(false); } else { track.setLooping(true); } } return true; case 1: //Stop Music synchronized (this) { track.switchTracks(); btnPlay.setBackgroundResource(R.drawable.play); } return true; default: return false; } } private void createMenu(Menu menu) { MenuItem miLooping = menu.add(0, 0, 0, "Looping"); { miLooping.setIcon(R.drawable.looping); } MenuItem miStop = menu.add(0, 1, 1, "Stop"); { miStop.setIcon(R.drawable.stop); } } public void click(View view) { int id = view.getId(); switch (id) { case R.id.btnPlay: synchronized (this) { if (isTuning) { isTuning = false; btnPlay.setBackgroundResource(R.drawable.play); track.pause(); } else { isTuning = true; btnPlay.setBackgroundResource(R.drawable.pause); playTrack(); } } return; case R.id.btnPrevious: setTrack(0); loadTrack(); playTrack(); return; case R.id.btnNext: setTrack(1); loadTrack(); playTrack(); return; default: return; } } private void setTrack(int direction) { if (direction == 0) { currentTrack--; if (currentTrack < 0) { currentTrack = trackNames.size() - 1; } } else if (direction == 1) { currentTrack++; if (currentTrack > trackNames.size() - 1) { currentTrack = 0; } } } //Plays the Track private void playTrack() { if (isTuning && track != null) { track.play(); } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
a7d77cc7dc7304195e88787874f6ee2bec9f7343
ecf4cf6f0e3cda94851b228742b6877fc8b02254
/backend/Assignment3_Backend/src/main/java/com/assignment1/Assignment3_Backend/dto/builder/MedicationListBuilder.java
984860a9e6c8e3b8c6fc895a733d1c2918f953e9
[]
no_license
Ioniqe/Online-Medication-Platform
c205359bb31468f130cfcda6fa2066434858a3c4
674bdd3ae91b9762526b6f0549fa3a36f01a191c
refs/heads/master
2023-04-19T20:33:04.035307
2021-05-09T20:40:37
2021-05-09T20:40:37
365,830,659
0
0
null
null
null
null
UTF-8
Java
false
false
883
java
package com.assignment1.DS2020_30441_Bozdog_Ioana_Assignment_3.dto.builder; import com.assignment1.DS2020_30441_Bozdog_Ioana_Assignment_3.dto.MedicationListDTO; import com.assignment1.DS2020_30441_Bozdog_Ioana_Assignment_3.entity.MedicationList; import com.assignment1.DS2020_30441_Bozdog_Ioana_Assignment_3.entity.MedicationPlan; public class MedicationListBuilder { public MedicationListBuilder() { } public static MedicationListDTO toMedicationListDTO(MedicationList medicationList){ return new MedicationListDTO(medicationList.getId(), medicationList.getStartInterval(), medicationList.getEndInterval()); } public static MedicationList toEntity(MedicationListDTO medicationListDTO, MedicationPlan medicationPlan){ return new MedicationList(medicationListDTO.getStartInterval(), medicationListDTO.getEndInterval(), medicationPlan); } }
[ "bozdogioana@yahoo.com" ]
bozdogioana@yahoo.com
a5f8efeac7c9f8ccf9799ef1867c0fba0097ddda
edb4528f327fb0656a10c673372a5bae3daeb236
/MavenProject/src/test/java/com/picnic/maven/MultipleWindowHandle.java
7f96ca8853dc9751837235ffa5d9610a5c214424
[]
no_license
Gopalakrishnanjm/firstdemo
630d532d9aaf486343e9b0a5457b6cf2cf7c6269
9d6507a1999071df2817385e857c75060970c58b
refs/heads/master
2023-08-07T12:17:30.238719
2021-09-20T07:08:15
2021-09-20T07:08:15
407,403,044
0
0
null
null
null
null
UTF-8
Java
false
false
2,013
java
package com.picnic.maven; import java.util.Iterator; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class MultipleWindowHandle { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\gopalakrishnanjm\\eclipse-workspace-seleniumTraining\\SeleniumProject\\drivers\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); //Launching the site. driver.get("http://demo.guru99.com/popup.php"); driver.manage().window().maximize(); driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click(); String MainWindow=driver.getWindowHandle(); // To handle all new opened window. Set<String> s1=driver.getWindowHandles(); Iterator<String> i1=s1.iterator(); while(i1.hasNext()) { String ChildWindow=i1.next(); if(!MainWindow.equalsIgnoreCase(ChildWindow)) { Thread.sleep(3000); // Switching to Child window driver.switchTo().window(ChildWindow); driver.findElement(By.name("emailid")) .sendKeys("gaurav.3n@gmail.com"); driver.findElement(By.name("btnLogin")).click(); // Closing the Child Window. driver.close(); } } // Switching to Parent window i.e Main Window. driver.switchTo().window(MainWindow); } }
[ "gopalakrishnanjm@maveric-systems.com" ]
gopalakrishnanjm@maveric-systems.com
330435d5b24a1d2224bd2a1f44cccf9a51e9f8fe
15ab87a5513fb3f8ee5b9a35b55e56a2257121ea
/etransaction-service/src/main/java/com/eventuate/example/etransaction/configuration/ETransactionConfiguration.java
470151287c477feaee1237b7d21128f7e9d2ce20
[]
no_license
camapac/spring-boot-eventuate-local-example
64aa01e4ddf701903c62d9dc3f19ebbe944c3dc4
5f8d1e6b5b37b1c0f0397c4aa2d3925786cb1839
refs/heads/master
2022-04-02T01:30:38.493474
2020-02-05T10:23:45
2020-02-05T10:23:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,436
java
package com.eventuate.example.etransaction.configuration; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import com.eventuate.example.entity.Transaction; import com.eventuate.example.etransaction.event.TransactionWorkflow; import com.eventuate.example.info.command.TransactionCommand; import io.eventuate.sync.AggregateRepository; import io.eventuate.sync.EventuateAggregateStore; import io.eventuate.javaclient.spring.EnableEventHandlers; @Configuration @EnableEventHandlers @ComponentScan public class ETransactionConfiguration { @Bean public HttpMessageConverters customConverters() { HttpMessageConverter<?> additional = new MappingJackson2HttpMessageConverter(); return new HttpMessageConverters(additional); } @Bean(name="transactionWorkflow") public TransactionWorkflow transactionWorkflow() { return new TransactionWorkflow(); } @Bean(name="transactionRepository") public AggregateRepository<Transaction, TransactionCommand> transactionRepository(EventuateAggregateStore eventStore) { return new AggregateRepository<>(Transaction.class, eventStore); } }
[ "doduyloi@gmail.com" ]
doduyloi@gmail.com
7407b91a36f44a69da17f892acdec45fa82553dc
6be59179379fd781ef5093b9fb42b0c61151100d
/src/br/com/View/TelaPrincipal.java
c87f30a1e7335e3ca97a91df7f69ebc87d8a18ca
[]
no_license
wagnerlim/APS-interface
5f3b2a044f3e1493c7cf5ce181771b174cd8d33d
14701089cda3b730916fbb87db65d18878ebc19d
refs/heads/master
2023-03-07T12:15:14.983700
2021-02-10T17:48:23
2021-02-10T17:48:23
337,779,027
0
0
null
null
null
null
ISO-8859-1
Java
false
false
12,057
java
package br.com.View; import java.awt.EventQueue; import java.util.List; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import br.com.UsuarioController.AlunosController; import br.com.modelo.Alunos; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import java.awt.event.ActionListener; import java.io.IOException; import java.sql.SQLException; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JComboBox; import java.awt.Font; import javax.swing.ImageIcon; import java.awt.Color; public class TelaPrincipal extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private DefaultTableModel modelo; private AlunosController AlunosController; private JTable table_1; private JLabel nomeLabel; private JLabel dataNascimentoLabel; private JLabel cursoLabel; private JLabel situacaoLabel; private JMenuItem adicionarAlunoMenuItem; /** * Launch the application. */ public static void main(String[] args) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { } EventQueue.invokeLater(new Runnable() { public void run() { try { TelaPrincipal frame = new TelaPrincipal(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public TelaPrincipal() { setResizable(false); this.AlunosController = new AlunosController(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 800, 500); // contentPane = new JPanel(); try { // "C:\\Users\\wagne\\Desktop\\Aps interface\\Prancheta 1.png" fundo para teste // "C:\\Users\\wagne\\Desktop\\Aps interface\\FundoTesteAPS.png" Outro fundo para teste contentPane = new FundoBg("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\Fundos de tela\\FundoTesteAPS.png"); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } setContentPane(contentPane); table_1 = new JTable(); table_1.setBounds(10, 218, 764, 169); modelo = (DefaultTableModel) table_1.getModel(); modelo.addColumn("RA"); modelo.addColumn("NOME"); modelo.addColumn("DATA DE NASCIMENTO"); modelo.addColumn("Nome Curso"); modelo.addColumn("Situação"); contentPane.setLayout(null); contentPane.add(table_1); JLabel raLabel = new JLabel("RA"); raLabel.setForeground(Color.BLACK); raLabel.setBounds(10, 204, 46, 14); contentPane.add(raLabel); nomeLabel = new JLabel("Aluno"); nomeLabel.setForeground(Color.BLACK); nomeLabel.setBounds(162, 204, 46, 14); contentPane.add(nomeLabel); dataNascimentoLabel = new JLabel("Data de Nascimento"); dataNascimentoLabel.setForeground(Color.BLACK); dataNascimentoLabel.setBounds(315, 204, 138, 14); contentPane.add(dataNascimentoLabel); cursoLabel = new JLabel("Curso"); cursoLabel.setForeground(Color.BLACK); cursoLabel.setBounds(468, 204, 46, 14); contentPane.add(cursoLabel); situacaoLabel = new JLabel("Situação"); situacaoLabel.setForeground(Color.BLACK); situacaoLabel.setBounds(619, 204, 93, 14); contentPane.add(situacaoLabel); JMenuBar menuBar = new JMenuBar(); menuBar.setBounds(0, 0, 794, 22); contentPane.add(menuBar); JMenu menuAlunos = new JMenu("Alunos"); menuAlunos.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\study.png")); menuBar.add(menuAlunos); // Item do menu Alunos, Adicionar adicionarAlunoMenuItem = new JMenuItem("Adicionar"); adicionarAlunoMenuItem.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\plus.png")); menuAlunos.add(adicionarAlunoMenuItem); // Item do menu Alunos, Remover JMenuItem RemoverAlunoMenu = new JMenuItem("Remover"); RemoverAlunoMenu.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\delete.png")); menuAlunos.add(RemoverAlunoMenu); JMenu mnNewMenu = new JMenu("Usuários"); mnNewMenu.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\user.png")); menuBar.add(mnNewMenu); JMenuItem AdicionarUsuarioMenuItem = new JMenuItem("Adicionar"); AdicionarUsuarioMenuItem .setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\userAdicionar.png")); mnNewMenu.add(AdicionarUsuarioMenuItem); JMenuItem removerUsuarioItem = new JMenuItem("Remover"); removerUsuarioItem .setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\userRemover.png")); mnNewMenu.add(removerUsuarioItem); JMenuItem mntmNewMenuItem = new JMenuItem("Log off"); mntmNewMenuItem.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\Log off.png")); mnNewMenu.add(mntmNewMenuItem); // Botão de atualizar a tabela JButton btnNewButton = new JButton("Atualizar"); btnNewButton.setIcon(new ImageIcon("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\icones Tela principal\\botao-atualizar.png")); btnNewButton.setBounds(637, 170, 115, 23); contentPane.add(btnNewButton); // Caixa de cursos JComboBox<String> cursoCombox = new JComboBox<String>(); cursoCombox.setBounds(23, 157, 138, 22); contentPane.add(cursoCombox); cursoCombox.addItem("Curso"); List<String> cursos = this.cursosListar(); for (String string : cursos) { cursoCombox.addItem(string); } // Caixa de Seleção de Situações da matricula JComboBox<String> SituacaoCombox = new JComboBox<String>(); SituacaoCombox.setBounds(184, 157, 138, 22); contentPane.add(SituacaoCombox); SituacaoCombox.addItem("Selecione"); List<String> Situacao = this.SituacaoListar(); for (String string : Situacao) { SituacaoCombox.addItem(string); } // Botão Alterar JButton AlterarBotao = new JButton("Alterar"); AlterarBotao.setBounds(10, 422, 89, 23); contentPane.add(AlterarBotao); JLabel cursosLabel = new JLabel("Cursos"); cursosLabel.setForeground(Color.BLACK); cursosLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); cursosLabel.setBounds(23, 143, 46, 14); contentPane.add(cursosLabel); JLabel matriculaLabel = new JLabel("Status"); matriculaLabel.setForeground(Color.BLACK); matriculaLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); matriculaLabel.setBounds(184, 143, 135, 14); contentPane.add(matriculaLabel); // Evento que acontece quando clica no botão Atualizar btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { limparTabela(); preencherTabelaComCurso(); } }); preencherTabelaComCurso(); // Evento que acontece quando clica no item Adicionar do menu alunos adicionarAlunoMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AdicionarAlunoFrame novaView = new AdicionarAlunoFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no item remover do menu alunos RemoverAlunoMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RemoverAlunoFrame novaView = new RemoverAlunoFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no item Adicionar do menu Usuarios AdicionarUsuarioMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AdicionarUsuarioFrame novaView = new AdicionarUsuarioFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no item Remover menu do Usuarios removerUsuarioItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { RemoverUsuarioFrame novaView = new RemoverUsuarioFrame(); novaView.setVisible(true); novaView.setLocationRelativeTo(null); } }); // Evento que acontece quando clica no botão alterar AlterarBotao.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cursoCombox.getSelectedItem().equals("Curso") == true) { JOptionPane.showMessageDialog(null, "Selecione um curso", "Nenhum curso Selecionado", JOptionPane.ERROR_MESSAGE); } else if (SituacaoCombox.getSelectedItem().equals("Selecione") == true) { JOptionPane.showMessageDialog(null, "Selecione um status da matricula", "Nenhum Status da matricula foi selecionado", JOptionPane.ERROR_MESSAGE); } else { try { alterar(converterCursoEmInt(String.valueOf(cursoCombox.getSelectedItem())), converterSituacaoEmInt(String.valueOf(SituacaoCombox.getSelectedItem()))); JOptionPane.showMessageDialog(null, "Alterações aplicadas!", "Alterações feitas", JOptionPane.INFORMATION_MESSAGE); // limparTabela(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); //Evento do botão log off mntmNewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); NovaTelaLogin novaTelaLogin = new NovaTelaLogin(); novaTelaLogin.setVisible(true); } }); } // METODOS DA VIEW public void preencherTabela() { List<Alunos> alunos = ListarAlunos(); try { for (Alunos aluno : alunos) { modelo.addRow(new Object[] { aluno.getRA(), aluno.getNome(), aluno.getDataNascimento() }); } } catch (Exception e) { throw e; } } private void limparTabela() { int UltimaTabela = modelo.getRowCount() - 1; System.out.println(UltimaTabela); modelo.removeRow(UltimaTabela); modelo.getDataVector().clear(); } private void preencherTabelaComCurso() { List<Alunos> alunos = ListarAlunosComCurso(); try { for (Alunos aluno : alunos) { modelo.addRow(new Object[] { aluno.getRA(), aluno.getNome(), aluno.getDataNascimento(), aluno.getCursonome(), aluno.getSituacaoNome() }); } } catch (Exception e) { throw e; } } private List<Alunos> ListarAlunos() { return this.AlunosController.listar(); } private List<Alunos> ListarAlunosComCurso() { return this.AlunosController.listarComCurso(); } private List<String> cursosListar() { return AlunosController.listarCursos(); } private List<String> SituacaoListar() { return AlunosController.listarSituacao(); } public int converterCursoEmInt(String CursoNome) throws SQLException { return this.AlunosController.ConversorCursoNomeId(CursoNome); } public int converterSituacaoEmInt(String Situacaonome) throws SQLException { return this.AlunosController.ConversosSituacaoId(Situacaonome); } private void alterar(int Cursoid, int Situacaoid) { Object objetoDaLinha = (Object) modelo.getValueAt(table_1.getSelectedRow(), table_1.getSelectedColumn()); if (objetoDaLinha instanceof String) { String ra = (String) objetoDaLinha; String nome = (String) modelo.getValueAt(table_1.getSelectedRow(), 1); String data_nascimento = (String) modelo.getValueAt(table_1.getSelectedRow(), 2); this.AlunosController.Alterar(nome, data_nascimento, Cursoid, Situacaoid, ra); } else { JOptionPane.showMessageDialog(this, "Por favor, selecionar o RA"); } } }
[ "wagnerlima695@hotmail.com" ]
wagnerlima695@hotmail.com
c33f24d37190299232b77d4160dc5c01af5e54d7
2b2de55c2fb0f407f59f9b80c3946728c8f5cb33
/src/edu/ecsu/csc360/JChatModel.java
302d4ee141a24f7c761b3544cd21f4c35009b4ec
[]
no_license
cuadrosjb/CSC360-Assignment-I---A-Chat-GUI-Application
17549a088fc6201ffe62e4253696f2b9beb9a8d4
ae51f5c4cad49aa439d99345120a0857a8189352
refs/heads/master
2021-01-19T21:12:12.866376
2016-09-25T22:04:56
2016-09-25T22:04:56
69,120,983
0
0
null
null
null
null
UTF-8
Java
false
false
2,521
java
package edu.ecsu.csc360; /* import java.awt.Button; import java.awt.Frame; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; */ import javax.jms.BytesMessage; import javax.jms.MapMessage; import javax.jms.Message; import javax.jms.ObjectMessage; import javax.jms.StreamMessage; import javax.jms.TextMessage; public class JChatModel { boolean connected = false; String outgoingMsgTypeString; int outgoingMsgType; JChatMessageCreator outgoingMsgCreator; JChatMessageCreator txtMsgCreator, objMsgCreator, mapMsgCreator, bytesMsgCreator, streamMsgCreator; public JChatMessageCreator getMessageCreator(int type) { switch (type) { case JChatDialog.MSG_TYPE_TEXT: if (txtMsgCreator == null) { txtMsgCreator = new JChatTextMessageCreator(); } return (txtMsgCreator); case JChatDialog.MSG_TYPE_OBJECT: if (objMsgCreator == null) { objMsgCreator = new JChatObjMessageCreator(); } return (objMsgCreator); case JChatDialog.MSG_TYPE_MAP: if (mapMsgCreator == null) { mapMsgCreator = new JChatMapMessageCreator(); } return (mapMsgCreator); case JChatDialog.MSG_TYPE_BYTES: if (bytesMsgCreator == null) { bytesMsgCreator = new JChatBytesMessageCreator(); } return (bytesMsgCreator); case JChatDialog.MSG_TYPE_STREAM: if (streamMsgCreator == null) { streamMsgCreator = new JChatStreamMessageCreator(); } return (streamMsgCreator); } return (null); } public JChatMessageCreator getMessageCreator(Message msg) { if (msg instanceof TextMessage) { if (txtMsgCreator == null) { txtMsgCreator = new JChatTextMessageCreator(); } return (txtMsgCreator); } else if (msg instanceof ObjectMessage) { if (objMsgCreator == null) { objMsgCreator = new JChatObjMessageCreator(); } return (objMsgCreator); } else if (msg instanceof MapMessage) { if (mapMsgCreator == null) { mapMsgCreator = new JChatMapMessageCreator(); } return (mapMsgCreator); } else if (msg instanceof BytesMessage) { if (bytesMsgCreator == null) { bytesMsgCreator = new JChatBytesMessageCreator(); } return (bytesMsgCreator); } else if (msg instanceof StreamMessage) { if (streamMsgCreator == null) { streamMsgCreator = new JChatStreamMessageCreator(); } return (streamMsgCreator); } return (null); } }
[ "cuadrosjb@gmail.com" ]
cuadrosjb@gmail.com
1e30b4b556df9ee48eb01de45c0eb64751d01bbf
bc4d88cf490020416afb86720cec067b32c9ff26
/src/main/java/test/ExcampleTest.java
cbac2ba813b7527a96d731cb436684378a860c72
[]
no_license
guofengma/AskMeServer
132ae605471adcdf8552b8cbcb732c15ecae91fd
c3adf2bd2210ede91c794b636bc8ae440bb4e0c7
refs/heads/master
2020-04-25T13:22:08.861566
2018-09-02T05:46:16
2018-09-02T05:46:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
550
java
package test; import org.junit.After; import org.junit.Before; import org.junit.Test; import static junit.framework.TestCase.assertEquals; /** * Created by Administrator on 2018/9/2 0002. */ public class ExcampleTest { @Before public void before() { System.out.println("befor"); } @After public void after() { System.out.println("after"); } @Test public void test1(){ System.out.println("test.."); int i = 2+3; assertEquals(5,i); } }
[ "zhanyd@sina.com" ]
zhanyd@sina.com
476b7c0efc2bb4b7a5d4ca64560aac8c29e65c26
647508b7af8ef6b10573157841e73ccc7ee90b86
/Practice_Chap12(제어자와 다형성)/src/example06/Book.java
78b9de337de396fcf1a1214196925b28c3ea8479
[]
no_license
kimlsy2444/JAVA-Study
f2fc8cd47879db1c84cd5ca0bf5572b58bebcc70
592d0d603f2ba6f953950189eb1c3151474490fd
refs/heads/main
2023-07-16T19:17:43.457984
2021-09-02T09:14:36
2021-09-02T09:14:36
402,355,464
1
0
null
null
null
null
UHC
Java
false
false
810
java
package example06; public class Book extends Product { private int ISBN; private String title; private String author; public Book(int proudctID, String description, String maker, int price, int iSBN, String title, String author) { super(proudctID, description, maker, price); this.ISBN = iSBN; this.title = title; this.author = author; } public int getISBN() { return ISBN; } public String getTitle() { return title; } public String getAuthor() { return author; } @Override public void showInfo() { super.showInfo(); // 조상크래스의 매서드를 명시적 호출 System.out.println("국제표준도서번호 >> " + this.getISBN()); System.out.println("책 제목 >> " + this.getTitle()); System.out.println("저자 >> " + this.getAuthor()); } }
[ "[Github" ]
[Github
db4c9ec08fa889f53c6db79bbba669362cc2ff1b
9f7f51739dbddf02db6ad2d203c928479a0d5353
/course-api/src/main/java/com/sharat/springbootstarter/controller/TopicController.java
0a5d821906740c4bed97e8aaea5ae9416c563cd5
[ "Apache-2.0" ]
permissive
sinsharat/RestfulSpringBootProjects
7aeb9059ada131b7f9f4164f378380cbcb9709fc
420715c688d42d669410a9f5aea0431ef949a2f3
refs/heads/master
2022-08-27T13:16:54.008669
2022-08-11T18:40:48
2022-08-11T18:41:30
232,589,113
0
0
null
null
null
null
UTF-8
Java
false
false
1,420
java
package com.sharat.springbootstarter.controller; import java.util.List; 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.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.sharat.springbootstarter.info.Topic; import com.sharat.springbootstarter.service.TopicService; @RestController public class TopicController { @Autowired TopicService topicService; @RequestMapping(method = RequestMethod.GET, path = {"/topics"}) public List<Topic> getAllTopics() { return topicService.getAllTopics(); } @RequestMapping(method = RequestMethod.GET, path = {"/topics/{id}"}) public Topic getTopic(@PathVariable String id) { return topicService.getTopic(id); } @RequestMapping(method = RequestMethod.POST, path= {"/topics"}) public void addTopic(@RequestBody Topic topic) { topicService.addTopic(topic); } @RequestMapping(method = RequestMethod.PUT, path= {"/topics"}) public void modifyTopic (@RequestBody Topic topic) { topicService.modifyTopic(topic); } @RequestMapping(method = RequestMethod.DELETE, path= {"topics/{id}"}) public void deleteTopic(@PathVariable String id) { topicService.deleteTopic(id); } }
[ "sinsharat@gmail.com" ]
sinsharat@gmail.com
489e6593f73a99a62d3b7470c6c3b359e488cd74
21e25a7626b593fd80c572cdb5c8ebcbcdfe66a1
/leetcode/com/practice/easy/util/TreeNode.java
dc181097fd288edddcbd24507a3c710d077dd9a5
[]
no_license
prabhakaran302/online-coding-platforms
5e5cbe837d1cb579ce0c5e75b3541110a8f0e633
3997f735f0559d5b1c28d74502543b40ad966c92
refs/heads/master
2021-06-29T03:32:43.024444
2021-06-09T17:08:21
2021-06-09T17:08:21
235,970,566
0
0
null
null
null
null
UTF-8
Java
false
false
184
java
package com.practice.easy.util; public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val) { super(); this.val = val; } }
[ "prabhakaran.nivanil@gmail.com" ]
prabhakaran.nivanil@gmail.com
0a4e413efa2506d50ad9d42c7f50fe1a86962693
3e98bd275545853adbb4839cd3ad1063a88c560b
/Tanks_SS2012_Rainbowtank/lib/lib_src/eea/engine/action/basicactions/MoveBackwardAction.java
5c3a43e2d71f734eb61ec65424e7473dd3e1ebac
[]
no_license
peter89/TUD-SS2012-Tanks
4f728ef44245ac102072484e5a5cc5a15683e6fe
b8ad37b122285a495bbff872f2f5c0991a8a161a
refs/heads/master
2016-08-06T17:01:16.717725
2012-08-24T03:17:34
2012-08-24T03:17:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,731
java
package eea.engine.action.basicactions; import org.newdawn.slick.GameContainer; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.StateBasedGame; import eea.engine.component.Component; import eea.engine.interfaces.IMovement; /** * Actions können zu einem Event hinzugefügt werden. Tritt das Event ein, so werden alle * auf diesem Event registrierten Actions ausgefuehrt. * * Die Entitaet wird rueckwaerts der Bewegungsrichtung bewegt. */ public class MoveBackwardAction extends Movement implements IMovement{ /** * @param speed Geschwindigkeit der Rueckwaertsbewegung */ public MoveBackwardAction(float speed){ super(speed); } @Override public void update(GameContainer gc, StateBasedGame sb, int delta, Component event) { Vector2f position = getNextPosition(event.getOwnerEntity().getPosition(), speed, event.getOwnerEntity().getRotation(), delta);//event.getOwnerEntity().getPosition(); event.getOwnerEntity().setPosition(position); /* float rotation = event.getOwnerEntity().getRotation(); Vector2f position = event.getOwnerEntity().getPosition(); float hip = speed * delta; position.x -= hip * java.lang.Math.sin(java.lang.Math.toRadians(rotation)); position.y += hip *java.lang.Math.cos(java.lang.Math.toRadians(rotation)); */ } @Override public Vector2f getNextPosition(Vector2f position, float speed, float rotation, int delta) { Vector2f pos= new Vector2f(position); float hip = speed * delta; pos.x -= hip * java.lang.Math.sin(java.lang.Math.toRadians(rotation)); pos.y += hip *java.lang.Math.cos(java.lang.Math.toRadians(rotation)); return pos; } }
[ "Peter.tobias.kilian@googlemail.com" ]
Peter.tobias.kilian@googlemail.com
9ab0843a574de84cbcddfd883b3fadbc7e57becd
83c439bf68736a6fb331283397c559ba56b4d6b6
/Android/PreZenTainer/src/com/puregodic/android/prezentainer/DetailSettingActivity.java
aacfa142c807a1939b15bd21fd870fbd25f3c5c6
[]
no_license
5-SH/PREZENTAINER
03b61a8b94709fb1f993a37a88c3082d393b6f2f
0609e4c9fa8cc057da05bcca3c2d569d8b1051c4
refs/heads/master
2021-05-29T07:05:30.656733
2015-08-09T10:19:52
2015-08-09T10:19:52
null
0
0
null
null
null
null
UHC
Java
false
false
6,108
java
package com.puregodic.android.prezentainer; import java.util.ArrayList; import android.app.ActionBar.LayoutParams; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; public class DetailSettingActivity extends AppCompatActivity { public static int incrementID = 0; public static ArrayList<String> timeInterval = new ArrayList<String>(); public static ArrayList<EditText> editTextArr = new ArrayList<EditText>(); public static final int REQUEST_DETAIL = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detailsetting); final EditText num = (EditText)findViewById(R.id.num); final LinearLayout list =(LinearLayout)findViewById(R.id.list); Button btn = (Button)findViewById(R.id.btn); Button btnResult = (Button)findViewById(R.id.btnResult); //동적으로 원하는 갯수 만큼 edit text를 생성하는 확인 버튼 btn.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //이전값 삭제 timeInterval.clear(); editTextArr.clear(); list.removeAllViews(); incrementID = 0; //edittext 몇개 생성할 것인지 입력한 숫자 처리 String inputNumString = num.getText().toString(); final int inputNum = Integer.valueOf(inputNumString); //프레젠테이션 수가 너무 많으면 다시 물음 if (inputNum >= 100) { AlertDialog.Builder alert_confirm = new AlertDialog.Builder(DetailSettingActivity.this); alert_confirm.setMessage("입력하신 갯수가 맞습니까?").setCancelable(false).setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 'YES' -> 입력한대로 EditText 동적생성 for (int i = 0; i < inputNum; i++) { incrementID++; final EditText numAdd = new EditText(DetailSettingActivity.this); //edit text 설정 numAdd.setHint(incrementID + "번째 슬라이드"); numAdd.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); numAdd.setPadding(50, 10, 50, 10); numAdd.setBackgroundColor(Color.YELLOW); numAdd.setId(incrementID); numAdd.setInputType(0x00000002); //숫자키패드만 뜨도록 //edit text 뷰에 올리는 메소드 list.addView(numAdd, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); //list.addView(numAdd, i); editTextArr.add(numAdd); } } }).setNegativeButton("재입력", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 'No' -> 재입력 return; } }); AlertDialog alert = alert_confirm.create(); alert.show(); } else { //edit Text 동적생성 (100개를 넘지 않는 경우) for (int i = 0; i < inputNum; i++) { incrementID++; final EditText numAdd = new EditText(DetailSettingActivity.this); //edit text 설정 numAdd.setHint(incrementID + "번째 슬라이드"); numAdd.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); numAdd.setPadding(50, 10, 50, 10); numAdd.setBackgroundColor(Color.YELLOW); numAdd.setId(incrementID); numAdd.setInputType(0x00000002); //숫자키패드만 뜨도록 //edit text 뷰에 올리는 메소드 list.addView(numAdd, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); //list.addView(numAdd, i); editTextArr.add(numAdd); } } } }); //최종 결정된 time interval들을 입력하는 최종확인 버튼 btnResult.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { for (int i = 0; i < editTextArr.size(); i++) { // 사용자가 입력한 슬라이드시간 timeInteval에 입력 timeInterval.add(editTextArr.get(i).getText().toString()); Log.i("timeInterval", "tI size : " + timeInterval.size() + " tIvalue : " + timeInterval.get(i)); } //Intent intent = new Intent(DetailSettingActivity.this, SettingActivity.class); Intent intent = new Intent(); intent.putStringArrayListExtra("timeInterval", timeInterval); setResult(REQUEST_DETAIL, intent); finish(); } }); } }
[ "quki09@naver.com" ]
quki09@naver.com
635b2011b1a9e0ae47ca18cadf57c377123884f3
f0c8eb22449d567e8a215e84fbe68e4e8c5a0893
/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/CompositeFieldValidator.java
7aa075edb2a676235a671f65898f12ccbc27e41c
[ "Apache-2.0", "MIT", "BSD-3-Clause", "MIT-0", "CC-BY-2.5", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "GPL-1.0-or-later", "MPL-1.1" ]
permissive
apache/tapestry-5
6c8c9d5f1f28abe03f424b21b1ff96af9955f76d
b5bda40756c5e946901d18694a094f023ba6d2b5
refs/heads/master
2023-08-28T16:05:10.291603
2023-07-13T17:25:04
2023-07-13T17:25:04
4,416,959
89
103
Apache-2.0
2023-09-14T11:59:30
2012-05-23T07:00:11
Java
UTF-8
Java
false
false
1,700
java
// Copyright 2007, 2008 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.internal.services; import org.apache.tapestry5.FieldValidator; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.ValidationException; import java.util.List; /** * Aggregates together a number of field validator instances as a single unit. */ public final class CompositeFieldValidator implements FieldValidator { private final FieldValidator[] validators; public CompositeFieldValidator(List<FieldValidator> validators) { this.validators = validators.toArray(new FieldValidator[validators.size()]); } @SuppressWarnings("unchecked") public void validate(Object value) throws ValidationException { for (FieldValidator fv : validators) fv.validate(value); } public void render(MarkupWriter writer) { for (FieldValidator fv : validators) fv.render(writer); } public boolean isRequired() { for (FieldValidator fv : validators) { if (fv.isRequired()) return true; } return false; } }
[ "hlship@apache.org" ]
hlship@apache.org
1c499a1928a0b542a2e3fb0ae78648511bbb47c1
b7635ffe6a2a624ee84c1fd5f4425125c72b306a
/src/main/java/com/example/demo/service/OdmUserRepo.java
35a111e5453d4a7f8a3840171d570e059098764e
[]
no_license
FanGaoXS/springboot_ldap
c0b9c2a1863b778cef416b9b0054cade5a196688
0523a5e7ee72ff5b39b586c1326fa26f2105147f
refs/heads/master
2023-01-29T22:46:33.496086
2020-12-09T10:38:47
2020-12-09T10:38:47
315,501,835
0
0
null
null
null
null
UTF-8
Java
false
false
1,208
java
package com.example.demo.service; import com.example.demo.entry.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.core.LdapTemplate; import org.springframework.stereotype.Service; import java.util.List; import static org.springframework.ldap.query.LdapQueryBuilder.query; /** * Created with IntelliJ IDEA. * * @Auther: 吴青珂 * @Date: 2020/12/09/15:47 * @Description: */ @Service public class OdmUserRepo { @Autowired private LdapTemplate ldapTemplate; /* * 新增User * */ public User create(User user){ ldapTemplate.create(user); return user; } /* * 通过cn查询User * */ public User findByCn(String cn){ return ldapTemplate.findOne(query().where("cn").is(cn),User.class); } /* * 修改User * */ public User modifyUser(User user){ ldapTemplate.update(user); return user; } /* * 删除User * */ public void deleteUser(User user){ ldapTemplate.delete(user); } /* * 查询所有User * */ public List<User> findAll(){ return ldapTemplate.findAll(User.class); } }
[ "954278478@qq.com" ]
954278478@qq.com
45aa464809af834535056024683bd6cea01813c8
617155d7092fa9d5459f57632a8d885e64941918
/app/src/main/java/com/apps/multiboo/Screenshotone.java
c3a811c47d4123978d06df4168a7aeb26aa841c7
[]
no_license
soumyamads/MultiBoo
34a43738f35a041e8468f3ef42419ab582a12bf8
cd2d1c97d5c589ea625fc86add41530d283fa5b2
refs/heads/master
2021-01-10T03:42:03.951469
2016-02-17T08:31:50
2016-02-17T08:31:50
50,709,839
0
0
null
null
null
null
UTF-8
Java
false
false
2,541
java
package com.apps.multiboo; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.graphics.Typeface; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.apps.multiboo.R; /** * Created by soumya on 1/24/2016. */ public class Screenshotone extends Fragment { Typeface custom_font; TextView skip,next; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.screenshotone, container, false); skip=(TextView)v.findViewById(R.id.skip); next=(TextView)v.findViewById(R.id.next); custom_font = Typeface.createFromAsset(getActivity().getAssets(), "font/gretoon.ttf"); skip.setTypeface(custom_font); next.setTypeface(custom_font); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getActivity(),Menupage.class); startActivity(intent); } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Boolean Firstclick; SharedPreferences app_preferences = PreferenceManager .getDefaultSharedPreferences(getActivity()); SharedPreferences.Editor editor = app_preferences.edit(); Firstclick = app_preferences.getBoolean("Firstclick", true); if (Firstclick) { HowActivity.pageclick(1); editor.putBoolean("Firstclick", false); editor.commit(); }else{ //app open directly // Musiccontinue=true; HelpActivity.pageclick(1); } } }); return v; } public static Screenshotone newInstance(String text) { Screenshotone f = new Screenshotone(); // Bundle b = new Bundle(); // b.putString("msg", text); // // f.setArguments(b); return f; } }
[ "soumyamekm@gmail.com" ]
soumyamekm@gmail.com
2062b36e0d6668eb87d6554a2addfd668cb60722
38933bae7638a11fef6836475fef0d73e14c89b5
/magma-func-builder/src/test/java/eu/lunisolar/magma/func/build/function/to/LTieDblFunctionBuilderTest.java
ab5845f44426c6abaecb13af009465530df06da2
[ "Apache-2.0" ]
permissive
lunisolar/magma
b50ed45ce2f52daa5c598e4760c1e662efbbc0d4
41d3db2491db950685fe403c934cfa71f516c7dd
refs/heads/master
2023-08-03T10:13:20.113127
2023-07-24T15:01:49
2023-07-24T15:01:49
29,874,142
5
0
Apache-2.0
2023-05-09T18:25:01
2015-01-26T18:03:44
Java
UTF-8
Java
false
false
5,617
java
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2023 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.func.build.function.to; import eu.lunisolar.magma.asserts.func.FuncAttests; import eu.lunisolar.magma.func.supp.Be; import eu.lunisolar.magma.func.supp.check.Checks; import eu.lunisolar.magma.func.*; // NOSONAR import eu.lunisolar.magma.asserts.*; // NOSONAR import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import java.util.Objects;// NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import org.testng.Assert; import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR import org.testng.annotations.*; //NOSONAR import java.util.regex.Pattern; //NOSONAR import java.text.ParseException; //NOSONAR import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR import java.util.concurrent.atomic.AtomicInteger; //NOSONAR import java.util.function.*; //NOSONAR import static eu.lunisolar.magma.func.build.function.to.LTieDblFunctionBuilder.tieDblFunction; import static eu.lunisolar.magma.func.build.function.to.LTieDblFunctionBuilder.tieDblFunctionFrom; public class LTieDblFunctionBuilderTest<T>{ @Test public void testOtherwiseThrow() { try { LTieDblFunction<Integer> function = tieDblFunctionFrom(b-> b .build() ); function.applyAsInt(100,100,100d); Assert.fail("No exception was thrown."); } catch (Throwable e) { Assert.assertSame(e.getClass(), IllegalStateException.class); Assert.assertTrue(e.getMessage().contains("There is no case configured for the arguments (if any).")); } } @Test public void testHandlingCanBeSetOnlyOnce() { try { LTieDblFunction<Integer> function = tieDblFunctionFrom(b-> b .withHandling(h -> h.wrapIf(RuntimeException.class::isInstance, RuntimeException::new)) .build(h -> h.wrapIf(RuntimeException.class::isInstance, RuntimeException::new)) ); Assert.fail("No exception was thrown."); } catch (Throwable e) { Assert.assertSame(e.getClass(), UnsupportedOperationException.class); Assert.assertTrue(e.getMessage().contains("Handling is already set for this builder.")); } } @Test public void testHandling() { try { LTieDblFunction<Integer> function = tieDblFunctionFrom(b -> b .otherwise((a1,a2,a3) -> { throw new RuntimeException("ORIGINAL"); }) .build(h -> h.wrapIf(RuntimeException.class::isInstance, IllegalStateException::new, "NEW EXCEPTION")) ); function.applyAsInt(100,100,100d); Assert.fail("No exception was thrown."); } catch (Throwable e) { Assert.assertSame(e.getClass(), IllegalStateException.class); Assert.assertTrue(e.getMessage().contains("NEW EXCEPTION")); Assert.assertSame(e.getCause().getClass(), RuntimeException.class); } } @Test public void testBuild() { LTieDblFunction<Integer> function = tieDblFunctionFrom( b -> b .aCase(ce -> ce.of((a1,a2,a3) -> a1 == 0) .evaluate((a1,a2,a3) -> 0)) .inCase((a1,a2,a3) -> a1 > 0 && a1 < 10).evaluate((a1,a2,a3) -> 1) .inCase((a1,a2,a3) -> a1 > 10 && a1 < 20).evaluate((a1,a2,a3) -> 2) .otherwise((a1,a2,a3) -> 99) .build() ); FuncAttests.attestTieDblFunc(function) .doesApplyAsInt(0,0,0d).when(null).to(a -> a.mustEx(Be::equalEx, 0)) .doesApplyAsInt(5,5,5d).when(null).to(a -> a.mustEx(Be::equalEx, 1)) .doesApplyAsInt(15,15,15d).when(null).to(a -> a.mustEx(Be::equalEx, 2)) .doesApplyAsInt(10,10,10d).when(null).to(a -> a.mustEx(Be::equalEx, 99)) ; } }
[ "open@lunisolar.eu" ]
open@lunisolar.eu
89d8176ccec0d3f2181456f8eebd1efd1ca3f139
383ca8f0babc70b9f3cf6192ca2feb5b94f74b6d
/src/pddsh/Main3.java
7e34e91bf18c23cc5284016bc2b30c8d68a71123
[]
no_license
stianyu/CompanyOnlineJudge2020
8a8f810b9ec3a87f2c1030cab0a58113f0b2a479
396b3080f9b10307406a4aa63d5e5d751c003932
refs/heads/master
2023-08-22T12:42:31.144946
2021-10-13T14:27:26
2021-10-13T14:27:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package pddsh; import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int n = in.nextInt(); int m = in.nextInt(); int[] f = new int[m+1]; for( int i = 0; i < n; i++) { int c = in.nextInt(); int v = in.nextInt(); if (c > 0 && v > 0) { for(int j = c; j <= m; j++) { f[j] = Math.max(f[j], f[j-c] + v); } } } System.out.println(f[m]); } } }
[ "shengtianyu_wh@163.com" ]
shengtianyu_wh@163.com
0d480a26ca36fb02c672e939464e737279d8c4f5
62aaa67a468107022635b566cbcf1109d3e4e648
/huiyuan/src/private/nc/bs/pub/action/N_HK28_SAVEBASE.java
b015ddeff136eb06fa9a597bc3803c8e8f7bc5c5
[]
no_license
boblee821226/hongkun
f17a90221683f816f382443f5c223347b41afefc
46c02ab124924f2c976044c5f31e632f706e61cf
refs/heads/master
2021-06-25T03:57:28.516510
2021-02-22T05:42:07
2021-02-22T05:42:07
204,677,636
1
1
null
null
null
null
GB18030
Java
false
false
1,921
java
package nc.bs.pub.action; import nc.bs.framework.common.NCLocator; import nc.bs.pubapp.pf.action.AbstractPfAction; import nc.impl.pubapp.pattern.rule.IRule; import nc.impl.pubapp.pattern.rule.processer.CompareAroundProcesser; import nc.vo.jcom.lang.StringUtil; import nc.vo.pub.BusinessException; import nc.vo.pubapp.pattern.exception.ExceptionUtils; import nc.bs.hkjt.huiyuan.kazuofei.plugin.bpplugin.Hy_kazuofeiPluginPoint; import nc.vo.hkjt.huiyuan.kazuofei.KazuofeiBillVO; import nc.itf.hkjt.IHy_kazuofeiMaintain; public class N_HK28_SAVEBASE extends AbstractPfAction<KazuofeiBillVO> { @Override protected CompareAroundProcesser<KazuofeiBillVO> getCompareAroundProcesserWithRules( Object userObj) { CompareAroundProcesser<KazuofeiBillVO> processor = null; KazuofeiBillVO[] clientFullVOs = (KazuofeiBillVO[]) this.getVos(); if (!StringUtil.isEmptyWithTrim(clientFullVOs[0].getParentVO() .getPrimaryKey())) { processor = new CompareAroundProcesser<KazuofeiBillVO>( Hy_kazuofeiPluginPoint.SCRIPT_UPDATE); } else { processor = new CompareAroundProcesser<KazuofeiBillVO>( Hy_kazuofeiPluginPoint.SCRIPT_INSERT); } // TODO 在此处添加前后规则 IRule<KazuofeiBillVO> rule = null; return processor; } @Override protected KazuofeiBillVO[] processBP(Object userObj, KazuofeiBillVO[] clientFullVOs, KazuofeiBillVO[] originBills) { KazuofeiBillVO[] bills = null; try { IHy_kazuofeiMaintain operator = NCLocator.getInstance() .lookup(IHy_kazuofeiMaintain.class); if (!StringUtil.isEmptyWithTrim(clientFullVOs[0].getParentVO() .getPrimaryKey())) { bills = operator.update(clientFullVOs, originBills); } else { bills = operator.insert(clientFullVOs, originBills); } } catch (BusinessException e) { ExceptionUtils.wrappBusinessException(e.getMessage()); } return bills; } }
[ "441814246@qq.com" ]
441814246@qq.com
114191eeda0b2bcb8ea881cac08fbc8d117cead1
96495de9622faec1cf75517642ad725e93b8cb3c
/src/Aves.java
137aa3244ac9000889e4b257264cd1e8d4c8ecb0
[]
no_license
needarb/game-of-life
baade0bf0441b971b53b4544dfd8a760ebb0d4ba
d9d97b79278cddee3490d281d51dff3f4df1841d
refs/heads/master
2020-05-23T11:19:24.764497
2014-04-06T20:52:30
2014-04-06T20:52:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
66
java
/** * Created by needa_000 on 2/27/14. */ public class Aves { }
[ "needarb@gmail.com" ]
needarb@gmail.com
56a462d430c585e29d4f4eec65d51e85d84547e2
f52a67afd5727eb8b84eb73704d4035716487cd5
/Level1/src/main/java/lambda/sample/articles/Person.java
d34820bf95dfb3db5caba1451747982484057812
[]
no_license
rocksolidbasics/Practice
0418988aa74472ed7fd4d198d76643ee08291be2
9afa12da6f643dd33c3348f60c302a5f21ef7b94
refs/heads/master
2021-06-11T18:58:52.928566
2019-09-28T08:22:52
2019-09-28T08:22:52
135,718,638
0
0
null
2021-06-04T02:08:59
2018-06-01T13:05:56
Java
UTF-8
Java
false
false
1,492
java
package lambda.sample.articles; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Person { private String _givenName; private String _surname; private Gender _gender; private int _age; private Map<Integer, ArticleInfo> _selling = new ConcurrentHashMap<>(); private Map<Integer, ArticleInfo> _buying = new ConcurrentHashMap<>(); private int _discount; public String getGivenName() { return _givenName; } public void setGivenName(String givenName) { _givenName = givenName; } public String getSurname() { return _surname; } public void setSurname(String surname) { _surname = surname; } public Gender getGender() { return _gender; } public void setGender(Gender gender) { _gender = gender; } public boolean isFemale(){ return _gender == Gender.Female; } public int getAge() { return _age; } public void setAge(int age) { _age = age; } public boolean isVendor() { return _selling.size() > 0; } public int getDiscount() { return _discount; } public void setDiscount(int discount) { _discount = discount; } public Map<Integer, ArticleInfo> getSelling() { return _selling; } public void setSelling(Map<Integer, ArticleInfo> selling) { _selling = selling; } public Map<Integer, ArticleInfo> getBuying() { return _buying; } public void setBuying(Map<Integer, ArticleInfo> buying) { _buying = buying; } }
[ "shyamsivaraman.1@gmail.com" ]
shyamsivaraman.1@gmail.com
fbe2cdf4c2b8e5f918b43d8ec5f8359266660177
e70350ed3b2b01cfceeaee8eed4ef311b057a28d
/app/src/main/java/com/example/zhaoting/myapplication/model/comment/CommentModel.java
4a91457bd60fcfe52e4a83bd5339aced2c09c8a8
[]
no_license
ting0220/Test
2e4bb4760cc7343399967dea4e7ac921d27a345c
0884839c2261e805a7ac5282a7650b6bf43f08c7
refs/heads/master
2021-01-19T08:59:17.012309
2016-07-05T10:21:58
2016-07-05T10:21:58
56,648,870
0
0
null
null
null
null
UTF-8
Java
false
false
308
java
package com.example.zhaoting.myapplication.model.comment; import com.example.zhaoting.myapplication.model.OnListener; /** * Created by zhaoting on 16/6/2. */ public interface CommentModel { void getShortComments(int id, OnListener listener); void getLongComments(int id, OnListener listener); }
[ "466490327@qq.com" ]
466490327@qq.com
8a7b51b7a735813b1637b1588cab8e141a059c02
caa967361492508c13e51ba4800d38f67adc63b0
/src/lesson11/TestLeafcutterAnts.java
40470649ed90eca09691152d2824db194e80c265
[]
no_license
lofrei/codingexamples
eb1cb7f191ddf574cced9e8ee5c82617df38c49f
e51ecc36f51a87123c811d201d3a92b909253f44
refs/heads/master
2020-08-23T05:46:07.246886
2019-12-07T18:08:19
2019-12-07T18:08:19
216,556,506
0
0
null
2019-10-21T12:22:26
2019-10-21T11:56:47
null
UTF-8
Java
false
false
1,661
java
package lesson11; class LeafcutterAnt { double headsize; LeafcutterAnt(double headsize){ this.headsize = headsize; } public void work(){}; } class Minim extends LeafcutterAnt{ Minim(){ super(0.9); } public void work(){ System.out.println("Hi, I am Minim #"+ this.hashCode() + ". I am a tiny ant with headsize " + headsize + ". I am caring for our fungus gardens."); } } class Minor extends LeafcutterAnt{ Minor(){ super(1.8); } public void work(){ System.out.println("Hi, I am Minor #"+ this.hashCode() + ". I am a small ant with headsize " + headsize + ". I am defending our food searching ants."); } } class Media extends LeafcutterAnt{ Media(){ super(4.5); } public void work(){ System.out.println("Hi, I am Media #"+ this.hashCode() + ". I am a midsize ant with headsize " + headsize + ". I am cutting the leaves and carry them home."); } } class Major extends LeafcutterAnt{ Major(){ super(7); } public void work(){ System.out.println("Hi, I am Major #"+ this.hashCode() + ". I am a really large ant with headsize " + headsize + ". I am a warrior defending our nest."); } } public class TestLeafcutterAnts { public static void main(String[] args) { LeafcutterAnt[] colony = {new Minim(), new Minor(), new Media(), new Major()}; for (LeafcutterAnt ant:colony){ ant.work(); } } }
[ "lotte.freischlad@web.de" ]
lotte.freischlad@web.de
fd49496a7e2663a048d0bd320cbbb76f2627bb5a
79a9e525809ac5efe331958d1737d678cbe1a74e
/src/main/java/com/jmatio/types/MLUInt32.java
5fe4ed8af4d845bfb5d9cc9f23b425eb5b92d37d
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
diffplug/matfilerw
170b4e8d2194771e39c00df44a9914c9ff766fb7
5edb6b223c77fe1dfdc5210f2078f94878d3f721
refs/heads/master
2021-01-17T15:18:30.390668
2018-12-28T19:45:27
2018-12-28T19:45:27
43,794,907
61
22
NOASSERTION
2018-12-28T19:30:20
2015-10-07T04:23:06
Java
UTF-8
Java
false
false
678
java
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2006, Wojciech Gradkowski * All code after tags/original: Copyright (c) 2015, DiffPlug */ package com.jmatio.types; public class MLUInt32 extends MLInt32 { public MLUInt32(String name, int[] dims, int type, int attributes) { super(name, dims, type, attributes); } public MLUInt32(String name, int[] vals, int m) { super(name, vals, m); } public MLUInt32(String name, int[] dims) { super(name, dims); } public MLUInt32(String name, int[][] vals) { super(name, vals); } public MLUInt32(String name, Integer[] vals, int m) { super(name, vals, m); } }
[ "ned.twigg@diffplug.com" ]
ned.twigg@diffplug.com
4618a74468b37c7c2b036a39d12e7962eb20096e
0d2079efaeb5d41d6c99c45ab350eb4a501936c1
/src/main/java/mchorse/mclib/utils/keyframes/KeyframeInterpolation.java
da34204695883b67d05d1023da0737b4c409f1db
[ "MIT" ]
permissive
srgantmoomoo/mclib-rpc
0b302986a1e02f83ba6edc9cbfc74aee514c332e
55f4a9e0f2c2621acc49736ef3d77a7d89e5711d
refs/heads/master
2023-02-13T20:05:10.888590
2021-01-10T23:16:29
2021-01-10T23:16:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,724
java
package mchorse.mclib.utils.keyframes; import mchorse.mclib.utils.Interpolation; import mchorse.mclib.utils.Interpolations; import mchorse.mclib.utils.MathUtils; public enum KeyframeInterpolation { CONST("const") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { return a.value; } }, LINEAR("linear") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { return Interpolations.lerp(a.value, b.value, x); } }, QUAD("quad") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (a.easing == KeyframeEasing.IN) return Interpolation.QUAD_IN.interpolate(a.value, b.value, x); if (a.easing == KeyframeEasing.OUT) return Interpolation.QUAD_OUT.interpolate(a.value, b.value, x); return Interpolation.QUAD_INOUT.interpolate(a.value, b.value, x); } }, CUBIC("cubic") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (a.easing == KeyframeEasing.IN) return Interpolation.CUBIC_IN.interpolate(a.value, b.value, x); if (a.easing == KeyframeEasing.OUT) return Interpolation.CUBIC_OUT.interpolate(a.value, b.value, x); return Interpolation.CUBIC_INOUT.interpolate(a.value, b.value, x); } }, HERMITE("hermite") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { double v0 = a.prev.value; double v1 = a.value; double v2 = b.value; double v3 = b.next.value; return Interpolations.cubicHermite(v0, v1, v2, v3, x); } }, EXP("exp") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (a.easing == KeyframeEasing.IN) return Interpolation.EXP_IN.interpolate(a.value, b.value, x); if (a.easing == KeyframeEasing.OUT) return Interpolation.EXP_OUT.interpolate(a.value, b.value, x); return Interpolation.EXP_INOUT.interpolate(a.value, b.value, x); } }, BEZIER("bezier") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (x <= 0) return a.value; if (x >= 1) return b.value; /* Transform input to 0..1 */ double w = b.tick - a.tick; double h = b.value - a.value; /* In case if there is no slope whatsoever */ if (h == 0) h = 0.00001; double x1 = a.rx / w; double y1 = a.ry / h; double x2 = (w - b.lx) / w; double y2 = (h + b.ly) / h; double e = 0.0005; e = h == 0 ? e : Math.max(Math.min(e, 1 / h * e), 0.00001); x1 = MathUtils.clamp(x1, 0, 1); x2 = MathUtils.clamp(x2, 0, 1); return Interpolations.bezier(0, y1, y2, 1, Interpolations.bezierX(x1, x2, x, e)) * h + a.value; } }, BACK("back") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (a.easing == KeyframeEasing.IN) return Interpolation.BACK_IN.interpolate(a.value, b.value, x); if (a.easing == KeyframeEasing.OUT) return Interpolation.BACK_OUT.interpolate(a.value, b.value, x); return Interpolation.BACK_INOUT.interpolate(a.value, b.value, x); } }, ELASTIC("elastic") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (a.easing == KeyframeEasing.IN) return Interpolation.ELASTIC_IN.interpolate(a.value, b.value, x); if (a.easing == KeyframeEasing.OUT) return Interpolation.ELASTIC_OUT.interpolate(a.value, b.value, x); return Interpolation.ELASTIC_INOUT.interpolate(a.value, b.value, x); } }, BOUNCE("bounce") { @Override public double interpolate(Keyframe a, Keyframe b, float x) { if (a.easing == KeyframeEasing.IN) return Interpolation.BOUNCE_IN.interpolate(a.value, b.value, x); if (a.easing == KeyframeEasing.OUT) return Interpolation.BOUNCE_OUT.interpolate(a.value, b.value, x); return Interpolation.BOUNCE_INOUT.interpolate(a.value, b.value, x); } }; public final String key; private KeyframeInterpolation(String key) { this.key = key; } public abstract double interpolate(Keyframe a, Keyframe b, float x); public String getKey() { return "mclib.interpolations." + this.key; } }
[ "" ]
5b90d928f05160e80c02f4a995eee1a490a6e031
cd9a2f19fe97dfebdc646becdf7ae7e5ce476123
/spring-web/src/main/java/org/springframework/web/context/AbstractContextLoaderInitializer.java
d38e739876e3ac66fa48c564804bf3653708c51d
[]
no_license
nicky-chen/spring-framework-3.2.x
d5f0fae80847da4f303f94443ce46cd92352979a
e33e9639d82aa9395509227567aa714d41ac2a2b
refs/heads/master
2021-08-29T00:54:28.870499
2021-08-17T11:28:08
2021-08-17T11:28:08
125,344,623
2
0
null
null
null
null
UTF-8
Java
false
false
3,073
java
/* * Copyright 2002-2014 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 * * 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.springframework.web.context; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.WebApplicationInitializer; /** * Convenient base class for {@link WebApplicationInitializer} implementations * that register a {@link ContextLoaderListener} in the servlet context. * * <p>The only method required to be implemented by subclasses is * {@link #createRootApplicationContext()}, which gets invoked from * {@link #registerContextLoaderListener(ServletContext)}. * * @author Arjen Poutsma * @author Chris Beams * @since 3.2 */ public abstract class AbstractContextLoaderInitializer implements WebApplicationInitializer { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); public void onStartup(ServletContext servletContext) throws ServletException { registerContextLoaderListener(servletContext); } /** * Register a {@link ContextLoaderListener} against the given servlet context. The * {@code ContextLoaderListener} is initialized with the application context returned * from the {@link #createRootApplicationContext()} template method. * @param servletContext the servlet context to register the listener against */ protected void registerContextLoaderListener(ServletContext servletContext) { WebApplicationContext rootAppContext = createRootApplicationContext(); if (rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext)); } else { logger.debug("No ContextLoaderListener registered, as " + "createRootApplicationContext() did not return an application context"); } } /** * Create the "<strong>root</strong>" application context to be provided to the * {@code ContextLoaderListener}. * <p>The returned context is delegated to * {@link ContextLoaderListener#ContextLoaderListener(WebApplicationContext)} and will * be established as the parent context for any {@code DispatcherServlet} application * contexts. As such, it typically contains middle-tier services, data sources, etc. * @return the root application context, or {@code null} if a root context is not * desired * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer */ protected abstract WebApplicationContext createRootApplicationContext(); }
[ "cx52018761@hotmail.com" ]
cx52018761@hotmail.com
9f9c21f5f03e7dc60d082f688b4cafe00f491253
ecfbaced6ba4b11e679c5467dc89d4dbe450b627
/app/src/main/java/com/shwm/freshmallpos/view/IMainOrderView.java
65432e335935babaf78bd6f289e495e2b42fcdb5
[]
no_license
damo2/testPos
34683947a125bf04d2ceb0a573509811ce10279d
f8292db8b091014eade593957258a757ed5a71e0
refs/heads/master
2022-02-27T11:41:18.344409
2019-09-30T03:24:24
2019-09-30T03:24:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
293
java
package com.shwm.freshmallpos.view; import java.util.List; import com.shwm.freshmallpos.been.OrderEntity; public interface IMainOrderView extends IBaseView{ int getPageType(); void showListOrder(List<OrderEntity> listOrder); void setLoadType(int loadType); void refreshCancel(); }
[ "wangru0926@sina.com" ]
wangru0926@sina.com
407742d20155d9f7e042900164c58510710cfc9e
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/elastic--elasticsearch/2cc97a0d3ed2a9276378e2a6462942deab04a1fb/before/MinTests.java
e045809aa85d7b660c343c85f742a178f912a706
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
14,580
java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.messy.tests; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService.ScriptType; import org.elasticsearch.script.groovy.GroovyPlugin; import org.elasticsearch.search.aggregations.bucket.global.Global; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.metrics.AbstractNumericTestCase; import org.elasticsearch.search.aggregations.metrics.min.Min; import org.junit.Test; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.search.aggregations.AggregationBuilders.global; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.min; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; /** * */ public class MinTests extends AbstractNumericTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(GroovyPlugin.class); } @Override @Test public void testEmptyAggregation() throws Exception { SearchResponse searchResponse = client().prepareSearch("empty_bucket_idx") .setQuery(matchAllQuery()) .addAggregation(histogram("histo").field("value").interval(1l).minDocCount(0).subAggregation(min("min"))) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(2l)); Histogram histo = searchResponse.getAggregations().get("histo"); assertThat(histo, notNullValue()); Histogram.Bucket bucket = histo.getBuckets().get(1); assertThat(bucket, notNullValue()); Min min = bucket.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(Double.POSITIVE_INFINITY)); } @Override @Test public void testUnmapped() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx_unmapped") .setQuery(matchAllQuery()) .addAggregation(min("min").field("value")) .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(0l)); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(Double.POSITIVE_INFINITY)); } @Override @Test public void testSingleValuedField() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(min("min").field("value")) .execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); } @Test public void testSingleValuedField_WithFormatter() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").format("0000.0").field("value")).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); assertThat(min.getValueAsString(), equalTo("0001.0")); } @Override @Test public void testSingleValuedField_getProperty() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(global("global").subAggregation(min("min").field("value"))).execute().actionGet(); assertHitCount(searchResponse, 10); Global global = searchResponse.getAggregations().get("global"); assertThat(global, notNullValue()); assertThat(global.getName(), equalTo("global")); assertThat(global.getDocCount(), equalTo(10l)); assertThat(global.getAggregations(), notNullValue()); assertThat(global.getAggregations().asMap().size(), equalTo(1)); Min min = global.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); double expectedMinValue = 1.0; assertThat(min.getValue(), equalTo(expectedMinValue)); assertThat((Min) global.getProperty("min"), equalTo(min)); assertThat((double) global.getProperty("min.value"), equalTo(expectedMinValue)); assertThat((double) min.getProperty("value"), equalTo(expectedMinValue)); } @Override @Test public void testSingleValuedField_PartiallyUnmapped() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx", "idx_unmapped") .setQuery(matchAllQuery()) .addAggregation(min("min").field("value")) .execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); } @Override @Test public void testSingleValuedField_WithValueScript() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(min("min").field("value").script(new Script("_value - 1"))) .execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(0.0)); } @Override @Test public void testSingleValuedField_WithValueScript_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(min("min").field("value").script(new Script("_value - dec", ScriptType.INLINE, null, params))) .execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(0.0)); } @Override @Test public void testMultiValuedField() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(min("min").field("values")) .execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(2.0)); } @Override @Test public void testMultiValuedField_WithValueScript() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(min("min").field("values").script(new Script("_value - 1"))).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); } @Test public void testMultiValuedField_WithValueScript_Reverse() throws Exception { // test what happens when values arrive in reverse order since the min // aggregator is optimized to work on sorted values SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").field("values").script(new Script("_value * -1"))).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(-12d)); } @Override @Test public void testMultiValuedField_WithValueScript_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").field("values").script(new Script("_value - dec", ScriptType.INLINE, null, params))).execute() .actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); } @Override @Test public void testScript_SingleValued() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").script(new Script("doc['value'].value"))).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); } @Override @Test public void testScript_SingleValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").script(new Script("doc['value'].value - dec", ScriptType.INLINE, null, params))).execute() .actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(0.0)); } @Override @Test public void testScript_ExplicitSingleValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").script(new Script("doc['value'].value - dec", ScriptType.INLINE, null, params))).execute() .actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(0.0)); } @Override @Test public void testScript_MultiValued() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").script(new Script("doc['values'].values"))).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(2.0)); } @Override @Test public void testScript_ExplicitMultiValued() throws Exception { SearchResponse searchResponse = client().prepareSearch("idx").setQuery(matchAllQuery()) .addAggregation(min("min").script(new Script("doc['values'].values"))).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(2.0)); } @Override @Test public void testScript_MultiValued_WithParams() throws Exception { Map<String, Object> params = new HashMap<>(); params.put("dec", 1); SearchResponse searchResponse = client() .prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation( min("min") .script(new Script( "List values = doc['values'].values; double[] res = new double[values.size()]; for (int i = 0; i < res.length; i++) { res[i] = values.get(i) - dec; }; return res;", ScriptType.INLINE, null, params))).execute().actionGet(); assertHitCount(searchResponse, 10); Min min = searchResponse.getAggregations().get("min"); assertThat(min, notNullValue()); assertThat(min.getName(), equalTo("min")); assertThat(min.getValue(), equalTo(1.0)); } }
[ "fraczwojciech@gmail.com" ]
fraczwojciech@gmail.com
e33060a62b8a50ff16a94f2ac34172f133c9ee33
94b2566e2ed25d37abd0498b74ef273daf24f6c8
/app/components/dao/ReadDao.java
deccd5c144323db1f96fe18f32d405de63215c52
[ "MIT" ]
permissive
uktrade/lite-exporter-dashboard-archive
d0f1837a17b794313bd3b7487666471fa3093071
e3eab54f39204b3a105b27a06ee6d259e4faf1bf
refs/heads/master
2022-04-01T15:49:38.398191
2019-07-01T13:53:14
2019-07-01T13:53:14
97,020,103
0
0
null
null
null
null
UTF-8
Java
false
false
251
java
package components.dao; import java.util.List; import models.Read; public interface ReadDao { List<Read> getReadList(String userId); void insertRead(Read read); void deleteAllReadDataByUserId(String userId); void deleteAllReadData(); }
[ "stefan.brach@digital.trade.gov.uk" ]
stefan.brach@digital.trade.gov.uk
72056d9cb552910dfcb33c30544b66969c8895f7
737d06ff92d509def65ec5062b86c7493773e023
/prd-api/src/main/java/rebue/prd/svc/PrdProductCategorySvc.java
a11aa153bc0c69164e27b66238deb0e10f9672da
[]
no_license
rebue/prd
a23e633b1f973932988638ab7b22fff50b1c9c80
cdc03ede65518569bcc3b8ef53bae96d85cef1cb
refs/heads/master
2020-05-20T00:49:20.944467
2019-09-23T07:34:11
2019-09-23T07:34:11
185,295,506
0
0
null
null
null
null
UTF-8
Java
false
false
738
java
package rebue.prd.svc; import java.util.List; import rebue.prd.jo.PrdProductCategoryJo; import rebue.prd.mo.PrdProductCategoryMo; import rebue.prd.ro.PrdProductCategoryTreeRo; import rebue.robotech.svc.BaseSvc; /** * 产品分类 * * @mbg.generated 自动生成的注释,如需修改本注释,请删除本行 */ public interface PrdProductCategorySvc extends BaseSvc<java.lang.Long, PrdProductCategoryMo, PrdProductCategoryJo> { /** * 获取产品分类树 * * @return */ List<PrdProductCategoryTreeRo> categoryTree(); /** * 根据分类编码获取产品分类树 * * @param code * @return */ List<PrdProductCategoryTreeRo> categoryTreeByCode(String code); }
[ "596038980@qq.com" ]
596038980@qq.com
2072a09c28c9a8e5ce482e6e56c7fe8defae8eda
50da523d820bf991ab9aef375cd6dca4ada07e25
/src/main/java/com/zdv/shop/common/utils/CellServer.java
71d6f0f412e95e55ae0b09ac10c8ccdc4a37c3ec
[]
no_license
729324091/zdv_shop
e46e6c4381cfea3fb737eeab84a7b024b1b5597c
40c78b1d4f5a024e1e31f1a86d36990862b23475
refs/heads/master
2020-07-22T12:21:08.304663
2019-09-09T04:09:50
2019-09-09T04:09:52
207,200,757
0
0
null
null
null
null
UTF-8
Java
false
false
11,777
java
package com.zdv.shop.common.utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class CellServer { private static final String[] sms_words ={"李克强","年化收益","习近平","东方闪电","乳房","中国电信","世界末日","公寓","监狱","好声音","装 修","商铺","星光","平方","拘留所","楼宇","代办","人民内情真相","法轮","人民真实报道","人民之声论坛","人权","杀笔","傻逼","煞笔","射精","涉日","神通加持法","时代论坛","时事参考","时事论坛","事实独立","收容所","四川独立","他妈的","台独","台盟","台湾独立","台湾狗","台湾建国运动组织","台湾青年独立联盟","台湾政论区","台湾自由联盟","太子党","套牌","天安门录影带","天安门事件","天安门屠杀","天安门一代","统独","统独论坛","突厥斯坦","屠杀","推翻","吾尔开希","西藏独立","洗脑","下体","小肛","邪恶","新观察论坛","新华举报","新华内情","新华通论坛","新疆独立","新生网","新闻封锁","信用危机","性交","学潮","学联","学运","学自联","央视内部晚会","夜话紫禁城","一中一台","伊斯兰运动","阴道","阴胫","淫秽","淫穴","印尼伊斯兰祈祷团","游行","幼齿","幼女","舆论反制","造反","贼民","镇压","争鸣论坛","正见网","正义党论坛","政变","政治反对派","政治犯","政治风波","支那","指点江山论坛","中国复兴论坛","中国孤儿院","中国社会进步党","中国社会论坛","中国威胁论","中国问题论坛","中国真实内容","中国之春","中国猪","中华人民实话实说","中华人民正邪","中华时事","中华养生益智功","中华真实报道","钟山风雨论坛","猪毛","猪毛1","自已的故事","自由民主论坛","自由运动","走私","屙民","嫖娼","汽油短缺","江泽民","汽油飞涨","罢工","法轮功","胡锦涛","人民真实","独院","别墅","公寓","地产","平方","荡妇","贱B","楼宇","a片","商铺","中国移动通信","中央军委","中共中央","二奶","代办证件","你老母","修炼者","做爱","六和彩","台湾陆委会","善念","国民党","处女膜","妓男女院","彩民","性行为","恶警","抵制日货","拉丹","拉登","杀生","李洪志","李登辉","极品推荐","民进党","江流氓","法轮伦","温家宝","男妓","睾丸","短信中心","砸蛋活动","示威","罪魁","聊天热线","达赖","阴部道","陈水扁","罢课","保钓","暴乱","暴政","北大三角地论坛","北韩","北京当局","北京之春","北美自由论坛","藏独","操你妈逼","赤匪","赤化","传单","春夏自由论坛","打倒","大参考","代办","弹劾","地下教会","地下刊物","电视流氓","钓鱼岛","东北独立","东方红时空","东突","东突厥斯坦","东土耳其斯坦","东西南北论坛","动乱","独裁","独裁政治","独夫","独立台湾会","法伦","法仑","法沦","三陪","色情","法纶","法论","法.轮.功","法十轮十功","法谪","法谪功","法囵","法愣","反封锁技术","反腐败论坛","反革命","反攻","反共","反人类","反日","反社会","分裂","粉饰太平","风雨神州","风雨神州论坛","佛展千手法","肛交","高自联","工自联","功法","功友","共产","共产党","共党","共匪","共狗","共军","狗逼","贯通两极法","国家安全","国家机密","国研新闻邮件","国贼","韩东方","韩联潮","汉奸","黑庄","红灯区","红色恐怖","胡紧掏","胡总书记","护法","花花公子","华通时事论坛","华语世界论坛","华岳时事论坛","回民暴动","悔过书","鸡8","鸡扒","鸡吧","鸡八","鸡巴","鸡鸡","鸡毛信文汇","僵贼民","江core","江ze民","江澤民","江八点","江独裁","江戏子","江则民","江贼民","江猪","江猪媳","江主席","疆独","讲法","教徒","揭批书","靖国神社","九评","老人政治","李宏志","李红痔","联总","联总之声","联总之声传单","连胜德","廉政大论坛","炼功","两岸关系","两岸三地论坛","两个中国","流亡","六合彩","六四","陆委会","抡功","轮大","轮功","轮奸","伦功","麻将机","卖国唐捷","毛厕洞","毛片","法抡","毛贼东","美国参考","美国之音","蒙独","蒙古独立","猛料","密穴","民意论坛","民主墙","民族矛盾","南大自由论坛","闹事","你说我说论坛","泡沫经济","屁眼","青天白日旗","情妇","情趣","热站政论网","人民大众时事参考","没有此城市数据","中国电信","三星装饰","装修","装修","洋房","首付","移民","家教","名校","今日建仓","今天布局","今日布局","黑马","私幕","今天建仓","拉升","获利","年化收益","价格6分到8分","建仓","强力","冲击","涨停","实惠套餐","特招班","乳房","首查","法輪","人民真實報導","人民之聲論壇","人權","殺筆","煞筆","時代論壇","時事參考","時事論壇","事實獨立","四川獨立","他媽的","台獨","臺盟","臺灣獨立","臺灣狗","臺灣青年獨立聯盟","臺灣政論區","臺灣自由聯盟","天安門錄影帶","天安門事件","天安門屠殺","天安門一代","統獨","統獨論壇","屠殺","吾爾開希","西藏獨立","洗腦","下體","邪惡","新觀察論壇","新華舉報","新華內情","新華通論壇","新疆獨立","新生網","新聞封鎖","學潮","學聯","學?學自聯","央視內部晚會","夜話紫禁城","伊斯蘭邉?陰道","陰脛","淫穢","遊行","幼齒","輿論反制","倜?鎮壓","爭鳴論壇","正見網","正義黨論壇","政變","政治反對派","政治風波","指點江山論壇","中國復興論壇","中國孤兒院","中國社會進步黨","中國社會論壇","中國威脅論","中國問題論壇","中國真實內容","中國之春","中國豬","中華人民實話實說","中華人民正邪","中華時事","中華養生益智功","中華真實報導","鐘山風雨論壇","豬毛","豬毛1","自由民主論壇","汽油飛漲","罷工","法輪功","人民真實","蕩婦","中國移動通信","中央軍委","代辦證件","修煉者","做愛","臺灣陸委會","國民黨","處女膜","性行為","惡警","抵制日貨","殺生","李登輝","極品推薦","民進黨","達賴","陰部道","陳水扁","21世紀中國基金會","罷課","保釣","暴亂","北大三角地論壇","北韓","北京當局","北美自由論壇","藏獨","操你媽逼","傳單","春夏自由論壇","大參考","代辦","彈劾","地下教會","釣魚島","東北獨立","東方紅時空","東突","法綸","法論","法十輪十功","法謫","法謫功","法圇","反封鎖技術","反腐敗論壇","反人類","反社會","粉飾太平","風雨神州","風雨神州論壇","高自聯","工自聯","共產","共產黨","共黨","共軍","貫通兩極法","國家安全","國家機密","華通時事論壇","華語世界論壇","華嶽時事論壇","回民暴動","悔過書","雞8","雞扒","雞吧","雞八","雞巴","雞雞","雞毛信文匯","僵倜?江八點","江獨裁","江戲子","江則民","江倜?江豬","江豬媳","疆獨","講法","揭批書","靖國神社","九評","李紅痔","聯總","聯總之聲","聯總之聲傳單","陸委會","掄功","輪大","輪功","輪奸","倫功","麻將機","賣國唐捷","毛廁洞","法掄","毛贃|","美國參考","美國之音","蒙獨","蒙古獨立","民意論壇","民主牆","南大自由論壇","鬧事","你說我說論壇","泡沫經濟","情婦","熱站政論網","人民大眾時事參考","耶穌","聖經","家庭電臺","審判日","薄熙來","耶稣","圣经","基督","家庭电台","审判日","宗共","人民內情真相","薄熙来","信用危機","溫家寶","東突厥斯坦","東土耳其斯坦","東西南北論壇","動亂","獨裁","獨裁政治","獨夫","獨立臺灣會","法倫","法侖","法淪","國研新聞郵件","韓聯潮","漢奸","黑莊","紅燈區","紅色恐怖","胡緊掏","胡總書記","護法","連勝德","廉政大論壇","煉功","兩岸關係","兩岸三地論壇","兩個中國","今日建倉","今天佈局","今日佈局","黑馬","星光大道","21世纪中国基金会","生肖","留学"}; private static final CellServer instance = new CellServer(); private CellServer() { } public static CellServer getInstance() { return instance; } public static String smsPlit(String source){ String str=source,sc = "",sto = ""; for(int i=0;i<sms_words.length;i++){ sc = sms_words[i]; if(str.indexOf(sms_words[i])>0){ sto = ""; StringBuilder sb = new StringBuilder(sc); int len = sb.length(); for(int ii=0;ii<len;ii++){ char ch = sc.charAt(ii); if(ii==(len-1)) sto +=ch; else sto +=ch+"l"; } str = str.replaceAll(sms_words[i],sto); } } return str; } public static void main(String[] args) { // TODO Auto-generated method stub CellServer cs = CellServer.getInstance(); cs.sendMessage("13760351001","收到吗",2); /*String message = "易买易送提供(08日12点34分)卤五花肉饭中份1份;隆江猪脚饭中份1份;九零后,单号2098,18938860833送餐地址:深圳留 学生创业大厦1206;交易码876559 回复7:已收到订单;回复8:该菜品已售完,另订"; message = smsPlit(message);*/ //System.out.println(cs.sendSmsxin("")); //System.out.println(cs.ReceiveMessage("").length());18988776708 //cs.confrim("22811549711"); } public boolean sendMessage(String tel,String message,int i){ //生成调用的URL.如果参数中有中文一定要用 java.net.URLEncoder.encode(<参数>,"UTF-8") String qurl=""; try { if("".equalsIgnoreCase(message)||message==null)return false; message = smsPlit(message); qurl = "http://gd.ums86.com:8899/sms/Api/Send.do?SpCode=208433&LoginName=send&Password=hjbpyzn@1937&MessageContent=" + java.net.URLEncoder.encode(message,"GBK")+"&UserNumber="+tel+"&SerialNumber=&ScheduleTime=&ExtendAccessNum=&f=1"; } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } URL url; try { url = new URL(qurl); URLConnection URLconnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)URLconnection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream urlStream = httpConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream,"GBK")); String sCurrentLine = ""; String sTotalString = ""; while ((sCurrentLine = bufferedReader.readLine()) != null) { sTotalString += sCurrentLine; } //System.out.println(sTotalString); //假设该url页面输出为"OK" if (sTotalString.indexOf("发送短信成功")>0) { return true; } else { return false; } }else{ System.err.println("失败"); } } catch (Exception e) { // TODO Auto-generated catch blockeb e.printStackTrace(); } return false; } }
[ "729324091@qq.com" ]
729324091@qq.com
d842fd4e08c9c7c916235746f8d6dac7d2473cc1
fd6119771bd19cbad9857c4559595de9688b3440
/src/classes/Square.java
fff84d721141076fd414cc19983fc48b88cc302a
[]
no_license
nesurr7/prac_4_1
e454a05cc4cd4c945f9bd2100daeb37342689b56
d3e116bc68b0fae6c8f2c445152053527e08745a
refs/heads/master
2022-12-11T06:58:50.506178
2020-09-10T07:55:36
2020-09-10T07:55:36
294,342,153
0
0
null
null
null
null
UTF-8
Java
false
false
1,064
java
package classes; public class Square extends Rectangle { double side; Square() { } Square(double side) { super(side, side); this.side=side; } Square(double side, String color, boolean filled) { super(side, side, color, filled); this.side=side; } public double getSide() { return side; } public void setSide(double side) { this.side = side; this.length=side; this.width=side; } @Override public void setLength(double length) { this.side = side; this.length=side; this.width=side; } @Override public void setWidth(double width) { this.side = side; this.length=side; this.width=side; } @Override public String toString() { return "Параметры квадрата:" + "\nДлина стороны:" + side + "\nЦвет:" + color + "\nЗаполнен:" + filled + "\n________________";} }
[ "nesurr7@gmail.com" ]
nesurr7@gmail.com
c9b3697b3174f4a03857b5e1f615a234e6d1ee32
1e19ee066d600f1d39131e6eb6ffe76524053a57
/src/br/com/dfmachado/listadefilmes/views/ComponentsAndRenderers/StatusComboModel.java
ef81f029fbfaa692aeded29cf03796103b3bf7f2
[]
no_license
diegofelipem/ListaDeFilmes
c90901b35fdef5653b92df062ad54f8f2f432147
2064de75f2e61541825a5e80ff9414de2601bb88
refs/heads/master
2021-06-26T07:46:39.099275
2017-09-10T22:30:58
2017-09-10T22:30:58
103,065,842
0
0
null
null
null
null
UTF-8
Java
false
false
1,101
java
package br.com.dfmachado.listadefilmes.views.ComponentsAndRenderers; import br.com.dfmachado.listadefilmes.controllers.StatusController; import br.com.dfmachado.listadefilmes.models.Status; import java.util.List; import javax.swing.AbstractListModel; import javax.swing.ComboBoxModel; /** * * @author diego.felipe */ public class StatusComboModel extends AbstractListModel implements ComboBoxModel { private final List<Status> status; private final StatusController controller = new StatusController(); private Status selecao = null; public StatusComboModel() { this.status = this.controller.listAll(); this.status.add(null); } @Override public int getSize() { return this.status.size(); } @Override public Object getElementAt(int index) { return this.status.get(index); } @Override public void setSelectedItem(Object anItem) { this.selecao = (Status) anItem; } @Override public Object getSelectedItem() { return this.selecao; } }
[ "diego@DIEGO-NOTE" ]
diego@DIEGO-NOTE
2a43335df9ef0b1d8782d3b7c4843f4dc3e0df19
5ed9f418963b8853e4a706cc5971af97cd588e5e
/src/main/java/br/com/projetcworkshop/services/exception/DataIntegrityException.java
60d3ad0f2cdaab999d07bd7c23b2a6a7de1d64d4
[]
no_license
LeoFernandes193/Project-Workshop-Java
e6c0248beba2508168208b369ecbe10a3d92da54
ad75bef5a86455343e3d48056d81caee310a4403
refs/heads/master
2020-07-29T13:05:57.153752
2019-07-04T19:56:53
2019-07-04T19:56:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
337
java
package br.com.projetcworkshop.services.exception; public class DataIntegrityException extends RuntimeException{ private static final long serialVersionUID = 1L; public DataIntegrityException(String message) { super(message); } public DataIntegrityException(String message, Throwable cause) { super(message, cause); } }
[ "thaleslima-19@hotmail.com" ]
thaleslima-19@hotmail.com
5ca601b9d978929ac2f0d923392da9dc87b0f98e
0a92a5036703276c76660bd13bfbf67e0970ead0
/app/src/androidTest/java/edu/orangecoastcollege/cs273/ltruong58/tapcounter/ApplicationTest.java
f4b42928bf3763860b2884167cdebdbf507cff07
[]
no_license
ltruong58/TapCounter2
dc80861736aea470ac53a2a53d0a11c9f32007f3
5cff5dd3281297e17ad9f0fb86545d374b467487
refs/heads/master
2020-12-08T12:33:48.602552
2016-09-07T00:11:11
2016-09-07T00:11:11
67,556,248
0
0
null
null
null
null
UTF-8
Java
false
false
380
java
package edu.orangecoastcollege.cs273.ltruong58.tapcounter; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "long.truongnguyenthanh@gmail.com" ]
long.truongnguyenthanh@gmail.com
51bfba6453576aa71a3b1c6883b8ecc6254d1b85
eb103eddf6d1e23881c207474db5468b4500f66d
/Ganador.java
e2f0c4b93c16f562431bd6b8f7816a86a695e22c
[]
no_license
objetos15161/Juan-vs-El-Mundo
af55a311944d4e96952f127153ef73f43831fcad
ce19d5ad32bcef972d4deeaa99aa2a539ccdad16
refs/heads/master
2021-01-10T05:50:38.121594
2015-12-09T18:56:24
2015-12-09T18:56:24
46,182,564
0
0
null
null
null
null
UTF-8
Java
false
false
498
java
import greenfoot.*; /** * Ganador clase que indica el fin del juego mencionando que lo ganaste. * * @Ulises Gomez * @7/12/15 */ public class Ganador extends World { /** * Constructor para objetos de clase Ganador. * */ public Ganador() { // Crea un nuevo mundo de 700x400 celdas con un tamaño de celda de 1x1 pixeles. super(700, 400, 1); Back b=new Back();//Crea Boton de regreso addObject(b,600,300); } }
[ "buly_puma@hotmail.com" ]
buly_puma@hotmail.com
14a62bf014321c228b7f9abef6adb05ddb1c532d
2088303ad9939663f5f8180f316b0319a54bc1a6
/src/main/java/com/lottery/common/schedule/IScheduler.java
932dfeafd9c5b04782fd7c643db3f996866e5859
[]
no_license
lichaoliu/lottery
f8afc33ccc70dd5da19c620250d14814df766095
7796650e5b851c90fce7fd0a56f994f613078e10
refs/heads/master
2022-12-23T05:30:22.666503
2019-06-10T13:46:38
2019-06-10T13:46:38
141,867,129
7
1
null
2022-12-16T10:52:50
2018-07-22T04:59:44
Java
UTF-8
Java
false
false
169
java
package com.lottery.common.schedule; /** * 调度接口,所有调度器都必须实现 * @author fengqinyun * */ public interface IScheduler { public void run(); }
[ "1147149597@qq.com" ]
1147149597@qq.com
6f8e516670334aab6459cb648b9c2d4afe8bab1f
54f081bccc85c22cebdc0b5ff27eaffd06c1e4ed
/src/main/java/br/com/sondait/timesheet/config/WebConfig.java
f36e3f070b16ac6738bee9cbf1eebb3100e55c99
[]
no_license
LeonardoMelloOficial/sonda-timesheet-accelerator
18dd1644378b818a81a2b72e8e10aa8f7391a585
7688dc5f934525e60facee7b646934d61aea090a
refs/heads/master
2020-06-20T08:30:33.655236
2019-07-30T20:23:55
2019-07-30T20:23:55
197,059,554
1
1
null
2019-08-24T17:47:01
2019-07-15T19:28:05
Java
UTF-8
Java
false
false
725
java
package br.com.sondait.timesheet.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "TRACE", "CONNECT"); } // public void addResourceHandlers(ResourceHandlerRegistry registry) { // registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); // } }
[ "y2k8@br-petrobras.com.br" ]
y2k8@br-petrobras.com.br
a5387df0b89bc32c784b7a56d2d097509b4161fc
b1bc6be0d323f93d6eb0507ac8b545401c1fedcc
/basicKnowledge/src/com/xdc/basic/api/apache/commons/chain/comparison/implwithchain/command/GetCustomerInfo.java
fd4c2718af1f4b89c5f690707a1194d9bc3e95c1
[]
no_license
xdc0209/java-code
5a331ebcae979fe6b672b527e3b533f2bb42866c
9dc5c89d9a1f8d880afff34903d315c3ca8ddbb2
refs/heads/master
2021-01-17T01:28:31.707484
2019-04-16T18:51:47
2019-04-16T18:51:47
9,099,623
7
4
null
null
null
null
UTF-8
Java
false
false
457
java
package com.xdc.basic.api.apache.commons.chain.comparison.implwithchain.command; import org.apache.commons.chain.Command; import org.apache.commons.chain.Context; public class GetCustomerInfo implements Command { @SuppressWarnings("unchecked") @Override public boolean execute(Context ctx) throws Exception { System.out.println("Get customer info"); ctx.put("customerName", "George Burdell"); return false; } }
[ "xdc0209@qq.com" ]
xdc0209@qq.com
243880cc15adc7d6f20c6b5861fd9ebaa12fba31
7ced6c0ed03f2f9345bbc06a09dbbcf5c8687619
/catering-front/front-wx-api/src/main/java/com/meiyuan/catering/wx/api/index/WxIndexController.java
887e42d530d13bef6faef33e86d7d1894d8240a8
[]
no_license
haorq/food-word
c14d5752c6492aed4a6a1410f9e0352479460da0
18a71259d77b4d96261dab8ed51ca1f109ab5c2f
refs/heads/master
2023-01-01T12:19:48.967366
2020-10-26T07:32:25
2020-10-26T07:32:25
307,292,398
1
0
null
null
null
null
UTF-8
Java
false
false
3,649
java
package com.meiyuan.catering.wx.api.index; import com.meiyuan.catering.core.dto.goods.RecommendDTO; import com.meiyuan.catering.core.dto.user.Notice; import com.meiyuan.catering.core.page.PageData; import com.meiyuan.catering.core.util.Result; import com.meiyuan.catering.es.dto.merchant.EsMerchantListParamDTO; import com.meiyuan.catering.es.dto.wx.EsWxMerchantDTO; import com.meiyuan.catering.marketing.dto.ticket.TicketWxIndexDTO; import com.meiyuan.catering.wx.annotation.LoginUser; import com.meiyuan.catering.wx.dto.UserTokenDTO; import com.meiyuan.catering.wx.dto.goods.WxIndexMarketingGoodsDTO; import com.meiyuan.catering.wx.dto.index.WxCategoryVO; import com.meiyuan.catering.wx.dto.index.WxIndexDTO; import com.meiyuan.catering.wx.dto.index.WxRecommendVO; import com.meiyuan.catering.wx.service.index.WxIndexService; import com.meiyuan.catering.wx.vo.WxAdvertisingExtVO; import com.meiyuan.catering.wx.vo.WxAdvertisingVO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author yaoozu * @description 首页 * @date 2020/3/2111:35 * @since v1.0.0 */ @RestController @RequestMapping("/api/index") @Api(tags = "yaozou-首页") @Slf4j public class WxIndexController { @Autowired private WxIndexService indexService; @GetMapping("/intraCityShop/{location}") @ApiOperation("是否有同城店铺") public Result<WxIndexDTO> intraCityShop(@LoginUser(required = false) UserTokenDTO token, @PathVariable String location) { return indexService.intraCityShop(token, location); } @GetMapping("/noticeList/{categoryLimit}") @ApiOperation("公告信息") public Result<List<Notice>> noticeList(@PathVariable Integer categoryLimit) { return indexService.noticeList(categoryLimit); } @ApiOperation("获取缓存广告 v1.4.0") @GetMapping("/advertisingList") public Result<WxAdvertisingVO> advertisingList() { return indexService.advertisingList(); } @ApiOperation("获取广告二级页面 v1.4.0") @GetMapping("/queryAdvertisingExtList/{id}") public Result<List<WxAdvertisingExtVO>> queryAdvertisingExtList(@PathVariable Long id) { return indexService.advertisingExtList(id); } @GetMapping("/categoryList") @ApiOperation("小程序类目,好物推荐") public Result<WxCategoryVO> categoryList() { return indexService.categoryList(); } @PostMapping("/recommendList") @ApiOperation("爆品橱窗") public Result<PageData<WxRecommendVO>> recommendList(@LoginUser(required = false) UserTokenDTO token, @RequestBody RecommendDTO dto) { return indexService.recommendList(token, dto); } @PostMapping("/merchantList") @ApiOperation("附近商家") public Result<PageData<EsWxMerchantDTO>> merchantList(@LoginUser(required = false) UserTokenDTO token, @RequestBody EsMerchantListParamDTO dto) { return indexService.merchantList(token, dto); } @GetMapping("/couponList") @ApiOperation("优惠卷") public Result<List<TicketWxIndexDTO>> couponList(@LoginUser(required = false) UserTokenDTO token) { return indexService.couponList(token); } @GetMapping("/killGoodsList/{cityCode}") @ApiOperation("限时特惠") public Result<List<WxIndexMarketingGoodsDTO>> killGoodsList(@LoginUser(required = false) UserTokenDTO token, @PathVariable String cityCode) { return indexService.killGoodsList(token, cityCode); } }
[ "386234736" ]
386234736
9cc283789f063ffad94fc45796ecca5cf0851ae1
2be836581f85090b43649b8b966d78434e8bf674
/app/src/main/java/www/winroad/mvp/presenter/HomePresenter.java
d97b54f7a56866db558676e009918193698110a5
[]
no_license
lvzhuozhao/Project
de3d1328ce2da965fa4cb1a24fb1cda2e08ce95d
6c6b33910083f8146aaeed941c04fac355ac20d0
refs/heads/master
2020-04-11T21:18:20.638079
2018-12-14T10:02:54
2018-12-14T10:02:54
162,101,214
0
0
null
null
null
null
UTF-8
Java
false
false
1,252
java
package www.winroad.mvp.presenter; import android.util.Log; import rx.Subscription; import www.winroad.basemvp.BasePresenter; import www.winroad.data.callback.LoadTaskCallback; import www.winroad.entity.UserInfoBean; import www.winroad.mvp.contract.HomeContract; import www.winroad.remote.TasksRepositoryProxy; import static android.content.ContentValues.TAG; public class HomePresenter extends BasePresenter<HomeContract.homeView> implements HomeContract.homeModel { @Override public void homemodel() { Log.i(TAG, "homemodel: 首页打开成功"); Subscription homein = TasksRepositoryProxy.getInstance().homein(new LoadTaskCallback<UserInfoBean>() { @Override public void onTaskLoaded(UserInfoBean data) { getView().homeSuccess(); } @Override public void onDataNotAvailable(String msg) { getView().homeFailed(msg); } @Override public void onStart() { getView().showLoading(); } @Override public void onCompleted() { getView().hideLoading(); } }); addSubscription(homein); } }
[ "13744405279@163.com" ]
13744405279@163.com
c10093f7727471b8360dfab2b11b6e8f8b370573
212146a3c8b7a526f77708453c592970b0d55108
/app/src/main/java/xaidworkz/selectordemo/MainActivity.java
3564f21ab5d4ed032856a039ba207557bf04e17f
[]
no_license
zaid-kamil/Android-Camera-Contact-Intent
6b12607f8d8028755e99188b4ea9158ba53a2625
d2431ed4d6590c46001c3b741db96a55504cd622
refs/heads/master
2021-01-19T14:52:24.077482
2017-08-27T09:07:34
2017-08-27T09:07:34
100,932,526
3
1
null
null
null
null
UTF-8
Java
false
false
12,134
java
package xaidworkz.selectordemo; import android.Manifest; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.ContactsContract; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.widget.CardView; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import xaidworkz.selectordemo.utils.AlbumStorageDirFactory; import xaidworkz.selectordemo.utils.BaseAlbumDirFactory; import xaidworkz.selectordemo.utils.FroyoAlbumDirFactory; import static android.provider.ContactsContract.Contacts; public class MainActivity extends BaseActivity { public static final int REQUEST_EXTERNAL_STORAGE = 91; /*FOR CAMERA INTENT */ private static final int ACTION_TAKE_PHOTO = 1; private static final String JPEG_FILE_PREFIX = "IMG_"; private static final String JPEG_FILE_SUFFIX = ".jpg"; private static final int REQUEST_SELECT_CONTACT = 23; private static final String BITMAP_STORAGE_KEY = "viewbitmap"; private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility"; private static final String TAG = "hahaha"; Bitmap mImageBitmap; private String contactID; // contacts unique ID private AlbumStorageDirFactory mAlbumStorageDirFactory = null; private String mCurrentPhotoPath; private TextView tvLauchSelection; private ImageView ivSelected; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: snack(ivSelected, "No magic here"); return true; case R.id.navigation_phone: if (handlePermission(Manifest.permission.READ_CONTACTS, REQUEST_SELECT_CONTACT)) { fetchContact(); } return true; case R.id.navigation_notifications: snack(ivSelected, "not here also"); return true; } return false; } }; private File imagefile; /*contact fields*/ private Uri contactUri; private ImageView ivPic; private TextView tvName; private TextView tvMobile; private CardView cvContact; /*contact fields ends*/ private void fetchContact() { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); intent.setType(Contacts.CONTENT_TYPE); if (intent.resolveActivity(getPackageManager()) != null) { startActivityForResult(intent, REQUEST_SELECT_CONTACT); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvLauchSelection = (TextView) findViewById(R.id.tvLauchSelection); ivSelected = (ImageView) findViewById(R.id.ivSelection); /*contact display view*/ cvContact = (CardView) findViewById(R.id.cvContact); ivPic = (ImageView) findViewById(R.id.ivPic); tvName = (TextView) findViewById(R.id.tvName); tvMobile = (TextView) findViewById(R.id.tvMobile); /*contact displat view end*/ tvLauchSelection.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { initSelectionSetup(); } }); mImageBitmap = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { mAlbumStorageDirFactory = new FroyoAlbumDirFactory(); } else { mAlbumStorageDirFactory = new BaseAlbumDirFactory(); } BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); } private void initSelectionSetup() { if (handlePermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_EXTERNAL_STORAGE)) { dispatchTakePictureIntent(ACTION_TAKE_PHOTO); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_EXTERNAL_STORAGE) { for (int i = 0; i < permissions.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { snack(ivSelected, "Permission Granted"); initSelectionSetup(); } } } if (requestCode == REQUEST_SELECT_CONTACT) { for (int i = 0; i < permissions.length; i++) { if (grantResults[i] == PackageManager.PERMISSION_GRANTED) { snack(ivSelected, "Permission Granted"); fetchContact(); } } } } /* Photo album for this application */ private String getAlbumName() { return getString(R.string.album_name); } private File getAlbumDir() { File storageDir = null; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName()); if (storageDir != null) { if (!storageDir.mkdirs()) { if (!storageDir.exists()) { snack(ivSelected, " failed to create directory"); return null; } } } } return storageDir; } private File setUpPhotoFile() throws IOException { imagefile = createImageFile(); mCurrentPhotoPath = imagefile.getAbsolutePath(); return imagefile; } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_"; File albumF = getAlbumDir(); File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF); return imageF; } private void setPic() { Picasso.with(context).load(Uri.fromFile(imagefile)).into(ivSelected); ivSelected.setVisibility(View.VISIBLE); } private void galleryAddPic() { Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE"); File f = new File(mCurrentPhotoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent); } private void dispatchTakePictureIntent(int actionCode) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File f = null; try { f = setUpPhotoFile(); mCurrentPhotoPath = f.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); } catch (IOException e) { e.printStackTrace(); f = null; mCurrentPhotoPath = null; } startActivityForResult(takePictureIntent, actionCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case ACTION_TAKE_PHOTO: if (resultCode == RESULT_OK) { handleBigCameraPhoto(); } break; case REQUEST_SELECT_CONTACT: contactUri = data.getData(); retrieveContactName(); retrieveContactNumber(); retrieveContactPhoto(); cvContact.setVisibility(View.VISIBLE); break; } // switch } /*phone*/ private void retrieveContactPhoto() { Bitmap photo = null; InputStream inpStream = null; try { inpStream = Contacts.openContactPhotoInputStream(getContentResolver(), ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.valueOf(contactID))); if (inpStream != null) { photo = BitmapFactory.decodeStream(inpStream); ivPic.setImageBitmap(photo); } } catch (Exception e) { snack(ivPic, e.getMessage()); } } private void retrieveContactNumber() { String contactNumber = null; // getting contacts ID Cursor cursorID = getContentResolver().query(contactUri, new String[]{ContactsContract.Contacts._ID}, null, null, null); if (cursorID.moveToFirst()) { contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID)); } cursorID.close(); // Using the contact ID now we will get contact phone number Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " + ContactsContract.CommonDataKinds.Phone.TYPE + " = " + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, new String[]{contactID}, null); if (cursorPhone.moveToFirst()) { contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); } cursorPhone.close(); if (contactNumber != null) { tvMobile.setText(contactNumber); } } private void retrieveContactName() { String contactName = null; // querying contact data store Cursor cursor = getContentResolver().query(contactUri, null, null, null, null); if (cursor.moveToFirst()) { // DISPLAY_NAME = The display name for the contact. // HAS_PHONE_NUMBER = An indicator of whether this contact has at least one phone number. contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); } cursor.close(); if (contactName != null) { tvName.setText(contactName); } } /*end phone*/ private void handleBigCameraPhoto() { if (mCurrentPhotoPath != null) { galleryAddPic(); setPic(); mCurrentPhotoPath = null; } } // Some lifecycle callbacks so that the image can survive orientation change @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap); outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null)); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY); ivSelected.setImageBitmap(mImageBitmap); ivSelected.setVisibility(savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE : ImageView.INVISIBLE ); } }
[ "xaidmetamorphos@gmail.com" ]
xaidmetamorphos@gmail.com
40cb1f04e8afc8e8e49f74815521ba6ea56af111
0a6ec9042d8e25fbe93b38cb9612bed1c87aa38c
/Algorithm_Practice/Level Test/src/Re_BJ1011.java
2c42b372dee27b0dc78ce9006a99c3b813b9d7f0
[]
no_license
park-seung-hyun/Data_Structure_And_Algorithm
053c1c5352abc88f83326c180ff5850abf4337dc
ed33a122bea99bc8cd72c7ff52e0a135e59ca378
refs/heads/master
2020-04-15T04:32:46.121017
2019-05-11T07:22:11
2019-05-11T07:22:11
164,387,726
1
0
null
null
null
null
UTF-8
Java
false
false
569
java
// 1011번 (복습) // Fly me to the Alpha Centauri // 규칙 찾기 import java.util.Scanner; public class Re_BJ1011 { static int[] visited; public static void main(String[] args) { Scanner stdIn = new Scanner (System.in); int t = stdIn.nextInt(); for(int i=0;i<t;i++) { int a = stdIn.nextInt(); int b = stdIn.nextInt(); System.out.println(solve(a,b)); } } static int solve(int a, int b) { int n = b-a; int k = (int) Math.sqrt(n); if(!(k*k == n)) { k+=1; } if(k*k-n < k) { return 2*k-1; }else { return 2*(k-1); } } }
[ "shp9408@gmail.com" ]
shp9408@gmail.com
9f98ff8d451e9e8966f40f8e9d5a00669066a09f
4800b21c8816a490baa33c15f0bdeca1bb30b841
/Lab4/server/src/main/java/LabServiceImplBaseImpl.java
5c629b97aef89db8e907e8085506973edcbf6663
[]
no_license
pawelurban/Rozprochy
8296f282f3dc4a5b4a5e6860a6afe864e75cd99b
316030a0fd7c8c062678be3abeb777417ba20926
refs/heads/master
2020-03-20T10:07:37.843249
2017-06-06T19:53:40
2017-06-06T19:53:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,886
java
import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.time.LocalDateTime; import java.util.Objects; public class LabServiceImplBaseImpl extends LabServiceGrpc.LabServiceImplBase { @Override public void addResults(Hospital.AddExamRequest request, StreamObserver<Hospital.Response> responseObserver) { checkPerms(request.getLab()); Hospital.Doctor doctor = Server.doctors.get(request.getDoctor()); Hospital.Patient patient = Server.patients.get(request.getPatient()); if(Objects.isNull(doctor) || Objects.isNull(patient)) { throw new StatusRuntimeException(Status.NOT_FOUND); } Hospital.Lab lab = Server.labs.get(request.getLab()); Hospital.MedicalExam medicalExam = Hospital.MedicalExam.newBuilder() .setDoctor(doctor) .setLab(lab) .setPatient(patient) .setTime(LocalDateTime.now().toString()) .putAllResults(request.getResultsMap()) .build(); synchronized (Server.exams) { Server.exams.add(medicalExam); } responseObserver.onNext(Hospital.Response.getDefaultInstance()); responseObserver.onCompleted(); } @Override public void requestAllResultsForLab(Hospital.Request request, StreamObserver<Hospital.MedicalExam> responseObserver) { checkPerms(request.getId()); synchronized (Server.exams) { Server.exams.stream().filter(e -> e.getLab().getPerson().getId() == request.getId()) .forEach(responseObserver::onNext); } responseObserver.onCompleted(); } private void checkPerms(long id) { if(Objects.isNull(Server.labs.get(id))) { throw new StatusRuntimeException(Status.PERMISSION_DENIED); } } }
[ "19mariusz95@gmail.com" ]
19mariusz95@gmail.com
7fc578623e1494d88ab20d27d0e15c17918ba0fb
eb36ddb1e9c25d2a35d1fc94abaa6ef0f8fa6f7b
/src/main/java/POGOProtos/Rpc/EncounterTutorialCompleteOutProto.java
6f815ec5b094b42289f577ada51892dce477dbd3
[ "BSD-3-Clause" ]
permissive
pokemongo-dev-contrib/pogoprotos-java
bbc941b238c051fd1430d364fae108604b13eebd
af129776faf08bfbfc69b32e19e8293bff2e8991
refs/heads/master
2021-06-10T15:45:44.441267
2021-02-04T21:46:16
2021-02-04T21:46:16
83,863,204
6
1
NOASSERTION
2020-10-17T20:10:32
2017-03-04T03:51:45
Java
UTF-8
Java
false
true
33,867
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos.Rpc.proto package POGOProtos.Rpc; /** * Protobuf type {@code POGOProtos.Rpc.EncounterTutorialCompleteOutProto} */ public final class EncounterTutorialCompleteOutProto extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:POGOProtos.Rpc.EncounterTutorialCompleteOutProto) EncounterTutorialCompleteOutProtoOrBuilder { private static final long serialVersionUID = 0L; // Use EncounterTutorialCompleteOutProto.newBuilder() to construct. private EncounterTutorialCompleteOutProto(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private EncounterTutorialCompleteOutProto() { result_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new EncounterTutorialCompleteOutProto(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private EncounterTutorialCompleteOutProto( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { int rawValue = input.readEnum(); result_ = rawValue; break; } case 18: { POGOProtos.Rpc.PokemonProto.Builder subBuilder = null; if (pokemon_ != null) { subBuilder = pokemon_.toBuilder(); } pokemon_ = input.readMessage(POGOProtos.Rpc.PokemonProto.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(pokemon_); pokemon_ = subBuilder.buildPartial(); } break; } case 26: { POGOProtos.Rpc.CaptureScoreProto.Builder subBuilder = null; if (scores_ != null) { subBuilder = scores_.toBuilder(); } scores_ = input.readMessage(POGOProtos.Rpc.CaptureScoreProto.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(scores_); scores_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_EncounterTutorialCompleteOutProto_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_EncounterTutorialCompleteOutProto_fieldAccessorTable .ensureFieldAccessorsInitialized( POGOProtos.Rpc.EncounterTutorialCompleteOutProto.class, POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Builder.class); } /** * Protobuf enum {@code POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result} */ public enum Result implements com.google.protobuf.ProtocolMessageEnum { /** * <code>UNSET = 0;</code> */ UNSET(0), /** * <code>SUCCESS = 1;</code> */ SUCCESS(1), /** * <code>ERROR_INVALID_POKEMON = 2;</code> */ ERROR_INVALID_POKEMON(2), UNRECOGNIZED(-1), ; /** * <code>UNSET = 0;</code> */ public static final int UNSET_VALUE = 0; /** * <code>SUCCESS = 1;</code> */ public static final int SUCCESS_VALUE = 1; /** * <code>ERROR_INVALID_POKEMON = 2;</code> */ public static final int ERROR_INVALID_POKEMON_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static Result valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static Result forNumber(int value) { switch (value) { case 0: return UNSET; case 1: return SUCCESS; case 2: return ERROR_INVALID_POKEMON; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Result> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< Result> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Result>() { public Result findValueByNumber(int number) { return Result.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return POGOProtos.Rpc.EncounterTutorialCompleteOutProto.getDescriptor().getEnumTypes().get(0); } private static final Result[] VALUES = values(); public static Result valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private Result(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result) } public static final int RESULT_FIELD_NUMBER = 1; private int result_; /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @return The enum numeric value on the wire for result. */ @java.lang.Override public int getResultValue() { return result_; } /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @return The result. */ @java.lang.Override public POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result getResult() { @SuppressWarnings("deprecation") POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result.valueOf(result_); return result == null ? POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result.UNRECOGNIZED : result; } public static final int POKEMON_FIELD_NUMBER = 2; private POGOProtos.Rpc.PokemonProto pokemon_; /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> * @return Whether the pokemon field is set. */ @java.lang.Override public boolean hasPokemon() { return pokemon_ != null; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> * @return The pokemon. */ @java.lang.Override public POGOProtos.Rpc.PokemonProto getPokemon() { return pokemon_ == null ? POGOProtos.Rpc.PokemonProto.getDefaultInstance() : pokemon_; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ @java.lang.Override public POGOProtos.Rpc.PokemonProtoOrBuilder getPokemonOrBuilder() { return getPokemon(); } public static final int SCORES_FIELD_NUMBER = 3; private POGOProtos.Rpc.CaptureScoreProto scores_; /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> * @return Whether the scores field is set. */ @java.lang.Override public boolean hasScores() { return scores_ != null; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> * @return The scores. */ @java.lang.Override public POGOProtos.Rpc.CaptureScoreProto getScores() { return scores_ == null ? POGOProtos.Rpc.CaptureScoreProto.getDefaultInstance() : scores_; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ @java.lang.Override public POGOProtos.Rpc.CaptureScoreProtoOrBuilder getScoresOrBuilder() { return getScores(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (result_ != POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result.UNSET.getNumber()) { output.writeEnum(1, result_); } if (pokemon_ != null) { output.writeMessage(2, getPokemon()); } if (scores_ != null) { output.writeMessage(3, getScores()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (result_ != POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result.UNSET.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, result_); } if (pokemon_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, getPokemon()); } if (scores_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, getScores()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof POGOProtos.Rpc.EncounterTutorialCompleteOutProto)) { return super.equals(obj); } POGOProtos.Rpc.EncounterTutorialCompleteOutProto other = (POGOProtos.Rpc.EncounterTutorialCompleteOutProto) obj; if (result_ != other.result_) return false; if (hasPokemon() != other.hasPokemon()) return false; if (hasPokemon()) { if (!getPokemon() .equals(other.getPokemon())) return false; } if (hasScores() != other.hasScores()) return false; if (hasScores()) { if (!getScores() .equals(other.getScores())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESULT_FIELD_NUMBER; hash = (53 * hash) + result_; if (hasPokemon()) { hash = (37 * hash) + POKEMON_FIELD_NUMBER; hash = (53 * hash) + getPokemon().hashCode(); } if (hasScores()) { hash = (37 * hash) + SCORES_FIELD_NUMBER; hash = (53 * hash) + getScores().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(POGOProtos.Rpc.EncounterTutorialCompleteOutProto prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code POGOProtos.Rpc.EncounterTutorialCompleteOutProto} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:POGOProtos.Rpc.EncounterTutorialCompleteOutProto) POGOProtos.Rpc.EncounterTutorialCompleteOutProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_EncounterTutorialCompleteOutProto_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_EncounterTutorialCompleteOutProto_fieldAccessorTable .ensureFieldAccessorsInitialized( POGOProtos.Rpc.EncounterTutorialCompleteOutProto.class, POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Builder.class); } // Construct using POGOProtos.Rpc.EncounterTutorialCompleteOutProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); result_ = 0; if (pokemonBuilder_ == null) { pokemon_ = null; } else { pokemon_ = null; pokemonBuilder_ = null; } if (scoresBuilder_ == null) { scores_ = null; } else { scores_ = null; scoresBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return POGOProtos.Rpc.POGOProtosRpc.internal_static_POGOProtos_Rpc_EncounterTutorialCompleteOutProto_descriptor; } @java.lang.Override public POGOProtos.Rpc.EncounterTutorialCompleteOutProto getDefaultInstanceForType() { return POGOProtos.Rpc.EncounterTutorialCompleteOutProto.getDefaultInstance(); } @java.lang.Override public POGOProtos.Rpc.EncounterTutorialCompleteOutProto build() { POGOProtos.Rpc.EncounterTutorialCompleteOutProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public POGOProtos.Rpc.EncounterTutorialCompleteOutProto buildPartial() { POGOProtos.Rpc.EncounterTutorialCompleteOutProto result = new POGOProtos.Rpc.EncounterTutorialCompleteOutProto(this); result.result_ = result_; if (pokemonBuilder_ == null) { result.pokemon_ = pokemon_; } else { result.pokemon_ = pokemonBuilder_.build(); } if (scoresBuilder_ == null) { result.scores_ = scores_; } else { result.scores_ = scoresBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof POGOProtos.Rpc.EncounterTutorialCompleteOutProto) { return mergeFrom((POGOProtos.Rpc.EncounterTutorialCompleteOutProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(POGOProtos.Rpc.EncounterTutorialCompleteOutProto other) { if (other == POGOProtos.Rpc.EncounterTutorialCompleteOutProto.getDefaultInstance()) return this; if (other.result_ != 0) { setResultValue(other.getResultValue()); } if (other.hasPokemon()) { mergePokemon(other.getPokemon()); } if (other.hasScores()) { mergeScores(other.getScores()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { POGOProtos.Rpc.EncounterTutorialCompleteOutProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (POGOProtos.Rpc.EncounterTutorialCompleteOutProto) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int result_ = 0; /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @return The enum numeric value on the wire for result. */ @java.lang.Override public int getResultValue() { return result_; } /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @param value The enum numeric value on the wire for result to set. * @return This builder for chaining. */ public Builder setResultValue(int value) { result_ = value; onChanged(); return this; } /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @return The result. */ @java.lang.Override public POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result getResult() { @SuppressWarnings("deprecation") POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result.valueOf(result_); return result == null ? POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result.UNRECOGNIZED : result; } /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @param value The result to set. * @return This builder for chaining. */ public Builder setResult(POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result value) { if (value == null) { throw new NullPointerException(); } result_ = value.getNumber(); onChanged(); return this; } /** * <code>.POGOProtos.Rpc.EncounterTutorialCompleteOutProto.Result result = 1;</code> * @return This builder for chaining. */ public Builder clearResult() { result_ = 0; onChanged(); return this; } private POGOProtos.Rpc.PokemonProto pokemon_; private com.google.protobuf.SingleFieldBuilderV3< POGOProtos.Rpc.PokemonProto, POGOProtos.Rpc.PokemonProto.Builder, POGOProtos.Rpc.PokemonProtoOrBuilder> pokemonBuilder_; /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> * @return Whether the pokemon field is set. */ public boolean hasPokemon() { return pokemonBuilder_ != null || pokemon_ != null; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> * @return The pokemon. */ public POGOProtos.Rpc.PokemonProto getPokemon() { if (pokemonBuilder_ == null) { return pokemon_ == null ? POGOProtos.Rpc.PokemonProto.getDefaultInstance() : pokemon_; } else { return pokemonBuilder_.getMessage(); } } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ public Builder setPokemon(POGOProtos.Rpc.PokemonProto value) { if (pokemonBuilder_ == null) { if (value == null) { throw new NullPointerException(); } pokemon_ = value; onChanged(); } else { pokemonBuilder_.setMessage(value); } return this; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ public Builder setPokemon( POGOProtos.Rpc.PokemonProto.Builder builderForValue) { if (pokemonBuilder_ == null) { pokemon_ = builderForValue.build(); onChanged(); } else { pokemonBuilder_.setMessage(builderForValue.build()); } return this; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ public Builder mergePokemon(POGOProtos.Rpc.PokemonProto value) { if (pokemonBuilder_ == null) { if (pokemon_ != null) { pokemon_ = POGOProtos.Rpc.PokemonProto.newBuilder(pokemon_).mergeFrom(value).buildPartial(); } else { pokemon_ = value; } onChanged(); } else { pokemonBuilder_.mergeFrom(value); } return this; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ public Builder clearPokemon() { if (pokemonBuilder_ == null) { pokemon_ = null; onChanged(); } else { pokemon_ = null; pokemonBuilder_ = null; } return this; } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ public POGOProtos.Rpc.PokemonProto.Builder getPokemonBuilder() { onChanged(); return getPokemonFieldBuilder().getBuilder(); } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ public POGOProtos.Rpc.PokemonProtoOrBuilder getPokemonOrBuilder() { if (pokemonBuilder_ != null) { return pokemonBuilder_.getMessageOrBuilder(); } else { return pokemon_ == null ? POGOProtos.Rpc.PokemonProto.getDefaultInstance() : pokemon_; } } /** * <code>.POGOProtos.Rpc.PokemonProto pokemon = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< POGOProtos.Rpc.PokemonProto, POGOProtos.Rpc.PokemonProto.Builder, POGOProtos.Rpc.PokemonProtoOrBuilder> getPokemonFieldBuilder() { if (pokemonBuilder_ == null) { pokemonBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< POGOProtos.Rpc.PokemonProto, POGOProtos.Rpc.PokemonProto.Builder, POGOProtos.Rpc.PokemonProtoOrBuilder>( getPokemon(), getParentForChildren(), isClean()); pokemon_ = null; } return pokemonBuilder_; } private POGOProtos.Rpc.CaptureScoreProto scores_; private com.google.protobuf.SingleFieldBuilderV3< POGOProtos.Rpc.CaptureScoreProto, POGOProtos.Rpc.CaptureScoreProto.Builder, POGOProtos.Rpc.CaptureScoreProtoOrBuilder> scoresBuilder_; /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> * @return Whether the scores field is set. */ public boolean hasScores() { return scoresBuilder_ != null || scores_ != null; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> * @return The scores. */ public POGOProtos.Rpc.CaptureScoreProto getScores() { if (scoresBuilder_ == null) { return scores_ == null ? POGOProtos.Rpc.CaptureScoreProto.getDefaultInstance() : scores_; } else { return scoresBuilder_.getMessage(); } } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ public Builder setScores(POGOProtos.Rpc.CaptureScoreProto value) { if (scoresBuilder_ == null) { if (value == null) { throw new NullPointerException(); } scores_ = value; onChanged(); } else { scoresBuilder_.setMessage(value); } return this; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ public Builder setScores( POGOProtos.Rpc.CaptureScoreProto.Builder builderForValue) { if (scoresBuilder_ == null) { scores_ = builderForValue.build(); onChanged(); } else { scoresBuilder_.setMessage(builderForValue.build()); } return this; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ public Builder mergeScores(POGOProtos.Rpc.CaptureScoreProto value) { if (scoresBuilder_ == null) { if (scores_ != null) { scores_ = POGOProtos.Rpc.CaptureScoreProto.newBuilder(scores_).mergeFrom(value).buildPartial(); } else { scores_ = value; } onChanged(); } else { scoresBuilder_.mergeFrom(value); } return this; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ public Builder clearScores() { if (scoresBuilder_ == null) { scores_ = null; onChanged(); } else { scores_ = null; scoresBuilder_ = null; } return this; } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ public POGOProtos.Rpc.CaptureScoreProto.Builder getScoresBuilder() { onChanged(); return getScoresFieldBuilder().getBuilder(); } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ public POGOProtos.Rpc.CaptureScoreProtoOrBuilder getScoresOrBuilder() { if (scoresBuilder_ != null) { return scoresBuilder_.getMessageOrBuilder(); } else { return scores_ == null ? POGOProtos.Rpc.CaptureScoreProto.getDefaultInstance() : scores_; } } /** * <code>.POGOProtos.Rpc.CaptureScoreProto scores = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< POGOProtos.Rpc.CaptureScoreProto, POGOProtos.Rpc.CaptureScoreProto.Builder, POGOProtos.Rpc.CaptureScoreProtoOrBuilder> getScoresFieldBuilder() { if (scoresBuilder_ == null) { scoresBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< POGOProtos.Rpc.CaptureScoreProto, POGOProtos.Rpc.CaptureScoreProto.Builder, POGOProtos.Rpc.CaptureScoreProtoOrBuilder>( getScores(), getParentForChildren(), isClean()); scores_ = null; } return scoresBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:POGOProtos.Rpc.EncounterTutorialCompleteOutProto) } // @@protoc_insertion_point(class_scope:POGOProtos.Rpc.EncounterTutorialCompleteOutProto) private static final POGOProtos.Rpc.EncounterTutorialCompleteOutProto DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new POGOProtos.Rpc.EncounterTutorialCompleteOutProto(); } public static POGOProtos.Rpc.EncounterTutorialCompleteOutProto getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<EncounterTutorialCompleteOutProto> PARSER = new com.google.protobuf.AbstractParser<EncounterTutorialCompleteOutProto>() { @java.lang.Override public EncounterTutorialCompleteOutProto parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new EncounterTutorialCompleteOutProto(input, extensionRegistry); } }; public static com.google.protobuf.Parser<EncounterTutorialCompleteOutProto> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<EncounterTutorialCompleteOutProto> getParserForType() { return PARSER; } @java.lang.Override public POGOProtos.Rpc.EncounterTutorialCompleteOutProto getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
[ "msntchat@hotmail.fr" ]
msntchat@hotmail.fr
a367e3a53b506246ce739dcfafa6d13300710610
4b97c615878008844deb7aa687d689a751e6a190
/megamind-server-app/app/src/main/java/com/megamind/abdul/server/DisclaimerActivity.java
5b5abae790e9940b7113fdeb8cde396c14e4110b
[]
no_license
ShrutikaSingh/Tex_TE_Project
cfbec88e3e0920ccefbc2690050f3113f14b2d98
f3d268072cb0a3c03b941f580a6a135deb13a7ee
refs/heads/master
2020-05-16T03:42:39.459323
2019-04-22T15:30:46
2019-04-22T15:30:46
182,740,931
0
0
null
null
null
null
UTF-8
Java
false
false
350
java
package com.megamind.abdul.server; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class DisclaimerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_disclaimer); } }
[ "you@example.com" ]
you@example.com
2140bbd0c1f594062cfb1dcc3e5cd07686a0e810
4838b0aa27864b87fd110f67c8c86da7e81f8107
/src/main/java/com/donat/donchess/config/WebConfiguration.java
50e47c2c4aaf8b598c62c5da5b4a7de0700ac43e
[]
no_license
udvarid/donchess_ver2
8a4cc8dd5a5a910890c383adb7f20682786c5fb3
d0171f34554fd6c4bd3e4455ac7243a995abd24a
refs/heads/master
2022-10-04T15:56:54.091949
2020-04-08T03:42:01
2020-04-08T03:42:01
189,479,754
0
0
null
2022-09-22T18:56:43
2019-05-30T20:41:48
Java
UTF-8
Java
false
false
1,012
java
package com.donat.donchess.config; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * A web MVC konfigurációja. */ @Configuration @EnableWebMvc public class WebConfiguration implements WebMvcConfigurer { private final Environment environment; /** * DI constructor * * @param environment DI bean */ public WebConfiguration(Environment environment) { this.environment = environment; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html"); } }
[ "udvarid@hotmail.com" ]
udvarid@hotmail.com
587e078ed9be5804d09f5c755ee178215b3a74a3
fe3a061968e26cc0f4462326f89cb7b788c53ad5
/Forchild000/src/com/forchild/data/imple/AnalysisSendValid.java
0b16ae8c687d8218b4e590a715abd27833326bbb
[]
no_license
reeki/ReekiTest
ffd7a6b354fa7a14c31fabac283ffde9912528fb
9bb1a3f440e767c3c1fb016805bdfd43119e08a7
refs/heads/master
2021-01-10T05:06:20.930104
2015-12-16T08:06:33
2015-12-16T08:06:33
47,959,404
0
0
null
null
null
null
UTF-8
Java
false
false
631
java
package com.forchild.data.imple; import org.json.JSONObject; import com.forchild.data.BaseProtocolFrame; import com.forchild.data.RequestSendSOS; import com.forchild.data.RequestSendValidCode; public class AnalysisSendValid implements BaseProtocolFrameProcess { @Override public BaseProtocolFrame parse(BaseProtocolFrame protocol, JSONObject json) { if (protocol != null && protocol instanceof RequestSendValidCode) { protocol.setReq(json.optInt("req", -1)); protocol.setIsResponse(true); return protocol; } return null; } @Override public int getType() { return BaseProtocolFrame.SEND_VALID_CODE; } }
[ "likizer0@hotmail.com" ]
likizer0@hotmail.com
72027e4439b7665f727db3452b2657d09918ee19
5af9e86fae132a36c4c62dfecbbd368996c385b1
/app/src/main/java/com/atheeshproperty/ddwed/NoteDAO.java
68c88733884b9c23cd226af2e64697e43305247b
[]
no_license
AtheeshRathnaweera/An-Android-Project-by-using-Android-Room-View-Model-Live-Data-libraries
47255b40e0abfa4c6bd36c872d8269d4960c9770
4c565840bfe75008bb7f2bfd9d8b368fde9522c5
refs/heads/master
2020-05-07T09:54:33.141069
2019-04-10T14:38:15
2019-04-10T14:38:15
180,396,619
1
0
null
null
null
null
UTF-8
Java
false
false
961
java
package com.atheeshproperty.ddwed; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import java.util.List; @Dao public interface NoteDAO {//This Dao is for "note" object // This is an interface( Also can be an abstract class ). // Because DAO(Data Access Object) only contains methods which doesnt have bodies @Insert void insert(Note note); @Update void update(Note note); @Delete void delete(Note note); @Query("DELETE FROM note_table")//Delete all data of note_table. We use @Query to define a database operation by ourselves void deleteAllNotes(); @Query("SELECT * FROM note_table ORDER BY priority DESC") LiveData<List<Note>> getAllNotes(); }
[ "rathnaweeraatheesh72@gmail.com" ]
rathnaweeraatheesh72@gmail.com
905a152d9ab512261941fa111b2ae4fcb9b7097e
9e10883092c7484acf042e6c9ab3f217a56945f3
/app/src/test/java/newspaperdemo/example/com/newspaper/ExampleUnitTest.java
926e07ed73079d7e37628d2d3d41b0d9a01d2c87
[]
no_license
nuruzzamn/newsPaper
eb863352a1147b7df9ed2e0ff12897b3719472bc
bce46cba9be2d25e512a3b4c88356e8fe40e1610
refs/heads/master
2020-08-30T13:08:25.802505
2019-10-29T21:53:53
2019-10-29T21:53:53
218,390,509
0
0
null
null
null
null
UTF-8
Java
false
false
413
java
package newspaperdemo.example.com.newspaper; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "nur.mnzaman@gmail.com" ]
nur.mnzaman@gmail.com
8d2f7cf565c0587537b7b249b61714089a7cae87
368c663f8d031f576e3add37dde8e9052dc628d8
/java/bbop/tags/bbop-1.000/src/org/bbop/expression/parser/ASTEQNode.java
6ab28d40850d392105fdd87f167c1c92dcc0e3c0
[]
no_license
mahmoudimus/obo-edit
494a588830758ddbd7cf43d2e70550ddd542cb1b
61c146958fd7d0ba7f78cda77f56d45849897b3e
refs/heads/master
2022-01-31T22:59:21.316185
2014-03-20T17:05:47
2014-03-20T17:05:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,921
java
/* * Copyright 2002-2006 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.bbop.expression.parser; import org.bbop.expression.JexlContext; import org.bbop.expression.util.Coercion; /** * Represents equality between values. * * If the values are of the same class, .equals() is used. * * If either value is a {@link Float} or {@link Double} (but both are not the same class), * the values are coerced to {@link Double}s before comparing. * * If either value is a {@link Number} or {@link Character} (but both are not the same class), * the values are coerced to {@link Long}s before comparing. * * If either value is a {@link Boolean} (but both are not the same class), * the values are coerced to {@link Boolean}s before comparing. * * If either value is a {@link String} (but both are not the same class), * toString() is called on both before comparing. * * Otherwise left.equals(right) is returned. * * @author <a href="mailto:geirm@apache.org">Geir Magnusson Jr.</a> * @version $Id: ASTEQNode.java,v 1.2 2007/09/27 01:02:09 jmr39 Exp $ */ public class ASTEQNode extends SimpleNode { /** * Create the node given an id. * * @param id node id. */ public ASTEQNode(int id) { super(id); } /** * Create a node with the given parser and id. * * @param p a parser. * @param id node id. */ public ASTEQNode(Parser p, int id) { super(p, id); } /** {@inheritDoc} */ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } /** {@inheritDoc} */ public Object value(JexlContext pc) throws Exception { Object left = ((SimpleNode) jjtGetChild(0)).value(pc); Object right = ((SimpleNode) jjtGetChild(1)).value(pc); if (left == null && right == null) { /* * if both are null L == R */ return Boolean.TRUE; } else if (left == null || right == null) { /* * we know both aren't null, therefore L != R */ return Boolean.FALSE; } else if (left.getClass().equals(right.getClass())) { return left.equals(right) ? Boolean.TRUE : Boolean.FALSE; } else if (left instanceof Float || left instanceof Double || right instanceof Float || right instanceof Double) { Double l = Coercion.coerceDouble(left); Double r = Coercion.coerceDouble(right); return l.equals(r) ? Boolean.TRUE : Boolean.FALSE; } else if (left instanceof Number || right instanceof Number || left instanceof Character || right instanceof Character) { return Coercion.coerceLong(left).equals(Coercion.coerceLong(right)) ? Boolean.TRUE : Boolean.FALSE; } else if (left instanceof Boolean || right instanceof Boolean) { return Coercion.coerceBoolean(left).equals( Coercion.coerceBoolean(right)) ? Boolean.TRUE : Boolean.FALSE; } else if (left instanceof java.lang.String || right instanceof String) { return left.toString().equals(right.toString()) ? Boolean.TRUE : Boolean.FALSE; } return left.equals(right) ? Boolean.TRUE : Boolean.FALSE; } }
[ "jmr39@6f0e8829-b336-0410-acfb-cb9b228023ad" ]
jmr39@6f0e8829-b336-0410-acfb-cb9b228023ad
c754af3e6ec29cd921d3ab1869e22c12b15aa23c
e26e5b697473326f1bfa2def3fbd427363f82251
/src/Modelo/FachadaMundo.java
1627dd7b31fb4ce6806fa214a14fbd4dc2427432
[]
no_license
diegorodriguezv/SimEvac
ea59ec10fbb2c24f2f3e98ea116d2d095f4960d1
4585a2e9cce9187a563c23aaed0183d171260336
refs/heads/master
2021-01-01T15:49:57.297215
2010-07-01T06:43:46
2010-07-01T06:43:46
750,790
1
0
null
null
null
null
UTF-8
Java
false
false
24,669
java
package Modelo; import Persistencia.Xml; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Double; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; public class FachadaMundo { private static final double GROSOR_PARED = 0.4F; private ArrayList<ObjetoSimulación> paredes; private ArrayList<Agente> agentes; private Point2D.Double orígenVisualización, tamañoVisualización; public FachadaMundo(File archivo) { iniciarObjetos(archivo); } public ArrayList<ObjetoSimulación> getParedesCercanas(Point2D.Double p, double distancia) { ArrayList<ObjetoSimulación> objetosCercanos = new ArrayList<ObjetoSimulación>(); for (ObjetoSimulación objetoSimulación : paredes) { if (objetoSimulación.colisiona(p, distancia)) { objetosCercanos.add(objetoSimulación); } } return objetosCercanos; } public ArrayList<ObjetoSimulación> getObjetosCercanos(Point2D.Double p, double distancia) { ArrayList<ObjetoSimulación> objetosCercanos = new ArrayList<ObjetoSimulación>(); for (ObjetoSimulación objetoSimulación : paredes) { if (objetoSimulación.colisiona(p, distancia)) { objetosCercanos.add(objetoSimulación); } } for (ObjetoSimulación objetoSimulación : agentes) { if (objetoSimulación.colisiona(p, distancia)) { objetosCercanos.add(objetoSimulación); } } return objetosCercanos; } public ArrayList<Agente> getAgentesCercanos(Point2D.Double p, double distancia) { ArrayList<Agente> agentesCercanos = new ArrayList<Agente>(); for (Agente agente : agentes) { if (agente.colisiona(p, distancia)) { agentesCercanos.add(agente); } } return agentesCercanos; } public void actualizarTodos(long tiempo) { for (int i = 0; i < agentes.size(); i++) { Agente objeto = agentes.get(i); objeto.calcularFuerzas(); } for (int i = 0; i < agentes.size(); i++) { Agente objeto = agentes.get(i); objeto.actualizar(tiempo); } } public ArrayList<ObjetoSimulación> getObjetos() { return paredes; } public ArrayList<Agente> getAgentes() { return agentes; } private void iniciarObjetos(File archivo) { // CargarMundo1(); // CargarMundo2(); // CargarMundo3(); File dir1 = new File("."); try { System.out.println("Current dir : " + dir1.getCanonicalPath()); } catch (Exception e) { e.printStackTrace(); } if (archivo == null) { CargarMundo3(); } else { CargarMundoDesdeArchivo(archivo.getPath()); } } public void CargarMundoDesdeArchivo(String rutaArchivo) { Xml mundo = new Xml(rutaArchivo, "mundo"); System.out.println("cargando archivo: " + rutaArchivo); System.out.println("versión: " + mundo.child("versión").content()); System.out.println("título: " + mundo.child("título").content()); System.out.println("descripción: " + mundo.child("descripción").content()); paredes = new ArrayList<ObjetoSimulación>(); ObjetoSimulación nuevoObjeto; agentes = new ArrayList<Agente>(); Xml punto = mundo.child("visualización").children("punto").get(0); orígenVisualización = new Double(Float.parseFloat(punto.string("x")), Float.parseFloat(punto.string("y"))); punto = mundo.child("visualización").children("punto").get(1); tamañoVisualización = new Double(Float.parseFloat(punto.string("x")), Float.parseFloat(punto.string("y"))); for (Xml pared : mundo.child("paredes").children("pared")) { System.out.println("pared: " + pared.string("grosor")); Point2D.Double p1, p2; punto = pared.children("punto").get(0); p1 = new Double(Float.parseFloat(punto.string("x")), Float.parseFloat(punto.string("y"))); punto = pared.children("punto").get(1); p2 = new Double(Float.parseFloat(punto.string("x")), Float.parseFloat(punto.string("y"))); nuevoObjeto = new Pared(p1, p2, Float.parseFloat(pared.string("grosor"))); paredes.add(nuevoObjeto); System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } for (Xml puerta : mundo.child("puertas").children("puerta")) { System.out.println("pared: " + puerta.string("grosor")); Point2D.Double p1, p2; punto = puerta.children("punto").get(0); p1 = new Double(Float.parseFloat(punto.string("x")), Float.parseFloat(punto.string("y"))); punto = puerta.children("punto").get(1); p2 = new Double(Float.parseFloat(punto.string("x")), Float.parseFloat(punto.string("y"))); nuevoObjeto = new Puerta(p1, p2, Float.parseFloat(puerta.string("grosor"))); paredes.add(nuevoObjeto); System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } Xml movimientos = mundo.child("agentes").child("movimientos"); System.out.println("movimientos: " + movimientos.string("directorio")); String dir = movimientos.string("directorio"); Map<String, ArrayList<Point2D.Double>> rutasMap = new HashMap<String, ArrayList<Double>>(); Map<String, IMovimiento> movimientosMap = new HashMap<String, IMovimiento>(); for (Xml ruta : movimientos.child("rutas").children("ruta")) { ArrayList<Point2D.Double> estaRuta = new ArrayList<Double>(); System.out.println("ruta: " + ruta.string("nombre")); for (Xml puntoRuta : ruta.children("punto")) { System.out.println("x,y: " + puntoRuta.string("x") + "," + puntoRuta.string("y")); estaRuta.add(new Double(Float.parseFloat(puntoRuta.string("x")), Float.parseFloat(puntoRuta.string("y")))); } rutasMap.put(ruta.string("nombre"), estaRuta); } for (Xml movimiento : movimientos.children("movimiento")) { System.out.println("movimiento: " + movimiento.string("nombre") + movimiento.string("archivo")); movimientosMap.put(movimiento.string("nombre"), crearMovimiento(rutasMap.get(movimiento.string("ruta")), null)); } for (Xml multitud : mundo.child("agentes").children("multitud")) { System.out.println("cantidad: " + multitud.string("cantidad")); Xml esquinaÁrea1 = multitud.child("área").children("punto").get(0); Xml esquinaÁrea2 = multitud.child("área").children("punto").get(1); Xml varAncho = multitud.child("variación_ancho"); System.out.println("[min,max]: [" + varAncho.string("min") + "," + varAncho.string("max") + "]"); Xml varLargoAncho = multitud.child("variación_relacion_largo_ancho"); System.out.println("[min,max]: [" + varLargoAncho.string("min") + "," + varLargoAncho.string("max") + "]"); construirMultitud(rutasMap.get(multitud.string("ruta")), new Double(Float.parseFloat(esquinaÁrea1.string("x")), Float.parseFloat(esquinaÁrea1.string("y"))), new Double(Float.parseFloat(esquinaÁrea2.string("x")), Float.parseFloat(esquinaÁrea2.string("y"))), Integer.parseInt(multitud.string("cantidad")), Float.parseFloat(varAncho.string("min")), Float.parseFloat(varAncho.string("max"))); } // agregar la referencia al mundo para todos los objetos for (ObjetoSimulación objetoSimulación : paredes) { objetoSimulación.setMundo(this); } for (Agente agente : agentes) { agente.setMundo(this); } } public Double getOrígenVisualización() { return orígenVisualización; } public Double getTamañoVisualización() { return tamañoVisualización; } private void ImprimirMundoDesdeArchivo(String rutaArchivo) { Xml mundo = new Xml(rutaArchivo, "mundo"); System.out.println("versión: " + mundo.child("versión").content()); System.out.println("título: " + mundo.child("título").content()); System.out.println("descripción: " + mundo.child("descripción").content()); for (Xml punto : mundo.child("visualización").children("punto")) { System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } for (Xml pared : mundo.child("paredes").children("pared")) { System.out.println("pared: " + pared.string("grosor")); for (Xml punto : pared.children("punto")) { System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } } for (Xml puerta : mundo.child("puertas").children("puerta")) { System.out.println("pared: " + puerta.string("grosor")); for (Xml punto : puerta.children("punto")) { System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } } for (Xml movimientos : mundo.child("agentes").children("movimientos")) { System.out.println("movimientos: " + movimientos.string("directorio")); for (Xml ruta : movimientos.child("rutas").children("ruta")) { System.out.println("ruta: " + ruta.string("nombre")); for (Xml punto : ruta.children("punto")) { System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } } for (Xml movimiento : movimientos.children("movimiento")) { System.out.println("movimiento: " + movimiento.string("nombre") + movimiento.string("archivo")); } } for (Xml multitud : mundo.child("agentes").children("multitud")) { System.out.println("cantidad: " + multitud.string("cantidad")); for (Xml punto : multitud.child("área").children("punto")) { System.out.println("x,y: " + punto.string("x") + "," + punto.string("y")); } Xml varAncho = multitud.child("variación_ancho"); System.out.println("[min,max]: [" + varAncho.string("min") + "," + varAncho.string("max") + "]"); Xml varLargoAncho = multitud.child("variación_relacion_largo_ancho"); System.out.println("[min,max]: [" + varLargoAncho.string("min") + "," + varLargoAncho.string("max") + "]"); } } private void CargarMundo1() { orígenVisualización = new Double(0, 0); tamañoVisualización = new Double(500, 500); paredes = new ArrayList<ObjetoSimulación>(); ObjetoSimulación nuevoObjeto; agentes = new ArrayList<Agente>(); Point2D.Double p1 = new Point2D.Double(50, 200); Point2D.Double p2 = new Point2D.Double(400, 200); Point2D.Double p3 = new Point2D.Double(400, 450); Point2D.Double p4 = new Point2D.Double(50, 250); Point2D.Double p5 = new Point2D.Double(350, 250); Point2D.Double p6 = new Point2D.Double(350, 450); Point2D.Double p7 = new Point2D.Double(250, 210); Point2D.Double p8 = new Point2D.Double(375, 225); Point2D.Double p9 = new Point2D.Double(375, 350); Point2D.Double p10 = new Point2D.Double(375, 495); nuevoObjeto = new Pared(p1, p2, 0.2f); paredes.add(nuevoObjeto); nuevoObjeto = new Pared(p2, p3, 0.2f); paredes.add(nuevoObjeto); nuevoObjeto = new Pared(p4, p5, 0.2f); paredes.add(nuevoObjeto); nuevoObjeto = new Pared(p5, p6, 0.2f); paredes.add(nuevoObjeto); nuevoObjeto = new Puerta(p1, p4, 0.2f); paredes.add(nuevoObjeto); nuevoObjeto = new Puerta(p6, p3, 0.2f); paredes.add(nuevoObjeto); ArrayList<Point2D.Double> ruta = new ArrayList<Point2D.Double>(); ruta.add(new Point2D.Double(100, 100)); ruta.add(new Point2D.Double(300, 100)); Agente nuevoAgente = new Agente(p7, 5f, 2.5f); nuevoAgente.setDestino(p10); nuevoAgente.setRapidez(2f); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); agentes.add(nuevoAgente); nuevoAgente = new Agente(p8, 5f, 2.5f); nuevoAgente.setDestino(p10); nuevoAgente.setRapidez(2f); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); agentes.add(nuevoAgente); nuevoAgente = new Agente(p9, 5f, 2.5f); nuevoAgente.setDestino(p10); nuevoAgente.setRapidez(2f); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); agentes.add(nuevoAgente); // agregar la referencia al mundo para todos los objetos for (ObjetoSimulación objetoSimulación : paredes) { objetoSimulación.setMundo(this); } for (Agente agente : agentes) { agente.setMundo(this); } } private void CargarMundo2() { orígenVisualización = new Double(0, 0); tamañoVisualización = new Double(500, 500); paredes = new ArrayList<ObjetoSimulación>(); ObjetoSimulación nuevoObjeto; agentes = new ArrayList<Agente>(); Point2D.Double p1; Point2D.Double p2; p1 = new Point2D.Double(250, 400); p2 = new Point2D.Double(250, 150); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 150); p2 = new Point2D.Double(400, 150); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 150); p2 = new Point2D.Double(200, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(100, 200); p2 = new Point2D.Double(200, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(100, 200); p2 = new Point2D.Double(100, 50); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(100, 50); p2 = new Point2D.Double(200, 50); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 50); p2 = new Point2D.Double(200, 100); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 100); p2 = new Point2D.Double(450, 100); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(450, 100); p2 = new Point2D.Double(450, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(450, 200); p2 = new Point2D.Double(300, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(300, 200); p2 = new Point2D.Double(300, 400); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(300, 400); p2 = new Point2D.Double(250, 400); nuevoObjeto = new Puerta(p1, p2, GROSOR_PARED * 8); paredes.add(nuevoObjeto); ArrayList<Point2D.Double> ruta = new ArrayList<Point2D.Double>(); ruta.add(new Point2D.Double(190, 125)); ruta.add(new Point2D.Double(400, 145)); ruta.add(new Point2D.Double(400, 155)); ruta.add(new Point2D.Double(300, 195)); ruta.add(new Point2D.Double(275, 360)); ruta.add(new Point2D.Double(275, 450)); Agente nuevoAgente = new Agente(new Point2D.Double(150, 100), 0.8f, 0.4f); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); agentes.add(nuevoAgente); nuevoAgente = new Agente(new Point2D.Double(150, 125), 0.8f, 0.4f); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); agentes.add(nuevoAgente); nuevoAgente = new Agente(new Point2D.Double(150, 190), 0.8f, 0.4f); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); agentes.add(nuevoAgente); // agregar la referencia al mundo para todos los objetos for (ObjetoSimulación objetoSimulación : paredes) { objetoSimulación.setMundo(this); } for (Agente agente : agentes) { agente.setMundo(this); } } private void CargarMundo3() { orígenVisualización = new Double(0, 0); tamañoVisualización = new Double(500, 500); paredes = new ArrayList<ObjetoSimulación>(); ObjetoSimulación nuevoObjeto; agentes = new ArrayList<Agente>(); Point2D.Double p1; Point2D.Double p2; p1 = new Point2D.Double(250, 400); p2 = new Point2D.Double(250, 150); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 150); p2 = new Point2D.Double(400, 150); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 130); p2 = new Point2D.Double(200, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(100, 200); p2 = new Point2D.Double(200, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(100, 200); p2 = new Point2D.Double(100, 50); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(100, 50); p2 = new Point2D.Double(200, 50); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 50); p2 = new Point2D.Double(200, 120); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(200, 100); p2 = new Point2D.Double(450, 100); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(450, 100); p2 = new Point2D.Double(450, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(450, 200); p2 = new Point2D.Double(300, 200); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(300, 200); p2 = new Point2D.Double(300, 400); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); // obstáculo p1 = new Point2D.Double(300, 150); p2 = new Point2D.Double(330, 130); nuevoObjeto = new Pared(p2, p1, GROSOR_PARED); paredes.add(nuevoObjeto); p1 = new Point2D.Double(330, 130); p2 = new Point2D.Double(340, 120); nuevoObjeto = new Pared(p1, p2, GROSOR_PARED); paredes.add(nuevoObjeto); // puerta p1 = new Point2D.Double(300, 400); p2 = new Point2D.Double(250, 400); nuevoObjeto = new Puerta(p1, p2, GROSOR_PARED * 8); paredes.add(nuevoObjeto); ArrayList<Point2D.Double> ruta = new ArrayList<Point2D.Double>(); ruta.add(new Point2D.Double(210, 125)); // ruta.add(new Point2D.Double(405, 145)); ruta.add(new Point2D.Double(410, 150)); ruta.add(new Point2D.Double(290, 200)); ruta.add(new Point2D.Double(275, 360)); ruta.add(new Point2D.Double(275, 450)); construirMultitud(ruta, new Double(105, 55), new Double(90, 140), 100, 0.5, 0.7); // agregar la referencia al mundo para todos los objetos for (ObjetoSimulación objetoSimulación : paredes) { objetoSimulación.setMundo(this); } for (Agente agente : agentes) { agente.setMundo(this); } } private void construirMultitud(ArrayList<Double> ruta, Point2D.Double orígenVentana, Point2D.Double tamañoVentana, int cantidad, double minRadio, double maxRadio) { for (int i = 0; i < cantidad; i++) { double x, y, ancho, largo; Point2D.Double orientación = new Double(); Random generador = new Random(); x = númeroAleatorio(orígenVentana.x, orígenVentana.x + tamañoVentana.x, generador); y = númeroAleatorio(orígenVentana.y, orígenVentana.y + tamañoVentana.y, generador); orientación.x = númeroAleatorio(0, 1, generador); orientación.y = númeroAleatorio(0, 1, generador); ancho = númeroAleatorio(minRadio, maxRadio, generador); largo = ancho * númeroAleatorio(0.4, 0.7, generador); // gordos y flacos // ancho = 10; // largo = 0.1; Agente nuevoAgente = new Agente(new Point2D.Double(x, y), ancho, largo); nuevoAgente.setEstrategiaMovimiento(crearMovimiento(ruta, nuevoAgente)); nuevoAgente.setOrientación(orientación); if (nuevoAgente.colisionaConAgentes(agentes).isEmpty()) { agentes.add(nuevoAgente); } else { i--; } } } private double númeroAleatorio(double rangoIni, double rangoFin, Random generador) { double num = generador.nextDouble(); // de 0.0 a 1.0 double resultado; resultado = num * (rangoFin - rangoIni) + rangoIni; return resultado; } private MovimientoHelbing crearMovimiento(ArrayList<Point2D.Double> ruta, Agente agente) { MovimientoHelbing nuevoMovimiento = new MovimientoHelbing(this, agente); nuevoMovimiento.setRuta(ruta); return nuevoMovimiento; } private void CargarMundoCalibración() { paredes = new ArrayList<ObjetoSimulación>(); ObjetoSimulación nuevoObjeto; agentes = new ArrayList<Agente>(); Point2D.Double puntoNuevo; Point2D.Double puntoAnterior; puntoAnterior = new Point2D.Double(0, 0); puntoNuevo = new Point2D.Double(0, 500); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = puntoNuevo; puntoNuevo = new Point2D.Double(500, 500); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = puntoNuevo; puntoNuevo = new Point2D.Double(500, 0); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = puntoNuevo; puntoNuevo = new Point2D.Double(0, 0); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = puntoNuevo; puntoNuevo = new Point2D.Double(500, 500); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = new Point2D.Double(500, 0); puntoNuevo = new Point2D.Double(0, 500); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = new Point2D.Double(250, 0); puntoNuevo = new Point2D.Double(250, 500); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); puntoAnterior = new Point2D.Double(0, 250); puntoNuevo = new Point2D.Double(500, 250); nuevoObjeto = new Pared(puntoAnterior, puntoNuevo, GROSOR_PARED); paredes.add(nuevoObjeto); // agregar la referencia al mundo para todos los objetos for (ObjetoSimulación objetoSimulación : paredes) { objetoSimulación.setMundo(this); } for (Agente agente : agentes) { agente.setMundo(this); } } }
[ "diegorodriguezv@gmail.com" ]
diegorodriguezv@gmail.com
44b146b967d44312eef5072054e4aa05d5ff67c6
44493cbda76efc9ae7de7f2e6fc084a988cfbf2d
/java8_7/Test_04.java
c8f60e9897e9dda75648bb4292d480e78f4ebc5b
[]
no_license
ximuyou/javase
06d9e74fac72a7838e1b5f10fa8159e930842290
50ea03e54a350ae4ddadb1c46a1bd570a58d6820
refs/heads/master
2020-03-25T10:42:30.623524
2018-08-07T03:29:36
2018-08-07T03:29:36
143,702,841
0
0
null
null
null
null
UTF-8
Java
false
false
761
java
package java8_7; public class Test_04 { public static void main(String[] args) { int[]arr=new int[]{2,3,45,666,0}; turnnum(arr); System.out.println(seach(arr,0)+1); } static int seach(int[]arr,int num){ int max=arr.length-1; int min=0; while(min<=max){ int mid=(max+min)/2; if(arr[mid]>num){ max=mid-1; } else if(arr[mid]<num){ min=mid+1; } else if(arr[mid]==num) return mid; } return -1; } static void turnnum(int[]arr){ for(int i=0;i<arr.length-1;i++){ for(int j=i+1;j>0;j--){ if(arr[j-1]>arr[j]) turn(arr,j-1,j); else break; } } } static void turn(int[]arr,int i,int j){ int num=arr[i]; arr[i]=arr[j]; arr[j]=num; } }
[ "3147448393@qq.com" ]
3147448393@qq.com
2d50c9abf97d00435c9397e6947c002420986935
de3f5c7c3021232cf53e452b938df688929fc345
/tags/Stable-030608/src/examples/tls/Shootist.java
fc16e9d94d883ad2795f133736d799f4f07d41bd
[ "LicenseRef-scancode-public-domain" ]
permissive
rkday/jain-sip
bd3f728948bdaafd98c17bb4843148edab74cd0d
cf52d49d540f8515b209352f861365dbe3d59d90
refs/heads/master
2021-01-22T09:26:50.309500
2014-01-25T19:59:06
2014-01-25T19:59:06
16,236,776
2
3
null
null
null
null
UTF-8
Java
false
false
12,253
java
package examples.tls; import javax.sip.*; import javax.sip.address.*; import javax.sip.header.*; import javax.sip.message.*; import java.util.*; /** * This class is a UAC template. Shootist is the guy that shoots and shootme * is the guy that gets shot. * *@author Daniel Martinez *@author Ivelin Ivanov */ public class Shootist implements SipListener { private static SipProvider tlsProvider; private static AddressFactory addressFactory; private static MessageFactory messageFactory; private static HeaderFactory headerFactory; private static SipStack sipStack; private int reInviteCount; private ContactHeader contactHeader; private ListeningPoint tlsListeningPoint; private int counter; protected ClientTransaction inviteTid; protected static final String usageString = "java " + "examples.shootistTLS.Shootist \n" + ">>>> is your class path set to the root?"; private static void usage() { System.out.println(usageString); System.exit(0); } private void shutDown() { try { try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("nulling reference"); sipStack.deleteListeningPoint(tlsListeningPoint); // This will close down the stack and exit all threads tlsProvider.removeSipListener(this); while (true) { try { sipStack.deleteSipProvider(tlsProvider); break; } catch (ObjectInUseException ex) { try { Thread.sleep(2000); } catch (InterruptedException e) { continue; } } } sipStack = null; tlsProvider = null; this.inviteTid = null; this.contactHeader = null; addressFactory = null; headerFactory = null; messageFactory = null; this.tlsListeningPoint = null; this.reInviteCount = 0; System.gc(); //Redo this from the start. if (counter < 10 ) this.init(); else counter ++; } catch (Exception ex) { ex.printStackTrace(); } } public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent.getServerTransaction(); System.out.println( "\n\nRequest " + request.getMethod() + " received at " + sipStack.getStackName() + " with server transaction id " + serverTransactionId); // We are the UAC so the only request we get is the BYE. if (request.getMethod().equals(Request.BYE)) processBye(request, serverTransactionId); } public void processBye( Request request, ServerTransaction serverTransactionId) { try { System.out.println("shootist: got a bye ."); if (serverTransactionId == null) { System.out.println("shootist: null TID."); return; } Dialog dialog = serverTransactionId.getDialog(); System.out.println("Dialog State = " + dialog.getState()); Response response = messageFactory.createResponse (200, request); serverTransactionId.sendResponse(response); System.out.println("shootist: Sending OK."); System.out.println("Dialog State = " + dialog.getState()); this.shutDown(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } } public void processResponse(ResponseEvent responseReceivedEvent) { System.out.println("Got a response"); Response response = (Response) responseReceivedEvent.getResponse(); Transaction tid = responseReceivedEvent.getClientTransaction(); System.out.println( "Response received with client transaction id " + tid + ":\n" + response.getStatusCode()); if (tid == null) { System.out.println("Stray response -- dropping "); return; } System.out.println("transaction state is " + tid.getState()); System.out.println("Dialog = " + tid.getDialog()); System.out.println("Dialog State is " + tid.getDialog().getState()); try { if (response.getStatusCode() == Response.OK && ((CSeqHeader) response.getHeader(CSeqHeader.NAME)) .getMethod() .equals( Request.INVITE)) { // Request cancel = inviteTid.createCancel(); // ClientTransaction ct = // sipProvider.getNewClientTransaction(cancel); // ct.sendRequest(); Dialog dialog = tid.getDialog(); Request ackRequest = dialog.createRequest(Request.ACK); System.out.println("Sending ACK"); dialog.sendAck(ackRequest); // Send a Re INVITE if (reInviteCount == 0) { Request inviteRequest = dialog.createRequest(Request.INVITE); //((SipURI)inviteRequest.getRequestURI()).removeParameter("transport"); //((ViaHeader)inviteRequest.getHeader(ViaHeader.NAME)).setTransport("tls"); // inviteRequest.addHeader(contactHeader); try {Thread.sleep(100); } catch (Exception ex) {} ClientTransaction ct = tlsProvider.getNewClientTransaction(inviteRequest); dialog.sendRequest(ct); reInviteCount ++; } } } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } } public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) { System.out.println("Transaction Time out" ); } public void init() { SipFactory sipFactory = null; sipStack = null; sipFactory = SipFactory.getInstance(); sipFactory.setPathName("gov.nist"); Properties properties = new Properties(); // If you want to try TCP transport change the following to String transport = "tcp"; String peerHostPort = "127.0.0.1:5071"; properties.setProperty("javax.sip.IP_ADDRESS", "127.0.0.1"); properties.setProperty( "javax.sip.OUTBOUND_PROXY", peerHostPort + "/" + transport); // If you want to use UDP then uncomment this. //properties.setProperty( // "javax.sip.ROUTER_PATH", // "examples.shootistTLS.MyRouter"); properties.setProperty("javax.sip.STACK_NAME", "shootist"); properties.setProperty("javax.sip.RETRANSMISSION_FILTER", "on"); // The following properties are specific to nist-sip // and are not necessarily part of any other jain-sip // implementation. // You can set a max message size for tcp transport to // guard against denial of service attack. properties.setProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE", "1048576"); properties.setProperty( "gov.nist.javax.sip.DEBUG_LOG", "shootistdebug.txt"); properties.setProperty( "gov.nist.javax.sip.SERVER_LOG", "shootistlog.txt"); // Drop the client connection after we are done with the transaction. properties.setProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS", "false"); // Set to 0 in your production code for max speed. // You need 16 for logging traces. 32 for debug + traces. // Your code will limp at 32 but it is best for debugging. properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "16"); try { // Create SipStack object sipStack = sipFactory.createSipStack(properties); System.out.println("createSipStack " + sipStack); } catch (PeerUnavailableException e) { // could not find // gov.nist.jain.protocol.ip.sip.SipStackImpl // in the classpath e.printStackTrace(); System.err.println(e.getMessage()); System.exit(0); } try { headerFactory = sipFactory.createHeaderFactory(); addressFactory = sipFactory.createAddressFactory(); messageFactory = sipFactory.createMessageFactory(); Shootist listener = this; tlsListeningPoint = sipStack.createListeningPoint (sipStack.getIPAddress(), 5060, "tcp"); tlsProvider = sipStack.createSipProvider(tlsListeningPoint); tlsProvider.addSipListener(listener); SipProvider sipProvider = tlsProvider; String fromName = "BigGuy"; String fromSipAddress = "here.com"; String fromDisplayName = "The Master Blaster"; String toSipAddress = "there.com"; String toUser = "LittleGuy"; String toDisplayName = "The Little Blister"; // create >From Header SipURI fromAddress = addressFactory.createSipURI(fromName, fromSipAddress); //fromAddress.setSecure(true); Address fromNameAddress = addressFactory.createAddress(fromAddress); fromNameAddress.setDisplayName(fromDisplayName); FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, "12345"); // create To Header SipURI toAddress = addressFactory.createSipURI(toUser, toSipAddress); //toAddress.setSecure(true); Address toNameAddress = addressFactory.createAddress(toAddress); toNameAddress.setDisplayName(toDisplayName); ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null); // create Request URI SipURI requestURI = addressFactory.createSipURI(toUser, peerHostPort); //requestURI.setSecure( true ); // Create ViaHeaders ArrayList viaHeaders = new ArrayList(); int port = sipProvider.getListeningPoint(transport).getPort(); ViaHeader viaHeader = headerFactory.createViaHeader( sipStack.getIPAddress(), port, transport, null); // add via headers viaHeaders.add(viaHeader); // Create ContentTypeHeader ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("application", "sdp"); // Create a new CallId header CallIdHeader callIdHeader = sipProvider.getNewCallId(); // Create a new Cseq header CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, Request.INVITE); // Create a new MaxForwardsHeader MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70); // Create the request. Request request = messageFactory.createRequest( requestURI, Request.INVITE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards); // Create contact headers String host = sipStack.getIPAddress(); //SipURI contactUrl = addressFactory.createSipURI(fromName, host); //contactUrl.setPort(tlsListeningPoint.getPort()); // Create the contact name address. SipURI contactURI = addressFactory.createSipURI(fromName, host); //contactURI.setSecure( true ); contactURI.setPort(port); contactURI.setTransportParam("tcp"); Address contactAddress = addressFactory.createAddress(contactURI); // Add the contact address. contactAddress.setDisplayName(fromName); contactHeader = headerFactory.createContactHeader(contactAddress); request.addHeader(contactHeader); // Add the extension header. Header extensionHeader = headerFactory.createHeader("My-Header", "my header value"); request.addHeader(extensionHeader); String sdpData = "v=0\r\n" + "o=4855 13760799956958020 13760799956958020" + " IN IP4 129.6.55.78\r\n" + "s=mysession session\r\n" + "p=+46 8 52018010\r\n" + "c=IN IP4 129.6.55.78\r\n" + "t=0 0\r\n" + "m=audio 6022 RTP/AVP 0 4 18\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n"; byte[] contents = sdpData.getBytes(); //byte[] contents = sdpBuff.toString().getBytes(); request.setContent(contents, contentTypeHeader); extensionHeader = headerFactory.createHeader( "My-Other-Header", "my new header value "); request.addHeader(extensionHeader); Header callInfoHeader = headerFactory.createHeader( "Call-Info", "<http://www.antd.nist.gov>"); request.addHeader(callInfoHeader); // Create the client transaction. listener.inviteTid = sipProvider.getNewClientTransaction(request); // send the request out. listener.inviteTid.sendRequest(); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); usage(); } } public static void main(String args[]) { new Shootist().init(); } public void processIOException(IOExceptionEvent exceptionEvent) { System.out.println("IOException occured while retransmitting requests:" + exceptionEvent); } public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { System.out.println("Transaction Terminated event: " + transactionTerminatedEvent ); } public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { System.out.println("Dialog Terminated event: " + dialogTerminatedEvent); } }
[ "(no author)@8e71dc83-d81e-6649-80f2-80b843a9b2be" ]
(no author)@8e71dc83-d81e-6649-80f2-80b843a9b2be
64756749d8e3ebd131531ce49a697f63699b0d79
ab739b2979a97faf0b28edac7d2995fc86921f39
/app/src/main/java/weka/classifiers/meta/Vote.java
4bcab684ba38e3832ffc13dbbe194648fa78bd13
[]
no_license
yishanhe/GlassGesture
286f79822217a7f147b88ef27bb05db1db934b7e
86e1b9718ab1fd61a4d43eb827059cc5879a21a0
refs/heads/master
2021-01-19T20:36:33.942863
2017-03-03T05:15:08
2017-03-03T05:15:08
83,759,471
2
0
null
null
null
null
UTF-8
Java
false
false
20,253
java
/* * 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 2 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Vote.java * Copyright (C) 2000 University of Waikato * Copyright (C) 2006 Roberto Perdisci * */ package weka.classifiers.meta; import weka.classifiers.RandomizableMultipleClassifiersCombiner; import weka.core.Capabilities; import weka.core.Instance; import weka.core.Instances; import weka.core.Option; import weka.core.RevisionUtils; import weka.core.SelectedTag; import weka.core.Tag; import weka.core.TechnicalInformation; import weka.core.TechnicalInformationHandler; import weka.core.Utils; import weka.core.Capabilities.Capability; import weka.core.TechnicalInformation.Field; import weka.core.TechnicalInformation.Type; import java.util.Enumeration; import java.util.Random; import java.util.Vector; /** <!-- globalinfo-start --> * Class for combining classifiers. Different combinations of probability estimates for classification are available.<br/> * <br/> * For more information see:<br/> * <br/> * Ludmila I. Kuncheva (2004). Combining Pattern Classifiers: Methods and Algorithms. John Wiley and Sons, Inc..<br/> * <br/> * J. Kittler, M. Hatef, Robert P.W. Duin, J. Matas (1998). On combining classifiers. IEEE Transactions on Pattern Analysis and Machine Intelligence. 20(3):226-239. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -S &lt;num&gt; * Random number seed. * (default 1)</pre> * * <pre> -B &lt;classifier specification&gt; * Full class name of classifier to include, followed * by scheme options. May be specified multiple times. * (default: "weka.classifiers.rules.ZeroR")</pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * * <pre> -R &lt;AVG|PROD|MAJ|MIN|MAX|MED&gt; * The combination rule to use * (default: AVG)</pre> * <!-- options-end --> * <!-- technical-bibtex-start --> * BibTeX: * <pre> * &#64;book{Kuncheva2004, * author = {Ludmila I. Kuncheva}, * publisher = {John Wiley and Sons, Inc.}, * title = {Combining Pattern Classifiers: Methods and Algorithms}, * year = {2004} * } * * &#64;article{Kittler1998, * author = {J. Kittler and M. Hatef and Robert P.W. Duin and J. Matas}, * journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, * number = {3}, * pages = {226-239}, * title = {On combining classifiers}, * volume = {20}, * year = {1998} * } * </pre> * <p/> <!-- technical-bibtex-end --> * * @author Alexander K. Seewald (alex@seewald.at) * @author Eibe Frank (eibe@cs.waikato.ac.nz) * @author Roberto Perdisci (roberto.perdisci@gmail.com) * @version $Revision: 5987 $ */ public class Vote extends RandomizableMultipleClassifiersCombiner implements TechnicalInformationHandler { /** for serialization */ static final long serialVersionUID = -637891196294399624L; /** combination rule: Average of Probabilities */ public static final int AVERAGE_RULE = 1; /** combination rule: Product of Probabilities (only nominal classes) */ public static final int PRODUCT_RULE = 2; /** combination rule: Majority Voting (only nominal classes) */ public static final int MAJORITY_VOTING_RULE = 3; /** combination rule: Minimum Probability */ public static final int MIN_RULE = 4; /** combination rule: Maximum Probability */ public static final int MAX_RULE = 5; /** combination rule: Median Probability (only numeric class) */ public static final int MEDIAN_RULE = 6; /** combination rules */ public static final Tag[] TAGS_RULES = { new Tag(AVERAGE_RULE, "AVG", "Average of Probabilities"), new Tag(PRODUCT_RULE, "PROD", "Product of Probabilities"), new Tag(MAJORITY_VOTING_RULE, "MAJ", "Majority Voting"), new Tag(MIN_RULE, "MIN", "Minimum Probability"), new Tag(MAX_RULE, "MAX", "Maximum Probability"), new Tag(MEDIAN_RULE, "MED", "Median") }; /** Combination Rule variable */ protected int m_CombinationRule = AVERAGE_RULE; /** the random number generator used for breaking ties in majority voting * @see #distributionForInstanceMajorityVoting(weka.core.Instance) */ protected Random m_Random; /** * Returns a string describing classifier * @return a description suitable for * displaying in the explorer/experimenter gui */ public String globalInfo() { return "Class for combining classifiers. Different combinations of " + "probability estimates for classification are available.\n\n" + "For more information see:\n\n" + getTechnicalInformation().toString(); } /** * Returns an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Enumeration enm; Vector result; result = new Vector(); enm = super.listOptions(); while (enm.hasMoreElements()) result.addElement(enm.nextElement()); result.addElement(new Option( "\tThe combination rule to use\n" + "\t(default: AVG)", "R", 1, "-R " + Tag.toOptionList(TAGS_RULES))); return result.elements(); } /** * Gets the current settings of Vote. * * @return an array of strings suitable for passing to setOptions() */ public String [] getOptions() { int i; Vector result; String[] options; result = new Vector(); options = super.getOptions(); for (i = 0; i < options.length; i++) result.add(options[i]); result.add("-R"); result.add("" + getCombinationRule()); return (String[]) result.toArray(new String[result.size()]); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -S &lt;num&gt; * Random number seed. * (default 1)</pre> * * <pre> -B &lt;classifier specification&gt; * Full class name of classifier to include, followed * by scheme options. May be specified multiple times. * (default: "weka.classifiers.rules.ZeroR")</pre> * * <pre> -D * If set, classifier is run in debug mode and * may output additional info to the console</pre> * * <pre> -R &lt;AVG|PROD|MAJ|MIN|MAX|MED&gt; * The combination rule to use * (default: AVG)</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String tmpStr; tmpStr = Utils.getOption('R', options); if (tmpStr.length() != 0) setCombinationRule(new SelectedTag(tmpStr, TAGS_RULES)); else setCombinationRule(new SelectedTag(AVERAGE_RULE, TAGS_RULES)); super.setOptions(options); } /** * Returns an instance of a TechnicalInformation object, containing * detailed information about the technical background of this class, * e.g., paper reference or book this class is based on. * * @return the technical information about this class */ public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; TechnicalInformation additional; result = new TechnicalInformation(Type.BOOK); result.setValue(Field.AUTHOR, "Ludmila I. Kuncheva"); result.setValue(Field.TITLE, "Combining Pattern Classifiers: Methods and Algorithms"); result.setValue(Field.YEAR, "2004"); result.setValue(Field.PUBLISHER, "John Wiley and Sons, Inc."); additional = result.add(Type.ARTICLE); additional.setValue(Field.AUTHOR, "J. Kittler and M. Hatef and Robert P.W. Duin and J. Matas"); additional.setValue(Field.YEAR, "1998"); additional.setValue(Field.TITLE, "On combining classifiers"); additional.setValue(Field.JOURNAL, "IEEE Transactions on Pattern Analysis and Machine Intelligence"); additional.setValue(Field.VOLUME, "20"); additional.setValue(Field.NUMBER, "3"); additional.setValue(Field.PAGES, "226-239"); return result; } /** * Returns default capabilities of the classifier. * * @return the capabilities of this classifier */ public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); // class if ( (m_CombinationRule == PRODUCT_RULE) || (m_CombinationRule == MAJORITY_VOTING_RULE) ) { result.disableAllClasses(); result.disableAllClassDependencies(); result.enable(Capability.NOMINAL_CLASS); result.enableDependency(Capability.NOMINAL_CLASS); } else if (m_CombinationRule == MEDIAN_RULE) { result.disableAllClasses(); result.disableAllClassDependencies(); result.enable(Capability.NUMERIC_CLASS); result.enableDependency(Capability.NUMERIC_CLASS); } return result; } /** * Buildclassifier selects a classifier from the set of classifiers * by minimising error on the training data. * * @param data the training data to be used for generating the * boosted classifier. * @throws Exception if the classifier could not be built successfully */ public void buildClassifier(Instances data) throws Exception { // can classifier handle the data? getCapabilities().testWithFail(data); // remove instances with missing class Instances newData = new Instances(data); newData.deleteWithMissingClass(); m_Random = new Random(getSeed()); for (int i = 0; i < m_Classifiers.length; i++) { getClassifier(i).buildClassifier(newData); } } /** * Classifies the given test instance. * * @param instance the instance to be classified * @return the predicted most likely class for the instance or * Utils.missingValue() if no prediction is made * @throws Exception if an error occurred during the prediction */ public double classifyInstance(Instance instance) throws Exception { double result; double[] dist; int index; switch (m_CombinationRule) { case AVERAGE_RULE: case PRODUCT_RULE: case MAJORITY_VOTING_RULE: case MIN_RULE: case MAX_RULE: dist = distributionForInstance(instance); if (instance.classAttribute().isNominal()) { index = Utils.maxIndex(dist); if (dist[index] == 0) result = Utils.missingValue(); else result = index; } else if (instance.classAttribute().isNumeric()){ result = dist[0]; } else { result = Utils.missingValue(); } break; case MEDIAN_RULE: result = classifyInstanceMedian(instance); break; default: throw new IllegalStateException("Unknown combination rule '" + m_CombinationRule + "'!"); } return result; } /** * Classifies the given test instance, returning the median from all * classifiers. * * @param instance the instance to be classified * @return the predicted most likely class for the instance or * Utils.missingValue() if no prediction is made * @throws Exception if an error occurred during the prediction */ protected double classifyInstanceMedian(Instance instance) throws Exception { double[] results = new double[m_Classifiers.length]; double result; for (int i = 0; i < results.length; i++) results[i] = m_Classifiers[i].classifyInstance(instance); if (results.length == 0) result = 0; else if (results.length == 1) result = results[0]; else result = Utils.kthSmallestValue(results, results.length / 2); return result; } /** * Classifies a given instance using the selected combination rule. * * @param instance the instance to be classified * @return the distribution * @throws Exception if instance could not be classified * successfully */ public double[] distributionForInstance(Instance instance) throws Exception { double[] result = new double[instance.numClasses()]; switch (m_CombinationRule) { case AVERAGE_RULE: result = distributionForInstanceAverage(instance); break; case PRODUCT_RULE: result = distributionForInstanceProduct(instance); break; case MAJORITY_VOTING_RULE: result = distributionForInstanceMajorityVoting(instance); break; case MIN_RULE: result = distributionForInstanceMin(instance); break; case MAX_RULE: result = distributionForInstanceMax(instance); break; case MEDIAN_RULE: result[0] = classifyInstance(instance); break; default: throw new IllegalStateException("Unknown combination rule '" + m_CombinationRule + "'!"); } if (!instance.classAttribute().isNumeric() && (Utils.sum(result) > 0)) Utils.normalize(result); return result; } /** * Classifies a given instance using the Average of Probabilities * combination rule. * * @param instance the instance to be classified * @return the distribution * @throws Exception if instance could not be classified * successfully */ protected double[] distributionForInstanceAverage(Instance instance) throws Exception { double[] probs = getClassifier(0).distributionForInstance(instance); for (int i = 1; i < m_Classifiers.length; i++) { double[] dist = getClassifier(i).distributionForInstance(instance); for (int j = 0; j < dist.length; j++) { probs[j] += dist[j]; } } for (int j = 0; j < probs.length; j++) { probs[j] /= (double)m_Classifiers.length; } return probs; } /** * Classifies a given instance using the Product of Probabilities * combination rule. * * @param instance the instance to be classified * @return the distribution * @throws Exception if instance could not be classified * successfully */ protected double[] distributionForInstanceProduct(Instance instance) throws Exception { double[] probs = getClassifier(0).distributionForInstance(instance); for (int i = 1; i < m_Classifiers.length; i++) { double[] dist = getClassifier(i).distributionForInstance(instance); for (int j = 0; j < dist.length; j++) { probs[j] *= dist[j]; } } return probs; } /** * Classifies a given instance using the Majority Voting combination rule. * * @param instance the instance to be classified * @return the distribution * @throws Exception if instance could not be classified * successfully */ protected double[] distributionForInstanceMajorityVoting(Instance instance) throws Exception { double[] probs = new double[instance.classAttribute().numValues()]; double[] votes = new double[probs.length]; for (int i = 0; i < m_Classifiers.length; i++) { probs = getClassifier(i).distributionForInstance(instance); int maxIndex = 0; for(int j = 0; j<probs.length; j++) { if(probs[j] > probs[maxIndex]) maxIndex = j; } // Consider the cases when multiple classes happen to have the same probability for (int j=0; j<probs.length; j++) { if (probs[j] == probs[maxIndex]) votes[j]++; } } int tmpMajorityIndex = 0; for (int k = 1; k < votes.length; k++) { if (votes[k] > votes[tmpMajorityIndex]) tmpMajorityIndex = k; } // Consider the cases when multiple classes receive the same amount of votes Vector<Integer> majorityIndexes = new Vector<Integer>(); for (int k = 0; k < votes.length; k++) { if (votes[k] == votes[tmpMajorityIndex]) majorityIndexes.add(k); } // Resolve the ties according to a uniform random distribution int majorityIndex = majorityIndexes.get(m_Random.nextInt(majorityIndexes.size())); //set probs to 0 for (int k = 0; k<probs.length; k++) probs[k] = 0; probs[majorityIndex] = 1; //the class that have been voted the most receives 1 return probs; } /** * Classifies a given instance using the Maximum Probability combination rule. * * @param instance the instance to be classified * @return the distribution * @throws Exception if instance could not be classified * successfully */ protected double[] distributionForInstanceMax(Instance instance) throws Exception { double[] max = getClassifier(0).distributionForInstance(instance); for (int i = 1; i < m_Classifiers.length; i++) { double[] dist = getClassifier(i).distributionForInstance(instance); for (int j = 0; j < dist.length; j++) { if(max[j]<dist[j]) max[j]=dist[j]; } } return max; } /** * Classifies a given instance using the Minimum Probability combination rule. * * @param instance the instance to be classified * @return the distribution * @throws Exception if instance could not be classified * successfully */ protected double[] distributionForInstanceMin(Instance instance) throws Exception { double[] min = getClassifier(0).distributionForInstance(instance); for (int i = 1; i < m_Classifiers.length; i++) { double[] dist = getClassifier(i).distributionForInstance(instance); for (int j = 0; j < dist.length; j++) { if(dist[j]<min[j]) min[j]=dist[j]; } } return min; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String combinationRuleTipText() { return "The combination rule used."; } /** * Gets the combination rule used * * @return the combination rule used */ public SelectedTag getCombinationRule() { return new SelectedTag(m_CombinationRule, TAGS_RULES); } /** * Sets the combination rule to use. Values other than * * @param newRule the combination rule method to use */ public void setCombinationRule(SelectedTag newRule) { if (newRule.getTags() == TAGS_RULES) m_CombinationRule = newRule.getSelectedTag().getID(); } /** * Output a representation of this classifier * * @return a string representation of the classifier */ public String toString() { if (m_Classifiers == null) { return "Vote: No model built yet."; } String result = "Vote combines"; result += " the probability distributions of these base learners:\n"; for (int i = 0; i < m_Classifiers.length; i++) { result += '\t' + getClassifierSpec(i) + '\n'; } result += "using the '"; switch (m_CombinationRule) { case AVERAGE_RULE: result += "Average of Probabilities"; break; case PRODUCT_RULE: result += "Product of Probabilities"; break; case MAJORITY_VOTING_RULE: result += "Majority Voting"; break; case MIN_RULE: result += "Minimum Probability"; break; case MAX_RULE: result += "Maximum Probability"; break; case MEDIAN_RULE: result += "Median Probability"; break; default: throw new IllegalStateException("Unknown combination rule '" + m_CombinationRule + "'!"); } result += "' combination rule \n"; return result; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 5987 $"); } /** * Main method for testing this class. * * @param argv should contain the following arguments: * -t training file [-T test file] [-c class index] */ public static void main(String [] argv) { runClassifier(new Vote(), argv); } }
[ "syi@email.wm.edu" ]
syi@email.wm.edu
ce58dc1c8181afd7de6b165b3f82dbeeac0f51fd
fc112cf66bbd9b791bae936b8a6e1f75d0dc2d41
/src/observer/Buffer.java
754c4aa3a3b7ed9f1cf487095c7e585137783159
[]
no_license
Mojib501/Observer
190ccf1f8b851276f25b20dfe2effc92b6885a86
f8bfd8b8e10a353360e20cdf8b092df137b7f3f6
refs/heads/master
2021-01-11T23:52:36.465401
2017-01-11T13:19:15
2017-01-11T13:19:15
78,639,684
0
0
null
null
null
null
UTF-8
Java
false
false
957
java
/* * 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 observer; import java.util.ArrayList; import java.util.List; /** * * @author masi * diese klasse ist der Subject in der Observer Konstelation */ public class Buffer { private int state; private List<Observer> observerList= new ArrayList<Observer>(); public void attach(Observer observer){ observerList.add(observer); } public int getState(){ return state; } public void printObserverName(){ notifyAllObservers(); } public void notifyAllObservers(){ for(Observer observer : observerList){ //jeden observer mit Messadten füttern //es muss berücksichtigt werden dass nur gesedet wird wenn //Nachfrage besteht observer.update(); } } }
[ "mojib@mail.hs-ulm.de" ]
mojib@mail.hs-ulm.de
47b6481b8365d0ab3de04ed65c2c8868d855bb6e
6f69ae89d559bd86643cf610e5540e787728581b
/PLP/src/view/pitagoras.java
1ecb81efc8de534895f726c3ef032cc4e22c4f53
[]
no_license
Amancio302/Resolucao-de-Equacoes
d4c8122df1f8bb7e2e9dfd4955f321b29369a91e
9ee8a81046ea2e7ceaf77301236cdddb074ec0d0
refs/heads/master
2020-09-21T17:54:24.747088
2019-11-29T15:19:29
2019-11-29T15:19:29
224,873,827
0
0
null
null
null
null
UTF-8
Java
false
false
13,693
java
/* * 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 view; /** * * @author aluno */ public class pitagoras extends javax.swing.JFrame { /** * Creates new form pitagoras */ public pitagoras() { 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() { jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); exit1 = new javax.swing.JButton(); c = new javax.swing.JTextField(); a = new javax.swing.JTextField(); b = new javax.swing.JTextField(); send1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); resposta = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel3.setText("c:"); jLabel4.setText("a:"); jLabel5.setText("b:"); exit1.setText("Sair"); exit1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exit1ActionPerformed(evt); } }); c.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cActionPerformed(evt); } }); c.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { cKeyReleased(evt); } }); a.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aActionPerformed(evt); } }); a.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { aKeyReleased(evt); } }); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bActionPerformed(evt); } }); b.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { bKeyReleased(evt); } }); send1.setText("Enviar"); send1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { send1ActionPerformed(evt); } }); jLabel1.setText("Resposta:"); jLabel2.setFont(new java.awt.Font("Meiryo", 3, 18)); // NOI18N jLabel2.setText("c = a²+b²"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(send1)) .addGroup(layout.createSequentialGroup() .addGap(137, 137, 137) .addComponent(jLabel2))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(exit1) .addGap(90, 90, 90)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel3)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(b, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(98, 98, 98)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resposta, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel4) .addGap(88, 88, 88)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(c, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resposta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(b, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(40, 40, 40))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(exit1) .addComponent(send1)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void exit1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit1ActionPerformed this.dispose(); }//GEN-LAST:event_exit1ActionPerformed private void cActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cActionPerformed private void cKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cKeyReleased c.setText(c.getText().replaceAll("[^0-9 | ^.]" , "")); // TODO add your handling code here: }//GEN-LAST:event_cKeyReleased private void aActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aActionPerformed // TODO add your handling code here: }//GEN-LAST:event_aActionPerformed private void aKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_aKeyReleased a.setText(a.getText().replaceAll("[^0-9 | ^.]" , "")); // TODO add your handling code here: }//GEN-LAST:event_aKeyReleased private void bActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bActionPerformed b.setText(b.getText().replaceAll("[^0-9 | ^.]" , "")); // TODO add your handling code here: }//GEN-LAST:event_bActionPerformed private void bKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bKeyReleased b.setText(b.getText().replaceAll("[^0-9 | ^.]" , "")); // TODO add your handling code here: }//GEN-LAST:event_bKeyReleased private void send1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_send1ActionPerformed if(c.getText().isEmpty()){ double _a , _b, res; String result; _a = Double.parseDouble(a.getText()); _b = Double.parseDouble(b.getText()); res = Math.sqrt(Math.pow(_a,2) + Math.pow(_b,2)); result = Double.toString(res); resposta.setText(result); } if(a.getText().isEmpty()){ double _c , _b, res; String result; _c = Double.parseDouble(c.getText()); _b = Double.parseDouble(b.getText()); res = Math.sqrt(Math.pow(_c,2) - Math.pow(_b,2)); result = Double.toString(res); resposta.setText(result); } if(b.getText().isEmpty()){ double _c , _a, res; String result; _c = Double.parseDouble(c.getText()); _a = Double.parseDouble(a.getText()); res = Math.sqrt(Math.pow(_c,2) - Math.pow(_a,2)); result = Double.toString(res); resposta.setText(result); } }//GEN-LAST:event_send1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(pitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(pitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(pitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(pitagoras.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new pitagoras().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField a; private javax.swing.JTextField b; private javax.swing.JTextField c; private javax.swing.JButton exit1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField resposta; private javax.swing.JButton send1; // End of variables declaration//GEN-END:variables }
[ "matheuusamancioferreira@gmail.com" ]
matheuusamancioferreira@gmail.com
687a27e9ce70066dd09b527abd25e2207ab77402
38a38588bd7c90304c139eecee1a4e2dbdccb25a
/RouteServer/src/com/soon/core/db/pool/DbPoolMgr.java
286fee807bb4fcc8438c259acf12d88befbcef09
[]
no_license
dumbant/gameserver
9c5322155961255e7474fa6d48f7334b78764fc9
1e681155883fd24b4ba7aec3ebe7f5f9cf69c80f
refs/heads/master
2020-03-20T21:45:47.559372
2018-06-18T14:00:09
2018-06-18T14:00:09
137,758,981
0
0
null
null
null
null
UTF-8
Java
false
false
478
java
package com.soon.core.db.pool; import com.soon.core.config.DbConfigInfo; import com.soon.util.DESUtil; public class DbPoolMgr { public static IDBPool initPool(DbConfigInfo configInfo){ IDBPool pool = null; try { pool = new BoneCPDBPool(configInfo); } catch (Exception e) { e.printStackTrace(); } return pool; } public static void main(String[] args) { System.out.println(DESUtil.encrypt("root")); System.out.println(DESUtil.encrypt("123456")); } }
[ "zsl354310@163.com" ]
zsl354310@163.com
97943c453e9db6f0ac94df47606c773267e49ac6
abf491afff7ccf1564c10671d9df9a2d206408b5
/src/main/java/ch/rweiss/terminal/Key.java
6b1531711c526251d9f0f89d4a439f5e33ee3aef
[ "Apache-2.0" ]
permissive
weissreto/ansi-terminal
7f029f4d2e93c9635544b649dc813cb32d615476
5c7dc874b0829c100381f25ba79f1f79105fc527
refs/heads/master
2021-10-11T12:54:34.696732
2019-01-25T21:20:21
2019-01-25T21:20:21
111,735,791
1
0
null
null
null
null
UTF-8
Java
false
false
11,924
java
package ch.rweiss.terminal; import ch.rweiss.terminal.internal.EscCodeParser; public abstract class Key { public static final Key UP = new Control(EscCode.csi('A'), "UP"); public static final Key DOWN = new Control(EscCode.csi('B'), "DOWN"); public static final Key RIGHT = new Control(EscCode.csi('C'), "RIGHT"); public static final Key LEFT = new Control(EscCode.csi('D'), "LEFT"); public static final Key HOME = new Control(EscCode.csi('H'), "HOME"); public static final Key END = new Control(EscCode.csi('F'), "END"); public static final Key INSERT = new Control(EscCode.csi('~', 2), "INSERT"); public static final Key DELETE = new Control(EscCode.csi('~', 3), "DELETE"); public static final Key PAGE_UP = new Control(EscCode.csi('~', 5), "PAGE UP"); public static final Key PAGE_DOWN = new Control(EscCode.csi('~', 6), "PAGE DOWN"); public static final Key F1 = new Control(EscCode.esc("OP"), "F1"); public static final Key F2 = new Control(EscCode.esc("OQ"), "F2"); public static final Key F3 = new Control(EscCode.esc("OR"), "F3"); public static final Key F4 = new Control(EscCode.esc("OS"), "F4"); public static final Key F5 = new Control(EscCode.csi('~', 15), "F5"); public static final Key F6 = new Control(EscCode.csi('~', 17), "F6"); public static final Key F7 = new Control(EscCode.csi('~', 18), "F7"); public static final Key F8 = new Control(EscCode.csi('~', 19), "F8"); public static final Key F9 = new Control(EscCode.csi('~', 20), "F9"); public static final Key F10 = new Control(EscCode.csi('~', 21), "F10"); public static final Key F11 = new Control(EscCode.csi('~', 23), "F11"); public static final Key F12 = new Control(EscCode.csi('~', 24), "F12"); public static final Key CTRL_UP = new Control(EscCode.csi('A', 1, 5), "CTRL & UP"); public static final Key CTRL_DOWN = new Control(EscCode.csi('B', 1, 5), "CTRL & DOWN"); public static final Key CTRL_RIGHT = new Control(EscCode.csi('C', 1, 5), "CTRL & RIGHT"); public static final Key CTRL_LEFT = new Control(EscCode.csi('D', 1, 5), "CTRL & LEFT"); public static final Key CTRL_HOME = new Control(EscCode.csi('H', 1, 5), "CTRL & HOME"); public static final Key CTRL_END = new Control(EscCode.csi('F', 1, 5), "CTRL & END"); public static final Key CTRL_INSERT = new Control(EscCode.csi('~', 2, 5), "CTRL & INSERT"); public static final Key CTRL_DELETE = new Control(EscCode.csi('~', 3, 5), "CTRL & DELETE"); public static final Key CTRL_PAGE_UP = new Control(EscCode.csi('~', 5, 5), "CTRL & PAGE UP"); public static final Key CTRL_PAGE_DOWN = new Control(EscCode.csi('~', 6, 5), "CTRL & PAGE DOWN"); public static final Key CTRL_F1 = new Control(EscCode.csi('P', 1, 5), "CTRL & F1"); public static final Key CTRL_F2 = new Control(EscCode.csi('Q', 1, 5), "CTRL & F2"); public static final Key CTRL_F3 = new Control(EscCode.csi('R', 1, 5), "CTRL & F3"); public static final Key CTRL_F4 = new Control(EscCode.csi('S', 1, 5), "CTRL & F4"); public static final Key CTRL_F5 = new Control(EscCode.csi('~', 15, 5), "CTRL & F5"); public static final Key CTRL_F6 = new Control(EscCode.csi('~', 17, 5), "CTRL & F6"); public static final Key CTRL_F7 = new Control(EscCode.csi('~', 18, 5), "CTRL & F7"); public static final Key CTRL_F8 = new Control(EscCode.csi('~', 19, 5), "CTRL & F8"); public static final Key CTRL_F9 = new Control(EscCode.csi('~', 20, 5), "CTRL & F9"); public static final Key CTRL_F10 = new Control(EscCode.csi('~', 21, 5), "CTRL & F10"); public static final Key CTRL_F11 = new Control(EscCode.csi('~', 23, 5), "CTRL & F11"); public static final Key CTRL_F12 = new Control(EscCode.csi('~', 24, 5), "CTRL & F12"); public static final Key ALT_UP = new Control(EscCode.csi('A', 1, 3), "ALT & UP"); public static final Key ALT_DOWN = new Control(EscCode.csi('B', 1, 3), "ALT & DOWN"); public static final Key ALT_RIGHT = new Control(EscCode.csi('C', 1, 3), "ALT & RIGHT"); public static final Key ALT_LEFT = new Control(EscCode.csi('D', 1, 3), "ALT & LEFT"); public static final Key ALT_HOME = new Control(EscCode.csi('H', 1, 3), "ALT & HOME"); public static final Key ALT_END = new Control(EscCode.csi('F', 1, 3), "ALT & END"); public static final Key ALT_INSERT = new Control(EscCode.csi('~', 2, 3), "ALT & INSERT"); public static final Key ALT_DELETE = new Control(EscCode.csi('~', 3, 3), "ALT & DELETE"); public static final Key ALT_PAGE_UP = new Control(EscCode.csi('~', 5, 3), "ALT & PAGE UP"); public static final Key ALT_PAGE_DOWN = new Control(EscCode.csi('~', 6, 3), "ALT & PAGE DOWN"); public static final Key ALT_F1 = new Control(EscCode.csi('P', 1, 3), "ALT & F1"); public static final Key ALT_F2 = new Control(EscCode.csi('Q', 1, 3), "ALT & F2"); public static final Key ALT_F3 = new Control(EscCode.csi('R', 1, 3), "ALT & F3"); public static final Key ALT_F4 = new Control(EscCode.csi('S', 1, 3), "ALT & F4"); public static final Key ALT_F5 = new Control(EscCode.csi('~', 15, 3), "ALT & F5"); public static final Key ALT_F6 = new Control(EscCode.csi('~', 17, 3), "ALT & F6"); public static final Key ALT_F7 = new Control(EscCode.csi('~', 18, 3), "ALT & F7"); public static final Key ALT_F8 = new Control(EscCode.csi('~', 19, 3), "ALT & F8"); public static final Key ALT_F9 = new Control(EscCode.csi('~', 20, 3), "ALT & F9"); public static final Key ALT_F10 = new Control(EscCode.csi('~', 21, 3), "ALT & F10"); public static final Key ALT_F11 = new Control(EscCode.csi('~', 23, 3), "ALT & F11"); public static final Key ALT_F12 = new Control(EscCode.csi('~', 24, 3), "ALT & F12"); public static final Key CTRL_ALT_UP = new Control(EscCode.csi('A', 1, 7), "CTRL & ALT & UP"); public static final Key CTRL_ALT_DOWN = new Control(EscCode.csi('B', 1, 7), "CTRL & ALT & DOWN"); public static final Key CTRL_ALT_RIGHT = new Control(EscCode.csi('C', 1, 7), "CTRL & ALT & RIGHT"); public static final Key CTRL_ALT_LEFT = new Control(EscCode.csi('D', 1, 7), "CTRL & ALT & LEFT"); public static final Key CTRL_ALT_HOME = new Control(EscCode.csi('H', 1, 7), "CTRL & ALT & HOME"); public static final Key CTRL_ALT_END = new Control(EscCode.csi('F', 1, 7), "CTRL & ALT & END"); public static final Key CTRL_ALT_INSERT = new Control(EscCode.csi('~', 2, 7), "CTRL & ALT & INSERT"); public static final Key CTRL_ALT_DELETE = new Control(EscCode.csi('~', 3, 7), "CTRL & ALT & DELETE"); public static final Key CTRL_ALT_PAGE_UP = new Control(EscCode.csi('~', 5, 7), "CTRL & ALT & PAGE UP"); public static final Key CTRL_ALT_PAGE_DOWN = new Control(EscCode.csi('~', 6, 7), "CTRL & ALT & PAGE DOWN"); public static final Key CTRL_ALT_F1 = new Control(EscCode.csi('P', 1, 7), "CTRL & ALT & F1"); public static final Key CTRL_ALT_F2 = new Control(EscCode.csi('Q', 1, 7), "CTRL & ALT & F2"); public static final Key CTRL_ALT_F3 = new Control(EscCode.csi('R', 1, 7), "CTRL & ALT & F3"); public static final Key CTRL_ALT_F4 = new Control(EscCode.csi('S', 1, 7), "CTRL & ALT & F4"); public static final Key CTRL_ALT_F5 = new Control(EscCode.csi('~', 15, 7), "CTRL & ALT & F5"); public static final Key CTRL_ALT_F6 = new Control(EscCode.csi('~', 17, 7), "CTRL & ALT & F6"); public static final Key CTRL_ALT_F7 = new Control(EscCode.csi('~', 18, 7), "CTRL & ALT & F7"); public static final Key CTRL_ALT_F8 = new Control(EscCode.csi('~', 19, 7), "CTRL & ALT & F8"); public static final Key CTRL_ALT_F9 = new Control(EscCode.csi('~', 20, 7), "CTRL & ALT & F9"); public static final Key CTRL_ALT_F10 = new Control(EscCode.csi('~', 21, 7), "CTRL & ALT & F10"); public static final Key CTRL_ALT_F11 = new Control(EscCode.csi('~', 23, 7), "CTRL & ALT & F11"); public static final Key CTRL_ALT_F12 = new Control(EscCode.csi('~', 24, 7), "CTRL & ALT & F12"); private static Key[] WELL_KNOWN = new Key[] { UP, DOWN, RIGHT, LEFT, HOME, END, INSERT, DELETE, PAGE_UP, PAGE_DOWN, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, CTRL_UP, CTRL_DOWN, CTRL_RIGHT, CTRL_LEFT, CTRL_HOME, CTRL_END, CTRL_INSERT, CTRL_DELETE, CTRL_PAGE_UP, CTRL_PAGE_DOWN, CTRL_F1, CTRL_F2, CTRL_F3, CTRL_F4, CTRL_F5, CTRL_F6, CTRL_F7, CTRL_F8, CTRL_F9, CTRL_F10, CTRL_F11, CTRL_F12, ALT_UP, ALT_DOWN, ALT_RIGHT, ALT_LEFT, ALT_HOME, ALT_END, ALT_INSERT, ALT_DELETE, ALT_PAGE_UP, ALT_PAGE_DOWN, ALT_F1, ALT_F2, ALT_F3, ALT_F4, ALT_F5, ALT_F6, ALT_F7, ALT_F8, ALT_F9, ALT_F10, ALT_F11, ALT_F12, CTRL_ALT_UP, CTRL_ALT_DOWN, CTRL_ALT_RIGHT, CTRL_ALT_LEFT, CTRL_ALT_HOME, CTRL_ALT_END, CTRL_ALT_INSERT, CTRL_ALT_DELETE, CTRL_ALT_PAGE_UP, CTRL_ALT_PAGE_DOWN, CTRL_ALT_F1, CTRL_ALT_F2, CTRL_ALT_F3, CTRL_ALT_F4, CTRL_ALT_F5, CTRL_ALT_F6, CTRL_ALT_F7, CTRL_ALT_F8, CTRL_ALT_F9, CTRL_ALT_F10, CTRL_ALT_F11, CTRL_ALT_F12 }; public abstract boolean isPrintable(); public abstract boolean isControl(); /** * Either the printable character of the pressed key e.g. "a" or the name of the control key &gt;UP&lt; */ @Override public String toString() { return ""; } /** * Either the printable character of the pressed key e.g. 'a'. '\033' ESCAPE for control keys */ public char toChar() { return ' '; } public static class Printable extends Key { private char ch; public Printable(char ch) { this.ch = ch; } @Override public boolean isPrintable() { return true; } @Override public boolean isControl() { return false; } @Override public String toString() { return ""+ch; } @Override public char toChar() { return ch; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (other.getClass() != Printable.class) { return false; } Printable printable = (Printable) other; return printable.ch == ch; } @Override public int hashCode() { return Character.hashCode(ch); } } public static class Control extends Key { private EscCode escCode; private String name; private Control(EscCode escCode, String name) { this.escCode = escCode; this.name = "<"+name+">"; } private Control(EscCode escCode) { this(escCode, escCode.toString()); } @Override public boolean isPrintable() { return false; } @Override public boolean isControl() { return true; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.getClass() != Control.class) { return false; } Control other = (Control) obj; return escCode.equals(other.escCode); } @Override public int hashCode() { return escCode.hashCode(); } @Override public String toString() { return name; } @Override public char toChar() { return EscCodeParser.ESCAPE; } public static Key forEscCode(EscCode escCode) { for (Key control : WELL_KNOWN) { if (((Control)control).escCode.equals(escCode)) { return control; } } return new Control(escCode); } } }
[ "reto.weiss@ivyteam.ch" ]
reto.weiss@ivyteam.ch
a611c534d76bc8b9aedc0c194972bff2cdfe2b05
c9aaada8bcef5ed77aea0357b6560ef145e4296d
/tictactoe/src/engine/Board.java
406e1d77aa9f3ca5060ee4742b2c651c527bbf84
[]
no_license
STFinancial/operation-cyclone
799d57158413af1eabf3c39d96c23216775e0d6d
e442b753f05c1e7c2cb110af93d2ab68b4446577
refs/heads/master
2023-01-24T02:11:26.672113
2020-11-26T06:37:52
2020-11-26T06:37:52
316,098,812
0
0
null
null
null
null
UTF-8
Java
false
false
2,141
java
package engine; class Board { private MarkType[][] board; Board() { board = new MarkType[3][3]; clearBoard(); } /** Resets engine.Board state, should be called before a new game */ void clearBoard() { for (int row = 0; row < 3; ++row) { for (int column = 0; column < 3; ++column) { board[row][column] = MarkType.EMPTY; } } } /** Marks the position for the Player, returns true if the position was previously empty, false if not */ boolean markPosition(int row, int column, Player player) { if (board[row][column] != MarkType.EMPTY) { return false; } if (player == Player.X) { board[row][column] = MarkType.X; } else if (player == Player.O){ board[row][column] = MarkType.O; } else { throw new IllegalStateException("Invalid engine.Player type attempting to mark position."); } return true; } /** Returns the Player at the given position, null if it has not been marked */ Player get(int row, int column) { if (board[row][column] == MarkType.X) { return Player.X; } else if (board[row][column] == MarkType.O) { return Player.O; } else { return null; } } @Override public String toString() { String output = "-------------\n"; for (int row = 0; row < 3; ++row) { output += "|"; for (int column = 0; column < 3; ++column) { output += " "; output += board[row][column].toString(); output += " |"; } output += "\n"; output += "-------------\n"; } return output; } private static enum MarkType { X("X"), O("O"), EMPTY(" "); private final String markString; private MarkType(String markString) { this.markString = markString; } @Override public String toString() { return markString; } } }
[ "palla021@umn.edu" ]
palla021@umn.edu
f2cb4ef74dd0c4cf27615f6a8db1ea17606291eb
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-111/u-11-111-1112/u-11-111-1112-11113/u-11-111-1112-11113-f6324.java
db2288c76827016c833ec860672b39b526de6302
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
106
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 8445059038043
[ "jenkins@khan.paloaltonetworks.local" ]
jenkins@khan.paloaltonetworks.local
46db5c3f4306e8f50475560cf6772f8267c8f0ea
6635387159b685ab34f9c927b878734bd6040e7e
/src/org/apache/commons/codec/language/bm/Languages$SomeLanguages.java
02e3bb78489f549ee1a2361df9da62ef3f94cfb3
[]
no_license
RepoForks/com.snapchat.android
987dd3d4a72c2f43bc52f5dea9d55bfb190966e2
6e28a32ad495cf14f87e512dd0be700f5186b4c6
refs/heads/master
2021-05-05T10:36:16.396377
2015-07-16T16:46:26
2015-07-16T16:46:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,710
java
package org.apache.commons.codec.language.bm; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public final class Languages$SomeLanguages extends Languages.LanguageSet { private final Set<String> languages; private Languages$SomeLanguages(Set<String> paramSet) { languages = Collections.unmodifiableSet(paramSet); } public final boolean contains(String paramString) { return languages.contains(paramString); } public final String getAny() { return (String)languages.iterator().next(); } public final Set<String> getLanguages() { return languages; } public final boolean isEmpty() { return languages.isEmpty(); } public final boolean isSingleton() { return languages.size() == 1; } public final Languages.LanguageSet restrictTo(Languages.LanguageSet paramLanguageSet) { if (paramLanguageSet == Languages.NO_LANGUAGES) { localObject = paramLanguageSet; } do { do { return (Languages.LanguageSet)localObject; localObject = this; } while (paramLanguageSet == Languages.ANY_LANGUAGE); paramLanguageSet = (SomeLanguages)paramLanguageSet; localObject = this; } while (languages.containsAll(languages)); Object localObject = new HashSet(languages); ((Set)localObject).retainAll(languages); return from((Set)localObject); } public final String toString() { return "Languages(" + languages.toString() + ")"; } } /* Location: * Qualified Name: org.apache.commons.codec.language.bm.Languages.SomeLanguages * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
[ "reverseengineeringer@hackeradmin.com" ]
reverseengineeringer@hackeradmin.com
6c1b7f5f83a5572e5b4f87c4a78c5cb90946718d
976c792afad6f74cffac57ec5e5b58358d8b6cf6
/server/site-server/src/main/java/com/opencloud/site/service/impl/UserDetailsServiceImpl.java
40c67bf1ae4d619bdcb98d1945168d55cbaf155a
[ "MIT" ]
permissive
andymiaomiao/openCloud
3097abef10c2debf72d8c2d412bd8acf0d3d07b6
88cc7583415cda69e7a8fbed5afc37081fb8e122
refs/heads/master
2022-03-27T04:37:42.321962
2020-01-20T04:15:26
2020-01-20T04:15:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,357
java
package com.opencloud.site.service.impl; import com.opencloud.common.model.ResultBody; import com.opencloud.common.security.BaseUserDetails; import com.opencloud.common.security.oauth2.SocialProperties; import com.opencloud.common.utils.WebUtil; import com.opencloud.site.service.feign.SystemDeveloperServiceClient; import com.opencloud.system.client.constants.SystemConstants; import com.opencloud.system.client.model.UserInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.Map; /** * Security用户信息获取实现类 * * @author liuyadu */ @Slf4j @Service("userDetailService") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private SystemDeveloperServiceClient systemDeveloperServiceClient; @Autowired private SocialProperties clientProperties; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { HttpServletRequest request = WebUtil.getHttpServletRequest();; Map<String, String> parameterMap = WebUtil.getParamMap(request); // 第三方登录标识 String thirdParty = parameterMap.get("thirdParty"); ResultBody<UserInfo> resp = systemDeveloperServiceClient.login(username,thirdParty); UserInfo account = resp.getData(); if (account == null || account.getAccountId()==null) { throw new UsernameNotFoundException("系统用户 " + username + " 不存在!"); } String domain = account.getDomain(); Long accountId = account.getAccountId(); Long userId = account.getUserId(); String password = account.getPassword(); String nickName = account.getNickName(); String avatar = account.getAvatar(); String accountType = account.getAccountType(); boolean accountNonLocked = account.getStatus().intValue() != SystemConstants.ACCOUNT_STATUS_LOCKED; boolean credentialsNonExpired = true; boolean enabled = account.getStatus().intValue() == SystemConstants.ACCOUNT_STATUS_NORMAL ? true : false; boolean accountNonExpired = true; BaseUserDetails userDetails = new BaseUserDetails(); userDetails.setDomain(domain); userDetails.setAccountId(accountId); userDetails.setUserId(userId); userDetails.setUsername(username); userDetails.setPassword(password); userDetails.setNickName(nickName); userDetails.setAuthorities(account.getAuthorities()); userDetails.setAvatar(avatar); userDetails.setAccountId(accountId); userDetails.setAccountNonLocked(accountNonLocked); userDetails.setAccountNonExpired(accountNonExpired); userDetails.setAccountType(accountType); userDetails.setCredentialsNonExpired(credentialsNonExpired); userDetails.setEnabled(enabled); userDetails.setClientId(clientProperties.getClient().get("portal").getClientId()); return userDetails; } }
[ "1317225796@qq.com" ]
1317225796@qq.com
9b6c5fc5ff8d5043af4dd662660c840c664eeeb1
cfaa4bac442f5036dca1981f74771b23c21eed72
/src/com/swingsword/ssengine/game/games/rust/listeners/GunListener.java
11d5ebad839428ea26c1c9ffcae1176be76510e5
[]
no_license
CashVillan/SSEngine
cfa04b5a19052bea3ca5591648361afce3c7cec4
76867e0c57912b8623f2eebffc702ba2ccd34b32
refs/heads/master
2021-03-19T10:32:57.385226
2016-10-03T21:41:54
2016-10-03T21:41:54
69,909,441
0
0
null
null
null
null
UTF-8
Java
false
false
5,631
java
package com.swingsword.ssengine.game.games.rust.listeners; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.craftbukkit.Main; import org.bukkit.entity.Player; import org.bukkit.event.Event.Result; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.swingsword.ssengine.MasterPlugin; import com.swingsword.ssengine.game.games.rust.guns.Gun; import com.swingsword.ssengine.game.games.rust.guns.GunData; import com.swingsword.ssengine.game.games.rust.guns.Guns; import com.swingsword.ssengine.game.games.rust.utils.ItemUtils; public class GunListener implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) { if (Gun.isGun(player.getItemInHand())) { Gun gun = Gun.getGun(player.getItemInHand().getItemMeta().getDisplayName()); if (player != null && gun != null) { gun.reload(player, gun); } } } else if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (Gun.isGun(player.getItemInHand())) { Gun gun = Gun.getGun(ChatColor.stripColor(player.getItemInHand().getItemMeta().getDisplayName())); if (Gun.canShoot(player, gun)) { gun.shoot(player, gun); event.setCancelled(true); event.setUseItemInHand(Result.DENY); } else if (!GunData.reloading.containsKey(player) && !GunData.delay.containsKey(player)) { player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 0.5F, 2); gun.reload(player, gun); } } } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { Player player = event.getPlayer(); if(GunData.reloading.containsKey(player)) { event.setCancelled(true); } } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if(event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); if(GunData.reloading.containsKey(player)) { event.setCancelled(true); } } } @EventHandler public void onProjectileHit(final ProjectileHitEvent event) { if(GunData.bullets.containsKey(event.getEntity())) { Bukkit.getScheduler().scheduleSyncDelayedTask(MasterPlugin.getMasterPlugin(), new Runnable() { public void run() { GunData.bullets.remove(event.getEntity()); GunData.bulletVel.remove(event.getEntity()); event.getEntity().remove(); } }, 1L); } } @EventHandler public void onPlayerTeleport(final PlayerTeleportEvent event) { if(event.getCause().equals(TeleportCause.ENDER_PEARL)) { event.setCancelled(true); } } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if(event.getPlayer() instanceof Player) { Player player = (Player) event.getPlayer(); if(Guns.playerEquip.containsKey(player)) { List<String> lore = ItemUtils.getLore(player.getItemInHand()); if(lore != null) { if(!ItemUtils.loreContains(lore, "Attachments:")) { lore.add(""); lore.add(ChatColor.GRAY + "Attachments:"); } for(ItemStack all : Guns.playerEquip.get(player)) { if(all != null && all.getItemMeta() != null && all.getItemMeta().getDisplayName() != null) { if(all.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.WHITE + "Silencer") && !ItemUtils.loreContains(lore, "Silencer")) { lore.add(ChatColor.GRAY + "Silencer"); player.sendMessage(ChatColor.GREEN + "Equipped Silencer."); } else if(all.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.WHITE + "Flashlight Mod") && !ItemUtils.loreContains(lore, "Flashlight Mod")) { lore.add(ChatColor.GRAY + "Flashlight Mod"); player.sendMessage(ChatColor.GREEN + "Equipped Flashlight Mod."); } else if(all.getItemMeta().getDisplayName().equalsIgnoreCase(ChatColor.WHITE + "Holo Sight") && !ItemUtils.loreContains(lore, "Holo Sight")) { lore.add(ChatColor.GRAY + "Holo Sight"); player.sendMessage(ChatColor.GREEN + "Equipped Holo Sight."); } else { player.getInventory().addItem(all); } } } ItemMeta meta = player.getItemInHand().getItemMeta(); meta.setLore(lore); player.getItemInHand().setItemMeta(meta); player.updateInventory(); } Guns.playerEquip.remove(player); } } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); if(player.getInventory().getHelmet() != null) { if(player.getInventory().getHelmet().getType() == Material.PUMPKIN) { if(GunData.playerHelmet.containsKey(player)) { player.getInventory().setHelmet(GunData.playerHelmet.get(player)); GunData.playerHelmet.remove(player); } player.updateInventory(); } } } }
[ "jordanwheatley86@yahoo.com" ]
jordanwheatley86@yahoo.com