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
3fb78e9fded57bba012cdf923e47a625e9e34bcf
ca1d1038649544675a57b2682e0f36bb32a3534e
/KaKu/src/main/java/com/yichang/kaku/tools/okhttp/OkHttpUtil.java
57272dc2e69399de110ec2d3890333b453b7f5da
[]
no_license
MoonQiQi/kaku_driver2
7b0f97628f3883c8220e0231039416fac223fbef
22526350aacc8a0a29ea1818ba9396da25ebe911
refs/heads/master
2021-01-18T18:58:54.804817
2017-05-04T06:04:19
2017-05-04T06:04:24
86,878,868
2
0
null
null
null
null
UTF-8
Java
false
false
1,998
java
package com.yichang.kaku.tools.okhttp; import android.os.Handler; import android.text.TextUtils; import com.squareup.okhttp.Call; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.yichang.kaku.BuildConfig; import com.yichang.kaku.response.BaseResp; import java.util.Iterator; import java.util.Map; import java.util.Set; public class OkHttpUtil { private static final OkHttpClient mOkHttpClient = new OkHttpClient(); public static Handler handler; public static void init(Handler handler) { OkHttpUtil.handler = handler; } public static void getAsync(String url, RequestCallback callback) { Request request = new Request.Builder() .url(url) .build(); mOkHttpClient.newCall(request).enqueue(callback); } public static Call postAsync(String url, Params params, RequestCallback<? extends BaseResp> callback) { Set<Map.Entry<String, String>> entrySet = params.entrySet(); FormEncodingBuilder builder = new FormEncodingBuilder(); for (Iterator<Map.Entry<String, String>> iterator = entrySet.iterator(); iterator.hasNext(); ) { Map.Entry<String, String> entry = iterator.next(); String key = entry.getKey(); String value = entry.getValue(); if (TextUtils.isEmpty(value)) { value = ""; } builder.add(key, value); if (BuildConfig.DEBUG) { } } Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(callback); return call; } public static Call postAsync(String url, Params.builder builder, RequestCallback<? extends BaseResp> callback) { return postAsync(url, builder.build(), callback); } }
[ "123qwe" ]
123qwe
b4819c95a6a0db4f5cd455306d095b54a30521c8
f0fc01efbec2d5a2bae5d9e83b411ac8f9f51782
/app/src/test/java/com/example/randhir/currencyconverter/ExampleUnitTest.java
597171e7093e196015e380328d1c17edfbbad9bf
[]
no_license
aaddven/Dollar-to-Rupee-Converter
1f2fa8984886b8846124c7175a7f62aa8122b2cd
e354755d0b2dd7d92ecd09aa11c2aec0482f24b2
refs/heads/master
2022-11-30T17:39:17.967127
2020-07-31T23:36:58
2020-07-31T23:36:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
415
java
package com.example.randhir.currencyconverter; 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); } }
[ "randhirpct2000@gmail.com" ]
randhirpct2000@gmail.com
8459b50f0bbec8dc1a70385560663ee359d50690
e9bbf87ec76350ec4f6f489d00cc0df6e55e2dfc
/src/main/java/com/ll/designpattern/observer/v5/Child.java
f96e80a0c9129272a02fbc80b2b703733abda077
[]
no_license
StartAmazing/DesignPattern
37ba2930897e6bee5d415ca9795a4a2c63bea224
c3b3a8670aff325db3da1067e1e31ebc0a6c02dc
refs/heads/master
2023-02-09T00:03:53.136415
2021-01-04T15:31:34
2021-01-04T15:31:34
285,014,854
0
0
null
null
null
null
UTF-8
Java
false
false
474
java
package com.ll.designpattern.observer.v5; import java.util.ArrayList; import java.util.List; public class Child { private boolean isCry; List<Observer> observers = new ArrayList<>(); { observers.add(new Dad()); observers.add(new Mum()); observers.add(new Dog()); } public boolean isCry() { return isCry; } public void wakeUp() { isCry = true; observers.forEach(Observer::actionWakeUp); } }
[ "goodMorning@163.com" ]
goodMorning@163.com
a98a98988699d4e6f9fb1d181d5a04f6c5672778
fe6603be13ec9dc5dd08c5ef00e179c993147ac5
/LPOO/Progressao/Java/src/progressao/Ex16.java
280a9ac37f63fce5bea6c764cef46d6edfaab7d5
[]
no_license
luizRubens/FIEC1
bd814e7b5832d1a7cd76013859ce43e8461e072a
877c57183d47da4d761667bf2bb18f3d83ddeebe
refs/heads/master
2021-01-19T14:10:58.695428
2014-10-18T20:28:31
2014-10-18T20:28:31
null
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,736
java
package progressao; import javax.swing.JOptionPane; public class Ex16 { public static void main(String[] args) { int i; i = Integer.parseInt(JOptionPane.showInputDialog(null,"Digite a idade de um nadador e veja a qual categoria ele pertençe.")); if (i<=4){ JOptionPane.showMessageDialog(null,"Ainda não existe categoria para crianças menores de 5 anos." ); } if (i==5){ JOptionPane.showMessageDialog(null,"Categoria Infantil A = 5 a 7 anos."); } if (i==6){ JOptionPane.showMessageDialog(null,"Categoria Infantil A = 5 a 7 anos."); } if (i==7){ JOptionPane.showMessageDialog(null,"Categoria Infantil A = 5 a 7 anos."); } if (i==8){ JOptionPane.showMessageDialog(null,"Categoria Infantil B = 8 a 11 anos."); } if (i==9){ JOptionPane.showMessageDialog(null,"Categoria Infantil B = 8 a 11 anos."); } if (i==10){ JOptionPane.showMessageDialog(null,"Categoria Infantil B = 8 a 11 anos."); } if (i==11){ JOptionPane.showMessageDialog(null,"Categoria Infantil B = 8 a 11 anos."); } if (i==12){ JOptionPane.showMessageDialog(null,"Categoria Juvenil A = 12 a 13 anos."); } if (i==13){ JOptionPane.showMessageDialog(null,"Categoria Juvenil A = 12 a 13 anos."); } if (i==14){ JOptionPane.showMessageDialog(null,"Categoria Juvenil B = 14 a 17 anos."); } if (i==15){ JOptionPane.showMessageDialog(null,"Categoria Juvenil B = 14 a 17 anos."); } if (i==16){ JOptionPane.showMessageDialog(null,"Categoria Juvenil B = 14 a 17 anos."); } if (i==17){ JOptionPane.showMessageDialog(null,"Categoria Juvenil B = 14 a 17 anos."); } if (i>=18){ JOptionPane.showMessageDialog(null,"Categoria Adulta maiores de 18 anos"); } System.exit(0); } }
[ "luiz.rubens@hotmail.com" ]
luiz.rubens@hotmail.com
12bca60baa75aea6deb4a6b9071c096989e8f403
3a6657296de7fc1c97b76da629e7c3c4a6ad9a2b
/src/main/java/com/aif/language/common/ConstructorForTests.java
b4909195e911f77514dff6b094b0d48192d612e9
[ "MIT" ]
permissive
RobertEviston/AIF2
f5e9c500f5f5eb4a0c8e99863ab5dc35a67056a3
e6e8be0465cd7c6fdfea6cff80d009e96973e5be
refs/heads/master
2021-01-22T07:52:56.785542
2014-10-31T22:59:42
2014-10-31T22:59:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
76
java
package com.aif.language.common; public @interface ConstructorForTests { }
[ "vsk@amazon.com" ]
vsk@amazon.com
68cba5fcaa8aca76d5000473d202c9153acf0ca0
d4abeff3603f1f53b3c9e42e712846ef2e423285
/zflow-engine/src/main/java/com/yimei/zflow/api/annotation/GraphProperty.java
ef18030f39f5ac0517dcc2278bfaf1bbf4effd58
[]
no_license
jinwyp/aegis-zflow
5ed5ab015bb97f472f50260ddec0ba52953cc07e
bb0a1d32bc78354c77f19501e2fad0f24a7f1cd2
refs/heads/master
2021-03-27T10:33:18.669004
2017-02-03T07:17:38
2017-02-03T07:17:38
85,272,432
0
1
null
null
null
null
UTF-8
Java
false
false
343
java
package com.yimei.zflow.api.annotation; import java.lang.annotation.*; /** * Created by hary on 16/12/23. */ @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface GraphProperty { String graphType(); boolean persistent() default true; int timeout() default 200; String initial(); }
[ "94093146@qq.com" ]
94093146@qq.com
9f46c4cbc695d796d2797b1b33e0e7f71f9807cf
b7b3649f7005f12f4b4df2a9d6b996c5558db2bd
/Snapsauce/app/src/main/java/com/example/varun/snapsauce/datababse/DBHelper.java
e10c7b2358db8b7879ea5a5f827fbaf417680b1d
[]
no_license
vk117/TakeOutOrderManagementSystem
1f750b4b6c5a2de10de59d190d7ec0213d0f2792
c72e5607cc61ba51c8f9682a975ccf12c1557e70
refs/heads/master
2020-03-15T13:18:29.255358
2018-05-10T22:40:08
2018-05-10T22:40:08
132,163,392
0
0
null
null
null
null
UTF-8
Java
false
false
2,401
java
package com.example.varun.snapsauce.datababse; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; public class DBHelper extends SQLiteOpenHelper{ public static final String DATABASE_NAME = "snapsauce.db"; public static final int DATABASE_VERSION = 1; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db){ db.execSQL("create table " + DBSchema.TABLE_NAME + "(" + "_id integer primary key autoincrement, " + DBSchema.PHONE + "," + DBSchema.NAME + "," + DBSchema.EMAIL + "," + DBSchema.PASSWORD + ")" ); db.execSQL("create table " + DBSchema.TABLE2_NAME + "(" + "_id integer primary key autoincrement, " + DBSchema.CATEGORY + "," + DBSchema.NAME2 + "," + DBSchema.PRICE + "," + DBSchema.CALORIES + "," + DBSchema.TIME + "," + "image" + " " + "BLOB" + ")" ); db.execSQL("create table " + DBSchema.TABLE3_NAME + "(" + "_id integer primary key autoincrement, " + DBSchema.ORDERED_BY + "," + DBSchema.QUANTITY + "," + DBSchema.UNIT_PRICE + "," + DBSchema.PREP_TIME + "," + DBSchema.ITEM_NAME + ")" ); db.execSQL("create table " + DBSchema.TABLE4_NAME + "(" + "_id integer primary key autoincrement, " + DBSchema.ORDERED_BY2 + "," + DBSchema.PREP_TIME2 + "," + DBSchema.STATUS + "," + DBSchema.ITEM_NAME2 + ")" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists " + DBSchema.TABLE_NAME ); db.execSQL("drop table if exists " + DBSchema.TABLE2_NAME); db.execSQL("drop table if exists " + DBSchema.TABLE3_NAME); db.execSQL("drop table if exists " + DBSchema.TABLE4_NAME); onCreate(db); } }
[ "varun.khatri@sjsu.edu" ]
varun.khatri@sjsu.edu
28159a7daa14c2b9eb119c14b0e6e8dcf0ac4617
4624dede72b513e97719b00dd784f4aaf097b468
/src/main/java/br/com/jonyfs/errors/ErrorDetails.java
26fe624946713ed54546a490fbfb553cac8661b6
[]
no_license
jonyfs/spring-security-api
b80ebed6cfb32ba51e0e2f8e29bc80ece8d1e297
6b9db93946f4a41b58caf79f0f9dea44d3e42588
refs/heads/master
2020-03-26T20:23:28.874869
2018-08-30T21:32:44
2018-08-30T21:32:44
145,321,086
0
0
null
null
null
null
UTF-8
Java
false
false
506
java
package br.com.jonyfs.errors; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.Date; import java.util.List; import lombok.Builder; import lombok.ToString; import lombok.Value; import org.springframework.validation.FieldError; @Builder @Value @ToString @JsonInclude(JsonInclude.Include.NON_NULL) public class ErrorDetails { private final Date timestamp; private final String message; private final String details; private final List<FieldError> fieldErrorDetails; }
[ "jonyferreira@hotmail.com" ]
jonyferreira@hotmail.com
816a479ebe9a75e89fdad1b7c2ef91dbbb3ece57
37fc9967a0d407ccd97302b51614aface8d67cdb
/repositories/src/main/java/com/benchmarks/repos/generic_repos/InMemoryRepository.java
18b66dbcb923a7d23f35ae1453f7eb260dfb3208
[]
no_license
LauraOnac/maven-samples
16d3f56bbbcdc24a8d6fd1de2aa674581b65d7c5
ada01f4218f85b33c42630e93c4dd6fda04c6344
refs/heads/master
2021-09-02T17:05:07.656966
2018-01-03T18:30:17
2018-01-03T18:30:17
105,624,511
0
0
null
2017-10-03T07:20:18
2017-10-03T07:20:18
null
UTF-8
Java
false
false
235
java
package com.benchmarks.repos.generic_repos; /** * Created by Laura on 10/17/2017. */ public interface InMemoryRepository<T> { void add(T element); boolean contains(T element); void remove(T element); void clear(); }
[ "olie1970@scs.ubbcluj.ro" ]
olie1970@scs.ubbcluj.ro
635814ba82bdc7881b70ce34cce05a9dee6a08b2
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XRENDERING-481-3-2-NSGA_II-WeightedSum:TestLen:CallDiversity/org/xwiki/rendering/internal/transformation/macro/MacroTransformation_ESTest_scaffolding.java
ca8b82caa7d900a2dfe1af57ac4d1638c02399dc
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
473
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Thu Apr 02 09:27:59 UTC 2020 */ package org.xwiki.rendering.internal.transformation.macro; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; @EvoSuiteClassExclude public class MacroTransformation_ESTest_scaffolding { // Empty scaffolding for empty test suite }
[ "pouria.derakhshanfar@gmail.com" ]
pouria.derakhshanfar@gmail.com
8f604db2c4138d85c49d423bf2c1bdf1d83904bf
b5b36b2554dbd2f9aad48b09e61229aebdf86b08
/Java8/Tema2_Tipos de datos, operadores y estructuras de control/Proyectos/Ejercicios_Ejemplos_T2/src/manipulacionDatos/Operadores.java
af773885b6873f96228aa049e6d3f11f66d37e4b
[]
no_license
Emiju7/Java8
b3da75bac495d6a9b4cd275e201c8783ecd94a4b
77a9ba4a43d481ed4422b8fc43d4a9dd03b57345
refs/heads/master
2022-04-11T00:30:50.193521
2020-03-21T14:16:31
2020-03-21T14:16:31
250,355,900
0
0
null
null
null
null
UTF-8
Java
false
false
777
java
package manipulacionDatos; /** * * @author Emilio Luis Pareja Hinojosa */ public class Operadores { public static void main(String[] args) { int num1 = 4, num2 = 2, num3 = 0; int resultado; System.out.println("Suma: " + (num3 + 5)); System.out.println("Resta: " + (num1 - num2)); System.out.println("Multiplicacion: " + (num1 * num2)); System.out.println("Division: " + (num1 / num2)); System.out.println("Modulo: " + (num1 % 3)); System.out.println("++ : " + num3++); System.out.println("-- : " + num1--); //De igual manera se hace con la suma, la resta, la multiplicacion, el modulo y la division resultado = (num1 += num2); System.out.println(resultado); } }
[ "emijugigante7@gmail.com" ]
emijugigante7@gmail.com
b767f92b664be82ab1805e6d7ee34bd2316f0abf
bc63ec353d904f03bbc0bb4aaa45d47518496153
/major-server/src/main/java/com/yzm/majorserver/web/dataobject/UserDO.java
145689778996af8368417ab74b00040da16912d7
[]
no_license
apple006/major-onepunch
8ba85091cbddc8c77bb1f84b8715926ff3231835
3fcbfb2c2786624e3d471affcfccf650b673cfbf
refs/heads/master
2020-12-02T01:59:34.655034
2019-06-21T01:24:32
2019-06-21T01:24:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,343
java
package com.yzm.majorserver.web.dataobject; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.hibernate.validator.constraints.Length; import org.springframework.data.annotation.Transient; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.List; /** * @author : yizuomin * @date : Created in 15:57 2019/4/11 */ @Data public class UserDO implements UserDetails, Serializable { private static final long serialVersionUID = -7593316976318182376L; private Integer id; @NotBlank(message = "用户名不能为空") private String username; @NotBlank(message = "密码不能为空") private String password; @NotNull(message = "性别不能为空") private Integer sex; @Length(max = 11, min = 11, message = "手机号不合法") private String phone; @Email(message = "非法的邮箱格式") private String email; @NotBlank(message = "昵称不能为空") @Length(max = 20, min = 2, message = "昵称长度为2-20个字符") private String nickName; private String imgUrl; @Length(max = 255, message = "长度在255个字符内") private String signature; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; private List<RoleDO> roles; @Transient private Collection<? extends GrantedAuthority> grantedAuthority; @Override @JsonIgnore public Collection<? extends GrantedAuthority> getAuthorities() { return grantedAuthority; } @Override @JsonIgnore public boolean isAccountNonExpired() { return true; } @Override @JsonIgnore public boolean isAccountNonLocked() { return true; } @Override @JsonIgnore public boolean isCredentialsNonExpired() { return true; } @Override @JsonIgnore public boolean isEnabled() { return true; } }
[ "278406977@qq.com" ]
278406977@qq.com
ba163f748917fb63dd707eb50bf3f7688a9f0c69
5e819b4d8db56615d464b468675888830bebd670
/runtime-src/proj.android.456/src/com/game456/lytl/noscreen/AppActivity.java
6553618cb369881e7944c96a76f85bcc48497f05
[]
no_license
GameFramework/frameworks
192473f512601d47e55d143f007628a5ec5a5c0e
14a1e5eb70e5176cbbcdeb807963ce96fa48f75c
refs/heads/master
2021-07-05T09:37:52.312587
2017-09-27T09:44:57
2017-09-27T09:46:43
104,860,728
1
3
null
null
null
null
GB18030
Java
false
false
2,196
java
package com.game456.lytl.noscreen; import org.cocos2dx.lib.Cocos2dxActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.WindowManager; import com.sdk.mgr.LogManager; import com.sdk.mgr.SDKManager; import com.sdk.mgr.utility; public class AppActivity extends Cocos2dxActivity{ protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); initHandler(); //熄屏屏蔽 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //300000 为appid 与 init 里的appid 要一致 com.yunva.im.sdk.lib.YvLoginInit.initApplicationOnCreate(this.getApplication(),"1000541"); LogManager.isDevMode = false; SDKManager.getInstance().initSdk(AppActivity.this, savedInstanceState); } @Override protected void onStart() { super.onStart(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onResume() { SDKManager.vqsManager.onResume(); super.onResume(); } @Override public void onPause() { SDKManager.vqsManager.onPause(); super.onPause(); } @Override protected void onStop() { SDKManager.vqsManager.onStop(); super.onStop(); } @Override protected void onDestroy() { SDKManager.vqsManager.onDestroy(); super.onDestroy(); com.yunva.im.sdk.lib.YvLoginInit.release(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } static { System.loadLibrary("YvImSdk"); System.loadLibrary("cocos2dlua"); } /* * 客服端消息分发 */ @SuppressLint("HandlerLeak") private Handler mHandler = null; private void initHandler() { mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { default: SDKManager.onHandleMessage(msg); break; } } }; utility.handler = mHandler; } }
[ "469350450@qq.com" ]
469350450@qq.com
247269289cf674ff98d35554c4f6fee5478a8aa4
91882d9829f5d4e6e4ed6a1fe99a8ce206c99247
/src/main/java/com/demo/springshop/kafka/config/KafkaConfig.java
9c9a9545b26ecbedcd5f38ab8e183449793a971a
[]
no_license
mnetna/springkafka
b38a20023ea8ff84c32d2250a3b8ed75c0f0021f
14a79e2d223f33a33a5296668c02f7517181bfba
refs/heads/master
2022-02-25T01:17:38.374864
2019-09-18T08:49:31
2019-09-18T08:49:31
185,367,409
0
0
null
2023-09-05T22:01:42
2019-05-07T09:20:02
Java
UTF-8
Java
false
false
1,507
java
package com.demo.springshop.kafka.config; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.kafka.KafkaProperties.Listener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.*; import java.util.HashMap; import java.util.Map; @Configuration @EnableKafka public class KafkaConfig { @Bean public ProducerFactory<Integer, String> producerFactory() { return new DefaultKafkaProducerFactory<>(producerConfigs()); } @Bean public Map<String, Object> producerConfigs() { Map<String, Object> props = new HashMap<>(); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.56.1:9093,192.168.56.1:9095,192.168.56.1:9097"); props.put(ProducerConfig.ACKS_CONFIG, "1"); return props; } @Bean public KafkaTemplate<Integer, String> kafkaTemplate() { return new KafkaTemplate<Integer, String>(producerFactory()); } }
[ "sssolee90@gmail.com" ]
sssolee90@gmail.com
b93348136eea03991ed8ffd2f351327d0046d215
59c304ba8532e2d06f549dfc1f4258ac5e90ab65
/voronoi-pages-app/src/main/java/uq/spark/index/Page.java
72a87cbd3a4b9ee99b72b7d07d89f532a50fc942
[]
no_license
douglasapeixoto/voronoi-pages-spark
5c70348885dfae022eb6adca0c4e0fcd9c157ce5
0246d272e083c3c22102990e9aab841dbaf8f7dd
refs/heads/master
2020-12-29T00:13:08.771542
2016-06-15T08:23:19
2016-06-15T08:23:19
46,105,129
0
1
null
null
null
null
UTF-8
Java
false
false
4,454
java
package uq.spark.index; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.hadoop.io.Writable; import uq.spark.EnvironmentVariables; import uq.spatial.Point; import uq.spatial.Trajectory; import uq.spatial.TrajectoryRTree; /** * Implements a Voronoi Page. * </br></br> * A page is a spatial-temporal Voronoi polygon with a tree of * sub-trajectories during a certain time interval. * * @author uqdalves */ @SuppressWarnings("serial") public class Page implements Serializable, Writable, EnvironmentVariables{ /** * The tree containing the MBR of the * trajectories/sub-trajectories in this page */ private TrajectoryRTree trajectoryTree = new TrajectoryRTree(); /** * List of the parent trajectories of * the sub-trajectories in this page */ private HashSet<String> parentIdSet = new HashSet<String>(); /** * Add a trajectory/sub-trajectory to this page tree. */ public void add(Trajectory trajectory){ // add the MBR of this trajectory to the RTree trajectoryTree.add(trajectory); parentIdSet.add(trajectory.id); } /** * Merge two pages. * Add the trajectories/sub-trajectories from the given * page to this page trajectory tree. * * @return Return this merged page. */ public Page merge(Page page){ trajectoryTree.addAll(page.getTrajectoryList()); parentIdSet.addAll(page.parentIdSet); return this; } /** * Return the tree of sub-trajectories in this page. */ public TrajectoryRTree getTrajectoryTree(){ return trajectoryTree; } /** * Return the set of trajectories that overlaps with this page. * </br> * The parent trajectories of the sub-trajectories in this page. * * @return Return trajectories ID. */ public HashSet<String> getTrajectoryIdSet(){ return parentIdSet; } /** * The list of trajectories/sub-trajectories in this page. * </br></br> * Note that if a trajectory is contained in more than one page, * this function will return only those sub-trajectories contained * in the tree of this page specifically. */ public List<Trajectory> getTrajectoryList() { return trajectoryTree.getTrajectoryList(); } /** * Given a trajectory T id, return all * sub-trajectories in this page belonging to T. */ public List<Trajectory> getTrajectoriesById(String trajectoryId){ List<Trajectory> list = new ArrayList<Trajectory>(); for(Trajectory t : trajectoryTree.getTrajectoryList()){ if(trajectoryId.equals(t.id)){ list.add(t); } } return list; } /** * A list with all trajectory points in this page. */ public List<Point> getPointsList() { List<Point> pointsList = new ArrayList<Point>(); for(Trajectory t : trajectoryTree.getTrajectoryList()){ pointsList.addAll(t.getPointsList()); } return pointsList; } /** * Return the number of trajectories/sub-trajectories * in this page. */ public int size(){ return trajectoryTree.numTrajectories(); } /** * Return true is this page has no element * or is null. */ public boolean isEmpty(){ return trajectoryTree.isEmpty(); } /** * Print this page: System out. */ public String print() { String string = "Page ["; for(Trajectory t : trajectoryTree.getTrajectoryList()){ string += t.id + " {"; for(Point p : t.getPointsList()){ string += p.toString(); } string += "}"; } string += "]"; return string; } @Override public String toString() { // sub-trajectories separated by ":" // sample points separated by " " String string = ""; for(Trajectory t : trajectoryTree.getTrajectoryList()){ string += t.id; for(Point p : t.getPointsList()){ string += " " + p.toString(); } string += ":"; } return string.substring(0, string.length()-1); } public void readFields(DataInput in) throws IOException { int size = in.readInt(); trajectoryTree = new TrajectoryRTree(); parentIdSet = new HashSet<String>(size); for(int i = 0; i < size; i++){ Trajectory t = new Trajectory(); t.readFields(in); trajectoryTree.add(t); parentIdSet.add(t.id); } } public void write(DataOutput out) throws IOException { out.writeInt(this.size()); for(Trajectory t : trajectoryTree.getTrajectoryList()) { t.write(out); } } }
[ "Douglas A. Peixoto" ]
Douglas A. Peixoto
5a942a27aa22ec5caa420e94f1fc4a3589b96776
9aa5b3468ca1f59c5826a9927d44193a80ed6acd
/cq-component-maven-plugin/src/main/java/com/citytechinc/cq/component/editconfig/inplaceediting/image/ImageEditorMaker.java
a1d03589ba01f7f73b288ee0c4f0bd16803557f5
[ "Apache-2.0" ]
permissive
Pushparajan/cq-component-maven-plugin
9e063b0d5f00f3b5626ad3f27df15fdccea8a192
9af284307554106d214b90a57eb7f485a05588ee
refs/heads/develop
2021-01-21T07:20:15.210280
2017-05-29T02:24:21
2017-05-29T02:24:21
91,610,775
1
0
null
2017-05-17T19:02:13
2017-05-17T19:02:13
null
UTF-8
Java
false
false
5,117
java
/** * Copyright 2017 ICF Olson * * 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.citytechinc.cq.component.editconfig.inplaceediting.image; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.citytechinc.cq.component.AspectRatio; import com.citytechinc.cq.component.AspectRatioParameters; import com.citytechinc.cq.component.AspectRatios; import com.citytechinc.cq.component.AspectRatiosParameters; import com.citytechinc.cq.component.editconfig.ConfigElement; import com.citytechinc.cq.component.editconfig.DefaultInPlaceEditorParameters; import com.citytechinc.cq.component.editconfig.InPlaceEditorElement; import com.citytechinc.cq.component.editconfig.maker.AbstractInPlaceEditorMaker; import com.citytechinc.cq.component.editconfig.maker.InPlaceEditorMakerParameters; import com.citytechinc.cq.component.editconfig.annotations.inplaceeditors.ImageEditor; import com.citytechinc.cq.component.util.Constants; import com.citytechinc.cq.component.xml.DefaultXmlElement; import com.citytechinc.cq.component.xml.DefaultXmlElementParameters; import com.citytechinc.cq.component.xml.XmlElement; public class ImageEditorMaker extends AbstractInPlaceEditorMaker<DefaultInPlaceEditorParameters> { public ImageEditorMaker(InPlaceEditorMakerParameters parameters) { super(parameters); } @Override protected InPlaceEditorElement make(DefaultInPlaceEditorParameters parameters) throws ClassNotFoundException, IllegalAccessException, InstantiationException { ImageEditor imageEditor = (ImageEditor) this.parameters.getInPlaceEditorConfig().getInPlaceEditorAnnotation(); parameters.setTitle(imageEditor.title()); parameters.setEditorType("image"); List<XmlElement> pluginChildren = new ArrayList<XmlElement>(); // Builds rotate node DefaultXmlElementParameters rotateParameters = new DefaultXmlElementParameters(); rotateParameters.setFieldName("rotate"); rotateParameters.setPrimaryType(Constants.NT_UNSTRUCTURED); rotateParameters.setAdditionalProperties(Collections.singletonMap("features", imageEditor.enableRotate() ? "*" : "-")); pluginChildren.add(new DefaultXmlElement(rotateParameters)); // Builds crop node DefaultXmlElementParameters cropParameters = new DefaultXmlElementParameters(); cropParameters.setFieldName("crop"); cropParameters.setPrimaryType(Constants.NT_UNSTRUCTURED); cropParameters.setAdditionalProperties(Collections.singletonMap("features", imageEditor.enableCrop() ? "*" : "-")); if (imageEditor.cropAspectRatios().length > 0) { List<AspectRatio> aspectRatioChildren = new ArrayList<AspectRatio>(); for (int i = 0; i < imageEditor.cropAspectRatios().length; i++) { com.citytechinc.cq.component.annotations.AspectRatio aspectRatio = imageEditor.cropAspectRatios()[i]; AspectRatioParameters arp = new AspectRatioParameters(); arp.setName(aspectRatio.text()); arp.setRatio((double) aspectRatio.height() / aspectRatio.width()); arp.setFieldName(Integer.toString(i)); aspectRatioChildren.add(new AspectRatio(arp)); } AspectRatiosParameters aspectRatiosParameters = new AspectRatiosParameters(); aspectRatiosParameters.setContainedElements(aspectRatioChildren); cropParameters.setContainedElements(Arrays.asList(new AspectRatios(aspectRatiosParameters))); } pluginChildren.add(new DefaultXmlElement(cropParameters)); // Builds map node DefaultXmlElementParameters mapParameters = new DefaultXmlElementParameters(); mapParameters.setFieldName("map"); mapParameters.setPrimaryType(Constants.NT_UNSTRUCTURED); mapParameters .setAdditionalProperties(Collections.singletonMap("features", imageEditor.enableMap() ? "*" : "-")); pluginChildren.add(new DefaultXmlElement(mapParameters)); // Builds plugin node DefaultXmlElementParameters pluginsParameters = new DefaultXmlElementParameters(); pluginsParameters.setFieldName("plugins"); pluginsParameters.setPrimaryType(Constants.NT_UNSTRUCTURED); pluginsParameters.setContainedElements(pluginChildren); DefaultXmlElement plugins = new DefaultXmlElement(pluginsParameters); // Builds config node DefaultXmlElementParameters configParameters = new DefaultXmlElementParameters(); configParameters.setPrimaryType(Constants.NT_UNSTRUCTURED); configParameters.setContainedElements(Arrays.asList(plugins)); ConfigElement config = new ConfigElement(configParameters); parameters.setConfigElement(config); return new com.citytechinc.cq.component.editconfig.inplaceediting.image.ImageEditor(parameters); } }
[ "mhodgdon@citytechinc.com" ]
mhodgdon@citytechinc.com
d919135c227758307b83277bbd09bec822ef00a1
cf8b01ff30ccbad0d7762d5551fdacb15e8d40cf
/app/src/main/java/cn/fluencycat/protecteyes/PickImg/GlideImageLoader.java
43cd441efa303b1dcc560627ad68f9631f86a515
[]
no_license
FluencySCU/ProtectEyes
2a574d5edd7255c31b6d4ba1dad508865333ede9
ae995fa057de241662b2ffcf4e267e209825ede8
refs/heads/master
2021-04-15T14:15:37.896792
2018-03-23T14:06:47
2018-03-23T14:06:47
126,488,279
3
1
null
null
null
null
UTF-8
Java
false
false
1,148
java
package cn.fluencycat.protecteyes.PickImg; import android.content.Context; import android.net.Uri; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.imnjh.imagepicker.ImageLoader; import cn.fluencycat.protecteyes.Const.CONTEXT; import cn.fluencycat.protecteyes.R; public class GlideImageLoader implements ImageLoader { @Override public void bindImage(ImageView imageView, Uri uri, int width, int height) { Glide.with(CONTEXT.context).load(uri).placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher).override(width, height).dontAnimate().into(imageView); } @Override public void bindImage(ImageView imageView, Uri uri) { Glide.with(CONTEXT.context).load(uri).placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher).dontAnimate().into(imageView); } @Override public ImageView createImageView(Context context) { ImageView imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); return imageView; } @Override public ImageView createFakeImageView(Context context) { return new ImageView(context); } }
[ "1300975604@qq.com" ]
1300975604@qq.com
008f271675040544d60c31b28ee3a633d231ba5a
ef85d001323d6d6fbe010b74d2cdf86917ea1957
/Android Apps/Ratify/app/src/main/java/com/nitin/ratify/RatifyApp.java
331da83bce3534988d996ebd5dc15165cd94b86f
[]
no_license
danigunawan/EasyKyc
6b303c72d4f4ccfb0050b7a8668c452a140e4d2e
e93e0b69d0060f7d90f489102af9df0ca51089ff
refs/heads/master
2021-06-14T16:11:46.083138
2017-03-21T03:54:03
2017-03-21T03:54:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,871
java
package com.nitin.ratify; import android.app.Application; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.TextUtils; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.nitin.ratify.repository.remote.OkHttpStack; /** * Created by root on 21/3/17. */ public class RatifyApp extends Application { public static final String PACKAGE_NAME = "com.nitin.ekyc"; private static final String TAG = RatifyApp.class.getSimpleName(); private static RatifyApp mInstance; private RequestQueue mRequestQueue; public static synchronized RatifyApp getInstance() { return mInstance; } /** * Method provides defaultRetryPolice. * First Attempt = 14+(14*1)= 28s. * Second attempt = 28+(28*1)= 56s. * then invoke Response.ErrorListener callback. * * @return DefaultRetryPolicy object */ public static DefaultRetryPolicy getDefaultRetryPolice() { return new DefaultRetryPolicy(14000, 2, 1); } @Override public void onCreate() { super.onCreate(); mInstance = this; } /** * Method check, if internet is available. * * @return true if internet is available. Else otherwise. */ public boolean isDataConnected() { ConnectivityManager connectMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectMan.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); } public boolean isWiFiConnection() { ConnectivityManager connectMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectMan.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI; } //////////////////////// Volley request /////////////////////////////////////////////////////////////////////////////////////// public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(this, new OkHttpStack()); } return mRequestQueue; } public void setRequestQueue(RequestQueue requestQueue) { mRequestQueue = requestQueue; } public <T> void addToRequestQueue(Request<T> req, String tag) { // set the default tag if tag is empty req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); getRequestQueue().add(req); } public void cancelPendingRequests(Object tag) { if (mRequestQueue != null) { mRequestQueue.cancelAll(tag); } } }
[ "nitin@localhost.localdomain" ]
nitin@localhost.localdomain
479759b94208ba90b6ef4deb4ad3c96797ee43a3
02880a8ffb5633b13d5f3802adf0da753cb3b746
/consumerapp/src/main/java/winarwahyuw/winw/consumerapp/view_model/FavoriteViewModel.java
0d4ae572f8df5da3987908ce3e1ffd45cdb9619f
[]
no_license
winarwahyuw/Github-User-App
ccd80fb2ca9499d1cb4d98143c5333f75cebb6ea
aa0ba1f783dd1c2fcd635609aad66bbb626b0fce
refs/heads/master
2022-11-10T10:31:26.218901
2020-06-23T14:36:22
2020-06-23T14:36:22
274,425,796
0
0
null
null
null
null
UTF-8
Java
false
false
1,491
java
package winarwahyuw.winw.consumerapp.view_model; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import java.util.List; import winarwahyuw.winw.consumerapp.helper.MappingHelper; import winarwahyuw.winw.consumerapp.model.User; import static winarwahyuw.winw.consumerapp.database.DatabaseContract.FavoriteColumns.CONTENT_URI; public class FavoriteViewModel extends ViewModel { private MutableLiveData<List<User>> favoriteUser = new MutableLiveData<>();//untuk hal Favorite //untuk hal favorite public LiveData<List<User>> getFavoriteUser() { return favoriteUser; } //untuk hal favorite public void setFavoriteUser(Context context) { Uri uri = Uri.parse(CONTENT_URI.toString()); //ambil semua Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); Log.d("CEK", "ISI CURSOR" + cursor); if (cursor != null) { List<User> users = MappingHelper.mapCursorToArrayList(cursor); cursor.moveToNext(); favoriteUser.postValue(users); cursor.close(); Log.d("GET", "FAVORITE BERHASIL QUERYALL" + users); Log.d("GET", "FAVORITE BERHASIL QUERYALL" + favoriteUser); } else { Log.d("WARNING", "FAVORITE GAGAL DIMUAT"); } } }
[ "winarwahyuw99@gmail.com" ]
winarwahyuw99@gmail.com
ba26146161181b3975981a3028b02f011121f73e
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project54/src/test/java/org/gradle/test/performance54_3/Test54_230.java
f1eeafc1eb25944a58d45e52d57ae55bbc0b4397
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
292
java
package org.gradle.test.performance54_3; import static org.junit.Assert.*; public class Test54_230 { private final Production54_230 production = new Production54_230("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
[ "cedric.champeau@gmail.com" ]
cedric.champeau@gmail.com
c0a14432447e66c947d111f8b2859e969e7a5dce
9d9db5ec0531c12a1a9c4323e5ea7426cb31cc9e
/src/org/japo/java/main/Main.java
406ca65796e843669a3ff755a18149c9e0208cf9
[]
no_license
oscargimenez4/03310-EntradaBooleanRepeticion
dc366cbe69e0f79b26fa93d70ca9eb3e0f92b1e1
370b8e6a509f85331826c9d95ddd9994c0647247
refs/heads/master
2020-09-05T11:53:09.616004
2019-11-06T21:40:41
2019-11-06T21:40:41
220,095,666
0
0
null
null
null
null
UTF-8
Java
false
false
1,591
java
/* * Copyright 2019 Oscar G.4 - oscargimenez4@gmail.com. * * 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.japo.java.main; import java.util.Locale; import java.util.Scanner; /** * * @author Oscar G.4 - oscargimenez4@gmail.com */ public class Main { public static final Scanner SCN = new Scanner(System.in, "Windows-1252") .useLocale(Locale.ENGLISH).useDelimiter("\\s+"); public static void main(String[] args) { //Variables boolean testOK = false; boolean dato = true; //Bucle do { try { System.out.print("Introduzca un boolean....: "); dato = SCN.nextBoolean(); testOK = true; } catch (Exception e) { System.out.println("ERROR: Entrada incorrecta"); } finally { SCN.nextLine(); } } while (!testOK); System.out.printf(Locale.ENGLISH, "Su dato es ..............: %b%n", dato); } }
[ "OscarGim4" ]
OscarGim4
73644e2524b172b52188ba0886a787a7b6e52c45
b71673707e418dcbf869d0e53ef76f7ec7651ce1
/entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/builder/EntityViewBuilderTest.java
fc53c85e928ebce03272c615709035e6cee1f341
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Mobe91/blaze-persistence
bf92028028b241eb6a0a5f13dec323566f5ec9f8
8a4c867f07d6d31404d35e4db672b481fc8a2d59
refs/heads/master
2023-08-17T05:42:02.526696
2020-11-28T20:13:04
2020-11-28T20:13:04
83,560,399
0
0
NOASSERTION
2020-02-05T21:56:44
2017-03-01T13:59:01
Java
UTF-8
Java
false
false
3,938
java
/* * Copyright 2014 - 2020 Blazebit. * * 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.blazebit.persistence.view.testsuite.builder; import com.blazebit.persistence.view.EntityViewBuilder; import com.blazebit.persistence.view.EntityViewManager; import com.blazebit.persistence.view.EntityViews; import com.blazebit.persistence.view.spi.EntityViewConfiguration; import com.blazebit.persistence.view.testsuite.AbstractEntityViewTest; import com.blazebit.persistence.view.testsuite.builder.model.DocumentBuilderView; import com.blazebit.persistence.view.testsuite.builder.model.PersonView; import org.junit.Assert; import org.junit.Test; import java.util.Collections; /** * * @author Christian Beikov * @since 1.5.0 */ public class EntityViewBuilderTest extends AbstractEntityViewTest { @Test public void testBuilder() { Object global = new Object(); EntityViewConfiguration cfg = EntityViews.createDefaultConfiguration(); cfg.setOptionalParameter("test", global); EntityViewManager evm = build(cfg, DocumentBuilderView.class, PersonView.class); EntityViewBuilder<DocumentBuilderView> builder = evm.createBuilder(DocumentBuilderView.class); DocumentBuilderView view = builder.with("id", 10L) .with("name", "Test") .withSingularBuilder("owner") .with("id", 100L) .with("name", "Owner") .build() .withMapBuilder("contacts", 1) .with("id", 100L) .with("name", "Owner") .build() .withListBuilder("people", 1) .with("id", 100L) .with("name", "Owner") .build() .withCollectionBuilder("peopleListBag") .with("id", 100L) .with("name", "Owner") .build() .withCollectionBuilder("partners") .with("id", 100L) .with("name", "Owner") .build() .withElement("strings", "Test") .build(); assertView(view); Assert.assertEquals(global, view.getTest()); Object overridden = new Object(); DocumentBuilderView view2 = evm.createBuilder(view, Collections.singletonMap("test", overridden)) .withListBuilder("people", 0) .with("id", 100L) .with("name", "Owner") .build() .build(); assertView(view2); Assert.assertEquals(overridden, view2.getTest()); Assert.assertNull(view.getPeople().get(0)); assertOwner(view2.getPeople().get(0)); DocumentBuilderView view3 = evm.createBuilder(view).with(0, "Test").build(); Assert.assertEquals("Test", view3.getTest()); } private void assertView(DocumentBuilderView view) { Assert.assertEquals(10L, view.getId().longValue()); Assert.assertEquals("Test", view.getName()); assertOwner(view.getOwner()); assertOwner(view.getContacts().get(1)); assertOwner(view.getPeople().get(1)); assertOwner(view.getPeopleListBag().get(0)); assertOwner(view.getPartners().iterator().next()); Assert.assertEquals("Test", view.getStrings().iterator().next()); } private void assertOwner(PersonView p) { Assert.assertEquals(100L, p.getId().longValue()); Assert.assertEquals("Owner", p.getName()); } }
[ "christian.beikov@gmail.com" ]
christian.beikov@gmail.com
10efcf0e3d95f45ff591d30b22f87b4c219a561e
5cc014bfa847351780edbdcc330c8f5b9fc44601
/app/src/main/java/com/example/tae/snackbarexample3/MainActivity.java
576bf95fe4d3f250b14130c2e279d917f1af2023
[]
no_license
Anna-21/SnackBarExample3
841fb7cc32115d5f5a5eb6f45a004567f9405a63
cede27cb73c3917fec57f74f412c85367d05d53c
refs/heads/master
2020-06-05T05:50:56.595253
2019-06-17T11:47:17
2019-06-17T11:47:17
192,336,041
0
0
null
null
null
null
UTF-8
Java
false
false
2,027
java
package com.example.tae.snackbarexample3; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final View.OnClickListener snackBarClick = new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(),"This is a text", Toast.LENGTH_LONG).show(); } }; FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "This is a snack bar", Snackbar.LENGTH_LONG); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
[ "annashukallari@gmai.com" ]
annashukallari@gmai.com
e998a8de8b336b30b760ab518d8ea38698897406
ab9672fd9dc9e8e27489b8a9f808ebf692764e52
/rule/src/main/java/com/networknt/light/rule/file/UplFileRule.java
f382c790b8e7435cb2bd4e48f598a902a7767f06
[ "Apache-2.0" ]
permissive
Arsalaan-Hameed/light
b22e2ef65881897600c9bc5ae82b16c1670b0c3f
bf40443e38a94206169c14d8e3db195d8ecc0a03
refs/heads/master
2021-01-07T05:17:24.806135
2018-09-10T13:02:34
2018-09-10T13:02:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
596
java
package com.networknt.light.rule.file; import com.networknt.light.rule.Rule; import com.networknt.light.util.ServiceLocator; import io.undertow.server.HttpServerExchange; import io.undertow.util.Headers; import io.undertow.util.HttpString; import java.io.File; import java.util.Map; import java.util.concurrent.ConcurrentMap; /** * Created by steve on 2/26/2016. * * AccessLevel: R [fileAdmin, admin, owner] * */ public class UplFileRule extends AbstractFileRule implements Rule { public boolean execute (Object ...objects) throws Exception { return uplFile(objects); } }
[ "stevehu@gmail.com" ]
stevehu@gmail.com
d9c65816f9a7b0a5b28902f038069db5a9759f13
f9ee3538208b160eade2071cdd88d9e1831fbdc3
/src/main/java/servlets/LoginServlet.java
648a44db6f23be6d3541ddce5f86b094e3c52146
[]
no_license
rus-project01/newProject1.5
4eb8807c891095d39da5072ba8fbf3a88fa16844
bc91f13547b96e4fd58af6bdeb54e5e37ace4173
refs/heads/newProject1.3.1
2022-11-29T03:56:30.731910
2020-04-04T19:48:10
2020-04-04T19:48:10
253,085,762
0
0
null
2022-11-24T07:03:19
2020-04-04T19:46:08
Java
UTF-8
Java
false
false
1,056
java
package servlets; import model.User; import service.UserService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getServletContext().getRequestDispatcher("/login.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().removeAttribute("us"); req.getSession().removeAttribute("nameAttribute"); req.getSession().removeAttribute("roleAttribute"); req.getSession().removeAttribute("passwordAttribute"); req.getRequestDispatcher("/login.jsp").forward(req, resp); } }
[ "ruslanio.07@mail.ru" ]
ruslanio.07@mail.ru
219cf2a1e849b1be5e6e471278c21c7a3cbde3a7
d6388af8c5dd12e9bff244dfb296ac8af72fffdb
/View@Darly/app/src/main/java/com/darly/darlyview/wedget/focusresize/FocusResizeAdapter.java
04bfcbaca6f6a83a11d167a0b21e81a25d37b235
[]
no_license
Darlyyuhui/view-darly
d6ef91158ca5ba4a50300843f5e7bbc2713b7333
de58571a3ec336cc3fc3315904b8b8211a26904f
refs/heads/master
2020-04-11T01:59:07.672807
2018-04-16T02:59:02
2018-04-16T02:59:02
124,320,570
0
0
null
null
null
null
UTF-8
Java
false
false
3,386
java
/* * Copyright (C) 2016 Borja Bravo Álvarez * * 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.darly.darlyview.wedget.focusresize; import android.app.Activity; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.darly.darlyview.R; public abstract class FocusResizeAdapter<T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<T> { private static final int VIEW_TYPE_FOOTER = 1; private Context context; private int height; public FocusResizeAdapter(Context context, int height) { this.context = context; this.height = height; } @Override public T onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_FOOTER) { return (T) new FooterViewHolder( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer, parent, false)); } else { return onCreateFooterViewHolder(parent, viewType); } } @Override public final void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { // Loader ViewHolder if (position != getFooterItemCount()) { onBindFooterViewHolder((T) viewHolder, position); } } @Override public final int getItemCount() { if (getFooterItemCount() == 0) { return 0; } return getFooterItemCount() + 1; } @Override public final int getItemViewType(int position) { if (position != 0 && position == getItemCount() - 1) { return VIEW_TYPE_FOOTER; } return getItemFooterViewType(position); } public abstract void onItemBigResize(RecyclerView.ViewHolder viewHolder, int position, int dyAbs); public abstract void onItemBigResizeScrolled(RecyclerView.ViewHolder viewHolder, int position, int dyAbs); public abstract void onItemSmallResizeScrolled(RecyclerView.ViewHolder viewHolder, int position, int dyAbs); public abstract void onItemSmallResize(RecyclerView.ViewHolder viewHolder, int position, int dyAbs); public abstract void onItemInit(RecyclerView.ViewHolder viewHolder); public int getItemFooterViewType(int position) { return 0; } public abstract int getFooterItemCount(); public abstract T onCreateFooterViewHolder(ViewGroup parent, int viewType); public abstract void onBindFooterViewHolder(T holder, int position); public class FooterViewHolder extends RecyclerView.ViewHolder { public FooterViewHolder(View v) { super(v); v.getLayoutParams().height = Utils.getFooterHeight(((Activity) context), (int)(height * 1.5)); } } public int getHeight() { return height; } }
[ "Darlyyuhui@hotmail.com" ]
Darlyyuhui@hotmail.com
74b09ada3c4131a3c97131c560880e9d0f0a198c
2c9a480274e34d31b7b697988ca80e02b70c260a
/ydsy-manager/ydsy-manager-serviceimpl/src/main/java/cn/ydsy/manager/serviceimpl/ProductBookServiceImpl.java
0fc1df747549c2d4a0f5fe7d167cb9877f6c581c
[]
no_license
pdss/parent
e948b8605699cd7e0fb378510518d99421873114
b2aeb651a485fc93f499c491afe9de278b3fa3c5
refs/heads/master
2022-12-14T17:34:22.319653
2019-09-06T04:56:22
2019-09-06T04:56:22
206,714,348
0
0
null
2022-12-10T05:20:37
2019-09-06T04:42:51
Java
UTF-8
Java
false
false
868
java
package cn.ydsy.manager.serviceimpl; import cn.ydsy.manager.mapper.TbProductbookMapper; import cn.ydsy.manager.mapper.TbSchoolMapper; import cn.ydsy.manager.model.dbo.TbProductbook; import cn.ydsy.manager.model.dbo.TbSchool; import cn.ydsy.manager.model.dto.ProductBookDTO; import cn.ydsy.manager.model.dto.SchoolDTO; import cn.ydsy.manager.service.ProductBookService; import cn.ydsy.manager.service.SchoolService; import cn.ydsy.manager.utils.TransactionUtils; import com.alibaba.dubbo.config.annotation.Service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; @Service(interfaceClass = ProductBookService.class) public class ProductBookServiceImpl extends BaseServiceImpl<TbProductbookMapper, TbProductbook, ProductBookDTO> implements ProductBookService { }
[ "cao_steven@163.com" ]
cao_steven@163.com
6e461b191548b43fad9b18d08fbaac97abb7521d
9496cd26c2a4f1349d6c35b9bdb90a63cb4a4b74
/designdemo/src/main/java/com/example/builder/ColdDrink.java
12f225569e989fdc3914edf3d1d21e5bc23927d4
[]
no_license
apeing/designmodel
e88998929ed3b8294e19343b239664fa811da6ba
ac1f45aca0d266c115d82bd36cc643deec955e94
refs/heads/main
2023-04-15T21:43:09.442547
2021-04-27T09:00:11
2021-04-27T09:00:11
362,039,566
0
0
null
null
null
null
UTF-8
Java
false
false
215
java
package com.example.builder; public abstract class ColdDrink implements Item { //包装方法 public Packing packing() { return new Bottle(); } //价格 public abstract float price(); }
[ "lxl@gmail.com" ]
lxl@gmail.com
68523b7a9f4990e55c6024e26c627c032ef75f89
bae89ec0779f5ffeffbbea16a4a8baa171c7f0e7
/ps-mdm/src/com/orchestranetworks/ps/project/trigger/ProjectSubjectTableTrigger.java
24fe336a96e468517a3c99c3b4a8c98def4f4231
[]
no_license
static-x03/compensarEBX
25eec424e24ee1bc32e6944f6e57f9658fa7e684
82bc89d7f64d666b8a8b78d4c4c3f11894a97ce7
refs/heads/main
2023-08-13T02:22:17.735874
2021-10-14T02:10:48
2021-10-14T02:10:48
416,941,464
0
0
null
null
null
null
UTF-8
Java
false
false
12,604
java
/* * Copyright Orchestra Networks 2000-2012. All rights reserved. */ package com.orchestranetworks.ps.project.trigger; import java.util.*; import com.onwbp.adaptation.*; import com.onwbp.base.text.*; import com.orchestranetworks.instance.*; import com.orchestranetworks.ps.deepcopy.*; import com.orchestranetworks.ps.project.path.*; import com.orchestranetworks.ps.project.util.*; import com.orchestranetworks.ps.trigger.*; import com.orchestranetworks.ps.trigger.TriggerActionValidator.*; import com.orchestranetworks.ps.util.*; import com.orchestranetworks.schema.trigger.*; import com.orchestranetworks.service.*; /** * IMPORTANT NOTE: This class will now enforce application of User Permissions during any kind of Imports (either native EBX Imports or the Data Exchange add-on Imports) * -- BE AWARE that in any of your Table Trigger Subclasses, you should always be using <ValueContext.setValueEnablingPrivilegeForNode> instead of <<ValueContext.setValue> * when setting fields that the end-user might not have permission to update */ /** */ public abstract class ProjectSubjectTableTrigger extends BaseTableTriggerEnforcingPermissions implements ProjectPathCapable, SubjectPathCapable { // private static final String DELETED_PROJECT_SUBJECT_PROJECT_TYPE_PREFIX = "deletedProjectSubjectProjectType_"; private static final String DELETED_PROJECT_SUBJECT_SUBJECT_PK_PREFIX = "deletedProjectSubjectSubjectPK_"; public static final String ALLOW_SUBJECT_DELETION_PREFIX = "allowSubjectDeletion_"; protected abstract String getMasterDataSpaceName(); // // This is a stopgap measure to prevent someone from adding a subject to a non-new subject // project, // changing the subject, then removing it from the project. That would result in the changes // being merged // to the master even though they were never approved. // // Long-term strategy should be to back out the changes they made when they remove it, but that // can require some // extensive changes to be implemented so this is the default behavior. If that is done, then // extend this method // to not return a <code>ProjectSubjectTriggerActionValidator</code>. // @Override protected TriggerActionValidator createTriggerActionValidator(TriggerAction triggerAction) { return new ProjectSubjectTriggerActionValidator(); } /** * Return whether to check that the project's type is a New Subject type. * By default always checks if you're in a workflow, but can be overridden to customize the behavior. * * @param session the session * @return whether to check if it's a new subject type */ protected boolean checkIfNewSubjectProjectType(Session session) { return session.getInteraction(true) != null; } /** * Override this in order to specify to cascade delete when it's not a New Menu/Other Item * project and when the item hasn't already been deleted. (This will occur when a Detach * happens on the association.) */ // TODO: Can't do this because it will lead to error in EBX when it goes to delete // the menu item in a Delete context. Waiting to hear back from engineering on // how we can accomplish different behavior between Detach & Delete. // For now, a tech admin will just have to delete the unattached menu item. // If we end up doing this, will also need to set enableCascadeDelete = true and // foreignKeysToDelete = /menuItem or /offerOrOtherItem // @Override // protected boolean shouldCascadeDelete(TableTriggerExecutionContext context) // { // if (super.shouldCascadeDelete(context)) // { // String tablePathStr = context.getTable().getTablePath().format(); // String projectType = (String) context.getSession() // .getAttribute(DELETED_PROJECT_SUBJECT_PROJECT_TYPE_PREFIX + tablePathStr); // ProjectPathConfig projectPathConfig = getProjectPathConfig(); // if (projectPathConfig.isNewSubjectProjectType(projectType)) // { // Adaptation subjectRecord = getSubjectRecordFromSessionAttribute(context); // if (subjectRecord != null) // { // return true; // } // } // } // return false; // } @Override public void handleAfterCreate(AfterCreateOccurrenceContext context) throws OperationException { Session session = context.getSession(); if (session.getInteraction(true) != null) { SubjectPathConfig subjectPathConfig = getSubjectPathConfig(); Adaptation projectSubjectRecord = context.getAdaptationOccurrence(); Adaptation projectRecord = AdaptationUtil.followFK( projectSubjectRecord, subjectPathConfig.getProjectSubjectProjectFieldPath()); Adaptation subjectRecord = AdaptationUtil.followFK( projectSubjectRecord, subjectPathConfig.getProjectSubjectSubjectFieldPath()); // TODO: This is a workaround for the fact that EBX allows link table records to be // created even when // their fk filter is violated. Once that is addressed in EBX, this can be removed. // It needs to be done in afterCreate since we don't have a record to validate until // then. ValidationReport validationReport = projectSubjectRecord.getValidationReport(); if (validationReport.hasItemsOfSeverityOrMore(Severity.ERROR)) { throw OperationException.createError( "Association to " + projectRecord.getContainerTable().getTableNode().getLabel( session.getLocale()) + " can't be created. " + subjectRecord.getContainerTable().getTableNode().getLabel( session.getLocale()) + " may violate a constraint."); } modifySubjectRecordAfterCreate( projectRecord, subjectRecord, context.getProcedureContext(), session); } } protected void modifySubjectRecordAfterCreate( Adaptation projectRecord, Adaptation subjectRecord, ProcedureContext pContext, Session session) throws OperationException { ProjectPathConfig projectPathConfig = getProjectPathConfig(); String projectType = projectRecord .getString(projectPathConfig.getProjectProjectTypeFieldPath()); setCurrentProjectType(projectType, pContext, session, projectRecord, subjectRecord); } @Override public void handleBeforeDelete(BeforeDeleteOccurrenceContext context) throws OperationException { Session session = context.getSession(); Set<String> sessionAttributes = null; if (session.getInteraction(true) != null) { sessionAttributes = new HashSet<>(); SubjectPathConfig subjectPathConfig = getSubjectPathConfig(); Adaptation projectSubjectRecord = context.getAdaptationOccurrence(); String subjectPK = projectSubjectRecord .getString(subjectPathConfig.getProjectSubjectSubjectFieldPath()); String tablePathStr = context.getTable().getTablePath().format(); String sessionAttribute = DELETED_PROJECT_SUBJECT_SUBJECT_PK_PREFIX + tablePathStr; session.setAttribute(sessionAttribute, subjectPK); sessionAttributes.add(sessionAttribute); ProjectPathConfig projectPathConfig = getProjectPathConfig(); String projectType = (String) AdaptationUtil.followFK( projectSubjectRecord, subjectPathConfig.getProjectSubjectProjectFieldPath(), projectPathConfig.getProjectProjectTypeFieldPath()); if (projectPathConfig.isNewSubjectProjectType(projectType)) { // Put this in the session to be cleared out by the subject trigger. // If in a New Subject workflow, they detach the subject instead of // delete, then it won't get cleared but shouldn't really matter. sessionAttribute = ALLOW_SUBJECT_DELETION_PREFIX + subjectPathConfig.getSubjectTablePath().format() + "_" + subjectPK; session.setAttribute(sessionAttribute, "true"); sessionAttributes.add(sessionAttribute); } // sessionAttribute = DELETED_PROJECT_SUBJECT_PROJECT_TYPE_PREFIX + tablePathStr; // session.setAttribute(sessionAttribute, projectType); // sessionAttributes.add(sessionAttribute); } try { super.handleBeforeDelete(context); } catch (Exception ex) { if (sessionAttributes != null) { for (String sessionAttribute : sessionAttributes) { session.setAttribute(sessionAttribute, null); } } throw ex; } } @Override public void handleAfterDelete(AfterDeleteOccurrenceContext context) throws OperationException { Session session = context.getSession(); String tablePathStr = context.getTable().getTablePath().format(); try { if (session.getInteraction(true) != null) { Adaptation subjectRecord = getSubjectRecordFromSessionAttribute(context); if (subjectRecord != null) { SubjectPathConfig subjectPathConfig = getSubjectPathConfig(); Adaptation projectRecord = AdaptationUtil.followFK( context.getOccurrenceContext(), subjectPathConfig.getProjectSubjectProjectFieldPath()); setCurrentProjectType( null, context.getProcedureContext(), session, projectRecord, subjectRecord); } } super.handleAfterDelete(context); } finally { session.setAttribute(DELETED_PROJECT_SUBJECT_SUBJECT_PK_PREFIX + tablePathStr, null); // session.setAttribute(DELETED_PROJECT_SUBJECT_PROJECT_TYPE_PREFIX + tablePathStr, null); } } protected void setCurrentProjectType( String currentProjectType, ProcedureContext pContext, Session session, Adaptation projectRecord, Adaptation subjectRecord) throws OperationException { ProjectUtil.setCurrentProjectType( currentProjectType, subjectRecord, pContext, session, getProjectPathConfig(), getSubjectPathConfig()); } protected UserMessage checkCurrentProjectType( Session session, Adaptation projectRecord, Adaptation subjectRecord) { // TODO: This is a workaround for the fact that EBX allows link table // records to be created even when // their fk filter is violated. Once that is addressed in EBX, this can be // removed. String currentProjectType = ProjectUtil .getCurrentProjectType(subjectRecord, getMasterDataSpaceName(), getSubjectPathConfig()); if (currentProjectType != null) { Locale locale = session.getLocale(); return UserMessage.createError( "Association to " + projectRecord.getContainerTable().getTableNode().getLabel(locale) + " can't be created. " + subjectRecord.getContainerTable().getTableNode().getLabel(locale) + " is associated with another project."); } return null; } private Adaptation getSubjectRecordFromSessionAttribute(TableTriggerExecutionContext context) { Session session = context.getSession(); String tablePathStr = context.getTable().getTablePath().format(); String subjectPK = (String) session .getAttribute(DELETED_PROJECT_SUBJECT_SUBJECT_PK_PREFIX + tablePathStr); AdaptationTable subjectTable = context.getTable().getContainerAdaptation().getTable( getSubjectPathConfig().getSubjectTablePath()); return subjectTable.lookupAdaptationByPrimaryKey(PrimaryKey.parseString(subjectPK)); } protected class ProjectSubjectTriggerActionValidator implements TriggerActionValidator { @Override public UserMessage validateTriggerAction( Session session, ValueContext valueContext, ValueChanges valueChanges, TriggerAction action) throws OperationException { ProjectPathConfig projectPathConfig = getProjectPathConfig(); SubjectPathConfig subjectPathConfig = getSubjectPathConfig(); Adaptation projectRecord = AdaptationUtil .followFK(valueContext, subjectPathConfig.getProjectSubjectProjectFieldPath()); if (projectRecord != null) { if (action == TriggerAction.CREATE) { // If not deep copying, check the currentProjectType Boolean deepCopy = (Boolean) session .getAttribute(DeepCopyImpl.DEEP_COPY_SESSION_ATTRIBUTE); if (!Boolean.TRUE.equals(deepCopy)) { Adaptation subjectRecord = AdaptationUtil.followFK( valueContext, subjectPathConfig.getProjectSubjectSubjectFieldPath()); UserMessage msg = checkCurrentProjectType( session, projectRecord, subjectRecord); if (msg != null) { return msg; } } } else if (action == TriggerAction.DELETE) { if (checkIfNewSubjectProjectType(session)) { String projectType = projectRecord .getString(projectPathConfig.getProjectProjectTypeFieldPath()); if (!projectPathConfig.isNewSubjectProjectType(projectType)) { return UserMessage.createError( "Record cannot be removed from a " + projectType + " project once it has been added. You must cancel the project and relaunch it."); } } } } return null; } } }
[ "static-x03@hotmail.com" ]
static-x03@hotmail.com
0c3783d22ddd8ba6059fee8274334141749f9eea
e5d26140738ae894b519b5f2ce3ff8fb1b0a4a23
/app/src/main/java/tech/bloomgenetics/bloomapp/Login.java
2f07ed29bb4bdf2e6b6d5affd614e6480249e7d0
[]
no_license
JacquesTheRock/BloomApp
618123ed705a055c642f4d236bbddd99554bde2c
ff20355810891f476dd001236aee31487e75451d
refs/heads/master
2021-01-11T03:30:23.022645
2016-12-08T15:49:34
2016-12-08T15:49:34
70,998,640
0
0
null
null
null
null
UTF-8
Java
false
false
14,014
java
package tech.bloomgenetics.bloomapp; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.app.LoaderManager.LoaderCallbacks; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import static android.Manifest.permission.READ_CONTACTS; import android.content.Intent; /** * A login screen that offers login via email/password. */ public class Login extends AppCompatActivity implements LoaderCallbacks<Cursor> { /** * Id to identity READ_CONTACTS permission request. */ //private static final int REQUEST_READ_CONTACTS = 0; private String id = null; private String token = null; /** * Keep track of the login task to ensure we can cancel it if requested. */ private UserLoginTask mAuthTask = null; // UI references. private AutoCompleteTextView mEmailView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Set up the login form. // Collects username and password from text lines, attempts to log in using them. mEmailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); // Button that attempts to log in when button is pressed. Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { attemptLogin(); } }); // Button that redirects to the "Create New Account" page Button mCreateAccountButton = (Button) findViewById(R.id.create_account_button); mCreateAccountButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { goCreateAccount(); } }); mLoginFormView = findViewById(R.id.login_form); mProgressView = findViewById(R.id.login_progress); } // Here by default. We never use the contacts, but this function is needed by other parts of this page. private void populateAutoComplete() { /* if (!mayRequestContacts()) { return; } */ getLoaderManager().initLoader(0, null, this); } /* private boolean mayRequestContacts() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { return true; } if (shouldShowRequestPermissionRationale(READ_CONTACTS)) { Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, new View.OnClickListener() { @Override @TargetApi(Build.VERSION_CODES.M) public void onClick(View v) { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } }); } else { requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS); } return false; } */ /** * Callback received when a permissions request has been completed. @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_CONTACTS) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { populateAutoComplete(); } } } */ /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ private void attemptLogin() { if (mAuthTask != null) { return; } // Reset errors. mEmailView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // Check for a valid email address. if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } /*else if (!isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; }*/ if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); mAuthTask = new UserLoginTask(email, password); mAuthTask.execute((Void) null); } } // Not used anymore, left here in case we decide to use it later. private boolean isEmailValid(String email) { //TODO: Replace this with your own logic return email.contains("@"); } private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 4; } /** * Shows the progress UI and hides the login form. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) private void showProgress(final boolean show) { // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow // for very easy animations. If available, use these APIs to fade-in // the progress spinner. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); mLoginFormView.animate().setDuration(shortAnimTime).alpha( show ? 0 : 1).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } }); mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mProgressView.animate().setDuration(shortAnimTime).alpha( show ? 1 : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); } }); } else { // The ViewPropertyAnimator APIs are not available, so simply show // and hide the relevant UI components. mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); } } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact. Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses. ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[]{ContactsContract.CommonDataKinds.Email .CONTENT_ITEM_TYPE}, // Show primary email addresses first. Note that there won't be // a primary email address if the user hasn't specified one. ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { List<String> emails = new ArrayList<>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { emails.add(cursor.getString(ProfileQuery.ADDRESS)); cursor.moveToNext(); } addEmailsToAutoComplete(emails); } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { } private void addEmailsToAutoComplete(List<String> emailAddressCollection) { //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. ArrayAdapter<String> adapter = new ArrayAdapter<>(Login.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection); mEmailView.setAdapter(adapter); } private interface ProfileQuery { String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY, }; int ADDRESS = 0; int IS_PRIMARY = 1; } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { private final String mEmail; private final String mPassword; UserLoginTask(String email, String password) { mEmail = email; mPassword = password; } @Override protected Boolean doInBackground(Void... params) { // TODO: attempt authentication against a network service. try { // Simulate network access. Thread.sleep(2000); } catch (InterruptedException e) { return false; } /* for (String credential : DUMMY_CREDENTIALS) { String[] pieces = credential.split(":"); if (pieces[0].equals(mEmail)) { // Account exists, return true if the password matches. return pieces[1].equals(mPassword); } } */ UserAuth u = UserAuth.getInstance(); u.setUsername(mEmail); if(u.Login(mPassword)) { goMain(); } else { return false; } // TODO: register the new account here. return true; } // Checks to see if user token is same as last time to avoid having to log in every time. private void confirmToken(String token) { //URL apiURL = new URL("http://" + mEmail + ":" + token + "@bloomgenetics.tech/api/v1/auth"); } // Happens if attempting to log in fails. @Override protected void onPostExecute(final Boolean success) { mAuthTask = null; showProgress(false); if (success) { finish(); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } } @Override protected void onCancelled() { mAuthTask = null; showProgress(false); } } /* Redirects user to MainPage when login button is clicked */ public void goMain() { Intent intent = new Intent(this.getBaseContext(), MainPage.class); startActivity(intent); } /* Redirects user to CreateAccount when appropriate button is clicked */ public void goCreateAccount() { Intent intent = new Intent(this.getBaseContext(), CreateAccount.class); startActivity(intent); } }
[ "mdrichards95@yahoo.com" ]
mdrichards95@yahoo.com
5897487b694a43f98634761938af0009b4d5c07f
8f3da1595ac53b45c2270c17182fd7fe69848542
/16_12_ALL/src/Day06/ArraryCopyEx.java
3dcb43d20598620ea0245799b6030b36c87da142
[]
no_license
late-autumn/Java
7d0037d7bf9b265bd1a4742a41561d2b648e4269
c8e52ac4f1937185c3f45bce3c865d8e8bfd60ed
refs/heads/master
2021-01-12T00:19:29.848293
2017-02-23T01:16:58
2017-02-23T01:16:58
78,704,502
0
0
null
null
null
null
UTF-8
Java
false
false
362
java
package Day06; public class ArraryCopyEx { public static void main(String[] args) { String[] src = {"JAVA","DB","IoT","Linux"}; String[] des = new String[6]; des[0] = "os"; des[1] = "network"; System.arraycopy(src, 0, des, 2, 4); //원본, 위치, 복사할 대상, 복사할 인덱스, 총값 for(String te : des) System.out.println(te); } }
[ "late_autumn88@naver.com" ]
late_autumn88@naver.com
be4e812a5961f9b1b93467a663fa6925ddd2cd1f
ba3717948e52bfa24301b8f7c5469906e9452e6b
/WindowManager/app/src/test/java/com/example/admin/windowmanager/ExampleUnitTest.java
219fc462b80607637ac71a3e14a82ccb6a1a546f
[]
no_license
trantronghien/WindowManager
b226bde9b5d0ffbc628403b3f24e1135be373683
bea3a565e79de7c58c032a524339f23096e55f25
refs/heads/master
2021-01-24T18:12:30.173986
2017-05-22T06:47:26
2017-05-22T06:47:26
84,413,409
0
0
null
null
null
null
UTF-8
Java
false
false
409
java
package com.example.admin.windowmanager; 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); } }
[ "trantronghienit85@gmail.com" ]
trantronghienit85@gmail.com
c144c964bd109b68146837233cc71ccbeafca795
eaf8ee4a5becf87b1943dfb4241d7cd791958853
/media/java/android/media/AudioService.java
135cfb8229f98c85e526ae00e3c114cecfcfd482
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
gazachin/cc_frameworks_base
05b1246a10a4d00f9a94bfbdbb83ad42d68e5f18
3c5d4b6a8c0154cfa67801de0baad688707facd5
refs/heads/master
2021-05-28T05:27:39.633959
2012-10-14T13:54:45
2012-10-14T13:54:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
235,554
java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.media; import static android.Manifest.permission.REMOTE_AUDIO_PLAYBACK; import static android.media.AudioManager.RINGER_MODE_NORMAL; import static android.media.AudioManager.RINGER_MODE_SILENT; import static android.media.AudioManager.RINGER_MODE_VIBRATE; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.KeyguardManager; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.app.PendingIntent.OnFinished; import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothProfile; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.database.ContentObserver; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.os.Binder; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemProperties; import android.os.Vibrator; import android.provider.Settings; import android.provider.Settings.System; import android.speech.RecognizerIntent; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.VolumePanel; import android.provider.Settings.SettingNotFoundException; import android.content.res.Resources; import com.android.internal.app.ThemeUtils; import com.android.internal.telephony.ITelephony; import java.io.FileDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.Stack; /** * The implementation of the volume manager service. * <p> * This implementation focuses on delivering a responsive UI. Most methods are * asynchronous to external calls. For example, the task of setting a volume * will update our internal state, but in a separate thread will set the system * volume and later persist to the database. Similarly, setting the ringer mode * will update the state and broadcast a change and in a separate thread later * persist the ringer mode. * * @hide */ public class AudioService extends IAudioService.Stub implements OnFinished { private static final String TAG = "AudioService"; /** Debug remote control client/display feature */ protected static final boolean DEBUG_RC = false; /** Debug volumes */ protected static final boolean DEBUG_VOL = false; /** How long to delay before persisting a change in volume/ringer mode. */ private static final int PERSIST_DELAY = 500; private Context mContext; private ContentResolver mContentResolver; private boolean mVoiceCapable; /** The UI */ private VolumePanel mVolumePanel; private Context mUiContext; private Handler mHandler; // sendMsg() flags /** If the msg is already queued, replace it with this one. */ private static final int SENDMSG_REPLACE = 0; /** If the msg is already queued, ignore this one and leave the old. */ private static final int SENDMSG_NOOP = 1; /** If the msg is already queued, queue this one and leave the old. */ private static final int SENDMSG_QUEUE = 2; // AudioHandler messages private static final int MSG_SET_DEVICE_VOLUME = 0; private static final int MSG_PERSIST_VOLUME = 1; private static final int MSG_PERSIST_MASTER_VOLUME = 2; private static final int MSG_PERSIST_RINGER_MODE = 3; private static final int MSG_MEDIA_SERVER_DIED = 4; private static final int MSG_MEDIA_SERVER_STARTED = 5; private static final int MSG_PLAY_SOUND_EFFECT = 6; private static final int MSG_BTA2DP_DOCK_TIMEOUT = 7; private static final int MSG_LOAD_SOUND_EFFECTS = 8; private static final int MSG_SET_FORCE_USE = 9; private static final int MSG_PERSIST_MEDIABUTTONRECEIVER = 10; private static final int MSG_BT_HEADSET_CNCT_FAILED = 11; private static final int MSG_RCDISPLAY_CLEAR = 12; private static final int MSG_RCDISPLAY_UPDATE = 13; private static final int MSG_SET_ALL_VOLUMES = 14; private static final int MSG_PERSIST_MASTER_VOLUME_MUTE = 15; private static final int MSG_REPORT_NEW_ROUTES = 16; private static final int MSG_REEVALUATE_REMOTE = 17; private static final int MSG_RCC_NEW_PLAYBACK_INFO = 18; private static final int MSG_RCC_NEW_VOLUME_OBS = 19; // start of messages handled under wakelock // these messages can only be queued, i.e. sent with queueMsgUnderWakeLock(), // and not with sendMsg(..., ..., SENDMSG_QUEUE, ...) private static final int MSG_SET_WIRED_DEVICE_CONNECTION_STATE = 20; private static final int MSG_SET_A2DP_CONNECTION_STATE = 21; // end of messages handled under wakelock // flags for MSG_PERSIST_VOLUME indicating if current and/or last audible volume should be // persisted private static final int PERSIST_CURRENT = 0x1; private static final int PERSIST_LAST_AUDIBLE = 0x2; private static final int BTA2DP_DOCK_TIMEOUT_MILLIS = 8000; // Timeout for connection to bluetooth headset service private static final int BT_HEADSET_CNCT_TIMEOUT_MS = 3000; /** @see AudioSystemThread */ private AudioSystemThread mAudioSystemThread; /** @see AudioHandler */ private AudioHandler mAudioHandler; /** @see VolumeStreamState */ private VolumeStreamState[] mStreamStates; private SettingsObserver mSettingsObserver; //nodelay in a2dp private boolean noDelayInATwoDP = Resources.getSystem().getBoolean(com.android.internal.R.bool.config_noDelayInATwoDP); private int mMode; // protects mRingerMode private final Object mSettingsLock = new Object(); private boolean mMediaServerOk; private SoundPool mSoundPool; private final Object mSoundEffectsLock = new Object(); private static final int NUM_SOUNDPOOL_CHANNELS = 4; // Internally master volume is a float in the 0.0 - 1.0 range, // but to support integer based AudioManager API we translate it to 0 - 100 private static final int MAX_MASTER_VOLUME = 100; // Maximum volume adjust steps allowed in a single batch call. private static final int MAX_BATCH_VOLUME_ADJUST_STEPS = 4; /* Sound effect file names */ private static final String SOUND_EFFECTS_PATH = "/media/audio/ui/"; private static final String[] SOUND_EFFECT_FILES = new String[] { "Effect_Tick.ogg", "KeypressStandard.ogg", "KeypressSpacebar.ogg", "KeypressDelete.ogg", "KeypressReturn.ogg" }; /* Sound effect file name mapping sound effect id (AudioManager.FX_xxx) to * file index in SOUND_EFFECT_FILES[] (first column) and indicating if effect * uses soundpool (second column) */ private final int[][] SOUND_EFFECT_FILES_MAP = new int[][] { {0, -1}, // FX_KEY_CLICK {0, -1}, // FX_FOCUS_NAVIGATION_UP {0, -1}, // FX_FOCUS_NAVIGATION_DOWN {0, -1}, // FX_FOCUS_NAVIGATION_LEFT {0, -1}, // FX_FOCUS_NAVIGATION_RIGHT {1, -1}, // FX_KEYPRESS_STANDARD {2, -1}, // FX_KEYPRESS_SPACEBAR {3, -1}, // FX_FOCUS_DELETE {4, -1} // FX_FOCUS_RETURN }; /** @hide Maximum volume index values for audio streams */ private final int[] MAX_STREAM_VOLUME = new int[] { 5, // STREAM_VOICE_CALL 7, // STREAM_SYSTEM 7, // STREAM_RING 15, // STREAM_MUSIC 7, // STREAM_ALARM 7, // STREAM_NOTIFICATION 15, // STREAM_BLUETOOTH_SCO 7, // STREAM_SYSTEM_ENFORCED 15, // STREAM_DTMF 15 // STREAM_TTS }; /* mStreamVolumeAlias[] indicates for each stream if it uses the volume settings * of another stream: This avoids multiplying the volume settings for hidden * stream types that follow other stream behavior for volume settings * NOTE: do not create loops in aliases! * Some streams alias to different streams according to device category (phone or tablet) or * use case (in call s off call...).See updateStreamVolumeAlias() for more details * STREAM_VOLUME_ALIAS contains the default aliases for a voice capable device (phone) and * STREAM_VOLUME_ALIAS_NON_VOICE for a non voice capable device (tablet).*/ private final int[] STREAM_VOLUME_ALIAS = new int[] { AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL AudioSystem.STREAM_RING, // STREAM_SYSTEM AudioSystem.STREAM_RING, // STREAM_RING AudioSystem.STREAM_MUSIC, // STREAM_MUSIC AudioSystem.STREAM_ALARM, // STREAM_ALARM AudioSystem.STREAM_RING, // STREAM_NOTIFICATION AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO AudioSystem.STREAM_RING, // STREAM_SYSTEM_ENFORCED AudioSystem.STREAM_RING, // STREAM_DTMF AudioSystem.STREAM_MUSIC // STREAM_TTS }; private final int[] STREAM_VOLUME_ALIAS_NON_VOICE = new int[] { AudioSystem.STREAM_VOICE_CALL, // STREAM_VOICE_CALL AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM AudioSystem.STREAM_RING, // STREAM_RING AudioSystem.STREAM_MUSIC, // STREAM_MUSIC AudioSystem.STREAM_ALARM, // STREAM_ALARM AudioSystem.STREAM_RING, // STREAM_NOTIFICATION AudioSystem.STREAM_BLUETOOTH_SCO, // STREAM_BLUETOOTH_SCO AudioSystem.STREAM_MUSIC, // STREAM_SYSTEM_ENFORCED AudioSystem.STREAM_MUSIC, // STREAM_DTMF AudioSystem.STREAM_MUSIC // STREAM_TTS }; private int[] mStreamVolumeAlias; // stream names used by dumpStreamStates() private final String[] STREAM_NAMES = new String[] { "STREAM_VOICE_CALL", "STREAM_SYSTEM", "STREAM_RING", "STREAM_MUSIC", "STREAM_ALARM", "STREAM_NOTIFICATION", "STREAM_BLUETOOTH_SCO", "STREAM_SYSTEM_ENFORCED", "STREAM_DTMF", "STREAM_TTS" }; private boolean mLinkNotificationWithVolume; private static final int HEADSET_VOLUME_RESTORE_CAP_MUSIC = 8; // Out of 15 private final AudioSystem.ErrorCallback mAudioSystemCallback = new AudioSystem.ErrorCallback() { public void onError(int error) { switch (error) { case AudioSystem.AUDIO_STATUS_SERVER_DIED: if (mMediaServerOk) { sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0, null, 1500); mMediaServerOk = false; } break; case AudioSystem.AUDIO_STATUS_OK: if (!mMediaServerOk) { sendMsg(mAudioHandler, MSG_MEDIA_SERVER_STARTED, SENDMSG_NOOP, 0, 0, null, 0); mMediaServerOk = true; } break; default: break; } } }; /** * Current ringer mode from one of {@link AudioManager#RINGER_MODE_NORMAL}, * {@link AudioManager#RINGER_MODE_SILENT}, or * {@link AudioManager#RINGER_MODE_VIBRATE}. */ // protected by mSettingsLock private int mRingerMode; /** @see System#MODE_RINGER_STREAMS_AFFECTED */ private int mRingerModeAffectedStreams; // Streams currently muted by ringer mode private int mRingerModeMutedStreams; /** @see System#MUTE_STREAMS_AFFECTED */ private int mMuteAffectedStreams; /** * NOTE: setVibrateSetting(), getVibrateSetting(), shouldVibrate() are deprecated. * mVibrateSetting is just maintained during deprecation period but vibration policy is * now only controlled by mHasVibrator and mRingerMode */ private int mVibrateSetting; // Is there a vibrator private final boolean mHasVibrator; // Broadcast receiver for device connections intent broadcasts private final BroadcastReceiver mReceiver = new AudioServiceBroadcastReceiver(); // Used to alter media button redirection when the phone is ringing. private boolean mIsRinging = false; // Devices currently connected private final HashMap <Integer, String> mConnectedDevices = new HashMap <Integer, String>(); // Forced device usage for communications private int mForcedUseForComm; // True if we have master volume support private final boolean mUseMasterVolume; private final int[] mMasterVolumeRamp; // List of binder death handlers for setMode() client processes. // The last process to have called setMode() is at the top of the list. private final ArrayList <SetModeDeathHandler> mSetModeDeathHandlers = new ArrayList <SetModeDeathHandler>(); // List of clients having issued a SCO start request private final ArrayList <ScoClient> mScoClients = new ArrayList <ScoClient>(); // BluetoothHeadset API to control SCO connection private BluetoothHeadset mBluetoothHeadset; // Bluetooth headset device private BluetoothDevice mBluetoothHeadsetDevice; // Indicate if SCO audio connection is currently active and if the initiator is // audio service (internal) or bluetooth headset (external) private int mScoAudioState; // SCO audio state is not active private static final int SCO_STATE_INACTIVE = 0; // SCO audio activation request waiting for headset service to connect private static final int SCO_STATE_ACTIVATE_REQ = 1; // SCO audio state is active or starting due to a local request to start a virtual call private static final int SCO_STATE_ACTIVE_INTERNAL = 3; // SCO audio deactivation request waiting for headset service to connect private static final int SCO_STATE_DEACTIVATE_REQ = 5; // SCO audio state is active due to an action in BT handsfree (either voice recognition or // in call audio) private static final int SCO_STATE_ACTIVE_EXTERNAL = 2; // Deactivation request for all SCO connections (initiated by audio mode change) // waiting for headset service to connect private static final int SCO_STATE_DEACTIVATE_EXT_REQ = 4; // Current connection state indicated by bluetooth headset private int mScoConnectionState; // true if boot sequence has been completed private boolean mBootCompleted; // listener for SoundPool sample load completion indication private SoundPoolCallback mSoundPoolCallBack; // thread for SoundPool listener private SoundPoolListenerThread mSoundPoolListenerThread; // message looper for SoundPool listener private Looper mSoundPoolLooper = null; // volume applied to sound played with playSoundEffect() private static int SOUND_EFFECT_VOLUME_DB; // getActiveStreamType() will return STREAM_NOTIFICATION during this period after a notification // stopped private static final int NOTIFICATION_VOLUME_DELAY_MS = 5000; // previous volume adjustment direction received by checkForRingerModeChange() private int mPrevVolDirection = AudioManager.ADJUST_SAME; // Keyguard manager proxy private KeyguardManager mKeyguardManager; // mVolumeControlStream is set by VolumePanel to temporarily force the stream type which volume // is controlled by Vol keys. private int mVolumeControlStream = -1; private final Object mForceControlStreamLock = new Object(); // VolumePanel is currently the only client of forceVolumeControlStream() and runs in system // server process so in theory it is not necessary to monitor the client death. // However it is good to be ready for future evolutions. private ForceControlStreamClient mForceControlStreamClient = null; // Used to play ringtones outside system_server private volatile IRingtonePlayer mRingtonePlayer; private int mDeviceOrientation = Configuration.ORIENTATION_UNDEFINED; // Request to override default use of A2DP for media private boolean mBluetoothA2dpEnabled; private final Object mBluetoothA2dpEnabledLock = new Object(); // Monitoring of audio routes. Protected by mCurAudioRoutes. final AudioRoutesInfo mCurAudioRoutes = new AudioRoutesInfo(); final RemoteCallbackList<IAudioRoutesObserver> mRoutesObservers = new RemoteCallbackList<IAudioRoutesObserver>(); /** * A fake stream type to match the notion of remote media playback */ public final static int STREAM_REMOTE_MUSIC = -200; /////////////////////////////////////////////////////////////////////////// // Construction /////////////////////////////////////////////////////////////////////////// /** @hide */ public AudioService(Context context) { mContext = context; mContentResolver = context.getContentResolver(); mHandler = new Handler(); mVoiceCapable = mContext.getResources().getBoolean( com.android.internal.R.bool.config_voice_capable); PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent"); Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); mHasVibrator = vibrator == null ? false : vibrator.hasVibrator(); // Intialized volume MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL] = SystemProperties.getInt( "ro.config.vc_call_vol_steps", MAX_STREAM_VOLUME[AudioSystem.STREAM_VOICE_CALL]); SOUND_EFFECT_VOLUME_DB = context.getResources().getInteger( com.android.internal.R.integer.config_soundEffectVolumeDb); mMode = AudioSystem.MODE_NORMAL; mForcedUseForComm = AudioSystem.FORCE_NONE; createAudioSystemThread(); readPersistedSettings(); mSettingsObserver = new SettingsObserver(); updateStreamVolumeAlias(false /*updateVolumes*/); createStreamStates(); mMediaServerOk = true; // Call setRingerModeInt() to apply correct mute // state on streams affected by ringer mode. mRingerModeMutedStreams = 0; setRingerModeInt(getRingerMode(), false); AudioSystem.setErrorCallback(mAudioSystemCallback); // Register for device connection intent broadcasts. IntentFilter intentFilter = new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED); if (noDelayInATwoDP) intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED); intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED); intentFilter.addAction(Intent.ACTION_DOCK_EVENT); intentFilter.addAction(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG); intentFilter.addAction(Intent.ACTION_USB_AUDIO_DEVICE_PLUG); intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED); intentFilter.addAction(Intent.ACTION_SCREEN_ON); intentFilter.addAction(Intent.ACTION_SCREEN_OFF); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); // Register a configuration change listener only if requested by system properties // to monitor orientation changes (off by default) if (SystemProperties.getBoolean("ro.audio.monitorOrientation", false)) { Log.v(TAG, "monitoring device orientation"); intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); // initialize orientation in AudioSystem setOrientationForAudioSystem(); } context.registerReceiver(mReceiver, intentFilter); // Register for package removal intent broadcasts for media button receiver persistence IntentFilter pkgFilter = new IntentFilter(); pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); pkgFilter.addDataScheme("package"); context.registerReceiver(mReceiver, pkgFilter); ThemeUtils.registerThemeChangeReceiver(context, new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mUiContext = null; } }); // Register for phone state monitoring TelephonyManager tmgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); mUseMasterVolume = context.getResources().getBoolean( com.android.internal.R.bool.config_useMasterVolume); restoreMasterVolume(); mMasterVolumeRamp = context.getResources().getIntArray( com.android.internal.R.array.config_masterVolumeRamp); mMainRemote = new RemotePlaybackState(-1, MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC], MAX_STREAM_VOLUME[AudioManager.STREAM_MUSIC]); mHasRemotePlayback = false; mMainRemoteIsActive = false; postReevaluateRemote(); } private void createAudioSystemThread() { mAudioSystemThread = new AudioSystemThread(); mAudioSystemThread.start(); waitForAudioHandlerCreation(); } /** Waits for the volume handler to be created by the other thread. */ private void waitForAudioHandlerCreation() { synchronized(this) { while (mAudioHandler == null) { try { // Wait for mAudioHandler to be set by the other thread wait(); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while waiting on volume handler."); } } } } private void checkAllAliasStreamVolumes() { int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = 0; streamType < numStreamTypes; streamType++) { if (streamType != mStreamVolumeAlias[streamType]) { mStreamStates[streamType]. setAllIndexes(mStreamStates[mStreamVolumeAlias[streamType]], false /*lastAudible*/); mStreamStates[streamType]. setAllIndexes(mStreamStates[mStreamVolumeAlias[streamType]], true /*lastAudible*/); } // apply stream volume if (mStreamStates[streamType].muteCount() == 0) { mStreamStates[streamType].applyAllVolumes(); } } } private void createStreamStates() { int numStreamTypes = AudioSystem.getNumStreamTypes(); VolumeStreamState[] streams = mStreamStates = new VolumeStreamState[numStreamTypes]; for (int i = 0; i < numStreamTypes; i++) { streams[i] = new VolumeStreamState(System.VOLUME_SETTINGS[mStreamVolumeAlias[i]], i); } checkAllAliasStreamVolumes(); } private void dumpStreamStates(PrintWriter pw) { pw.println("\nStream volumes (device: index)"); int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int i = 0; i < numStreamTypes; i++) { pw.println("- "+STREAM_NAMES[i]+":"); mStreamStates[i].dump(pw); pw.println(""); } } private void updateStreamVolumeAlias(boolean updateVolumes) { int dtmfStreamAlias; if (mVoiceCapable) { mStreamVolumeAlias = STREAM_VOLUME_ALIAS; dtmfStreamAlias = AudioSystem.STREAM_RING; } else { mStreamVolumeAlias = STREAM_VOLUME_ALIAS_NON_VOICE; dtmfStreamAlias = AudioSystem.STREAM_MUSIC; } if (isInCommunication()) { dtmfStreamAlias = AudioSystem.STREAM_VOICE_CALL; } mStreamVolumeAlias[AudioSystem.STREAM_DTMF] = dtmfStreamAlias; if (mLinkNotificationWithVolume) { mStreamVolumeAlias[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING; } else { mStreamVolumeAlias[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION; } if (updateVolumes) { mStreamStates[AudioSystem.STREAM_DTMF].setAllIndexes(mStreamStates[dtmfStreamAlias], false /*lastAudible*/); mStreamStates[AudioSystem.STREAM_DTMF].setAllIndexes(mStreamStates[dtmfStreamAlias], true /*lastAudible*/); sendMsg(mAudioHandler, MSG_SET_ALL_VOLUMES, SENDMSG_QUEUE, 0, 0, mStreamStates[AudioSystem.STREAM_DTMF], 0); } } private void readPersistedSettings() { final ContentResolver cr = mContentResolver; int ringerModeFromSettings = System.getInt(cr, System.MODE_RINGER, AudioManager.RINGER_MODE_NORMAL); int ringerMode = ringerModeFromSettings; // sanity check in case the settings are restored from a device with incompatible // ringer modes if (!AudioManager.isValidRingerMode(ringerMode)) { ringerMode = AudioManager.RINGER_MODE_NORMAL; } if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) { ringerMode = AudioManager.RINGER_MODE_SILENT; } if (ringerMode != ringerModeFromSettings) { System.putInt(cr, System.MODE_RINGER, ringerMode); } synchronized(mSettingsLock) { mRingerMode = ringerMode; } // System.VIBRATE_ON is not used any more but defaults for mVibrateSetting // are still needed while setVibrateSetting() and getVibrateSetting() are being deprecated. mVibrateSetting = getValueForVibrateSetting(0, AudioManager.VIBRATE_TYPE_NOTIFICATION, mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT : AudioManager.VIBRATE_SETTING_OFF); mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, AudioManager.VIBRATE_TYPE_RINGER, mHasVibrator ? AudioManager.VIBRATE_SETTING_ONLY_SILENT : AudioManager.VIBRATE_SETTING_OFF); // make sure settings for ringer mode are consistent with device type: non voice capable // devices (tablets) include media stream in silent mode whereas phones don't. mRingerModeAffectedStreams = Settings.System.getInt(cr, Settings.System.MODE_RINGER_STREAMS_AFFECTED, ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED))); if (mVoiceCapable) { mRingerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC); } else { mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC); } Settings.System.putInt(cr, Settings.System.MODE_RINGER_STREAMS_AFFECTED, mRingerModeAffectedStreams); mLinkNotificationWithVolume = Settings.System.getInt(cr, Settings.System.VOLUME_LINK_NOTIFICATION, 1) == 1; mMuteAffectedStreams = System.getInt(cr, System.MUTE_STREAMS_AFFECTED, ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM))); boolean masterMute = System.getInt(cr, System.VOLUME_MASTER_MUTE, 0) == 1; AudioSystem.setMasterMute(masterMute); broadcastMasterMuteStatus(masterMute); // Each stream will read its own persisted settings // Broadcast the sticky intent broadcastRingerMode(ringerMode); // Broadcast vibrate settings broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); broadcastVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION); // Restore the default media button receiver from the system settings restoreMediaButtonReceiver(); } private int rescaleIndex(int index, int srcStream, int dstStream) { return (index * mStreamStates[dstStream].getMaxIndex() + mStreamStates[srcStream].getMaxIndex() / 2) / mStreamStates[srcStream].getMaxIndex(); } /////////////////////////////////////////////////////////////////////////// // IPC methods /////////////////////////////////////////////////////////////////////////// /** @see AudioManager#adjustVolume(int, int) */ public void adjustVolume(int direction, int flags) { adjustSuggestedStreamVolume(direction, AudioManager.USE_DEFAULT_STREAM_TYPE, flags); } /** @see AudioManager#adjustLocalOrRemoteStreamVolume(int, int) with current assumption * on streamType: fixed to STREAM_MUSIC */ public void adjustLocalOrRemoteStreamVolume(int streamType, int direction) { if (DEBUG_VOL) Log.d(TAG, "adjustLocalOrRemoteStreamVolume(dir="+direction+")"); if (checkUpdateRemoteStateIfActive(AudioSystem.STREAM_MUSIC)) { adjustRemoteVolume(AudioSystem.STREAM_MUSIC, direction, 0); } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) { adjustStreamVolume(AudioSystem.STREAM_MUSIC, direction, 0); } } /** @see AudioManager#adjustVolume(int, int, int) */ public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) { if (DEBUG_VOL) Log.d(TAG, "adjustSuggestedStreamVolume() stream="+suggestedStreamType); int streamType; if (mVolumeControlStream != -1) { streamType = mVolumeControlStream; } else { streamType = getActiveStreamType(suggestedStreamType); } // Play sounds on STREAM_RING only and if lock screen is not on. if ((streamType != STREAM_REMOTE_MUSIC) && (flags & AudioManager.FLAG_PLAY_SOUND) != 0 && ((mStreamVolumeAlias[streamType] != AudioSystem.STREAM_RING) || (mKeyguardManager != null && mKeyguardManager.isKeyguardLocked()))) { flags &= ~AudioManager.FLAG_PLAY_SOUND; } if (streamType == STREAM_REMOTE_MUSIC) { // don't play sounds for remote flags &= ~AudioManager.FLAG_PLAY_SOUND; //if (DEBUG_VOL) Log.i(TAG, "Need to adjust remote volume: calling adjustRemoteVolume()"); adjustRemoteVolume(AudioSystem.STREAM_MUSIC, direction, flags); } else { adjustStreamVolume(streamType, direction, flags); } } /** @see AudioManager#adjustStreamVolume(int, int, int) */ public void adjustStreamVolume(int streamType, int direction, int flags) { if (DEBUG_VOL) Log.d(TAG, "adjustStreamVolume() stream="+streamType+", dir="+direction); ensureValidDirection(direction); ensureValidStreamType(streamType); // use stream type alias here so that streams with same alias have the same behavior, // including with regard to silent mode control (e.g the use of STREAM_RING below and in // checkForRingerModeChange() in place of STREAM_RING or STREAM_NOTIFICATION) int streamTypeAlias = mStreamVolumeAlias[streamType]; VolumeStreamState streamState = mStreamStates[streamTypeAlias]; final int device = getDeviceForStream(streamTypeAlias); // get last audible index if stream is muted, current index otherwise final int aliasIndex = streamState.getIndex(device, (streamState.muteCount() != 0) /* lastAudible */); boolean adjustVolume = true; // convert one UI step (+/-1) into a number of internal units on the stream alias int step = rescaleIndex(10, streamType, streamTypeAlias); // If either the client forces allowing ringer modes for this adjustment, // or the stream type is one that is affected by ringer modes if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) || (streamTypeAlias == getMasterStreamType())) { int ringerMode = getRingerMode(); // do not vibrate if already in vibrate mode if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) { flags &= ~AudioManager.FLAG_VIBRATE; } // Check if the ringer mode changes with this volume adjustment. If // it does, it will handle adjusting the volume, so we won't below adjustVolume = checkForRingerModeChange(aliasIndex, direction, step); if ((streamTypeAlias == getMasterStreamType()) && (mRingerMode == AudioManager.RINGER_MODE_SILENT)) { streamState.setLastAudibleIndex(0, device); } } // If stream is muted, adjust last audible index only int index; final int oldIndex = mStreamStates[streamType].getIndex(device, (mStreamStates[streamType].muteCount() != 0) /* lastAudible */); if (streamState.muteCount() != 0) { if (adjustVolume) { // Post a persist volume msg // no need to persist volume on all streams sharing the same alias streamState.adjustLastAudibleIndex(direction * step, device); sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, SENDMSG_QUEUE, PERSIST_LAST_AUDIBLE, device, streamState, PERSIST_DELAY); } index = mStreamStates[streamType].getIndex(device, true /* lastAudible */); } else { if (adjustVolume && streamState.adjustIndex(direction * step, device)) { // Post message to set system volume (it in turn will post a message // to persist). Do not change volume if stream is muted. sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE, device, 0, streamState, 0); } index = mStreamStates[streamType].getIndex(device, false /* lastAudible */); } sendVolumeUpdate(streamType, oldIndex, index, flags); } /** @see AudioManager#adjustMasterVolume(int) */ public void adjustMasterVolume(int steps, int flags) { ensureValidSteps(steps); int volume = Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME); int delta = 0; int numSteps = Math.abs(steps); int direction = steps > 0 ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER; for (int i = 0; i < numSteps; ++i) { delta = findVolumeDelta(direction, volume); volume += delta; } //Log.d(TAG, "adjustMasterVolume volume: " + volume + " steps: " + steps); setMasterVolume(volume, flags); } /** @see AudioManager#setStreamVolume(int, int, int) */ public void setStreamVolume(int streamType, int index, int flags) { ensureValidStreamType(streamType); VolumeStreamState streamState = mStreamStates[mStreamVolumeAlias[streamType]]; final int device = getDeviceForStream(streamType); // get last audible index if stream is muted, current index otherwise final int oldIndex = streamState.getIndex(device, (streamState.muteCount() != 0) /* lastAudible */); index = rescaleIndex(index * 10, streamType, mStreamVolumeAlias[streamType]); // setting volume on master stream type also controls silent mode if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) || (mStreamVolumeAlias[streamType] == getMasterStreamType())) { int newRingerMode; if (index == 0) { newRingerMode = mHasVibrator ? AudioManager.RINGER_MODE_VIBRATE : AudioManager.RINGER_MODE_SILENT; setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, false, true); } else { newRingerMode = AudioManager.RINGER_MODE_NORMAL; } setRingerMode(newRingerMode); } setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, false, true); // get last audible index if stream is muted, current index otherwise index = mStreamStates[streamType].getIndex(device, (mStreamStates[streamType].muteCount() != 0) /* lastAudible */); sendVolumeUpdate(streamType, oldIndex, index, flags); } /** @see AudioManager#forceVolumeControlStream(int) */ public void forceVolumeControlStream(int streamType, IBinder cb) { synchronized(mForceControlStreamLock) { mVolumeControlStream = streamType; if (mVolumeControlStream == -1) { if (mForceControlStreamClient != null) { mForceControlStreamClient.release(); mForceControlStreamClient = null; } } else { mForceControlStreamClient = new ForceControlStreamClient(cb); } } } private class ForceControlStreamClient implements IBinder.DeathRecipient { private IBinder mCb; // To be notified of client's death ForceControlStreamClient(IBinder cb) { if (cb != null) { try { cb.linkToDeath(this, 0); } catch (RemoteException e) { // Client has died! Log.w(TAG, "ForceControlStreamClient() could not link to "+cb+" binder death"); cb = null; } } mCb = cb; } public void binderDied() { synchronized(mForceControlStreamLock) { Log.w(TAG, "SCO client died"); if (mForceControlStreamClient != this) { Log.w(TAG, "unregistered control stream client died"); } else { mForceControlStreamClient = null; mVolumeControlStream = -1; } } } public void release() { if (mCb != null) { mCb.unlinkToDeath(this, 0); mCb = null; } } } private int findVolumeDelta(int direction, int volume) { int delta = 0; if (direction == AudioManager.ADJUST_RAISE) { if (volume == MAX_MASTER_VOLUME) { return 0; } // This is the default value if we make it to the end delta = mMasterVolumeRamp[1]; // If we're raising the volume move down the ramp array until we // find the volume we're above and use that groups delta. for (int i = mMasterVolumeRamp.length - 1; i > 1; i -= 2) { if (volume >= mMasterVolumeRamp[i - 1]) { delta = mMasterVolumeRamp[i]; break; } } } else if (direction == AudioManager.ADJUST_LOWER){ if (volume == 0) { return 0; } int length = mMasterVolumeRamp.length; // This is the default value if we make it to the end delta = -mMasterVolumeRamp[length - 1]; // If we're lowering the volume move up the ramp array until we // find the volume we're below and use the group below it's delta for (int i = 2; i < length; i += 2) { if (volume <= mMasterVolumeRamp[i]) { delta = -mMasterVolumeRamp[i - 1]; break; } } } return delta; } // UI update and Broadcast Intent private void sendVolumeUpdate(int streamType, int oldIndex, int index, int flags) { if (!mVoiceCapable && (streamType == AudioSystem.STREAM_RING)) { streamType = AudioSystem.STREAM_NOTIFICATION; } showVolumeChangeUi(streamType, flags); oldIndex = (oldIndex + 5) / 10; index = (index + 5) / 10; Intent intent = new Intent(AudioManager.VOLUME_CHANGED_ACTION); intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, streamType); intent.putExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, index); intent.putExtra(AudioManager.EXTRA_PREV_VOLUME_STREAM_VALUE, oldIndex); mContext.sendBroadcast(intent); } // UI update and Broadcast Intent private void sendMasterVolumeUpdate(int flags, int oldVolume, int newVolume) { mVolumePanel.postMasterVolumeChanged(flags); Intent intent = new Intent(AudioManager.MASTER_VOLUME_CHANGED_ACTION); intent.putExtra(AudioManager.EXTRA_PREV_MASTER_VOLUME_VALUE, oldVolume); intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_VALUE, newVolume); mContext.sendBroadcast(intent); } // UI update and Broadcast Intent private void sendMasterMuteUpdate(boolean muted, int flags) { mVolumePanel.postMasterMuteChanged(flags); broadcastMasterMuteStatus(muted); } private void broadcastMasterMuteStatus(boolean muted) { Intent intent = new Intent(AudioManager.MASTER_MUTE_CHANGED_ACTION); intent.putExtra(AudioManager.EXTRA_MASTER_VOLUME_MUTED, muted); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | Intent.FLAG_RECEIVER_REPLACE_PENDING); long origCallerIdentityToken = Binder.clearCallingIdentity(); mContext.sendStickyBroadcast(intent); Binder.restoreCallingIdentity(origCallerIdentityToken); } /** * Sets the stream state's index, and posts a message to set system volume. * This will not call out to the UI. Assumes a valid stream type. * * @param streamType Type of the stream * @param index Desired volume index of the stream * @param device the device whose volume must be changed * @param force If true, set the volume even if the desired volume is same * as the current volume. * @param lastAudible If true, stores new index as last audible one */ private void setStreamVolumeInt(int streamType, int index, int device, boolean force, boolean lastAudible) { VolumeStreamState streamState = mStreamStates[streamType]; // If stream is muted, set last audible index only if (streamState.muteCount() != 0) { // Do not allow last audible index to be 0 if (index != 0) { streamState.setLastAudibleIndex(index, device); // Post a persist volume msg sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, SENDMSG_QUEUE, PERSIST_LAST_AUDIBLE, device, streamState, PERSIST_DELAY); } } else { if (streamState.setIndex(index, device, lastAudible) || force) { // Post message to set system volume (it in turn will post a message // to persist). sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE, device, 0, streamState, 0); } } } /** @see AudioManager#setStreamSolo(int, boolean) */ public void setStreamSolo(int streamType, boolean state, IBinder cb) { for (int stream = 0; stream < mStreamStates.length; stream++) { if (!isStreamAffectedByMute(stream) || stream == streamType) continue; // Bring back last audible volume mStreamStates[stream].mute(cb, state); } } /** @see AudioManager#setStreamMute(int, boolean) */ public void setStreamMute(int streamType, boolean state, IBinder cb) { if (isStreamAffectedByMute(streamType)) { mStreamStates[streamType].mute(cb, state); } } /** get stream mute state. */ public boolean isStreamMute(int streamType) { return (mStreamStates[streamType].muteCount() != 0); } /** @see AudioManager#setMasterMute(boolean, IBinder) */ public void setMasterMute(boolean state, int flags, IBinder cb) { if (state != AudioSystem.getMasterMute()) { AudioSystem.setMasterMute(state); // Post a persist master volume msg sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME_MUTE, SENDMSG_REPLACE, state ? 1 : 0, 0, null, PERSIST_DELAY); sendMasterMuteUpdate(state, flags); } } /** get master mute state. */ public boolean isMasterMute() { return AudioSystem.getMasterMute(); } /** @see AudioManager#getStreamVolume(int) */ public int getStreamVolume(int streamType) { ensureValidStreamType(streamType); int device = getDeviceForStream(streamType); return (mStreamStates[streamType].getIndex(device, false /* lastAudible */) + 5) / 10; } public int getMasterVolume() { if (isMasterMute()) return 0; return getLastAudibleMasterVolume(); } public void setMasterVolume(int volume, int flags) { if (volume < 0) { volume = 0; } else if (volume > MAX_MASTER_VOLUME) { volume = MAX_MASTER_VOLUME; } doSetMasterVolume((float)volume / MAX_MASTER_VOLUME, flags); } private void doSetMasterVolume(float volume, int flags) { // don't allow changing master volume when muted if (!AudioSystem.getMasterMute()) { int oldVolume = getMasterVolume(); AudioSystem.setMasterVolume(volume); int newVolume = getMasterVolume(); if (newVolume != oldVolume) { // Post a persist master volume msg sendMsg(mAudioHandler, MSG_PERSIST_MASTER_VOLUME, SENDMSG_REPLACE, Math.round(volume * (float)1000.0), 0, null, PERSIST_DELAY); } // Send the volume update regardless whether there was a change. sendMasterVolumeUpdate(flags, oldVolume, newVolume); } } /** @see AudioManager#getStreamMaxVolume(int) */ public int getStreamMaxVolume(int streamType) { ensureValidStreamType(streamType); return (mStreamStates[streamType].getMaxIndex() + 5) / 10; } public int getMasterMaxVolume() { return MAX_MASTER_VOLUME; } /** Get last audible volume before stream was muted. */ public int getLastAudibleStreamVolume(int streamType) { ensureValidStreamType(streamType); int device = getDeviceForStream(streamType); return (mStreamStates[streamType].getIndex(device, true /* lastAudible */) + 5) / 10; } /** Get last audible master volume before it was muted. */ public int getLastAudibleMasterVolume() { return Math.round(AudioSystem.getMasterVolume() * MAX_MASTER_VOLUME); } /** @see AudioManager#getMasterStreamType(int) */ public int getMasterStreamType() { if (mVoiceCapable) { return AudioSystem.STREAM_RING; } else { return AudioSystem.STREAM_MUSIC; } } /** @see AudioManager#getRingerMode() */ public int getRingerMode() { synchronized(mSettingsLock) { return mRingerMode; } } private void ensureValidRingerMode(int ringerMode) { if (!AudioManager.isValidRingerMode(ringerMode)) { throw new IllegalArgumentException("Bad ringer mode " + ringerMode); } } /** @see AudioManager#setRingerMode(int) */ public void setRingerMode(int ringerMode) { if ((ringerMode == AudioManager.RINGER_MODE_VIBRATE) && !mHasVibrator) { ringerMode = AudioManager.RINGER_MODE_SILENT; } if (ringerMode != getRingerMode()) { setRingerModeInt(ringerMode, true); // Send sticky broadcast broadcastRingerMode(ringerMode); } } private void setRingerModeInt(int ringerMode, boolean persist) { synchronized(mSettingsLock) { mRingerMode = ringerMode; } // Mute stream if not previously muted by ringer mode and ringer mode // is not RINGER_MODE_NORMAL and stream is affected by ringer mode. // Unmute stream if previously muted by ringer mode and ringer mode // is RINGER_MODE_NORMAL or stream is not affected by ringer mode. int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (isStreamMutedByRingerMode(streamType)) { if (!isStreamAffectedByRingerMode(streamType) || ringerMode == AudioManager.RINGER_MODE_NORMAL) { // ring and notifications volume should never be 0 when not silenced // on voice capable devices if (mVoiceCapable && mStreamVolumeAlias[streamType] == AudioSystem.STREAM_RING) { synchronized (mStreamStates[streamType]) { Set set = mStreamStates[streamType].mLastAudibleIndex.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); if ((Integer)entry.getValue() == 0) { entry.setValue(10); } } } } mStreamStates[streamType].mute(null, false); mRingerModeMutedStreams &= ~(1 << streamType); } } else { if (isStreamAffectedByRingerMode(streamType) && ringerMode != AudioManager.RINGER_MODE_NORMAL) { mStreamStates[streamType].mute(null, true); mRingerModeMutedStreams |= (1 << streamType); } } } // Post a persist ringer mode msg if (persist) { sendMsg(mAudioHandler, MSG_PERSIST_RINGER_MODE, SENDMSG_REPLACE, 0, 0, null, PERSIST_DELAY); } } private void restoreMasterVolume() { if (mUseMasterVolume) { float volume = Settings.System.getFloat(mContentResolver, Settings.System.VOLUME_MASTER, -1.0f); if (volume >= 0.0f) { AudioSystem.setMasterVolume(volume); } } } /** @see AudioManager#shouldVibrate(int) */ public boolean shouldVibrate(int vibrateType) { if (!mHasVibrator) return false; switch (getVibrateSetting(vibrateType)) { case AudioManager.VIBRATE_SETTING_ON: return getRingerMode() != AudioManager.RINGER_MODE_SILENT; case AudioManager.VIBRATE_SETTING_ONLY_SILENT: return getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; case AudioManager.VIBRATE_SETTING_OFF: // return false, even for incoming calls return false; default: return false; } } /** @see AudioManager#getVibrateSetting(int) */ public int getVibrateSetting(int vibrateType) { if (!mHasVibrator) return AudioManager.VIBRATE_SETTING_OFF; return (mVibrateSetting >> (vibrateType * 2)) & 3; } /** @see AudioManager#setVibrateSetting(int, int) */ public void setVibrateSetting(int vibrateType, int vibrateSetting) { if (!mHasVibrator) return; mVibrateSetting = getValueForVibrateSetting(mVibrateSetting, vibrateType, vibrateSetting); // Broadcast change broadcastVibrateSetting(vibrateType); } /** * @see #setVibrateSetting(int, int) */ public static int getValueForVibrateSetting(int existingValue, int vibrateType, int vibrateSetting) { // First clear the existing setting. Each vibrate type has two bits in // the value. Note '3' is '11' in binary. existingValue &= ~(3 << (vibrateType * 2)); // Set into the old value existingValue |= (vibrateSetting & 3) << (vibrateType * 2); return existingValue; } private class SetModeDeathHandler implements IBinder.DeathRecipient { private IBinder mCb; // To be notified of client's death private int mPid; private int mMode = AudioSystem.MODE_NORMAL; // Current mode set by this client SetModeDeathHandler(IBinder cb, int pid) { mCb = cb; mPid = pid; } public void binderDied() { int newModeOwnerPid = 0; synchronized(mSetModeDeathHandlers) { Log.w(TAG, "setMode() client died"); int index = mSetModeDeathHandlers.indexOf(this); if (index < 0) { Log.w(TAG, "unregistered setMode() client died"); } else { newModeOwnerPid = setModeInt(AudioSystem.MODE_NORMAL, mCb, mPid); } } // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all // SCO connections not started by the application changing the mode if (newModeOwnerPid != 0) { disconnectBluetoothSco(newModeOwnerPid); } } public int getPid() { return mPid; } public void setMode(int mode) { mMode = mode; } public int getMode() { return mMode; } public IBinder getBinder() { return mCb; } } /** @see AudioManager#setMode(int) */ public void setMode(int mode, IBinder cb) { if (!checkAudioSettingsPermission("setMode()")) { return; } if (mode < AudioSystem.MODE_CURRENT || mode >= AudioSystem.NUM_MODES) { return; } int newModeOwnerPid = 0; synchronized(mSetModeDeathHandlers) { if (mode == AudioSystem.MODE_CURRENT) { mode = mMode; } newModeOwnerPid = setModeInt(mode, cb, Binder.getCallingPid()); } // when entering RINGTONE, IN_CALL or IN_COMMUNICATION mode, clear all // SCO connections not started by the application changing the mode if (newModeOwnerPid != 0) { disconnectBluetoothSco(newModeOwnerPid); } } // must be called synchronized on mSetModeDeathHandlers // setModeInt() returns a valid PID if the audio mode was successfully set to // any mode other than NORMAL. int setModeInt(int mode, IBinder cb, int pid) { int newModeOwnerPid = 0; if (cb == null) { Log.e(TAG, "setModeInt() called with null binder"); return newModeOwnerPid; } SetModeDeathHandler hdlr = null; Iterator iter = mSetModeDeathHandlers.iterator(); while (iter.hasNext()) { SetModeDeathHandler h = (SetModeDeathHandler)iter.next(); if (h.getPid() == pid) { hdlr = h; // Remove from client list so that it is re-inserted at top of list iter.remove(); hdlr.getBinder().unlinkToDeath(hdlr, 0); break; } } int status = AudioSystem.AUDIO_STATUS_OK; do { if (mode == AudioSystem.MODE_NORMAL) { // get new mode from client at top the list if any if (!mSetModeDeathHandlers.isEmpty()) { hdlr = mSetModeDeathHandlers.get(0); cb = hdlr.getBinder(); mode = hdlr.getMode(); } } else { if (hdlr == null) { hdlr = new SetModeDeathHandler(cb, pid); } // Register for client death notification try { cb.linkToDeath(hdlr, 0); } catch (RemoteException e) { // Client has died! Log.w(TAG, "setMode() could not link to "+cb+" binder death"); } // Last client to call setMode() is always at top of client list // as required by SetModeDeathHandler.binderDied() mSetModeDeathHandlers.add(0, hdlr); hdlr.setMode(mode); } if (mode != mMode) { status = AudioSystem.setPhoneState(mode); if (status == AudioSystem.AUDIO_STATUS_OK) { mMode = mode; } else { if (hdlr != null) { mSetModeDeathHandlers.remove(hdlr); cb.unlinkToDeath(hdlr, 0); } // force reading new top of mSetModeDeathHandlers stack mode = AudioSystem.MODE_NORMAL; } } else { status = AudioSystem.AUDIO_STATUS_OK; } } while (status != AudioSystem.AUDIO_STATUS_OK && !mSetModeDeathHandlers.isEmpty()); if (status == AudioSystem.AUDIO_STATUS_OK) { if (mode != AudioSystem.MODE_NORMAL) { if (mSetModeDeathHandlers.isEmpty()) { Log.e(TAG, "setMode() different from MODE_NORMAL with empty mode client stack"); } else { newModeOwnerPid = mSetModeDeathHandlers.get(0).getPid(); } } int streamType = getActiveStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE); if (streamType == STREAM_REMOTE_MUSIC) { // here handle remote media playback the same way as local playback streamType = AudioManager.STREAM_MUSIC; } int device = getDeviceForStream(streamType); int index = mStreamStates[mStreamVolumeAlias[streamType]].getIndex(device, false); setStreamVolumeInt(mStreamVolumeAlias[streamType], index, device, true, false); updateStreamVolumeAlias(true /*updateVolumes*/); } return newModeOwnerPid; } /** @see AudioManager#getMode() */ public int getMode() { return mMode; } /** @see AudioManager#playSoundEffect(int) */ public void playSoundEffect(int effectType) { sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_NOOP, effectType, -1, null, 0); } /** @see AudioManager#playSoundEffect(int, float) */ public void playSoundEffectVolume(int effectType, float volume) { loadSoundEffects(); sendMsg(mAudioHandler, MSG_PLAY_SOUND_EFFECT, SENDMSG_NOOP, effectType, (int) (volume * 1000), null, 0); } /** * Loads samples into the soundpool. * This method must be called at first when sound effects are enabled */ public boolean loadSoundEffects() { int status; synchronized (mSoundEffectsLock) { if (!mBootCompleted) { Log.w(TAG, "loadSoundEffects() called before boot complete"); return false; } if (mSoundPool != null) { return true; } mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0); try { mSoundPoolCallBack = null; mSoundPoolListenerThread = new SoundPoolListenerThread(); mSoundPoolListenerThread.start(); // Wait for mSoundPoolCallBack to be set by the other thread mSoundEffectsLock.wait(); } catch (InterruptedException e) { Log.w(TAG, "Interrupted while waiting sound pool listener thread."); } if (mSoundPoolCallBack == null) { Log.w(TAG, "loadSoundEffects() could not create SoundPool listener or thread"); if (mSoundPoolLooper != null) { mSoundPoolLooper.quit(); mSoundPoolLooper = null; } mSoundPoolListenerThread = null; mSoundPool.release(); mSoundPool = null; return false; } /* * poolId table: The value -1 in this table indicates that corresponding * file (same index in SOUND_EFFECT_FILES[] has not been loaded. * Once loaded, the value in poolId is the sample ID and the same * sample can be reused for another effect using the same file. */ int[] poolId = new int[SOUND_EFFECT_FILES.length]; for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { poolId[fileIdx] = -1; } /* * Effects whose value in SOUND_EFFECT_FILES_MAP[effect][1] is -1 must be loaded. * If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0: * this indicates we have a valid sample loaded for this effect. */ int lastSample = 0; for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { // Do not load sample if this effect uses the MediaPlayer if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) { continue; } if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) { String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]]; int sampleId = mSoundPool.load(filePath, 0); if (sampleId <= 0) { Log.w(TAG, "Soundpool could not load file: "+filePath); } else { SOUND_EFFECT_FILES_MAP[effect][1] = sampleId; poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId; lastSample = sampleId; } } else { SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]]; } } // wait for all samples to be loaded if (lastSample != 0) { mSoundPoolCallBack.setLastSample(lastSample); try { mSoundEffectsLock.wait(); status = mSoundPoolCallBack.status(); } catch (java.lang.InterruptedException e) { Log.w(TAG, "Interrupted while waiting sound pool callback."); status = -1; } } else { status = -1; } if (mSoundPoolLooper != null) { mSoundPoolLooper.quit(); mSoundPoolLooper = null; } mSoundPoolListenerThread = null; if (status != 0) { Log.w(TAG, "loadSoundEffects(), Error " + ((lastSample != 0) ? mSoundPoolCallBack.status() : -1) + " while loading samples"); for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { if (SOUND_EFFECT_FILES_MAP[effect][1] > 0) { SOUND_EFFECT_FILES_MAP[effect][1] = -1; } } mSoundPool.release(); mSoundPool = null; } } return (status == 0); } /** * Unloads samples from the sound pool. * This method can be called to free some memory when * sound effects are disabled. */ public void unloadSoundEffects() { synchronized (mSoundEffectsLock) { if (mSoundPool == null) { return; } mAudioHandler.removeMessages(MSG_LOAD_SOUND_EFFECTS); mAudioHandler.removeMessages(MSG_PLAY_SOUND_EFFECT); int[] poolId = new int[SOUND_EFFECT_FILES.length]; for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) { poolId[fileIdx] = 0; } for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) { if (SOUND_EFFECT_FILES_MAP[effect][1] <= 0) { continue; } if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == 0) { mSoundPool.unload(SOUND_EFFECT_FILES_MAP[effect][1]); SOUND_EFFECT_FILES_MAP[effect][1] = -1; poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1; } } mSoundPool.release(); mSoundPool = null; } } class SoundPoolListenerThread extends Thread { public SoundPoolListenerThread() { super("SoundPoolListenerThread"); } @Override public void run() { Looper.prepare(); mSoundPoolLooper = Looper.myLooper(); synchronized (mSoundEffectsLock) { if (mSoundPool != null) { mSoundPoolCallBack = new SoundPoolCallback(); mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack); } mSoundEffectsLock.notify(); } Looper.loop(); } } private final class SoundPoolCallback implements android.media.SoundPool.OnLoadCompleteListener { int mStatus; int mLastSample; public int status() { return mStatus; } public void setLastSample(int sample) { mLastSample = sample; } public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { synchronized (mSoundEffectsLock) { if (status != 0) { mStatus = status; } if (sampleId == mLastSample) { mSoundEffectsLock.notify(); } } } } /** @see AudioManager#reloadAudioSettings() */ public void reloadAudioSettings() { // restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings readPersistedSettings(); // restore volume settings int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = 0; streamType < numStreamTypes; streamType++) { VolumeStreamState streamState = mStreamStates[streamType]; synchronized (streamState) { streamState.readSettings(); // unmute stream that was muted but is not affect by mute anymore if (streamState.muteCount() != 0 && !isStreamAffectedByMute(streamType)) { int size = streamState.mDeathHandlers.size(); for (int i = 0; i < size; i++) { streamState.mDeathHandlers.get(i).mMuteCount = 1; streamState.mDeathHandlers.get(i).mute(false); } } } } checkAllAliasStreamVolumes(); // apply new ringer mode setRingerModeInt(getRingerMode(), false); } /** @see AudioManager#setSpeakerphoneOn() */ public void setSpeakerphoneOn(boolean on){ if (!checkAudioSettingsPermission("setSpeakerphoneOn()")) { return; } mForcedUseForComm = on ? AudioSystem.FORCE_SPEAKER : AudioSystem.FORCE_NONE; sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0); } /** @see AudioManager#isSpeakerphoneOn() */ public boolean isSpeakerphoneOn() { return (mForcedUseForComm == AudioSystem.FORCE_SPEAKER); } /** @see AudioManager#setBluetoothScoOn() */ public void setBluetoothScoOn(boolean on){ if (!checkAudioSettingsPermission("setBluetoothScoOn()")) { return; } mForcedUseForComm = on ? AudioSystem.FORCE_BT_SCO : AudioSystem.FORCE_NONE; sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, AudioSystem.FOR_COMMUNICATION, mForcedUseForComm, null, 0); sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, AudioSystem.FOR_RECORD, mForcedUseForComm, null, 0); } /** @see AudioManager#isBluetoothScoOn() */ public boolean isBluetoothScoOn() { return (mForcedUseForComm == AudioSystem.FORCE_BT_SCO); } /** @see AudioManager#setBluetoothA2dpOn() */ public void setBluetoothA2dpOn(boolean on) { if (!checkAudioSettingsPermission("setBluetoothA2dpOn()") && noDelayInATwoDP) { return; } setBluetoothA2dpOnInt(on); } /** @see AudioManager#isBluetoothA2dpOn() */ public boolean isBluetoothA2dpOn() { synchronized (mBluetoothA2dpEnabledLock) { return mBluetoothA2dpEnabled; } } /** @see AudioManager#startBluetoothSco() */ public void startBluetoothSco(IBinder cb){ if (!checkAudioSettingsPermission("startBluetoothSco()") || !mBootCompleted) { return; } ScoClient client = getScoClient(cb, true); client.incCount(); } /** @see AudioManager#stopBluetoothSco() */ public void stopBluetoothSco(IBinder cb){ if (!checkAudioSettingsPermission("stopBluetoothSco()") || !mBootCompleted) { return; } ScoClient client = getScoClient(cb, false); if (client != null) { client.decCount(); } } private class ScoClient implements IBinder.DeathRecipient { private IBinder mCb; // To be notified of client's death private int mCreatorPid; private int mStartcount; // number of SCO connections started by this client ScoClient(IBinder cb) { mCb = cb; mCreatorPid = Binder.getCallingPid(); mStartcount = 0; } public void binderDied() { synchronized(mScoClients) { Log.w(TAG, "SCO client died"); int index = mScoClients.indexOf(this); if (index < 0) { Log.w(TAG, "unregistered SCO client died"); } else { clearCount(true); mScoClients.remove(this); } } } public void incCount() { synchronized(mScoClients) { requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED); if (mStartcount == 0) { try { mCb.linkToDeath(this, 0); } catch (RemoteException e) { // client has already died! Log.w(TAG, "ScoClient incCount() could not link to "+mCb+" binder death"); } } mStartcount++; } } public void decCount() { synchronized(mScoClients) { if (mStartcount == 0) { Log.w(TAG, "ScoClient.decCount() already 0"); } else { mStartcount--; if (mStartcount == 0) { try { mCb.unlinkToDeath(this, 0); } catch (NoSuchElementException e) { Log.w(TAG, "decCount() going to 0 but not registered to binder"); } } requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED); } } } public void clearCount(boolean stopSco) { synchronized(mScoClients) { if (mStartcount != 0) { try { mCb.unlinkToDeath(this, 0); } catch (NoSuchElementException e) { Log.w(TAG, "clearCount() mStartcount: "+mStartcount+" != 0 but not registered to binder"); } } mStartcount = 0; if (stopSco) { requestScoState(BluetoothHeadset.STATE_AUDIO_DISCONNECTED); } } } public int getCount() { return mStartcount; } public IBinder getBinder() { return mCb; } public int getPid() { return mCreatorPid; } public int totalCount() { synchronized(mScoClients) { int count = 0; int size = mScoClients.size(); for (int i = 0; i < size; i++) { count += mScoClients.get(i).getCount(); } return count; } } private void requestScoState(int state) { checkScoAudioState(); if (totalCount() == 0) { if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) { // Make sure that the state transitions to CONNECTING even if we cannot initiate // the connection. broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING); // Accept SCO audio activation only in NORMAL audio mode or if the mode is // currently controlled by the same client process. synchronized(mSetModeDeathHandlers) { if ((mSetModeDeathHandlers.isEmpty() || mSetModeDeathHandlers.get(0).getPid() == mCreatorPid) && (mScoAudioState == SCO_STATE_INACTIVE || mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) { if (mScoAudioState == SCO_STATE_INACTIVE) { if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) { if (mBluetoothHeadset.startScoUsingVirtualVoiceCall( mBluetoothHeadsetDevice)) { mScoAudioState = SCO_STATE_ACTIVE_INTERNAL; } else { broadcastScoConnectionState( AudioManager.SCO_AUDIO_STATE_DISCONNECTED); } } else if (getBluetoothHeadset()) { mScoAudioState = SCO_STATE_ACTIVATE_REQ; } } else { mScoAudioState = SCO_STATE_ACTIVE_INTERNAL; broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTED); } } else { broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED); } } } else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED && (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL || mScoAudioState == SCO_STATE_ACTIVATE_REQ)) { if (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL) { if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null) { if (!mBluetoothHeadset.stopScoUsingVirtualVoiceCall( mBluetoothHeadsetDevice)) { mScoAudioState = SCO_STATE_INACTIVE; broadcastScoConnectionState( AudioManager.SCO_AUDIO_STATE_DISCONNECTED); } } else if (getBluetoothHeadset()) { mScoAudioState = SCO_STATE_DEACTIVATE_REQ; } } else { mScoAudioState = SCO_STATE_INACTIVE; broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED); } } } } } private void checkScoAudioState() { if (mBluetoothHeadset != null && mBluetoothHeadsetDevice != null && mScoAudioState == SCO_STATE_INACTIVE && mBluetoothHeadset.getAudioState(mBluetoothHeadsetDevice) != BluetoothHeadset.STATE_AUDIO_DISCONNECTED) { mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL; } } private ScoClient getScoClient(IBinder cb, boolean create) { synchronized(mScoClients) { ScoClient client = null; int size = mScoClients.size(); for (int i = 0; i < size; i++) { client = mScoClients.get(i); if (client.getBinder() == cb) return client; } if (create) { client = new ScoClient(cb); mScoClients.add(client); } return client; } } public void clearAllScoClients(int exceptPid, boolean stopSco) { synchronized(mScoClients) { ScoClient savedClient = null; int size = mScoClients.size(); for (int i = 0; i < size; i++) { ScoClient cl = mScoClients.get(i); if (cl.getPid() != exceptPid) { cl.clearCount(stopSco); } else { savedClient = cl; } } mScoClients.clear(); if (savedClient != null) { mScoClients.add(savedClient); } } } private boolean getBluetoothHeadset() { boolean result = false; BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { result = adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener, BluetoothProfile.HEADSET); } // If we could not get a bluetooth headset proxy, send a failure message // without delay to reset the SCO audio state and clear SCO clients. // If we could get a proxy, send a delayed failure message that will reset our state // in case we don't receive onServiceConnected(). sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, SENDMSG_REPLACE, 0, 0, null, result ? BT_HEADSET_CNCT_TIMEOUT_MS : 0); return result; } private void disconnectBluetoothSco(int exceptPid) { synchronized(mScoClients) { checkScoAudioState(); if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL || mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) { if (mBluetoothHeadsetDevice != null) { if (mBluetoothHeadset != null) { if (!mBluetoothHeadset.stopVoiceRecognition( mBluetoothHeadsetDevice)) { sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, SENDMSG_REPLACE, 0, 0, null, 0); } } else if (mScoAudioState == SCO_STATE_ACTIVE_EXTERNAL && getBluetoothHeadset()) { mScoAudioState = SCO_STATE_DEACTIVATE_EXT_REQ; } } } else { clearAllScoClients(exceptPid, true); } } } private void resetBluetoothSco() { synchronized(mScoClients) { clearAllScoClients(0, false); mScoAudioState = SCO_STATE_INACTIVE; broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_DISCONNECTED); } } private void broadcastScoConnectionState(int state) { if (state != mScoConnectionState) { Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED); newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state); newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE, mScoConnectionState); mContext.sendStickyBroadcast(newIntent); mScoConnectionState = state; } } private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener = new BluetoothProfile.ServiceListener() { public void onServiceConnected(int profile, BluetoothProfile proxy) { BluetoothDevice btDevice; List<BluetoothDevice> deviceList; switch(profile) { case BluetoothProfile.A2DP: BluetoothA2dp a2dp = (BluetoothA2dp) proxy; deviceList = a2dp.getConnectedDevices(); if (deviceList.size() > 0) { btDevice = deviceList.get(0); if (!noDelayInATwoDP){ synchronized (mConnectedDevices) { int state = a2dp.getConnectionState(btDevice); int delay = checkSendBecomingNoisyIntent( AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0); queueMsgUnderWakeLock(mAudioHandler, MSG_SET_A2DP_CONNECTION_STATE, state, 0, btDevice, delay); } } else { onSetA2dpConnectionState(btDevice, a2dp.getConnectionState(btDevice)); } } break; case BluetoothProfile.HEADSET: synchronized (mScoClients) { // Discard timeout message mAudioHandler.removeMessages(MSG_BT_HEADSET_CNCT_FAILED); mBluetoothHeadset = (BluetoothHeadset) proxy; deviceList = mBluetoothHeadset.getConnectedDevices(); if (deviceList.size() > 0) { mBluetoothHeadsetDevice = deviceList.get(0); } else { mBluetoothHeadsetDevice = null; } // Refresh SCO audio state checkScoAudioState(); // Continue pending action if any if (mScoAudioState == SCO_STATE_ACTIVATE_REQ || mScoAudioState == SCO_STATE_DEACTIVATE_REQ || mScoAudioState == SCO_STATE_DEACTIVATE_EXT_REQ) { boolean status = false; if (mBluetoothHeadsetDevice != null) { switch (mScoAudioState) { case SCO_STATE_ACTIVATE_REQ: mScoAudioState = SCO_STATE_ACTIVE_INTERNAL; status = mBluetoothHeadset.startScoUsingVirtualVoiceCall( mBluetoothHeadsetDevice); break; case SCO_STATE_DEACTIVATE_REQ: status = mBluetoothHeadset.stopScoUsingVirtualVoiceCall( mBluetoothHeadsetDevice); break; case SCO_STATE_DEACTIVATE_EXT_REQ: status = mBluetoothHeadset.stopVoiceRecognition( mBluetoothHeadsetDevice); } } if (!status) { sendMsg(mAudioHandler, MSG_BT_HEADSET_CNCT_FAILED, SENDMSG_REPLACE, 0, 0, null, 0); } } } break; default: break; } } public void onServiceDisconnected(int profile) { switch(profile) { case BluetoothProfile.A2DP: synchronized (mConnectedDevices) { if (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)) { makeA2dpDeviceUnavailableNow( mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP)); } } break; case BluetoothProfile.HEADSET: synchronized (mScoClients) { mBluetoothHeadset = null; } break; default: break; } } }; /////////////////////////////////////////////////////////////////////////// // Internal methods /////////////////////////////////////////////////////////////////////////// /** * Checks if the adjustment should change ringer mode instead of just * adjusting volume. If so, this will set the proper ringer mode and volume * indices on the stream states. */ private boolean checkForRingerModeChange(int oldIndex, int direction, int step) { boolean adjustVolumeIndex = true; int ringerMode = getRingerMode(); switch (ringerMode) { case RINGER_MODE_NORMAL: if (direction == AudioManager.ADJUST_LOWER) { if (mHasVibrator) { // "step" is the delta in internal index units corresponding to a // change of 1 in UI index units. // Because of rounding when rescaling from one stream index range to its alias // index range, we cannot simply test oldIndex == step: // (step <= oldIndex < 2 * step) is equivalent to: (old UI index == 1) if (step <= oldIndex && oldIndex < 2 * step) { ringerMode = RINGER_MODE_VIBRATE; } } else { // (oldIndex < step) is equivalent to (old UI index == 0) if ((oldIndex < step) && mPrevVolDirection != AudioManager.ADJUST_LOWER) { ringerMode = RINGER_MODE_SILENT; } } } break; case RINGER_MODE_VIBRATE: if (!mHasVibrator) { Log.e(TAG, "checkForRingerModeChange() current ringer mode is vibrate" + "but no vibrator is present"); break; } if ((direction == AudioManager.ADJUST_LOWER)) { if (mPrevVolDirection != AudioManager.ADJUST_LOWER) { ringerMode = RINGER_MODE_SILENT; } } else if (direction == AudioManager.ADJUST_RAISE) { ringerMode = RINGER_MODE_NORMAL; } adjustVolumeIndex = false; break; case RINGER_MODE_SILENT: if (direction == AudioManager.ADJUST_RAISE) { if (mHasVibrator) { ringerMode = RINGER_MODE_VIBRATE; } else { ringerMode = RINGER_MODE_NORMAL; } } adjustVolumeIndex = false; break; default: Log.e(TAG, "checkForRingerModeChange() wrong ringer mode: "+ringerMode); break; } setRingerMode(ringerMode); mPrevVolDirection = direction; return adjustVolumeIndex; } public boolean isStreamAffectedByRingerMode(int streamType) { return (mRingerModeAffectedStreams & (1 << streamType)) != 0; } private boolean isStreamMutedByRingerMode(int streamType) { return (mRingerModeMutedStreams & (1 << streamType)) != 0; } public boolean isStreamAffectedByMute(int streamType) { return (mMuteAffectedStreams & (1 << streamType)) != 0; } private void ensureValidDirection(int direction) { if (direction < AudioManager.ADJUST_LOWER || direction > AudioManager.ADJUST_RAISE) { throw new IllegalArgumentException("Bad direction " + direction); } } private void ensureValidSteps(int steps) { if (Math.abs(steps) > MAX_BATCH_VOLUME_ADJUST_STEPS) { throw new IllegalArgumentException("Bad volume adjust steps " + steps); } } private void ensureValidStreamType(int streamType) { if (streamType < 0 || streamType >= mStreamStates.length) { throw new IllegalArgumentException("Bad stream type " + streamType); } } private boolean isInCommunication() { boolean isOffhook = false; if (mVoiceCapable) { try { ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); if (phone != null) isOffhook = phone.isOffhook(); } catch (RemoteException e) { Log.w(TAG, "Couldn't connect to phone service", e); } } return (isOffhook || getMode() == AudioManager.MODE_IN_COMMUNICATION); } private int getActiveStreamType(int suggestedStreamType) { if (mVoiceCapable) { if (isInCommunication()) { if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO..."); return AudioSystem.STREAM_BLUETOOTH_SCO; } else { // Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL..."); return AudioSystem.STREAM_VOICE_CALL; } } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { // Having the suggested stream be USE_DEFAULT_STREAM_TYPE is how remote control // volume can have priority over STREAM_MUSIC if (checkUpdateRemoteStateIfActive(AudioSystem.STREAM_MUSIC)) { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_REMOTE_MUSIC"); return STREAM_REMOTE_MUSIC; } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active"); return AudioSystem.STREAM_MUSIC; } else { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_RING b/c default"); return AudioSystem.STREAM_RING; } } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0)) { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_MUSIC stream active"); return AudioSystem.STREAM_MUSIC; } else { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); return suggestedStreamType; } } else { if (isInCommunication()) { if (AudioSystem.getForceUse(AudioSystem.FOR_COMMUNICATION) == AudioSystem.FORCE_BT_SCO) { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_BLUETOOTH_SCO"); return AudioSystem.STREAM_BLUETOOTH_SCO; } else { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_VOICE_CALL"); return AudioSystem.STREAM_VOICE_CALL; } } else if (AudioSystem.isStreamActive(AudioSystem.STREAM_NOTIFICATION, NOTIFICATION_VOLUME_DELAY_MS) || AudioSystem.isStreamActive(AudioSystem.STREAM_RING, NOTIFICATION_VOLUME_DELAY_MS)) { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_NOTIFICATION"); return AudioSystem.STREAM_NOTIFICATION; } else if (suggestedStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { if (checkUpdateRemoteStateIfActive(AudioSystem.STREAM_MUSIC)) { // Having the suggested stream be USE_DEFAULT_STREAM_TYPE is how remote control // volume can have priority over STREAM_MUSIC if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Forcing STREAM_REMOTE_MUSIC"); return STREAM_REMOTE_MUSIC; } else { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: using STREAM_MUSIC as default"); return AudioSystem.STREAM_MUSIC; } } else { if (DEBUG_VOL) Log.v(TAG, "getActiveStreamType: Returning suggested type " + suggestedStreamType); return suggestedStreamType; } } } private void broadcastRingerMode(int ringerMode) { // Send sticky broadcast Intent broadcast = new Intent(AudioManager.RINGER_MODE_CHANGED_ACTION); broadcast.putExtra(AudioManager.EXTRA_RINGER_MODE, ringerMode); broadcast.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | Intent.FLAG_RECEIVER_REPLACE_PENDING); long origCallerIdentityToken = Binder.clearCallingIdentity(); mContext.sendStickyBroadcast(broadcast); Binder.restoreCallingIdentity(origCallerIdentityToken); } private void broadcastVibrateSetting(int vibrateType) { // Send broadcast if (ActivityManagerNative.isSystemReady()) { Intent broadcast = new Intent(AudioManager.VIBRATE_SETTING_CHANGED_ACTION); broadcast.putExtra(AudioManager.EXTRA_VIBRATE_TYPE, vibrateType); broadcast.putExtra(AudioManager.EXTRA_VIBRATE_SETTING, getVibrateSetting(vibrateType)); mContext.sendBroadcast(broadcast); } } // Message helper methods /** * Queue a message on the given handler's message queue, after acquiring the service wake lock. * Note that the wake lock needs to be released after the message has been handled. */ private void queueMsgUnderWakeLock(Handler handler, int msg, int arg1, int arg2, Object obj, int delay) { mMediaEventWakeLock.acquire(); sendMsg(handler, msg, SENDMSG_QUEUE, arg1, arg2, obj, delay); } private static void sendMsg(Handler handler, int msg, int existingMsgPolicy, int arg1, int arg2, Object obj, int delay) { if (existingMsgPolicy == SENDMSG_REPLACE) { handler.removeMessages(msg); } else if (existingMsgPolicy == SENDMSG_NOOP && handler.hasMessages(msg)) { return; } handler.sendMessageDelayed(handler.obtainMessage(msg, arg1, arg2, obj), delay); } boolean checkAudioSettingsPermission(String method) { if (mContext.checkCallingOrSelfPermission("android.permission.MODIFY_AUDIO_SETTINGS") == PackageManager.PERMISSION_GRANTED) { return true; } String msg = "Audio Settings Permission Denial: " + method + " from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid(); Log.w(TAG, msg); return false; } private int getDeviceForStream(int stream) { int device = AudioSystem.getDevicesForStream(stream); if ((device & (device - 1)) != 0) { // Multiple device selection is either: // - speaker + one other device: give priority to speaker in this case. // - one A2DP device + another device: happens with duplicated output. In this case // retain the device on the A2DP output as the other must not correspond to an active // selection if not the speaker. if ((device & AudioSystem.DEVICE_OUT_SPEAKER) != 0) { device = AudioSystem.DEVICE_OUT_SPEAKER; } else { device &= AudioSystem.DEVICE_OUT_ALL_A2DP; } } return device; } public void setWiredDeviceConnectionState(int device, int state, String name) { synchronized (mConnectedDevices) { int delay = checkSendBecomingNoisyIntent(device, state); queueMsgUnderWakeLock(mAudioHandler, MSG_SET_WIRED_DEVICE_CONNECTION_STATE, device, state, name, delay); } } public int setBluetoothA2dpDeviceConnectionState(BluetoothDevice device, int state) { int delay; if(!noDelayInATwoDP) { synchronized (mConnectedDevices) { delay = checkSendBecomingNoisyIntent(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, (state == BluetoothA2dp.STATE_CONNECTED) ? 1 : 0); queueMsgUnderWakeLock(mAudioHandler, MSG_SET_A2DP_CONNECTION_STATE, state, 0, device, delay); } } else { delay = 0; } return delay; } /////////////////////////////////////////////////////////////////////////// // Inner classes /////////////////////////////////////////////////////////////////////////// public class VolumeStreamState { private final int mStreamType; private String mVolumeIndexSettingName; private String mLastAudibleVolumeIndexSettingName; private int mIndexMax; private final ConcurrentHashMap<Integer, Integer> mIndex = new ConcurrentHashMap<Integer, Integer>(8, 0.75f, 4); private final ConcurrentHashMap<Integer, Integer> mLastAudibleIndex = new ConcurrentHashMap<Integer, Integer>(8, 0.75f, 4); private ArrayList<VolumeDeathHandler> mDeathHandlers; //handles mute/solo clients death private VolumeStreamState(String settingName, int streamType) { mVolumeIndexSettingName = settingName; mLastAudibleVolumeIndexSettingName = settingName + System.APPEND_FOR_LAST_AUDIBLE; mStreamType = streamType; mIndexMax = MAX_STREAM_VOLUME[streamType]; AudioSystem.initStreamVolume(streamType, 0, mIndexMax); mIndexMax *= 10; readSettings(); mDeathHandlers = new ArrayList<VolumeDeathHandler>(); } public String getSettingNameForDevice(boolean lastAudible, int device) { String name = lastAudible ? mLastAudibleVolumeIndexSettingName : mVolumeIndexSettingName; String suffix = AudioSystem.getDeviceName(device); if (suffix.isEmpty()) { return name; } return name + "_" + suffix; } public synchronized void readSettings() { int remainingDevices = AudioSystem.DEVICE_OUT_ALL; for (int i = 0; remainingDevices != 0; i++) { int device = (1 << i); if ((device & remainingDevices) == 0) { continue; } remainingDevices &= ~device; // retrieve current volume for device String name = getSettingNameForDevice(false /* lastAudible */, device); // if no volume stored for current stream and device, use default volume if default // device, continue otherwise int defaultIndex = (device == AudioSystem.DEVICE_OUT_DEFAULT) ? AudioManager.DEFAULT_STREAM_VOLUME[mStreamType] : -1; int index = Settings.System.getInt(mContentResolver, name, defaultIndex); if (index == -1) { continue; } // retrieve last audible volume for device name = getSettingNameForDevice(true /* lastAudible */, device); // use stored last audible index if present, otherwise use current index if not 0 // or default index defaultIndex = (index > 0) ? index : AudioManager.DEFAULT_STREAM_VOLUME[mStreamType]; int lastAudibleIndex = Settings.System.getInt(mContentResolver, name, defaultIndex); // a last audible index of 0 should never be stored for ring and notification // streams on phones (voice capable devices). // same for system stream on phones and tablets if ((lastAudibleIndex == 0) && ((mVoiceCapable && (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_RING)) || (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_SYSTEM))) { lastAudibleIndex = AudioManager.DEFAULT_STREAM_VOLUME[mStreamType]; // Correct the data base sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, SENDMSG_QUEUE, PERSIST_LAST_AUDIBLE, device, this, PERSIST_DELAY); } mLastAudibleIndex.put(device, getValidIndex(10 * lastAudibleIndex)); // the initial index should never be 0 for ring and notification streams on phones // (voice capable devices) if not in silent or vibrate mode. // same for system stream on phones and tablets if ((index == 0) && (mRingerMode == AudioManager.RINGER_MODE_NORMAL) && ((mVoiceCapable && (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_RING)) || (mStreamVolumeAlias[mStreamType] == AudioSystem.STREAM_SYSTEM))) { index = lastAudibleIndex; // Correct the data base sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, SENDMSG_QUEUE, PERSIST_CURRENT, device, this, PERSIST_DELAY); } mIndex.put(device, getValidIndex(10 * index)); } } public void applyDeviceVolume(int device) { AudioSystem.setStreamVolumeIndex(mStreamType, (getIndex(device, false /* lastAudible */) + 5)/10, device); } public synchronized void applyAllVolumes() { // apply default volume first: by convention this will reset all // devices volumes in audio policy manager to the supplied value AudioSystem.setStreamVolumeIndex(mStreamType, (getIndex(AudioSystem.DEVICE_OUT_DEFAULT, false /* lastAudible */) + 5)/10, AudioSystem.DEVICE_OUT_DEFAULT); // then apply device specific volumes Set set = mIndex.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); int device = ((Integer)entry.getKey()).intValue(); if (device != AudioSystem.DEVICE_OUT_DEFAULT) { AudioSystem.setStreamVolumeIndex(mStreamType, ((Integer)entry.getValue() + 5)/10, device); } } } public boolean adjustIndex(int deltaIndex, int device) { return setIndex(getIndex(device, false /* lastAudible */) + deltaIndex, device, true /* lastAudible */); } public synchronized boolean setIndex(int index, int device, boolean lastAudible) { int oldIndex = getIndex(device, false /* lastAudible */); index = getValidIndex(index); mIndex.put(device, getValidIndex(index)); if (oldIndex != index) { if (lastAudible) { mLastAudibleIndex.put(device, index); } // Apply change to all streams using this one as alias // if changing volume of current device, also change volume of current // device on aliased stream boolean currentDevice = (device == getDeviceForStream(mStreamType)); int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (streamType != mStreamType && mStreamVolumeAlias[streamType] == mStreamType) { int scaledIndex = rescaleIndex(index, mStreamType, streamType); mStreamStates[streamType].setIndex(scaledIndex, device, lastAudible); if (currentDevice) { mStreamStates[streamType].setIndex(scaledIndex, getDeviceForStream(streamType), lastAudible); } } } return true; } else { return false; } } public synchronized int getIndex(int device, boolean lastAudible) { ConcurrentHashMap <Integer, Integer> indexes; if (lastAudible) { indexes = mLastAudibleIndex; } else { indexes = mIndex; } Integer index = indexes.get(device); if (index == null) { // there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT index = indexes.get(AudioSystem.DEVICE_OUT_DEFAULT); } return index.intValue(); } public synchronized void setLastAudibleIndex(int index, int device) { // Apply change to all streams using this one as alias // if changing volume of current device, also change volume of current // device on aliased stream boolean currentDevice = (device == getDeviceForStream(mStreamType)); int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (streamType != mStreamType && mStreamVolumeAlias[streamType] == mStreamType) { int scaledIndex = rescaleIndex(index, mStreamType, streamType); mStreamStates[streamType].setLastAudibleIndex(scaledIndex, device); if (currentDevice) { mStreamStates[streamType].setLastAudibleIndex(scaledIndex, getDeviceForStream(streamType)); } } } mLastAudibleIndex.put(device, getValidIndex(index)); } public synchronized void adjustLastAudibleIndex(int deltaIndex, int device) { setLastAudibleIndex(getIndex(device, true /* lastAudible */) + deltaIndex, device); } public int getMaxIndex() { return mIndexMax; } // only called by setAllIndexes() which is already synchronized public ConcurrentHashMap <Integer, Integer> getAllIndexes(boolean lastAudible) { if (lastAudible) { return mLastAudibleIndex; } else { return mIndex; } } public synchronized void setAllIndexes(VolumeStreamState srcStream, boolean lastAudible) { ConcurrentHashMap <Integer, Integer> indexes = srcStream.getAllIndexes(lastAudible); Set set = indexes.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); int device = ((Integer)entry.getKey()).intValue(); int index = ((Integer)entry.getValue()).intValue(); index = rescaleIndex(index, srcStream.getStreamType(), mStreamType); setIndex(index, device, lastAudible); } } public synchronized void mute(IBinder cb, boolean state) { VolumeDeathHandler handler = getDeathHandler(cb, state); if (handler == null) { Log.e(TAG, "Could not get client death handler for stream: "+mStreamType); return; } handler.mute(state); } public int getStreamType() { return mStreamType; } private int getValidIndex(int index) { if (index < 0) { return 0; } else if (index > mIndexMax) { return mIndexMax; } return index; } private class VolumeDeathHandler implements IBinder.DeathRecipient { private IBinder mICallback; // To be notified of client's death private int mMuteCount; // Number of active mutes for this client VolumeDeathHandler(IBinder cb) { mICallback = cb; } // must be called while synchronized on parent VolumeStreamState public void mute(boolean state) { if (state) { if (mMuteCount == 0) { // Register for client death notification try { // mICallback can be 0 if muted by AudioService if (mICallback != null) { mICallback.linkToDeath(this, 0); } mDeathHandlers.add(this); // If the stream is not yet muted by any client, set level to 0 if (muteCount() == 0) { Set set = mIndex.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); int device = ((Integer)entry.getKey()).intValue(); setIndex(0, device, false /* lastAudible */); } sendMsg(mAudioHandler, MSG_SET_ALL_VOLUMES, SENDMSG_QUEUE, 0, 0, VolumeStreamState.this, 0); } } catch (RemoteException e) { // Client has died! binderDied(); return; } } else { Log.w(TAG, "stream: "+mStreamType+" was already muted by this client"); } mMuteCount++; } else { if (mMuteCount == 0) { Log.e(TAG, "unexpected unmute for stream: "+mStreamType); } else { mMuteCount--; if (mMuteCount == 0) { // Unregister from client death notification mDeathHandlers.remove(this); // mICallback can be 0 if muted by AudioService if (mICallback != null) { mICallback.unlinkToDeath(this, 0); } if (muteCount() == 0) { // If the stream is not muted any more, restore its volume if // ringer mode allows it if (!isStreamAffectedByRingerMode(mStreamType) || mRingerMode == AudioManager.RINGER_MODE_NORMAL) { Set set = mIndex.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); int device = ((Integer)entry.getKey()).intValue(); setIndex(getIndex(device, true /* lastAudible */), device, false /* lastAudible */); } sendMsg(mAudioHandler, MSG_SET_ALL_VOLUMES, SENDMSG_QUEUE, 0, 0, VolumeStreamState.this, 0); } } } } } } public void binderDied() { Log.w(TAG, "Volume service client died for stream: "+mStreamType); if (mMuteCount != 0) { // Reset all active mute requests from this client. mMuteCount = 1; mute(false); } } } private synchronized int muteCount() { int count = 0; int size = mDeathHandlers.size(); for (int i = 0; i < size; i++) { count += mDeathHandlers.get(i).mMuteCount; } return count; } // only called by mute() which is already synchronized private VolumeDeathHandler getDeathHandler(IBinder cb, boolean state) { VolumeDeathHandler handler; int size = mDeathHandlers.size(); for (int i = 0; i < size; i++) { handler = mDeathHandlers.get(i); if (cb == handler.mICallback) { return handler; } } // If this is the first mute request for this client, create a new // client death handler. Otherwise, it is an out of sequence unmute request. if (state) { handler = new VolumeDeathHandler(cb); } else { Log.w(TAG, "stream was not muted by this client"); handler = null; } return handler; } private void dump(PrintWriter pw) { pw.print(" Current: "); Set set = mIndex.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); pw.print(Integer.toHexString(((Integer)entry.getKey()).intValue()) + ": " + ((((Integer)entry.getValue()).intValue() + 5) / 10)+", "); } pw.print("\n Last audible: "); set = mLastAudibleIndex.entrySet(); i = set.iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry)i.next(); pw.print(Integer.toHexString(((Integer)entry.getKey()).intValue()) + ": " + ((((Integer)entry.getValue()).intValue() + 5) / 10)+", "); } } } /** Thread that handles native AudioSystem control. */ private class AudioSystemThread extends Thread { AudioSystemThread() { super("AudioService"); } @Override public void run() { // Set this thread up so the handler will work on it Looper.prepare(); synchronized(AudioService.this) { mAudioHandler = new AudioHandler(); // Notify that the handler has been created AudioService.this.notify(); } // Listen for volume change requests that are set by VolumePanel Looper.loop(); } } /** Handles internal volume messages in separate volume thread. */ private class AudioHandler extends Handler { private void setDeviceVolume(VolumeStreamState streamState, int device) { // Apply volume streamState.applyDeviceVolume(device); // Apply change to all streams using this one as alias int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (streamType != streamState.mStreamType && mStreamVolumeAlias[streamType] == streamState.mStreamType) { mStreamStates[streamType].applyDeviceVolume(getDeviceForStream(streamType)); } } // Post a persist volume msg sendMsg(mAudioHandler, MSG_PERSIST_VOLUME, SENDMSG_QUEUE, PERSIST_CURRENT|PERSIST_LAST_AUDIBLE, device, streamState, PERSIST_DELAY); } private void setAllVolumes(VolumeStreamState streamState) { // Apply volume streamState.applyAllVolumes(); // Apply change to all streams using this one as alias int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { if (streamType != streamState.mStreamType && mStreamVolumeAlias[streamType] == streamState.mStreamType) { mStreamStates[streamType].applyAllVolumes(); } } } private void persistVolume(VolumeStreamState streamState, int persistType, int device) { if ((persistType & PERSIST_CURRENT) != 0) { System.putInt(mContentResolver, streamState.getSettingNameForDevice(false /* lastAudible */, device), (streamState.getIndex(device, false /* lastAudible */) + 5)/ 10); } if ((persistType & PERSIST_LAST_AUDIBLE) != 0) { System.putInt(mContentResolver, streamState.getSettingNameForDevice(true /* lastAudible */, device), (streamState.getIndex(device, true /* lastAudible */) + 5) / 10); } } private void persistRingerMode(int ringerMode) { System.putInt(mContentResolver, System.MODE_RINGER, ringerMode); } private void playSoundEffect(int effectType, int volume) { synchronized (mSoundEffectsLock) { if (mSoundPool == null) { return; } float volFloat; // use default if volume is not specified by caller if (volume < 0) { volFloat = (float)Math.pow(10, SOUND_EFFECT_VOLUME_DB/20); } else { volFloat = (float) volume / 1000.0f; } if (SOUND_EFFECT_FILES_MAP[effectType][1] > 0) { mSoundPool.play(SOUND_EFFECT_FILES_MAP[effectType][1], volFloat, volFloat, 0, 0, 1.0f); } else { MediaPlayer mediaPlayer = new MediaPlayer(); try { String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]]; mediaPlayer.setDataSource(filePath); mediaPlayer.setAudioStreamType(AudioSystem.STREAM_SYSTEM); mediaPlayer.prepare(); mediaPlayer.setVolume(volFloat, volFloat); mediaPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { cleanupPlayer(mp); } }); mediaPlayer.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { cleanupPlayer(mp); return true; } }); mediaPlayer.start(); } catch (IOException ex) { Log.w(TAG, "MediaPlayer IOException: "+ex); } catch (IllegalArgumentException ex) { Log.w(TAG, "MediaPlayer IllegalArgumentException: "+ex); } catch (IllegalStateException ex) { Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); } } } } private void onHandlePersistMediaButtonReceiver(ComponentName receiver) { Settings.System.putString(mContentResolver, Settings.System.MEDIA_BUTTON_RECEIVER, receiver == null ? "" : receiver.flattenToString()); } private void cleanupPlayer(MediaPlayer mp) { if (mp != null) { try { mp.stop(); mp.release(); } catch (IllegalStateException ex) { Log.w(TAG, "MediaPlayer IllegalStateException: "+ex); } } } private void setForceUse(int usage, int config) { AudioSystem.setForceUse(usage, config); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SET_DEVICE_VOLUME: setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1); break; case MSG_SET_ALL_VOLUMES: setAllVolumes((VolumeStreamState) msg.obj); break; case MSG_PERSIST_VOLUME: persistVolume((VolumeStreamState) msg.obj, msg.arg1, msg.arg2); break; case MSG_PERSIST_MASTER_VOLUME: Settings.System.putFloat(mContentResolver, Settings.System.VOLUME_MASTER, (float)msg.arg1 / (float)1000.0); break; case MSG_PERSIST_MASTER_VOLUME_MUTE: Settings.System.putInt(mContentResolver, Settings.System.VOLUME_MASTER_MUTE, msg.arg1); break; case MSG_PERSIST_RINGER_MODE: // note that the value persisted is the current ringer mode, not the // value of ringer mode as of the time the request was made to persist persistRingerMode(getRingerMode()); break; case MSG_MEDIA_SERVER_DIED: if (!mMediaServerOk) { Log.e(TAG, "Media server died."); // Force creation of new IAudioFlinger interface so that we are notified // when new media_server process is back to life. AudioSystem.setErrorCallback(mAudioSystemCallback); sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SENDMSG_NOOP, 0, 0, null, 500); } break; case MSG_MEDIA_SERVER_STARTED: Log.e(TAG, "Media server started."); // indicate to audio HAL that we start the reconfiguration phase after a media // server crash // Note that MSG_MEDIA_SERVER_STARTED message is only received when the media server // process restarts after a crash, not the first time it is started. AudioSystem.setParameters("restarting=true"); // Restore device connection states synchronized (mConnectedDevices) { Set set = mConnectedDevices.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry device = (Map.Entry)i.next(); AudioSystem.setDeviceConnectionState( ((Integer)device.getKey()).intValue(), AudioSystem.DEVICE_STATE_AVAILABLE, (String)device.getValue()); } } // Restore call state AudioSystem.setPhoneState(mMode); // Restore forced usage for communcations and record AudioSystem.setForceUse(AudioSystem.FOR_COMMUNICATION, mForcedUseForComm); AudioSystem.setForceUse(AudioSystem.FOR_RECORD, mForcedUseForComm); // Restore stream volumes int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) { VolumeStreamState streamState = mStreamStates[streamType]; AudioSystem.initStreamVolume(streamType, 0, (streamState.mIndexMax + 5) / 10); streamState.applyAllVolumes(); } // Restore ringer mode setRingerModeInt(getRingerMode(), false); // Restore master volume restoreMasterVolume(); // Reset device orientation (if monitored for this device) if (SystemProperties.getBoolean("ro.audio.monitorOrientation", false)) { setOrientationForAudioSystem(); } synchronized (mBluetoothA2dpEnabledLock) { AudioSystem.setForceUse(AudioSystem.FOR_MEDIA, mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP); } // indicate the end of reconfiguration phase to audio HAL AudioSystem.setParameters("restarting=false"); break; case MSG_LOAD_SOUND_EFFECTS: loadSoundEffects(); break; case MSG_PLAY_SOUND_EFFECT: playSoundEffect(msg.arg1, msg.arg2); break; case MSG_BTA2DP_DOCK_TIMEOUT: // msg.obj == address of BTA2DP device synchronized (mConnectedDevices) { makeA2dpDeviceUnavailableNow( (String) msg.obj ); } break; case MSG_SET_FORCE_USE: setForceUse(msg.arg1, msg.arg2); break; case MSG_PERSIST_MEDIABUTTONRECEIVER: onHandlePersistMediaButtonReceiver( (ComponentName) msg.obj ); break; case MSG_RCDISPLAY_CLEAR: onRcDisplayClear(); break; case MSG_RCDISPLAY_UPDATE: // msg.obj is guaranteed to be non null onRcDisplayUpdate( (RemoteControlStackEntry) msg.obj, msg.arg1); break; case MSG_BT_HEADSET_CNCT_FAILED: resetBluetoothSco(); break; case MSG_SET_WIRED_DEVICE_CONNECTION_STATE: onSetWiredDeviceConnectionState(msg.arg1, msg.arg2, (String)msg.obj); mMediaEventWakeLock.release(); break; case MSG_SET_A2DP_CONNECTION_STATE: onSetA2dpConnectionState((BluetoothDevice)msg.obj, msg.arg1); mMediaEventWakeLock.release(); break; case MSG_REPORT_NEW_ROUTES: { int N = mRoutesObservers.beginBroadcast(); if (N > 0) { AudioRoutesInfo routes; synchronized (mCurAudioRoutes) { routes = new AudioRoutesInfo(mCurAudioRoutes); } while (N > 0) { N--; IAudioRoutesObserver obs = mRoutesObservers.getBroadcastItem(N); try { obs.dispatchAudioRoutesChanged(routes); } catch (RemoteException e) { } } } mRoutesObservers.finishBroadcast(); break; } case MSG_REEVALUATE_REMOTE: onReevaluateRemote(); break; case MSG_RCC_NEW_PLAYBACK_INFO: onNewPlaybackInfoForRcc(msg.arg1 /* rccId */, msg.arg2 /* key */, ((Integer)msg.obj).intValue() /* value */); break; case MSG_RCC_NEW_VOLUME_OBS: onRegisterVolumeObserverForRcc(msg.arg1 /* rccId */, (IRemoteVolumeObserver)msg.obj /* rvo */); break; } } } private class SettingsObserver extends ContentObserver { SettingsObserver() { super(new Handler()); mContentResolver.registerContentObserver(Settings.System.getUriFor( Settings.System.MODE_RINGER_STREAMS_AFFECTED), false, this); mContentResolver.registerContentObserver(Settings.System.getUriFor( Settings.System.VOLUME_LINK_NOTIFICATION), false, this); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); // FIXME This synchronized is not necessary if mSettingsLock only protects mRingerMode. // However there appear to be some missing locks around mRingerModeMutedStreams // and mRingerModeAffectedStreams, so will leave this synchronized for now. // mRingerModeMutedStreams and mMuteAffectedStreams are safe (only accessed once). synchronized (mSettingsLock) { int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver, Settings.System.MODE_RINGER_STREAMS_AFFECTED, ((1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_NOTIFICATION)| (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED))); if (mVoiceCapable) { ringerModeAffectedStreams &= ~(1 << AudioSystem.STREAM_MUSIC); } else { ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC); } if (ringerModeAffectedStreams != mRingerModeAffectedStreams) { /* * Ensure all stream types that should be affected by ringer mode * are in the proper state. */ mRingerModeAffectedStreams = ringerModeAffectedStreams; setRingerModeInt(getRingerMode(), false); } mLinkNotificationWithVolume = Settings.System.getInt(mContentResolver, Settings.System.VOLUME_LINK_NOTIFICATION, 1) == 1; if (mLinkNotificationWithVolume) { mStreamVolumeAlias[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_RING; } else { mStreamVolumeAlias[AudioSystem.STREAM_NOTIFICATION] = AudioSystem.STREAM_NOTIFICATION; } } } } // must be called synchronized on mConnectedDevices private void makeA2dpDeviceAvailable(String address) { // enable A2DP before notifying A2DP connection to avoid unecessary processing in // audio policy manager setBluetoothA2dpOnInt(true); AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, AudioSystem.DEVICE_STATE_AVAILABLE, address); // Reset A2DP suspend state each time a new sink is connected AudioSystem.setParameters("A2dpSuspended=false"); mConnectedDevices.put( new Integer(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP), address); } private void sendBecomingNoisyIntent() { mContext.sendBroadcast(new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY)); } // must be called synchronized on mConnectedDevices private void makeA2dpDeviceUnavailableNow(String address) { if (noDelayInATwoDP) sendBecomingNoisyIntent(); AudioSystem.setDeviceConnectionState(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP, AudioSystem.DEVICE_STATE_UNAVAILABLE, address); mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); } // must be called synchronized on mConnectedDevices private void makeA2dpDeviceUnavailableLater(String address) { // prevent any activity on the A2DP audio output to avoid unwanted // reconnection of the sink. AudioSystem.setParameters("A2dpSuspended=true"); // the device will be made unavailable later, so consider it disconnected right away mConnectedDevices.remove(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP); // send the delayed message to make the device unavailable later Message msg = mAudioHandler.obtainMessage(MSG_BTA2DP_DOCK_TIMEOUT, address); mAudioHandler.sendMessageDelayed(msg, BTA2DP_DOCK_TIMEOUT_MILLIS); } // must be called synchronized on mConnectedDevices private void cancelA2dpDeviceTimeout() { mAudioHandler.removeMessages(MSG_BTA2DP_DOCK_TIMEOUT); } // must be called synchronized on mConnectedDevices private boolean hasScheduledA2dpDockTimeout() { return mAudioHandler.hasMessages(MSG_BTA2DP_DOCK_TIMEOUT); } private void onSetA2dpConnectionState(BluetoothDevice btDevice, int state) { if (btDevice == null) { return; } String address = btDevice.getAddress(); if (!BluetoothAdapter.checkBluetoothAddress(address)) { address = ""; } synchronized (mConnectedDevices) { boolean isConnected = (mConnectedDevices.containsKey(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP) && mConnectedDevices.get(AudioSystem.DEVICE_OUT_BLUETOOTH_A2DP).equals(address)); if (isConnected && state != BluetoothProfile.STATE_CONNECTED) { if (btDevice.isBluetoothDock()) { if (state == BluetoothProfile.STATE_DISCONNECTED) { // introduction of a delay for transient disconnections of docks when // power is rapidly turned off/on, this message will be canceled if // we reconnect the dock under a preset delay makeA2dpDeviceUnavailableLater(address); // the next time isConnected is evaluated, it will be false for the dock } } else { makeA2dpDeviceUnavailableNow(address); } synchronized (mCurAudioRoutes) { if (mCurAudioRoutes.mBluetoothName != null) { mCurAudioRoutes.mBluetoothName = null; sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES, SENDMSG_NOOP, 0, 0, null, 0); } } } else if (!isConnected && state == BluetoothProfile.STATE_CONNECTED) { if (btDevice.isBluetoothDock()) { // this could be a reconnection after a transient disconnection cancelA2dpDeviceTimeout(); mDockAddress = address; } else { // this could be a connection of another A2DP device before the timeout of // a dock: cancel the dock timeout, and make the dock unavailable now if(hasScheduledA2dpDockTimeout()) { cancelA2dpDeviceTimeout(); makeA2dpDeviceUnavailableNow(mDockAddress); } } makeA2dpDeviceAvailable(address); synchronized (mCurAudioRoutes) { String name = btDevice.getAliasName(); if (!TextUtils.equals(mCurAudioRoutes.mBluetoothName, name)) { mCurAudioRoutes.mBluetoothName = name; sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES, SENDMSG_NOOP, 0, 0, null, 0); } } } } } private boolean handleDeviceConnection(boolean connected, int device, String params) { synchronized (mConnectedDevices) { boolean isConnected = (mConnectedDevices.containsKey(device) && (params.isEmpty() || mConnectedDevices.get(device).equals(params))); if (isConnected && !connected) { AudioSystem.setDeviceConnectionState(device, AudioSystem.DEVICE_STATE_UNAVAILABLE, mConnectedDevices.get(device)); mConnectedDevices.remove(device); return true; } else if (!isConnected && connected) { AudioSystem.setDeviceConnectionState(device, AudioSystem.DEVICE_STATE_AVAILABLE, params); mConnectedDevices.put(new Integer(device), params); return true; } } return false; } // Devices which removal triggers intent ACTION_AUDIO_BECOMING_NOISY. The intent is only // sent if none of these devices is connected. int mBecomingNoisyIntentDevices = AudioSystem.DEVICE_OUT_WIRED_HEADSET | AudioSystem.DEVICE_OUT_WIRED_HEADPHONE | AudioSystem.DEVICE_OUT_ALL_A2DP; // must be called before removing the device from mConnectedDevices private int checkSendBecomingNoisyIntent(int device, int state) { int delay = 0; if ((state == 0) && ((device & mBecomingNoisyIntentDevices) != 0)) { int devices = 0; for (int dev : mConnectedDevices.keySet()) { if ((dev & mBecomingNoisyIntentDevices) != 0) { devices |= dev; } } if (devices == device) { delay = 1000; sendBecomingNoisyIntent(); } } if (mAudioHandler.hasMessages(MSG_SET_A2DP_CONNECTION_STATE) || mAudioHandler.hasMessages(MSG_SET_WIRED_DEVICE_CONNECTION_STATE)) { delay = 1000; } return delay; } private void sendDeviceConnectionIntent(int device, int state, String name) { Intent intent = new Intent(); intent.putExtra("state", state); intent.putExtra("name", name); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); int connType = 0; if (device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) { connType = AudioRoutesInfo.MAIN_HEADSET; intent.setAction(Intent.ACTION_HEADSET_PLUG); intent.putExtra("microphone", 1); } else if (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE) { connType = AudioRoutesInfo.MAIN_HEADPHONES; intent.setAction(Intent.ACTION_HEADSET_PLUG); intent.putExtra("microphone", 0); } else if (device == AudioSystem.DEVICE_OUT_ANLG_DOCK_HEADSET) { connType = AudioRoutesInfo.MAIN_DOCK_SPEAKERS; intent.setAction(Intent.ACTION_ANALOG_AUDIO_DOCK_PLUG); } else if (device == AudioSystem.DEVICE_OUT_DGTL_DOCK_HEADSET) { connType = AudioRoutesInfo.MAIN_DOCK_SPEAKERS; intent.setAction(Intent.ACTION_DIGITAL_AUDIO_DOCK_PLUG); } else if (device == AudioSystem.DEVICE_OUT_AUX_DIGITAL) { connType = AudioRoutesInfo.MAIN_HDMI; intent.setAction(Intent.ACTION_HDMI_AUDIO_PLUG); } synchronized (mCurAudioRoutes) { if (connType != 0) { int newConn = mCurAudioRoutes.mMainType; if (state != 0) { newConn |= connType; } else { newConn &= ~connType; } if (newConn != mCurAudioRoutes.mMainType) { mCurAudioRoutes.mMainType = newConn; sendMsg(mAudioHandler, MSG_REPORT_NEW_ROUTES, SENDMSG_NOOP, 0, 0, null, 0); } } } ActivityManagerNative.broadcastStickyIntent(intent, null); } private void onSetWiredDeviceConnectionState(int device, int state, String name) { synchronized (mConnectedDevices) { if ((state == 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) || (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE))) { setBluetoothA2dpOnInt(true); } handleDeviceConnection((state == 1), device, ""); if ((state != 0) && ((device == AudioSystem.DEVICE_OUT_WIRED_HEADSET) || (device == AudioSystem.DEVICE_OUT_WIRED_HEADPHONE))) { setBluetoothA2dpOnInt(false); } sendDeviceConnectionIntent(device, state, name); } } /* cache of the address of the last dock the device was connected to */ private String mDockAddress; /** * Receiver for misc intent broadcasts the Phone app cares about. */ private class AudioServiceBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); int device; int state; if (action.equals(Intent.ACTION_DOCK_EVENT)) { int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); int config; switch (dockState) { case Intent.EXTRA_DOCK_STATE_DESK: config = AudioSystem.FORCE_BT_DESK_DOCK; break; case Intent.EXTRA_DOCK_STATE_CAR: config = AudioSystem.FORCE_BT_CAR_DOCK; break; case Intent.EXTRA_DOCK_STATE_LE_DESK: config = AudioSystem.FORCE_ANALOG_DOCK; break; case Intent.EXTRA_DOCK_STATE_HE_DESK: config = AudioSystem.FORCE_DIGITAL_DOCK; break; case Intent.EXTRA_DOCK_STATE_UNDOCKED: default: config = AudioSystem.FORCE_NONE; } AudioSystem.setForceUse(AudioSystem.FOR_DOCK, config); } else if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) && noDelayInATwoDP) { state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED); BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); onSetA2dpConnectionState(btDevice, state); } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) { state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothProfile.STATE_DISCONNECTED); device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO; String address = null; BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (btDevice == null) { return; } address = btDevice.getAddress(); BluetoothClass btClass = btDevice.getBluetoothClass(); if (btClass != null) { switch (btClass.getDeviceClass()) { case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET: case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE: device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_HEADSET; break; case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO: device = AudioSystem.DEVICE_OUT_BLUETOOTH_SCO_CARKIT; break; } } if (!BluetoothAdapter.checkBluetoothAddress(address)) { address = ""; } boolean connected = (state == BluetoothProfile.STATE_CONNECTED); if (handleDeviceConnection(connected, device, address)) { synchronized (mScoClients) { if (connected) { mBluetoothHeadsetDevice = btDevice; } else { mBluetoothHeadsetDevice = null; resetBluetoothSco(); } } } } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { state = intent.getIntExtra("state", 0); if (state == 1) { // Headset plugged in // Avoid connection glitches if (noDelayInATwoDP) { setBluetoothA2dpOnInt(false); } // Media volume restore capping final boolean capVolumeRestore = Settings.System.getInt(mContentResolver, Settings.System.SAFE_HEADSET_VOLUME_RESTORE, 1) == 1; if (capVolumeRestore) { final int volume = getStreamVolume(AudioSystem.STREAM_MUSIC); if (volume > HEADSET_VOLUME_RESTORE_CAP_MUSIC) { setStreamVolume(AudioSystem.STREAM_MUSIC, HEADSET_VOLUME_RESTORE_CAP_MUSIC, 0); } } } else { // Headset disconnected // Avoid disconnection glitches if (noDelayInATwoDP) { setBluetoothA2dpOnInt(true); } } } else if (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) || action.equals(Intent.ACTION_USB_AUDIO_DEVICE_PLUG)) { state = intent.getIntExtra("state", 0); int alsaCard = intent.getIntExtra("card", -1); int alsaDevice = intent.getIntExtra("device", -1); String params = (alsaCard == -1 && alsaDevice == -1 ? "" : "card=" + alsaCard + ";device=" + alsaDevice); device = action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ? AudioSystem.DEVICE_OUT_USB_ACCESSORY : AudioSystem.DEVICE_OUT_USB_DEVICE; Log.v(TAG, "Broadcast Receiver: Got " + (action.equals(Intent.ACTION_USB_AUDIO_ACCESSORY_PLUG) ? "ACTION_USB_AUDIO_ACCESSORY_PLUG" : "ACTION_USB_AUDIO_DEVICE_PLUG") + ", state = " + state + ", card: " + alsaCard + ", device: " + alsaDevice); handleDeviceConnection((state == 1), device, params); } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) { boolean broadcast = false; int scoAudioState = AudioManager.SCO_AUDIO_STATE_ERROR; synchronized (mScoClients) { int btState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); // broadcast intent if the connection was initated by AudioService if (!mScoClients.isEmpty() && (mScoAudioState == SCO_STATE_ACTIVE_INTERNAL || mScoAudioState == SCO_STATE_ACTIVATE_REQ || mScoAudioState == SCO_STATE_DEACTIVATE_REQ)) { broadcast = true; } switch (btState) { case BluetoothHeadset.STATE_AUDIO_CONNECTED: scoAudioState = AudioManager.SCO_AUDIO_STATE_CONNECTED; if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL && mScoAudioState != SCO_STATE_DEACTIVATE_REQ && mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) { mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL; } break; case BluetoothHeadset.STATE_AUDIO_DISCONNECTED: scoAudioState = AudioManager.SCO_AUDIO_STATE_DISCONNECTED; mScoAudioState = SCO_STATE_INACTIVE; clearAllScoClients(0, false); break; case BluetoothHeadset.STATE_AUDIO_CONNECTING: if (mScoAudioState != SCO_STATE_ACTIVE_INTERNAL && mScoAudioState != SCO_STATE_DEACTIVATE_REQ && mScoAudioState != SCO_STATE_DEACTIVATE_EXT_REQ) { mScoAudioState = SCO_STATE_ACTIVE_EXTERNAL; } default: // do not broadcast CONNECTING or invalid state broadcast = false; break; } } if (broadcast) { broadcastScoConnectionState(scoAudioState); //FIXME: this is to maintain compatibility with deprecated intent // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate. Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, scoAudioState); mContext.sendStickyBroadcast(newIntent); } } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { mBootCompleted = true; sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_NOOP, 0, 0, null, 0); mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); mScoConnectionState = AudioManager.SCO_AUDIO_STATE_ERROR; resetBluetoothSco(); getBluetoothHeadset(); //FIXME: this is to maintain compatibility with deprecated intent // AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED. Remove when appropriate. Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED); newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, AudioManager.SCO_AUDIO_STATE_DISCONNECTED); mContext.sendStickyBroadcast(newIntent); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener, BluetoothProfile.A2DP); } } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)) { if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { // a package is being removed, not replaced String packageName = intent.getData().getSchemeSpecificPart(); if (packageName != null) { removeMediaButtonReceiverForPackage(packageName); } } } else if (action.equals(Intent.ACTION_SCREEN_ON)) { AudioSystem.setParameters("screen_state=on"); } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { AudioSystem.setParameters("screen_state=off"); } else if (action.equalsIgnoreCase(Intent.ACTION_CONFIGURATION_CHANGED)) { handleConfigurationChanged(context); } } } private void showVolumeChangeUi(final int streamType, final int flags) { if (mUiContext != null && mVolumePanel != null) { mVolumePanel.postVolumeChanged(streamType, flags); } else { mHandler.post(new Runnable() { @Override public void run() { if (mUiContext == null) { mUiContext = ThemeUtils.createUiContext(mContext); } final Context context = mUiContext != null ? mUiContext : mContext; mVolumePanel = new VolumePanel(context, AudioService.this); mVolumePanel.postVolumeChanged(streamType, flags); } }); } } //========================================================================================== // AudioFocus //========================================================================================== /* constant to identify focus stack entry that is used to hold the focus while the phone * is ringing or during a call. Used by com.android.internal.telephony.CallManager when * entering and exiting calls. */ public final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls"; private final static Object mAudioFocusLock = new Object(); private final static Object mRingingLock = new Object(); private PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { if (state == TelephonyManager.CALL_STATE_RINGING) { //Log.v(TAG, " CALL_STATE_RINGING"); synchronized(mRingingLock) { mIsRinging = true; } } else if ((state == TelephonyManager.CALL_STATE_OFFHOOK) || (state == TelephonyManager.CALL_STATE_IDLE)) { synchronized(mRingingLock) { mIsRinging = false; } } } }; private void notifyTopOfAudioFocusStack() { // notify the top of the stack it gained focus if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) { if (canReassignAudioFocus()) { try { mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( AudioManager.AUDIOFOCUS_GAIN, mFocusStack.peek().mClientId); } catch (RemoteException e) { Log.e(TAG, "Failure to signal gain of audio control focus due to "+ e); e.printStackTrace(); } } } } private static class FocusStackEntry { public int mStreamType = -1;// no stream type public IAudioFocusDispatcher mFocusDispatcher = null; public IBinder mSourceRef = null; public String mClientId; public int mFocusChangeType; public AudioFocusDeathHandler mHandler; public String mPackageName; public int mCallingUid; public FocusStackEntry() { } public FocusStackEntry(int streamType, int duration, IAudioFocusDispatcher afl, IBinder source, String id, AudioFocusDeathHandler hdlr, String pn, int uid) { mStreamType = streamType; mFocusDispatcher = afl; mSourceRef = source; mClientId = id; mFocusChangeType = duration; mHandler = hdlr; mPackageName = pn; mCallingUid = uid; } public void unlinkToDeath() { try { if (mSourceRef != null && mHandler != null) { mSourceRef.unlinkToDeath(mHandler, 0); mHandler = null; } } catch (java.util.NoSuchElementException e) { Log.e(TAG, "Encountered " + e + " in FocusStackEntry.unlinkToDeath()"); } } @Override protected void finalize() throws Throwable { unlinkToDeath(); // unlink exception handled inside method super.finalize(); } } private final Stack<FocusStackEntry> mFocusStack = new Stack<FocusStackEntry>(); /** * Helper function: * Display in the log the current entries in the audio focus stack */ private void dumpFocusStack(PrintWriter pw) { pw.println("\nAudio Focus stack entries:"); synchronized(mAudioFocusLock) { Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); while(stackIterator.hasNext()) { FocusStackEntry fse = stackIterator.next(); pw.println(" source:" + fse.mSourceRef + " -- client: " + fse.mClientId + " -- duration: " + fse.mFocusChangeType + " -- uid: " + fse.mCallingUid); } } } /** * Helper function: * Called synchronized on mAudioFocusLock * Remove a focus listener from the focus stack. * @param focusListenerToRemove the focus listener * @param signal if true and the listener was at the top of the focus stack, i.e. it was holding * focus, notify the next item in the stack it gained focus. */ private void removeFocusStackEntry(String clientToRemove, boolean signal) { // is the current top of the focus stack abandoning focus? (because of request, not death) if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientToRemove)) { //Log.i(TAG, " removeFocusStackEntry() removing top of stack"); FocusStackEntry fse = mFocusStack.pop(); fse.unlinkToDeath(); if (signal) { // notify the new top of the stack it gained focus notifyTopOfAudioFocusStack(); // there's a new top of the stack, let the remote control know synchronized(mRCStack) { checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } } } else { // focus is abandoned by a client that's not at the top of the stack, // no need to update focus. Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); while(stackIterator.hasNext()) { FocusStackEntry fse = (FocusStackEntry)stackIterator.next(); if(fse.mClientId.equals(clientToRemove)) { Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for " + fse.mClientId); stackIterator.remove(); fse.unlinkToDeath(); } } } } /** * Helper function: * Called synchronized on mAudioFocusLock * Remove focus listeners from the focus stack for a particular client when it has died. */ private void removeFocusStackEntryForClient(IBinder cb) { // is the owner of the audio focus part of the client to remove? boolean isTopOfStackForClientToRemove = !mFocusStack.isEmpty() && mFocusStack.peek().mSourceRef.equals(cb); Iterator<FocusStackEntry> stackIterator = mFocusStack.iterator(); while(stackIterator.hasNext()) { FocusStackEntry fse = (FocusStackEntry)stackIterator.next(); if(fse.mSourceRef.equals(cb)) { Log.i(TAG, " AudioFocus abandonAudioFocus(): removing entry for " + fse.mClientId); stackIterator.remove(); // the client just died, no need to unlink to its death } } if (isTopOfStackForClientToRemove) { // we removed an entry at the top of the stack: // notify the new top of the stack it gained focus. notifyTopOfAudioFocusStack(); // there's a new top of the stack, let the remote control know synchronized(mRCStack) { checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } } } /** * Helper function: * Returns true if the system is in a state where the focus can be reevaluated, false otherwise. */ private boolean canReassignAudioFocus() { // focus requests are rejected during a phone call or when the phone is ringing // this is equivalent to IN_VOICE_COMM_FOCUS_ID having the focus if (!mFocusStack.isEmpty() && IN_VOICE_COMM_FOCUS_ID.equals(mFocusStack.peek().mClientId)) { return false; } return true; } /** * Inner class to monitor audio focus client deaths, and remove them from the audio focus * stack if necessary. */ private class AudioFocusDeathHandler implements IBinder.DeathRecipient { private IBinder mCb; // To be notified of client's death AudioFocusDeathHandler(IBinder cb) { mCb = cb; } public void binderDied() { synchronized(mAudioFocusLock) { Log.w(TAG, " AudioFocus audio focus client died"); removeFocusStackEntryForClient(mCb); } } public IBinder getBinder() { return mCb; } } /** @see AudioManager#requestAudioFocus(IAudioFocusDispatcher, int, int) */ public int requestAudioFocus(int mainStreamType, int focusChangeHint, IBinder cb, IAudioFocusDispatcher fd, String clientId, String callingPackageName) { Log.i(TAG, " AudioFocus requestAudioFocus() from " + clientId); // the main stream type for the audio focus request is currently not used. It may // potentially be used to handle multiple stream type-dependent audio focuses. // we need a valid binder callback for clients if (!cb.pingBinder()) { Log.e(TAG, " AudioFocus DOA client for requestAudioFocus(), aborting."); return AudioManager.AUDIOFOCUS_REQUEST_FAILED; } synchronized(mAudioFocusLock) { if (!canReassignAudioFocus()) { return AudioManager.AUDIOFOCUS_REQUEST_FAILED; } // handle the potential premature death of the new holder of the focus // (premature death == death before abandoning focus) // Register for client death notification AudioFocusDeathHandler afdh = new AudioFocusDeathHandler(cb); try { cb.linkToDeath(afdh, 0); } catch (RemoteException e) { // client has already died! Log.w(TAG, "AudioFocus requestAudioFocus() could not link to "+cb+" binder death"); return AudioManager.AUDIOFOCUS_REQUEST_FAILED; } if (!mFocusStack.empty() && mFocusStack.peek().mClientId.equals(clientId)) { // if focus is already owned by this client and the reason for acquiring the focus // hasn't changed, don't do anything if (mFocusStack.peek().mFocusChangeType == focusChangeHint) { // unlink death handler so it can be gc'ed. // linkToDeath() creates a JNI global reference preventing collection. cb.unlinkToDeath(afdh, 0); return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } // the reason for the audio focus request has changed: remove the current top of // stack and respond as if we had a new focus owner FocusStackEntry fse = mFocusStack.pop(); fse.unlinkToDeath(); } // notify current top of stack it is losing focus if (!mFocusStack.empty() && (mFocusStack.peek().mFocusDispatcher != null)) { try { mFocusStack.peek().mFocusDispatcher.dispatchAudioFocusChange( -1 * focusChangeHint, // loss and gain codes are inverse of each other mFocusStack.peek().mClientId); } catch (RemoteException e) { Log.e(TAG, " Failure to signal loss of focus due to "+ e); e.printStackTrace(); } } // focus requester might already be somewhere below in the stack, remove it removeFocusStackEntry(clientId, false /* signal */); // push focus requester at the top of the audio focus stack mFocusStack.push(new FocusStackEntry(mainStreamType, focusChangeHint, fd, cb, clientId, afdh, callingPackageName, Binder.getCallingUid())); // there's a new top of the stack, let the remote control know synchronized(mRCStack) { checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } }//synchronized(mAudioFocusLock) return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } /** @see AudioManager#abandonAudioFocus(IAudioFocusDispatcher) */ public int abandonAudioFocus(IAudioFocusDispatcher fl, String clientId) { Log.i(TAG, " AudioFocus abandonAudioFocus() from " + clientId); try { // this will take care of notifying the new focus owner if needed synchronized(mAudioFocusLock) { removeFocusStackEntry(clientId, true); } } catch (java.util.ConcurrentModificationException cme) { // Catching this exception here is temporary. It is here just to prevent // a crash seen when the "Silent" notification is played. This is believed to be fixed // but this try catch block is left just to be safe. Log.e(TAG, "FATAL EXCEPTION AudioFocus abandonAudioFocus() caused " + cme); cme.printStackTrace(); } return AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } public void unregisterAudioFocusClient(String clientId) { synchronized(mAudioFocusLock) { removeFocusStackEntry(clientId, false); } } //========================================================================================== // RemoteControl //========================================================================================== public void dispatchMediaKeyEvent(KeyEvent keyEvent) { filterMediaKeyEvent(keyEvent, false /*needWakeLock*/); } public void dispatchMediaKeyEventUnderWakelock(KeyEvent keyEvent) { filterMediaKeyEvent(keyEvent, true /*needWakeLock*/); } private void filterMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) { // sanity check on the incoming key event if (!isValidMediaKeyEvent(keyEvent)) { Log.e(TAG, "not dispatching invalid media key event " + keyEvent); return; } // event filtering for telephony synchronized(mRingingLock) { synchronized(mRCStack) { if ((mMediaReceiverForCalls != null) && (mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL))) { dispatchMediaKeyEventForCalls(keyEvent, needWakeLock); return; } } } // event filtering based on voice-based interactions if (isValidVoiceInputKeyCode(keyEvent.getKeyCode())) { filterVoiceInputKeyEvent(keyEvent, needWakeLock); } else { dispatchMediaKeyEvent(keyEvent, needWakeLock); } } /** * Handles the dispatching of the media button events to the telephony package. * Precondition: mMediaReceiverForCalls != null * @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event * is dispatched. */ private void dispatchMediaKeyEventForCalls(KeyEvent keyEvent, boolean needWakeLock) { Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); keyIntent.setPackage(mMediaReceiverForCalls.getPackageName()); if (needWakeLock) { mMediaEventWakeLock.acquire(); keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED); } mContext.sendOrderedBroadcast(keyIntent, null, mKeyEventDone, mAudioHandler, Activity.RESULT_OK, null, null); } /** * Handles the dispatching of the media button events to one of the registered listeners, * or if there was none, broadcast an ACTION_MEDIA_BUTTON intent to the rest of the system. * @param keyEvent a non-null KeyEvent whose key code is one of the supported media buttons * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event * is dispatched. */ private void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) { if (needWakeLock) { mMediaEventWakeLock.acquire(); } Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); synchronized(mRCStack) { if (!mRCStack.empty()) { // send the intent that was registered by the client try { mRCStack.peek().mMediaIntent.send(mContext, needWakeLock ? WAKELOCK_RELEASE_ON_FINISHED : 0 /*code*/, keyIntent, AudioService.this, mAudioHandler); } catch (CanceledException e) { Log.e(TAG, "Error sending pending intent " + mRCStack.peek()); e.printStackTrace(); } } else { // legacy behavior when nobody registered their media button event receiver // through AudioManager if (needWakeLock) { keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED); } mContext.sendOrderedBroadcast(keyIntent, null, mKeyEventDone, mAudioHandler, Activity.RESULT_OK, null, null); } } } /** * The different actions performed in response to a voice button key event. */ private final static int VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS = 1; private final static int VOICEBUTTON_ACTION_START_VOICE_INPUT = 2; private final static int VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS = 3; private final Object mVoiceEventLock = new Object(); private boolean mVoiceButtonDown; private boolean mVoiceButtonHandled; /** * Filter key events that may be used for voice-based interactions * @param keyEvent a non-null KeyEvent whose key code is that of one of the supported * media buttons that can be used to trigger voice-based interactions. * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held while this key event * is dispatched. */ private void filterVoiceInputKeyEvent(KeyEvent keyEvent, boolean needWakeLock) { if (DEBUG_RC) { Log.v(TAG, "voice input key event: " + keyEvent + ", needWakeLock=" + needWakeLock); } int voiceButtonAction = VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS; int keyAction = keyEvent.getAction(); synchronized (mVoiceEventLock) { if (keyAction == KeyEvent.ACTION_DOWN) { if (keyEvent.getRepeatCount() == 0) { // initial down mVoiceButtonDown = true; mVoiceButtonHandled = false; } else if (mVoiceButtonDown && !mVoiceButtonHandled && (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) { // long-press, start voice-based interactions mVoiceButtonHandled = true; voiceButtonAction = VOICEBUTTON_ACTION_START_VOICE_INPUT; } } else if (keyAction == KeyEvent.ACTION_UP) { if (mVoiceButtonDown) { // voice button up mVoiceButtonDown = false; if (!mVoiceButtonHandled && !keyEvent.isCanceled()) { voiceButtonAction = VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS; } } } }//synchronized (mVoiceEventLock) // take action after media button event filtering for voice-based interactions switch (voiceButtonAction) { case VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS: if (DEBUG_RC) Log.v(TAG, " ignore key event"); break; case VOICEBUTTON_ACTION_START_VOICE_INPUT: if (DEBUG_RC) Log.v(TAG, " start voice-based interactions"); // then start the voice-based interactions startVoiceBasedInteractions(needWakeLock); break; case VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS: if (DEBUG_RC) Log.v(TAG, " send simulated key event"); sendSimulatedMediaButtonEvent(keyEvent, needWakeLock); break; } } private void sendSimulatedMediaButtonEvent(KeyEvent originalKeyEvent, boolean needWakeLock) { // send DOWN event KeyEvent keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_DOWN); dispatchMediaKeyEvent(keyEvent, needWakeLock); // send UP event keyEvent = KeyEvent.changeAction(originalKeyEvent, KeyEvent.ACTION_UP); dispatchMediaKeyEvent(keyEvent, needWakeLock); } private static boolean isValidMediaKeyEvent(KeyEvent keyEvent) { if (keyEvent == null) { return false; } final int keyCode = keyEvent.getKeyCode(); switch (keyCode) { case KeyEvent.KEYCODE_MUTE: case KeyEvent.KEYCODE_HEADSETHOOK: case KeyEvent.KEYCODE_MEDIA_PLAY: case KeyEvent.KEYCODE_MEDIA_PAUSE: case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: case KeyEvent.KEYCODE_MEDIA_STOP: case KeyEvent.KEYCODE_MEDIA_NEXT: case KeyEvent.KEYCODE_MEDIA_PREVIOUS: case KeyEvent.KEYCODE_MEDIA_REWIND: case KeyEvent.KEYCODE_MEDIA_RECORD: case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: case KeyEvent.KEYCODE_MEDIA_CLOSE: case KeyEvent.KEYCODE_MEDIA_EJECT: break; default: return false; } return true; } /** * Checks whether the given key code is one that can trigger the launch of voice-based * interactions. * @param keyCode the key code associated with the key event * @return true if the key is one of the supported voice-based interaction triggers */ private static boolean isValidVoiceInputKeyCode(int keyCode) { if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) { return true; } else { return false; } } /** * Tell the system to start voice-based interactions / voice commands */ private void startVoiceBasedInteractions(boolean needWakeLock) { Intent voiceIntent = null; // select which type of search to launch: // - screen on and device unlocked: action is ACTION_WEB_SEARCH // - device locked or screen off: action is ACTION_VOICE_SEARCH_HANDS_FREE // with EXTRA_SECURE set to true if the device is securely locked PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked(); if (!isLocked && pm.isScreenOn()) { voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH); } else { voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE); voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, isLocked && mKeyguardManager.isKeyguardSecure()); } // start the search activity if (needWakeLock) { mMediaEventWakeLock.acquire(); } try { if (voiceIntent != null) { voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); mContext.startActivity(voiceIntent); } } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity for search: " + e); } finally { if (needWakeLock) { mMediaEventWakeLock.release(); } } } private PowerManager.WakeLock mMediaEventWakeLock; private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; //magic number // only set when wakelock was acquired, no need to check value when received private static final String EXTRA_WAKELOCK_ACQUIRED = "android.media.AudioService.WAKELOCK_ACQUIRED"; public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, String resultData, Bundle resultExtras) { if (resultCode == WAKELOCK_RELEASE_ON_FINISHED) { mMediaEventWakeLock.release(); } } BroadcastReceiver mKeyEventDone = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (intent == null) { return; } Bundle extras = intent.getExtras(); if (extras == null) { return; } if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)) { mMediaEventWakeLock.release(); } } }; private final Object mCurrentRcLock = new Object(); /** * The one remote control client which will receive a request for display information. * This object may be null. * Access protected by mCurrentRcLock. */ private IRemoteControlClient mCurrentRcClient = null; private final static int RC_INFO_NONE = 0; private final static int RC_INFO_ALL = RemoteControlClient.FLAG_INFORMATION_REQUEST_ALBUM_ART | RemoteControlClient.FLAG_INFORMATION_REQUEST_KEY_MEDIA | RemoteControlClient.FLAG_INFORMATION_REQUEST_METADATA | RemoteControlClient.FLAG_INFORMATION_REQUEST_PLAYSTATE; /** * A monotonically increasing generation counter for mCurrentRcClient. * Only accessed with a lock on mCurrentRcLock. * No value wrap-around issues as we only act on equal values. */ private int mCurrentRcClientGen = 0; /** * Inner class to monitor remote control client deaths, and remove the client for the * remote control stack if necessary. */ private class RcClientDeathHandler implements IBinder.DeathRecipient { private IBinder mCb; // To be notified of client's death private PendingIntent mMediaIntent; RcClientDeathHandler(IBinder cb, PendingIntent pi) { mCb = cb; mMediaIntent = pi; } public void binderDied() { Log.w(TAG, " RemoteControlClient died"); // remote control client died, make sure the displays don't use it anymore // by setting its remote control client to null registerRemoteControlClient(mMediaIntent, null/*rcClient*/, null/*ignored*/); // the dead client was maybe handling remote playback, reevaluate postReevaluateRemote(); } public IBinder getBinder() { return mCb; } } /** * A global counter for RemoteControlClient identifiers */ private static int sLastRccId = 0; private class RemotePlaybackState { int mRccId; int mVolume; int mVolumeMax; int mVolumeHandling; private RemotePlaybackState(int id, int vol, int volMax) { mRccId = id; mVolume = vol; mVolumeMax = volMax; mVolumeHandling = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME_HANDLING; } } /** * Internal cache for the playback information of the RemoteControlClient whose volume gets to * be controlled by the volume keys ("main"), so we don't have to iterate over the RC stack * every time we need this info. */ private RemotePlaybackState mMainRemote; /** * Indicates whether the "main" RemoteControlClient is considered active. * Use synchronized on mMainRemote. */ private boolean mMainRemoteIsActive; /** * Indicates whether there is remote playback going on. True even if there is no "active" * remote playback (mMainRemoteIsActive is false), but a RemoteControlClient has declared it * handles remote playback. * Use synchronized on mMainRemote. */ private boolean mHasRemotePlayback; private static class RemoteControlStackEntry { public int mRccId = RemoteControlClient.RCSE_ID_UNREGISTERED; /** * The target for the ACTION_MEDIA_BUTTON events. * Always non null. */ public PendingIntent mMediaIntent; /** * The registered media button event receiver. * Always non null. */ public ComponentName mReceiverComponent; public String mCallingPackageName; public int mCallingUid; /** * Provides access to the information to display on the remote control. * May be null (when a media button event receiver is registered, * but no remote control client has been registered) */ public IRemoteControlClient mRcClient; public RcClientDeathHandler mRcClientDeathHandler; /** * Information only used for non-local playback */ public int mPlaybackType; public int mPlaybackVolume; public int mPlaybackVolumeMax; public int mPlaybackVolumeHandling; public int mPlaybackStream; public int mPlaybackState; public IRemoteVolumeObserver mRemoteVolumeObs; public void resetPlaybackInfo() { mPlaybackType = RemoteControlClient.PLAYBACK_TYPE_LOCAL; mPlaybackVolume = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME; mPlaybackVolumeMax = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME; mPlaybackVolumeHandling = RemoteControlClient.DEFAULT_PLAYBACK_VOLUME_HANDLING; mPlaybackStream = AudioManager.STREAM_MUSIC; mPlaybackState = RemoteControlClient.PLAYSTATE_STOPPED; mRemoteVolumeObs = null; } /** precondition: mediaIntent != null, eventReceiver != null */ public RemoteControlStackEntry(PendingIntent mediaIntent, ComponentName eventReceiver) { mMediaIntent = mediaIntent; mReceiverComponent = eventReceiver; mCallingUid = -1; mRcClient = null; mRccId = ++sLastRccId; resetPlaybackInfo(); } public void unlinkToRcClientDeath() { if ((mRcClientDeathHandler != null) && (mRcClientDeathHandler.mCb != null)) { try { mRcClientDeathHandler.mCb.unlinkToDeath(mRcClientDeathHandler, 0); mRcClientDeathHandler = null; } catch (java.util.NoSuchElementException e) { // not much we can do here Log.e(TAG, "Encountered " + e + " in unlinkToRcClientDeath()"); e.printStackTrace(); } } } @Override protected void finalize() throws Throwable { unlinkToRcClientDeath();// unlink exception handled inside method super.finalize(); } } /** * The stack of remote control event receivers. * Code sections and methods that modify the remote control event receiver stack are * synchronized on mRCStack, but also BEFORE on mFocusLock as any change in either * stack, audio focus or RC, can lead to a change in the remote control display */ private final Stack<RemoteControlStackEntry> mRCStack = new Stack<RemoteControlStackEntry>(); /** * The component the telephony package can register so telephony calls have priority to * handle media button events */ private ComponentName mMediaReceiverForCalls = null; /** * Helper function: * Display in the log the current entries in the remote control focus stack */ private void dumpRCStack(PrintWriter pw) { pw.println("\nRemote Control stack entries:"); synchronized(mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); pw.println(" pi: " + rcse.mMediaIntent + " -- ercvr: " + rcse.mReceiverComponent + " -- client: " + rcse.mRcClient + " -- uid: " + rcse.mCallingUid + " -- type: " + rcse.mPlaybackType + " state: " + rcse.mPlaybackState); } } } /** * Helper function: * Display in the log the current entries in the remote control stack, focusing * on RemoteControlClient data */ private void dumpRCCStack(PrintWriter pw) { pw.println("\nRemote Control Client stack entries:"); synchronized(mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); pw.println(" uid: " + rcse.mCallingUid + " -- id: " + rcse.mRccId + " -- type: " + rcse.mPlaybackType + " -- state: " + rcse.mPlaybackState + " -- vol handling: " + rcse.mPlaybackVolumeHandling + " -- vol: " + rcse.mPlaybackVolume + " -- volMax: " + rcse.mPlaybackVolumeMax + " -- volObs: " + rcse.mRemoteVolumeObs); } } synchronized (mMainRemote) { pw.println("\nRemote Volume State:"); pw.println(" has remote: " + mHasRemotePlayback); pw.println(" is remote active: " + mMainRemoteIsActive); pw.println(" rccId: " + mMainRemote.mRccId); pw.println(" volume handling: " + ((mMainRemote.mVolumeHandling == RemoteControlClient.PLAYBACK_VOLUME_FIXED) ? "PLAYBACK_VOLUME_FIXED(0)" : "PLAYBACK_VOLUME_VARIABLE(1)")); pw.println(" volume: " + mMainRemote.mVolume); pw.println(" volume steps: " + mMainRemote.mVolumeMax); } } /** * Helper function: * Remove any entry in the remote control stack that has the same package name as packageName * Pre-condition: packageName != null */ private void removeMediaButtonReceiverForPackage(String packageName) { synchronized(mRCStack) { if (mRCStack.empty()) { return; } else { RemoteControlStackEntry oldTop = mRCStack.peek(); Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); // iterate over the stack entries while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next(); if (packageName.equalsIgnoreCase(rcse.mReceiverComponent.getPackageName())) { // a stack entry is from the package being removed, remove it from the stack stackIterator.remove(); rcse.unlinkToRcClientDeath(); } } if (mRCStack.empty()) { // no saved media button receiver mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, null)); } else if (oldTop != mRCStack.peek()) { // the top of the stack has changed, save it in the system settings // by posting a message to persist it mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, mRCStack.peek().mReceiverComponent)); } } } } /** * Helper function: * Restore remote control receiver from the system settings. */ private void restoreMediaButtonReceiver() { String receiverName = Settings.System.getString(mContentResolver, Settings.System.MEDIA_BUTTON_RECEIVER); if ((null != receiverName) && !receiverName.isEmpty()) { ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName); // construct a PendingIntent targeted to the restored component name // for the media button and register it Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); // the associated intent will be handled by the component being registered mediaButtonIntent.setComponent(eventReceiver); PendingIntent pi = PendingIntent.getBroadcast(mContext, 0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/); registerMediaButtonIntent(pi, eventReceiver); } } /** * Helper function: * Set the new remote control receiver at the top of the RC focus stack. * precondition: mediaIntent != null, target != null */ private void pushMediaButtonReceiver(PendingIntent mediaIntent, ComponentName target) { // already at top of stack? if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) { return; } Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); RemoteControlStackEntry rcse = null; boolean wasInsideStack = false; while(stackIterator.hasNext()) { rcse = (RemoteControlStackEntry)stackIterator.next(); if(rcse.mMediaIntent.equals(mediaIntent)) { wasInsideStack = true; stackIterator.remove(); break; } } if (!wasInsideStack) { rcse = new RemoteControlStackEntry(mediaIntent, target); } mRCStack.push(rcse); // post message to persist the default media button receiver mAudioHandler.sendMessage( mAudioHandler.obtainMessage( MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) ); } /** * Helper function: * Remove the remote control receiver from the RC focus stack. * precondition: pi != null */ private void removeMediaButtonReceiver(PendingIntent pi) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next(); if(rcse.mMediaIntent.equals(pi)) { stackIterator.remove(); rcse.unlinkToRcClientDeath(); break; } } } /** * Helper function: * Called synchronized on mRCStack */ private boolean isCurrentRcController(PendingIntent pi) { if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(pi)) { return true; } return false; } //========================================================================================== // Remote control display / client //========================================================================================== /** * Update the remote control displays with the new "focused" client generation */ private void setNewRcClientOnDisplays_syncRcsCurrc(int newClientGeneration, PendingIntent newMediaIntent, boolean clearing) { // NOTE: Only one IRemoteControlDisplay supported in this implementation if (mRcDisplay != null) { try { mRcDisplay.setCurrentClientId( newClientGeneration, newMediaIntent, clearing); } catch (RemoteException e) { Log.e(TAG, "Dead display in setNewRcClientOnDisplays_syncRcsCurrc() "+e); // if we had a display before, stop monitoring its death rcDisplay_stopDeathMonitor_syncRcStack(); mRcDisplay = null; } } } /** * Update the remote control clients with the new "focused" client generation */ private void setNewRcClientGenerationOnClients_syncRcsCurrc(int newClientGeneration) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry se = stackIterator.next(); if ((se != null) && (se.mRcClient != null)) { try { se.mRcClient.setCurrentClientGenerationId(newClientGeneration); } catch (RemoteException e) { Log.w(TAG, "Dead client in setNewRcClientGenerationOnClients_syncRcsCurrc()"+e); stackIterator.remove(); se.unlinkToRcClientDeath(); } } } } /** * Update the displays and clients with the new "focused" client generation and name * @param newClientGeneration the new generation value matching a client update * @param newClientEventReceiver the media button event receiver associated with the client. * May be null, which implies there is no registered media button event receiver. * @param clearing true if the new client generation value maps to a remote control update * where the display should be cleared. */ private void setNewRcClient_syncRcsCurrc(int newClientGeneration, PendingIntent newMediaIntent, boolean clearing) { // send the new valid client generation ID to all displays setNewRcClientOnDisplays_syncRcsCurrc(newClientGeneration, newMediaIntent, clearing); // send the new valid client generation ID to all clients setNewRcClientGenerationOnClients_syncRcsCurrc(newClientGeneration); } /** * Called when processing MSG_RCDISPLAY_CLEAR event */ private void onRcDisplayClear() { if (DEBUG_RC) Log.i(TAG, "Clear remote control display"); synchronized(mRCStack) { synchronized(mCurrentRcLock) { mCurrentRcClientGen++; // synchronously update the displays and clients with the new client generation setNewRcClient_syncRcsCurrc(mCurrentRcClientGen, null /*newMediaIntent*/, true /*clearing*/); } } } /** * Called when processing MSG_RCDISPLAY_UPDATE event */ private void onRcDisplayUpdate(RemoteControlStackEntry rcse, int flags /* USED ?*/) { synchronized(mRCStack) { synchronized(mCurrentRcLock) { if ((mCurrentRcClient != null) && (mCurrentRcClient.equals(rcse.mRcClient))) { if (DEBUG_RC) Log.i(TAG, "Display/update remote control "); mCurrentRcClientGen++; // synchronously update the displays and clients with // the new client generation setNewRcClient_syncRcsCurrc(mCurrentRcClientGen, rcse.mMediaIntent /*newMediaIntent*/, false /*clearing*/); // tell the current client that it needs to send info try { mCurrentRcClient.onInformationRequested(mCurrentRcClientGen, flags, mArtworkExpectedWidth, mArtworkExpectedHeight); } catch (RemoteException e) { Log.e(TAG, "Current valid remote client is dead: "+e); mCurrentRcClient = null; } } else { // the remote control display owner has changed between the // the message to update the display was sent, and the time it // gets to be processed (now) } } } } /** * Helper function: * Called synchronized on mRCStack */ private void clearRemoteControlDisplay_syncAfRcs() { synchronized(mCurrentRcLock) { mCurrentRcClient = null; } // will cause onRcDisplayClear() to be called in AudioService's handler thread mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_CLEAR) ); } /** * Helper function for code readability: only to be called from * checkUpdateRemoteControlDisplay_syncAfRcs() which checks the preconditions for * this method. * Preconditions: * - called synchronized mAudioFocusLock then on mRCStack * - mRCStack.isEmpty() is false */ private void updateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) { RemoteControlStackEntry rcse = mRCStack.peek(); int infoFlagsAboutToBeUsed = infoChangedFlags; // this is where we enforce opt-in for information display on the remote controls // with the new AudioManager.registerRemoteControlClient() API if (rcse.mRcClient == null) { //Log.w(TAG, "Can't update remote control display with null remote control client"); clearRemoteControlDisplay_syncAfRcs(); return; } synchronized(mCurrentRcLock) { if (!rcse.mRcClient.equals(mCurrentRcClient)) { // new RC client, assume every type of information shall be queried infoFlagsAboutToBeUsed = RC_INFO_ALL; } mCurrentRcClient = rcse.mRcClient; } // will cause onRcDisplayUpdate() to be called in AudioService's handler thread mAudioHandler.sendMessage( mAudioHandler.obtainMessage(MSG_RCDISPLAY_UPDATE, infoFlagsAboutToBeUsed /* arg1 */, 0, rcse /* obj, != null */) ); } /** * Helper function: * Called synchronized on mAudioFocusLock, then mRCStack * Check whether the remote control display should be updated, triggers the update if required * @param infoChangedFlags the flags corresponding to the remote control client information * that has changed, if applicable (checking for the update conditions might trigger a * clear, rather than an update event). */ private void checkUpdateRemoteControlDisplay_syncAfRcs(int infoChangedFlags) { // determine whether the remote control display should be refreshed // if either stack is empty, there is a mismatch, so clear the RC display if (mRCStack.isEmpty() || mFocusStack.isEmpty()) { clearRemoteControlDisplay_syncAfRcs(); return; } // if the top of the two stacks belong to different packages, there is a mismatch, clear if ((mRCStack.peek().mCallingPackageName != null) && (mFocusStack.peek().mPackageName != null) && !(mRCStack.peek().mCallingPackageName.compareTo( mFocusStack.peek().mPackageName) == 0)) { clearRemoteControlDisplay_syncAfRcs(); return; } // if the audio focus didn't originate from the same Uid as the one in which the remote // control information will be retrieved, clear if (mRCStack.peek().mCallingUid != mFocusStack.peek().mCallingUid) { clearRemoteControlDisplay_syncAfRcs(); return; } // refresh conditions were verified: update the remote controls // ok to call: synchronized mAudioFocusLock then on mRCStack, mRCStack is not empty updateRemoteControlDisplay_syncAfRcs(infoChangedFlags); } /** * see AudioManager.registerMediaButtonIntent(PendingIntent pi, ComponentName c) * precondition: mediaIntent != null, target != null */ public void registerMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) { Log.i(TAG, " Remote Control registerMediaButtonIntent() for " + mediaIntent); synchronized(mAudioFocusLock) { synchronized(mRCStack) { pushMediaButtonReceiver(mediaIntent, eventReceiver); // new RC client, assume every type of information shall be queried checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } } } /** * see AudioManager.unregisterMediaButtonIntent(PendingIntent mediaIntent) * precondition: mediaIntent != null, eventReceiver != null */ public void unregisterMediaButtonIntent(PendingIntent mediaIntent, ComponentName eventReceiver) { Log.i(TAG, " Remote Control unregisterMediaButtonIntent() for " + mediaIntent); synchronized(mAudioFocusLock) { synchronized(mRCStack) { boolean topOfStackWillChange = isCurrentRcController(mediaIntent); removeMediaButtonReceiver(mediaIntent); if (topOfStackWillChange) { // current RC client will change, assume every type of info needs to be queried checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } } } } /** * see AudioManager.registerMediaButtonEventReceiverForCalls(ComponentName c) * precondition: c != null */ public void registerMediaButtonEventReceiverForCalls(ComponentName c) { if (mContext.checkCallingPermission("android.permission.MODIFY_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) { Log.e(TAG, "Invalid permissions to register media button receiver for calls"); return; } synchronized(mRCStack) { mMediaReceiverForCalls = c; } } /** * see AudioManager.unregisterMediaButtonEventReceiverForCalls() */ public void unregisterMediaButtonEventReceiverForCalls() { if (mContext.checkCallingPermission("android.permission.MODIFY_PHONE_STATE") != PackageManager.PERMISSION_GRANTED) { Log.e(TAG, "Invalid permissions to unregister media button receiver for calls"); return; } synchronized(mRCStack) { mMediaReceiverForCalls = null; } } /** * see AudioManager.registerRemoteControlClient(ComponentName eventReceiver, ...) * @return the unique ID of the RemoteControlStackEntry associated with the RemoteControlClient * Note: using this method with rcClient == null is a way to "disable" the IRemoteControlClient * without modifying the RC stack, but while still causing the display to refresh (will * become blank as a result of this) */ public int registerRemoteControlClient(PendingIntent mediaIntent, IRemoteControlClient rcClient, String callingPackageName) { if (DEBUG_RC) Log.i(TAG, "Register remote control client rcClient="+rcClient); int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED; synchronized(mAudioFocusLock) { synchronized(mRCStack) { // store the new display information Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if(rcse.mMediaIntent.equals(mediaIntent)) { // already had a remote control client? if (rcse.mRcClientDeathHandler != null) { // stop monitoring the old client's death rcse.unlinkToRcClientDeath(); } // save the new remote control client rcse.mRcClient = rcClient; rcse.mCallingPackageName = callingPackageName; rcse.mCallingUid = Binder.getCallingUid(); if (rcClient == null) { // here rcse.mRcClientDeathHandler is null; rcse.resetPlaybackInfo(); break; } rccId = rcse.mRccId; // there is a new (non-null) client: // 1/ give the new client the current display (if any) if (mRcDisplay != null) { try { rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay); } catch (RemoteException e) { Log.e(TAG, "Error connecting remote control display to client: "+e); e.printStackTrace(); } } // 2/ monitor the new client's death IBinder b = rcse.mRcClient.asBinder(); RcClientDeathHandler rcdh = new RcClientDeathHandler(b, rcse.mMediaIntent); try { b.linkToDeath(rcdh, 0); } catch (RemoteException e) { // remote control client is DOA, disqualify it Log.w(TAG, "registerRemoteControlClient() has a dead client " + b); rcse.mRcClient = null; } rcse.mRcClientDeathHandler = rcdh; break; } } // if the eventReceiver is at the top of the stack // then check for potential refresh of the remote controls if (isCurrentRcController(mediaIntent)) { checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } } } return rccId; } /** * see AudioManager.unregisterRemoteControlClient(PendingIntent pi, ...) * rcClient is guaranteed non-null */ public void unregisterRemoteControlClient(PendingIntent mediaIntent, IRemoteControlClient rcClient) { synchronized(mAudioFocusLock) { synchronized(mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if ((rcse.mMediaIntent.equals(mediaIntent)) && rcClient.equals(rcse.mRcClient)) { // we found the IRemoteControlClient to unregister // stop monitoring its death rcse.unlinkToRcClientDeath(); // reset the client-related fields rcse.mRcClient = null; rcse.mCallingPackageName = null; } } } } } /** * The remote control displays. * Access synchronized on mRCStack * NOTE: Only one IRemoteControlDisplay supported in this implementation */ private IRemoteControlDisplay mRcDisplay; private RcDisplayDeathHandler mRcDisplayDeathHandler; private int mArtworkExpectedWidth = -1; private int mArtworkExpectedHeight = -1; /** * Inner class to monitor remote control display deaths, and unregister them from the list * of displays if necessary. */ private class RcDisplayDeathHandler implements IBinder.DeathRecipient { private IBinder mCb; // To be notified of client's death public RcDisplayDeathHandler(IBinder b) { if (DEBUG_RC) Log.i(TAG, "new RcDisplayDeathHandler for "+b); mCb = b; } public void binderDied() { synchronized(mRCStack) { Log.w(TAG, "RemoteControl: display died"); mRcDisplay = null; } } public void unlinkToRcDisplayDeath() { if (DEBUG_RC) Log.i(TAG, "unlinkToRcDisplayDeath for "+mCb); try { mCb.unlinkToDeath(this, 0); } catch (java.util.NoSuchElementException e) { // not much we can do here, the display was being unregistered anyway Log.e(TAG, "Encountered " + e + " in unlinkToRcDisplayDeath()"); e.printStackTrace(); } } } private void rcDisplay_stopDeathMonitor_syncRcStack() { if (mRcDisplay != null) { // implies (mRcDisplayDeathHandler != null) // we had a display before, stop monitoring its death mRcDisplayDeathHandler.unlinkToRcDisplayDeath(); } } private void rcDisplay_startDeathMonitor_syncRcStack() { if (mRcDisplay != null) { // new non-null display, monitor its death IBinder b = mRcDisplay.asBinder(); mRcDisplayDeathHandler = new RcDisplayDeathHandler(b); try { b.linkToDeath(mRcDisplayDeathHandler, 0); } catch (RemoteException e) { // remote control display is DOA, disqualify it Log.w(TAG, "registerRemoteControlDisplay() has a dead client " + b); mRcDisplay = null; } } } /** * Register an IRemoteControlDisplay. * Notify all IRemoteControlClient of the new display and cause the RemoteControlClient * at the top of the stack to update the new display with its information. * Since only one IRemoteControlDisplay is supported, this will unregister the previous display. * @param rcd the IRemoteControlDisplay to register. No effect if null. */ public void registerRemoteControlDisplay(IRemoteControlDisplay rcd) { if (DEBUG_RC) Log.d(TAG, ">>> registerRemoteControlDisplay("+rcd+")"); synchronized(mAudioFocusLock) { synchronized(mRCStack) { if ((mRcDisplay == rcd) || (rcd == null)) { return; } // if we had a display before, stop monitoring its death rcDisplay_stopDeathMonitor_syncRcStack(); mRcDisplay = rcd; // new display, start monitoring its death rcDisplay_startDeathMonitor_syncRcStack(); // let all the remote control clients there is a new display // no need to unplug the previous because we only support one display // and the clients don't track the death of the display Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if(rcse.mRcClient != null) { try { rcse.mRcClient.plugRemoteControlDisplay(mRcDisplay); } catch (RemoteException e) { Log.e(TAG, "Error connecting remote control display to client: " + e); e.printStackTrace(); } } } // we have a new display, of which all the clients are now aware: have it be updated checkUpdateRemoteControlDisplay_syncAfRcs(RC_INFO_ALL); } } } /** * Unregister an IRemoteControlDisplay. * Since only one IRemoteControlDisplay is supported, this has no effect if the one to * unregister is not the current one. * @param rcd the IRemoteControlDisplay to unregister. No effect if null. */ public void unregisterRemoteControlDisplay(IRemoteControlDisplay rcd) { if (DEBUG_RC) Log.d(TAG, "<<< unregisterRemoteControlDisplay("+rcd+")"); synchronized(mRCStack) { // only one display here, so you can only unregister the current display if ((rcd == null) || (rcd != mRcDisplay)) { if (DEBUG_RC) Log.w(TAG, " trying to unregister unregistered RCD"); return; } // if we had a display before, stop monitoring its death rcDisplay_stopDeathMonitor_syncRcStack(); mRcDisplay = null; // disconnect this remote control display from all the clients Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if(rcse.mRcClient != null) { try { rcse.mRcClient.unplugRemoteControlDisplay(rcd); } catch (RemoteException e) { Log.e(TAG, "Error disconnecting remote control display to client: " + e); e.printStackTrace(); } } } } } public void remoteControlDisplayUsesBitmapSize(IRemoteControlDisplay rcd, int w, int h) { synchronized(mRCStack) { // NOTE: Only one IRemoteControlDisplay supported in this implementation mArtworkExpectedWidth = w; mArtworkExpectedHeight = h; } } public void setPlaybackInfoForRcc(int rccId, int what, int value) { sendMsg(mAudioHandler, MSG_RCC_NEW_PLAYBACK_INFO, SENDMSG_QUEUE, rccId /* arg1 */, what /* arg2 */, Integer.valueOf(value) /* obj */, 0 /* delay */); } // handler for MSG_RCC_NEW_PLAYBACK_INFO private void onNewPlaybackInfoForRcc(int rccId, int key, int value) { if(DEBUG_RC) Log.d(TAG, "onNewPlaybackInfoForRcc(id=" + rccId + ", what=" + key + ",val=" + value + ")"); synchronized(mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if (rcse.mRccId == rccId) { switch (key) { case RemoteControlClient.PLAYBACKINFO_PLAYBACK_TYPE: rcse.mPlaybackType = value; postReevaluateRemote(); break; case RemoteControlClient.PLAYBACKINFO_VOLUME: rcse.mPlaybackVolume = value; synchronized (mMainRemote) { if (rccId == mMainRemote.mRccId) { mMainRemote.mVolume = value; mVolumePanel.postHasNewRemotePlaybackInfo(); } } break; case RemoteControlClient.PLAYBACKINFO_VOLUME_MAX: rcse.mPlaybackVolumeMax = value; synchronized (mMainRemote) { if (rccId == mMainRemote.mRccId) { mMainRemote.mVolumeMax = value; mVolumePanel.postHasNewRemotePlaybackInfo(); } } break; case RemoteControlClient.PLAYBACKINFO_VOLUME_HANDLING: rcse.mPlaybackVolumeHandling = value; synchronized (mMainRemote) { if (rccId == mMainRemote.mRccId) { mMainRemote.mVolumeHandling = value; mVolumePanel.postHasNewRemotePlaybackInfo(); } } break; case RemoteControlClient.PLAYBACKINFO_USES_STREAM: rcse.mPlaybackStream = value; break; case RemoteControlClient.PLAYBACKINFO_PLAYSTATE: rcse.mPlaybackState = value; synchronized (mMainRemote) { if (rccId == mMainRemote.mRccId) { mMainRemoteIsActive = isPlaystateActive(value); postReevaluateRemote(); } } break; default: Log.e(TAG, "unhandled key " + key + " for RCC " + rccId); break; } return; } } } } public void registerRemoteVolumeObserverForRcc(int rccId, IRemoteVolumeObserver rvo) { sendMsg(mAudioHandler, MSG_RCC_NEW_VOLUME_OBS, SENDMSG_QUEUE, rccId /* arg1 */, 0, rvo /* obj */, 0 /* delay */); } // handler for MSG_RCC_NEW_VOLUME_OBS private void onRegisterVolumeObserverForRcc(int rccId, IRemoteVolumeObserver rvo) { synchronized(mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if (rcse.mRccId == rccId) { rcse.mRemoteVolumeObs = rvo; break; } } } } /** * Checks if a remote client is active on the supplied stream type. Update the remote stream * volume state if found and playing * @param streamType * @return false if no remote playing is currently playing */ private boolean checkUpdateRemoteStateIfActive(int streamType) { synchronized(mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if ((rcse.mPlaybackType == RemoteControlClient.PLAYBACK_TYPE_REMOTE) && isPlaystateActive(rcse.mPlaybackState) && (rcse.mPlaybackStream == streamType)) { if (DEBUG_RC) Log.d(TAG, "remote playback active on stream " + streamType + ", vol =" + rcse.mPlaybackVolume); synchronized (mMainRemote) { mMainRemote.mRccId = rcse.mRccId; mMainRemote.mVolume = rcse.mPlaybackVolume; mMainRemote.mVolumeMax = rcse.mPlaybackVolumeMax; mMainRemote.mVolumeHandling = rcse.mPlaybackVolumeHandling; mMainRemoteIsActive = true; } return true; } } } synchronized (mMainRemote) { mMainRemoteIsActive = false; } return false; } /** * Returns true if the given playback state is considered "active", i.e. it describes a state * where playback is happening, or about to * @param playState the playback state to evaluate * @return true if active, false otherwise (inactive or unknown) */ private static boolean isPlaystateActive(int playState) { switch (playState) { case RemoteControlClient.PLAYSTATE_PLAYING: case RemoteControlClient.PLAYSTATE_BUFFERING: case RemoteControlClient.PLAYSTATE_FAST_FORWARDING: case RemoteControlClient.PLAYSTATE_REWINDING: case RemoteControlClient.PLAYSTATE_SKIPPING_BACKWARDS: case RemoteControlClient.PLAYSTATE_SKIPPING_FORWARDS: return true; default: return false; } } private void adjustRemoteVolume(int streamType, int direction, int flags) { int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED; boolean volFixed = false; synchronized (mMainRemote) { if (!mMainRemoteIsActive) { if (DEBUG_VOL) Log.w(TAG, "adjustRemoteVolume didn't find an active client"); return; } rccId = mMainRemote.mRccId; volFixed = (mMainRemote.mVolumeHandling == RemoteControlClient.PLAYBACK_VOLUME_FIXED); } // unlike "local" stream volumes, we can't compute the new volume based on the direction, // we can only notify the remote that volume needs to be updated, and we'll get an async' // update through setPlaybackInfoForRcc() if (!volFixed) { sendVolumeUpdateToRemote(rccId, direction); } // fire up the UI mVolumePanel.postRemoteVolumeChanged(streamType, flags); } private void sendVolumeUpdateToRemote(int rccId, int direction) { if (DEBUG_VOL) { Log.d(TAG, "sendVolumeUpdateToRemote(rccId="+rccId+" , dir="+direction); } if (direction == 0) { // only handling discrete events return; } IRemoteVolumeObserver rvo = null; synchronized (mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); //FIXME OPTIMIZE store this info in mMainRemote so we don't have to iterate? if (rcse.mRccId == rccId) { rvo = rcse.mRemoteVolumeObs; break; } } } if (rvo != null) { try { rvo.dispatchRemoteVolumeUpdate(direction, -1); } catch (RemoteException e) { Log.e(TAG, "Error dispatching relative volume update", e); } } } public int getRemoteStreamMaxVolume() { synchronized (mMainRemote) { if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) { return 0; } return mMainRemote.mVolumeMax; } } public int getRemoteStreamVolume() { synchronized (mMainRemote) { if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) { return 0; } return mMainRemote.mVolume; } } public void setRemoteStreamVolume(int vol) { if (DEBUG_VOL) { Log.d(TAG, "setRemoteStreamVolume(vol="+vol+")"); } int rccId = RemoteControlClient.RCSE_ID_UNREGISTERED; synchronized (mMainRemote) { if (mMainRemote.mRccId == RemoteControlClient.RCSE_ID_UNREGISTERED) { return; } rccId = mMainRemote.mRccId; } IRemoteVolumeObserver rvo = null; synchronized (mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if (rcse.mRccId == rccId) { //FIXME OPTIMIZE store this info in mMainRemote so we don't have to iterate? rvo = rcse.mRemoteVolumeObs; break; } } } if (rvo != null) { try { rvo.dispatchRemoteVolumeUpdate(0, vol); } catch (RemoteException e) { Log.e(TAG, "Error dispatching absolute volume update", e); } } } /** * Call to make AudioService reevaluate whether it's in a mode where remote players should * have their volume controlled. In this implementation this is only to reset whether * VolumePanel should display remote volumes */ private void postReevaluateRemote() { sendMsg(mAudioHandler, MSG_REEVALUATE_REMOTE, SENDMSG_QUEUE, 0, 0, null, 0); } private void onReevaluateRemote() { if (DEBUG_VOL) { Log.w(TAG, "onReevaluateRemote()"); } // is there a registered RemoteControlClient that is handling remote playback boolean hasRemotePlayback = false; synchronized (mRCStack) { Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator(); while(stackIterator.hasNext()) { RemoteControlStackEntry rcse = stackIterator.next(); if (rcse.mPlaybackType == RemoteControlClient.PLAYBACK_TYPE_REMOTE) { hasRemotePlayback = true; break; } } } synchronized (mMainRemote) { if (mHasRemotePlayback != hasRemotePlayback) { mHasRemotePlayback = hasRemotePlayback; mVolumePanel.postRemoteSliderVisibility(hasRemotePlayback); } } } //========================================================================================== // Device orientation //========================================================================================== /** * Handles device configuration changes that may map to a change in the orientation. * This feature is optional, and is defined by the definition and value of the * "ro.audio.monitorOrientation" system property. */ private void handleConfigurationChanged(Context context) { try { // reading new orientation "safely" (i.e. under try catch) in case anything // goes wrong when obtaining resources and configuration int newOrientation = context.getResources().getConfiguration().orientation; if (newOrientation != mDeviceOrientation) { mDeviceOrientation = newOrientation; setOrientationForAudioSystem(); } } catch (Exception e) { Log.e(TAG, "Error retrieving device orientation: " + e); } } private void setOrientationForAudioSystem() { switch (mDeviceOrientation) { case Configuration.ORIENTATION_LANDSCAPE: //Log.i(TAG, "orientation is landscape"); AudioSystem.setParameters("orientation=landscape"); break; case Configuration.ORIENTATION_PORTRAIT: //Log.i(TAG, "orientation is portrait"); AudioSystem.setParameters("orientation=portrait"); break; case Configuration.ORIENTATION_SQUARE: //Log.i(TAG, "orientation is square"); AudioSystem.setParameters("orientation=square"); break; case Configuration.ORIENTATION_UNDEFINED: //Log.i(TAG, "orientation is undefined"); AudioSystem.setParameters("orientation=undefined"); break; default: Log.e(TAG, "Unknown orientation"); } } // Handles request to override default use of A2DP for media. public void setBluetoothA2dpOnInt(boolean on) { synchronized (mBluetoothA2dpEnabledLock) { mBluetoothA2dpEnabled = on; sendMsg(mAudioHandler, MSG_SET_FORCE_USE, SENDMSG_QUEUE, AudioSystem.FOR_MEDIA, mBluetoothA2dpEnabled ? AudioSystem.FORCE_NONE : AudioSystem.FORCE_NO_BT_A2DP, null, 0); } } @Override public void setRingtonePlayer(IRingtonePlayer player) { mContext.enforceCallingOrSelfPermission(REMOTE_AUDIO_PLAYBACK, null); mRingtonePlayer = player; } @Override public IRingtonePlayer getRingtonePlayer() { return mRingtonePlayer; } @Override public AudioRoutesInfo startWatchingRoutes(IAudioRoutesObserver observer) { synchronized (mCurAudioRoutes) { AudioRoutesInfo routes = new AudioRoutesInfo(mCurAudioRoutes); mRoutesObservers.register(observer); return routes; } } @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG); dumpFocusStack(pw); dumpRCStack(pw); dumpRCCStack(pw); dumpStreamStates(pw); pw.println("\nAudio routes:"); pw.print(" mMainType=0x"); pw.println(Integer.toHexString(mCurAudioRoutes.mMainType)); pw.print(" mBluetoothName="); pw.println(mCurAudioRoutes.mBluetoothName); } }
[ "ngiordano75@gmail.com" ]
ngiordano75@gmail.com
99ae300dc144c29600fa1c8a7ceb8a1c2c25c0d1
461491411d2f33256867907529624f8f849b946d
/helpshiftSdkAndroid/build/generated/source/r/androidTest/debug/com/helpshift/test/R.java
6497c100324d035703939da265f4c6db0d7bcda9
[]
no_license
saisheshankc/BangertechDoodhwaala
d7ff93d6f6fe4317ec97d76085e980d087107db6
0ad548621b507afdb95af7efecc756b3e7846287
refs/heads/master
2021-01-10T03:56:26.395526
2016-02-10T08:30:43
2016-02-10T08:30:43
47,325,654
0
1
null
null
null
null
UTF-8
Java
false
false
84,753
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 com.helpshift.test; public final class R { public static final class attr { /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__acceptButtonIconColor=0x7f01000c; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__actionBarCompatTextColorPrimary=0x7f010029; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__actionButtonIconColor=0x7f010006; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__actionButtonNotificationIconColor=0x7f010007; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__actionButtonNotificationTextColor=0x7f010008; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__actionbarCompatItemBaseStyle=0x7f010027; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__actionbarCompatProgressIndicatorStyle=0x7f010028; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__actionbarCompatTitleStyle=0x7f010026; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__adminChatBubbleColor=0x7f010012; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__attachScreenshotActionButtonIcon=0x7f010018; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__attachScreenshotButtonIconColor=0x7f010010; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__buttonCompoundDrawableIconColor=0x7f010009; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__chatBubbleAdminBackground=0x7f01001e; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__chatBubbleSeparatorColor=0x7f010005; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__chatBubbleUserBackground=0x7f01001f; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__contactUsButtonStyle=0x7f010023; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__contentSeparatorColor=0x7f010003; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__conversationActionButtonIcon=0x7f01001a; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__conversationNotificationActionButtonIcon=0x7f01001b; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__csatDialogBackgroundColor=0x7f010014; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__downloadAttachmentButtonIconColor=0x7f010015; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__faqFooterSeparatorColor=0x7f010004; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__faqHelpfulButtonStyle=0x7f010024; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__faqHelpfulButtonTextColor=0x7f01000e; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__faqUnhelpfulButtonStyle=0x7f010025; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__faqUnhelpfulButtonTextColor=0x7f01000f; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__faqsFooterBackgroundColor=0x7f010001; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__faqsListItemStyle=0x7f010022; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__faqsPagerTabStripIndicatorColor=0x7f010000; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__faqsPagerTabStripStyle=0x7f010021; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__launchAttachmentButtonIconColor=0x7f010016; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__messagesTextColor=0x7f010002; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__rejectButtonIconColor=0x7f01000d; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__reviewButtonIconColor=0x7f010011; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__searchActionButtonIcon=0x7f010019; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__searchHighlightColor=0x7f010017; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__searchOnNewConversationDoneActionButtonIcon=0x7f01001d; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__selectableItemBackground=0x7f010020; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__sendMessageButtonActiveIconColor=0x7f01000b; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__sendMessageButtonIconColor=0x7f01000a; /** <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". */ public static final int hs__startConversationActionButtonIcon=0x7f01001c; /** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. */ public static final int hs__userChatBubbleColor=0x7f010013; } public static final class bool { public static final int limit_to_single_line=0x7f060000; } public static final class color { public static final int hs__accept_button_icon_dark=0x7f090000; public static final int hs__accept_button_icon_light=0x7f090001; public static final int hs__actionbar_compat_background_dark=0x7f090002; public static final int hs__actionbar_compat_background_light=0x7f090003; public static final int hs__actionbar_compat_background_light_dark_actionbar=0x7f090004; public static final int hs__actionbar_compat_text_primary_dark=0x7f090005; public static final int hs__actionbar_compat_text_primary_light=0x7f090006; public static final int hs__actionbutton_icon_dark=0x7f090007; public static final int hs__actionbutton_icon_light=0x7f090008; public static final int hs__actionbutton_notification_icon_dark=0x7f090009; public static final int hs__actionbutton_notification_icon_light=0x7f09000a; public static final int hs__actionbutton_notification_text_dark=0x7f09000b; public static final int hs__actionbutton_notification_text_light=0x7f09000c; public static final int hs__admin_chat_bubble_dark=0x7f09000d; public static final int hs__admin_chat_bubble_light=0x7f09000e; public static final int hs__attach_screenshot_button_icon_dark=0x7f09000f; public static final int hs__attach_screenshot_button_icon_light=0x7f090010; public static final int hs__button_compound_drawable_icon_dark=0x7f090011; public static final int hs__button_compound_drawable_icon_light=0x7f090012; public static final int hs__chat_bubble_separator_dark=0x7f090013; public static final int hs__chat_bubble_separator_light=0x7f090014; public static final int hs__csat_dialog_background_color_dark=0x7f090015; public static final int hs__csat_dialog_background_color_light=0x7f090016; public static final int hs__download_attachment_button_icon_dark=0x7f090017; public static final int hs__download_attachment_button_icon_light=0x7f090018; public static final int hs__faq_footer_separator_dark=0x7f090019; public static final int hs__faq_footer_separator_light=0x7f09001a; public static final int hs__launch_attachment_button_icon_dark=0x7f09001b; public static final int hs__launch_attachment_button_icon_light=0x7f09001c; public static final int hs__messages_text_dark=0x7f09001d; public static final int hs__messages_text_light=0x7f09001e; public static final int hs__question_footer_background_dark=0x7f09001f; public static final int hs__question_footer_background_light=0x7f090020; public static final int hs__question_helpful_button_text_dark=0x7f090021; public static final int hs__question_helpful_button_text_light=0x7f090022; public static final int hs__question_unhelpful_button_text_dark=0x7f090023; public static final int hs__question_unhelpful_button_text_light=0x7f090024; public static final int hs__questions_pagertabstrip_background_dark=0x7f090025; public static final int hs__questions_pagertabstrip_background_light=0x7f090026; public static final int hs__questions_pagertabstrip_indicator_dark=0x7f090027; public static final int hs__questions_pagertabstrip_indicator_light=0x7f090028; public static final int hs__questions_pagertabstrip_text_dark=0x7f090029; public static final int hs__questions_pagertabstrip_text_light=0x7f09002a; public static final int hs__reject_button_icon_dark=0x7f09002b; public static final int hs__reject_button_icon_light=0x7f09002c; public static final int hs__review_button_icon_dark=0x7f09002d; public static final int hs__review_button_icon_light=0x7f09002e; public static final int hs__search_highlight_color_dark=0x7f09002f; public static final int hs__search_highlight_color_light=0x7f090030; public static final int hs__send_message_button_active_icon_dark=0x7f090031; public static final int hs__send_message_button_active_icon_light=0x7f090032; public static final int hs__send_message_button_icon_dark=0x7f090033; public static final int hs__send_message_button_icon_light=0x7f090034; public static final int hs__separator_dark=0x7f090035; public static final int hs__separator_light=0x7f090036; public static final int hs__user_chat_bubble_dark=0x7f090037; public static final int hs__user_chat_bubble_light=0x7f090038; } public static final class dimen { public static final int activity_horizontal_margin=0x7f070002; public static final int activity_vertical_margin=0x7f070003; public static final int hs__actionbar_compat_button_home_width=0x7f070004; public static final int hs__actionbar_compat_button_width=0x7f070005; public static final int hs__actionbar_compat_height=0x7f070006; public static final int hs__actionbar_compat_icon_vertical_padding=0x7f070007; public static final int hs__button_padding_right=0x7f070008; public static final int hs__content_wrapper_padding=0x7f070009; public static final int hs__content_wrapper_top_padding=0x7f07000a; public static final int hs__faqs_sync_status_height=0x7f07000b; public static final int hs__listPreferredItemHeightSmall=0x7f07000c; public static final int hs__listPreferredItemPaddingBottom=0x7f07000d; public static final int hs__listPreferredItemPaddingLeft=0x7f07000e; public static final int hs__listPreferredItemPaddingRight=0x7f07000f; public static final int hs__listPreferredItemPaddingTop=0x7f070010; public static final int hs__marginLeft=0x7f070011; public static final int hs__msgActionButtonPadding=0x7f070012; public static final int hs__msgPreferredItemPaddingBottom=0x7f070013; public static final int hs__msgPreferredItemPaddingLeft=0x7f070014; public static final int hs__msgPreferredItemPaddingRight=0x7f070015; public static final int hs__msgPreferredItemPaddingTop=0x7f070016; public static final int hs__msg_timestamp_alpha=0x7f070017; public static final int hs__msg_timestamp_padding=0x7f070018; public static final int hs__question_text_padding=0x7f070019; public static final int hs__tablet_dialog_horizontal_scale=0x7f070000; public static final int hs__tablet_dialog_vertical_scale=0x7f070001; public static final int hs__textSizeSmall=0x7f07001a; } public static final class drawable { public static final int hs__action_back=0x7f020000; public static final int hs__action_cancel=0x7f020001; public static final int hs__action_download=0x7f020002; public static final int hs__action_launch=0x7f020003; public static final int hs__action_new_picture=0x7f020004; public static final int hs__action_no=0x7f020005; public static final int hs__action_review=0x7f020006; public static final int hs__action_search=0x7f020007; public static final int hs__action_yes=0x7f020008; public static final int hs__actionbar_compat_item_focused=0x7f020009; public static final int hs__actionbar_compat_item_pressed=0x7f02000a; public static final int hs__actionbar_compat_selectable_item_background=0x7f02000b; public static final int hs__actionbar_compat_shadow=0x7f02000c; public static final int hs__attach_screenshot_action_button=0x7f02000d; public static final int hs__chat_bubble_admin=0x7f02000e; public static final int hs__chat_bubble_user=0x7f02000f; public static final int hs__chat_new=0x7f020010; public static final int hs__chat_new_icon=0x7f020011; public static final int hs__chat_notif=0x7f020012; public static final int hs__edit_text_compat_background=0x7f020013; public static final int hs__logo=0x7f020014; public static final int hs__notification_badge=0x7f020015; public static final int hs__report_issue=0x7f020016; public static final int hs__screenshot_clear=0x7f020017; public static final int hs__search_on_conversation_done=0x7f020018; public static final int hs__send=0x7f020019; public static final int hs__text_field_compat_activated=0x7f02001a; public static final int hs__text_field_compat_default=0x7f02001b; public static final int hs__text_field_compat_disabled=0x7f02001c; public static final int hs__text_field_compat_disabled_focused=0x7f02001d; public static final int hs__text_field_compat_focused=0x7f02001e; public static final int hs__warning=0x7f02001f; } public static final class id { public static final int additional_feedback=0x7f0a000c; public static final int admin_message=0x7f0a0021; public static final int button_containers=0x7f0a0037; public static final int button_separator=0x7f0a0022; public static final int change=0x7f0a0038; public static final int csat_dislike_msg=0x7f0a0010; public static final int csat_like_msg=0x7f0a0011; public static final int csat_message=0x7f0a000f; public static final int csat_view_stub=0x7f0a001a; public static final int divider=0x7f0a000d; public static final int file_details=0x7f0a001f; public static final int file_info=0x7f0a0020; public static final int horizontal_divider=0x7f0a0036; public static final int hs__action_add_conversation=0x7f0a0047; public static final int hs__action_done=0x7f0a0049; public static final int hs__action_faq_helpful=0x7f0a002c; public static final int hs__action_faq_unhelpful=0x7f0a002d; public static final int hs__action_report_issue=0x7f0a004a; public static final int hs__action_search=0x7f0a0048; public static final int hs__actionbar_compat=0x7f0a0002; public static final int hs__actionbar_compat_home=0x7f0a0004; public static final int hs__actionbar_compat_item_refresh_progress=0x7f0a0000; public static final int hs__actionbar_compat_title=0x7f0a0001; public static final int hs__actionbar_compat_up=0x7f0a0003; public static final int hs__attach_screenshot=0x7f0a0046; public static final int hs__confirmation=0x7f0a0017; public static final int hs__contactUsContainer=0x7f0a002b; public static final int hs__contact_us_btn=0x7f0a0030; public static final int hs__conversationDetail=0x7f0a0023; public static final int hs__conversation_icon=0x7f0a0005; public static final int hs__customViewContainer=0x7f0a0032; public static final int hs__email=0x7f0a0026; public static final int hs__faqs_fragment=0x7f0a0013; public static final int hs__fragment_holder=0x7f0a0008; public static final int hs__fullscreen_custom_content=0x7f0a0044; public static final int hs__helpful_text=0x7f0a0031; public static final int hs__helpshiftActivityFooter=0x7f0a0014; public static final int hs__messageText=0x7f0a001d; public static final int hs__messagesList=0x7f0a0016; public static final int hs__newConversationFooter=0x7f0a0009; public static final int hs__new_conversation=0x7f0a0018; public static final int hs__new_conversation_btn=0x7f0a001b; public static final int hs__notification_badge=0x7f0a0006; public static final int hs__pager_tab_strip=0x7f0a0034; public static final int hs__question=0x7f0a002e; public static final int hs__questionContent=0x7f0a0029; public static final int hs__question_container=0x7f0a0027; public static final int hs__question_fragment=0x7f0a0028; public static final int hs__root=0x7f0a0007; public static final int hs__screenshot=0x7f0a0024; public static final int hs__searchResultActivity=0x7f0a003b; public static final int hs__search_button=0x7f0a0042; public static final int hs__search_query=0x7f0a0040; public static final int hs__search_query_clear=0x7f0a0041; public static final int hs__sectionContainer=0x7f0a003e; public static final int hs__sectionFooter=0x7f0a003f; public static final int hs__sections_pager=0x7f0a0033; public static final int hs__sendMessageBtn=0x7f0a001e; public static final int hs__unhelpful_text=0x7f0a002f; public static final int hs__username=0x7f0a0025; public static final int hs__webViewParent=0x7f0a002a; public static final int hs__webview_main_content=0x7f0a0045; public static final int like_status=0x7f0a000b; public static final int option_text=0x7f0a0012; public static final int progress_indicator=0x7f0a0043; public static final int ratingBar=0x7f0a000a; public static final int relativeLayout1=0x7f0a001c; public static final int report_issue=0x7f0a003a; public static final int screenshotPreview=0x7f0a0035; public static final int search_result_message=0x7f0a003d; public static final int send=0x7f0a0039; public static final int send_anyway_button=0x7f0a003c; public static final int submit=0x7f0a000e; public static final int textView1=0x7f0a0019; public static final int user_message=0x7f0a0015; } public static final class integer { public static final int hs__chat_max_lines=0x7f0b0000; public static final int hs__conversation_detail_lines=0x7f0b0001; public static final int hs__issue_description_min_chars=0x7f0b0002; } public static final class layout { public static final int hs__actionbar_compat=0x7f030000; public static final int hs__actionbar_compat_home=0x7f030001; public static final int hs__actionbar_indeterminate_progress=0x7f030002; public static final int hs__badge_layout=0x7f030003; public static final int hs__conversation=0x7f030004; public static final int hs__csat_dialog=0x7f030005; public static final int hs__csat_holder=0x7f030006; public static final int hs__csat_view=0x7f030007; public static final int hs__faqs=0x7f030008; public static final int hs__local_msg_request_screenshot=0x7f030009; public static final int hs__messages_fragment=0x7f03000a; public static final int hs__messages_list_footer=0x7f03000b; public static final int hs__msg_attachment_generic=0x7f03000c; public static final int hs__msg_attachment_image=0x7f03000d; public static final int hs__msg_confirmation_box=0x7f03000e; public static final int hs__msg_confirmation_status=0x7f03000f; public static final int hs__msg_request_screenshot=0x7f030010; public static final int hs__msg_review_accepted=0x7f030011; public static final int hs__msg_review_request=0x7f030012; public static final int hs__msg_screenshot_status=0x7f030013; public static final int hs__msg_txt_admin=0x7f030014; public static final int hs__msg_txt_user=0x7f030015; public static final int hs__new_conversation_fragment=0x7f030016; public static final int hs__no_faqs=0x7f030017; public static final int hs__question=0x7f030018; public static final int hs__question_fragment=0x7f030019; public static final int hs__questions_list=0x7f03001a; public static final int hs__screenshot_preview=0x7f03001b; public static final int hs__search_list_footer=0x7f03001c; public static final int hs__search_result_activity=0x7f03001d; public static final int hs__search_result_footer=0x7f03001e; public static final int hs__search_result_header=0x7f03001f; public static final int hs__section=0x7f030020; public static final int hs__simple_list_item_1=0x7f030021; public static final int hs__simple_list_item_3=0x7f030022; public static final int hs__simple_search_view=0x7f030023; public static final int hs__video_loading_progress=0x7f030024; public static final int hs__webview_custom_content=0x7f030025; } public static final class menu { public static final int hs__actionbar_indeterminate_progress=0x7f0c0000; public static final int hs__add_conversation_menu=0x7f0c0001; public static final int hs__faqs_fragment=0x7f0c0002; public static final int hs__messages_menu=0x7f0c0003; public static final int hs__search_on_conversation=0x7f0c0004; public static final int hs__show_conversation=0x7f0c0005; } public static final class plurals { public static final int hs__csat_rating_value=0x7f040000; public static final int hs__notification_content_title=0x7f040001; } public static final class string { public static final int hs__attach_screenshot_btn=0x7f050000; public static final int hs__ca_msg=0x7f050001; public static final int hs__change_btn=0x7f050002; public static final int hs__chat_hint=0x7f050003; public static final int hs__confirmation_footer_msg=0x7f050004; public static final int hs__confirmation_msg=0x7f050005; public static final int hs__contact_us_btn=0x7f050006; public static final int hs__conversation_detail_error=0x7f050007; public static final int hs__conversation_end_msg=0x7f050008; public static final int hs__conversation_header=0x7f050009; public static final int hs__conversation_started_message=0x7f05000a; public static final int hs__could_not_open_attachment_msg=0x7f05000b; public static final int hs__could_not_reach_support_msg=0x7f05000c; public static final int hs__cr_msg=0x7f05000d; public static final int hs__csat_additonal_feedback_message=0x7f05000e; public static final int hs__csat_dislike_message=0x7f05000f; public static final int hs__csat_like_message=0x7f050010; public static final int hs__csat_message=0x7f050011; public static final int hs__csat_option_message=0x7f050012; public static final int hs__csat_ratingbar=0x7f050013; public static final int hs__csat_submit_toast=0x7f050014; public static final int hs__data_not_found_msg=0x7f050015; public static final int hs__default_notification_content_title=0x7f050016; public static final int hs__description_invalid_length_error=0x7f050017; public static final int hs__dm_video_loading=0x7f050018; public static final int hs__done_btn=0x7f050019; public static final int hs__email_hint=0x7f05001a; public static final int hs__email_required_hint=0x7f05001b; public static final int hs__empty_section=0x7f05001c; public static final int hs__faq_header=0x7f05001d; public static final int hs__faqs_search_footer=0x7f05001e; public static final int hs__feedback_button=0x7f05001f; public static final int hs__file_not_found_msg=0x7f050020; public static final int hs__file_type_audio=0x7f050021; public static final int hs__file_type_csv=0x7f050022; public static final int hs__file_type_ms_office=0x7f050023; public static final int hs__file_type_pdf=0x7f050024; public static final int hs__file_type_rtf=0x7f050025; public static final int hs__file_type_text=0x7f050026; public static final int hs__file_type_unknown=0x7f050027; public static final int hs__file_type_video=0x7f050028; public static final int hs__help_header=0x7f050029; public static final int hs__invalid_description_error=0x7f05002a; public static final int hs__invalid_email_error=0x7f05002b; public static final int hs__mark_helpful_toast=0x7f05002c; public static final int hs__mark_no=0x7f05002d; public static final int hs__mark_unhelpful_toast=0x7f05002e; public static final int hs__mark_yes=0x7f05002f; public static final int hs__mark_yes_no_question=0x7f050030; public static final int hs__network_error_msg=0x7f050031; public static final int hs__network_unavailable_msg=0x7f050032; public static final int hs__new_conversation_btn=0x7f050033; public static final int hs__new_conversation_header=0x7f050034; public static final int hs__new_conversation_hint=0x7f050035; public static final int hs__notification_content_text=0x7f050036; public static final int hs__question_header=0x7f050037; public static final int hs__question_helpful_message=0x7f050038; public static final int hs__question_unhelpful_message=0x7f050039; public static final int hs__rate_button=0x7f05003a; public static final int hs__remove_screenshot_btn=0x7f05003b; public static final int hs__review_accepted_message=0x7f05003c; public static final int hs__review_close_button=0x7f05003d; public static final int hs__review_message=0x7f05003e; public static final int hs__review_request_message=0x7f05003f; public static final int hs__review_title=0x7f050040; public static final int hs__screen_type=0x7f050055; public static final int hs__screenshot_add=0x7f050041; public static final int hs__screenshot_cloud_attach_error=0x7f050042; public static final int hs__screenshot_limit_error=0x7f050043; public static final int hs__screenshot_remove=0x7f050044; public static final int hs__screenshot_sent_msg=0x7f050045; public static final int hs__screenshot_upload_error_msg=0x7f050046; public static final int hs__search_footer=0x7f050047; public static final int hs__search_hint=0x7f050048; public static final int hs__search_result_message=0x7f050049; public static final int hs__search_result_title=0x7f05004a; public static final int hs__search_title=0x7f05004b; public static final int hs__send_anyway=0x7f05004c; public static final int hs__send_msg_btn=0x7f05004d; public static final int hs__sending_fail_msg=0x7f05004e; public static final int hs__sending_msg=0x7f05004f; public static final int hs__solved_btn=0x7f050050; public static final int hs__submit_conversation_btn=0x7f050051; public static final int hs__unsolved_btn=0x7f050052; public static final int hs__username_blank_error=0x7f050053; public static final int hs__username_hint=0x7f050054; } public static final class style { public static final int HSActionBarCompatBackground=0x7f080004; public static final int HSActionBarCompatBackground_Dark=0x7f080005; public static final int HSActionBarCompatBackground_Light=0x7f080006; public static final int HSActionBarCompatBackground_LightDarkActionBar=0x7f080007; public static final int HSActionBarCompatItemBase=0x7f080008; public static final int HSActionBarCompatProgressIndicator=0x7f080009; public static final int HSActionBarCompatTitle=0x7f08000a; public static final int HSActionBarCompatTitle_Dark=0x7f08000b; public static final int HSActionBarCompatTitle_Light=0x7f08000c; public static final int HSDivider=0x7f08000d; public static final int HSEditTextCompat=0x7f08000e; public static final int Helpshift=0x7f08000f; public static final int Helpshift_Compat_Theme_Dark=0x7f080010; public static final int Helpshift_Compat_Theme_Light=0x7f080011; public static final int Helpshift_Compat_Theme_Light_DarkActionBar=0x7f080012; public static final int Helpshift_Style=0x7f080013; public static final int Helpshift_Style_ContactUsButton=0x7f080014; public static final int Helpshift_Style_FaqHelpfulButton=0x7f080015; public static final int Helpshift_Style_FaqUnhelpfulButton=0x7f080016; public static final int Helpshift_Style_FaqsListItem=0x7f080017; public static final int Helpshift_Style_QuestionsPagerTabStrip=0x7f080018; public static final int Helpshift_Theme_Activity=0x7f080000; public static final int Helpshift_Theme_Base=0x7f080019; public static final int Helpshift_Theme_Dark=0x7f080001; public static final int Helpshift_Theme_Dialog=0x7f08001a; public static final int Helpshift_Theme_Light=0x7f080002; public static final int Helpshift_Theme_Light_DarkActionBar=0x7f080003; } public static final class styleable { /** Attributes that can be used with a HelpshiftTheme_Activity. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__acceptButtonIconColor com.helpshift.test:hs__acceptButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__actionButtonIconColor com.helpshift.test:hs__actionButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__actionButtonNotificationIconColor com.helpshift.test:hs__actionButtonNotificationIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__actionButtonNotificationTextColor com.helpshift.test:hs__actionButtonNotificationTextColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__adminChatBubbleColor com.helpshift.test:hs__adminChatBubbleColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__attachScreenshotActionButtonIcon com.helpshift.test:hs__attachScreenshotActionButtonIcon}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__attachScreenshotButtonIconColor com.helpshift.test:hs__attachScreenshotButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__buttonCompoundDrawableIconColor com.helpshift.test:hs__buttonCompoundDrawableIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__chatBubbleAdminBackground com.helpshift.test:hs__chatBubbleAdminBackground}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__chatBubbleSeparatorColor com.helpshift.test:hs__chatBubbleSeparatorColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__chatBubbleUserBackground com.helpshift.test:hs__chatBubbleUserBackground}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__contactUsButtonStyle com.helpshift.test:hs__contactUsButtonStyle}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__contentSeparatorColor com.helpshift.test:hs__contentSeparatorColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__conversationActionButtonIcon com.helpshift.test:hs__conversationActionButtonIcon}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__conversationNotificationActionButtonIcon com.helpshift.test:hs__conversationNotificationActionButtonIcon}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__csatDialogBackgroundColor com.helpshift.test:hs__csatDialogBackgroundColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__downloadAttachmentButtonIconColor com.helpshift.test:hs__downloadAttachmentButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqFooterSeparatorColor com.helpshift.test:hs__faqFooterSeparatorColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqHelpfulButtonStyle com.helpshift.test:hs__faqHelpfulButtonStyle}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqHelpfulButtonTextColor com.helpshift.test:hs__faqHelpfulButtonTextColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqUnhelpfulButtonStyle com.helpshift.test:hs__faqUnhelpfulButtonStyle}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqUnhelpfulButtonTextColor com.helpshift.test:hs__faqUnhelpfulButtonTextColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqsFooterBackgroundColor com.helpshift.test:hs__faqsFooterBackgroundColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqsListItemStyle com.helpshift.test:hs__faqsListItemStyle}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqsPagerTabStripIndicatorColor com.helpshift.test:hs__faqsPagerTabStripIndicatorColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__faqsPagerTabStripStyle com.helpshift.test:hs__faqsPagerTabStripStyle}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__launchAttachmentButtonIconColor com.helpshift.test:hs__launchAttachmentButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__messagesTextColor com.helpshift.test:hs__messagesTextColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__rejectButtonIconColor com.helpshift.test:hs__rejectButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__reviewButtonIconColor com.helpshift.test:hs__reviewButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__searchActionButtonIcon com.helpshift.test:hs__searchActionButtonIcon}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__searchHighlightColor com.helpshift.test:hs__searchHighlightColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__searchOnNewConversationDoneActionButtonIcon com.helpshift.test:hs__searchOnNewConversationDoneActionButtonIcon}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__selectableItemBackground com.helpshift.test:hs__selectableItemBackground}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__sendMessageButtonActiveIconColor com.helpshift.test:hs__sendMessageButtonActiveIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__sendMessageButtonIconColor com.helpshift.test:hs__sendMessageButtonIconColor}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__startConversationActionButtonIcon com.helpshift.test:hs__startConversationActionButtonIcon}</code></td><td></td></tr> <tr><td><code>{@link #HelpshiftTheme_Activity_hs__userChatBubbleColor com.helpshift.test:hs__userChatBubbleColor}</code></td><td></td></tr> </table> @see #HelpshiftTheme_Activity_hs__acceptButtonIconColor @see #HelpshiftTheme_Activity_hs__actionButtonIconColor @see #HelpshiftTheme_Activity_hs__actionButtonNotificationIconColor @see #HelpshiftTheme_Activity_hs__actionButtonNotificationTextColor @see #HelpshiftTheme_Activity_hs__adminChatBubbleColor @see #HelpshiftTheme_Activity_hs__attachScreenshotActionButtonIcon @see #HelpshiftTheme_Activity_hs__attachScreenshotButtonIconColor @see #HelpshiftTheme_Activity_hs__buttonCompoundDrawableIconColor @see #HelpshiftTheme_Activity_hs__chatBubbleAdminBackground @see #HelpshiftTheme_Activity_hs__chatBubbleSeparatorColor @see #HelpshiftTheme_Activity_hs__chatBubbleUserBackground @see #HelpshiftTheme_Activity_hs__contactUsButtonStyle @see #HelpshiftTheme_Activity_hs__contentSeparatorColor @see #HelpshiftTheme_Activity_hs__conversationActionButtonIcon @see #HelpshiftTheme_Activity_hs__conversationNotificationActionButtonIcon @see #HelpshiftTheme_Activity_hs__csatDialogBackgroundColor @see #HelpshiftTheme_Activity_hs__downloadAttachmentButtonIconColor @see #HelpshiftTheme_Activity_hs__faqFooterSeparatorColor @see #HelpshiftTheme_Activity_hs__faqHelpfulButtonStyle @see #HelpshiftTheme_Activity_hs__faqHelpfulButtonTextColor @see #HelpshiftTheme_Activity_hs__faqUnhelpfulButtonStyle @see #HelpshiftTheme_Activity_hs__faqUnhelpfulButtonTextColor @see #HelpshiftTheme_Activity_hs__faqsFooterBackgroundColor @see #HelpshiftTheme_Activity_hs__faqsListItemStyle @see #HelpshiftTheme_Activity_hs__faqsPagerTabStripIndicatorColor @see #HelpshiftTheme_Activity_hs__faqsPagerTabStripStyle @see #HelpshiftTheme_Activity_hs__launchAttachmentButtonIconColor @see #HelpshiftTheme_Activity_hs__messagesTextColor @see #HelpshiftTheme_Activity_hs__rejectButtonIconColor @see #HelpshiftTheme_Activity_hs__reviewButtonIconColor @see #HelpshiftTheme_Activity_hs__searchActionButtonIcon @see #HelpshiftTheme_Activity_hs__searchHighlightColor @see #HelpshiftTheme_Activity_hs__searchOnNewConversationDoneActionButtonIcon @see #HelpshiftTheme_Activity_hs__selectableItemBackground @see #HelpshiftTheme_Activity_hs__sendMessageButtonActiveIconColor @see #HelpshiftTheme_Activity_hs__sendMessageButtonIconColor @see #HelpshiftTheme_Activity_hs__startConversationActionButtonIcon @see #HelpshiftTheme_Activity_hs__userChatBubbleColor */ public static final int[] HelpshiftTheme_Activity = { 0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003, 0x7f010004, 0x7f010005, 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01000f, 0x7f010010, 0x7f010011, 0x7f010012, 0x7f010013, 0x7f010014, 0x7f010015, 0x7f010016, 0x7f010017, 0x7f010018, 0x7f010019, 0x7f01001a, 0x7f01001b, 0x7f01001c, 0x7f01001d, 0x7f01001e, 0x7f01001f, 0x7f010020, 0x7f010021, 0x7f010022, 0x7f010023, 0x7f010024, 0x7f010025 }; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__acceptButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__acceptButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__acceptButtonIconColor = 12; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__actionButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__actionButtonIconColor = 6; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionButtonNotificationIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__actionButtonNotificationIconColor */ public static final int HelpshiftTheme_Activity_hs__actionButtonNotificationIconColor = 7; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionButtonNotificationTextColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__actionButtonNotificationTextColor */ public static final int HelpshiftTheme_Activity_hs__actionButtonNotificationTextColor = 8; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__adminChatBubbleColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__adminChatBubbleColor */ public static final int HelpshiftTheme_Activity_hs__adminChatBubbleColor = 18; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__attachScreenshotActionButtonIcon} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__attachScreenshotActionButtonIcon */ public static final int HelpshiftTheme_Activity_hs__attachScreenshotActionButtonIcon = 24; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__attachScreenshotButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__attachScreenshotButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__attachScreenshotButtonIconColor = 16; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__buttonCompoundDrawableIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__buttonCompoundDrawableIconColor */ public static final int HelpshiftTheme_Activity_hs__buttonCompoundDrawableIconColor = 9; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__chatBubbleAdminBackground} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__chatBubbleAdminBackground */ public static final int HelpshiftTheme_Activity_hs__chatBubbleAdminBackground = 30; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__chatBubbleSeparatorColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__chatBubbleSeparatorColor */ public static final int HelpshiftTheme_Activity_hs__chatBubbleSeparatorColor = 5; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__chatBubbleUserBackground} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__chatBubbleUserBackground */ public static final int HelpshiftTheme_Activity_hs__chatBubbleUserBackground = 31; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__contactUsButtonStyle} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__contactUsButtonStyle */ public static final int HelpshiftTheme_Activity_hs__contactUsButtonStyle = 35; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__contentSeparatorColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__contentSeparatorColor */ public static final int HelpshiftTheme_Activity_hs__contentSeparatorColor = 3; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__conversationActionButtonIcon} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__conversationActionButtonIcon */ public static final int HelpshiftTheme_Activity_hs__conversationActionButtonIcon = 26; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__conversationNotificationActionButtonIcon} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__conversationNotificationActionButtonIcon */ public static final int HelpshiftTheme_Activity_hs__conversationNotificationActionButtonIcon = 27; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__csatDialogBackgroundColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__csatDialogBackgroundColor */ public static final int HelpshiftTheme_Activity_hs__csatDialogBackgroundColor = 20; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__downloadAttachmentButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__downloadAttachmentButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__downloadAttachmentButtonIconColor = 21; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqFooterSeparatorColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__faqFooterSeparatorColor */ public static final int HelpshiftTheme_Activity_hs__faqFooterSeparatorColor = 4; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqHelpfulButtonStyle} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__faqHelpfulButtonStyle */ public static final int HelpshiftTheme_Activity_hs__faqHelpfulButtonStyle = 36; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqHelpfulButtonTextColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__faqHelpfulButtonTextColor */ public static final int HelpshiftTheme_Activity_hs__faqHelpfulButtonTextColor = 14; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqUnhelpfulButtonStyle} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__faqUnhelpfulButtonStyle */ public static final int HelpshiftTheme_Activity_hs__faqUnhelpfulButtonStyle = 37; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqUnhelpfulButtonTextColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__faqUnhelpfulButtonTextColor */ public static final int HelpshiftTheme_Activity_hs__faqUnhelpfulButtonTextColor = 15; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqsFooterBackgroundColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__faqsFooterBackgroundColor */ public static final int HelpshiftTheme_Activity_hs__faqsFooterBackgroundColor = 1; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqsListItemStyle} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__faqsListItemStyle */ public static final int HelpshiftTheme_Activity_hs__faqsListItemStyle = 34; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqsPagerTabStripIndicatorColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__faqsPagerTabStripIndicatorColor */ public static final int HelpshiftTheme_Activity_hs__faqsPagerTabStripIndicatorColor = 0; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__faqsPagerTabStripStyle} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__faqsPagerTabStripStyle */ public static final int HelpshiftTheme_Activity_hs__faqsPagerTabStripStyle = 33; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__launchAttachmentButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__launchAttachmentButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__launchAttachmentButtonIconColor = 22; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__messagesTextColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__messagesTextColor */ public static final int HelpshiftTheme_Activity_hs__messagesTextColor = 2; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__rejectButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__rejectButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__rejectButtonIconColor = 13; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__reviewButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__reviewButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__reviewButtonIconColor = 17; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__searchActionButtonIcon} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__searchActionButtonIcon */ public static final int HelpshiftTheme_Activity_hs__searchActionButtonIcon = 25; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__searchHighlightColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__searchHighlightColor */ public static final int HelpshiftTheme_Activity_hs__searchHighlightColor = 23; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__searchOnNewConversationDoneActionButtonIcon} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__searchOnNewConversationDoneActionButtonIcon */ public static final int HelpshiftTheme_Activity_hs__searchOnNewConversationDoneActionButtonIcon = 29; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__selectableItemBackground} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__selectableItemBackground */ public static final int HelpshiftTheme_Activity_hs__selectableItemBackground = 32; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__sendMessageButtonActiveIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__sendMessageButtonActiveIconColor */ public static final int HelpshiftTheme_Activity_hs__sendMessageButtonActiveIconColor = 11; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__sendMessageButtonIconColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__sendMessageButtonIconColor */ public static final int HelpshiftTheme_Activity_hs__sendMessageButtonIconColor = 10; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__startConversationActionButtonIcon} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__startConversationActionButtonIcon */ public static final int HelpshiftTheme_Activity_hs__startConversationActionButtonIcon = 28; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__userChatBubbleColor} attribute's value can be found in the {@link #HelpshiftTheme_Activity} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__userChatBubbleColor */ public static final int HelpshiftTheme_Activity_hs__userChatBubbleColor = 19; /** Attributes that can be used with a Theme_HelpshiftCompat. <p>Includes the following attributes:</p> <table> <colgroup align="left" /> <colgroup align="left" /> <tr><th>Attribute</th><th>Description</th></tr> <tr><td><code>{@link #Theme_HelpshiftCompat_hs__actionBarCompatTextColorPrimary com.helpshift.test:hs__actionBarCompatTextColorPrimary}</code></td><td></td></tr> <tr><td><code>{@link #Theme_HelpshiftCompat_hs__actionbarCompatItemBaseStyle com.helpshift.test:hs__actionbarCompatItemBaseStyle}</code></td><td></td></tr> <tr><td><code>{@link #Theme_HelpshiftCompat_hs__actionbarCompatProgressIndicatorStyle com.helpshift.test:hs__actionbarCompatProgressIndicatorStyle}</code></td><td></td></tr> <tr><td><code>{@link #Theme_HelpshiftCompat_hs__actionbarCompatTitleStyle com.helpshift.test:hs__actionbarCompatTitleStyle}</code></td><td></td></tr> </table> @see #Theme_HelpshiftCompat_hs__actionBarCompatTextColorPrimary @see #Theme_HelpshiftCompat_hs__actionbarCompatItemBaseStyle @see #Theme_HelpshiftCompat_hs__actionbarCompatProgressIndicatorStyle @see #Theme_HelpshiftCompat_hs__actionbarCompatTitleStyle */ public static final int[] Theme_HelpshiftCompat = { 0x7f010026, 0x7f010027, 0x7f010028, 0x7f010029 }; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionBarCompatTextColorPrimary} attribute's value can be found in the {@link #Theme_HelpshiftCompat} array. <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>", "<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>". <p>This may also be a reference to a resource (in the form "<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or theme attribute (in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>") containing a value of this type. @attr name com.helpshift.test:hs__actionBarCompatTextColorPrimary */ public static final int Theme_HelpshiftCompat_hs__actionBarCompatTextColorPrimary = 3; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionbarCompatItemBaseStyle} attribute's value can be found in the {@link #Theme_HelpshiftCompat} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__actionbarCompatItemBaseStyle */ public static final int Theme_HelpshiftCompat_hs__actionbarCompatItemBaseStyle = 1; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionbarCompatProgressIndicatorStyle} attribute's value can be found in the {@link #Theme_HelpshiftCompat} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__actionbarCompatProgressIndicatorStyle */ public static final int Theme_HelpshiftCompat_hs__actionbarCompatProgressIndicatorStyle = 2; /** <p>This symbol is the offset where the {@link com.helpshift.test.R.attr#hs__actionbarCompatTitleStyle} attribute's value can be found in the {@link #Theme_HelpshiftCompat} array. <p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>" or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>". @attr name com.helpshift.test:hs__actionbarCompatTitleStyle */ public static final int Theme_HelpshiftCompat_hs__actionbarCompatTitleStyle = 0; }; }
[ "saisheshan13@gmail.com" ]
saisheshan13@gmail.com
437876656e61f49b24332ff4193e9dff9330340a
8328141b22f3d7f47a5191d5783dbfd73da87dd7
/app/src/main/java/com/example/fuentesmadrid/MapsActivity.java
ea653f7ca4617df28bcd336a4640e08d0c68477b
[]
no_license
MarioLopezz/Fuentes-Madrid
9acd924944b3e569d68de8279dfb5b058301954c
5251a0679ef28e0b988be0dccef6a3b2642de69d
refs/heads/master
2020-06-04T02:27:30.984848
2019-06-13T21:37:11
2019-06-13T21:39:49
191,834,552
2
0
null
null
null
null
UTF-8
Java
false
false
6,665
java
package com.example.fuentesmadrid; import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.example.fuentesmadrid.Model.Fountain; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private static final int REQUEST_CODE = 1000; private FusedLocationProviderClient fusedLocationClient; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CODE: if (grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else if (grantResults[0]==PackageManager.PERMISSION_DENIED){ } } break; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); } else { if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); return; } } mMap.setMyLocationEnabled(true); fusedLocationClient = LocationServices.getFusedLocationProviderClient(this); fusedLocationClient.getLastLocation() .addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { double lat= location.getLatitude(); double lon = location.getLongitude(); LatLng currentLocation = new LatLng(lat,lon); CameraUpdate center= CameraUpdateFactory.newLatLng(currentLocation); CameraUpdate zoom=CameraUpdateFactory.zoomTo(15); mMap.moveCamera(center); mMap.animateCamera(zoom); }else{ LatLng madrid = new LatLng(40.416905, -3.703563); CameraUpdate center= CameraUpdateFactory.newLatLng(madrid); CameraUpdate zoom=CameraUpdateFactory.zoomTo(15); mMap.moveCamera(center); mMap.animateCamera(zoom); } } }); parseXML(); } private void parseXML(){ XmlPullParserFactory parserFactory; try { parserFactory= XmlPullParserFactory.newInstance(); XmlPullParser parser= parserFactory.newPullParser(); InputStream is= getResources().openRawResource(R.raw.fuentes2019); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false); parser.setInput(is,null); getFountainList(parser); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void getFountainList(XmlPullParser parser) throws XmlPullParserException, IOException { ArrayList<Fountain> fountains = new ArrayList<>(); int eventType=parser.getEventType(); Fountain fountain=null; while (eventType!=XmlPullParser.END_DOCUMENT){ String parserName=null; switch (eventType){ case XmlPullParser.START_TAG: parserName=parser.getName(); if("entry".equals(parserName)){ fountain=new Fountain(); fountains.add(fountain); } else if(fountain!=null){ if("title".equals(parserName)) { fountain.setTitle(parser.nextText()); }else if("geo:lat".equals(parserName)){ fountain.setGeolat(parser.nextText()); } else if("geo:long".equals(parserName)) { fountain.setGeolong(parser.nextText()); } } break; } eventType=parser.next(); } for (Fountain fountain2: fountains) { LatLng fountainLocation = new LatLng(Double.parseDouble(fountain2.getGeolat()),Double.parseDouble(fountain2.getGeolong())); mMap.addMarker(new MarkerOptions().position(fountainLocation).title(""+fountain2.getTitle())); } } }
[ "mariolopezzbueno@gmail.com" ]
mariolopezzbueno@gmail.com
1453139a362dcd81a7d1f85bee76badb2261ef4d
b722fd3c42d920e18b52f1dd9f8ce90c661453af
/src/sample/Database.java
48a978c7dc945362bb925de551583b3180bf8d8d
[]
no_license
EvanArno/RoomManager
dac7797af50233a64090e6820e7adc24f5145ba1
f467f30a6adf4f5c2d4e9bf7b6ecabab8f935132
refs/heads/master
2022-11-28T08:54:06.073442
2020-08-12T13:17:57
2020-08-12T13:17:57
287,015,732
0
0
null
null
null
null
UTF-8
Java
false
false
1,324
java
package sample; import java.sql.*; public class Database { private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>(); public static void link() throws Exception{ String strCon = "jdbc:mysql://127.0.0.1:3306/dormitory"; //System.out.println("正在连接数据库..."); Class.forName("com.mysql.jdbc.Driver"); Connection con; con = DriverManager.getConnection(strCon,"root","123456"); if(con != null){ //System.out.println("连接成功"); } } public static Connection getConnection() { String strCon = "jdbc:mysql://127.0.0.1:3306/dormitory"; Connection conn=threadLocal.get();// 从线程中获得数据库连接 if (conn == null) {// 没有可用的数据库连接 try { conn = DriverManager.getConnection(strCon, "root", "123456");// 创建新的数据库连接 threadLocal.set(conn);// 将数据库连接保存到线程中 } catch (SQLException e) { e.printStackTrace(); } } //System.out.println("数据库连接成功 "); //控制台信息查看 return conn; } public static String getdata(String sql){ String a = ""; return a; } }
[ "zlxkchv@163.com" ]
zlxkchv@163.com
70960645a1bacfec2214a6cb0e2e2ba1bf00c8bc
6cb04581d450e5c037d67e6174275d2b7a6eb228
/src/com/polytech/devintandroid/HelpActivity.java
d216425a24f66a6a0f923e78d97016e725ac7e9f
[]
no_license
fabienpinel/DevintAndroid
3fc7c57d5b825ede5c4cba08486768217c819ca6
ddfb368407188579f8c9b664ebcd3adf7739c3f0
refs/heads/master
2016-09-06T10:22:42.283352
2014-04-10T12:27:40
2014-04-10T12:27:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,334
java
package com.polytech.devintandroid; import java.util.Locale; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; public class HelpActivity extends Activity implements OnInitListener { LinearLayout layout = null; TextView helptext; private TextToSpeech mTts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layout = (LinearLayout) LinearLayout.inflate(this, R.layout.activity_help, null); loadSettings(); setContentView(layout); init(); helptext = (TextView) findViewById(R.id.texthelp); Button playHelpButton = (Button) layout .findViewById(R.id.playHelpButton); playHelpButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playThisText(helptext.getText().toString()); } }); } public void loadSettings() { SharedPreferences settings = getSharedPreferences("prefs", Context.MODE_PRIVATE); TextView titre = (TextView) layout.findViewById(R.id.titleHelp); switch (settings.getInt("titreFond", 0)) { case OptionsActivity.THEME_BLEU: titre.setBackgroundColor(Color.parseColor("#0000FF")); break; case OptionsActivity.THEME_ROUGE: titre.setBackgroundColor(Color.parseColor("#FF0000")); break; default: titre.setBackgroundColor(Color.parseColor("#0000FF")); } } public void init() { Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, 0x01); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0x01) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // Succès, au moins un moteur de TTS à été trouvé, on // l'instancie mTts = new TextToSpeech(this, this); if (mTts.isLanguageAvailable(Locale.FRANCE) == TextToSpeech.LANG_COUNTRY_AVAILABLE) { mTts.setLanguage(Locale.FRANCE); } mTts.setSpeechRate(1); // 1 est la valeur par défaut. Une valeur // inférieure rendra l'énonciation plus // lente, une valeur supérieure la // rendra plus rapide. mTts.setPitch(1); // 1 est la valeur par défaut. Une valeur // inférieure rendra l'énonciation plus // grave, une valeur supérieure la rendra // plus aigue. } else { // Echec, aucun moteur n'a été trouvé, on propose à // l'utilisateur d'en installer un depuis le Market Intent installIntent = new Intent(); installIntent .setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installIntent); } } } public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { Toast toast = Toast.makeText(getApplicationContext(), "TTS ready", Toast.LENGTH_SHORT); toast.show(); } } public void playThisText(String toPlay) { mTts.speak(toPlay, TextToSpeech.QUEUE_FLUSH, null); } }
[ "pinel.fabien@gmail.com" ]
pinel.fabien@gmail.com
787f40b31a0becade94e578ba4f12e4c1c3b3179
6402338098947f597731fc56058d77bf4e9229ec
/src/com/ery/hadoop/hq/ws/Constant.java
624e5b1fbe4c79e4467efc4bd2fb2153d24e30cb
[]
no_license
hans511002/mrddx-web
57f582e4863899df9869ba9887b7c468edceb7cc
4a907fa0e0db13e7358a5b149a6b4c1058ac124c
refs/heads/master
2021-01-18T16:51:20.332247
2017-07-18T06:39:07
2017-07-18T06:39:07
86,774,312
0
0
null
null
null
null
UTF-8
Java
false
false
5,250
java
package com.ery.hadoop.hq.ws; import java.util.HashMap; import java.util.Map; public class Constant { public static enum ERROR { error_user(1000, "用户信息认证失败!"), error_type(1001, "参数类型错误(应该为map)!"), error_ruleId_type(1002, "查询规则id类型错误!"), error_param(1003, "simpleMap参数错误,为空或者参数数量为0!"), error_noruleCode(1004, "请求数据中没有编码[ruleCode]!"), error_ruleCode(1005, "请求数据中规则编码[ruleCode]错误!"), error_noqryrule( 1006, "不存在请求的查询规则!"), error_noauthority(1007, "此用户对规则无访问权限!"), error_decoderule(1008, "规则解析失败!"), error_paramvalid(1009, "参数有效性错误!"), error_noqryruleCode(1010, "请求数据中没有编码[QUERY_RULE_ID]!"), ERROR_HB_TABLE_NAME(1010, "表名称不正确!"), ERROR_DATA_SOURCE_ID( 1011, "数据源不正确!"), ERROR_QUERY_RETURN_COUNT(1012, "取值范围不正确!"), ERROR_QUERY_RULE_ERROR(1013, "规则不存在或者规则加载无效!"), ERROR_MODIFY_HB_TABLE_DATA(1020, "修改数据不能为空!"), ERROR_MODIFY_HB_TABLE_DATA_TYPE( 1021, "修改数据josn格式不正确!"), ERROR_MODIFY_HB_TABLE_DATA_FIAL(1022, "修改数据失败!"), ERROR_MODIFY_HB_TABLE_DATA_OTHER(1023, "修改数据,其他错误!"), ERROR_ADD_HB_TABLE_DATA(1030, "新增数据不能为空!"), ERROR_ADD_HB_TABLE_DATA_TYPE(1031, "新增数据josn格式不正确!"), ERROR_ADD_HB_TABLE_DATA_FIAL( 1032, "新增数据失败!"), ERROR_ADD_HB_TABLE_DATA_OTHER(1033, "新增数据,其他错误!"), error_other(10000, "其他错误!"),error_tablename(10000, "表名错误"), ; public int code; public String msg; ERROR(int code, String msg) { this.code = code; this.msg = msg; } public String toString() { return "[" + code + "]" + msg; } }; // 对表参数名称 public static final String HT_NAME = "HT_NAME"; public static final String SOURCE_ID = "SOURCE_ID"; public static final String START_KEY = "START_KEY"; public static final String END_KEY = "END_KEY"; public static final String COUNT = "COUNT"; // 修改数据参数 public static final String ITEM_DATA = "ITEM_DATA"; public static final String VALUES = "VALUES"; public static final String STATUS = "STATUS"; public static final String CODE = "CODE"; // 响应参数名称 public static String RESULT_NAME = "result"; public static String VALUES_NAME = "values"; public static String ENFIELD_NAME = "enField"; public static String CHFIELD_NAME = "chField"; public static String ROWKEY_NAME = "ROWID"; public static String CURRENTCOUNT_NAME = "currentCount"; public static String RESPONSE_CODE = "code"; public static String RESPONSE_STATUS = "status"; public static final int QUERY_RETURN_DEFAULT_COUNT = 50; // // // 查询 // public static final String ERROR_HB_TABLE_NAME = "1010";// 表名称不正确 // public static final String ERROR_DATA_SOURCE_ID = "1011";// 表名称不正确 // public static final String ERROR_QUERY_RETURN_COUNT = "1012";// 取值范围不正确 // // // 修改 // public static final String ERROR_MODIFY_HB_TABLE_DATA = "1020";// 修改数据不能为空 // public static final String ERROR_MODIFY_HB_TABLE_DATA_TYPE = "1021";// 修改数据josn格式不正确 // public static final String ERROR_MODIFY_HB_TABLE_DATA_FIAL = "1022";// 修改数据失败 // public static final String ERROR_MODIFY_HB_TABLE_DATA_OTHER = "1023";// 修改数据,其他错误 // // // 新增 // public static final String ERROR_ADD_HB_TABLE_DATA = "1030";// 新增数据不能为空 // public static final String ERROR_ADD_HB_TABLE_DATA_TYPE = "1031";// 新增数据josn格式不正确 // public static final String ERROR_ADD_HB_TABLE_DATA_FIAL = "1032";// 新增数据失败 // public static final String ERROR_ADD_HB_TABLE_DATA_OTHER = "1033";// 新增数据,其他错误 // // public static final String error_user = "1000";// 用户信息认证失败! // public static final String error_type = "1001";// 参数类型错误(应该为map) // public static final String error_ruleId_type = "1002";// 查询规则id类型错误 // public static final String error_param = "1003";// simpleMap参数错误,为空或者参数数量为0 // public static final String error_noruleCode = "1004";// 请求数据中没有编码[ruleCode] // public static final String error_ruleCode = "1005";// 请求数据中规则编码[ruleCode]错误 // public static final String error_noauthority = "1006";// "此用户对规则无访问权限!" // public static final String error_decoderule = "1007";// 规则解析失败 // public static final String error_paramvalid = "1008";// 参数有效性错误 // public static final String error_other = "10000";// 其他错误 public static Map<String, Object> getRequetErrorMsg(ERROR code) { Map<String, Object> mapValue = new HashMap<String, Object>(); Map<String, Object> value = new HashMap<String, Object>(); value.put("code", code.code); value.put("msg", code.msg); value.put("status", "false"); mapValue.put("result", value); return mapValue; } }
[ "hans511002@sohu.com" ]
hans511002@sohu.com
18ccc50ab0a1f4c64afb8354872277155b7aa883
248f79e342fd1367a2571c015c335cd3ef367edc
/app/src/main/java/com/hrtzpi/models/registration_models/RegistrationSendModel.java
76e79d2292b7f5f13d48f2a849ba6d5e077e450d
[]
no_license
MohamedSobhyDeveloper/happyfaceAnd-master-hrtzpi
8e00990a3343d232cba25fe00c784619e6b2c2f9
7aaadb17be9ca6e868b5d9aa5ded824298433715
refs/heads/master
2022-11-10T20:07:47.543639
2020-06-30T09:08:50
2020-06-30T09:08:50
272,264,293
0
0
null
null
null
null
UTF-8
Java
false
false
2,702
java
package com.hrtzpi.models.registration_models; public class RegistrationSendModel { private String name, telephone, email, password, governmant, area, block, street, avenue, remarkaddress, house_no, datebirth, gender; double lat, lon; public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public RegistrationSendModel() { } public RegistrationSendModel(String name, String telephone, String email, String password) { this.name = name; this.telephone = telephone; this.email = email; this.password = password; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getGovernmant() { return governmant; } public void setGovernmant(String governmant) { this.governmant = governmant; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getBlock() { return block; } public void setBlock(String block) { this.block = block; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getAvenue() { return avenue; } public void setAvenue(String avenue) { this.avenue = avenue; } public String getRemarkaddress() { return remarkaddress; } public void setRemarkaddress(String remarkaddress) { this.remarkaddress = remarkaddress; } public String getHouse_no() { return house_no; } public void setHouse_no(String house_no) { this.house_no = house_no; } public String getDatebirth() { return datebirth; } public void setDatebirth(String datebirth) { this.datebirth = datebirth; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
[ "mamdouhsobhy923@gmail.com" ]
mamdouhsobhy923@gmail.com
9da37cb7a14c42549a337212787c772a18ea9b91
3dcff0b8d97fb464599e4915058995320e07029e
/src/test/java/com/wzy/baseTest/UserServiceTest.java
77b990e067a8422f535724ae33d5ad15b080d3ad
[]
no_license
vincent0322/first_maven_project
78b5c55b05ea2b239b92c429f42a09466caf369d
c0f4b2da8eb2f1557e7d842625f723c5f14520ca
refs/heads/master
2020-03-29T15:08:58.830372
2018-09-24T03:41:28
2018-09-24T03:41:28
149,604,614
0
0
null
null
null
null
GB18030
Java
false
false
2,030
java
package com.wzy.baseTest; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.wzy.model.User; import com.wzy.service.UserService; /** * @ClassName: UserServiceTest * * @author wangzhongyi * @date 2018年8月3日 上午10:14:48 * */ public class UserServiceTest extends SpringTestCase { private static String DRIVERNAME; private static String URL; private static String USER; private static String PASSWORD; @Autowired private UserService userService; @Test public void selectUserByNameTest() { User user = userService.selectUserByName("wangzy"); System.out.println(user.getUserName() + ":" + user.getAge()); } @Test public void jdbcConnectTest(){ try { Properties properties = new Properties(); properties.load(new FileInputStream("src/main/resources/properties/jdbc.properties")); // InputStream input = UserServiceTest.class.getClassLoader().getResourceAsStream("properties/jdbc.properties"); // properties.load(input); DRIVERNAME = properties.getProperty("jdbc_driverClassName"); URL = properties.getProperty("jdbc_url"); USER = properties.getProperty("jdbc_username"); PASSWORD = properties.getProperty("jdbc_password"); Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); System.out.println(connection.isClosed());// 不可以通过isClosed true还是false来判断是否连接成功 } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[ "xy_0322@126.com" ]
xy_0322@126.com
0d7650556664026aefdabc81f91c735239a8f764
fd5c245aa1aea7f3688f26f8521bbe444bf6dc4f
/src/com/Lbins/Mlt/library/internal/EmptyViewMethodAccessor.java
07a0153289542362eb6271bf9cf6c392286e997e
[]
no_license
eryiyi/MltApp
525d60a4cf948df58016e74cf47dd16d9e7d128e
78242754f20356da82ba6a8f646cb521b7a4805c
refs/heads/master
2020-05-29T14:41:29.588736
2016-08-10T14:34:11
2016-08-10T14:34:11
64,711,041
0
0
null
null
null
null
UTF-8
Java
false
false
1,427
java
/** * **************************************************************************** * Copyright 2011, 2012 Chris Banes. * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.Lbins.Mlt.library.internal; import android.view.View; /** * Interface that allows PullToRefreshBase to hijack the call to * AdapterView.setEmptyView() * * @author chris */ public interface EmptyViewMethodAccessor { /** * Calls upto AdapterView.setEmptyView() * * @param emptyView - to set as Empty View */ public void setEmptyViewInternal(View emptyView); /** * Should call PullToRefreshBase.setEmptyView() which will then * automatically call through to setEmptyViewInternal() * * @param emptyView - to set as Empty View */ public void setEmptyView(View emptyView); }
[ "826321978@qq.com" ]
826321978@qq.com
9ed18429d1738552b65b2b35cf3213bb5272a1ee
96523b00586bdf5770faae5d9c291dcc71d2de42
/src/main/java/com/leafBot/pages/HomePage.java
f35a64441a307b93bb2a53500652dc29726cb64f
[]
no_license
gokul-git/Acmelogin
fcb67fb0e7af18e27647b0fb547ba116702aad53
46068763ad217d464475e210cbd29e689b70edcb
refs/heads/master
2022-07-07T05:31:23.538041
2020-02-08T10:19:54
2020-02-08T10:19:54
239,108,363
0
0
null
2020-10-13T19:22:18
2020-02-08T10:23:53
HTML
UTF-8
Java
false
false
1,782
java
package com.leafBot.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.events.EventFiringWebDriver; import com.aventstack.extentreports.ExtentTest; import com.leafBot.testng.api.base.ProjectSpecificMethods; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; public class HomePage extends ProjectSpecificMethods { public HomePage(RemoteWebDriver driver, ExtentTest node, ExtentTest test) { this.driver = driver; this.node = node; this.test = test; PageFactory.initElements(driver, this); } @Given("Verify the Tilte") public HomePage Verifytitle() throws InterruptedException { Thread.sleep(3000); String actualtitle = driver.getTitle(); System.out.println(actualtitle); String expectedtitle = "ACME System 1 - Dashboard"; if (actualtitle.equalsIgnoreCase(expectedtitle)) { System.out.println("Title is matched"); } else { System.err.println("Title mismatched"); } return null; } /* @FindBy(how=How.XPATH,using="//h2[text()[contains(.,'Demo')]]") public WebElement eleLoggedName; public HomePage verifyLoggedName(String data) { verifyPartialText(eleLoggedName, data); return this; } @FindBy(how=How.LINK_TEXT,using="CRM/SFA") public WebElement eleCRMSFALink; public MyHomePage clickCRMSFA(){ click(eleCRMSFALink); return new MyHomePage(driver, node, test); } @FindBy(how=How.CLASS_NAME,using="decorativeSubmit") private WebElement eleLogOut; public LoginPage clickLogout() { click(eleLogOut); return new LoginPage(driver, node, test);*/ }
[ "Gokul Ganesan@DESKTOP-BLJ99G1" ]
Gokul Ganesan@DESKTOP-BLJ99G1
20a3965956e5ebcfc9f747fe425b3688cc265380
6c7feb23d077c6aef2a84366eec67a976f9de48d
/watsondev4/src/main/java/com/n1books/pilot/nlu/NLUController.java
79c8a9aaf8c8d40f690fb194565653bb47875e1c
[]
no_license
komincheol/bigdata_multicampus
a8fb4673a5d80ff4ac1e469d0ff7a2b74319e9d0
a114e8f8cc91f8d00bbf9d1c3b7e763c31a50dd0
refs/heads/master
2021-01-01T18:16:37.112901
2017-11-02T09:45:59
2017-11-02T09:45:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,992
java
package com.n1books.pilot.nlu; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.NaturalLanguageUnderstanding; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.model.AnalysisResults; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.model.AnalyzeOptions; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.model.EmotionOptions; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.model.EmotionResult; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.model.Features; import com.ibm.watson.developer_cloud.natural_language_understanding.v1.model.Model; @Controller public class NLUController { private static Logger logger = LoggerFactory.getLogger(NLUController.class); @Value("${nlu.username}") private String username; @Value("${nlu.password}") private String password; @Autowired //@Inject // @Qualifier == @Resource(name="nLUServiceImpl") private NLUService nluService; @GetMapping("list") public void list(Model model) { List<EmotionVO> list = new ArrayList<EmotionVO>(); } @RequestMapping("nluForm") public void nluForm() {} @RequestMapping(value = "nluProcess", headers="Accept=application/json;charset=UTF-8", produces= {MediaType.APPLICATION_JSON_UTF8_VALUE}) @ResponseBody() public String nluProcess(String statement) { //logger.info("statement : " + statement); NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27); service.setUsernameAndPassword(username, password); EmotionOptions emotions = new EmotionOptions.Builder().build(); Features features = new Features.Builder().emotion(emotions).build(); AnalyzeOptions parameters = new AnalyzeOptions.Builder().text(statement).features(features).build(); AnalysisResults response = service.analyze(parameters).execute(); EmotionResult er = response.getEmotion(); EmotionVO vo = new EmotionVO(); vo.setStatement(statement); vo.setAnger(er.getDocument().getEmotion().getAnger()); vo.setDisgust(er.getDocument().getEmotion().getDisgust()); vo.setFear(er.getDocument().getEmotion().getFear()); vo.setJoy(er.getDocument().getEmotion().getJoy()); vo.setSadness(er.getDocument().getEmotion().getSadness()); try { nluService.insertEmotion(vo); } catch (Exception e) { e.printStackTrace(); } return response.toString(); } }
[ "jckmm@naver.com" ]
jckmm@naver.com
7535c2dac209e31198ba8df512fe833335dcc93d
d5d60a7c6abd505a177b2fd7b060d705ee81691f
/app/src/main/java/com/example/pc_1/akb/Adapter/ContactAdapter.java
02edb1a7eef1b251c2315e739d458668defc4641
[]
no_license
alganiiqbal/10116125_UTS_AKB
2ea7331ae589ae5208230a7239f44730a396a78d
08bfc2df28a49e35bd47290cfabd6cbe1c57bc11
refs/heads/master
2020-05-25T09:25:58.751237
2019-05-21T01:07:58
2019-05-21T01:07:58
187,735,004
2
0
null
null
null
null
UTF-8
Java
false
false
1,242
java
package com.example.pc_1.akb.Adapter; /** 21/05/2019 10116125 Al Ghani Iqbal Dzulfiqar AKB -3 **/ import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.example.pc_1.akb.MenuDescription; import com.example.pc_1.akb.MenuEmail; import com.example.pc_1.akb.MenuInfo; import com.example.pc_1.akb.MenuProfil; import com.example.pc_1.akb.MenuSocmed; import com.example.pc_1.akb.MenuTelp; public class ContactAdapter extends FragmentStatePagerAdapter { int mNoOfTabs; public ContactAdapter(FragmentManager fm, int NumberOfTabs) { super(fm); this.mNoOfTabs = NumberOfTabs; } @Override public Fragment getItem(int position) { switch(position) { case 0: MenuTelp tab1 = new MenuTelp(); return tab1; case 1: MenuEmail tab2 = new MenuEmail(); return tab2; case 2: MenuSocmed tab3 = new MenuSocmed(); return tab3; default: return null; } } @Override public int getCount() { return mNoOfTabs; } }
[ "alganiiqbal@gmail.com" ]
alganiiqbal@gmail.com
57e736105de39089bc7e4476c2db73354b7d036e
0b78a1078ffec7fd5a948fb887928a42728d1812
/app/src/main/java/com/example/a2dam/quicktrade/Model/Usuario.java
936e2acef711561d7836f4d2677dacaff2960b48
[]
no_license
Saulmarti/QuickTradeExam
fdb12f3b1ecf7d225fb8aeb58a4e3d96ccd29d36
5cc7e9327cb445d4f9fc672b2bf28d91894db091
refs/heads/master
2021-05-10T14:06:20.309083
2018-01-22T19:20:59
2018-01-22T19:20:59
118,503,253
0
0
null
null
null
null
UTF-8
Java
false
false
1,536
java
package com.example.a2dam.quicktrade.Model; public class Usuario { private String usuario,nombre,correo,apellidos,direccion; public Usuario(String usuario, String nombre, String correo, String apellidos, String direccion) { this.usuario = usuario; this.nombre = nombre; this.correo = correo; this.apellidos = apellidos; this.direccion = direccion; } public Usuario(){ } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } @Override public String toString() { return "Usuario{" + "usuario='" + usuario + '\'' + ", nombre='" + nombre + '\'' + ", correo='" + correo + '\'' + ", apellidos='" + apellidos + '\'' + ", direccion='" + direccion + '\'' + '}'; } }
[ "saulmartivila@gmail.com" ]
saulmartivila@gmail.com
39375bc92baca3b5e35670a5461d26457f512bfe
a28453cf4916bbb1a9ce1a76f6737997fa8c21d5
/app/src/free/java/com/udacity/gradle/builditbigger/free/MainActivityFragment.java
a7a722e1dcd254144ce24e7609b5fad73a8a7c46
[]
no_license
skrskr/Project-Build-It-Bigger
994a4eec74abcfebcd70a7fdc5c6faaf7b3e1ce5
de87084371c4c81e948ebe2b491e7bb3fbb0b4b6
refs/heads/master
2021-05-13T23:24:02.190659
2018-01-07T09:58:20
2018-01-07T09:58:20
116,513,995
0
0
null
null
null
null
UTF-8
Java
false
false
1,496
java
package com.udacity.gradle.builditbigger.free; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.udacity.gradle.builditbigger.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { @BindView(R.id.adView) public AdView mAdView; private Unbinder unbinder; public MainActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_main, container, false); unbinder = ButterKnife.bind(this,root); // Create an ad request. Check logcat output for the hashed device ID to // get test ads on a physical device. e.g. // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device." AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); mAdView.loadAd(adRequest); return root; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } }
[ "mohamed1.sakr1996@gmail.com" ]
mohamed1.sakr1996@gmail.com
1d3027c692aa7b2e329be07eb412fd9c6494a19a
88188ea44988737f3211d6ac3d2c0158b03d5b45
/SingleNumber.java
f2790e4d004fde6e835c1e9e790a09235a70ee50
[]
no_license
joana92/practice-in-leetcode
123cdac032db0e6139967bc5e59c78ec600b01e3
0e58921d3592c4f14b94a650ce30ee88c8216319
refs/heads/master
2021-05-15T02:32:14.106968
2016-09-28T02:42:11
2016-09-28T02:42:11
37,707,040
0
0
null
null
null
null
UTF-8
Java
false
false
443
java
public class SingleNumber { public int singleNumber(int[] nums) { HashSet<Integer> set= new HashSet<>(); int one=nums[0]; for(int i=0;i<nums.length;i++){ if(set.contains(nums[i])){ set.remove(nums[i]); }else { set.add(nums[i]); } } for(Integer s: set){ one=s; } return one; } }
[ "joana92@users.noreply.github.com" ]
joana92@users.noreply.github.com
9f8986b67c405f6f35c13f88cd2a503734cd9512
b7b41a2df3430f63b17e7089015f795696e918c3
/MicroBlog/src/com/microblog/dao/BackuppwdDao.java
3bc16c97cddea2d46a0fd4601ad4a5123f188412
[]
no_license
yfm049/oldcode
87c3839529d2bc7d634a6fafce62e22ecdfcc4c5
eac280f716e798aee6b6a284c8a887fe38b3bdc0
refs/heads/master
2020-12-24T08:30:30.625579
2016-08-26T09:21:22
2016-08-26T09:21:22
33,308,446
1
2
null
null
null
null
UTF-8
Java
false
false
348
java
package com.microblog.dao; import com.microblog.dbutil.DBConn; public class BackuppwdDao { public void updatepwd(String newpwd3 ,String account ){ String updateSql="update user set u_pwd=? where u_account = ?"; DBConn dbconn=new DBConn(); dbconn.execOther(updateSql, new Object[]{newpwd3,account }); dbconn.closeConn(); } }
[ "yfm049@163.com" ]
yfm049@163.com
0440d56e520ee80d63845fe010f3fba8382fd0de
95025b8c61d099712a18e1d8d36691ab4ee1529c
/homeworkWeek1/Task8.java
4e2bd27338627e54737c148ee692bfb41ba38eca
[]
no_license
YureyKO/HomeWork
8dbb529ace776d89933b941bbc7c4c2a77ce9f4e
09e356b7c1f7516db79e76d685bbe4f9430ff327
refs/heads/master
2021-04-29T15:37:11.424218
2018-02-25T10:27:40
2018-02-25T10:27:40
121,800,840
0
0
null
null
null
null
UTF-8
Java
false
false
805
java
package homeworkWeek1; import java.util.Scanner; public class Task8 { public static void main(String[] args) { /*Вводимо два числа. Порівняти останні цифри цих чисел (користуємося оператором %) 124 4 - true 1456 567 - false 1 2 - false 18 98 - true */ Scanner scanner = new Scanner(System.in); System.out.print("Enter your Number1 - "); int num1 = scanner.nextInt(); System.out.print("Enter your Number2 - "); int num2 = scanner.nextInt(); int res1 = num1 % 10; int res2 = num2 % 10; if (res1 == res2) { System.out.print(true); } else System.out.print(false); } }
[ "br.yurey@gmail.com" ]
br.yurey@gmail.com
d7527702261101906b3cf4f90cb2a4e958e92474
0193529eaac0da115c100443483dcd683d2013e3
/PersonalManagerJava/weibo4j/weibo4j/util/BareBonesBrowserLaunch.java
075533998190b6f0e71950b2d6e6f3f57bf41c50
[]
no_license
grossopa/hamster-flex-3
08b090f080b979d0b7eb21df1cabd3ed3cc7dceb
a1b0dd499918caf59ddae743f686916e180f147c
refs/heads/master
2021-01-22T02:49:17.889400
2012-08-26T15:19:38
2012-08-26T15:19:38
34,765,999
1
0
null
null
null
null
UTF-8
Java
false
false
2,539
java
package weibo4j.util; ///////////////////////////////////////////////////////// //Bare Bones Browser Launch // //Version 1.5 (December 10, 2005) // //By Dem Pilafian // //Supports: Mac OS X, GNU/Linux, Unix, Windows XP // //Example Usage: // // String url = "http://www.centerkey.com/"; // // BareBonesBrowserLaunch.openURL(url); // //Public Domain Software -- Free to Use as You Like // ///////////////////////////////////////////////////////// /** * @author Dem Pilafian * @author John Kristian */ import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.swing.JOptionPane; @SuppressWarnings({"rawtypes", "unchecked" }) public class BareBonesBrowserLaunch { public static void openURL(String url) { try { browse(url); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error attempting to launch web browser:\n" + e.getLocalizedMessage()); } } private static void browse(String url) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InterruptedException, InvocationTargetException, IOException, NoSuchMethodException { String osName = System.getProperty("os.name", ""); if (osName.startsWith("Mac OS")) { Class fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class }); openURL.invoke(null, new Object[] { url }); } else if (osName.startsWith("Windows")) { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); } else { // assume Unix or Linux String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" }; String browser = null; for (int count = 0; count < browsers.length && browser == null; count++) if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) browser = browsers[count]; if (browser == null) throw new NoSuchMethodException("Could not find web browser"); else Runtime.getRuntime().exec(new String[] { browser, url }); } } }
[ "grossopaforever@gmail.com@da5100fe-2ae8-11de-a1c6-114bfcb2beae" ]
grossopaforever@gmail.com@da5100fe-2ae8-11de-a1c6-114bfcb2beae
e0f2248438bb56ae4e51444172f5fa46ed5a2843
c7c8a971c9f3402fe95513527b874d35aa2c2e21
/week-01/day-3/src/com/company/Swap.java
d6a47892a9694b8f12bfd86fa625c2acf2334584
[]
no_license
green-fox-academy/HomkiSvk
520f02c6ef5f94eb9320cdb84f6fe7f4d15776af
e3493e980899b4018476dbb15a2a90a7ae361a94
refs/heads/master
2023-07-02T12:13:31.685509
2021-08-09T10:30:38
2021-08-09T10:30:38
369,634,089
0
0
null
2021-05-24T07:58:10
2021-05-21T19:23:17
null
UTF-8
Java
false
false
499
java
package com.company; public class Swap { public static void main(String[] args) { // Swap the values of the variables int a = 123; int b = 526; System.out.println("Before swap:"); System.out.println("a: " +a); System.out.println("b: " +b); // swap int t; t = a; a = b; b = t; System.out.println("After swap:"); System.out.println("a: " +a); System.out.println("b: " +b); } }
[ "martin.novosedlik@gmail.com" ]
martin.novosedlik@gmail.com
21d1ae38615850f1db172753d7fde31a45ed955a
0eded8396cfd71896421c2d0d0a0b0702edf0758
/ExampleJavaDBApp/src/javadbkoppelingws2/DataSourceV2.java
5f8c612d187a85f4b8892dbdf3f230086978479c
[]
no_license
JorisWillig/DBJavaProject
cf3e49c61a5b3308b7fe0c503f9a7c4c3d46dff9
bc317865b79c79b947bfe5675816eac3d6ea2cb7
refs/heads/master
2021-01-17T16:40:21.258949
2016-06-17T18:07:36
2016-06-17T18:07:36
58,366,584
0
0
null
null
null
null
UTF-8
Java
false
false
2,214
java
package javadbkoppelingws2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** A simple data source for getting database connections. */ public class DataSourceV2 { private static String dbserver; private static String database; private static String username; private static String password; private static Connection activeConn; /** Initializes the data source. Checks if MySQL Driver is found contains the database driver, Fill variabels dbserver, database, username, and password * * TODO get variabels from a configuration file!!! * or credentials manager * Hardcoded is bad code!!! */ private static void init() { try { String driver = "com.mysql.jdbc.Driver"; Class.forName(driver); } catch (ClassNotFoundException e) { System.out.println(e); } dbserver="meru.hhs.nl"; database="15077179"; username = "15077179"; password = "ox4Eth7ohp"; } /** Gets a connection to the database. @return the database connection */ public static Connection getConnection() throws SQLException { if (activeConn==null) { init(); activeConn=createConnection(); } else { if (!activeConn.isValid(0)) { activeConn=createConnection(); } } return activeConn; } private static Connection createConnection() throws SQLException { String connectionString = "jdbc:mysql://" + dbserver + "/" + database + "?" + "user=" + username + "&password=" + password; return DriverManager.getConnection(connectionString); } public static void closeConnection() { if (activeConn!=null) { try { activeConn.close(); } catch(SQLException e) { //to catch and do nothing is the best option //don't know how to recover from this exception } finally { activeConn=null; } } } }
[ "Joris Willig" ]
Joris Willig
e30c5c50ec81875daa886e300ee59fceff737409
d1e8f41e13017ec63f134e8085f6f9ea61982ed9
/src/hl/facturas33/facturadigital/Cfdi.java
88b6e0f26cb4ac9a18dce9f4b912efe023d0b43b
[]
no_license
ts250mx/HLCore
205c47ddfff849191fa23ee1c5156149dbe4d01f
f8523faa18c96a9e6f7e68fc7857f44f7a7472e9
refs/heads/master
2021-05-12T09:46:31.184586
2018-01-13T10:19:08
2018-01-13T10:19:08
117,333,845
0
0
null
null
null
null
UTF-8
Java
false
false
2,151
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hl.facturas33.facturadigital; import java.util.Date; public class Cfdi { private String NoCertificado; public String getNoCertificado() { return this.NoCertificado; } public void setNoCertificado(String NoCertificado) { this.NoCertificado = NoCertificado; } private String UUID; public String getUUID() { return this.UUID; } public void setUUID(String UUID) { this.UUID = UUID; } private String FechaTimbrado; public String getFechaTimbrado() { return this.FechaTimbrado; } public void setFechaTimbrado(String FechaTimbrado) { this.FechaTimbrado = FechaTimbrado; } private String RfcProvCertif; public String getRfcProvCertif() { return this.RfcProvCertif; } public void setRfcProvCertif(String RfcProvCertif) { this.RfcProvCertif = RfcProvCertif; } private String SelloCFD; public String getSelloCFD() { return this.SelloCFD; } public void setSelloCFD(String SelloCFD) { this.SelloCFD = SelloCFD; } private String NoCertificadoSAT; public String getNoCertificadoSAT() { return this.NoCertificadoSAT; } public void setNoCertificadoSAT(String NoCertificadoSAT) { this.NoCertificadoSAT = NoCertificadoSAT; } private String SelloSAT; public String getSelloSAT() { return this.SelloSAT; } public void setSelloSAT(String SelloSAT) { this.SelloSAT = SelloSAT; } private String CadenaOrigTFD; public String getCadenaOrigTFD() { return this.CadenaOrigTFD; } public void setCadenaOrigTFD(String CadenaOrigTFD) { this.CadenaOrigTFD = CadenaOrigTFD; } private String CadenaQR; public String getCadenaQR() { return this.CadenaQR; } public void setCadenaQR(String CadenaQR) { this.CadenaQR = CadenaQR; } private String XmlBase64; public String getXmlBase64() { return this.XmlBase64; } public void setXmlBase64(String XmlBase64) { this.XmlBase64 = XmlBase64; } private String PDF; public String getPDF() { return this.PDF; } public void setPDF(String PDF) { this.PDF = PDF; } }
[ "Administrador@SERVERSAP" ]
Administrador@SERVERSAP
9bf7a7a8cd7a93eacc3939e0e296ad350e396e40
061fdcc4b71d7fdcdac4097075b463c40d2c5481
/src/Presentation/LaaneaftaleSkaerm.java
1a489706e5d3bac39a0b51d0dfbf64f3f1d54ef1
[]
no_license
liondepierre/FerrariCopyPaste-07-05-2021
e63a062d598877b9a3d475f82ba257c49c363b76
007f5db3044a90e78e7091719d20970d40be1cea
refs/heads/master
2023-04-19T00:02:41.293052
2021-05-07T14:34:40
2021-05-07T14:34:40
365,261,565
0
0
null
null
null
null
UTF-8
Java
false
false
4,487
java
package Presentation; import Logic.Kunde; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.RowConstraints; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class LaaneaftaleSkaerm extends GridPane { Kunde kunde; public LaaneaftaleSkaerm (Kunde kunde) { this.kunde = kunde; this.setAlignment(Pos.TOP_LEFT); this.setHgap(30); this.setVgap(30); this.setPadding(new Insets(5, 10, 5, 35)); this.getRowConstraints().add(new RowConstraints(75)); this.getColumnConstraints().add(new ColumnConstraints(150)); this.getColumnConstraints().add(new ColumnConstraints(150)); this.getColumnConstraints().add(new ColumnConstraints(260)); Text topLabel = new Text("Rente Aftale - " + kunde.getNavn()); topLabel.setFont(Font.font("Tahoma", FontWeight.NORMAL, 25)); this.add(topLabel, 0, 0,2,2); topLabel.setFill(Color.DARKRED); // model Label model = new Label("Model:"); this.add(model, 0, 1); model.setAlignment(Pos.BASELINE_CENTER); model.setTextFill(Color.web("#8B0000")); model.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); Label modelValgt = new Label(kunde.getModel()); this.add(modelValgt, 1, 1); modelValgt.setAlignment(Pos.BASELINE_CENTER); modelValgt.setTextFill(Color.web("#8B0000")); modelValgt.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); // totalpris Label totalpris = new Label("Total Pris:"); this.add(totalpris, 0, 2); totalpris.setAlignment(Pos.BASELINE_CENTER); totalpris.setTextFill(Color.web("#8B0000")); totalpris.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); TextField prisField = new TextField(); this.add(prisField,1,2); prisField.setAlignment(Pos.BASELINE_CENTER); prisField.setDisable(true); //udbetalingsprocent Label udbetalingsprocent = new Label("Udbetalingsprocent:"); this.add(udbetalingsprocent, 0, 3); udbetalingsprocent.setAlignment(Pos.BASELINE_CENTER); udbetalingsprocent.setTextFill(Color.web("#8B0000")); udbetalingsprocent.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); TextField ubField = new TextField(); this.add(ubField,1,3); ubField.setAlignment(Pos.BASELINE_CENTER); ubField.setDisable(false); //løbetid Label loebetid = new Label("Løbetid:"); this.add(loebetid, 0, 4); loebetid.setAlignment(Pos.BASELINE_CENTER); loebetid.setTextFill(Color.web("#8B0000")); loebetid.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); TextField loebetidField = new TextField(); this.add(loebetidField,1,4); loebetidField.setAlignment(Pos.BASELINE_CENTER); loebetidField.setDisable(false); //rentesats Label rentesats = new Label("Rentesats"); this.add(rentesats, 0, 5); rentesats.setAlignment(Pos.BASELINE_CENTER); rentesats.setTextFill(Color.web("#8B0000")); rentesats.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); TextField renteField = new TextField(); this.add(renteField,1,5); renteField.setAlignment(Pos.BASELINE_CENTER); renteField.setDisable(true); //månedlig udbetaling Label maanedligudbetaling = new Label("Månedligudbetaling"); this.add(maanedligudbetaling, 0, 6); maanedligudbetaling.setAlignment(Pos.BASELINE_CENTER); maanedligudbetaling.setTextFill(Color.web("#8B0000")); maanedligudbetaling.setFont(Font.font("Tahoma", FontWeight.BOLD, 13)); TextField mdrUdbetalingField = new TextField(); this.add(mdrUdbetalingField,1,6); mdrUdbetalingField.setAlignment(Pos.BASELINE_CENTER); mdrUdbetalingField.setDisable(true); Button nextButton = new Button("Videre"); Font NBSize = new Font(15); nextButton.setFont(NBSize); this.add(nextButton, 3, 7); nextButton.setAlignment(Pos.BASELINE_RIGHT); } }
[ "mertaslantas@outlool.com" ]
mertaslantas@outlool.com
fdd1911846dd32674914e5d47c63b0cafbb48de8
1f644b07da3e3f2645a4e9da221a2b1dbd093395
/src/lintcode/Test752.java
91e4761f7e8d397cd3e09184159aac5241e769c1
[]
no_license
Xchuanshuo/AlgorithmsDemo
16da4a2ed16b6a3967e3e382fbf4b5d8191e5599
b85ecdccb61b297bc4390c977a49f94f17993ff3
refs/heads/master
2021-09-18T13:37:15.633888
2021-09-05T09:11:53
2021-09-05T09:11:53
144,484,561
1
1
null
null
null
null
UTF-8
Java
false
false
1,227
java
package lintcode; /** * @author Legend * @data by on 18-9-7. * @description rogue-knight-sven * idea: * dp dp[i][j]表示有i个星球 并且金币为j时 斯温可通过传送门到达目的地的方法数 * 由于到达星球i 只能由不超过limit距离的星球来传送 所以对于每个星球i 有0..i-limit(k) * 这些位置的星球都能 传送到星球i 而每种传送方式都需要cost[i]金币的花费 所以传送还有一个 * 前提条件就是当前金币要足够 想清楚这些的话 就可以得出状态转移方程 * dp[i][j] += dp[k][j-cost[i]] 其中j-cost[i]>=0 还有注意初始化的情况 * 就是当星球为0时需要传送的目的地就是本身 不需要传送 所以只有一种传送方式 */ public class Test752 { public long getNumberOfWays(int n, int m, int limit, int[] cost) { long[][] dp = new long[n+1][m+1]; for (int j=0;j<=m;j++) dp[0][j] = 1; for (int i=1;i<=n;i++) { for (int j=0;j<=m;j++) { for (int k=Math.max(0, i-limit);k<i;k++) { dp[i][j] += j-cost[i]>=0?dp[k][j-cost[i]]:0; } } } return dp[n][m]; } }
[ "aixs241460@gmail.com" ]
aixs241460@gmail.com
bb0624a7abc58e94c89b81d18a28b5432df2b27d
2ea49bfaa6bc1b9301b025c5b2ca6fde7e5bb9df
/contributions/Maiatoday/java/Data Types/2016-07-05.java
796b3ed0180436e0db3a74e25969d58ddf1b70ed
[]
no_license
0x8801/commit
18f25a9449f162ee92945b42b93700e12fd4fd77
e7692808585bc7e9726f61f7f6baf43dc83e28ac
refs/heads/master
2021-10-13T08:04:48.200662
2016-12-20T01:59:47
2016-12-20T01:59:47
76,935,980
1
0
null
null
null
null
UTF-8
Java
false
false
159
java
`ArrayList` vs `LinkedList` Default values for unassigned data types Using `enum` in Java Two ways to use an `Iterator` Retrieve the component type of an array
[ "maiatoday@gmail.com" ]
maiatoday@gmail.com
599d88af63c286acc05653de758d453862445c62
12144de5347beeef935a1e842c6083ba322cf336
/src/main/java/com/lppz/etl/transform/transformer/OtterTransformerContext.java
e2f27b00c9829a240570a684bd7c20905396485a
[]
no_license
leego86/simple-setl
b424c1eda9f86b5efde3fbc150e4fff92b6871cb
79bb6f3e35dea3b31f8951e1586d9da7e56e37e2
refs/heads/master
2021-07-05T01:17:46.011546
2017-09-26T10:11:56
2017-09-26T10:11:56
104,853,120
0
1
null
null
null
null
UTF-8
Java
false
false
1,871
java
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lppz.etl.transform.transformer; import com.alibaba.otter.shared.common.model.config.data.DataMediaPair; import com.alibaba.otter.shared.common.model.config.pipeline.Pipeline; import com.alibaba.otter.shared.etl.model.Identity; /** * 数据转换过程中的上下文 * * @author jianghang 2011-10-27 下午05:12:53 * @version 4.0.0 */ public class OtterTransformerContext { private Identity identity; private Pipeline pipeline; private DataMediaPair dataMediaPair; public OtterTransformerContext(Identity identity, DataMediaPair dataMediaPair, Pipeline pipeline){ this.identity = identity; this.dataMediaPair = dataMediaPair; this.pipeline = pipeline; } public Identity getIdentity() { return identity; } public void setIdentity(Identity identity) { this.identity = identity; } public DataMediaPair getDataMediaPair() { return dataMediaPair; } public void setDataMediaPair(DataMediaPair dataMediaPair) { this.dataMediaPair = dataMediaPair; } public Pipeline getPipeline() { return pipeline; } public void setPipeline(Pipeline pipeline) { this.pipeline = pipeline; } }
[ "leego8697@gmail.com" ]
leego8697@gmail.com
6bffd51e0cc04f8cad35e5e7cb930473974454f9
ad7bb9abd92da99305eec9ca4a4f71a2887f6d07
/linkedlist/singlylist.java
b3844f84ead402e636ac7c93a1b8dfe7a9215170
[]
no_license
murarisumit/chotu-prep
4277867ce2b52ddd6f9fd2fffdf2a91deafd2453
dc149290dbc2958d2cdcbf90a0b67ef3a1f3e2f3
refs/heads/master
2020-05-16T13:33:01.358869
2019-04-26T07:53:27
2019-04-26T07:53:27
183,077,431
0
0
null
null
null
null
UTF-8
Java
false
false
472
java
import java.util.*; public class singlylist { public static void main(String[] args) { linkedlist list = new linkedlist(); list.append(4); list.append(49); list.append(9); list.append(19); list.append(3); list.printlist(); list.deletenode(4); list.printlist(); System.out.println("hahahahah"); list.insertatk(3,7); // insertion at specific position k insertatK(k,d); list.printlist(); } }
[ "sumit@murari.me" ]
sumit@murari.me
5a3fa4b520284d17ee8132714d6aa54890e4aee3
ce58847e6b8ead368c43a8528556ad1cbc4576e0
/src/ea/EA.java
f5a7c3b975c8f0cf542b2bf7269cc5576990151c
[]
no_license
nickyvo8910/Napier_ECO
2047a78ad63e801aa1e669087d2919599a74918b
f4c4e87fbfe529c064292261f268e5d1e28fa97a
refs/heads/master
2022-04-26T01:04:58.385007
2020-04-25T00:35:20
2020-04-25T00:35:20
258,653,468
0
0
null
null
null
null
UTF-8
Java
false
false
6,075
java
package ea; /*** * This is an example of an EA used to solve the problem * A chromosome consists of two arrays - the pacing strategy and the transition strategy * This algorithm is only provided as an example of how to use the code and is very simple - it ONLY evolves the transition strategy and simply sticks with the default * pacing strategy * The default settings in the parameters file make the EA work like a hillclimber: * the population size is set to 1, and there is no crossover, just mutation * The pacing strategy array is never altered in this version- mutation and crossover are only * applied to the transition strategy array * It uses a simple (and not very helpful) fitness function - if a strategy results in an * incomplete race, the fitness is set to 1000, regardless of how much of the race is completed * If the race is completed, the fitness is equal to the time taken * The idea is to minimise the fitness value */ import java.util.ArrayList; import teamPursuit.TeamPursuit; import teamPursuit.WomensTeamPursuit; public class EA implements Runnable { // create a new team with the default settings public static TeamPursuit teamPursuit = new WomensTeamPursuit(); private ArrayList<Individual> population = new ArrayList<Individual>(); private int iteration = 0; public EA() { } public static void main(String[] args) { EA ea = new EA(); ea.run(); } public void run() { initialisePopulation(); System.out.println("finished init pop"); iteration = 0; while (iteration < Parameters.maxIterations) { iteration++; Individual parent1 = tournamentSelection(); Individual parent2 = tournamentSelection(); Individual child = crossover(parent1, parent2); child = mutate(child); child.evaluate(teamPursuit); replace(child); printStats(); } Individual best = getBest(population); best.print(); } private void printStats() { System.out.println("" + iteration + "\t" + getBest(population) + "\t" + getWorst(population)); } private void replace(Individual child) { Individual worst = getWorst(population); if (child.getFitness() < worst.getFitness()) { int idx = population.indexOf(worst); population.set(idx, child); } } private Individual mutate(Individual child) { if (Parameters.rnd.nextDouble() > Parameters.mutationProbability) { return child; } // choose how many elements to alter int mutationRate = 1 + Parameters.rnd.nextInt(Parameters.mutationRateMax); // mutate the transition strategy // mutate the transition strategy by flipping boolean value for (int i = 0; i < mutationRate; i++) { int index = Parameters.rnd.nextInt(child.transitionStrategy.length); child.transitionStrategy[index] = !child.transitionStrategy[index]; } // // mutate the pacing strategy by randomly adding/taking pacing. for (int j = 0; j < mutationRate; j++) { int index = Parameters.rnd.nextInt(child.pacingStrategy.length); if (Parameters.rnd.nextFloat() < 0.5) { if (Math.toIntExact(Math.round(child.pacingStrategy[index] * 1.5)) <= 1200) child.pacingStrategy[index] = Math.toIntExact(Math.round(child.pacingStrategy[index] * 1.5)); else child.pacingStrategy[index] = Math.toIntExact(Math.round(child.pacingStrategy[index] * 0.5)); } else { if (Math.toIntExact(Math.round(child.pacingStrategy[index] * 0.5)) >= 200) child.pacingStrategy[index] = Math.toIntExact(Math.round(child.pacingStrategy[index] * 0.5)); else child.pacingStrategy[index] = Math.toIntExact(Math.round(child.pacingStrategy[index] * 1.5)); } } return child; } private Individual crossover(Individual parent1, Individual parent2) { if (Parameters.rnd.nextDouble() > Parameters.crossoverProbability) { return parent1; } Individual child = new Individual(); int crossoverPoint = Parameters.rnd.nextInt(parent1.transitionStrategy.length); // just copy the pacing strategy from p1 and p2 for (int i = 0; i < parent1.pacingStrategy.length; i++) { child.pacingStrategy[i] = parent1.pacingStrategy[i]; } for (int i = crossoverPoint; i < parent2.pacingStrategy.length; i++) { child.pacingStrategy[i] = parent2.pacingStrategy[i]; } for (int i = 0; i < crossoverPoint; i++) { child.transitionStrategy[i] = parent1.transitionStrategy[i]; } for (int i = crossoverPoint; i < parent2.transitionStrategy.length; i++) { child.transitionStrategy[i] = parent2.transitionStrategy[i]; } return child; } /** * Returns a COPY of the individual selected using tournament selection * * @return */ private Individual tournamentSelection() { ArrayList<Individual> candidates = new ArrayList<Individual>(); for (int i = 0; i < Parameters.tournamentSize; i++) { candidates.add(population.get(Parameters.rnd.nextInt(population.size()))); } return getBest(candidates).copy(); } private Individual getBest(ArrayList<Individual> aPopulation) { double bestFitness = Double.MAX_VALUE; Individual best = null; for (Individual individual : aPopulation) { if (individual.getFitness() < bestFitness || best == null) { best = individual; bestFitness = best.getFitness(); } } return best; } private Individual getWorst(ArrayList<Individual> aPopulation) { double worstFitness = 0; Individual worst = null; for (Individual individual : population) { if (individual.getFitness() > worstFitness || worst == null) { worst = individual; worstFitness = worst.getFitness(); } } return worst; } private void printPopulation() { for (Individual individual : population) { System.out.println(individual); } } private void initialisePopulation() { while (population.size() < Parameters.popSize) { Individual individual = new Individual(); individual.initialise(); individual.evaluate(teamPursuit); population.add(individual); } } }
[ "nickyvo8910@gmail.com" ]
nickyvo8910@gmail.com
c192c6665fe7302ce165ed8b9963679a9201f52d
ad9236b70fdc87dde358516e1dfae9cf016adc74
/src/main/java/demo/Test.java
9536212ab4b9ecf5899cd0903453e527c37f0e32
[]
no_license
zkkNike/zkknike-
d3f517f4a40edcbdbd97d742bc282bd662230dcd
cbcc1694bef10672abc90bb286d24bcb63e17b9d
refs/heads/master
2022-12-05T02:00:51.603140
2020-08-31T06:32:31
2020-08-31T06:32:31
291,653,858
0
0
null
null
null
null
UTF-8
Java
false
false
127
java
package demo; public class Test { public static void main(String[] args) { System.out.println("sbdckjs"); } }
[ "13466973015@163.com" ]
13466973015@163.com
d0dd8b2b603903af91590cb9d27c4970cb5e30ea
bc1f6a5009868fcaf8ec614165e0fac9effd0351
/src/SourceHeader.Gui/src/sourceheader/gui/dialogs/PreferencesDialog.java
d4d5a90cabaebcc15a949076f39d4e11d573ab0c
[]
no_license
steve-s/source-header
543d889c93f6884ed965c303098d15eafd0f4184
7b9e26a189f7b1f0fd0ce4481a2713cc0f7e773c
refs/heads/master
2021-01-10T03:27:33.541393
2010-02-28T17:07:57
2010-02-28T17:07:57
45,644,465
0
0
null
null
null
null
UTF-8
Java
false
false
6,908
java
/* * file PreferencesDialog.java * * This file is part of SourceHeader project. * * SourceHeader is software for easier maintaining source files' headers. * project web: http://code.google.com/p/source-header/ * author: Steve Sindelar * licence: New BSD Licence * * (c) Steve Sindelar */ package sourceheader.gui.dialogs; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import javax.swing.*; import sourceheader.gui.util.preferences.*; /** * Preferences dialog lets user change some basic preferences. * * @author steve */ public class PreferencesDialog extends JDialog { final ApplicationPreferences preferences; private final JTextField alternatingPartsConfigFileTextField = new JTextField(15); private final JTextField specialCharacterTextField = new JTextField(5); public PreferencesDialog(JFrame parent, ApplicationPreferences preferences) { super(parent, "Preferences"); this.preferences = preferences; this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(10, 5, 0, 0); this.add(new JLabel("Path to file with alternating blocks configuration"), c); c.insets = new Insets(0, 0, 0, 0); c.gridy++; this.add(this.initAlternatingBlocksPanel(), c); JSeparator separator = new JSeparator(JSeparator.HORIZONTAL); c.gridy++; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 10, 5, 10); this.add(separator, c); c.fill = GridBagConstraints.NONE; c.insets = new Insets(0, 0, 0, 0); c.gridy++; this.add(this.initSpecialCharacterPanel(), c); separator = new JSeparator(JSeparator.HORIZONTAL); c.gridy++; c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(5, 10, 5, 10); this.add(separator, c); c.fill = GridBagConstraints.NONE; c.gridy++; this.add(this.initButtonsPanel(), c); this.pack(); this.setLocation( parent.getX() + parent.getWidth()/2 - this.getWidth()/2, parent.getY() + parent.getHeight()/2 - this.getHeight()/2); this.setMinimumSize(this.getSize()); this.setVisible(true); } private JPanel initSpecialCharacterPanel() { this.specialCharacterTextField.setText( "" + this.preferences.getSpecialCharacter()); JPanel panel = new JPanel(new FlowLayout()); panel.add(new JLabel("Special character")); panel.add(this.specialCharacterTextField); return panel; } private JPanel initAlternatingBlocksPanel() { this.alternatingPartsConfigFileTextField.setText( this.preferences.getAlternatingPartsConfigFile()); final JButton insertDefaultConfButton = new JButton("Insert default config"); insertDefaultConfButton.addActionListener(new DefaultConfigButtonListener()); insertDefaultConfButton.setEnabled( !alternatingPartsConfigFileTextField.getText().isEmpty()); this.alternatingPartsConfigFileTextField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { super.keyTyped(e); insertDefaultConfButton.setEnabled( !alternatingPartsConfigFileTextField.getText().isEmpty()); } }); JButton openButton = new JButton("..."); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser dialog = new JFileChooser(); if (dialog.showSaveDialog(PreferencesDialog.this) == JFileChooser.APPROVE_OPTION) { String path = dialog.getSelectedFile().getPath(); alternatingPartsConfigFileTextField.setText(path); insertDefaultConfButton.setEnabled(true); } } }); JPanel panel = new JPanel(new FlowLayout()); panel.add(this.alternatingPartsConfigFileTextField); panel.add(openButton); panel.add(insertDefaultConfButton); return panel; } private JPanel initButtonsPanel() { JButton okButton = new JButton("OK"); okButton.addActionListener(new OkButtonActionListener()); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { PreferencesDialog.this.dispose(); } }); JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER)); panel.add(okButton); panel.add(cancelButton); return panel; } private class DefaultConfigButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (alternatingPartsConfigFileTextField.getText().isEmpty()) { return; } if (JOptionPane.showConfirmDialog( PreferencesDialog.this, "This will rewrite all content of this file.", "Are you sure?", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) { return; } try { AlternatingPartsHelper.saveDefaultConfigTo( alternatingPartsConfigFileTextField.getText()); } catch(IOException ex) { JOptionPane.showMessageDialog( PreferencesDialog.this, "Error occured: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private class OkButtonActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (!specialCharacterTextField.getText().isEmpty()) { preferences.setSpecialCharacter( specialCharacterTextField.getText().charAt(0)); } if (!alternatingPartsConfigFileTextField.getText().isEmpty()) { preferences.setAlternatingPartsConfigFile( alternatingPartsConfigFileTextField.getText()); } JOptionPane.showMessageDialog( PreferencesDialog.this, "Changes will take affect after application restart.", "Information", JOptionPane.INFORMATION_MESSAGE); PreferencesDialog.this.dispose(); } } }
[ "steve.sidelar@740322e4-be33-11de-afc4-699a8c260df9" ]
steve.sidelar@740322e4-be33-11de-afc4-699a8c260df9
b85ed4ee70d8dd0e853196d8850a3b8ea461e49d
38da8e655aa63106c89c9175c9dffea615014a0d
/src/main/java/sample/security/service/SampleUserDetailsService.java
e4f09464cdd49218f64f8804a569ea3fc8048196
[]
no_license
uustyle/security
72a1e972525f70a652b9f222fcfa3932e6d6a47c
2339075d30c04ba23ad67e995d041f8fd5f8d461
refs/heads/master
2020-05-24T19:40:04.896435
2017-03-14T12:23:22
2017-03-14T12:23:22
84,874,729
0
0
null
null
null
null
UTF-8
Java
false
false
1,004
java
package sample.security.service; import java.util.HashSet; import java.util.Set; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; public class SampleUserDetailsService implements UserDetailsService{ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); if (username.equals("user")) { authorities.add(new SimpleGrantedAuthority("ROLE_USER")); } else if (username.equals("admin")) { authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); } return new User(username, "arakawa", authorities); } }
[ "yukihiro.arakawa@gmail.com" ]
yukihiro.arakawa@gmail.com
3f21aaf724a4db10b2fb59021bcc70ed42eacec0
a0dd860d43aa5eb445dd6002c73a7ace345ce0b3
/src/main/java/be/svk/api/dto/SeasonDTO.java
c2a5d23055a5b704df2ca5e45a47eef232bdc199
[]
no_license
Goddy/svk-api
62b90fe422ce5e15d800abea23756ed50f3d8f9b
0f85e9c3f7658113905496b480b131616513cedd
refs/heads/master
2021-06-05T20:26:40.901812
2016-11-07T18:12:52
2016-11-07T18:12:52
72,997,779
0
0
null
null
null
null
UTF-8
Java
false
false
724
java
package be.svk.api.dto; /** * Created by u0090265 on 08/07/16. */ public class SeasonDTO extends DTOBaseClass { private String description; public SeasonDTO(String description) { super(); this.description = description; } public SeasonDTO(Long id, String description) { super(id); this.description = description; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "SeasonDTO{" + "description='" + description + '\'' + "} " + super.toString(); } }
[ "tom.dedobbeleer@kuleuven.be" ]
tom.dedobbeleer@kuleuven.be
f42496951070f26b20c38865e7a08afe037081a0
a42f8b961c5ae3a4bc999bd7afb88c2340f712f8
/Principles of Software Design/course_03_week_03_Interface/src/MarkovModel.java
f2a465b1cd7f44bd0ecdd45bb4007eafd7f61188
[]
no_license
vacous/Coursera_Java_Fundmental
72050a2c83ff672d8b57fc1a48ce9ae84b5875ab
9230e25ea545b63c78e04dc2eefba6fd5693e424
refs/heads/master
2021-01-11T15:30:50.161568
2017-02-28T06:08:05
2017-02-28T06:08:05
80,366,159
0
0
null
null
null
null
UTF-8
Java
false
false
857
java
import java.util.ArrayList; import java.util.Random; public class MarkovModel extends AbstractMarkovModel{ private int key_length; public MarkovModel(int input_length) { key_length = input_length; myRandom = new Random(); } public void setRandom(int seed){ myRandom = new Random(seed); } public String getRandomText(int numChars){ StringBuilder sb = new StringBuilder(); int index = myRandom.nextInt(myText.length() - key_length); String key = myText.substring(index, index + key_length); sb.append(key); for (int idx = 0; idx < numChars - key_length; idx += 1) { ArrayList<String> follows = get_follows(key); if ( follows.size() == 0) break; index = myRandom.nextInt(follows.size()); String next = follows.get(index); sb.append(next); key = key.substring(1) + next; } return sb.toString(); } }
[ "vaocus@gmail.com" ]
vaocus@gmail.com
d191de19fdb1cc9d960d892f3dac760aa63a9e66
77776a657fffac8d60c7de10b392263cfa43ab23
/src/chapter6/ch09/FileExceptionHandling.java
eb9ce0e1ccdf8dbe7875d3fc6a7e7a663ff24afa
[]
no_license
SeungjaeKim/studyjava
542e2b88f623f94a4dbbebb599c070e52635e8b5
b82e2bb89c8e39a0ebc1893306db5cd1543ba22e
refs/heads/master
2023-07-11T09:10:32.391295
2021-08-17T12:52:17
2021-08-17T12:52:17
346,021,775
0
0
null
null
null
null
UTF-8
Java
false
false
1,055
java
package chapter6.ch09; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileExceptionHandling { public static void main(String[] args) { /* FileInputStream fis = null; try { fis = new FileInputStream("a.txt"); System.out.println("read"); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println(e); return; } finally { if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("finally"); }*/ try(FileInputStream fis = new FileInputStream("a.txt")){ System.out.println("read"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("end"); } }
[ "kimseungjae@gmail.com" ]
kimseungjae@gmail.com
c485f78fcc3a30a3ebc3814cfa504f4a29b2b48f
6ff7d9324f3d74f268c241414b00a95820195306
/src/test/java/com/lvshen/demo/RedisSpringTest.java
98cacf7eddcd26105b9b4aa353707bb7f41aeb80
[]
no_license
lvshen9/demo-lvshen
2a7c940ae746d7bd0f9d58291e8ab9ff66166a1c
c9e879f9eb3cfeae2f74857e259253d8aa63f4f6
refs/heads/master
2022-07-23T16:18:02.252501
2020-05-19T05:21:41
2020-05-19T05:21:41
246,206,520
0
1
null
2022-06-17T02:56:00
2020-03-10T04:16:16
Java
UTF-8
Java
false
false
8,172
java
package com.lvshen.demo; import com.lvshen.demo.arithmetic.shorturl.ShortUrlUtil; import com.lvshen.demo.redis.ratelimiter.RateLimiter; import com.lvshen.demo.redis.reentrantlock.RedisDelayingQueue; import com.lvshen.demo.redis.reentrantlock.RedisWithReentrantLock; import com.lvshen.demo.redis.subscribe.GoodsMessage; import com.lvshen.demo.redis.subscribe.Publisher; import com.lvshen.demo.redis.subscribe.UserMessage; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.redisson.Redisson; import org.redisson.api.RAtomicLong; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.redisson.config.SingleServerConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import java.util.UUID; import java.util.concurrent.Semaphore; /** * Description: * * @author yuange * @version 1.0 * @date: 2019/12/26 14:52 * @since JDK 1.8 */ @Slf4j @SpringBootTest @RunWith(SpringRunner.class) public class RedisSpringTest { public static final String GET_NEXT_CODE = "get_next_code_spring"; public static final String HASH_KEY = "hash_key"; private static final String VALUE_KEY = "value_key"; // private static final String HASH_KEY = "hash_key"; //创建限流令牌 private static Semaphore semaphore = new Semaphore(50); @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Autowired private ShortUrlUtil shortUrlUtil; @Autowired private Publisher publisher; @Autowired private RedisWithReentrantLock redisWithReentrantLock; @Autowired private RedisDelayingQueue<String> delayingQueue; private static final String MESSAGE = "{\"code\":\"400\",\"msg\":\"FAIL\",\"desc\":\"触发限流\"}"; //模拟布隆过滤器 @Test public void testBit() { String userId = "10001001001"; int hasValue = Math.abs(userId.hashCode()); //key 做hash运算 long index = (long) (hasValue % Math.pow(2, 32)); //hash值与数组长度取模 Boolean bloomFilter = redisTemplate.opsForValue().setBit("user_bloom_filter", index, true); log.info("user_bloom_filter:{}", bloomFilter); } //缓存击穿解决方法 @Test public void testUnEffactiveCache() { String userId = "1001"; //1.系统初始化是init 布隆过滤器,将所有数据存于redis bitmap中 //2.查询是先做判断,该key是否存在与redis中 int hasValue = Math.abs(userId.hashCode()); //key 做hash运算 long index = (long) (hasValue % Math.pow(2, 32)); //hash值与数组长度取模 Boolean result = redisTemplate.opsForValue().getBit("user_bloom_filter", index); if (!result) { log.info("该userId在数据库中不存在:{}", userId); //return null; } //3.从缓存中获取 //4.缓存中没有,从数据库中获取,并存放于redis中 } @Test public void testCacheAvalanche() throws InterruptedException { //1.从redis里面读取缓存 //2.redis中没有,就需要从数据库中获取 //3.获取令牌 semaphore.acquire(); try { //4.从数据库中读取 //5.存入redis } finally { semaphore.release(); } } //redis可重入锁测试 @Test public void testRLock() { String KEY = "r_lock"; System.out.println("进入锁" + redisWithReentrantLock.lock(KEY)); System.out.println("第二次进入" + redisWithReentrantLock.lock(KEY)); System.out.println("第一次退出" + redisWithReentrantLock.unlock(KEY)); System.out.println("第二次退出" + redisWithReentrantLock.unlock(KEY)); } //多线程测试 @Test public void testRockWithThread() { String key = "r_lock"; new Thread(() -> { System.out.println("当前线程:" + Thread.currentThread().getName() + "进入锁" + redisWithReentrantLock.lock(key)); System.out.println("当前线程:" + Thread.currentThread().getName() + "第二次进入" + redisWithReentrantLock.lock(key)); }).start(); System.out.println("当前线程:" + Thread.currentThread().getName() + "进入锁" + redisWithReentrantLock.lock(key)); } //延迟队列测试 @Test public void testDelayQueue() { String queueKey = "redis_delay_queue"; delayingQueue.setQueueKey(queueKey); Thread producer = new Thread(() -> delayingQueue.delay("I am Lvshe", 10000)); Thread consumer = new Thread(() -> delayingQueue.loop()); producer.start(); consumer.start(); try { producer.join(); Thread.sleep(20000); consumer.interrupt(); consumer.join(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testCode() { long code = getCode(GET_NEXT_CODE); log.info("code:{}", code); } @Test public void setStringTest() { stringRedisTemplate.opsForValue().set(VALUE_KEY, "I am Lvshen9"); System.out.println("Test is OK"); } @Test public void setHashTest() { stringRedisTemplate.opsForHash().put(HASH_KEY, "lvshen", "a value that is lvshen"); System.out.println("Test is OK"); } /** * spring原生获取 * * @param key * @return */ public long getCode(String key) { RedissonClient redissonClient = getRedissonClient(); /*RLock rLock = redissonClient.getLock(key); rLock.tryLock();*/ RAtomicLong atomicVar = redissonClient.getAtomicLong(key); if (!atomicVar.isExists()) { atomicVar.set(100); } long value = atomicVar.incrementAndGet(); // 多线程调用该方法,不会造成数据丢失 return value; } public void saveHash(String key) { RedissonClient redissonClient = getRedissonClient(); } private RedissonClient getRedissonClient() { Config config = new Config(); SingleServerConfig singleServerConfig = config.useSingleServer(); singleServerConfig.setAddress("redis://192.168.42.128:6379"); singleServerConfig.setPassword("lvshen"); RedissonClient redissonClient = Redisson.create(config); return redissonClient; } @Test public void testShortUrl() { String url = "www.goolge.com"; String shortUrl = shortUrlUtil.getShortUrl(url, ShortUrlUtil.Decimal.D64); System.out.println("短链:" + shortUrl); } //redis发布订阅 pub/sub @Test public void pushMessage() { UserMessage userMessage = new UserMessage(); userMessage.setMsgId(UUID.randomUUID().toString().replace("-", "")); userMessage.setUserId("1"); userMessage.setUsername("admin"); userMessage.setUsername("root"); userMessage.setCreateStamp(System.currentTimeMillis()); publisher.pushMessage("user", userMessage); GoodsMessage goodsMessage = new GoodsMessage(); goodsMessage.setMsgId(UUID.randomUUID().toString().replace("-", "")); goodsMessage.setGoodsType("苹果"); goodsMessage.setNumber("十箱"); goodsMessage.setCreateStamp(System.currentTimeMillis()); publisher.pushMessage("goods", goodsMessage); } @Test public void test() { for (int i = 0; i < 10; i++) { System.out.println(limitFun()); } } /** * 10s内限制请求5次 * @return */ @RateLimiter(key = "ratedemo:1.0.0", limit = 5, expire = 10, message = MESSAGE) private String limitFun() { //System.out.println("正常请求"); return "正常请求"; } }
[ "1587023453@qq.com" ]
1587023453@qq.com
50cae73785e0a9e20ecbb8ecfd47c46f3bc7f90c
af7684ec53c9c26500a9ee8a5821c419a568d45e
/src/poject1/package-info.java
80127fb5506542e2181277fd77f39602f0649aa5
[]
no_license
priyanka1603/Pulldemo2
4a8305fb57f24e1c32ea62c53dcd58ffb5485872
461a25e17d3661a360501f2e621536b3444ced39
refs/heads/master
2023-06-20T10:38:57.267950
2021-07-09T13:29:37
2021-07-09T13:29:37
384,441,885
0
0
null
null
null
null
UTF-8
Java
false
false
16
java
package poject1;
[ "manohardevi2521@gmail.com" ]
manohardevi2521@gmail.com
1e4eb57dd63b79a823f223d439fa8754444a994d
6dddeec1c464ed551fa74e546f9912563062fc8a
/src/client/windows/ChatWindow.java
776ce5d4b97e8257427e9262d3c6baae27f5745a
[]
no_license
Nammine/YeChat
c77c96d8969bf038a9a7f86c575bddc0051b7b6b
2d2fc3c4da5c4d958ae8fcad5bcc3595b758520e
refs/heads/master
2016-09-14T00:32:37.111873
2016-05-24T04:53:40
2016-05-24T04:53:40
59,540,846
0
0
null
null
null
null
GB18030
Java
false
false
5,995
java
package client.windows; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.util.Calendar; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import client.connect.ClientMainClass; import client.panels.*; import entity.Message; import entity.Request; import entity.RequestType; import entity.User; public class ChatWindow extends JFrame implements ActionListener{ private static final long serialVersionUID = 1664152L; private UserInfoPanel userInfoPanel; private MessageReceivedArea receivedmessageArea; private ToolsPanel toolsPanel; private MessageWritingArea sendingMessageArea; private SendButtonPanel sendButtonPanel; private MessageRecordArea recordArea; private User user; public ChatWindow(User user) { super("Talk with"+user.getName()); this.user=user; this.userInfoPanel = new UserInfoPanel(user); this.receivedmessageArea = new MessageReceivedArea(); this.toolsPanel = new ToolsPanel(); this.sendingMessageArea=new MessageWritingArea(); this.sendButtonPanel = new SendButtonPanel(); this.recordArea=new MessageRecordArea(); init(); addHanderListener(); sendingMessageArea.getTextPane().requestFocusInWindow(); } public void init(){ Container container = this.getContentPane(); JPanel leftPanel = new JPanel(); leftPanel.setBorder(BorderFactory.createLineBorder(Color.darkGray,5)); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); //左边面板box布局 leftPanel.add(userInfoPanel);//左边面板添加组件 leftPanel.add(receivedmessageArea); leftPanel.add(toolsPanel); leftPanel.add(sendingMessageArea); leftPanel.add(sendButtonPanel); container.add(leftPanel, BorderLayout.CENTER); } public void addHanderListener(){ this.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { ChatWindow.this.dispose(); } }); userInfoPanel.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1){ new FriendInformation(user).showMe(); } } }); toolsPanel.getFontButton().addActionListener(this); toolsPanel.getColorButton().addActionListener(this); toolsPanel.getFaceButton().addActionListener(this); sendButtonPanel.getRecordButton().addActionListener(this); sendButtonPanel.getSentButton().addActionListener(this); sendButtonPanel.getCloseButton().addActionListener(this); } public void showMe(){ ImageIcon tp1=new ImageIcon("images/login/xy.jpg"); this.setIconImage(tp1.getImage()); this.setSize(400,540); this.setLocation(250,100); this.setVisible(true); this.setResizable(false); this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } public MessageReceivedArea getReceivedmessageArea() { return receivedmessageArea; } public void setReceivedmessageArea(MessageReceivedArea receivedmessageArea) { this.receivedmessageArea = receivedmessageArea; } @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Record")){ recordArea.setVisible(true); recordArea.setLocation(this.getX(),this.getY()+540); }else if(e.getActionCommand().equals("Send")){ Document doc = sendingMessageArea.getTextPane().getDocument(); Element root = doc.getDefaultRootElement(); Message message=new Message(sendingMessageArea.getTextPane().getParagraphAttributes()); message.setMessage(root); message.setFrom(ClientMainClass.currentUser); message.setTo(user); try { ClientMainClass.oos.writeObject(new Request(RequestType.sendMessage)); ClientMainClass.oos.writeObject(message); } catch (IOException e1) { e1.printStackTrace(); } sendingMessageArea.getTextPane().setText(""); //输出到本面板 SimpleAttributeSet set=new SimpleAttributeSet(); StyleConstants.setFontSize(set, 16); StyleConstants.setFontFamily(set,"宋体"); StyleConstants.setForeground(set, new Color(0,139,139)); JTextPane jtp=receivedmessageArea.getTextPane(); Calendar c = Calendar.getInstance(); String time=c.get(Calendar.YEAR)+"-"+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+" "+ (c.get(Calendar.HOUR_OF_DAY)+8)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND); try {//输出信息发送人,时间 jtp.getDocument().insertString(jtp.getDocument().getLength(), ClientMainClass.currentUser.getName()+" "+time+"\n", set); // 输出信息 message.analysisMessage(jtp); } catch (BadLocationException e1) { e1.printStackTrace(); } }else if(e.getActionCommand().equals("Close")){ dispose(); }else if(e.getActionCommand().equals("Font")){ Font font = MyFontChooser.showDialog(this,null,new Font("宋体",Font.BOLD,12)); sendingMessageArea.getTextPane().setFont(font); sendingMessageArea.getTextPane().requestFocusInWindow(); }else if(e.getActionCommand().equals("Color")){ Color c=JColorChooser.showDialog(this,"Please choose a color",Color.BLACK); sendingMessageArea.getTextPane().setForeground(c); sendingMessageArea.getTextPane().requestFocusInWindow(); }else if(e.getActionCommand().equals("Face")){ new FacePanel(sendingMessageArea.getTextPane()).setLocation(this.getX()+20,this.getY()+200); sendingMessageArea.getTextPane().requestFocusInWindow(); } } }
[ "namminewxy@gmail.com" ]
namminewxy@gmail.com
69e9bbeb6784ffa00a4a511426f6e1d2e85fdddc
688e9ca1702818b6f789dff1fa3a87e1c4638cf8
/src/main/java/cz/sajvera/ppro/bean/NovyReceptBean.java
be0d3d5f43ffd3929c2eae4316da722ee2da67c6
[]
no_license
Sajwy/EKucharka
1b7b6e3ae8f99af65bb017326692f421140c53a9
d7054e452709b2908f64a10904c73d4f21160a6f
refs/heads/master
2021-09-06T05:05:39.882948
2018-02-02T15:44:25
2018-02-02T15:44:25
116,700,147
0
0
null
null
null
null
UTF-8
Java
false
false
4,152
java
package cz.sajvera.ppro.bean; import cz.sajvera.ppro.dao.ReceptDao; import cz.sajvera.ppro.model.Fotka; import cz.sajvera.ppro.model.Kategorie; import cz.sajvera.ppro.model.Recept; import cz.sajvera.ppro.model.Surovina; import cz.sajvera.ppro.utils.ImageUtils; import org.primefaces.model.UploadedFile; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import java.io.Serializable; import java.util.Date; import java.util.List; @Named @ViewScoped public class NovyReceptBean implements Serializable { @Inject private ReceptDao receptDao; private Recept recept; @Inject private KategorieBean kategorieBean; private List<Kategorie> kategorieList; private Surovina surovina; @Inject private PrihlaseniOdhlaseniBean prihlaseniOdhlaseniBean; private UploadedFile file; @PostConstruct public void init() { recept = new Recept(); kategorieList = kategorieBean.getKategorieList(); surovina = new Surovina(); } public String pridatRecept() { if(recept.getSuroviny().isEmpty()) { FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Nepřidány žádné suroviny!", ""); FacesContext.getCurrentInstance().addMessage(null, message); return null; } else { if(file.getSize() > 0) { recept.setFotka(ImageUtils.vytvorFotku(file)); } else { recept.setFotka(new Fotka("/resources/img/teddybear.jpg", "/resources/img/teddybear.jpg", "/resources/img/teddybear.jpg")); } recept.setDatumPridani(new Date()); recept.setUzivatel(prihlaseniOdhlaseniBean.getUzivatel()); receptDao.save(recept); String zprava; if(recept.getNazev().length() > 15) zprava = "Recept " + recept.getNazev().substring(0, 14) + "... úspěšně přidán."; else zprava = "Recept " + recept.getNazev() + " úspěšně přidán."; FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, zprava, ""); FacesContext.getCurrentInstance().addMessage(null, message); return "seznamreceptu?faces-redirect=true"; } } public Recept getRecept() { return recept; } public void setRecept(Recept recept) { this.recept = recept; } public List<Kategorie> getKategorieList() { return kategorieList; } public void setKategorieList(List<Kategorie> kategorieList) { this.kategorieList = kategorieList; } public Surovina getSurovina() { return surovina; } public void setSurovina(Surovina surovina) { this.surovina = surovina; } public Kategorie getKategorie(Integer id) { if (id == null){ throw new IllegalArgumentException("no id provided"); } for (Kategorie k : kategorieList){ if (id.equals(k.getId())){ return k; } } return null; } public String reinitSurovina() { surovina.setRecept(recept); surovina = new Surovina(); return null; } public UploadedFile getFile() { return file; } public void setFile(UploadedFile file) { this.file = file; } public void reinitFile() { file = null; } public void validate(FacesContext context, UIComponent component, Object value) { UploadedFile file = (UploadedFile) value; if(file.getSize() > 0) { if (!(file.getContentType().indexOf("image/") >= 0)) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,"Soubor není typu obrázek!","")); } } } }
[ "sajwy@seznam.cz" ]
sajwy@seznam.cz
3f7d558e1ba45cac1e15d026f539d892af2b17c7
7f67d711d6f419c7dfbf3a20bc2a57c793c8cf19
/easyshop-common/src/main/java/com/easyshop/common/core/page/TableSupport.java
89b0b313416f9147f34fb6b4ec570abec48f3333
[ "MIT" ]
permissive
ArchivesTeam/easyshop
480a93610b400946bb82d96d7e67439b717ef37b
3101b50ae7d1c4cfb531c73947cd0a7afde43924
refs/heads/master
2020-05-04T07:21:28.108048
2019-04-11T11:49:08
2019-04-11T11:49:08
179,025,565
0
0
null
null
null
null
UTF-8
Java
false
false
818
java
package com.easyshop.common.core.page; import com.easyshop.common.constant.Constants; import com.easyshop.common.utils.ServletUtils; /** * 表格数据处理 * * @author ruoyi */ public class TableSupport { /** * 封装分页对象 */ public static PageDomain getPageDomain() { PageDomain pageDomain = new PageDomain(); pageDomain.setPageNum(ServletUtils.getParameterToInt(Constants.PAGE_NUM)); pageDomain.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE)); pageDomain.setOrderByColumn(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN)); pageDomain.setIsAsc(ServletUtils.getParameter(Constants.IS_ASC)); return pageDomain; } public static PageDomain buildPageRequest() { return getPageDomain(); } }
[ "majingyuanno.1@gmail.com" ]
majingyuanno.1@gmail.com
395a9a131381f6dce5d087bc8a5b288a2bce4d40
abff13a042e8c62ac919fb3a9781976407c62716
/src/main/java/org/spring/freemarker/common/utils/TimeLength.java
58465fc869d92d83b440c264df1dc2c88af469d5
[]
no_license
michealCM/spring-freemarker-ext
cc1b6af9e5f971fef83648c04d3425c1e28c028f
ae9f79478c4b19b5ce2b177addf70c9bc99c74ab
refs/heads/master
2020-04-06T09:46:42.865144
2019-01-02T02:29:06
2019-01-02T02:29:06
157,356,209
1
0
null
null
null
null
UTF-8
Java
false
false
1,499
java
package org.spring.freemarker.common.utils; import java.util.concurrent.TimeUnit; /** * * * @date 2018-11-23 11:19:47 */ public final class TimeLength { public static final TimeLength ZERO = TimeLength.seconds(0); public static TimeLength days(long days) { return new TimeLength(days, TimeUnit.DAYS); } public static TimeLength hours(long hours) { return new TimeLength(hours, TimeUnit.HOURS); } public static TimeLength minutes(long minutes) { return new TimeLength(minutes, TimeUnit.MINUTES); } public static TimeLength seconds(long seconds) { return new TimeLength(seconds, TimeUnit.SECONDS); } private final long length; private final TimeUnit unit; private TimeLength(long length, TimeUnit unit) { this.length = length; this.unit = unit; } public long length() { return length; } public TimeUnit unit() { return unit; } public long toMilliseconds() { return unit.toMillis(length); } public long toSeconds() { return unit.toSeconds(length); } @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof TimeLength)) return false; return toMilliseconds() == ((TimeLength) other).toMilliseconds(); } @Override public int hashCode() { long mills = toMilliseconds(); return (int) (mills ^ (mills >>> 32)); } }
[ "569145123@qq.com" ]
569145123@qq.com
53c061ef4246998304c5b55c963f2b62830d9572
00bb1051395d351ded97c07fed17299a1cce9977
/core/src/org/tetawex/tms/ui/MainMenuScreen.java
14125afd3de4be0f058d3063356e6beef73f5734
[]
no_license
Tetawex/the-mighty-smith
89598d5eddde54409bc458787c5e81f6237a9c38
45bdcb671d37d383f81003595fb8fbd91ce93676
refs/heads/master
2021-01-09T05:24:16.587908
2017-02-27T17:34:11
2017-02-27T17:34:11
77,287,585
0
0
null
null
null
null
UTF-8
Java
false
false
3,805
java
package org.tetawex.tms.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable; import com.badlogic.gdx.utils.viewport.ExtendViewport; import org.tetawex.tms.core.GameStateManager; import org.tetawex.tms.core.TMSGame; /** * Created by Tetawex on 28.12.2016. */ public class MainMenuScreen implements Screen { private Stage stage; private TMSGame game; public MainMenuScreen(TMSGame game) { this.game=game; stage=new Stage(new ExtendViewport(320,180,new OrthographicCamera(320f,180f))); Gdx.input.setInputProcessor(stage); initUi(); } private void initUi() { Skin skin = new Skin(); skin.addRegions(game.getAssetManager().get("atlas.atlas",TextureAtlas.class)); TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle(); NinePatch patch = skin.getPatch("ui_button_default"); NinePatchDrawable ninePatch = new NinePatchDrawable(patch); textButtonStyle.font = game.getAssetManager().get("font.fnt",BitmapFont.class); textButtonStyle.font.getData().setScale(0.5f); textButtonStyle.up = new Image(ninePatch).getDrawable(); patch = skin.getPatch("ui_button_pressed"); ninePatch = new NinePatchDrawable(patch); textButtonStyle.down = new Image(ninePatch).getDrawable(); Table mainTable=new Table(); stage.addActor(mainTable); Table midColumnTable = new Table(); TextButton playButton=new TextButton("play", textButtonStyle); playButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { game.getGameStateManager().setState(GameStateManager.GameState.GAME); } }); TextButton quitButton=new TextButton("quit", textButtonStyle); quitButton.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { game.dispose(); Gdx.app.exit(); } }); mainTable.setFillParent(true); mainTable.setFillParent(true); mainTable.add(midColumnTable).expandY().center(); midColumnTable.row(); midColumnTable.add(playButton).pad(4).prefSize(64,32); midColumnTable.row(); midColumnTable.add(new TextButton("settings", textButtonStyle)).pad(4).prefSize(64,32); midColumnTable.row(); midColumnTable.add(quitButton).pad(4).prefSize(64,32); midColumnTable.row().expandY(); //mainTable.setDebug(true); //midColumnTable.setDebug(true); } @Override public void show() { } @Override public void render(float delta) { stage.act(delta); stage.draw(); } @Override public void resize(int width, int height) { stage.getViewport().update(width,height,true); stage.getViewport().getCamera().update(); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
[ "tetawex@gmail.com" ]
tetawex@gmail.com
99985e28d0b8cc474340e95b44a0df7c331de299
823666c888d26a48d46e9fe00d1a174818ae99f6
/spring/DouglasAlmeida/cx-academy/src/main/java/com/nttdata/spring/cxacademy/service/CustomerService.java
f372017672688f00d89ca5e7d2cbf2f978a04755
[]
no_license
cesardanielntt/cx-academy
56a6713b69d9ad9c8244b9d86b425b56275c4ba3
1880da0e4f8b18c6dbd7b8c182599ba0d011bc40
refs/heads/master
2023-07-02T06:16:02.044162
2021-08-02T19:13:18
2021-08-02T19:13:18
383,924,414
0
6
null
2021-08-02T19:13:19
2021-07-07T21:05:46
Java
UTF-8
Java
false
false
368
java
package com.nttdata.spring.cxacademy.service; import com.nttdata.spring.cxacademy.model.CustomerModel; import java.util.List; public interface CustomerService { List<CustomerModel> getAllCustomers(); void saveCustomer(CustomerModel customer); CustomerModel getCustomerByCode(Integer customerCode); void deleteCustomer(Integer customerCode); }
[ "douglas.almeida02@hotmail.com" ]
douglas.almeida02@hotmail.com
89d3dcdac88181e5f4616c0ca954381bc7f585f7
948f2c7e44b79ca742249b28a27117fc60c7091c
/Java/FestivaluriClientServer/src/main/java/Repository/AngajatDBRepository.java
7a35ee6a78639d377a49c40afd1a6b7b10628f08
[]
no_license
AlexMihail/PersonalProjects
e97861b094931fce5d0abbff48917109e6b39a36
7115fae1c03839214c01c11d5253e84b014cea17
refs/heads/master
2020-05-30T16:24:53.014917
2019-06-02T12:30:55
2019-06-02T12:30:55
189,844,053
0
0
null
null
null
null
UTF-8
Java
false
false
4,687
java
package Repository; import Model.Angajat; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; public class AngajatDBRepository implements IAngajatRepository { private JdbcUtils dbUtils; public AngajatDBRepository() { Properties serverProps=new Properties(); try{ serverProps.load(AngajatDBRepository.class.getResourceAsStream("/server.properties")); System.out.println("Server properties set."); serverProps.list(System.out); } catch (IOException e) { System.err.println("Cannot find sever properties" + e); return; } dbUtils= new JdbcUtils(serverProps); } @Override public Angajat findByUsername(String username) { Connection con=dbUtils.getConnection(); Angajat an = null; try(PreparedStatement preStmt=con.prepareStatement("select * from Angajati where username = ?")) { preStmt.setString(1,username); try(ResultSet result=preStmt.executeQuery()) { if (result.next()) { int id = result.getInt("id"); String user= result.getString("username"); String parola = result.getString("parola"); an = new Angajat(user,parola); an.setId(id); } } } catch (SQLException e) { System.out.println("Error DB "+e); } return an; } @Override public Angajat findOne(Integer integer) { Connection con=dbUtils.getConnection(); Angajat an = null; try(PreparedStatement preStmt=con.prepareStatement("select * from Angajati where id = ?")) { preStmt.setInt(1,integer); try(ResultSet result=preStmt.executeQuery()) { if (result.next()) { int id = result.getInt("id"); String user= result.getString("username"); String parola = result.getString("parola"); an = new Angajat(user,parola); an.setId(id); } } } catch (SQLException e) { System.out.println("Error DB "+e); } return an; } @Override public List<Angajat> findAll() { Connection con=dbUtils.getConnection(); List<Angajat> angajati=new ArrayList<>(); try(PreparedStatement preStmt=con.prepareStatement("select * from Angajati")) { try(ResultSet result=preStmt.executeQuery()) { while (result.next()) { int id = result.getInt("id"); String username= result.getString("username"); String parola = result.getString("parola"); Angajat an = new Angajat(username,parola); an.setId(id); angajati.add(an); } } } catch (SQLException e) { System.out.println("Error DB "+e); } return angajati; } @Override public void save(Angajat entity) { Connection con=dbUtils.getConnection(); try(PreparedStatement preStmt=con.prepareStatement("insert into Angajati(username,parola) values (?,?)")){ //preStmt.setInt(1,entity.getId()); preStmt.setString(1,entity.getUsername()); preStmt.setString(2,entity.getPassword()); int result=preStmt.executeUpdate(); }catch (SQLException ex){ System.out.println("Error DB "+ex); } } @Override public void delete(Integer id) { Connection con=dbUtils.getConnection(); try(PreparedStatement preStmt=con.prepareStatement("delete from Angajati where id=?")){ preStmt.setInt(1,id); int result=preStmt.executeUpdate(); }catch (SQLException ex){ System.out.println("Error DB "+ex); } } @Override public void update(Integer id,Angajat an) { Connection con=dbUtils.getConnection(); try(PreparedStatement preStmt=con.prepareStatement("update Angajati set username= ?, parola = ? where id = ? ")){ preStmt.setString(1,an.getUsername()); preStmt.setString(2,an.getPassword()); preStmt.setInt(3,id); int result=preStmt.executeUpdate(); }catch (SQLException ex){ System.out.println("Error DB "+ex); } } }
[ "alex.mihail.craciun@gmail.com" ]
alex.mihail.craciun@gmail.com
37b6af8247846c19ab958826adc3d67ae49a4198
65a43b0e72289cfe6acf23164477125a75247d5e
/src/Paquete/FtpServidor.java
1fe39b9e1285989d5a8e5f00be3691967d7c0e6d
[]
no_license
cesarwelch/ProyectoFtpServer
287cd8569dec93b6618dfc1912488c183f7b09ed
938008fd17a538b1f92342da220dda5eb97a9a36
refs/heads/master
2021-01-18T18:16:09.483566
2015-08-17T02:47:10
2015-08-17T02:47:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,688
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Paquete; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.ftpserver.FtpServer; import org.apache.ftpserver.FtpServerFactory; import org.apache.ftpserver.ftplet.*; import org.apache.ftpserver.listener.ListenerFactory; import org.apache.ftpserver.usermanager.PasswordEncryptor; import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory; import org.apache.ftpserver.usermanager.impl.BaseUser; import org.apache.ftpserver.usermanager.impl.WritePermission; /** * * @author Alberto */ public class FtpServidor { private FtpServerFactory factory; private ListenerFactory listener; private FtpServer server; private ArrayList<User> usersList; public FtpServidor() { } public ArrayList<Paquete.User> getUsersList() { return usersList; } public void setUsersList(ArrayList<Paquete.User> usersList) { this.usersList = usersList; } public FtpServerFactory getFactory() { return factory; } public void setFactory(FtpServerFactory factory) { this.factory = factory; } public ListenerFactory getListener() { return listener; } public void setListener(ListenerFactory listener) { this.listener = listener; } public FtpServer getServer() { return server; } public void setServer(FtpServer server) { this.server = server; } public boolean iniciar() { boolean levantado = false; factory = new FtpServerFactory(); listener = new ListenerFactory(); listener.setPort(2221); factory.addListener("default", listener.createListener()); //PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory(); //userManagerFactory.setFile(new File("/ftp/data/config.xml"));//choose any. We're telling the FTP-server where to read it's user list /*userManagerFactory.setPasswordEncryptor(new PasswordEncryptor() {//We store clear-text passwords in this example @Override public String encrypt(String password) { return password; } @Override public boolean matches(String passwordToCheck, String storedPassword) { return passwordToCheck.equals(storedPassword); } }); for (int i = 0; i < usersList.size(); i++) { User current = usersList.get(i); BaseUser user = new BaseUser(); user.setName(current.getUsername()); user.setPassword(current.getPassword()); user.setHomeDirectory("/ftp/data/" + current.getUsername()); List<Authority> authorities = new ArrayList(); authorities.add(new WritePermission()); user.setAuthorities(authorities); UserManager um = userManagerFactory.createUserManager(); try { um.save(user); } catch (FtpException e1) { } factory.setUserManager(um); }*/ Map<String, Ftplet> m = new HashMap<String, Ftplet>(); m.put("miaFtplet", new Ftplet() { @Override public void init(FtpletContext ftpletContext) throws FtpException { } @Override public void destroy() { } @Override public FtpletResult beforeCommand(FtpSession session, FtpRequest request) throws FtpException, IOException { return FtpletResult.DEFAULT;//...or return accordingly } @Override public FtpletResult afterCommand(FtpSession session, FtpRequest request, FtpReply reply) throws FtpException, IOException { return FtpletResult.DEFAULT;//...or return accordingly } @Override public FtpletResult onConnect(FtpSession session) throws FtpException, IOException { return FtpletResult.DEFAULT;//...or return accordingly } @Override public FtpletResult onDisconnect(FtpSession session) throws FtpException, IOException { return FtpletResult.DEFAULT;//...or return accordingly } }); factory.setFtplets(m); server = factory.createServer(); try { server.start(); } catch (FtpException ex) { } return levantado; } }
[ "4lbertyson@gmail.com" ]
4lbertyson@gmail.com
72fbc59d771cd717dd64fadd198de3b5608757ec
fe12983a6303f3d6cbf014255427832198b5a7cc
/src/main/java/io/trabe/teaching/rest/model/pojo/api/external/ApiUserRequest.java
a259be12436a22a72f0bee96119ffd6e3cb18fb0
[]
no_license
lrcortizo/rest-api-design-course
9a4356904d1b431c2cfdeb9135270cbdde8b30cc
a6415b8dc83d4a2fbaceda5cb580c06c8c50421e
refs/heads/master
2020-10-02T01:07:36.427640
2019-12-12T17:53:36
2019-12-12T17:53:36
227,664,650
0
0
null
null
null
null
UTF-8
Java
false
false
171
java
package io.trabe.teaching.rest.model.pojo.api.external; import lombok.Builder; import lombok.Data; @Builder @Data public class ApiUserRequest { private String login; }
[ "xx651@globalia.com" ]
xx651@globalia.com
e9e0ab57a3a14d99b22759f00d06fe1d6078a408
6286216613d73af15e77a73f5c7b7aea1bda6f84
/TileEntities/TileEntityGasDuct.java
7f76795a0188c906c926435a463ee27e46e3e089
[]
no_license
Dabblecraft2DevTeam/ReactorCraft
f6301180a56329bb5a0dffc848c58e80f39d0f39
6b31af5ee01564f312738d6c371bd38f6aebce19
refs/heads/master
2020-06-12T21:04:51.364719
2016-10-11T02:26:17
2016-10-11T02:26:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,887
java
/******************************************************************************* * @author Reika Kalseki * * Copyright 2016 * * All rights reserved. * Distribution of the software in any form is only allowed with * explicit, prior permission from the owner. ******************************************************************************/ package Reika.ReactorCraft.TileEntities; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import Reika.ReactorCraft.Base.TileEntityReactorPiping; import Reika.ReactorCraft.Registry.ReactorTiles; public class TileEntityGasDuct extends TileEntityReactorPiping { @Override public int getIndex() { return ReactorTiles.GASPIPE.ordinal(); } @Override public IIcon getBlockIcon() { return Blocks.hardened_clay.getIcon(1, 0); } public boolean isConnectedToNonSelf(ForgeDirection dir) { if (!this.isConnectionValidForSide(dir)) return false; if (dir.offsetX == 0 && MinecraftForgeClient.getRenderPass() != 1) dir = dir.getOpposite(); int dx = xCoord+dir.offsetX; int dy = yCoord+dir.offsetY; int dz = zCoord+dir.offsetZ; World world = worldObj; Block id = world.getBlock(dx, dy, dz); int meta = world.getBlockMetadata(dx, dy, dz); return id != this.getMachine().getBlock() || meta != this.getMachine().getBlockMetadata(); } @Override public boolean isValidFluid(Fluid f) { return f.isGaseous(); } @Override protected void onIntake(TileEntity te) { } @Override public Block getPipeBlockType() { return Blocks.hardened_clay; } @Override public IIcon getGlassIcon() { return Blocks.glass.getIcon(0, 0); } }
[ "reikasminecraft@gmail.com" ]
reikasminecraft@gmail.com
97714a5710b9361ab83bf4731a00f21786e92f64
31e9708e20f9f3176b9f4d7c70ff36d9fa0dbec9
/app/src/main/java/com/example/jeneska/gamewishlist/GameDatabase.java
540dada37765f843a4558ec68fdb794a0cf30dc9
[]
no_license
jabano/GameWishList
74960584d07dc5bf5eaacfbfbf0841d15b058937
ede57d82193e567c41cc6a729b14d6c24f1c57ad
refs/heads/master
2020-04-17T12:45:57.481035
2019-01-22T03:00:23
2019-01-22T03:00:23
166,591,579
0
0
null
null
null
null
UTF-8
Java
false
false
960
java
package com.example.jeneska.gamewishlist; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; @Database(entities = {Game.class}, version = 1) public abstract class GameDatabase extends RoomDatabase { public abstract GameDao gameDao(); private static volatile GameDatabase mGameDb; static GameDatabase getGameDb(final Context context) { if (mGameDb == null) { synchronized (GameDatabase.class) { if(mGameDb == null) { mGameDb = buildDbInstance(context); } } } return mGameDb; } private static GameDatabase buildDbInstance(Context context) { return Room.databaseBuilder(context.getApplicationContext(), GameDatabase.class, "gameDb").build(); } public void cleanUp() { mGameDb = null; } }
[ "jabano@users.noreply.github.com" ]
jabano@users.noreply.github.com
c6fa8223bec5c6695605fef0fef38963786321d4
fc939a49aeaaccf8aef1794e9b0adb1901adfc6e
/app/src/main/java/com/example/ch/shixiaodong/callback/ICallBack.java
e56de9bc587d5dd63cef96ee9a3644b121f1e24e
[]
no_license
sxdjob123/ShiXiaoDong
691c2c7d3e71a7eb7bffbc6cadc557fc4fca071b
c7270be541b9a7f4ed3711f24f936a0a0e599106
refs/heads/master
2020-06-03T18:49:19.451427
2019-06-13T04:08:57
2019-06-13T04:08:57
191,688,977
0
0
null
null
null
null
UTF-8
Java
false
false
266
java
package com.example.ch.shixiaodong.callback; import com.example.ch.shixiaodong.bean.Student; import java.util.List; /** * Created by 76165 * on 2019/6/13 */ public interface ICallBack { void onSuccess(List<Student> list); void onFail(String error); }
[ "761651982@qq.com" ]
761651982@qq.com
e2f5d1c362cbf9f01a25e48b8ec56187d0571911
8bae72f6ac1d914d1f745496ea77d59c6ab5a4dd
/Java/src/domains/algorithms/Warmup/ChocolateFeastTest.java
c07133eb9c1f46878165046568f66ca2c2a87ec9
[]
no_license
Manish-Giri/HackerRank
2ef00f00b327f89d3be73018dde8e63680a1c9e8
852310136d374c311df4a4755b391a6b4bbc4834
refs/heads/master
2022-10-14T17:56:51.299521
2022-10-07T05:30:21
2022-10-07T05:30:21
33,174,122
7
7
null
null
null
null
UTF-8
Java
false
false
1,759
java
package domains.algorithms.Warmup; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by manishgiri on 4/8/15. */ public class ChocolateFeastTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter number of test cases:"); int T = Integer.parseInt(sc.nextLine()); List<Integer> result = new ArrayList<>(T); for(int i = 0; i < T; i++) { int numChoc = 0; int[] numbers = new int[3]; System.out.println("Enter N, C, M separated by spaces"); String next = sc.nextLine(); String[] nextSplit = next.split(" "); int item; for(int p = 0; p < 3; p++) { item = Integer.parseInt(nextSplit[p]); numbers[p] = item; } int N = numbers[0]; int C = numbers[1]; int M = numbers[2]; numChoc = N/C; if(numChoc < M) { result.add(numChoc); } else if(numChoc == M) { numChoc++; result.add(numChoc); } else if(numChoc > M) { int w = numChoc; do { int newchoc = w/M; int left = w%M; numChoc += newchoc; numChoc += left; w += left; } while ( w % M != 0); result.add(numChoc); } } System.out.println("Total number of chocolates:"); for(int i = 0; i < result.size(); i++) { System.out.println(result.get(i)); } } }
[ "manish.giri.me@gmail.com" ]
manish.giri.me@gmail.com
7f4ef538794e710175b7af34b82316e127b80b58
1a1c297118b653f98eef9d8f449f3831d03adefc
/src/main/java/com/izeye/playground/support/unit/domain/Unit.java
fc60b576da6e273c84923847bc82b023c2d12a59
[]
no_license
izeye/playground
c2f97d66ad12f74a3060c1c6f4b6487bc23efdab
12d199446876020f34344756ad6bb94cac8e6dd6
refs/heads/master
2020-06-04T19:44:35.218383
2013-12-07T16:04:18
2013-12-07T16:04:18
11,101,662
1
0
null
null
null
null
UTF-8
Java
false
false
226
java
package com.izeye.playground.support.unit.domain; import java.math.BigDecimal; public interface Unit<T extends Unit<?>> { String getName(); String getKey(); BigDecimal convert(BigDecimal sourceValue, T sourceUnit); }
[ "izeye@naver.com" ]
izeye@naver.com
b03f4bcc200d11e87c5b6b8c7855143873e45297
261e6bbe8da52787b06cd79b4990d9c4c5cfa77e
/app/src/main/java/com/example/educor_app/Assignment/Comments/RecyclerAdapter_comments.java
e001b5b5b6b0b4488864df67cb4a786b927f13a7
[]
no_license
johnsolomon1610/Educor_app
43ad391793b1c3cb2fb7345fbf2c12dcd0b9eee5
e3f37b59802c0e3a1e8f39868c661c2b0ff5ba57
refs/heads/master
2023-08-18T20:53:37.294003
2021-10-06T09:49:23
2021-10-06T09:49:23
414,104,599
2
1
null
null
null
null
UTF-8
Java
false
false
1,784
java
package com.example.educor_app.Assignment.Comments; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.example.educor_app.R; import java.util.ArrayList; public class RecyclerAdapter_comments extends RecyclerView.Adapter<RecyclerAdapter_comments.MyViewHolder> { Context context; ArrayList<comments> data; public RecyclerAdapter_comments(Context c , ArrayList<comments> p) { context = c; data= p; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.recyclerview_comments, parent, false)); } @Override public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) { holder.comment.setText(data.get(position).getComments()); holder.student_name.setText(data.get(position).getStudent_name()); holder.date.setText(data.get(position).getDate()); } @Override public int getItemCount() { return data.size(); } static class MyViewHolder extends RecyclerView.ViewHolder { TextView comment,student_name,date; CardView cardView; public MyViewHolder(View itemView) { super(itemView); comment = itemView.findViewById(R.id.comments); student_name = itemView.findViewById(R.id.name); date=itemView.findViewById(R.id.Date); cardView = itemView.findViewById(R.id.cardview1); } } }
[ "littlejohnsolomon@gmail.com" ]
littlejohnsolomon@gmail.com
1355e134f01a4f398d49056d140e9afcf59b0f23
60c083730b88157d505f3fc9308e7a00a88e921e
/src/main/java/com/example/springboottest/web/dto/PostsResponseDto.java
a885e7ddd439bbcae0f07444b732a5fe49db65e5
[]
no_license
wintersky-c/springbootTest1
e9e7f2d8af4f3b9ae0a582a3613bd7398757207e
17839257a8969abcce86b8ad7e8ae4826562c041
refs/heads/master
2023-05-06T10:21:38.168120
2021-05-29T07:03:10
2021-05-29T07:03:10
371,034,489
0
0
null
null
null
null
UTF-8
Java
false
false
480
java
package com.example.springboottest.web.dto; import com.example.springboottest.domain.posts.Posts; import lombok.Getter; @Getter public class PostsResponseDto { private Long id; private String title; private String content; private String author; public PostsResponseDto(Posts entity) { this.id = entity.getId(); this.title = entity.getTitle(); this.content = entity.getContent(); this.author = entity.getAuthor(); } }
[ "wintersky.c@gmail.com" ]
wintersky.c@gmail.com
a92d363ccbce56702231e4c09e51cb0179ce76bb
1286b5c1e30c049e3bccff44c6bcd3356e562a7d
/src/main/java/com/bms/rms/model/po/TMenuCustom.java
c9c2ee3db479312fe3ac0f6867031571ab9ead8c
[]
no_license
Togal/zh_rms
a0cd5cc26eec39fc4cb8e3a4a41e1ea33cc4ae03
52006522785fb43039460662bb4d01004b1b09c3
refs/heads/master
2021-01-13T07:57:43.066306
2016-11-09T16:04:05
2016-11-09T16:04:05
68,834,305
1
0
null
2016-11-09T16:04:06
2016-09-21T16:04:30
Java
UTF-8
Java
false
false
1,062
java
package com.bms.rms.model.po; import java.util.List; import com.bms.data.type.conversion.date.DateDataTypeConversion; import com.bms.data.type.conversion.date.vo.DATEFORMAT; /** * * Title:TMenuCustom * Description:菜单扩展类 * @author zwb * @date 2016年9月29日 下午2:12:32 * */ public class TMenuCustom extends TMenu { private List<TMenuCustom> slaveChildrenMenus;//从菜单的子菜单 private TPrivilege privilege;//权限 /** * 获取添加时间戳转日期结果 * @param date * @return */ public String getAddTimeToDate(){ return DateDataTypeConversion.timeMillisToDate(getAddtime(), true, DATEFORMAT.YYYY_MM_DD_HH_MM); } public List<TMenuCustom> getSlaveChildrenMenus() { return slaveChildrenMenus; } public void setSlaveChildrenMenus(List<TMenuCustom> slaveChildrenMenus) { this.slaveChildrenMenus = slaveChildrenMenus; } public TPrivilege getPrivilege() { return privilege; } public void setPrivilege(TPrivilege privilege) { this.privilege = privilege; } }
[ "zhangweibao@kugou.net" ]
zhangweibao@kugou.net
25060a12d6aaf42a61fc528917d4cc21dde646df
cf6849f32db9c75853926b0376f9e9ecce29d420
/app/src/test/java/com/firstexample/emarkova/session5/ExampleUnitTest.java
371a7cefd7fc574ffd9958e77133507f279d1f96
[]
no_license
katemeronandroid/Session5
e64f9323a3d924a45a37a7e8d6e0a060fe940b8f
d06edf7eb14d9b5b9fb38bd5096299524ffdc5a4
refs/heads/master
2020-03-21T07:53:28.560905
2018-06-22T13:34:36
2018-06-22T13:34:36
138,306,107
0
0
null
null
null
null
UTF-8
Java
false
false
395
java
package com.firstexample.emarkova.session5; 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() { assertEquals(4, 2 + 2); } }
[ "djisachan@gmail.com" ]
djisachan@gmail.com
33052b523a1522b8d6dfe092196e8cfd05c33f8e
e039da93350c4e23ef8592b96afb1dc12d0b87df
/app/src/main/java/com/jwzt/caibian/util/DateTimeUtils.java
81ffaa5da6375eab2502dcd68f3d76ffc51b124e
[]
no_license
lilaishun/JWZTCBProduct
38d7a566f9ee6d2f8b8f96a5ae195cb5f5813373
34f950df777351132c81b355b17bd7624e0e9bf6
refs/heads/master
2020-05-26T22:45:18.098965
2019-05-24T10:19:17
2019-05-24T10:19:17
188,400,965
0
3
null
null
null
null
UTF-8
Java
false
false
20,594
java
package com.jwzt.caibian.util; import android.annotation.SuppressLint; import android.content.Context; import android.text.TextUtils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @SuppressLint("SimpleDateFormat") public class DateTimeUtils { /** * @function getMsgShowTime 获取显示的日期,格式有三种:今天 、昨天、月/日 * @param timestamp long 毫秒级的时间戳 * @return String */ public static String getShowDate(long timestamp, Context context) { if (timestamp <= 0 || null == context) { return null; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("MM/dd");// 默认的日期格式 SimpleDateFormat dayFormat = new SimpleDateFormat("dd"); // 获取今天的日期 Calendar calendar = Calendar.getInstance(); String today = dayFormat.format(calendar.getTime()); // 获取昨天的日期 calendar.add(Calendar.DATE, -1);// 日期减一 String yesterday = dayFormat.format(calendar.getTime()); // 获取给定时间戳的日期 calendar.setTimeInMillis(timestamp); String day = dayFormat.format(calendar.getTime()); if (day.equals(today)) { return "今天"; } else if (day.equals(yesterday)) { return "昨天"; } else { return defaultDateFormat.format(calendar.getTime()); } } /** * @function 将yyyy-MM-dd HH:mm:ss转化为三种:今天 、昨天、月/日 * @return String */ public static String getStringDate(String dateString, Context context) { if (null == context) { return null; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 Date date; try { date = defaultDateFormat.parse(dateString); } catch (ParseException e) { e.printStackTrace(); return null; } return getShowDate(date.getTime(), context); } /** * @function yyyy-MM-dd HH:mm:ss --> yyyy年MM月dd日 HH:mm * @return String */ public static String getStringDateLocal(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormat1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");// 默认的日期格式 Date date; try { date = defaultDateFormat.parse(dateString); } catch (ParseException e) { return ""; } return defaultDateFormat1.format(date); } /** * @function yyyy-MM-dd HH:mm:ss --> dd日 HH:mm * @return String */ public static String getStringDayTime(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormat1 = new SimpleDateFormat("dd日 HH:mm");// 默认的日期格式 Date date; try { date = defaultDateFormat.parse(dateString); } catch (ParseException e) { return ""; } return defaultDateFormat1.format(date); } /** * @function yyyy-MM-dd HH:mm:ss --> dd日 HH:mm * @return String */ public static String getStringDay2(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormat1 = new SimpleDateFormat("dd日 HH:mm");// 默认的日期格式 Date date; try { date = defaultDateFormat.parse(dateString); } catch (ParseException e) { return ""; } return defaultDateFormat1.format(date); } /** * @function yyyy-MM-dd --> MM-dd * @return String */ public static String getStringDay(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 默认的日期格式 SimpleDateFormat defaultDateFormat1 = new SimpleDateFormat("MM-dd");// 默认的日期格式 Date date; try { date = defaultDateFormat.parse(dateString); } catch (ParseException e) { return ""; } return defaultDateFormat1.format(date); } /** * 将"yyyy-MM-dd HH:mm:ss" --> "yyyy年MM月dd日" * * @param dateString * @return */ public static String getStringDateTrans(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormatSrc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormatDst = new SimpleDateFormat("yyyy年MM月dd日");// 默认的日期格式 Date date; try { date = defaultDateFormatSrc.parse(dateString); } catch (ParseException e) { e.printStackTrace(); return ""; } return defaultDateFormatDst.format(date); } /** * 将"yyyy-MM-dd HH:mm:ss" --> "yyyy-MM-dd HH:mm" * * @param dateString * @return */ public static String getStringDateTrans2(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormatSrc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormatDst = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date date; try { date = defaultDateFormatSrc.parse(dateString); } catch (ParseException e) { e.printStackTrace(); return ""; } return defaultDateFormatDst.format(date); } /** * 将"yyyy-MM-dd HH:mm:ss" --> "yyyy-MM-dd" * * @param dateString * @return */ public static String getStringDateTrans3(String dateString) { if (TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat defaultDateFormatSrc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormatDst = new SimpleDateFormat("yyyy-MM-dd"); Date date; try { date = defaultDateFormatSrc.parse(dateString); } catch (ParseException e) { e.printStackTrace(); return ""; } return defaultDateFormatDst.format(date); } /** * yyyy-MM-dd HH:mm:ss --> 时间戳 */ public static long parseDateTime(String dateTime) { if (TextUtils.isEmpty(dateTime)) { return 0; } long time = 0; try { Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTime); if (null != date) { time = date.getTime(); } } catch (ParseException e) { e.printStackTrace(); } return time; } /** * 可以处理1970年以前的日期 * @return 输出格式为:yyyy-MM-dd */ public static String getStringDate(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); return sf.format(new Date(timestamp)); } /** * @return 输出格式为:yyyy年MM月dd日 */ public static String getStringDateCh(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日"); return sf.format(new Date(timestamp)); } /** * @return 输出格式为:MM月dd日 */ public static String getStringDateSimpleCh(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("MM月dd日"); return sf.format(new Date(timestamp)); } /** * yyyy年MM月dd日HH时 */ public static String getStringYMDH(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH时"); return sf.format(new Date(timestamp)); } /** * @return 输出格式为:yyyy年MM月dd日 HH:mm */ public static String getStringDateTime(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); return sf.format(new Date(timestamp)); } public static String getStringDateTimeNew(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sf.format(new Date(timestamp)); } /** * @return 输出格式为:yyyy-MM-dd HH */ public static String getStringDateTime2(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时"); return sf.format(new Date(timestamp)); } /** * @function getShowTime 获取显示的时间,格式为:HH:mm */ public static String getShowTime(long timestamp) { SimpleDateFormat formatter = new SimpleDateFormat("HH:mm"); Date curDate = new Date(timestamp); return formatter.format(curDate); } /** * 可以处理1970年以前的数据 * @function getShowTime 获取显示的时间,格式为:yyyy-MM-dd hh:mm:ss */ public static String getFullTime(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sf.format(new Date(timestamp)); } public static String getFullerTime(long timestamp) { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); return sf.format(new Date(timestamp)); } /** * xx年xx天xx小时 * @return */ public static String getYearDayHourString(long timestamp) { if (timestamp < 0) return ""; long year = timestamp / (365 * 24 * 3600); String dayHour = getStringDayHour(timestamp % (365 * 24 * 3600)); StringBuilder sb = new StringBuilder(); if (year > 0) sb.append(year).append("年"); if (!TextUtils.isEmpty(dayHour)) sb.append(dayHour); return sb.toString(); } /** * xx天xx小时 */ public static String getStringDayHour(long timestamp) { if (timestamp < 0) return ""; long tian = timestamp / (24 * 3600); long xiaoshi = (timestamp % (24 * 3600)) / 3600; StringBuilder sb = new StringBuilder(); if (tian > 0) sb.append(tian).append("天"); if (xiaoshi > 0) sb.append(xiaoshi).append("小时"); if (TextUtils.isEmpty(sb.toString())) { sb.append("不足一小时"); } return sb.toString(); } /** * xx天xx小时xx分 */ public static String getStringIntervalTime(long timestamp) { if (timestamp <= 0) return ""; long tian = timestamp / (24 * 3600); long xiaoshi = (timestamp % (24 * 3600)) / 3600; long fen = ((timestamp % (24 * 3600)) % 3600) / 60; StringBuilder sb = new StringBuilder(); if (tian > 0) sb.append(tian).append("天"); if (xiaoshi > 0) sb.append(xiaoshi).append("小时"); if (fen > 0) sb.append(fen).append("分"); return sb.toString(); } /** * @function getMsgShowTime 获取显示的日期,格式有:今天: xx点、昨天:月/日 * @return String */ public static String getRecordShowDate(long timestamp) { if (timestamp <= 0) { return null; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 默认的日期格式 SimpleDateFormat dayFormat = new SimpleDateFormat("dd"); SimpleDateFormat sf = new SimpleDateFormat("MM月dd日"); // 获取今天的日期 Calendar calendar = Calendar.getInstance(); String today = defaultDateFormat.format(calendar.getTime()); // 获取昨天的日期 calendar.add(Calendar.DATE, -1);// 日期减一 String yesterday = sf.format(calendar.getTime()); // 获取给定的日期 calendar.setTimeInMillis(timestamp); String createDate = getShowTime(timestamp); // String createDay = dayFormat.format(calendar.getTime()); String createDay = getStringDate(timestamp); // 2014-07-11 if (createDay.equals(today)) { return createDate; } else { return createDay.substring(5, 10); } } /** * @function getMsgShowTime 获取显示的日期,格式有:今天: xx点、昨天:月/日 * @return String */ public static String getZiXunRecordShowDate(long timestamp) { if (timestamp <= 0) { return null; } SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 默认的日期格式 // 获取今天的日期 Calendar calendar = Calendar.getInstance(); String today = defaultDateFormat.format(calendar.getTime()); // 获取昨天的日期 calendar.add(Calendar.DATE, -1);// 日期减一 String yesterday = defaultDateFormat.format(calendar.getTime()); // 获取给定的日期 calendar.setTimeInMillis(timestamp); String createDate = getShowTime(timestamp); String createDay = getStringDate(timestamp); // 2014-07-11 if (createDay.equals(today)) { // 12:20 String time[] = createDate.split(":"); if (time != null && time.length == 2) { int hour = -1; try { hour = Integer.parseInt(time[0]); } catch (NumberFormatException e) { e.printStackTrace(); } if (hour >= 0 && hour < 6) { return createDate; } else if (hour >= 6 && hour < 12) { return createDate; } else if (hour >= 12 && hour < 18) { return createDate; } else if (hour >= 18 && hour < 24) { return createDate; } } return createDate; } else if (createDay.equals(yesterday)) { return "昨天" + createDate; } else { return createDay; } } /** * 计算两个时间的差值 * */ public static long getDifferenceTime(long t0, long currTime) { long diff = currTime - t0; // 微秒级别 long diffHours = diff / (1000 * 60 * 60); return diffHours; } /** * 获取预约日历界面显示的月份 * */ public static String getCalendarShowMonth(String strDate) { String[] date = strDate.split("-"); String strMonth = ""; if (null != date && date.length == 3) { try { int month = Integer.parseInt(date[1]); if (month >= 1 && month < 10) { strMonth = date[1].substring(1, date[1].length()); } else if (month >= 10 && month <= 12) { strMonth = date[1]; } } catch (NumberFormatException e) { e.printStackTrace(); } } return strMonth; } /** * 将时间戳转换成相应的日期 */ public static String formatTime(String unixDate) { if (!TextUtils.isEmpty(unixDate)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { String date = sdf.format(new Date(Long.parseLong(unixDate))); return date; } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 将date转换成相应的日期 */ public static String formatTime(Date time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { String date = sdf.format(time); return date; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 解析时间字符串 eg: 2015-04-12 * @param time 需要转换的日期 * @return 返回相应的 时间 */ public static Date stringToDate(String time) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { return format.parse(time); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 解析时间字符串 eg: 2015-04-12 10 * @param time 需要转换的日期 * @return 返回相应的 时间 */ public static Date stringToDate2(String time) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH"); try { return format.parse(time); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 将时间转换成时间戳 eg: 2015-04-12 10 * @param time 需要转换的时间 * @return 返回相应的时间戳 */ public static long timeToUnixDate2(String time) { if (!TextUtils.isEmpty(time)) { return stringToDate2(time).getTime(); } return 0; } /** * 解析时间字符串 eg: 2015-04-12 10:20 * @param time 需要转换的日期 * @return 返回相应的 时间 */ public static Date stringToDate3(String time) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { return format.parse(time); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 将时间转换成时间戳 eg: 2015-04-12 10:20 * @param time 需要转换的时间 * @return 返回相应的时间戳 */ public static long timeToUnixDate3(String time) { if (!TextUtils.isEmpty(time)) { return stringToDate3(time).getTime(); } return 0; } /** * 将时间转换成时间戳 eg: 2015-04-12 * @param time 需要转换的时间 * @return 返回相应的时间戳 */ public static long timeToUnixDate(String time) { if (!TextUtils.isEmpty(time)) { return stringToDate(time).getTime(); } return 0; } /** * 判断是不是正确的日期格式 */ public static boolean isValidDate(String time) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); format.setLenient(true); try { format.parse(time); } catch (ParseException e) { return false; } return true; } /** * @param format * 想转换成的格式 * @param time * 要转换的时间 * @return */ public static String customFormat(String format, String time) { String result = ""; if (TextUtils.isEmpty(time)) { return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = df.parse(time); SimpleDateFormat df1 = new SimpleDateFormat(format); result = df1.format(date); } catch (ParseException e) { e.printStackTrace(); } return result; } public static String strToDate(String strDate) { if (TextUtils.isEmpty(strDate)) { return ""; } SimpleDateFormat defaultDateFormatSrc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormatDst = new SimpleDateFormat("yyyy"); Date date; try { date = defaultDateFormatSrc.parse(strDate); } catch (ParseException e) { e.printStackTrace(); return ""; } return defaultDateFormatDst.format(date); } public static String strToMonthDate(String strDate) { if (TextUtils.isEmpty(strDate)) { return ""; } SimpleDateFormat defaultDateFormatSrc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormatDst = new SimpleDateFormat("MM-dd"); Date date; try { date = defaultDateFormatSrc.parse(strDate); } catch (ParseException e) { e.printStackTrace(); return ""; } return defaultDateFormatDst.format(date); } public static String strToHourMinut(String strDate) { if (TextUtils.isEmpty(strDate)) { return ""; } SimpleDateFormat defaultDateFormatSrc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 默认的日期格式 SimpleDateFormat defaultDateFormatDst = new SimpleDateFormat("HH:mm"); Date date; try { date = defaultDateFormatSrc.parse(strDate); } catch (ParseException e) { e.printStackTrace(); return ""; } return defaultDateFormatDst.format(date); } public static String getDifferenceTime2(String strDate, int days) { //获得某日加/减 x天后的日期 String result = ""; DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date d = format.parse(strDate); Calendar c = Calendar.getInstance(); c.setTime(d); c.add(c.DATE, days); //days>0 加; days<0 减 Date temp_date = c.getTime(); result = format.format(temp_date); //结果2015-08-17 } catch (ParseException e) { e.printStackTrace(); } return result; } /** * 判断给定时间是否在某一时间段内 * * @param strDate * 传入时间 yyyy-MM-dd HH:mm * @param strDateBegin * 开始时间 00:00:00 * @param strDateEnd * 结束时间 00:05:00 * @return */ public static boolean isBetweenDate(String strDate, String strDateBegin, String strDateEnd) { // 截取传入时间的时分 int strDateH = Integer.parseInt(strDate.substring(11, 13)); int strDateM = Integer.parseInt(strDate.substring(14, 16)); // 截取开始时间时分 int strDateBeginH = Integer.parseInt(strDateBegin.substring(0, 2)); int strDateBeginM = Integer.parseInt(strDateBegin.substring(3, 5)); // 截取结束时间时分 int strDateEndH = Integer.parseInt(strDateEnd.substring(0, 2)); int strDateEndM = Integer.parseInt(strDateEnd.substring(3, 5)); if ((strDateH >= strDateBeginH && strDateH <= strDateEndH)) { // 当前时间小时数在开始时间和结束时间小时数之间 if (strDateH > strDateBeginH && strDateH < strDateEndH) { return true; // 当前时间小时数等于开始时间小时数 } else if (strDateH == strDateBeginH) { return true; } // 当前时间小时数大等于开始时间小时数,等于结束时间小时数,分钟数小等于结束时间分钟数 else if (strDateH >= strDateBeginH && strDateH == strDateEndH && strDateM <= strDateEndM) { return true; } else { return false; } } else { return false; } } /** * 得到几天后的时间 * @param d * @param day * @return */ public static Date getDateAfter(Date d, int day){ Calendar now = Calendar.getInstance(); now.setTime(d); now.set(Calendar.DATE,now.get(Calendar.DATE)+day); return now.getTime(); } }
[ "lls_android@163.com" ]
lls_android@163.com
1ac5344600fa69bd4687f6fcb48c66dae2f06971
f65991f1fc3bca4964e9945c675ff7ee9f8628a1
/mediapipe/src/main/java/com/dgkris/rsspipe/feeds/models/FeedSource.java
bcb9f6b26052e79e23fbda9acf50017ba09d31b9
[ "MIT" ]
permissive
dgkris/RSSPipe
f64a93a520cac71e8e32ef99e3aa50b43ca351a2
60661ae81e40d7abd7529f42fe3eaa041584d1e5
refs/heads/master
2016-09-05T09:14:35.700637
2014-07-02T10:38:36
2014-07-02T10:38:36
21,303,742
6
3
null
null
null
null
UTF-8
Java
false
false
1,124
java
package com.dgkris.rsspipe.feeds.models; import org.bson.types.ObjectId; /** * Represents a single source entry for a feed * (id,feedurl,state,country,name, type) */ public class FeedSource { private ObjectId feedId; private String publisherName; private String feedUrl; private String state, country; public FeedSource() { } public String getFeedUrl() { return feedUrl; } public void setFeedUrl(String feedUrl) { this.feedUrl = feedUrl; } public ObjectId getFeedId() { return feedId; } public void setFeedId(ObjectId feedId) { this.feedId = feedId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getPublisherName() { return publisherName; } public void setPublisherName(String publisherName) { this.publisherName = publisherName; } }
[ "deepak@addthis.com" ]
deepak@addthis.com
369a62e27a5bf0027da5eff15027bf9918c6def1
28dd8b0cda4b054aa45ebbe06578bd49c5c11240
/src/test/java/com/haulmont/tickman/screen/ticket/EstimateMatcherTest.java
86ff9de5120fcc9bceb68e938ffa04a6cbf3c782
[]
no_license
knstvk/tickman
6af67f287806a9afc88f8f25481ffef6e7c68a82
01892862fcfae108ac178ce34277a9f32bf5deb5
refs/heads/master
2023-03-25T00:45:57.346080
2021-03-21T13:43:28
2021-03-21T13:43:28
267,277,207
1
0
null
null
null
null
UTF-8
Java
false
false
1,120
java
package com.haulmont.tickman.screen.ticket; import com.haulmont.tickman.entity.Ticket; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EstimateMatcherTest { @Test void matches() { Ticket ticket = new Ticket(); ticket.setEstimate(null); assertTrue(EstimateMatcher.matches(ticket, "0")); assertTrue(EstimateMatcher.matches(ticket, "5, 0")); assertTrue(EstimateMatcher.matches(ticket, "0, 5")); assertFalse(EstimateMatcher.matches(ticket, "5")); ticket.setEstimate(5); assertTrue(EstimateMatcher.matches(ticket, "5")); assertTrue(EstimateMatcher.matches(ticket, "5,8")); assertTrue(EstimateMatcher.matches(ticket, "8,5")); assertTrue(EstimateMatcher.matches(ticket, ">=5")); assertTrue(EstimateMatcher.matches(ticket, ">3")); assertTrue(EstimateMatcher.matches(ticket, "<=5")); assertTrue(EstimateMatcher.matches(ticket, "<8")); assertFalse(EstimateMatcher.matches(ticket, "3")); assertFalse(EstimateMatcher.matches(ticket, "a")); } }
[ "krivopustov@haulmont.com" ]
krivopustov@haulmont.com
3eedb06928c1b79264313d3013e6bf79225c0fe2
3581ea333137a694eeec2e07da2b3c7b556ac32c
/testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/client/resource/ClientResponseRedirectIntf.java
9029fe4785c0fd7c63d8447e1a8d5fe36f249d5e
[ "Apache-2.0" ]
permissive
fabiocarvalho777/Resteasy
d8b39366c50d49d197d5938b97c73b1a5cb581b5
94dae2cf6866705fe409048fde78ef2316c93121
refs/heads/master
2020-12-02T16:28:18.396872
2017-07-07T18:36:57
2017-07-07T18:36:57
96,557,475
1
0
null
2017-07-07T16:41:04
2017-07-07T16:41:04
null
UTF-8
Java
false
false
230
java
package org.jboss.resteasy.test.client.resource; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/redirect") public interface ClientResponseRedirectIntf { @GET Response get(); }
[ "asoldano@redhat.com" ]
asoldano@redhat.com
df7393ef9e2321385e69c545182f3de471848111
81ea2e31ff6a840f676d1d363015fb4c9cfb192e
/src/com/ui/BeauTextArea.java
ddf6fb22f8c94eb6c4c6f71bd5c4b570984f4b5c
[]
no_license
nomber2/admin
e8946f84c4a0f22e9e65f8ff858f926a5a6905fe
21f140d529c88ad1d9a8ae2a478799ae5c8d4e8a
refs/heads/master
2021-08-31T13:09:37.748061
2017-12-21T11:32:57
2017-12-21T11:32:57
114,998,791
0
0
null
null
null
null
UTF-8
Java
false
false
903
java
package com.ui; import javax.swing.*; import java.awt.*; /** * Created by mona on 2017/9/22. */ public class BeauTextArea extends JTextArea { private int width; private int height; private String backPath; public BeauTextArea(String backPath){ this.backPath = backPath; this.setPreferredSize(new Dimension(this.width,this.height)); this.setBackground(null); //this.setOpaque(false); this.setLineWrap(true); this.setWrapStyleWord(true); } public BeauTextArea(){ super(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); ImageIcon imageIcon = new ImageIcon(getClass().getResource("/img/"+backPath)); imageIcon.setImage(imageIcon.getImage().getScaledInstance(this.width,this.height,Image.SCALE_FAST)); imageIcon.paintIcon(this,g,0,0); } }
[ "31921871+nomber2@users.noreply.github.com" ]
31921871+nomber2@users.noreply.github.com
e5c419ee54b2e269b7831fbef092e2274e88450d
c2b110a5f4447d493f1ae9c0fc945220c09813a5
/testapiswapi/src/test/java/TestApi.java
fc054bd1204c9e137354dc5144f6b81bc903d06a
[]
no_license
WINDGLEB/qa_test_task
b12d5dda4c79a4f06c8f6dd54b9655c30b5b55e8
f21649fbd9ee4e82a62236346b5e306fb16a3edd
refs/heads/master
2021-05-04T23:16:29.525630
2018-02-04T20:24:43
2018-02-04T20:24:43
120,138,106
0
0
null
2018-02-03T23:14:00
2018-02-03T23:14:00
null
UTF-8
Java
false
false
6,020
java
import models.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; public class TestApi { private static RestTemplate restTemplate; private static HttpHeaders headers; private static HttpEntity<String> entity; private static ResponseEntity<Films> responseFilms; private static ResponseEntity<Film> responseFilm; private static ResponseEntity<People> responsePeople; private static ResponseEntity<PeopleList> responsePeopleList; @BeforeClass public static void setUp() { restTemplate = new RestTemplate(); headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"); entity = new HttpEntity<>("parameters", headers); } @Test public void testCountFilms() { responseFilms = restTemplate.exchange("https://swapi.co/api/films", HttpMethod.GET, entity, Films.class); int actualCountFilms = responseFilms.getBody().getCount(); assertEquals(7, actualCountFilms); } @Test public void testDateFilmFourEpisode() { responseFilm = restTemplate.exchange("https://swapi.co/api/films/1", HttpMethod.GET, entity, Film.class); String actualCountFilms = responseFilm.getBody().getReleaseDate(); assertEquals("1977-05-25", actualCountFilms); } @Test public void testDirectorFilmFourEpisode() { responseFilm = restTemplate.exchange("https://swapi.co/api/films/1", HttpMethod.GET, entity, Film.class); String actualDirector = responseFilm.getBody().getDirector(); assertEquals("George Lucas", actualDirector); } @Test public void testTitleFilmFourEpisode() { responseFilm = restTemplate.exchange("https://swapi.co/api/films/1", HttpMethod.GET, entity, Film.class); String actualTitle = responseFilm.getBody().getTitle(); assertEquals("A New Hope", actualTitle); } @Test public void testNamePlanetsInEpisodeTwo() { responseFilm = restTemplate.exchange("https://swapi.co/api/films/5", HttpMethod.GET, entity, Film.class); List<String> planetsUrl = responseFilm.getBody().getPlanets(); List<String> actualPlanetsName = new ArrayList<>(); for (String planetName : planetsUrl) { ResponseEntity<Planet> responsePlanet = restTemplate.exchange(planetName, HttpMethod.GET, entity, Planet.class); actualPlanetsName.add(responsePlanet.getBody().getName()); } ArrayList expectedPlanetNames = new ArrayList<String>() {{ add("Naboo"); add("Coruscant"); add("Kamino"); add("Geonosis"); add("Tatooine"); }}; assertEquals(expectedPlanetNames, actualPlanetsName); } @Test public void testHomePlanetLukeSkywalker() { responsePeople = restTemplate.exchange("https://swapi.co/api/people/1/", HttpMethod.GET, entity, People.class); String urlHomeWorldLuke = responsePeople.getBody().getHomeworld(); ResponseEntity<Planet> responsePlanet = restTemplate.exchange(urlHomeWorldLuke, HttpMethod.GET, entity, Planet.class); String actualHomeWorldName = responsePlanet.getBody().getName(); assertEquals("Tatooine", actualHomeWorldName); } @Test public void testStarshipObiInThirdEpisode() { responseFilm = restTemplate.exchange("https://swapi.co/api/films/6", HttpMethod.GET, entity, Film.class); List<String> starShipsList = responseFilm.getBody().getStarships(); String actualNameStarShip = getStarShipByObi(starShipsList).getName(); assertEquals("Jedi starfighter", actualNameStarShip); } @Test public void testParametrsStarShipByObiInThirdEpisode() { responseFilm = restTemplate.exchange("https://swapi.co/api/films/6", HttpMethod.GET, entity, Film.class); List<String> starShipsList = responseFilm.getBody().getStarships(); StarShip actualStarShip = getStarShipByObi(starShipsList); assertEquals("Kuat Systems Engineering", actualStarShip.getManufacturer()); assertEquals(180000, actualStarShip.getCostInCredits()); assertEquals(1, actualStarShip.getCrew()); assertEquals(60, actualStarShip.getCargoCapacity()); } @Test public void testIsThereAHundredthPerson() { responsePeopleList = restTemplate.exchange("https://swapi.co/api/people/", HttpMethod.GET, entity, PeopleList.class); boolean isIsThereAHundredthPerson = false; int countPeople = responsePeopleList.getBody().getCount(); if (countPeople >= 100){ isIsThereAHundredthPerson = true; } assertEquals(false, isIsThereAHundredthPerson); } private StarShip getStarShipByObi(List<String> starShipsList) { for (String starship : starShipsList) { ResponseEntity<StarShip> responseStarship = restTemplate.exchange(starship, HttpMethod.GET, entity, StarShip.class); List<String> listPilots = responseStarship.getBody().getPilots(); if (isPilotObiThisShip(listPilots)) { return responseStarship.getBody(); } } return null; } private Boolean isPilotObiThisShip(List<String> listPilots) { for (String pilot : listPilots) { ResponseEntity<People> responsePilot = restTemplate.exchange(pilot, HttpMethod.GET, entity, People.class); String namePilot = responsePilot.getBody().getName(); if (namePilot.equals("Obi-Wan Kenobi")) { return true; } } return false; } }
[ "windgleb@gmail.com" ]
windgleb@gmail.com
6d523649e924d77abb617809a62453a21a959bae
c09ca5e4102aa784822af3975ad8bf34b2def628
/devcoinj/core/src/main/java/com/google/devcoin/core/VersionedChecksummedBytes.java
122dd739927f560dbe1b55f24df1bb2bf5a2d93a
[ "Apache-2.0" ]
permissive
sidhujag/devcoin-android
edd2bb0d8dd22f72e2bf7f204b6889bf7d8d3b9b
611851c0fff86ea486a4d0d4c22463a889b23947
refs/heads/master
2016-09-06T20:11:56.613640
2014-01-30T19:24:08
2014-01-30T19:24:08
15,754,659
1
2
null
null
null
null
UTF-8
Java
false
false
2,815
java
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devcoin.core; import java.util.Arrays; import static com.google.common.base.Preconditions.checkArgument; /** * <p>In Bitcoin the following format is often used to represent some type of key:</p> * <p/> * <pre>[one version byte] [data bytes] [4 checksum bytes]</pre> * <p/> * <p>and the result is then Base58 encoded. This format is used for addresses, and private keys exported using the * dumpprivkey command.</p> */ public class VersionedChecksummedBytes { protected int version; protected byte[] bytes; protected VersionedChecksummedBytes(String encoded) throws AddressFormatException { byte[] tmp = Base58.decodeChecked(encoded); version = tmp[0] & 0xFF; bytes = new byte[tmp.length - 1]; System.arraycopy(tmp, 1, bytes, 0, tmp.length - 1); } protected VersionedChecksummedBytes(int version, byte[] bytes) { checkArgument(version < 256 && version >= 0); this.version = version; this.bytes = bytes; } @Override public String toString() { // A stringified buffer is: // 1 byte version + data bytes + 4 bytes check code (a truncated hash) byte[] addressBytes = new byte[1 + bytes.length + 4]; addressBytes[0] = (byte) version; System.arraycopy(bytes, 0, addressBytes, 1, bytes.length); byte[] check = Utils.doubleDigest(addressBytes, 0, bytes.length + 1); System.arraycopy(check, 0, addressBytes, bytes.length + 1, 4); return Base58.encode(addressBytes); } @Override public int hashCode() { return Arrays.hashCode(bytes); } @Override public boolean equals(Object o) { if (!(o instanceof VersionedChecksummedBytes)) return false; VersionedChecksummedBytes vcb = (VersionedChecksummedBytes) o; return Arrays.equals(vcb.bytes, bytes); } /** * Returns the "version" or "header" byte: the first byte of the data. This is used to disambiguate what the * contents apply to, for example, which network the key or address is valid on. * * @return A positive number between 0 and 255. */ public int getVersion() { return version; } }
[ "sidhujag@hotmail.com" ]
sidhujag@hotmail.com
45e5ca328a87610b9d16e411effa23cd8af604a1
0606cf494e12067367580095addd4ebf6281a53a
/app/src/main/java/com/ace/member/main/third_party/samrithisak_loan/loan/LoanComponent.java
a97ed5299c369c9af113b6a63e73493ebc83f132
[]
no_license
kothsada/ace_member_android
d870d4a32e4e1cb669ee95f33fd0df0f4c60629c
f256216f8e5c49d2b00db0a39eecab6ed68a3257
refs/heads/master
2022-04-18T16:20:07.548800
2020-04-18T16:07:05
2020-04-18T16:07:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
210
java
package com.ace.member.main.third_party.samrithisak_loan.loan; import dagger.Component; @Component(modules = LoanPresenterModule.class) public interface LoanComponent { void inject(LoanActivity activity); }
[ "771613512@qq.com" ]
771613512@qq.com
5310f86dfccedc8f1233e5ef6fcd2bb91e735829
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/9/9_20c23334dec817e2076b4098f23ab63a7e2ff436/AbstractIgnitedLocationManagerTest/9_20c23334dec817e2076b4098f23ab63a7e2ff436_AbstractIgnitedLocationManagerTest_t.java
27bdcd8fc655d9a8f3c9e846b098d513c80beff4
[]
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
12,903
java
package com.github.ignition.location.tests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.BatteryManager; import com.github.ignition.location.IgnitedLocationConstants; import com.github.ignition.samples.ui.IgnitedLocationSampleActivity; import com.xtremelabs.robolectric.Robolectric; import com.xtremelabs.robolectric.shadows.ShadowActivity; import com.xtremelabs.robolectric.shadows.ShadowApplication; import com.xtremelabs.robolectric.shadows.ShadowApplication.Wrapper; import com.xtremelabs.robolectric.shadows.ShadowLocationManager; public abstract class AbstractIgnitedLocationManagerTest { protected ShadowApplication shadowApp; protected ShadowLocationManager shadowLocationManager; private IgnitedLocationSampleActivity activity; private Location lastKnownLocation; @Before public void setUp() throws Exception { activity = new IgnitedLocationSampleActivity(); shadowApp = Robolectric.getShadowApplication(); shadowLocationManager = Robolectric.shadowOf((LocationManager) activity .getSystemService(Context.LOCATION_SERVICE)); shadowLocationManager.setProviderEnabled(LocationManager.GPS_PROVIDER, true); shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, true); shadowLocationManager.setProviderEnabled(LocationManager.NETWORK_PROVIDER, true); lastKnownLocation = getMockLocation(); shadowLocationManager.setLastKnownLocation(LocationManager.GPS_PROVIDER, lastKnownLocation); sendBatteryLevelChangedBroadcast(100); activity.onCreate(null); } @After public void tearDown() throws Exception { if (!activity.isFinishing()) { finish(); } } protected Location getMockLocation() { Location location = new Location(LocationManager.GPS_PROVIDER); location.setLatitude(1.0); location.setLongitude(1.0); location.setAccuracy(50); return location; } protected Location sendMockLocationBroadcast(String provider) { return sendMockLocationBroadcast(provider, 50f); } protected Location sendMockLocationBroadcast(String provider, float accuracy) { Intent intent = new Intent(IgnitedLocationConstants.ACTIVE_LOCATION_UPDATE_ACTION); Location location = new Location(provider); location.setLatitude(2.0); location.setLongitude(2.0); location.setAccuracy(accuracy); intent.putExtra(LocationManager.KEY_LOCATION_CHANGED, location); shadowApp.sendBroadcast(intent); return location; } protected void sendBatteryLevelChangedBroadcast(int level) { Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED); intent.putExtra(BatteryManager.EXTRA_LEVEL, level); intent.putExtra(BatteryManager.EXTRA_SCALE, 100); shadowApp.sendStickyBroadcast(intent); } @Test public void ignitedLocationIsCurrentLocation() { resume(); assertThat(lastKnownLocation, equalTo(activity.getCurrentLocation())); Location newLocation = sendMockLocationBroadcast(LocationManager.GPS_PROVIDER); assertThat(newLocation, equalTo(activity.getCurrentLocation())); } @Test public void shouldActivelyRequestLocationUpdatesOnResume() { resume(); List<Wrapper> receivers = shadowApp.getRegisteredReceivers(); assertThat(receivers, notNullValue()); boolean receiverRegistered = false; for (Wrapper receiver : receivers) { if (receiver.intentFilter.getAction(0).equals( IgnitedLocationConstants.ACTIVE_LOCATION_UPDATE_ACTION)) { receiverRegistered = true; break; } } assertThat(receiverRegistered, is(true)); } // TODO: find a better way to test this. Now the activity must be resumed twice or an Exception // will be thrown because one of the receivers is not registered. @Test public void shouldNotHaveRegisteredReceiverOnPause() throws Exception { resume(); activity.onPause(); ShadowActivity shadowActivity = Robolectric.shadowOf(activity); shadowActivity.assertNoBroadcastListenersRegistered(); resume(); } // @Test // public void noTaskRunningOnFinish() { // // shadowApp.getBackgroundScheduler().pause(); // ActivityManager activityManager = (ActivityManager) activity // .getSystemService(Context.ACTIVITY_SERVICE); // ShadowActivityManager shadowActivityManager = Robolectric.shadowOf(activityManager); // resume(); // assertThat(shadowActivityManager.getRunningTasks(0).size(), equalTo(1)); // } @Test public void shouldSaveSettingsToPreferences() { resume(); SharedPreferences pref = activity.getSharedPreferences( IgnitedLocationConstants.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE); boolean followLocationChanges = pref.getBoolean( IgnitedLocationConstants.SP_KEY_ENABLE_PASSIVE_LOCATION_UPDATES, false); boolean useGps = pref.getBoolean(IgnitedLocationConstants.SP_KEY_LOCATION_UPDATES_USE_GPS, !IgnitedLocationConstants.USE_GPS_DEFAULT); boolean runOnce = pref.getBoolean(IgnitedLocationConstants.SP_KEY_RUN_ONCE, false); int locUpdatesDistDiff = pref.getInt( IgnitedLocationConstants.SP_KEY_LOCATION_UPDATES_DISTANCE_DIFF, IgnitedLocationConstants.LOCATION_UPDATES_DISTANCE_DIFF_DEFAULT + 1); long locUpdatesInterval = pref.getLong( IgnitedLocationConstants.SP_KEY_LOCATION_UPDATES_INTERVAL, IgnitedLocationConstants.PASSIVE_LOCATION_UPDATES_INTERVAL_DEFAULT + 1); int passiveLocUpdatesDistDiff = pref.getInt( IgnitedLocationConstants.SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF, IgnitedLocationConstants.PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF_DEFAULT + 1); long passiveLocUpdatesInterval = pref.getLong( IgnitedLocationConstants.SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL, IgnitedLocationConstants.PASSIVE_LOCATION_UPDATES_INTERVAL_DEFAULT + 1); long waitForGpsFixInterval = pref.getLong( IgnitedLocationConstants.SP_KEY_WAIT_FOR_GPS_FIX_INTERVAL, IgnitedLocationConstants.WAIT_FOR_GPS_FIX_INTERVAL_DEFAULT + 1); int minBatteryLevelToUseGps = pref.getInt( IgnitedLocationConstants.SP_KEY_MIN_BATTERY_LEVEL, IgnitedLocationConstants.MIN_BATTERY_LEVEL_FOR_GPS_DEFAULT + 1); boolean showWaitForLocationDialog = pref.getBoolean( IgnitedLocationConstants.SP_KEY_SHOW_WAIT_FOR_LOCATION_DIALOG, !IgnitedLocationConstants.SHOW_WAIT_FOR_LOCATION_DIALOG_DEFAULT); assertThat(followLocationChanges, is(true)); assertThat(useGps, is(true)); assertThat(runOnce, is(true)); assertThat(showWaitForLocationDialog, is(true)); assertThat(minBatteryLevelToUseGps, equalTo(IgnitedLocationConstants.MIN_BATTERY_LEVEL_FOR_GPS_DEFAULT)); assertThat(waitForGpsFixInterval, equalTo(IgnitedLocationConstants.WAIT_FOR_GPS_FIX_INTERVAL_DEFAULT)); assertThat(IgnitedLocationConstants.LOCATION_UPDATES_DISTANCE_DIFF_DEFAULT, equalTo(locUpdatesDistDiff)); assertThat(IgnitedLocationConstants.LOCATION_UPDATES_INTERVAL_DEFAULT, equalTo(locUpdatesInterval)); assertThat(IgnitedLocationConstants.PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF_DEFAULT, equalTo(passiveLocUpdatesDistDiff)); assertThat(IgnitedLocationConstants.PASSIVE_LOCATION_UPDATES_INTERVAL_DEFAULT, equalTo(passiveLocUpdatesInterval)); } @Test public void shouldRegisterListenerIfBestProviderDisabled() throws Exception { shadowLocationManager.setProviderEnabled(LocationManager.GPS_PROVIDER, false); shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, false); shadowLocationManager.setBestProvider(LocationManager.NETWORK_PROVIDER, true); resume(); List<LocationListener> listeners = shadowLocationManager .getRequestLocationUpdateListeners(); Assert.assertFalse(listeners.isEmpty()); } @Test public void shouldNotRegisterListenerIfBestProviderEnabled() throws Exception { resume(); List<LocationListener> listeners = shadowLocationManager .getRequestLocationUpdateListeners(); assertThat("No listener must be registered, the best provider is enabled!", listeners.isEmpty()); } @Test public void shouldRegisterLocationProviderDisabledReceiver() { resume(); List<Wrapper> receivers = shadowApp.getRegisteredReceivers(); assertThat(receivers, notNullValue()); boolean receiverRegistered = false; for (Wrapper receiver : receivers) { if (receiver.intentFilter.getAction(0).equals( IgnitedLocationConstants.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION)) { receiverRegistered = true; break; } } assertThat(receiverRegistered, is(true)); } @Test public void shouldNotRequestUpdatesFromGpsIfBatteryLow() { sendBatteryLevelChangedBroadcast(10); resume(); Map<PendingIntent, Criteria> locationPendingIntents = shadowLocationManager .getRequestLocationUdpateCriteriaPendingIntents(); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); assertThat("Updates from " + LocationManager.GPS_PROVIDER + " provider shouldn't be requested when battery power is low!", !locationPendingIntents.containsValue(criteria)); } @Test public void shouldSwitchToNetworkProviderIfBatteryLow() { resume(); Map<PendingIntent, Criteria> locationPendingIntents = shadowLocationManager .getRequestLocationUdpateCriteriaPendingIntents(); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); sendBatteryLevelChangedBroadcast(10); Intent intent = new Intent(); intent.setAction(Intent.ACTION_BATTERY_LOW); shadowApp.sendBroadcast(intent); sendBatteryLevelChangedBroadcast(100); assertThat("Updates from " + LocationManager.GPS_PROVIDER + " provider shouldn't be requested when battery power is low!", !locationPendingIntents.containsValue(criteria)); } // @Test // public void shouldDisableLocationUpdatesIfOnIgnitedLocationChangedReturnsFalse() { // resume(); // // assertThat("Location updates shouldn't be disabled at this point", !IgnitedLocationManager // .aspectOf().isLocationUpdatesDisabled()); // // sendMockLocationBroadcast(LocationManager.GPS_PROVIDER, 10f); // // assertThat("Location updates should be disabled at this point", IgnitedLocationManager // .aspectOf().isLocationUpdatesDisabled()); // } // @Test // public void requestLocationUpdatesFromAnotherProviderIfCurrentOneIsDisabled() { // // TODO // } @Test public void shouldUpdateDataOnNewLocation() { resume(); int countBefore = activity.getLocationCount(); sendMockLocationBroadcast(LocationManager.GPS_PROVIDER); int countAfter = activity.getLocationCount(); assertThat(countAfter, equalTo(++countBefore)); } // Helper methods protected void finish() { activity.finish(); activity.onPause(); activity.onStop(); activity.onDestroy(); } protected void resume() { activity.onStart(); activity.onResume(); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
73c8eba383721045d761c39500c9295f24120d2b
2411a409ada91e6b505e3bc7a719393879d93820
/DemoThread/src/main/java/by/serzhant/demothread/ex05c_demon/DemonThread.java
46731ea52a937158eae7749133a45e9e0052fa21
[]
no_license
mrSerzhant/epam-course-java
0eec64ac961c61e8ac75a710c584aa5eae0059a1
bad7dee58554b84ae1cf56ae7aa059594860a7fc
refs/heads/main
2023-08-26T11:38:55.153053
2021-10-22T12:49:35
2021-10-22T12:49:35
388,601,186
0
0
null
null
null
null
UTF-8
Java
false
false
398
java
package by.serzhant.demothread.ex05c_demon; import java.util.concurrent.TimeUnit; public class DemonThread implements Runnable { @Override public void run() { int count = 0; while (true) { System.out.println(count++); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { } } } }
[ "57715647+mrSerzhant@users.noreply.github.com" ]
57715647+mrSerzhant@users.noreply.github.com
533c16ae89a529b3dc9e5212ee5da2817e5d8907
954fcabee4daa295a71f814ea52401cbf75345b9
/src/fr/irit/sesame/tree/NodeConstructor.java
1c925e6d953979e1fbda22e0d3a43de96cbd5c34
[]
no_license
Jogo27/Sesame
2cc2680a5f1fd1387dfb73638323a92ca94aa4ba
8b1c16970de2eaadad9dc304bb3bd5b71c534730
refs/heads/master
2020-03-14T02:52:01.381027
2018-06-24T18:25:54
2018-06-24T18:25:54
131,408,102
0
0
null
null
null
null
UTF-8
Java
false
false
429
java
package fr.irit.sesame.tree; /** * Each Node should have a static field of type NodeConstructor. * This is needed because GWT does not implements the full reflection API. */ public interface NodeConstructor { String getDescription(); /** * Create a node. * Parameter <code>replaceAction</code> could be ignored by non-chooser nodes. */ Node makeNode(InnerNode parent, ReplaceSubtreeAction replaceAction); }
[ "joseph.boudou@matabio.net" ]
joseph.boudou@matabio.net
648948edbd336ecbb8a2ef5629678fd7184f259d
a4178e5042f43f94344789794d1926c8bdba51c0
/iwxxm3Converter/src/schemabindings/schemabindings31/aero/aixm/schema/_5_1/CodeTimeEventCombinationType.java
6e183cfa7919acf1589123929ddd46af50585c30
[ "Apache-2.0" ]
permissive
moryakovdv/iwxxmConverter
c6fb73bc49765c4aeb7ee0153cca04e3e3846ab0
5c2b57e57c3038a9968b026c55e381eef0f34dad
refs/heads/master
2023-07-20T06:58:00.317736
2023-07-05T10:10:10
2023-07-05T10:10:10
128,777,786
11
7
Apache-2.0
2023-07-05T10:03:12
2018-04-09T13:38:59
Java
UTF-8
Java
false
false
2,639
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.05.06 at 11:11:25 PM MSK // package schemabindings31.aero.aixm.schema._5_1; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for CodeTimeEventCombinationType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CodeTimeEventCombinationType"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.aixm.aero/schema/5.1.1>CodeTimeEventCombinationBaseType"> * &lt;attribute name="nilReason" type="{http://www.opengis.net/gml/3.2}NilReasonEnumeration" /> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CodeTimeEventCombinationType", propOrder = { "value" }) public class CodeTimeEventCombinationType { @XmlValue protected String value; @XmlAttribute(name = "nilReason") protected String nilReason; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } public boolean isSetValue() { return (this.value!= null); } /** * Gets the value of the nilReason property. * * @return * possible object is * {@link String } * */ public String getNilReason() { return nilReason; } /** * Sets the value of the nilReason property. * * @param value * allowed object is * {@link String } * */ public void setNilReason(String value) { this.nilReason = value; } public boolean isSetNilReason() { return (this.nilReason!= null); } }
[ "moryakovdv@gmail.com" ]
moryakovdv@gmail.com
9e74697485a41f50ce0643d3c582f296109cc646
dc5af548e624941d7a5ddd73d8eec4f93c445875
/lampcopy/src/main/java/com/example/demo/entity/Payment.java
6759d98e066dcb2b0fb619e35f1ec8296ce94fbf
[]
no_license
xiaokushen/jiangshuhua-biji
7a0f50018a89f7744e894485629280fe99f9127d
b9e8803bc054e35ab88c482b4f3d46e27273a38d
refs/heads/master
2023-03-08T13:56:15.212141
2021-02-28T02:01:20
2021-02-28T02:53:35
341,564,600
0
0
null
null
null
null
UTF-8
Java
false
false
1,492
java
package com.example.demo.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; //@Entity:类名对应表名,class字段名对应表的字段名 @Entity @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "jcxxt_payment_goods") public class Payment implements Serializable { @Id @Column(name = "PAYMENT_ID")//数据库实际列名STUDENT_ID如果报红色就点击右下角选中间 private String paymentId; @Column(name = "SHIPGOODS_ID")//数据库实际列名 private String shipGoodsId; @Column(name = "ACCOUNT_ID")//数据库实际列名 private Integer accountId; @Column(name = "DETAILEDLIST_ID")//数据库实际列名 private String detailedListId; @Column(name = "PAYMENT_TOTSL")//数据库实际列名 private String paymentTotsl; @Column(name = "PAYMENT_CREATDATE")//数据库实际列名 private String paymentCreatDate; @Column(name = "PAYMENT_CRTATOR")//数据库实际列名 private String paymentCrtator; @Column(name = "PAYMENT_MODIFYDATE")//数据库实际列名 private String paymentModifyDate; @Column(name = "PAYMENT_REVISER")//数据库实际列名 private String paymentReviser; @Column(name = "PAYMENT_DELET")//数据库实际列名 private String paymentDelet; }
[ "1602798159@qq.com" ]
1602798159@qq.com
e4000164102219a4bb60da1053e96b6b88857c71
5d31f4d202b77ba68cc836f06780699694764499
/app/src/main/java/com/example/calendar/MeiZuMonthView.java
65f02ceb5d038dadce5b2ec344eb70e8c8ff0781
[]
no_license
LivingwWell/Calendar
8a45a4e1a79901d13f5a38c3b7a13e877225c4c6
e32f4c6b6de2bc47eb0acf70aef36fddaffb1618
refs/heads/master
2020-08-10T19:36:06.570699
2019-10-19T10:40:05
2019-10-19T10:40:05
214,406,673
0
0
null
null
null
null
UTF-8
Java
false
false
5,246
java
package com.example.calendar; import android.content.Context; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; import com.haibin.calendarview.Calendar; import com.haibin.calendarview.MonthView; public class MeiZuMonthView extends MonthView { /** * 自定义魅族标记的文本画笔 */ private Paint mTextPaint = new Paint(); /** * 自定义魅族标记的圆形背景 */ private Paint mSchemeBasicPaint = new Paint(); private float mRadio; private int mPadding; private float mSchemeBaseLine; public MeiZuMonthView(Context context) { super(context); mTextPaint.setTextSize(dipToPx(context, 8)); mTextPaint.setColor(0xffffffff); mTextPaint.setAntiAlias(true); mTextPaint.setFakeBoldText(true); mSchemeBasicPaint.setAntiAlias(true); mSchemeBasicPaint.setStyle(Paint.Style.FILL); mSchemeBasicPaint.setTextAlign(Paint.Align.CENTER); mSchemeBasicPaint.setFakeBoldText(true); mRadio = dipToPx(getContext(), 7); mPadding = dipToPx(getContext(), 4); Paint.FontMetrics metrics = mSchemeBasicPaint.getFontMetrics(); mSchemeBaseLine = mRadio - metrics.descent + (metrics.bottom - metrics.top) / 2 + dipToPx(getContext(), 1); //兼容硬件加速无效的代码 setLayerType(View.LAYER_TYPE_SOFTWARE, mSchemeBasicPaint); //4.0以上硬件加速会导致无效 mSchemeBasicPaint.setMaskFilter(new BlurMaskFilter(25, BlurMaskFilter.Blur.SOLID)); } /** * 绘制选中的日子 * * @param canvas canvas * @param calendar 日历日历calendar * @param x 日历Card x起点坐标 * @param y 日历Card y起点坐标 * @param hasScheme hasScheme 非标记的日期 * @return true 则绘制onDrawScheme,因为这里背景色不是是互斥的 */ @Override protected boolean onDrawSelected(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme) { mSelectedPaint.setStyle(Paint.Style.FILL); canvas.drawRect(x + mPadding, y + mPadding, x + mItemWidth - mPadding, y + mItemHeight - mPadding, mSelectedPaint); return true; } /** * 绘制标记的事件日子 * * @param canvas canvas * @param calendar 日历calendar * @param x 日历Card x起点坐标 * @param y 日历Card y起点坐标 */ @Override protected void onDrawScheme(Canvas canvas, Calendar calendar, int x, int y) { mSchemeBasicPaint.setColor(calendar.getSchemeColor()); canvas.drawCircle(x + mItemWidth - mPadding - mRadio / 2, y + mPadding + mRadio, mRadio, mSchemeBasicPaint); canvas.drawText(calendar.getScheme(), x + mItemWidth - mPadding - mRadio / 2 - getTextWidth(calendar.getScheme()) / 2, y + mPadding + mSchemeBaseLine, mTextPaint); } private float getTextWidth(String text) { return mTextPaint.measureText(text); } /** * 绘制文本 * * @param canvas canvas * @param calendar 日历calendar * @param x 日历Card x起点坐标 * @param y 日历Card y起点坐标 * @param hasScheme 是否是标记的日期 * @param isSelected 是否选中 */ @SuppressWarnings("IntegerDivisionInFloatingPointContext") @Override protected void onDrawText(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme, boolean isSelected) { int cx = x + mItemWidth / 2; int top = y - mItemHeight / 6; boolean isInRange = isInRange(calendar); if (isSelected) { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, mSelectTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10, mSelectedLunarTextPaint); } else if (hasScheme) { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, calendar.isCurrentMonth() && isInRange ? mSchemeTextPaint : mOtherMonthTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10, mCurMonthLunarTextPaint); } else { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, calendar.isCurrentDay() ? mCurDayTextPaint : calendar.isCurrentMonth() && isInRange ? mCurMonthTextPaint : mOtherMonthTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10, calendar.isCurrentDay() && isInRange ? mCurDayLunarTextPaint : calendar.isCurrentMonth() ? mCurMonthLunarTextPaint : mOtherMonthLunarTextPaint); } } /** * dp转px * * @param context context * @param dpValue dp * @return px */ private static int dipToPx(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
[ "765995471@qq.com" ]
765995471@qq.com
6df08fad32fc44be361be4c657556f5d40b4865c
37cfbc1ee939d381ba6ad119bef919dfbfe2e501
/nuxeo-sample/src/main/java/org/nuxeo/sample/SampleSyncListener.java
2248d708d76220fab781f4b88868d551045e9d3b
[ "Apache-2.0" ]
permissive
ktsang/nuxeo-sample-project
713f0fd4978633667b6315920c543dd980a69c7f
9686b55e1ad996febc1d0ee142f7139243d4ab71
refs/heads/master
2023-09-06T05:16:05.411288
2020-06-04T14:56:02
2020-06-04T14:56:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
693
java
package org.nuxeo.sample; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventContext; import org.nuxeo.ecm.core.event.EventListener; import org.nuxeo.ecm.core.event.impl.DocumentEventContext; public class SampleSyncListener implements EventListener { @Override public void handleEvent(Event event) { EventContext ctx = event.getContext(); if (!(ctx instanceof DocumentEventContext)) { return; } DocumentEventContext docCtx = (DocumentEventContext) ctx; DocumentModel doc = docCtx.getSourceDocument(); // Add some logic starting from here. } }
[ "arnaud.k@gmail.com" ]
arnaud.k@gmail.com