blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b81794999c0fbff9c36889008a395165272c733 | dbdefcd1724112a0bae34241ce0d51c6b1f5d7e5 | /app/src/main/java/com/dozydroid/myfbchat/ui/activities/SplashActivity.java | 071e5d880f223256ae0863c6c80d731d29204ebe | [] | no_license | WaqasAzamKml/MyFBChat | f0f510238cd4efc081a160ad04f9807de43288b4 | 2ee474fdb30da9d919b7e5e96525787f1f064c80 | refs/heads/master | 2021-01-15T22:46:20.741334 | 2017-08-10T10:44:19 | 2017-08-10T10:44:19 | 99,912,527 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,543 | java | package com.dozydroid.myfbchat.ui.activities;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import com.dozydroid.myfbchat.R;
import com.google.firebase.auth.FirebaseAuth;
public class SplashActivity extends AppCompatActivity {
private static final int SPLASH_TIME_MS = 2000;
private Handler mHandler;
private Runnable mRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
// check if user is already logged in or not
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
// if logged in redirect the user to user listing activity
UserListingActivity.startActivity(SplashActivity.this);
} else {
// otherwise redirect the user to login activity
LoginActivity.startIntent(SplashActivity.this);
}
finish();
}
};
mHandler.postDelayed(mRunnable, SPLASH_TIME_MS);
}
/*@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(mRunnable);
}
@Override
protected void onResume() {
super.onResume();
mHandler.postDelayed(mRunnable, SPLASH_TIME_MS);
}*/
}
| [
"waqasazamkml@gmail.com"
] | waqasazamkml@gmail.com |
66026def215973d2c28849c81b55fe8b4090a4af | 86505462601eae6007bef6c9f0f4eeb9fcdd1e7b | /bin/modules/customer-coupon/customercouponoccaddon/acceleratoraddon/web/src/de/hybris/platform/customercouponoccaddon/validators/CustomerCouponAssignResultValidator.java | dd42c4207dde9185064d8d67ac8ad621fe4d9748 | [] | no_license | jp-developer0/hybrisTrail | 82165c5b91352332a3d471b3414faee47bdb6cee | a0208ffee7fee5b7f83dd982e372276492ae83d4 | refs/heads/master | 2020-12-03T19:53:58.652431 | 2020-01-02T18:02:34 | 2020-01-02T18:02:34 | 231,430,332 | 0 | 4 | null | 2020-08-05T22:46:23 | 2020-01-02T17:39:15 | null | UTF-8 | Java | false | false | 939 | java | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package de.hybris.platform.customercouponoccaddon.validators;
import de.hybris.platform.customercouponfacades.emums.AssignCouponResult;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class CustomerCouponAssignResultValidator implements Validator
{
@Override
public boolean supports(final Class<?> clazz)
{
return clazz == AssignCouponResult.class;
}
@Override
public void validate(final Object object, final Errors errors)
{
final AssignCouponResult result = (AssignCouponResult) object;
if (result == AssignCouponResult.ASSIGNED)
{
errors.rejectValue("", "customer.coupon.claimed");
}
else if (result == AssignCouponResult.INEXISTENCE)
{
errors.rejectValue("", "customer.coupon.inexistence");
}
}
}
| [
"juan.gonzalez.working@gmail.com"
] | juan.gonzalez.working@gmail.com |
9e88d7987acf54903f76f6cb0235345eba0a36ca | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /single-large-project/src/test/java/org/gradle/test/performancenull_215/Testnull_21409.java | d9a4453b54fb86c70d050d696b7b0c87cfe7d003 | [] | 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 | 308 | java | package org.gradle.test.performancenull_215;
import static org.junit.Assert.*;
public class Testnull_21409 {
private final Productionnull_21409 production = new Productionnull_21409("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
baea2171f4a919a3b890fb3dbbd8e6b25733891b | 217196157db2e978b21e7ceae0924f1ef3ae620d | /src/main/java/local/model/Guerreiro.java | a4c587a8c3ec29121c05f46fd6eec05ac7a16c1f | [] | no_license | VINICIUSCAETANO/RPGWalkingCrap | e369ff96b0bf13d93a9b6018d4eb0102372b9a40 | 06df94b0e6bfc9a301ac72c8d5ff951d42a063c2 | refs/heads/master | 2020-04-01T12:09:59.639386 | 2018-10-15T23:19:29 | 2018-10-15T23:19:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,602 | java | package local.model;
import local.util.Util;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import local.exception.VidaException;
public class Guerreiro extends Personagem{
public Guerreiro(String nome) {
//this.nome = nome + " Warrior";
setNome(String.format("%s Warrior", nome));
this.forca = Util.random(1,1000);
this.habilidadeMental = 0;
this.poderDeAtaque = this.forca*10;
this.esquiva = Util.random(0,50);
this.resistencia = Util.random(0,90);
this.vidaMaxima = Util.random(1,40000);
try {
setVidaAtual(Util.random(1,40000));
} catch (VidaException ex) {
}
}
@Override
public void atacar(Personagem oponente){
ataque(oponente);
if(oponente.vidaAtual>0){
oponente.contraAtacar(this);
}
}
public void contraAtacar(Personagem oponente){
ataque(oponente);
}
public void aprimorarHabilidadePrincipal(){
this.poderDeAtaque = (int)(this.poderDeAtaque * 1.1);
}
public void regenerarVida(){
this.vidaAtual = this.vidaAtual + (int)(this.vidaMaxima*0.05);
if(this.vidaAtual>this.vidaMaxima){
this.vidaAtual = this.vidaMaxima;
}
}
private void ataque(Personagem oponente){
boolean hit = Util.random(0,100) < oponente.esquiva;
if(hit){
oponente.vidaAtual = oponente.vidaAtual -
(poderDeAtaque - (oponente.resistencia/100)*oponente.vidaAtual);
}
}
}
| [
"viniciusbeschcaetano@gmail.com"
] | viniciusbeschcaetano@gmail.com |
50827f8ba223e699ea1e17f7e8c46e9c71974fc0 | 1c4ccc889eaf05a4e40100b93a2bcd84462b4249 | /mall/src/main/java/com/qingshop/mall/framework/config/FreemarkerConfig.java | d72169ec83546723754f30b8c73f7ddecd53ab80 | [
"Apache-2.0"
] | permissive | deagle-z/bopufeng-mall | 4f025883895acc4ee047f239bde24c9a0a7a7547 | 6d22b44e5272be01d488ec4e43c4c53c42e1abc0 | refs/heads/master | 2023-08-04T19:31:23.051669 | 2021-09-23T12:43:46 | 2021-09-23T12:43:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 601 | java | package com.qingshop.mall.framework.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.qingshop.mall.framework.shiro.ShiroTag;
import freemarker.template.Configuration;
/**
* freemarker与shiro标签
*/
@Component
public class FreemarkerConfig implements InitializingBean {
@Autowired
private Configuration configuration;
@Override
public void afterPropertiesSet() throws Exception {
configuration.setSharedVariable("shiro", new ShiroTag());
}
}
| [
"PercyJon.H@gmail.com"
] | PercyJon.H@gmail.com |
96e1f50c1193e938fbb6b4afc0b0ecae77d9896d | cc36062355847011da935897d6bb6c93f90fd71e | /Quick/src/run.java | ff18ce2532625a83c323c0ef50a024026c2b8f2b | [] | no_license | ehdwn1991/Datastructure | eac1b0a8457dd49cea667103cc72442818da591d | 204a45e4e351f4ff4964187bac71bd1f18ebe5e9 | refs/heads/master | 2016-08-11T08:39:48.994435 | 2016-02-25T06:26:23 | 2016-02-25T06:26:23 | 52,501,506 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 223 | java |
public class run {
public static void main(String[] args) {
// TODO Auto-generated method stub
int data[] = {45, 39, 98, 15, 52, 44, 33, 28, 40, 38, 77, 68, 11, 43};
quick sl = new quick();
sl.sequn(data);
}
}
| [
"ehdwn1991@gmail.com"
] | ehdwn1991@gmail.com |
25109ed45e7baf1118f1cd93554478becded6e99 | be41919ce8f96a8b1bcb99028d11c1a2a4744f97 | /src/CardHand.java | 55b10b191fd550d02d5f80261262b3732128ab95 | [] | no_license | ilieciprian18/BlackJack-with-GUI | b4dd5cdc3a30c41f717b1e73754a4c677329c14a | 4db602ab559fcf6dfa1378c349bc0e1aa4f38178 | refs/heads/main | 2023-06-02T01:21:19.281100 | 2021-06-23T15:19:20 | 2021-06-23T15:19:20 | 379,401,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,686 | java | import java.util.Vector;
public class CardHand {
protected Vector<Card> CardHand;
public CardHand(){
this.CardHand = new Vector<>();
}
public void addCard(Card x){//adaugan carte
this.CardHand.add(x);
}
public void AfisElementAtPosition(int intex){
System.out.println();
}
public Card ElementAtId(int index){
return this.CardHand.elementAt(index);
}
public Card lastElement(){
return this.CardHand.lastElement();
}
public int lastElementId(){
return this.CardHand.size()-1;
}
public int sumHard(){
int sum = 0;
int nrA = 0;
//tinem minte nr de A
//deoarece A este 1 sau 11
for(int i=0;i<CardHand.size();i++){
if( CardHand.elementAt(i).number.equals("Q") || CardHand.elementAt(i).number.equals("K") || CardHand.elementAt(i).number.equals("J"))
sum = sum + 10;
else if (CardHand.elementAt(i).number.equals("A")) {
nrA++;
sum = sum + 11;
}
else {
sum = sum + Integer.parseInt(CardHand.elementAt(i).number);
}
}
if(sum > 21)
while(nrA > 0 && sum > 21)
{
sum = sum -10;
nrA--;
}
return sum;
}
public void AfisHand(){
for(int i=0;i<CardHand.size();i++)
System.out.print(CardHand.elementAt(i) + " ");
System.out.println();
}
@Override
public String toString() {
return CardHand + " ";
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a932671aeb745f454f8c248812e54e31fe1dd08e | d539b61f1bc906ae07a8ae36fee80658ee01f2be | /MyFirstApp/app/src/main/java/aerogelcube/myapplication/MyActivity.java | 46eb2e4d0348a1edd8289efe36a0610818837f89 | [] | no_license | aerogelcube/HW10 | df6d7cb56f1dc2506b948041fbd591e836e40d48 | 8bf6b87348dff9fe8a8ffc704bfd52ea663bd1ed | refs/heads/master | 2021-01-01T19:46:12.915588 | 2015-05-07T02:59:54 | 2015-05-07T02:59:54 | 35,195,589 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,673 | java | package aerogelcube.myapplication;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@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_my, 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);
}
}
| [
"aerogelcube@gmail.com"
] | aerogelcube@gmail.com |
b4e1b91037060e22a1bc03b8719d65d5239284dd | df5c9563b3446418db86f1d53392331374aadcdd | /core/src/main/java/com/ibasco/agql/core/exceptions/WriteInProgressException.java | 39b091b9b4a66f7be1bff60fb9a87c8e5ac1d2a8 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | ribasco/async-gamequery-lib | c69bd5509feb5c2a5e36f965d7f5faf43a377a0f | 49584d2eccd2496b3ef815c65bbf6c9e05f51c8c | refs/heads/master | 2023-09-01T11:59:16.391157 | 2023-06-30T00:15:34 | 2023-06-30T00:15:34 | 74,885,543 | 135 | 38 | Apache-2.0 | 2023-09-14T19:36:26 | 2016-11-27T12:15:21 | Java | UTF-8 | Java | false | false | 1,380 | java | /*
* Copyright (c) 2022 Asynchronous Game Query Library
*
* 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.ibasco.agql.core.exceptions;
/**
* <p>WriteInProgressException class.</p>
*
* @author Rafael Luis Ibasco
*/
public class WriteInProgressException extends TransportException {
/**
* <p>Constructor for WriteInProgressException.</p>
*
* @param message
* a {@link java.lang.String} object
*/
public WriteInProgressException(String message) {
super(message);
}
/**
* <p>Constructor for WriteInProgressException.</p>
*
* @param message
* a {@link java.lang.String} object
* @param cause
* a {@link java.lang.Throwable} object
*/
public WriteInProgressException(String message, Throwable cause) {
super(message, cause);
}
}
| [
"ribasco@gmail.com"
] | ribasco@gmail.com |
233624228e5e9a1f0c8e0edfb199e6517271edbc | 57991fdca370a4fd16e338541f721170397ebff8 | /螺旋数组II.java | 766629b07d3ebe175c2bfb04b6e1aae3f933779c | [] | no_license | forkcodeaiyc/java | c1d86ed412d7f865fa8cbe319e27db2b9f7025c2 | 4e533b566c136b7c6ff6eee5e8d147142fbd6b98 | refs/heads/master | 2023-03-20T21:38:54.647183 | 2021-03-07T13:28:03 | 2021-03-07T13:28:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 995 | java | package 力扣;
public class 螺旋数组II {
public static void main(String[] args) {
int[][] arr = generateMatrix(5);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
public static int[][] generateMatrix(int n) {
int[][] arr = new int[n][n];
int min = 0,max = n;
int a = 0,b = 0;
int temp = 1;
while (temp <= n*n){
for (; b < max-1; b++)
arr[a][b] = temp++;
if (temp >= n*n)
break;
for (; a < max-1; a++)
arr[a][b] = temp++;
for (; b > min; b--)
arr[a][b] = temp++;
for (; a > min; a--)
arr[a][b] = temp++;
a++;b++;
min++;max--;
}
if (n%2 != 0){
arr[a][b]=n*n;
}
return arr;
}
}
| [
"passerby18@163.com"
] | passerby18@163.com |
5a88503b52f48cfc26694063357102e75ba1f0c2 | 75710e85c319bb0224b6d44883a568808482f79c | /plugins/org.locationtech.geoff.ui/src/org/locationtech/geoff/ui/Observable.java | 7348c7c62812a7d9d3032e7ef63725478363c558 | [] | no_license | locationtech/geoff | 1da79bf6a21aa79db477141d3de7fe722361ae1b | 8cd664821787ce00624264a3158703a95a276e1f | refs/heads/master | 2023-06-04T00:29:42.669836 | 2018-04-24T17:41:58 | 2018-04-24T17:41:58 | 27,555,397 | 7 | 3 | null | 2016-03-15T19:38:12 | 2014-12-04T19:05:56 | JavaScript | UTF-8 | Java | false | false | 354 | java | package org.locationtech.geoff.ui;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@javax.inject.Qualifier
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Observable {
Class<?> value();
}
| [
"erdal.karaca.de@googlemail.com"
] | erdal.karaca.de@googlemail.com |
ffdf4ebb90cbdb44da89686efc8cb17f256ef34b | 3e540bd368671db806dd60b929f07cdce6a9a64f | /app/src/main/java/jp/tomiyama/noir/drag_and_drop/StartActivity.java | 51ca087180545074c77d93df568335c61d4f0f29 | [] | no_license | tommy1038/Drag_and_Drop | f73d1753d8a1c2e2f049dec6c44904f19e76319a | 2e61d8f132b16d34ec09da87956d556fc4ec72e6 | refs/heads/master | 2022-02-25T15:18:49.697393 | 2019-09-13T09:11:49 | 2019-09-13T09:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,281 | java | package jp.tomiyama.noir.drag_and_drop;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartActivity extends AppCompatActivity {
// TODO
// なんかデータあったら初期化するかどうかユーザーに聞く
private SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
pref = getSharedPreferences("numeric_app",MODE_PRIVATE);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), FirstPlayerActivity.class);
startActivity(intent);
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO アラートダイアログで確認
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.apply();
}
});
}
}
| [
"lit.karu.noir@gmail.com"
] | lit.karu.noir@gmail.com |
2941e65ea17f499a382545ef580d460018358149 | 1573bd216981a304ca593ce67b0e8b3450888895 | /src/main/java/com/arc/auth/config/security/SecurityConfig.java | cd5b98b2e7747d36df53255f3323d25ba3e03174 | [] | no_license | lamymay/auth | 912603c3edebad6daf0bcb9a63480a8777697c59 | e1e34751aa46024dc065b01b011182becdd3254d | refs/heads/master | 2020-12-03T05:52:36.501346 | 2020-01-05T14:10:52 | 2020-01-05T14:10:52 | 231,220,355 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,037 | java | package com.arc.auth.config.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* @author 叶超
* @since: 2019/13/31
*/
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// .formLogin()
// .loginPage("/test_login")
// .loginProcessingUrl("/test_login")
// .and()
.authorizeRequests()
.antMatchers(
"/favicon.ico",
"/verify/**",
"/test/**"
//登陆表单提交的地址
//"/v1/login/form/process"
).permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.disable()
;
}
/**
* 密码加密解密
*
* @return
*/
@Bean(name = "passwordEncoder")
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// @Bean(name = "userDetailsService")
// public UserDetailsService securitySysUserService() {
// return new SecuritySysUserServiceImpl();
// }
// @Autowired private MyAccessDeniedHandle exceptionHandler;
// @Autowired
// private ArcSecurityProperties arcSecurityProperties;
// @Resource
// private RedisTemplate<Object, Object> redisTemplate;
}
| [
"lamymay@outlook.com"
] | lamymay@outlook.com |
cc479d99667647d0da39aadfee481799f463dfac | 92d0e4dfe06d7d1825e44c77bbd866e7255ee547 | /DrinkWeb/src/main/java/com/example/drinkweb/repository/UserRepository.java | c0b156572b5029d48c3f31aa8e5ad00338032e38 | [] | no_license | 31181025846/Drink-web-update-to-Perfume-web | b674f38d5e784411d5c1bb2eda188001d89e1d24 | 0d5141ca0c56b07b620b98f1948ec25c4beb5d6b | refs/heads/main | 2023-08-13T18:16:49.041869 | 2021-10-08T14:11:50 | 2021-10-08T14:11:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 473 | java | package com.example.drinkweb.repository;
import com.example.drinkweb.Entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAllByOrderByIdAsc();
User findByActivationCode(String code);
User findByEmail(String email);
User findByPasswordResetCode(String code);
}
| [
"73517481+31181025846@users.noreply.github.com"
] | 73517481+31181025846@users.noreply.github.com |
cc3781620b6c05a3c6dee3a80825d25fe59c556f | a00326c0e2fc8944112589cd2ad638b278f058b9 | /src/main/java/000/139/672/CWE470_Unsafe_Reflection__database_51b.java | e9fa9fff9a0e30078ace41f9b0e489d4c3fdeadd | [] | no_license | Lanhbao/Static-Testing-for-Juliet-Test-Suite | 6fd3f62713be7a084260eafa9ab221b1b9833be6 | b095b11c7cb6d4a5bb2b76181e35d6ee00e96e68 | refs/heads/master | 2020-08-24T13:34:04.004149 | 2019-10-25T09:26:00 | 2019-10-25T09:26:00 | 216,822,684 | 0 | 1 | null | 2019-11-08T09:51:54 | 2019-10-22T13:37:13 | Java | UTF-8 | Java | false | false | 1,451 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE470_Unsafe_Reflection__database_51b.java
Label Definition File: CWE470_Unsafe_Reflection.label.xml
Template File: sources-sink-51b.tmpl.java
*/
/*
* @description
* CWE: 470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
* BadSource: database Read data from a database
* GoodSource: Set data to a hardcoded class name
* BadSink: Instantiate class named in data
* Flow Variant: 51 Data flow: data passed as an argument from one function to another in different classes in the same package
*
* */
public class CWE470_Unsafe_Reflection__database_51b
{
public void badSink(String data ) throws Throwable
{
/* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */
Class<?> tempClass = Class.forName(data);
Object tempClassObject = tempClass.newInstance();
IO.writeLine(tempClassObject.toString()); /* Use tempClassObject in some way */
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(String data ) throws Throwable
{
/* POTENTIAL FLAW: Instantiate object of class named in data (which may be from external input) */
Class<?> tempClass = Class.forName(data);
Object tempClassObject = tempClass.newInstance();
IO.writeLine(tempClassObject.toString()); /* Use tempClassObject in some way */
}
}
| [
"anhtluet12@gmail.com"
] | anhtluet12@gmail.com |
bba1f177b10726ae500626c9f08b419749ba4187 | cc328476eba0f9dcbac108688cf1b97d1d06c189 | /src/main/java/com/cisco/policyconversiontool/dto/wsa/asyncos806/ProxEtcMusAsaSettingsAsaConfig.java | 73d94b7cdedf10c3a28152c03df9f9dc0f3f24e0 | [] | no_license | SecurView/cws-wsa | b9278caee8d52afd9f71b925516bc18380b5c331 | c3e9c245722f89d9a3189bf7bc9700e8b4c7f1d6 | refs/heads/master | 2016-09-06T21:35:20.674191 | 2014-12-19T14:45:23 | 2014-12-19T14:45:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,060 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// 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: 2014.11.26 at 05:46:49 PM IST
//
package com.cisco.policyconversiontool.dto.wsa.asyncos806;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"proxEtcMusAsaSettingsAsaList"
})
@XmlRootElement(name = "prox_etc_mus_asa_settings_asa_config")
public class ProxEtcMusAsaSettingsAsaConfig {
@XmlElement(name = "prox_etc_mus_asa_settings_asa_list")
protected List<ProxEtcMusAsaSettingsAsaList> proxEtcMusAsaSettingsAsaList;
/**
* Gets the value of the proxEtcMusAsaSettingsAsaList property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the proxEtcMusAsaSettingsAsaList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProxEtcMusAsaSettingsAsaList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProxEtcMusAsaSettingsAsaList }
*
*
*/
public List<ProxEtcMusAsaSettingsAsaList> getProxEtcMusAsaSettingsAsaList() {
if (proxEtcMusAsaSettingsAsaList == null) {
proxEtcMusAsaSettingsAsaList = new ArrayList<ProxEtcMusAsaSettingsAsaList>();
}
return this.proxEtcMusAsaSettingsAsaList;
}
}
| [
"kgadekar@securview.com"
] | kgadekar@securview.com |
be9edbff2a67cb206e9369fc134cb35ef52829d7 | aef3369650cb7b658927bba7ccb0a3d590e0de48 | /src/Arithmatic_Operators.java | 0da98ce71f2ccf018647fe7e93b670da094286c9 | [] | no_license | kishansinghverma/Learn_Java_Basics | 67573467e3cff99ccad6919714f2fbdb2d8f97b4 | 294ec597cfc476d20b375b90e072d421fc9ccefd | refs/heads/master | 2020-06-03T19:38:51.319209 | 2019-07-21T20:17:41 | 2019-07-21T20:17:41 | 191,705,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,206 | java | public class Arithmatic_Operators {
public static void main(String[] args) throws ArithmeticException {
System.out.println('a'+.78);
System.out.println(10/0.0);
System.out.println(10.0/0.0);
System.out.println(10.0/0);
System.out.println(0.0/0.0);
System.out.println(0/0.0);
System.out.println(0.0/0);
try {
System.out.println(0 / 0);
}catch (ArithmeticException e){System.out.println("Arithmetic Exception");}
try {
System.out.println(10 / 0);
}catch (ArithmeticException e){System.out.println("Arithmetic Exception");}
//No Way to represent infinity in integer arithmetic,
//but in floating point arithmetic there is a way to represent infinity in both the classes we have predefined constant
//to represent infinity ie. +ive infinity and -ive infinity
}
}
class test5{
byte b;
public static void main(String[] args) {
test5 obj=new test5();
//obj.b=20*10 out of range
obj.b=20*2; // allowed for this range
byte c=2;
obj.b= (byte)(c*10); // type casting required
System.out.println(obj.b);
}
}
| [
"kishansinghverma@gmail.com"
] | kishansinghverma@gmail.com |
a1cadef85576189cd5080507dad3b694d7ba0592 | 383f195d0bb3e90fce694560fcd587151093ef84 | /src/week7/WaitSignalMonitorDemo.java | 30daa5006f6eb32ba0468b929d07a702b70cb2cd | [] | no_license | TAMUSA2018/Week7 | 652120c49b36ce2c31bf13608b7f60d3155bc54d | 258d7974ce369aee69f78e16cb0bfd65c60e314c | refs/heads/master | 2021-01-24T01:30:28.953745 | 2018-02-25T17:45:40 | 2018-02-25T17:45:40 | 122,813,190 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,057 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package week7;
import java.util.concurrent.*;
/**
*
* @author ialsmadi
*/
public class WaitSignalMonitorDemo {
private static WaitSignalMonitor mon = new WaitSignalMonitor();
public static void main (String [] args) {
WaitSignalMonitorThread Num=null;
for (int i = 0; i <10; i ++) {
if(i % 2 == 0){
Num = new WaitSignalMonitorThread(mon, true, "print thread.."+ i);
}
else{
Num = new WaitSignalMonitorThread(mon, false, "print thread.."+ i);
}
try{
Num.t.join();}
catch(Exception ex){
}
}
}
}
| [
"ialsmadi@DESKTOP-T2VSKJH"
] | ialsmadi@DESKTOP-T2VSKJH |
560a0240075e4cddac2ed2569d7bd5c235a5796b | e6b786b3a6b96f06b7a70b450591767c6c315ce2 | /hsweb-system/hsweb-system-oauth2-client/hsweb-system-oauth2-client-controller/src/main/java/org/hswebframework/web/authorization/oauth2/controller/OAuth2ServerConfigController.java | ed73d6aad34bafd96da0fd154665aeb14f06d489 | [
"Apache-2.0"
] | permissive | shunhuawong/hsweb-framework | 2f16c47e8c462ddb0b634a75d3dd0f3cd21ab16e | e0dd32f51583f6f32cb4816e50dc8823ef4dec2d | refs/heads/master | 2021-07-24T05:40:11.697994 | 2017-11-06T01:26:23 | 2017-11-06T01:26:23 | 109,635,775 | 1 | 0 | null | 2017-11-06T02:04:35 | 2017-11-06T02:04:35 | null | UTF-8 | Java | false | false | 2,242 | java | /*
* Copyright 2016 http://www.hswebframework.org
*
* 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.hswebframework.web.authorization.oauth2.controller;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.controller.GenericEntityController;
import org.hswebframework.web.entity.oauth2.client.OAuth2ServerConfigEntity;
import org.hswebframework.web.logging.AccessLogger;
import org.hswebframework.web.service.oauth2.client.OAuth2ServerConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* OAuth2服务配置
*
* @author hsweb-generator-online
*/
@RestController
@RequestMapping("${hsweb.web.mappings.oauth2-server-config:oauth2-server-config}")
@Authorize(permission = "oauth2-server-config")
@AccessLogger("OAuth2服务配置")
public class OAuth2ServerConfigController implements GenericEntityController<OAuth2ServerConfigEntity, String, QueryParamEntity, OAuth2ServerConfigEntity> {
private OAuth2ServerConfigService oAuth2ServerConfigService;
@Override
public OAuth2ServerConfigEntity modelToEntity(OAuth2ServerConfigEntity model, OAuth2ServerConfigEntity entity) {
return model;
}
@Autowired
public void setOAuth2ServerConfigService(OAuth2ServerConfigService oAuth2ServerConfigService) {
this.oAuth2ServerConfigService = oAuth2ServerConfigService;
}
@Override
public OAuth2ServerConfigService getService() {
return oAuth2ServerConfigService;
}
}
| [
"zh.sqy@qq.com"
] | zh.sqy@qq.com |
9f6cdcac01ba429b6eab373e63a118983eeee6fb | fc9f781dcf4907114f884e33b634eb8d0f6ddd5a | /ActiSoftBD/src/bd/Kit_detalle.java | dc617fc7117f2a2a08659338fc7657ab5f9ba070 | [] | no_license | Dgiulian/ActiSoft | c3517fa09c0179764cde2e23405273f4c4d71554 | 7f9b50772b2bde1ed905cb0c899356d8b0a04e83 | refs/heads/master | 2021-05-01T15:22:57.506495 | 2020-10-10T00:35:35 | 2020-10-10T00:35:35 | 50,962,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 748 | java | package bd;
public class Kit_detalle {
public Integer id = 0;
public Integer id_kit = 0;
public Integer id_activo = 0;
public Integer cantidad = 0;
public Integer getId() {
return this.id;
}
public Kit_detalle setId(Integer id) {
this.id = id;
return this;
}
public Integer getId_kit() {
return this.id_kit;
}
public Kit_detalle setId_kit(Integer id_kit) {
this.id_kit = id_kit;
return this;
}
public Integer getId_activo() {
return this.id_activo;
}
public Kit_detalle setId_activo(Integer id_activo) {
this.id_activo = id_activo;
return this;
}
public Integer getCantidad() {
return this.cantidad;
}
public Kit_detalle setCantidad(Integer cantidad) {
this.cantidad = cantidad;
return this;
}
} | [
"giuliani.diego@gmail.com"
] | giuliani.diego@gmail.com |
b957f13dfc7d376bd2481af2fbf6b4430b4279c7 | d431b36970023985c40437fdbe64ceeb5539ecfc | /java-oop-basics/exam-preps/its-in-the-blood/src/Main.java | e2a94c1a4bab2f945724592dbc6372a1e523e54b | [] | no_license | HristoRaykov/JavaOOP-05.2018 | 4cb10766c309f4611c99743f11ef4e3ff341ebf4 | cab2c0cdd35c15312329a2681f9969d8a9276d14 | refs/heads/master | 2021-06-27T21:15:59.601826 | 2019-06-06T11:42:50 | 2019-06-06T11:42:50 | 163,294,049 | 0 | 0 | null | 2020-10-13T11:35:51 | 2018-12-27T12:49:21 | Java | UTF-8 | Java | false | false | 707 | java | import engines.Engine;
import engines.OrganismEngine;
import factories.CommandFactory;
import factories.CommandFactoryImpl;
import repositories.OrganismRepository;
import repositories.Repository;
import utils.*;
public class Main {
public static void main(String[] args) {
Reader inputReader = new ConsoleReader();
Writer outputWriter = new ConsoleWriter();
InputParser inputParser = new InputParserImpl();
Repository organismRepository = new OrganismRepository();
CommandFactory commandFactory = new CommandFactoryImpl(organismRepository);
Engine organismEngine = new OrganismEngine(inputReader, outputWriter, inputParser, commandFactory);
organismEngine.run();
}
}
| [
"hristocr@gmail.com"
] | hristocr@gmail.com |
933e32037302a6fca1a68635176b4478ee57d17f | dd8125f5a99597af9ea358ff6c32b7d65babb491 | /smartdetectview/src/main/java/com/lcd/smartdetectview/Utils/TransUtil.java | b7266294421b6066153ff8654902b3e007f4b1f0 | [] | no_license | Endhero/SmartDetector | 48678675f1edb254a9f4f5d544797bd02b8c199b | 5b3c545df6876d542862400221901ef0fa985378 | refs/heads/master | 2020-05-09T12:15:04.164929 | 2019-07-08T09:35:19 | 2019-07-08T09:35:19 | 181,105,394 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,674 | java | package com.lcd.smartdetectview.Utils;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import java.io.ByteArrayOutputStream;
public class TransUtil
{
public static byte[] Nv21toYuv(byte[] b, int nWidth, int nHeight)
{
byte[] bytes = new byte[]{};
try
{
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(b.length);
YuvImage yuvimage = new YuvImage(b, ImageFormat.NV21, nWidth, nHeight, null);
yuvimage.compressToJpeg(new Rect(0, 0, nWidth, nHeight), 80, bytearrayoutputstream);// 80--JPG图片的质量[0-100],100最高
bytes = bytearrayoutputstream.toByteArray();
}
catch (Exception exception)
{
exception.printStackTrace();
}
return bytes;
}
//摄像头旋转90度
public static byte[] rotateYUV420Degree90(byte[] data, int imageWidth, int imageHeight)
{
byte[] yuv = new byte[imageWidth * imageHeight * 3 / 2];
// Rotate the Y luma
int i = 0;
for (int x = 0; x < imageWidth; x++)
{
for (int y = imageHeight - 1; y >= 0; y--)
{
yuv[i] = data[y * imageWidth + x];
i++;
}
}
// Rotate the U and V color components
i = imageWidth * imageHeight * 3 / 2 - 1;
for (int x = imageWidth - 1; x > 0; x = x - 2)
{
for (int y = 0; y < imageHeight / 2; y++)
{
yuv[i] = data[(imageWidth * imageHeight) + (y * imageWidth) + x];
i--;
yuv[i] = data[(imageWidth * imageHeight) + (y * imageWidth) + (x - 1)];
i--;
}
}
return yuv;
}
//摄像头旋转180度
private static byte[] rotateYUV420Degree180(byte[] data, int imageWidth, int imageHeight)
{
byte[] yuv = new byte[imageWidth * imageHeight * 3 / 2];
int i = 0;
int count = 0;
for (i = imageWidth * imageHeight - 1; i >= 0; i--)
{
yuv[count] = data[i];
count++;
}
i = imageWidth * imageHeight * 3 / 2 - 1;
for (i = imageWidth * imageHeight * 3 / 2 - 1; i >= imageWidth * imageHeight; i -= 2)
{
yuv[count++] = data[i - 1];
yuv[count++] = data[i];
}
return yuv;
}
//摄像头旋转270度
public static byte[] rotateYUV420Degree270(byte[] data, int imageWidth, int imageHeight)
{
byte[] yuv = new byte[imageWidth * imageHeight * 3 / 2];
int nWidth = 0, nHeight = 0;
int wh = 0;
int uvHeight = 0;
if (imageWidth != nWidth || imageHeight != nHeight)
{
nWidth = imageWidth;
nHeight = imageHeight;
wh = imageWidth * imageHeight;
uvHeight = imageHeight >> 1;// uvHeight = height / 2
}
int k = 0;
for (int i = 0; i < imageWidth; i++)
{
int nPos = 0;
for (int j = 0; j < imageHeight; j++)
{
yuv[k] = data[nPos + i];
k++;
nPos += imageWidth;
}
}
for (int i = 0; i < imageWidth; i += 2)
{
int nPos = wh;
for (int j = 0; j < uvHeight; j++)
{
yuv[k] = data[nPos + i];
yuv[k + 1] = data[nPos + i + 1];
k += 2;
nPos += imageWidth;
}
}
return rotateYUV420Degree180(yuv, imageWidth, imageHeight);
}
}
| [
"lcdsss@163.com"
] | lcdsss@163.com |
72fbe4916220bf035c00e55d42e221899cc2abea | d6720f9cb13c0233b76bc8a81717a83b40ae9830 | /0ctope/java_api/src/org/omg/DynamicAny/_DynAnyStub.java | 39ab77a209c82f42eee94823c248193da28e3585 | [] | no_license | EchoLiao/nalstudy | e4565aadf80ff70388225c4c92eb9bb22d85f384 | 869288a16e540520cadc28c82702e52f1c8396ac | refs/heads/master | 2016-09-05T12:38:06.721690 | 2013-06-05T08:47:01 | 2013-06-05T08:47:01 | 33,391,633 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 50,116 | java | package org.omg.DynamicAny;
/**
* org/omg/DynamicAny/_DynAnyStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from ../../../../src/share/classes/org/omg/DynamicAny/DynamicAny.idl
* Monday, March 9, 2009 1:40:47 AM GMT-08:00
*/
/**
* Any values can be dynamically interpreted (traversed) and constructed through DynAny objects.
* A DynAny object is associated with a data value which corresponds to a copy of the value
* inserted into an any.
* <P>A DynAny object may be viewed as an ordered collection of component DynAnys.
* For DynAnys representing a basic type, such as long, or a type without components,
* such as an empty exception, the ordered collection of components is empty.
* Each DynAny object maintains the notion of a current position into its collection
* of component DynAnys. The current position is identified by an index value that runs
* from 0 to n-1, where n is the number of components.
* The special index value -1 indicates a current position that points nowhere.
* For values that cannot have a current position (such as an empty exception),
* the index value is fixed at -1.
* If a DynAny is initialized with a value that has components, the index is initialized to 0.
* After creation of an uninitialized DynAny (that is, a DynAny that has no value but a TypeCode
* that permits components), the current position depends on the type of value represented by
* the DynAny. (The current position is set to 0 or -1, depending on whether the new DynAny
* gets default values for its components.)
* <P>The iteration operations rewind, seek, and next can be used to change the current position
* and the current_component operation returns the component at the current position.
* The component_count operation returns the number of components of a DynAny.
* Collectively, these operations enable iteration over the components of a DynAny, for example,
* to (recursively) examine its contents.
* <P>A constructed DynAny object is a DynAny object associated with a constructed type.
* There is a different interface, inheriting from the DynAny interface, associated with
* each kind of constructed type in IDL (fixed, enum, struct, sequence, union, array,
* exception, and value type).
* <P>A constructed DynAny object exports operations that enable the creation of new DynAny objects,
* each of them associated with a component of the constructed data value.
* As an example, a DynStruct is associated with a struct value. This means that the DynStruct
* may be seen as owning an ordered collection of components, one for each structure member.
* The DynStruct object exports operations that enable the creation of new DynAny objects,
* each of them associated with a member of the struct.
* <P>If a DynAny object has been obtained from another (constructed) DynAny object,
* such as a DynAny representing a structure member that was created from a DynStruct,
* the member DynAny is logically contained in the DynStruct.
* Calling an insert or get operation leaves the current position unchanged.
* Destroying a top-level DynAny object (one that was not obtained as a component of another DynAny)
* also destroys any component DynAny objects obtained from it.
* Destroying a non-top level DynAny object does nothing.
* Invoking operations on a destroyed top-level DynAny or any of its descendants raises OBJECT_NOT_EXIST.
* If the programmer wants to destroy a DynAny object but still wants to manipulate some component
* of the data value associated with it, then he or she should first create a DynAny for the component
* and, after that, make a copy of the created DynAny object.
* <P>The behavior of DynAny objects has been defined in order to enable efficient implementations
* in terms of allocated memory space and speed of access. DynAny objects are intended to be used
* for traversing values extracted from anys or constructing values of anys at runtime.
* Their use for other purposes is not recommended.
* <P>Insert and get operations are necessary to handle basic DynAny objects
* but are also helpful to handle constructed DynAny objects.
* Inserting a basic data type value into a constructed DynAny object
* implies initializing the current component of the constructed data value
* associated with the DynAny object. For example, invoking insert_boolean on a
* DynStruct implies inserting a boolean data value at the current position
* of the associated struct data value.
* A type is consistent for inserting or extracting a value if its TypeCode is equivalent to
* the TypeCode contained in the DynAny or, if the DynAny has components, is equivalent to the TypeCode
* of the DynAny at the current position.
* <P>DynAny and DynAnyFactory objects are intended to be local to the process in which they are
* created and used. This means that references to DynAny and DynAnyFactory objects cannot be exported
* to other processes, or externalized with ORB.object_to_string().
* If any attempt is made to do so, the offending operation will raise a MARSHAL system exception.
* Since their interfaces are specified in IDL, DynAny objects export operations defined in the standard
* org.omg.CORBA.Object interface. However, any attempt to invoke operations exported through the Object
* interface may raise the standard NO_IMPLEMENT exception.
* An attempt to use a DynAny object with the DII may raise the NO_IMPLEMENT exception.
*/
public class _DynAnyStub extends org.omg.CORBA.portable.ObjectImpl implements org.omg.DynamicAny.DynAny
{
final public static java.lang.Class _opsClass = DynAnyOperations.class;
/**
* Returns the TypeCode associated with this DynAny object.
* A DynAny object is created with a TypeCode value assigned to it.
* This TypeCode value determines the type of the value handled through the DynAny object.
* Note that the TypeCode associated with a DynAny object is initialized at the time the
* DynAny is created and cannot be changed during lifetime of the DynAny object.
*
* @return The TypeCode associated with this DynAny object
*/
public org.omg.CORBA.TypeCode type ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("type", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.type ();
} finally {
_servant_postinvoke ($so);
}
} // type
/**
* Initializes the value associated with a DynAny object with the value
* associated with another DynAny object.
* The current position of the target DynAny is set to zero for values that have components
* and to -1 for values that do not have components.
*
* @param dyn_any
* @exception TypeMismatch if the type of the passed DynAny is not equivalent to the type of target DynAny
*/
public void assign (org.omg.DynamicAny.DynAny dyn_any) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("assign", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.assign (dyn_any);
} finally {
_servant_postinvoke ($so);
}
} // assign
/**
* Initializes the value associated with a DynAny object with the value contained in an any.
* The current position of the target DynAny is set to zero for values that have components
* and to -1 for values that do not have components.
*
* @exception TypeMismatch if the type of the passed Any is not equivalent to the type of target DynAny
* @exception InvalidValue if the passed Any does not contain a legal value (such as a null string)
*/
public void from_any (org.omg.CORBA.Any value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("from_any", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.from_any (value);
} finally {
_servant_postinvoke ($so);
}
} // from_any
/**
* Creates an any value from a DynAny object.
* A copy of the TypeCode associated with the DynAny object is assigned to the resulting any.
* The value associated with the DynAny object is copied into the any.
*
* @return a new Any object with the same value and TypeCode
*/
public org.omg.CORBA.Any to_any ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("to_any", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.to_any ();
} finally {
_servant_postinvoke ($so);
}
} // to_any
/**
* Compares two DynAny values for equality.
* Two DynAny values are equal if their TypeCodes are equivalent and, recursively, all component DynAnys
* have equal values.
* The current position of the two DynAnys being compared has no effect on the result of equal.
*
* @return true of the DynAnys are equal, false otherwise
*/
public boolean equal (org.omg.DynamicAny.DynAny dyn_any)
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("equal", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.equal (dyn_any);
} finally {
_servant_postinvoke ($so);
}
} // equal
/**
* Destroys a DynAny object.
* This operation frees any resources used to represent the data value associated with a DynAny object.
* It must be invoked on references obtained from one of the creation operations on the ORB interface
* or on a reference returned by DynAny.copy() to avoid resource leaks.
* Invoking destroy on component DynAny objects (for example, on objects returned by the
* current_component operation) does nothing.
* Destruction of a DynAny object implies destruction of all DynAny objects obtained from it.
* That is, references to components of a destroyed DynAny become invalid.
* Invocations on such references raise OBJECT_NOT_EXIST.
* It is possible to manipulate a component of a DynAny beyond the life time of the DynAny
* from which the component was obtained by making a copy of the component with the copy operation
* before destroying the DynAny from which the component was obtained.
*/
public void destroy ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("destroy", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.destroy ();
} finally {
_servant_postinvoke ($so);
}
} // destroy
/**
* Creates a new DynAny object whose value is a deep copy of the DynAny on which it is invoked.
* The operation is polymorphic, that is, invoking it on one of the types derived from DynAny,
* such as DynStruct, creates the derived type but returns its reference as the DynAny base type.
*
* @return a deep copy of the DynAny object
*/
public org.omg.DynamicAny.DynAny copy ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("copy", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.copy ();
} finally {
_servant_postinvoke ($so);
}
} // copy
/**
* Inserts a boolean value into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_boolean (boolean value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_boolean", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_boolean (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_boolean
/**
* Inserts a byte value into the DynAny. The IDL octet data type is mapped to the Java byte data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_octet (byte value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_octet", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_octet (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_octet
/**
* Inserts a char value into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_char (char value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_char", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_char (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_char
/**
* Inserts a short value into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_short (short value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_short", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_short (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_short
/**
* Inserts a short value into the DynAny. The IDL ushort data type is mapped to the Java short data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_ushort (short value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_ushort", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_ushort (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_ushort
/**
* Inserts an integer value into the DynAny. The IDL long data type is mapped to the Java int data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_long (int value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_long", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_long (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_long
/**
* Inserts an integer value into the DynAny. The IDL ulong data type is mapped to the Java int data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_ulong (int value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_ulong", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_ulong (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_ulong
/**
* Inserts a float value into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_float (float value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_float", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_float (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_float
/**
* Inserts a double value into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_double (double value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_double", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_double (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_double
/**
* Inserts a string value into the DynAny.
* Both bounded and unbounded strings are inserted using this method.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception InvalidValue if the string inserted is longer than the bound of a bounded string
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_string (String value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_string", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_string (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_string
/**
* Inserts a reference to a CORBA object into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_reference (org.omg.CORBA.Object value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_reference", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_reference (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_reference
/**
* Inserts a TypeCode object into the DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_typecode (org.omg.CORBA.TypeCode value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_typecode", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_typecode (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_typecode
/**
* Inserts a long value into the DynAny. The IDL long long data type is mapped to the Java long data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_longlong (long value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_longlong", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_longlong (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_longlong
/**
* Inserts a long value into the DynAny.
* The IDL unsigned long long data type is mapped to the Java long data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_ulonglong (long value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_ulonglong", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_ulonglong (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_ulonglong
/**
* Inserts a char value into the DynAny. The IDL wchar data type is mapped to the Java char data type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_wchar (char value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_wchar", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_wchar (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_wchar
/**
* Inserts a string value into the DynAny.
* Both bounded and unbounded strings are inserted using this method.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception InvalidValue if the string inserted is longer than the bound of a bounded string
*/
public void insert_wstring (String value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_wstring", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_wstring (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_wstring
/**
* Inserts an Any value into the Any represented by this DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_any (org.omg.CORBA.Any value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_any", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_any (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_any
/**
* Inserts the Any value contained in the parameter DynAny into the Any represented by this DynAny.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_dyn_any (org.omg.DynamicAny.DynAny value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_dyn_any", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_dyn_any (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_dyn_any
/**
* Inserts a reference to a Serializable object into this DynAny.
* The IDL ValueBase type is mapped to the Java Serializable type.
*
* @exception InvalidValue if this DynAny has components but has a current position of -1
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public void insert_val (java.io.Serializable value) throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("insert_val", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.insert_val (value);
} finally {
_servant_postinvoke ($so);
}
} // insert_val
/**
* Extracts the boolean value from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public boolean get_boolean () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_boolean", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_boolean ();
} finally {
_servant_postinvoke ($so);
}
} // get_boolean
/**
* Extracts the byte value from this DynAny. The IDL octet data type is mapped to the Java byte data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public byte get_octet () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_octet", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_octet ();
} finally {
_servant_postinvoke ($so);
}
} // get_octet
/**
* Extracts the char value from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public char get_char () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_char", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_char ();
} finally {
_servant_postinvoke ($so);
}
} // get_char
/**
* Extracts the short value from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public short get_short () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_short", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_short ();
} finally {
_servant_postinvoke ($so);
}
} // get_short
/**
* Extracts the short value from this DynAny. The IDL ushort data type is mapped to the Java short data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public short get_ushort () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_ushort", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_ushort ();
} finally {
_servant_postinvoke ($so);
}
} // get_ushort
/**
* Extracts the integer value from this DynAny. The IDL long data type is mapped to the Java int data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public int get_long () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_long", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_long ();
} finally {
_servant_postinvoke ($so);
}
} // get_long
/**
* Extracts the integer value from this DynAny. The IDL ulong data type is mapped to the Java int data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public int get_ulong () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_ulong", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_ulong ();
} finally {
_servant_postinvoke ($so);
}
} // get_ulong
/**
* Extracts the float value from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public float get_float () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_float", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_float ();
} finally {
_servant_postinvoke ($so);
}
} // get_float
/**
* Extracts the double value from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public double get_double () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_double", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_double ();
} finally {
_servant_postinvoke ($so);
}
} // get_double
/**
* Extracts the string value from this DynAny.
* Both bounded and unbounded strings are extracted using this method.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public String get_string () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_string", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_string ();
} finally {
_servant_postinvoke ($so);
}
} // get_string
/**
* Extracts the reference to a CORBA Object from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public org.omg.CORBA.Object get_reference () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_reference", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_reference ();
} finally {
_servant_postinvoke ($so);
}
} // get_reference
/**
* Extracts the TypeCode object from this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public org.omg.CORBA.TypeCode get_typecode () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_typecode", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_typecode ();
} finally {
_servant_postinvoke ($so);
}
} // get_typecode
/**
* Extracts the long value from this DynAny. The IDL long long data type is mapped to the Java long data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public long get_longlong () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_longlong", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_longlong ();
} finally {
_servant_postinvoke ($so);
}
} // get_longlong
/**
* Extracts the long value from this DynAny.
* The IDL unsigned long long data type is mapped to the Java long data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public long get_ulonglong () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_ulonglong", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_ulonglong ();
} finally {
_servant_postinvoke ($so);
}
} // get_ulonglong
/**
* Extracts the long value from this DynAny. The IDL wchar data type is mapped to the Java char data type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public char get_wchar () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_wchar", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_wchar ();
} finally {
_servant_postinvoke ($so);
}
} // get_wchar
/**
* Extracts the string value from this DynAny.
* Both bounded and unbounded strings are extracted using this method.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
*/
public String get_wstring () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_wstring", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_wstring ();
} finally {
_servant_postinvoke ($so);
}
} // get_wstring
/**
* Extracts an Any value contained in the Any represented by this DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public org.omg.CORBA.Any get_any () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_any", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_any ();
} finally {
_servant_postinvoke ($so);
}
} // get_any
/**
* Extracts the Any value contained in the Any represented by this DynAny and returns it wrapped
* into a new DynAny.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public org.omg.DynamicAny.DynAny get_dyn_any () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_dyn_any", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_dyn_any ();
} finally {
_servant_postinvoke ($so);
}
} // get_dyn_any
/**
* Extracts a Serializable object from this DynAny.
* The IDL ValueBase type is mapped to the Java Serializable type.
*
* @exception TypeMismatch if the accessed component in the DynAny is of a type
* that is not equivalent to the requested type.
* @exception TypeMismatch if called on a DynAny whose current component itself has components
* @exception InvalidValue if this DynAny has components but has a current position of -1
*/
public java.io.Serializable get_val () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch, org.omg.DynamicAny.DynAnyPackage.InvalidValue
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("get_val", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.get_val ();
} finally {
_servant_postinvoke ($so);
}
} // get_val
/**
* Sets the current position to index. The current position is indexed 0 to n-1, that is,
* index zero corresponds to the first component. The operation returns true if the resulting
* current position indicates a component of the DynAny and false if index indicates
* a position that does not correspond to a component.
* Calling seek with a negative index is legal. It sets the current position to -1 to indicate
* no component and returns false. Passing a non-negative index value for a DynAny that does not
* have a component at the corresponding position sets the current position to -1 and returns false.
*/
public boolean seek (int index)
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("seek", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.seek (index);
} finally {
_servant_postinvoke ($so);
}
} // seek
/**
* Is equivalent to seek(0).
*/
public void rewind ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("rewind", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
$self.rewind ();
} finally {
_servant_postinvoke ($so);
}
} // rewind
/**
* Advances the current position to the next component.
* The operation returns true while the resulting current position indicates a component, false otherwise.
* A false return value leaves the current position at -1.
* Invoking next on a DynAny without components leaves the current position at -1 and returns false.
*/
public boolean next ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("next", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.next ();
} finally {
_servant_postinvoke ($so);
}
} // next
/**
* Returns the number of components of a DynAny.
* For a DynAny without components, it returns zero.
* The operation only counts the components at the top level.
* For example, if component_count is invoked on a DynStruct with a single member,
* the return value is 1, irrespective of the type of the member.
* <UL>
* <LI>For sequences, the operation returns the current number of elements.
* <LI>For structures, exceptions, and value types, the operation returns the number of members.
* <LI>For arrays, the operation returns the number of elements.
* <LI>For unions, the operation returns 2 if the discriminator indicates that a named member is active,
* otherwise, it returns 1.
* <LI>For DynFixed and DynEnum, the operation returns zero.
* </UL>
*/
public int component_count ()
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("component_count", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.component_count ();
} finally {
_servant_postinvoke ($so);
}
} // component_count
/**
* Returns the DynAny for the component at the current position.
* It does not advance the current position, so repeated calls to current_component
* without an intervening call to rewind, next, or seek return the same component.
* The returned DynAny object reference can be used to get/set the value of the current component.
* If the current component represents a complex type, the returned reference can be narrowed
* based on the TypeCode to get the interface corresponding to the to the complex type.
* Calling current_component on a DynAny that cannot have components,
* such as a DynEnum or an empty exception, raises TypeMismatch.
* Calling current_component on a DynAny whose current position is -1 returns a nil reference.
* The iteration operations, together with current_component, can be used
* to dynamically compose an any value. After creating a dynamic any, such as a DynStruct,
* current_component and next can be used to initialize all the components of the value.
* Once the dynamic value is completely initialized, to_any creates the corresponding any value.
*
* @exception TypeMismatch If called on a DynAny that cannot have components,
* such as a DynEnum or an empty exception
*/
public org.omg.DynamicAny.DynAny current_component () throws org.omg.DynamicAny.DynAnyPackage.TypeMismatch
{
org.omg.CORBA.portable.ServantObject $so = _servant_preinvoke ("current_component", _opsClass);
DynAnyOperations $self = (DynAnyOperations) $so.servant;
try {
return $self.current_component ();
} finally {
_servant_postinvoke ($so);
}
} // current_component
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:omg.org/DynamicAny/DynAny:1.0"};
public String[] _ids ()
{
return (String[])__ids.clone ();
}
private void readObject (java.io.ObjectInputStream s) throws java.io.IOException
{
String str = s.readUTF ();
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init (args, props).string_to_object (str);
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate ();
_set_delegate (delegate);
}
private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
{
String[] args = null;
java.util.Properties props = null;
String str = org.omg.CORBA.ORB.init (args, props).object_to_string (this);
s.writeUTF (str);
}
} // class _DynAnyStub
| [
"nuoerlz@da13e6bb-9c2c-a04c-5f4c-2d7d41371f5f"
] | nuoerlz@da13e6bb-9c2c-a04c-5f4c-2d7d41371f5f |
44774aa93c75a2fdf9681cdbddfd35707f427ba8 | a0cba0ee530931e65cae24971d327c02f783ecac | /app/src/main/java/mahashakti/mahashakti/Adapters/AdapterBooking.java | 1fd3e87e6bfd4fa93ac9fed30a874af810fa2926 | [] | no_license | pankajkumar3291/mahashakti | 4c6d057cdf3b16af640319319f9f38e55b7b803c | 40e9f8d316a69a9b1333287623cfba029cc45214 | refs/heads/master | 2020-12-13T05:51:40.020176 | 2020-01-16T13:42:02 | 2020-01-16T13:42:02 | 234,328,603 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,884 | java | package mahashakti.mahashakti.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import mahashakti.mahashakti.Dialogs.BookingCancelDialog;
import mahashakti.mahashakti.Models.BookingModel;
import mahashakti.mahashakti.Models.ProgramModel;
import com.mahashakti.R;
/**
* Created by dharamveer on 11/1/18.
*/
public class AdapterBooking extends RecyclerView.Adapter<AdapterBooking.MyHolder>{
Context context;
View view;
ArrayList<BookingModel> bookingModelArrayList = new ArrayList<>();
public AdapterBookingClickListener adapterBookingClickListener;
public AdapterBooking(Context context, ArrayList<BookingModel> bookingModelArrayList) {
this.context = context;
this.bookingModelArrayList = bookingModelArrayList;
}
public interface AdapterBookingClickListener{
void onCancelButtonClik(View view, int position);
void onBookedButtonClicked(View view,int position);
}
public void setOnItemClickListener(AdapterBookingClickListener adapterBookingClickListener) {
this.adapterBookingClickListener = adapterBookingClickListener;
}
@Override
public AdapterBooking.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_booking, parent, false);
return new AdapterBooking.MyHolder(view);
}
@Override
public void onBindViewHolder(final AdapterBooking.MyHolder holder, final int position) {
BookingModel bookingModel = bookingModelArrayList.get(position);
holder.imageBooking.setImageResource(bookingModel.getImageProgramBooking());
holder.txtFestivalNameBooking.setText(bookingModel.getFestivalNameBooking());
holder.txtFestDescriptionBooking.setText(bookingModel.getFestDescriptionBooking());
holder.txtDateBooking.setText(bookingModel.getDateBooking());
holder.txtTimeBooking.setText(bookingModel.getTimeBooking());
holder.btnCancelBooking.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapterBookingClickListener.onCancelButtonClik(holder.btnCancelBooking,position);
}
});
holder.btnBookingAc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapterBookingClickListener.onBookedButtonClicked(holder.btnBookingAc,position);
}
});
}
@Override
public int getItemCount()
{
return bookingModelArrayList.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
private CircleImageView imageBooking;
private TextView txtFestivalNameBooking,txtFestDescriptionBooking,txtDateBooking,txtTimeBooking;
private Button btnBookingAc,btnCancelBooking;
public MyHolder(View itemView) {
super(itemView);
//Image view
imageBooking = itemView.findViewById(R.id.imageBooking);
//Text Views
txtFestivalNameBooking = itemView.findViewById(R.id.txtFestivalNameBooking);
txtFestDescriptionBooking = itemView.findViewById(R.id.txtFestDescriptionBooking);
txtDateBooking = itemView.findViewById(R.id.txtDateBooking);
txtTimeBooking = itemView.findViewById(R.id.txtTimeBooking);
//Buttons
btnBookingAc = itemView.findViewById(R.id.btnBookingAc);
btnCancelBooking = itemView.findViewById(R.id.btnCancelBooking);
}
}
}
| [
"dharamveer.smartitventures@gmail.com"
] | dharamveer.smartitventures@gmail.com |
edc854bbd43e27eeb33ef895fee25e8934aca804 | a49119eeb105310ed184df1ab0caaf6cdb87e8dc | /src/main/java/com/reedcons/demo/web/ArchivosRestController.java | f55323bd3c7687ff106339090ba3f4e5173850fb | [] | no_license | magm3333/demo | 00834d4f12cae5afa81a1244f94713475afaa9a0 | 56e0cedc39212f2331d75f3e0d8eec52b27a32f7 | refs/heads/master | 2021-08-15T23:49:00.956155 | 2018-12-14T13:46:40 | 2018-12-14T13:46:40 | 147,521,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,660 | java | package com.reedcons.demo.web;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.reedcons.demo.business.BusinessException;
import com.reedcons.demo.business.IArchivoBusiness;
import com.reedcons.demo.model.Archivo;
import com.reedcons.demo.model.exception.NotFoundException;
@RestController
@RequestMapping(Constantes.URL_ARCHIVOS)
public class ArchivosRestController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private IArchivoBusiness archivoBusiness;
// /api/v1/archivos/fs/
@PostMapping(value = { "/fs", "/fs/" })
public ResponseEntity<Archivo> uploadFS(@RequestParam("file") MultipartFile file) {
Archivo r;
try {
r = archivoBusiness.saveToFS(file);
r.setDownloadUri(Constantes.URL_ARCHIVOS + "/fs/" + r.getNombre());
HttpHeaders headers = new HttpHeaders();
headers.add("location", r.getDownloadUri());
return new ResponseEntity<Archivo>(r, headers, HttpStatus.CREATED);
//return ResponseEntity.status(HttpStatus.CREATED.value()).headers(headers).body(r);
} catch (BusinessException e) {
return new ResponseEntity<Archivo>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value = "/fs/{fileName:.+}")
public ResponseEntity<Resource> downloadFS(@PathVariable("fileName") String fileName, HttpServletRequest request) {
Resource resource;
try {
resource=archivoBusiness.loadFromFS(fileName);
} catch (BusinessException e) {
return new ResponseEntity<Resource>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (NotFoundException e) {
return new ResponseEntity<Resource>(HttpStatus.NOT_FOUND);
}
String mime = null;
try {
mime=request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException e) {
}
if(mime==null) {
mime="application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(mime))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
@PostMapping(value = { "/", "" })
public ResponseEntity<Archivo> upload(@RequestParam("file") MultipartFile file) {
Archivo r;
try {
r=guardarImpl(file);
HttpHeaders headers = new HttpHeaders();
headers.add("location", r.getDownloadUri());
return new ResponseEntity<Archivo>(r, headers, HttpStatus.CREATED);
} catch (IOException e) {
return new ResponseEntity<Archivo>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (BusinessException e) {
return new ResponseEntity<Archivo>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value = { "/", "" })
public ResponseEntity<List<Archivo>> list(
@RequestParam(required=false,value="q",defaultValue="*") String q,
@RequestParam(required=false,value="d",defaultValue="-1") long desde,
@RequestParam(required=false,value="h",defaultValue="-1") long hasta) {
try {
if (desde!=-1 && hasta!=-1 && desde<=hasta) {
return new ResponseEntity<List<Archivo>>(archivoBusiness.getAll(desde,hasta), HttpStatus.OK);
} else if (q.equals("*") || q.trim().length() == 0) {
return new ResponseEntity<List<Archivo>>(archivoBusiness.getAll(), HttpStatus.OK);
} else {
return new ResponseEntity<List<Archivo>>(archivoBusiness.getAll(q), HttpStatus.OK);
}
} catch (BusinessException e) {
return new ResponseEntity<List<Archivo>>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private Archivo guardarImpl( MultipartFile file) throws IOException, BusinessException {
Archivo a=new Archivo();
a.setContenido(file.getBytes());
a.setLength(a.getContenido().length);
a.setNombre(StringUtils.cleanPath(file.getOriginalFilename()));
a.setMime(file.getContentType());
archivoBusiness.add(a);
a.setDownloadUri(Constantes.URL_ARCHIVOS+"/"+a.getId());
return a;
}
}
| [
"magm3333@gmail.com"
] | magm3333@gmail.com |
b483e519753dd005ad340499aee1e7fe271c321e | eb9c62b7940f8e25f35ebd1491331b2658c455b0 | /src/main/java/com/bruce/theychat/hotswap/HackSystem.java | b4a4b0c16ab2c01e53355300788e7be3caae3e77 | [] | no_license | Imstrong/theychat | 203331bc24754877810c41d546f084dc9d701bb1 | e6ee52b943c2a49f56479b9116fb7e8dae397d7f | refs/heads/master | 2020-03-23T21:49:33.078291 | 2018-07-25T10:12:40 | 2018-07-25T10:12:40 | 142,135,078 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,115 | java | package com.bruce.theychat.hotswap;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
public class HackSystem {
public final static InputStream in=System.in;
private static ByteArrayOutputStream buffer=new ByteArrayOutputStream();
public final static PrintStream out=new PrintStream(buffer);
public final static PrintStream err=out;
public static String getBufferString(){
return buffer.toString();
}
public static void clearBuffer(){
buffer.reset();
}
public static void setSecurityManager(final SecurityManager s){
System.setSecurityManager(s);
}
public static SecurityManager getSecurityManager(){
return System.getSecurityManager();
}
public static long currentTimeMillis(){
return System.currentTimeMillis();
}
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length){
System.arraycopy(src,srcPos,dest,destPos,length);
}
public static int identityHashCode(Object x){
return System.identityHashCode(x);
}
}
| [
"zbzwcode@163.com"
] | zbzwcode@163.com |
83989393b7ade2097b25c9ef909951caaab8036a | 12f3724fd3e83c60f177d60184d9b65f65f96638 | /s3Email/src/main/java/com/s3mail/s3/service/StorageService.java | 7ce0f3b54f2da8029a63ee874f202d563d99dc96 | [] | no_license | rp9959/S3andMail | 7daec7f35ff7df375c7b0bd2311a7762b0733353 | 97573d3c1cdb07fd4918993e66ad2797c098c622 | refs/heads/master | 2023-08-12T20:28:15.644656 | 2021-09-08T17:36:51 | 2021-09-08T17:36:51 | 404,276,329 | 0 | 0 | null | 2021-09-08T13:09:06 | 2021-09-08T08:51:38 | Java | UTF-8 | Java | false | false | 3,601 | java | package com.s3mail.s3.service;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.util.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.time.Instant;
@Service
@Slf4j
public class StorageService {
@Value("${application.bucket.name}")
private String bucketName;
@Autowired
private AmazonS3 s3Client;
public String uploadFile(MultipartFile file, String username) {
File fileObj = convertMultiPartFileToFile(file);
String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
s3Client.putObject(new PutObjectRequest(bucketName, username+"/"+fileName, fileObj));
String url = getDownloadLink(bucketName, username+"/"+fileName);
fileObj.delete();
return url;
}
public String getDownloadLink(String bucketname,String objectKey)
{
URL url=null;
try {
java.util.Date expiration = new java.util.Date();
long expTimeMillis = Instant.now().toEpochMilli();
expTimeMillis += 1000 * 60 * 60;
expiration.setTime(expTimeMillis);
// Generate the presigned URL.
System.out.println("Generating pre-signed URL.");
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey)
.withMethod(HttpMethod.GET)
.withExpiration(expiration);
url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
return url.toString();
}
public byte[] downloadFile(String fileName) {
S3Object s3Object = s3Client.getObject(bucketName, fileName);
S3ObjectInputStream inputStream = s3Object.getObjectContent();
try {
byte[] content = IOUtils.toByteArray(inputStream);
return content;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String deleteFile(String fileName) {
s3Client.deleteObject(bucketName, fileName);
return fileName + " removed ...";
}
private File convertMultiPartFileToFile(MultipartFile file) {
File convertedFile = new File(file.getOriginalFilename());
try (FileOutputStream fos = new FileOutputStream(convertedFile)) {
fos.write(file.getBytes());
} catch (IOException e) {
System.out.println( "Error converting multipartFile to file"+e);
}
return convertedFile;
}
}
| [
"Rahul.Pagidala@cashe.local"
] | Rahul.Pagidala@cashe.local |
6844fe11bf374560e3364aca0d79291f6b16b1ed | 26ecb9806a573344cf46c6b49b897132a2b2f755 | /Pong/src/tenis/Teclado.java | 628cc3eec6162fa23d312e232635056567899242 | [] | no_license | Brenocsc/PongFramework | e399657eac7fdf3544e3c5fb111139c29e859c34 | c51f9a9762f74fb6a079423c998f759c575aa691 | refs/heads/master | 2020-06-19T06:18:14.458291 | 2019-07-12T14:35:22 | 2019-07-12T14:35:22 | 196,594,216 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,572 | java | package tenis;
import fw.FTeclado;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import fw.Fjogador;
import fw.Fpong;
import fw.Vetor;
import java.awt.TextArea;
public class Teclado extends FTeclado{
private Fjogador jogador1;
private Fjogador jogador2;
private float velocidade = 2;
private boolean PressCima1 = false;
private boolean PressCima2 = false;
private boolean PressBaixo1 = false;
private boolean PressBaixo2 = false;
private boolean umJogador;
private int W = KeyEvent.VK_W;
private int S = KeyEvent.VK_S;
private int UP = KeyEvent.VK_UP;
private int DOWN = KeyEvent.VK_DOWN;
public Teclado(Fjogador j1,Fjogador j2,boolean umJogador) {
jogador1 = j1;
jogador2 = j2;
this.umJogador = umJogador;
}
@Override
public void keyPressed(KeyEvent key) {
int Keycode = key.getKeyCode();
if(Keycode == W) {
PressCima1 = true;
} else if(Keycode == S) {
PressBaixo1 = true;
} else if(Keycode == UP) {
PressCima2 = true;
} else if(Keycode == DOWN) {
PressBaixo2 = true;
}
}
@Override
public void keyReleased(KeyEvent key) {
int Keycode = key.getKeyCode();
if(Keycode == W) {
PressCima1 = false;
} else if(Keycode == S) {
PressBaixo1 = false;
} else if(Keycode == UP) {
PressCima2 = false;
} else if(Keycode == DOWN) {
PressBaixo2 = false;
}
}
@Override
public void keyTyped(KeyEvent key) {}
@Override
public void Atualizar() {
float velocidadeDestino;
if(PressCima1 && PressBaixo1){
velocidadeDestino = 0;
} else if (PressCima1) {
velocidadeDestino = -velocidade;
} else if (PressBaixo1) {
velocidadeDestino = velocidade;
} else {
velocidadeDestino = 0;
}
jogador1.setVelocidade(new Vetor(jogador1.getVelocidade().x,velocidadeDestino));
if(!umJogador) {
if(PressCima2 && PressBaixo2){
velocidadeDestino = 0;
} else if (PressCima2) {
velocidadeDestino = -velocidade;
} else if (PressBaixo2) {
velocidadeDestino = velocidade;
} else {
velocidadeDestino = 0;
}
jogador2.setVelocidade(new Vetor(jogador2.getVelocidade().x,velocidadeDestino));
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
6bcbca1d7cced0b9a897ee08d6550c062357b93d | 42a2454fc1b336fd7e00c3583f379f03516d50e0 | /plugins/stream-debugger/src/com/intellij/debugger/streams/ui/impl/CollectionTree.java | 70f90fb5f6f1a6909efeb847c7efff73292ec2ec | [
"Apache-2.0"
] | permissive | meanmail/intellij-community | f65893f148b2913b18ec4787a82567c8b41c2e2b | edeb845e7c483d852d807eb0015d28ee8a813f87 | refs/heads/master | 2021-01-11T02:53:33.903981 | 2019-03-01T18:42:10 | 2019-03-01T18:42:10 | 70,822,840 | 1 | 1 | Apache-2.0 | 2019-03-01T18:42:11 | 2016-10-13T15:49:45 | Java | UTF-8 | Java | false | false | 13,929 | java | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.ui.impl;
import com.intellij.debugger.engine.JavaValue;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.memory.utils.InstanceJavaValue;
import com.intellij.debugger.streams.trace.TraceElement;
import com.intellij.debugger.streams.ui.PaintingListener;
import com.intellij.debugger.streams.ui.TraceContainer;
import com.intellij.debugger.streams.ui.ValuesSelectionListener;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.MessageDescriptor;
import com.intellij.debugger.ui.impl.watch.NodeManagerImpl;
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.ui.JBColor;
import com.intellij.util.EventDispatcher;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree;
import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreeListener;
import com.intellij.xdebugger.impl.ui.tree.nodes.RestorableStateNode;
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueContainerNode;
import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl;
import com.sun.jdi.Value;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Vitaliy.Bibaev
*/
public class CollectionTree extends XDebuggerTree implements TraceContainer {
private static final TreePath[] EMPTY_PATHS = new TreePath[0];
private static final Map<Integer, Color> COLORS_CACHE = new HashMap<>();
private static final Object NULL_MARKER = ObjectUtils.sentinel("CollectionTree.NULL_MARKER");
private final NodeManagerImpl myNodeManager;
private final Project myProject;
private final Map<TraceElement, TreePath> myValue2Path = new HashMap<>();
private final Map<TreePath, TraceElement> myPath2Value = new HashMap<>();
private final int myItemsCount;
private Set<TreePath> myHighlighted = Collections.emptySet();
private final EventDispatcher<ValuesSelectionListener> mySelectionDispatcher = EventDispatcher.create(ValuesSelectionListener.class);
private final EventDispatcher<PaintingListener> myPaintingDispatcher = EventDispatcher.create(PaintingListener.class);
private boolean myIgnoreInternalSelectionEvents = false;
private boolean myIgnoreExternalSelectionEvents = false;
CollectionTree(@NotNull List<Value> values,
@NotNull List<TraceElement> traceElements,
@NotNull EvaluationContextImpl evaluationContext) {
super(evaluationContext.getProject(), new JavaDebuggerEditorsProvider(), null, XDebuggerActions.INSPECT_TREE_POPUP_GROUP, null);
myProject = evaluationContext.getProject();
myNodeManager = new MyNodeManager(myProject);
myItemsCount = values.size();
final XValueNodeImpl root = new XValueNodeImpl(this, null, "root", new MyRootValue(values, evaluationContext));
setRoot(root, false);
root.setLeaf(false);
final Map<Object, List<TraceElement>> key2TraceElements =
StreamEx.of(traceElements).groupingBy(CollectionTree::extractKey);
final Map<Object, Integer> key2Index = new HashMap<>(key2TraceElements.size() + 1);
addTreeListener(new XDebuggerTreeListener() {
@Override
public void nodeLoaded(@NotNull RestorableStateNode node, @NotNull String name) {
final XDebuggerTreeListener listener = this;
if (node instanceof XValueContainerNode) {
final XValueContainer container = ((XValueContainerNode)node).getValueContainer();
if (container instanceof JavaValue) {
final ValueDescriptorImpl descriptor = ((JavaValue)container).getDescriptor();
evaluationContext.getDebugProcess().getManagerThread().schedule(new DebuggerCommandImpl() {
@Override
protected void action() {
final Value value = descriptor.getValue();
ApplicationManager.getApplication().invokeLater(() -> {
final Object key = value == null ? NULL_MARKER : value;
List<TraceElement> elements = key2TraceElements.get(key);
final int nextIndex = key2Index.getOrDefault(key, -1) + 1;
if (elements != null && nextIndex < elements.size()) {
final TraceElement element = elements.get(nextIndex);
myValue2Path.put(element, node.getPath());
myPath2Value.put(node.getPath(), element);
key2Index.put(key, nextIndex);
}
if (myPath2Value.size() == traceElements.size()) {
CollectionTree.this.removeTreeListener(listener);
ApplicationManager.getApplication().invokeLater(CollectionTree.this::repaint);
}
});
}
});
}
}
}
});
addTreeSelectionListener(e -> {
if (myIgnoreInternalSelectionEvents) {
return;
}
final TreePath[] selectedPaths = getSelectionPaths();
final TreePath[] paths = selectedPaths == null ? EMPTY_PATHS : selectedPaths;
final List<TraceElement> selectedItems =
Arrays.stream(paths)
.map(this::getTopPath)
.map(myPath2Value::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
fireSelectionChanged(selectedItems);
});
setSelectionRow(0);
expandNodesOnLoad(node -> node == root);
}
CollectionTree(@NotNull List<TraceElement> traceElements,
@NotNull EvaluationContextImpl evaluationContext) {
this(ContainerUtil.map(traceElements, TraceElement::getValue), traceElements, evaluationContext);
}
@Override
public boolean isFileColorsEnabled() {
return true;
}
@Nullable
@Override
public Color getFileColorForPath(@NotNull TreePath path) {
if (isPathHighlighted(path)) {
final Color background = UIUtil.getTreeSelectionBackground(true);
return COLORS_CACHE.computeIfAbsent(background.getRGB(), rgb -> new JBColor(
new Color(background.getRed(), background.getGreen(), background.getBlue(), 75),
new Color(background.getRed(), background.getGreen(), background.getBlue(), 100)));
}
return UIUtil.getTreeBackground();
}
@Override
public void clearSelection() {
myIgnoreInternalSelectionEvents = true;
super.clearSelection();
myIgnoreInternalSelectionEvents = false;
}
@Nullable
public Rectangle getRectByValue(@NotNull TraceElement element) {
final TreePath path = myValue2Path.get(element);
return path == null ? null : getPathBounds(path);
}
@Override
public void highlight(@NotNull List<TraceElement> elements) {
clearSelection();
highlightValues(elements);
tryScrollTo(elements);
updatePresentation();
}
@Override
public void select(@NotNull List<TraceElement> elements) {
final TreePath[] paths = elements.stream().map(myValue2Path::get).toArray(TreePath[]::new);
select(paths);
highlightValues(elements);
if (paths.length > 0) {
scrollPathToVisible(paths[0]);
}
updatePresentation();
}
@Override
public void addSelectionListener(@NotNull ValuesSelectionListener listener) {
// TODO: dispose?
mySelectionDispatcher.addListener(listener);
}
@Override
public boolean highlightedExists() {
return !isSelectionEmpty() || !myHighlighted.isEmpty();
}
public int getItemsCount() {
return myItemsCount;
}
public void addPaintingListener(@NotNull PaintingListener listener) {
myPaintingDispatcher.addListener(listener);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
myPaintingDispatcher.getMulticaster().componentPainted();
}
private void select(@NotNull TreePath[] paths) {
if (myIgnoreExternalSelectionEvents) {
return;
}
myIgnoreInternalSelectionEvents = true;
getSelectionModel().setSelectionPaths(paths);
myIgnoreInternalSelectionEvents = false;
}
private void fireSelectionChanged(List<TraceElement> selectedItems) {
myIgnoreExternalSelectionEvents = true;
mySelectionDispatcher.getMulticaster().selectionChanged(selectedItems);
myIgnoreExternalSelectionEvents = false;
}
private void tryScrollTo(@NotNull List<TraceElement> elements) {
final int[] rows = elements.stream().map(myValue2Path::get).filter(Objects::nonNull).mapToInt(this::getRowForPath).sorted().toArray();
if (rows.length == 0) {
return;
}
if (isShowing()) {
final Rectangle bestVisibleArea = optimizeRowsCountInVisibleRect(rows);
final Rectangle visibleRect = getVisibleRect();
final boolean notVisibleHighlightedRowExists = Arrays
.stream(rows)
.anyMatch(x -> !visibleRect.intersects(getRowBounds(x)));
if (notVisibleHighlightedRowExists) {
scrollRectToVisible(bestVisibleArea);
}
}
else {
// Use slow path if component hidden
scrollPathToVisible(getPathForRow(rows[0]));
}
}
@NotNull
private Rectangle optimizeRowsCountInVisibleRect(@NotNull int[] rows) {
// a simple scan-line algorithm to find an optimal subset of visible rows (maximum)
final Rectangle visibleRect = getVisibleRect();
final int height = visibleRect.height;
class Result {
private int top = 0;
private int bot = 0;
@Contract(pure = true)
private int count() {
return bot - top;
}
}
int topIndex = 0;
int bottomIndex = 1;
Rectangle rowBounds = getRowBounds(rows[topIndex]);
if (rowBounds == null) return visibleRect;
int topY = rowBounds.y;
final Result result = new Result();
while (bottomIndex < rows.length) {
final int nextY = getRowBounds(rows[bottomIndex]).y;
while (nextY - topY > height) {
topIndex++;
rowBounds = getRowBounds(rows[topIndex]);
if (rowBounds == null) return visibleRect;
topY = rowBounds.y;
}
if (bottomIndex - topIndex > result.count()) {
result.top = topIndex;
result.bot = bottomIndex;
}
bottomIndex++;
}
int y = getRowBounds(rows[result.top]).y;
if (y > visibleRect.y) {
final Rectangle botBounds = getRowBounds(rows[result.bot]);
y = botBounds.y + botBounds.height - visibleRect.height;
}
return new Rectangle(visibleRect.x, y, visibleRect.width, height);
}
private void highlightValues(@NotNull List<TraceElement> elements) {
myHighlighted = elements.stream().map(myValue2Path::get).collect(Collectors.toSet());
}
private void updatePresentation() {
revalidate();
repaint();
}
public boolean isHighlighted(@NotNull TraceElement traceElement) {
final TreePath path = myValue2Path.get(traceElement);
return path != null && isPathHighlighted(path);
}
private boolean isPathHighlighted(@NotNull TreePath path) {
return myHighlighted.contains(path) || isPathSelected(path);
}
private class MyRootValue extends XValue {
private final List<Value> myValues;
private final EvaluationContextImpl myEvaluationContext;
MyRootValue(@NotNull List<Value> values, @NotNull EvaluationContextImpl evaluationContext) {
myValues = values;
myEvaluationContext = evaluationContext;
}
@Override
public void computeChildren(@NotNull XCompositeNode node) {
final XValueChildrenList children = new XValueChildrenList();
for (final Value value : myValues) {
final PrimitiveValueDescriptor valueDescriptor = new PrimitiveValueDescriptor(myProject, value);
children.add(new InstanceJavaValue(valueDescriptor, myEvaluationContext, myNodeManager));
}
node.addChildren(children, true);
}
@Override
public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) {
node.setPresentation(null, "", "", true);
}
}
private final static class MyNodeManager extends NodeManagerImpl {
MyNodeManager(Project project) {
super(project, null);
}
@Override
public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) {
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
public DebuggerTreeNodeImpl createMessageNode(MessageDescriptor descriptor) {
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
public DebuggerTreeNodeImpl createMessageNode(String message) {
return new DebuggerTreeNodeImpl(null, new MessageDescriptor(message));
}
}
@NotNull
private TreePath getTopPath(@NotNull TreePath path) {
TreePath current = path;
while (current != null && !myPath2Value.containsKey(current)) {
current = current.getParentPath();
}
return current != null ? current : path;
}
private static Object extractKey(@NotNull TraceElement element) {
final Value value = element.getValue();
return value == null ? NULL_MARKER : value;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7d6875587866ab290802c8bba18663f19d1fda55 | b8d3678d90e7197c1e69adea7761473f4059e36f | /app/src/main/java/com/example/exchange_rate/Currency.java | 08968c4f535e63107d493f7e5c1667dba66a5498 | [] | no_license | 1211186431/Exchange_rate | 8d932cdc0845883ef624284871be1dceeadbfabc | 145f8e4aa6af14859b5485b60ae8f37d48c68201 | refs/heads/master | 2022-12-28T08:53:00.285512 | 2020-10-07T06:10:36 | 2020-10-07T06:10:36 | 301,747,963 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 649 | java | package com.example.exchange_rate;
public class Currency {
String name;
String code;
public Currency(String name, String code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "Currency{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
'}';
}
}
| [
"56494120+1211186431@users.noreply.github.com"
] | 56494120+1211186431@users.noreply.github.com |
6123ee2abb3fe500ebb764fc2a752a7f03aa1b28 | 92aba892f6cc504527e0865e88deb480511750f1 | /MicroServiceDemandeConge/src/main/java/com/cmu/demandeConge/payload/AuthResponse.java | df7aac16d22f13d28759ddea1354d9e855f5e1cf | [] | no_license | charlesvictor10/Systeme-Gestion-Absence-ANACMU | 491c09fbe97bb13d05f057f09f739e66a0a8dc46 | ad764f67432ab969b2b5cb4fa65eb70360597f54 | refs/heads/master | 2023-07-18T17:23:06.317740 | 2021-09-09T21:36:32 | 2021-09-09T21:36:32 | 287,998,827 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 567 | java | package com.cmu.demandeConge.payload;
public class AuthResponse {
private String accessToken;
private String tokenType = "Bearer";
public AuthResponse(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
}
| [
"vwade@gainde2000.sn"
] | vwade@gainde2000.sn |
fa7d16c5260f729c73c00322cc1f5f00dbb077af | c6543949789a427137f6aa860e8f9525430650ee | /src/main/java/com/tech/parsers/KMAT.java | 6b2a6a4d8bfb533f4ab0b2c1c29dc4a706808a5f | [] | no_license | appurajacool2015/jaxbparser | a14f10e8c66cb3195444a6ac715a7af39fb1149b | 6349a8166ef16eec1993c563678412c67da6e769 | refs/heads/master | 2021-01-23T00:39:48.392134 | 2017-05-30T10:33:27 | 2017-05-30T10:33:27 | 92,823,400 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,691 | java | package com.tech.parsers;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
@XmlAccessorType(XmlAccessType.FIELD)
public class KMAT {
@XmlElement(name="ID")
private String ID;
@XmlElement(name="MPN")
private String MPN;
@XmlElement(name="MPN_DESC")
private String MPN_DESC;
@XmlElement(name="OPTION_COUNT")
private String OPTION_COUNT;
@XmlElement(name="OPTIONS_ADDED")
private String OPTIONS_ADDED;
@XmlElement(name="OPTIONS_DELETES")
private String OPTIONS_DELETES;
@XmlElementWrapper(name="FIND_NOS")
@XmlElement(name="FIND_NO")
private List<FIND_NO> find_nos;
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getMPN() {
return MPN;
}
public void setMPN(String mPN) {
MPN = mPN;
}
public String getMPN_DESC() {
return MPN_DESC;
}
public void setMPN_DESC(String mPN_DESC) {
MPN_DESC = mPN_DESC;
}
public String getOPTION_COUNT() {
return OPTION_COUNT;
}
public void setOPTION_COUNT(String oPTION_COUNT) {
OPTION_COUNT = oPTION_COUNT;
}
public String getOPTIONS_ADDED() {
return OPTIONS_ADDED;
}
public void setOPTIONS_ADDED(String oPTIONS_ADDED) {
OPTIONS_ADDED = oPTIONS_ADDED;
}
public String getOPTIONS_DELETES() {
return OPTIONS_DELETES;
}
public void setOPTIONS_DELETES(String oPTIONS_DELETES) {
OPTIONS_DELETES = oPTIONS_DELETES;
}
public List<FIND_NO> getFind_nos() {
return find_nos;
}
public void setFind_nos(List<FIND_NO> find_nos) {
this.find_nos = find_nos;
}
}
| [
"anand_jhunjhunwala@apple.com"
] | anand_jhunjhunwala@apple.com |
e220c8cd7742df4657f2bf42ec0bf92ce0ba95aa | 88dafc04e4433d369606b1785165963be0b2fb35 | /app/src/main/java/com/kgurgul/cpuinfo/utils/processmanager/models/AndroidProcess.java | d32299a222b2936ec45046a505a1291792028ff5 | [
"Apache-2.0"
] | permissive | vaginessa/cpu-info | 99f28606352f81af8690ebef383a8e940fbc53f9 | 8153e3998f153ba03746b0e8e9caca5c1344c1cc | refs/heads/master | 2021-10-10T22:25:46.821673 | 2017-12-01T13:11:50 | 2017-12-01T13:11:50 | 112,911,314 | 0 | 0 | Apache-2.0 | 2019-01-18T10:10:42 | 2017-12-03T08:15:54 | Kotlin | UTF-8 | Java | false | false | 29,033 | java | /*
* Copyright (C) 2015. Jared Rummler <jared.rummler@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 com.kgurgul.cpuinfo.utils.processmanager.models;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import java.io.IOException;
public class AndroidProcess implements Parcelable {
public static final Creator<AndroidProcess> CREATOR = new Creator<AndroidProcess>() {
@Override
public AndroidProcess createFromParcel(Parcel source) {
return new AndroidProcess(source);
}
@Override
public AndroidProcess[] newArray(int size) {
return new AndroidProcess[size];
}
};
/**
* the process name
*/
public final String name;
/**
* the process id
*/
public final int pid;
/**
* AndroidProcess constructor
*
* @param pid the process id
* @throws IOException if /proc/[pid] does not exist or we don't have read access.
*/
public AndroidProcess(int pid) throws IOException {
this.pid = pid;
this.name = getProcessName(pid);
}
protected AndroidProcess(Parcel in) {
this.name = in.readString();
this.pid = in.readInt();
}
/**
* Get the name of a running process.
*
* @param pid the process id.
* @return the name of the process.
* @throws IOException if the file does not exist or we don't have read permissions.
*/
static String getProcessName(int pid) throws IOException {
String cmdline = null;
try {
cmdline = ProcFile.readFile(String.format("/proc/%d/cmdline", pid)).trim();
} catch (IOException ignored) {
}
if (TextUtils.isEmpty(cmdline)) {
return Stat.get(pid).getComm();
}
return cmdline;
}
/**
* Read the contents of a file in /proc/[pid]/[filename].
*
* @param filename the relative path to the file.
* @return the contents of the file.
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public String read(String filename) throws IOException {
return ProcFile.readFile(String.format("/proc/%d/%s", pid, filename));
}
/**
* <p>/proc/[pid]/attr/current (since Linux 2.6.0)</p>
* <p/>
* <p>The contents of this file represent the current security attributes of the process.</p>
* <p/>
* <p>In SELinux, this file is used to get the security context of a process. Prior to Linux
* 2.6.11, this file could not be used to set the security context (a write was always denied),
* since SELinux limited process security transitions to execve(2) (see the description of
* /proc/[pid]/attr/exec, below). ince Linux 2.6.11, SELinux lifted this restriction and began
* supporting "set" operations via writes to this node if authorized by policy, although use of
* this operation is only suitable for applications that are trusted to maintain any desired
* separation between the old and new security contexts. Prior to Linux 2.6.28, SELinux did not
* allow threads within a multi- threaded process to set their security context via this node as
* it would yield an inconsistency among the security contexts of the threads sharing the same
* memory space. Since Linux 2.6.28, SELinux lifted this restriction and began supporting "set"
* operations for threads within a multithreaded process if the new security context is bounded
* by the old security context, where the bounded relation is defined in policy and guarantees
* that the new security context has a subset of the permissions of the old security context.
* Other security modules may choose to support "set" operations via writes to this node.</p>
*
* @return the contents of /proc/[pid]/attr/current
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public String attr_current() throws IOException {
return read("attr/current");
}
/**
* <p>/proc/[pid]/cmdline</p>
* <p/>
* <p>This read-only file holds the complete command line for the process, unless the process is
* a zombie. In the latter case, there is nothing in this file: that is, a read on this file will
* return 0 characters. The command-line arguments appear in this file as a set of strings
* separated by null bytes ('\0'), with a further null byte after the last string.</p>
*
* @return the name of the process. (note: process name may be empty. In case it is empty get
* the process name from /proc/[pid]/stat).
* @throws IOException if the file does not exist or we don't have read permissions.
* @see #name
*/
public String cmdline() throws IOException {
return read("cmdline");
}
/**
* <p>/proc/[pid]/cgroup (since Linux 2.6.24)</p>
* <p/>
* <p>This file describes control groups to which the process/task belongs. For each cgroup
* hierarchy there is one entry containing colon-separated fields of the form:</p>
* <p/>
* <p>5:cpuacct,cpu,cpuset:/daemons</p>
* <p/>
* <p>The colon-separated fields are, from left to right:</p>
* <p/>
* <ol>
* <li>hierarchy ID number</li>
* <li>set of subsystems bound to the hierarchy</li>
* <li>control group in the hierarchy to which the process belongs</li>
* </ol>
* <p/>
* <p>This file is present only if the CONFIG_CGROUPS kernel configuration option is enabled.</p>
*
* @return the {@link Cgroup} for this process
* @throws IOException
*/
public Cgroup cgroup() throws IOException {
return Cgroup.get(pid);
}
/**
* <p>/proc/[pid]/oom_score (since Linux 2.6.11)</p>
* <p/>
* <p>This file displays the current score that the kernel gives to this process for the
* purpose of selecting a process for the OOM-killer. A higher score means that the
* process is more likely to be selected by the OOM-killer.</p>
* <p/>
* <p>The basis for this score is the amount of memory used by the process, with
* increases (+) or decreases (-) for factors including:</p>
* <p/>
* <ul>
* <li>whether the process creates a lot of children using fork(2)(+);</li>
* <li>whether the process has been running a long time, or has used a lot of CPU time (-);</li>
* <li>whether the process has a low nice value (i.e., > 0) (+);</li>
* <li>whether the process is privileged (-); and</li>
* <li>whether the process is making direct hardware access (-).</li>
* </ul>
* <p/>
* <p>The oom_score also reflects the adjustment specified by the oom_score_adj
* or oom_adj setting for the process.</p>
*
* @return the oom_score value for this process
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public int oom_score() throws IOException {
return Integer.parseInt(read("oom_score"));
}
/**
* <p>/proc/[pid]/oom_adj (since Linux 2.6.11)</p>
* <p/>
* <p>This file can be used to adjust the score used to select which process should be killed in
* an out-of-memory (OOM) situation. The kernel uses this value for a bit-shift operation of the
* process's oom_score value: valid values are in the* range -16 to +15, plus the special value
* -17, which disables OOM-killing altogether for this process. A positive score increases the
* likelihood of this process being killed by the OOM-killer; a negative score decreases the
* likelihood.</p>
* <p/>
* <p>The default value for this file is 0; a new process inherits its parent's oom_adj setting.
* A process must be privileged (CAP_SYS_RESOURCE) to update this file.</p>
* <p/>
* <p>Since Linux 2.6.36, use of this file is deprecated in favor of
* /proc/[pid]/oom_score_adj.</p>
*
* @return the oom_adj value for this process
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public int oom_adj() throws IOException {
return Integer.parseInt(read("oom_adj"));
}
/**
* <p>/proc/[pid]/oom_score_adj (since Linux 2.6.36)</p>
* <p/>
* <p>This file can be used to adjust the badness heuristic used to select which process gets
* killed in out-of-memory conditions.</p>
* <p/>
* <p>The badness heuristic assigns a value to each candidate task ranging from 0 (never kill) to
* 1000 (always kill) to determine which process is targeted. The units are roughly a proportion
* along that range of allowed memory the process may allocate from, based on an estimation of
* its current memory and swap use. For example, if a task is using all allowed memory, its
* badness score will be 1000. If it is using half of its allowed memory, its score will be
* 500.</p>
* <p/>
* <p>There is an additional factor included in the badness score: root processes are given 3%
* extra memory over other tasks.</p>
* <p/>
* <p>The amount of "allowed" memory depends on the context in which the OOM-killer was called.
* If it is due to the memory assigned to the allocating task's cpuset being exhausted, the
* allowed memory represents the set of mems assigned to that cpuset (see cpuset(7)). If it is
* due to a mempolicy's node(s) being exhausted, the allowed memory represents the set of
* mempolicy nodes. If it is due to a memory limit (or swap limit) being reached, the allowed
* memory is that configured limit. Finally, if it is due to the entire system being out of
* memory, the allowed memory represents all allocatable resources.</p>
* <p/>
* <p>The value of oom_score_adj is added to the badness score before it is used to determine
* which task to kill. Acceptable values range from -1000 (OOM_SCORE_ADJ_MIN) to +1000
* (OOM_SCORE_ADJ_MAX). This allows user space to control the preference for OOM-killing, ranging
* from always preferring a certain task or completely disabling it from OOM killing. The lowest
* possible value, -1000, is equivalent to disabling OOM- killing entirely for that task, since
* it will always report a badness score of 0.</p>
* <p/>
* <p>Consequently, it is very simple for user space to define the amount of memory to consider
* for each task. Setting a oom_score_adj value of +500, for example, is roughly equivalent to
* allowing the remainder of tasks sharing the same system, cpuset, mempolicy, or memory
* controller resources to use at least 50% more memory. A value of -500, on the other hand,
* would be roughly equivalent to discounting 50% of the task's allowed memory from being
* considered as scoring against the task.</p>
* <p/>
* <p>For backward compatibility with previous kernels, /proc/[pid]/oom_adj can still be used to
* tune the badness score. Its value is scaled linearly with oom_score_adj.</p>
* <p/>
* <p>Writing to /proc/[pid]/oom_score_adj or /proc/[pid]/oom_adj will change the other with its
* scaled value.</p>
*
* @return the oom_score_adj value for this process
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public int oom_score_adj() throws IOException {
return Integer.parseInt(read("oom_score_adj"));
}
/**
* <p>/proc/[pid]/stat</p>
* <p/>
* <p>Status information about the process. This is used by ps(1). It is defined in the kernel
* source file fs/proc/array.c.</p>
* <p/>
* <p>The fields, in order, with their proper scanf(3) format specifiers, are:</p>
* <p/>
* <ol>
* <p/>
* <li>pid %d The process ID.</li>
* <p/>
* <li>comm %s The filename of the executable, in parentheses. This is visible whether or not
* the executable is swapped out.</li>
* <p/>
* <li>state %c One of the following characters, indicating process state:
* <ul>
* <li>R Running</li>
* <li>S Sleeping in an interruptible wait</li>
* <li>D Waiting in uninterruptible disk sleep</li>
* <li>Z Zombie</li>
* <li>T Stopped (on a signal) or (before Linux 2.6.33) trace stopped</li>
* <li>t Tracing stop (Linux 2.6.33 onward)</li>
* <li>W Paging (only before Linux 2.6.0)</li>
* <li>X Dead (from Linux 2.6.0 onward)</li>
* <li>x Dead (Linux 2.6.33 to 3.13 only)</li>
* <li>K Wakekill (Linux 2.6.33 to 3.13 only)</li>
* <li>W Waking (Linux 2.6.33 to 3.13 only)</li>
* <li>P Parked (Linux 3.9 to 3.13 only)</li>
* </ul>
* </li>
* <p/>
* <li>ppid %d The PID of the parent of this process.</li>
* <p/>
* <li>pgrp %d The process group ID of the process.</li>
* <p/>
* <li>session %d The session ID of the process.</li>
* <p/>
* <li>tty_nr %d The controlling terminal of the process. (The minor device number is contained
* in the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 to 8.)
* </li>
* <p/>
* <li>tpgid %d The ID of the foreground process group of the controlling terminal of the
* process.</li>
* <p/>
* <li>flags %u The kernel flags word of the process. For bit meanings, see the PF_* defines in
* the Linux kernel source file include/linux/sched.h. Details depend on the kernel version.
* The format for this field was %lu before Linux 2.6.</li>
* <p/>
* <li>minflt %lu The number of minor faults the process has made which have not required
* loading a memory page from disk.</li>
* <p/>
* <li>cminflt %lu The number of minor faults that the process's waited-for children have
* made</li>
* <p/>
* <li>majflt %lu The number of major faults the process has made which have required loading a
* memory page from disk.</li>
* <p/>
* <li>cmajflt %lu The number of major faults that the process's waited-for children have
* made</li>
* <p/>
* <li>utime %lu Amount of time that this process has been scheduled in user mode, measured in
* clock ticks (divide by sysconf(_SC_CLK_TCK)). This includes guest time, guest_time (time
* spent running a virtual CPU, see below), so that applications that are not aware of the guest
* time field do not lose that time from their calculations.</li>
* <p/>
* <li>stime %lu Amount of time that this process has been scheduled in kernel mode, measured
* in clock ticks (divide by sysconf(_SC_CLK_TCK)).</li>
* <p/>
* <li>cutime %ld Amount of time that this process's waited-for children have been scheduled in
* user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)). (See also times(2).)
* This includes guest time, cguest_time (time spent running a virtual CPU, see below).</li>
* <p/>
* <li>cstime %ld Amount of time that this process's waited-for children have been scheduled in
* kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).</li>
* <p/>
* <li>priority %ld (Explanation for Linux 2.6) For processes running a real-time scheduling
* policy (policy below; see sched_setscheduler(2)), this is the negated scheduling priority,
* minus one; that is, a number in the range -2 to -100, corresponding to real-time priorities 1
* to 99. For processes running under a non-real-time scheduling policy, this is the raw nice
* value (setpriority(2)) as represented in the kernel. The kernel stores nice values as numbers
* in the range 0 (high) to 39 (low), corresponding to the user-visible nice range of -20 to 19.
* Before Linux 2.6, this was a scaled value based on the scheduler weighting given to this
* process</li>
* <p/>
* <li>nice %ld The nice value (see setpriority(2)), a value in the range 19 (low priority) to
* -20 (high priority).</li>
* <p/>
* <li>num_threads %ld Number of threads in this process (since Linux 2.6). Before kernel 2.6,
* this field was hard coded to 0 as a placeholder for an earlier removed field.</li>
* <p/>
* <li>itrealvalue %ld The time in jiffies before the next SIGALRM is sent to the process due
* to an interval timer. Since kernel 2.6.17, this field is no longer maintained, and is hard
* coded as 0.</li>
* <p/>
* <li>starttime %llu The time the process started after system boot. In kernels before Linux
* 2.6, this value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock
* ticks (divide by sysconf(_SC_CLK_TCK)).</li>
* <p/>
* <li>The format for this field was %lu before Linux 2.6. (23) vsize %lu Virtual memory size
* in bytes.</li>
* <p/>
* <li>rss %ld Resident Set Size: number of pages the process has in real memory. This is just
* the pages which count toward text, data, or stack space. This does not include pages which
* have not been demand-loaded in, or which are swapped out.</li>
* <p/>
* <li>rsslim %lu Current soft limit in bytes on the rss of the process; see the description of
* RLIMIT_RSS in getrlimit(2).</li>
* <p/>
* <li>startcode %lu The address above which program text can run.</li>
* <p/>
* <li>endcode %lu The address below which program text can run.</li>
* <p/>
* <li>startstack %lu The address of the start (i.e., bottom) of the stack.</li>
* <p/>
* <li>kstkesp %lu The current value of ESP (stack pointer), as found in the kernel stack page
* for the process.</li>
* <p/>
* <li>kstkeip %lu The current EIP (instruction pointer).</li>
* <p/>
* <li>signal %lu The bitmap of pending signals, displayed as a decimal number. Obsolete,
* because it does not provide information on real-time signals; use /proc/[pid]/status
* instead</li>
* <p/>
* <li>blocked %lu The bitmap of blocked signals, displayed as a decimal number. Obsolete,
* because it does not provide information on real-time signals; use /proc/[pid]/status
* instead</li>
* <p/>
* <li>sigignore %lu The bitmap of ignored signals, displayed as a decimal number. Obsolete,
* because it does not provide information on real-time signals; use /proc/[pid]/status
* instead</li>
* <p/>
* <li>sigcatch %lu The bitmap of caught signals, displayed as a decimal number. Obsolete,
* because it does not provide information on real-time signals; use /proc/[pid]/status
* instead.</li>
* <p/>
* <li>wchan %lu This is the "channel" in which the process is waiting. It is the address of a
* location in the kernel where the process is sleeping. The corresponding symbolic name can be
* found in /proc/[pid]/wchan.</li>
* <p/>
* <li>nswap %lu Number of pages swapped (not maintained).</li>
* <p/>
* <li>cnswap %lu Cumulative nswap for child processes (not maintained).</li>
* <p/>
* <li>exit_signal %d (since Linux 2.1.22) Signal to be sent to parent when we die.</li>
* <p/>
* <li>processor %d (since Linux 2.2.8) CPU number last executed on.</li>
* <p/>
* <li>rt_priority %u (since Linux 2.5.19) Real-time scheduling priority, a number in the
* range 1 to 99 for processes scheduled under a real-time policy, or 0, for non-real-time
* processes (see sched_setscheduler(2)).</li>
* <p/>
* <li>policy %u (since Linux 2.5.19) Scheduling policy (see sched_setscheduler(2)). Decode
* using the SCHED_* constants in linux/sched.h. The format for this field was %lu before Linux
* 2.6.22.</li>
* <p/>
* <li>delayacct_blkio_ticks %llu (since Linux 2.6.18) Aggregated block I/O delays, measured
* in clock ticks (centiseconds).</li>
* <p/>
* <li>guest_time %lu (since Linux 2.6.24) Guest time of the process (time spent running a
* virtual CPU for a guest operating system), measured in clock ticks (divide by
* sysconf(_SC_CLK_TCK)).</li>
* <p/>
* <li>cguest_time %ld (since Linux 2.6.24) Guest time of the process's children, measured in
* clock ticks (divide by sysconf(_SC_CLK_TCK)).</li>
* <p/>
* <li>start_data %lu (since Linux 3.3) Address above which program initialized and
* uninitialized (BSS) data are placed.</li>
* <p/>
* <li>end_data %lu (since Linux 3.3) Address below which program initialized and
* uninitialized (BSS) data are placed.</li>
* <p/>
* <li>start_brk %lu (since Linux 3.3) Address above which program heap can be expanded with
* brk(2).</li>
* <p/>
* <li>arg_start %lu (since Linux 3.5) Address above which program command-line arguments
* (argv) are placed.</li>
* <p/>
* <li>arg_end %lu (since Linux 3.5) Address below program command-line arguments (argv) are
* placed.</li>
* <p/>
* <li>env_start %lu (since Linux 3.5) Address above which program environment is placed.</li>
* <p/>
* <li>env_end %lu (since Linux 3.5) Address below which program environment is placed.</li>
* <p/>
* <li>exit_code %d (since Linux 3.5) The thread's exit status in the form reported by
* waitpid(2).</li>
* <p/>
* </ol>
*
* @return the {@link Stat} for this process
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public Stat stat() throws IOException {
return Stat.get(pid);
}
/**
* <p>Provides information about memory usage, measured in pages.</p>
* <p/>
* <p>The columns are:</p>
* <p/>
* <ul>
* <li>size (1) total program size (same as VmSize in /proc/[pid]/status)</li>
* <li>resident (2) resident set size (same as VmRSS in /proc/[pid]/status)</li>
* <li>share (3) shared pages (i.e., backed by a file)</li>
* <li>text (4) text (code)</li>
* <li>lib (5) library (unused in Linux 2.6)</li>
* <li>data (6) data + stack</li>
* <li>dt (7) dirty pages (unused in Linux 2.6)</li>
* </ul>
*
* @return the {@link Statm} for this process
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public Statm statm() throws IOException {
return Statm.get(pid);
}
/**
* <p>/proc/[pid]/status</p>
* <p/>
* <p>Provides much of the information in /proc/[pid]/stat and /proc/[pid]/statm in a format
* that's
* easier for humans to parse.</p>
* <p/>
* <p>Here's an example:</p>
* <p/>
* <pre>
* $ cat /proc/$$/status
* Name: bash
* State: S (sleeping)
* Tgid: 3515
* Pid: 3515
* PPid: 3452
* TracerPid: 0
* Uid: 1000 1000 1000 1000
* Gid: 100 100 100 100
* FDSize: 256
* Groups: 16 33 100
* VmPeak: 9136 kB
* VmSize: 7896 kB
* VmLck: 0 kB
* VmPin: 0 kB
* VmHWM: 7572 kB
* VmRSS: 6316 kB
* VmData: 5224 kB
* VmStk: 88 kB
* VmExe: 572 kB
* VmLib: 1708 kB
* VmPMD: 4 kB
* VmPTE: 20 kB
* VmSwap: 0 kB
* Threads: 1
* SigQ: 0/3067
* SigPnd: 0000000000000000
* ShdPnd: 0000000000000000
* SigBlk: 0000000000010000
* SigIgn: 0000000000384004
* SigCgt: 000000004b813efb
* CapInh: 0000000000000000
* CapPrm: 0000000000000000
* CapEff: 0000000000000000
* CapBnd: ffffffffffffffff
* Seccomp: 0
* Cpus_allowed: 00000001
* Cpus_allowed_list: 0
* Mems_allowed: 1
* Mems_allowed_list: 0
* voluntary_ctxt_switches: 150
* nonvoluntary_ctxt_switches: 545
* </pre>
* <p/>
* <p>The fields are as follows:</p>
* <p/>
* <ol>
* <li>Name: Command run by this process.</li>
* <li>State: Current state of the process. One of "R (running)", "S (sleeping)", "D (disk
* sleep)",
* "T (stopped)", "T (tracing stop)", "Z (zombie)", or "X (dead)".</li>
* <li>Tgid: Thread group ID (i.e., Process ID).</li>
* <li>Pid: Thread ID (see gettid(2)).</li>
* <li>PPid: PID of parent process.</li>
* <li>TracerPid: PID of process tracing this process (0 if not being traced).</li>
* <li>Uid, Gid: Real, effective, saved set, and filesystem UIDs (GIDs).</li>
* <li>FDSize: Number of file descriptor slots currently allocated.</li>
* <li>Groups: Supplementary group list.</li>
* <li>VmPeak: Peak virtual memory size.</li>
* <li>VmSize: Virtual memory size.</li>
* <li>VmLck: Locked memory size (see mlock(3)).</li>
* <li>VmPin: Pinned memory size (since Linux 3.2). These are pages that can't be moved because
* something needs to directly access physical memory.</li>
* <li>VmHWM: Peak resident set size ("high water mark").</li>
* <li>VmRSS: Resident set size.</li>
* <li>VmData, VmStk, VmExe: Size of data, stack, and text segments.</li>
* <li>VmLib: Shared library code size.</li>
* <li>VmPTE: Page table entries size (since Linux 2.6.10).</li>
* <li>VmPMD: Size of second-level page tables (since Linux 4.0).</li>
* <li>VmSwap: Swapped-out virtual memory size by anonymous private pages; shmem swap usage is
* not
* included (since Linux 2.6.34).</li>
* <li>Threads: Number of threads in process containing this thread.</li>
* <li>SigQ: This field contains two slash-separated numbers that relate to queued signals for
* the
* real user ID of this process. The first of these is the number of currently queued signals
* for
* this real user ID, and the second is the resource limit on the number of queued signals for
* this
* process (see the description of RLIMIT_SIGPENDING in getrlimit(2)).</li>
* <li>SigPnd, ShdPnd: Number of signals pending for thread and for process as a whole (see
* pthreads(7) and signal(7)).</li>
* <li>SigBlk, SigIgn, SigCgt: Masks indicating signals being blocked, ignored, and caught (see
* signal(7)).</li>
* <li>CapInh, CapPrm, CapEff: Masks of capabilities enabled in inheritable, permitted, and
* effective sets (see capabilities(7)).</li>
* <li>CapBnd: Capability Bounding set (since Linux 2.6.26, see capabilities(7)).</li>
* <li>Seccomp: Seccomp mode of the process (since Linux 3.8, see seccomp(2)). 0 means
* SECCOMP_MODE_DISABLED; 1 means SECCOMP_MODE_STRICT; 2 means SECCOMP_MODE_FILTER. This field is
* provided only if the kernel was built with the CONFIG_SECCOMP kernel configuration option
* enabled.</li>
* <li>Cpus_allowed: Mask of CPUs on which this process may run (since Linux 2.6.24, see
* cpuset(7)).</li>
* <li>Cpus_allowed_list: Same as previous, but in "list format" (since Linux 2.6.26, see
* cpuset(7)).</li>
* <li>Mems_allowed: Mask of memory nodes allowed to this process (since Linux 2.6.24, see
* cpuset(7)).</li>
* <li>Mems_allowed_list: Same as previous, but in "list format" (since Linux 2.6.26, see
* cpuset(7)).
* voluntary_ctxt_switches, nonvoluntary_ctxt_switches: Number of voluntary and involuntary
* context
* switches (since Linux 2.6.23).</li>
* </ol>
*
* @return the {@link Status} for this process
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public Status status() throws IOException {
return Status.get(pid);
}
/**
* The symbolic name corresponding to the location in the kernel where the process is sleeping.
*
* @return the contents of /proc/[pid]/wchan
* @throws IOException if the file does not exist or we don't have read permissions.
*/
public String wchan() throws IOException {
return read("wchan");
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.pid);
}
}
| [
"kamgurgul@gmail.com"
] | kamgurgul@gmail.com |
99830cd36901cc361bad23cd2b7e1e9b4d063f72 | fbf929423d43743b6ca44eef37859a4954fa066b | /LinkedList/compareLinkedList.java | db210eb351c6903cebaa67ced99010a8eb32d3c3 | [] | no_license | Harshita27/TreasureCode | f95c5bdfc58fb3261962dde9ea87f798bf7015a2 | b89796392111d74b12678be0f1531eed8b5cf60e | refs/heads/master | 2016-08-12T21:40:49.584023 | 2016-03-05T01:30:01 | 2016-03-05T01:30:01 | 50,263,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,054 | java | /*
Compare two linked lists A and B
Return 1 if they are identical and 0 if they are not.
Node is defined as
class Node {
int data;
Node next;
}
*/
int CompareLists(Node headA, Node headB) {
// This is a "method-only" submission.
// You only need to complete this method
if((headA == null && headB != null) || (headA !=null && headB == null))
{
return 0;
}
Node nodeA= new Node();
nodeA= headA;
Node nodeB = new Node();
nodeB = headB;
int countA=0;
int countB =0;
while(nodeA !=null)
{
countA +=1;
nodeA = nodeA.next;
}
while(nodeB !=null)
{
countB +=1;
nodeB= nodeB.next;
}
if(countA != countB)
{
return 0;
}
else
{
nodeA = headA;
nodeB = headB;
while(nodeA != null && nodeB != null)
{
if(nodeA.data == nodeB.data)
{nodeA = nodeA.next;
nodeB = nodeB.next;}
else
return 0;
}}
return 1;
}
| [
"agrawal.h@husky.neu.edu"
] | agrawal.h@husky.neu.edu |
725444c55f117249df9dd52dc0cb0160ba0a9a90 | 3885701ff8eb6d47bcb7e34a810ba76f987a374f | /src/main/java/de/rwth/i9/palm/controller/ManageTopicModelingController.java | eacc42e4d20bcbe0eb263b397e58b50972a41cda | [] | no_license | Silvester23/palm-core | 158cc02cb6f76c838d0a087f8b7d9ee0a20f959b | c78a4388f00983b32c40e5fb4535a1e0a55bf8b3 | refs/heads/master | 2021-01-16T19:58:55.824313 | 2016-04-27T12:29:47 | 2016-04-27T12:29:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,497 | java | package de.rwth.i9.palm.controller;
import java.util.HashMap;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
//import de.rwth.i9.palm.analytics.algorithm.dynamicLDA.ParallelTopicModel;
import de.rwth.i9.palm.analytics.api.PalmAnalytics;
import de.rwth.i9.palm.persistence.PersistenceStrategy;
@Controller
@RequestMapping( value = "/topicmodeling" )
public class ManageTopicModelingController
{
@Autowired
private PersistenceStrategy persistenceStrategy;
@Autowired
private PalmAnalytics palmAnalytics;
@Transactional
@RequestMapping( method = RequestMethod.GET )
public @ResponseBody String allReindex()
{
// ParallelTopicModel ptm = palmAnalytics.getDynamicTopicModel().createModel( "C:\\Users\\nifry\\Desktop\\Years\\", "Years", 11, 10 );
//
// List<String> topics = palmAnalytics.getDynamicTopicModel().getListTopics( ptm, 10 );
// LinkedHashMap<String, List<Double>> distribution = palmAnalytics.getDynamicTopicModel().getTopicDistributionforDocuments( ptm, 0.0, 10, ptm.numTopics );
Map<String, Object> ldaObjectResults = new HashMap<>();
ldaObjectResults.put( "algorithm", "lda" );
ldaObjectResults.put( "termvalues", "lda" );
return "success";
}
}
| [
"sigit.nugraha@gesis.org"
] | sigit.nugraha@gesis.org |
b8aed0b903582f5eee250fe06e397d0dcefe48be | 8a6f7a73fcf9cba90f376af432d9d4f133ba0b93 | /app/src/main/java/com/e/driver/activities/ui/about/AboutFragment.java | 5ba432f9ab4e96b08493ea3bb1db05d9928554e4 | [] | no_license | nitinshkaya001/NitinJPR | 8c38aeeb91ce3bdac35ed55c806ffb9c154e8566 | fe973c84e190d9ada3f1c1ce8ff093933f74e77a | refs/heads/master | 2020-07-29T20:40:49.939544 | 2019-09-28T08:11:19 | 2019-09-28T08:11:19 | 209,952,043 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 571 | java | package com.e.driver.activities.ui.about;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.e.driver.R;
public class AboutFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_aboutus, container, false);
return root;
}
}
| [
"raj95288@gmail.com"
] | raj95288@gmail.com |
f904ad9456f63e4f4d118adae983fbcf0677036c | 112e91a133bedbee16d31ef6886691f83eb9ea96 | /src/main/java/com/warehouse/pro/po/good/OutDepodExampleCustom.java | f961b4650b874ce054db2e330a0d8516391f087d | [] | no_license | 2977621972/Spring | af6ad2e97299d7352ede699b7d6a90d9047d6948 | 5bbc4320bdd3ae101edadab3586d4dfcb2e1ffe1 | refs/heads/master | 2020-03-22T08:06:21.519816 | 2018-07-04T16:43:08 | 2018-07-04T16:43:08 | 139,694,547 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 429 | java | package com.warehouse.pro.po.good;
public class OutDepodExampleCustom extends OutDepodExample {
private Integer beginRow;
private Integer pageSize;
public Integer getBeginRow() {
return beginRow;
}
public void setBeginRow(Integer beginRow) {
this.beginRow = beginRow;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
} | [
"2977621972@qq.com"
] | 2977621972@qq.com |
44e9177000934a9879d8f77f8eab18266dda294c | caa294ed781762ea51eae4363ef965e5bef9429f | /src/main/java/com/lee/mybatisplus/generator/core/parser/ISqlParser.java | 42bcbc8469db0b4d8a74db86f20a7b8bf5dc8a6b | [] | no_license | l848168/mybatis-generator | e854d877b9cb552aff87d6de284af09141954298 | fecb19f476685208c0f797fd8a226c739c99c26a | refs/heads/master | 2022-12-26T07:05:10.908962 | 2019-09-10T09:27:10 | 2019-09-10T09:27:10 | 207,206,709 | 0 | 0 | null | 2022-12-15T23:49:36 | 2019-09-09T02:23:20 | Java | UTF-8 | Java | false | false | 1,394 | java | /*
* Copyright (c) 2011-2020, baomidou (jobob@qq.com).
* <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>
* https://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.lee.mybatisplus.generator.core.parser;
import org.apache.ibatis.reflection.MetaObject;
/**
* SQL 解析接口
*
* @author hubin
* @since 2017-09-01
*/
public interface ISqlParser {
/**
* 解析 SQL 方法
*
* @param metaObject 元对象
* @param sql SQL 语句
* @return SQL 信息
*/
SqlInfo parser(MetaObject metaObject, String sql);
/**
* <p>
* 是否执行 SQL 解析 parser 方法
* </p>
*
* @param metaObject 元对象
* @param sql SQL 语句
* @return SQL 信息
*/
default boolean doFilter(final MetaObject metaObject, final String sql) {
// 默认 true 执行 SQL 解析, 可重写实现控制逻辑
return true;
}
}
| [
"you@example.com"
] | you@example.com |
67ee8061e036219e490fe08133a303724ee99645 | fdd4f25c59dcab1bb2a2d03bb6662918b0bb0063 | /app/src/main/java/com/lin/clay/emojikeyboard/utils/widget/NoHorizontalScrollerViewPager.java | 3df49868e4520d5e2825429f99c7bd930b69c6c3 | [
"Apache-2.0"
] | permissive | ClayLinW/EmojiKeyboard | b68b5be9ed2c36b392ec4d591cc13ed703349284 | 75613136ea1d72f5202550dc8e2667cede027d3d | refs/heads/master | 2020-04-22T11:42:36.220951 | 2019-02-20T16:03:47 | 2019-02-20T16:03:47 | 170,350,221 | 30 | 1 | null | null | null | null | UTF-8 | Java | false | false | 937 | java | package com.lin.clay.emojikeyboard.utils.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;
public class NoHorizontalScrollerViewPager extends ViewPager
{
public NoHorizontalScrollerViewPager(Context context) {
super(context);
}
public NoHorizontalScrollerViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 重写拦截事件,返回值设置为false,这时便不会横向滑动了。
* @param ev
* @return
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return false;
}
/**
* 重写拦截事件,返回值设置为false,这时便不会横向滑动了。
* @param ev
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
return false;
}
}
| [
"1225394906@qq.com"
] | 1225394906@qq.com |
089eebce36131f8538d566822888c177f9ad0eb2 | c610f659f8bc54f2fbd89d5016d902bff8ff9cdf | /src/main/groovy/org/codenarc/idea/inspections/generic/IllegalPackageReferenceInspectionTool.java | 8ad84914b0edd7d805e707d09d6799d4d65b4c20 | [] | no_license | sbglasius/codenarc-idea | 37461218d27249bbdecee4e8932a31db319ed524 | badc7a4bbc11aec913c7d6ce0b0360ea523e1fc5 | refs/heads/master | 2023-04-05T19:10:28.987198 | 2021-04-11T09:19:45 | 2021-04-11T09:19:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,891 | java | package org.codenarc.idea.inspections.generic;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.psi.PsiElement;
import java.util.Collection;
import java.util.Collections;
import javax.annotation.Generated;
import org.codenarc.idea.CodeNarcInspectionTool;
import org.codenarc.rule.Violation;
import org.codenarc.rule.generic.IllegalPackageReferenceRule;
import org.jetbrains.annotations.NotNull;
@Generated("You can customize this class at the end of the file or remove this annotation to skip regeneration completely")
public class IllegalPackageReferenceInspectionTool extends CodeNarcInspectionTool<IllegalPackageReferenceRule> {
// this code has been generated from org.codenarc.rule.generic.IllegalPackageReferenceRule
public static final String GROUP = "Generic";
public IllegalPackageReferenceInspectionTool() {
super(new IllegalPackageReferenceRule());
}
@Override
public String getRuleset() {
return GROUP;
}
public void setApplyToClassNames(String value) {
getRule().setApplyToClassNames(value);
}
public String getApplyToClassNames() {
return getRule().getApplyToClassNames();
}
public void setDoNotApplyToClassNames(String value) {
getRule().setDoNotApplyToClassNames(value);
}
public String getDoNotApplyToClassNames() {
return getRule().getDoNotApplyToClassNames();
}
public void setPackageNames(String value) {
getRule().setPackageNames(value);
}
public String getPackageNames() {
return getRule().getPackageNames();
}
// custom code can be written after this line and it will be preserved during the regeneration
@Override
protected @NotNull Collection<LocalQuickFix> getQuickFixesFor(Violation violation, PsiElement violatingElement) {
return Collections.emptyList();
}
}
| [
"vladimir@orany.cz"
] | vladimir@orany.cz |
9f1a22a285ba1638a5c929f2178bd68a3fe6b9dc | 205b4b0bd197fb45d3ef631e4e47593bcdf33fe3 | /src/main/java/com/gupao/baiyu/redis/ShardedJedisSentinelPool.java | 0e84edd401e417b06599bc6f69fca6c9919bd969 | [] | no_license | lihm659156/github_baiyu | e800fc775e6cfa5604683bd08e1883d714c41124 | bcd8f8c0448b06e4a67e0958a3279819ab6bd79c | refs/heads/master | 2021-04-09T14:25:18.728318 | 2018-04-11T02:15:21 | 2018-04-11T02:15:21 | 125,604,646 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,882 | java | package com.gupao.baiyu.redis;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.util.Hashing;
import redis.clients.util.Pool;
public class ShardedJedisSentinelPool extends Pool<ShardedJedis> {
public static final int MAX_RETRY_SENTINEL = 10;
protected final Logger log = Logger.getLogger(getClass().getName());
protected GenericObjectPoolConfig poolConfig;
protected int timeout = Protocol.DEFAULT_TIMEOUT;
private int sentinelRetry = 0;
protected String password;
protected int database = Protocol.DEFAULT_DATABASE;
protected Set<MasterListener> masterListeners = new HashSet<MasterListener>();
private volatile List<HostAndPort> currentHostMasters;
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels) {
this(masters, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels, String password) {
this(masters, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, password);
}
public ShardedJedisSentinelPool(final GenericObjectPoolConfig poolConfig, List<String> masters, Set<String> sentinels) {
this(masters, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout,
final String password) {
this(masters, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masters, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final String password) {
this(masters, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password);
}
public ShardedJedisSentinelPool(List<String> masters, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout,
final String password, final int database) {
this.poolConfig = poolConfig;
this.timeout = timeout;
this.password = password;
this.database = database;
List<HostAndPort> masterList = initSentinels(sentinels, masters);
initPool(masterList);
}
public void destroy() {
for (MasterListener m : masterListeners) {
m.shutdown();
}
super.destroy();
}
public List<HostAndPort> getCurrentHostMaster() {
return currentHostMasters;
}
private void initPool(List<HostAndPort> masters) {
if (!equals(currentHostMasters, masters)) {
StringBuffer sb = new StringBuffer();
for (HostAndPort master : masters) {
sb.append(master.toString());
sb.append(" ");
}
log.info("Created ShardedJedisPool to master at [" + sb.toString() + "]");
List<JedisShardInfo> shardMasters = makeShardInfoList(masters);
initPool(poolConfig, new ShardedJedisFactory(shardMasters, Hashing.MURMUR_HASH, null));
currentHostMasters = masters;
}
}
private boolean equals(List<HostAndPort> currentShardMasters, List<HostAndPort> shardMasters) {
if (currentShardMasters != null && shardMasters != null) {
if (currentShardMasters.size() == shardMasters.size()) {
for (int i = 0; i < currentShardMasters.size(); i++) {
if (!currentShardMasters.get(i).equals(shardMasters.get(i))) return false;
}
return true;
}
}
return false;
}
private List<JedisShardInfo> makeShardInfoList(List<HostAndPort> masters) {
List<JedisShardInfo> shardMasters = new ArrayList<JedisShardInfo>();
for (HostAndPort master : masters) {
JedisShardInfo jedisShardInfo = new JedisShardInfo(master.getHost(), master.getPort(), timeout);
jedisShardInfo.setPassword(password);
shardMasters.add(jedisShardInfo);
}
return shardMasters;
}
private List<HostAndPort> initSentinels(Set<String> sentinels, final List<String> masters) {
Map<String, HostAndPort> masterMap = new HashMap<String, HostAndPort>();
List<HostAndPort> shardMasters = new ArrayList<HostAndPort>();
log.info("Trying to find all master from available Sentinels...");
for (String masterName : masters) {
HostAndPort master = null;
boolean fetched = false;
while (!fetched && sentinelRetry < MAX_RETRY_SENTINEL) {
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
log.fine("Connecting to Sentinel " + hap);
try {
Jedis jedis = new Jedis(hap.getHost(), hap.getPort());
master = masterMap.get(masterName);
if (master == null) {
List<String> hostAndPort = jedis.sentinelGetMasterAddrByName(masterName);
if (hostAndPort != null && hostAndPort.size() > 0) {
master = toHostAndPort(hostAndPort);
log.fine("Found Redis master at " + master);
shardMasters.add(master);
masterMap.put(masterName, master);
fetched = true;
jedis.disconnect();
break;
}
}
} catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap + ". Trying next one.");
}
}
if (null == master) {
try {
log.severe("All sentinels down, cannot determine where is "
+ masterName + " master is running... sleeping 1000ms, Will try again.");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
fetched = false;
sentinelRetry++;
}
}
// Try MAX_RETRY_SENTINEL times.
if (!fetched && sentinelRetry >= MAX_RETRY_SENTINEL) {
log.severe("All sentinels down and try " + MAX_RETRY_SENTINEL + " times, Abort.");
throw new JedisConnectionException("Cannot connect all sentinels, Abort.");
}
}
// All shards master must been accessed.
if (masters.size() != 0 && masters.size() == shardMasters.size()) {
log.info("Starting Sentinel listeners...");
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel.split(":")));
MasterListener masterListener = new MasterListener(masters, hap.getHost(), hap.getPort());
masterListeners.add(masterListener);
masterListener.start();
}
}
return shardMasters;
}
private HostAndPort toHostAndPort(List<String> getMasterAddrByNameResult) {
String host = getMasterAddrByNameResult.get(0);
int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
return new HostAndPort(host, port);
}
/**
* PoolableObjectFactory custom impl.
*/
protected static class ShardedJedisFactory implements PooledObjectFactory<ShardedJedis> {
private List<JedisShardInfo> shards;
private Hashing algo;
private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
this.shards = shards;
this.algo = algo;
this.keyTagPattern = keyTagPattern;
}
public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<ShardedJedis>(jedis);
}
public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) throws Exception {
final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
for (Jedis jedis : shardedJedis.getAllShards()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
public boolean validateObject(PooledObject<ShardedJedis> pooledShardedJedis) {
try {
ShardedJedis jedis = pooledShardedJedis.getObject();
for (Jedis shard : jedis.getAllShards()) {
if (!shard.ping().equals("PONG")) {
return false;
}
}
return true;
} catch (Exception ex) {
return false;
}
}
public void activateObject(PooledObject<ShardedJedis> p) throws Exception {
}
public void passivateObject(PooledObject<ShardedJedis> p) throws Exception {
}
}
protected class JedisPubSubAdapter extends JedisPubSub {
@Override
public void onMessage(String channel, String message) {
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
}
protected class MasterListener extends Thread {
protected List<String> masters;
protected String host;
protected int port;
protected long subscribeRetryWaitTimeMillis = 5000;
protected Jedis jedis;
protected AtomicBoolean running = new AtomicBoolean(false);
protected MasterListener() {
}
public MasterListener(List<String> masters, String host, int port) {
this.masters = masters;
this.host = host;
this.port = port;
}
public MasterListener(List<String> masters, String host, int port,
long subscribeRetryWaitTimeMillis) {
this(masters, host, port);
this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
}
public void run() {
running.set(true);
while (running.get()) {
jedis = new Jedis(host, port);
try {
jedis.subscribe(new JedisPubSubAdapter() {
@Override
public void onMessage(String channel, String message) {
log.fine("Sentinel " + host + ":" + port + " published: " + message + ".");
String[] switchMasterMsg = message.split(" ");
if (switchMasterMsg.length > 3) {
int index = masters.indexOf(switchMasterMsg[0]);
if (index >= 0) {
HostAndPort newHostMaster = toHostAndPort(Arrays.asList(switchMasterMsg[3], switchMasterMsg[4]));
List<HostAndPort> newHostMasters = new ArrayList<HostAndPort>();
for (int i = 0; i < masters.size(); i++) {
newHostMasters.add(null);
}
Collections.copy(newHostMasters, currentHostMasters);
newHostMasters.set(index, newHostMaster);
initPool(newHostMasters);
} else {
StringBuffer sb = new StringBuffer();
for (String masterName : masters) {
sb.append(masterName);
sb.append(",");
}
log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0]
+ ", our monitor master name are ["
+ sb + "]");
}
} else {
log.severe("Invalid message received on Sentinel "
+ host
+ ":"
+ port
+ " on channel +switch-master: "
+ message);
}
}
}, "+switch-master");
} catch (JedisConnectionException e) {
if (running.get()) {
log.severe("Lost connection to Sentinel at " + host
+ ":" + port
+ ". Sleeping 5000ms and retrying.");
try {
Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
log.fine("Unsubscribing from Sentinel at " + host + ":"
+ port);
}
}
}
}
public void shutdown() {
try {
log.fine("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
jedis.disconnect();
} catch (Exception e) {
log.severe("Caught exception while shutting down: " + e.getMessage());
}
}
}
}
| [
"865622375@qq.com"
] | 865622375@qq.com |
b5d67ab8cbb1aa1aabbf39b5a1b768a7fe00e14b | 2610e3bccddf5a695cf58adc28f56e1858b94c3c | /microservice-loverent-webank-v1/src/main/java/org/gz/webank/service/WebankApiTicketService.java | 317d6c488be7c1b2c3862f71c6243f8cbe6b0da8 | [] | no_license | song121382/aizuji | 812958c3020e37c052d913cfdd3807b1a55b2115 | 5ec44cf60945d6ff017434d5f321c0bcf3f111f1 | refs/heads/master | 2020-04-08T07:34:00.885177 | 2018-07-17T08:37:26 | 2018-07-17T08:37:26 | 159,143,253 | 1 | 4 | null | null | null | null | UTF-8 | Java | false | false | 10,387 | java | package org.gz.webank.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.gz.cache.service.webank.WebankDataCacheService;
import org.gz.common.http.HttpUtils;
import org.gz.common.resp.ResponseResult;
import org.gz.common.resp.ResponseStatus;
import org.gz.common.utils.HttpClientUtil;
import org.gz.common.utils.ResultUtil;
import org.gz.common.utils.StringUtils;
import org.gz.webank.common.ConfigureConst;
import org.gz.webank.configure.WebankConfigure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.hash.Hashing;
/**
* api ticket
*
* @author yangdx
*/
@Service
@Slf4j
public class WebankApiTicketService {
private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
@Autowired
private WebankConfigure webankConfigure;
@Autowired
private WebankAccessTokenService accessTokenService;
@Autowired
private WebankDataCacheService webankDataCacheService;
private static final String GET_H5_FACEID_URL = "https://idasc.webank.com/api/server/h5/geth5faceid";
public ResponseResult<JSONObject> signData(Long userId) {
ResponseResult<JSONObject> result = new ResponseResult<>();
try {
String orderNo = buildOrderNo();
String nonceTicket = requestNonceTicket(userId);
String appId = webankConfigure.getAppId();
String version = ConfigureConst.VERSION;
String nonce = buildNonceStr();
List<String> eles = new ArrayList<>();
eles.add(userId.toString());
eles.add(nonceTicket);
// eles.add(orderNo);
eles.add(appId);
eles.add(version);
eles.add(nonce);
String sign = sign(eles);
JSONObject data = new JSONObject();
data.put("orderNo", orderNo);
data.put("openApiUserId", userId.toString());
data.put("openApiSign", sign);
data.put("openApiNonce", nonce);
data.put("openApiAppVersion", version);
data.put("openApiAppId", appId);
data.put("tiket", nonceTicket);
log.info("get signData success, data: {}", JSONObject.toJSONString(data));
result.setData(data);
} catch (Exception e) {
ResultUtil.buildResultWithResponseStatus(result, ResponseStatus.UNKNOW_SYSTEM_ERROR);
}
return result;
}
/**
* 获取nonce ticket
*/
public String requestNonceTicket(Long userId) {
String accessToken = webankDataCacheService.getAccessToken();
if (StringUtils.isEmpty(accessToken)) {
accessTokenService.requestTokenAndCache();
accessToken = webankDataCacheService.getAccessToken();
}
String resp = HttpUtils.httpGetCall(ConfigureConst.TICKET_URL, buildNonceTicketRequestParams(accessToken, userId));
log.info("WebankApiTicketService.requestNonceTicket() --> nonce ticket resp: {}", resp);
if (!StringUtils.isEmpty(resp)) {
JSONObject data = JSONObject.parseObject(resp);
String code = data.getString("code");
if (ConfigureConst.SUCCESS_CODE.equals(code)) {
JSONArray tickets = data.getJSONArray("tickets");
if (tickets != null && tickets.size() > 0) {
return tickets.getJSONObject(0).getString("value");
}
}
}
return null;
}
/**
* 获取sign ticket
*/
public String requestSignTicket() {
String accessToken = webankDataCacheService.getAccessToken();
if (StringUtils.isEmpty(accessToken)) {
accessTokenService.requestTokenAndCache();
accessToken = webankDataCacheService.getAccessToken();
}
String resp = HttpUtils.httpGetCall(ConfigureConst.TICKET_URL, buildSignTicketRequestParams(accessToken));
log.info("WebankApiTicketService.requestSignTicket() --> sign ticket resp: {}", resp);
if (!StringUtils.isEmpty(resp)) {
JSONObject data = JSONObject.parseObject(resp);
String code = data.getString("code");
if (ConfigureConst.SUCCESS_CODE.equals(code)) {
JSONArray tickets = data.getJSONArray("tickets");
if (tickets != null && tickets.size() > 0) {
return tickets.getJSONObject(0).getString("value");
}
}
}
return null;
}
/**
* 获取nonce tiket
* @param accessToken
* @param userId
* @return
*/
private Map<String, String> buildNonceTicketRequestParams(String accessToken, Long userId) {
Map<String, String> pm = new HashMap<String, String>();
pm.put("app_id", webankConfigure.getAppId());
pm.put("access_token", accessToken);
pm.put("type", ConfigureConst.NONCE_TYPE);
pm.put("version", ConfigureConst.VERSION);
pm.put("user_id", ""+userId);
return pm;
}
/**
* 获取sign tiket
* @param accessToken
* @return
*/
private Map<String, String> buildSignTicketRequestParams(String accessToken) {
Map<String, String> pm = new HashMap<String, String>();
pm.put("app_id", webankConfigure.getAppId());
pm.put("access_token", accessToken);
pm.put("type", ConfigureConst.SIGN_TYPE);
pm.put("version", ConfigureConst.VERSION);
return pm;
}
/**
* 查询订单标识
* @return
*/
public String buildOrderNo() {
return format.format(new Date());
}
/**
* 生成签名
* @param eles
* @return
*/
private String sign(List<String> eles) {
eles.removeAll(Collections.singleton(null));
Collections.sort(eles);
StringBuffer sb = new StringBuffer();
for (String el : eles) {
sb.append(el);
}
return Hashing.sha1().hashString(sb, Charsets.UTF_8).toString().toUpperCase();
}
private String buildNonceStr() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* OCR api 签名
* @return
*/
public ResponseResult<JSONObject> getOCRApiSign() {
ResponseResult<JSONObject> result = new ResponseResult<>();
try {
String orderNo = buildOrderNo();
String signTicket = requestSignTicket();
String appId = webankConfigure.getAppId();
String version = ConfigureConst.VERSION;
String nonce = buildNonceStr();
List<String> eles = new ArrayList<>();
eles.add(signTicket);
eles.add(orderNo);
eles.add(appId);
eles.add(version);
eles.add(nonce);
String sign = sign(eles);
JSONObject data = new JSONObject();
data.put("orderNo", orderNo);
data.put("sign", sign);
data.put("nonce", nonce);
data.put("version", version);
data.put("webankAppId", appId);
data.put("tiket", signTicket);
log.info("get getOCRApiSign success, data: {}", JSONObject.toJSONString(data));
result.setData(data);
} catch (Exception e) {
ResultUtil.buildResultWithResponseStatus(result, ResponseStatus.UNKNOW_SYSTEM_ERROR);
}
return result;
}
/**
* H5上送身份信息签名
* @param userId
* @return
*/
public ResponseResult<JSONObject> getH5Faceid(JSONObject body) {
ResponseResult<JSONObject> result = new ResponseResult<>();
try {
String orderNo = buildOrderNo();
String signTicket = requestSignTicket();
String appId = webankConfigure.getAppId();
String version = ConfigureConst.VERSION;
List<String> eles = new ArrayList<>();
eles.add(appId);
eles.add(orderNo);
eles.add(body.getString("name"));
eles.add(body.getString("idNo"));
eles.add(body.getString("userId"));
eles.add(version);
eles.add(signTicket);
String sign = sign(eles);
JSONObject data = new JSONObject();
data.put("webankAppId", appId);
data.put("orderNo", orderNo);
data.put("name", body.getString("name"));
data.put("idNo", body.getString("idNo"));
data.put("userId", body.getString("userId"));
data.put("sourcePhotoType", "1");
data.put("version", version);
data.put("sign", sign);
log.info("---> getH5FaceidSignData success, data: {}", JSONObject.toJSONString(data));
//请求获取faceid
String resp = HttpClientUtil.postParametersJson(GET_H5_FACEID_URL, data.toJSONString());
/*{
"code": "0",
"msg": "请求成功",
"bizSeqNo": "18022720001015100000000001144364",
"result": {
"bizSeqNo": "18022720001015100000000001144364",
"transactionTime": "20180227160355",
"orderNo": "20180227160355543",
"h5faceId": "d449bba50f3d7db9f14cac79abe6b4c6",
"success": false
},
"transactionTime": "20180227160355"
}*/
log.info("---> getH5Faceid request result: {}", resp);
String h5Faceid = null;
if (!StringUtils.isEmpty(resp)) {
JSONObject respData = JSONObject.parseObject(resp);
if ("0".equals(respData.getString("code"))) {
JSONObject childEle = respData.getJSONObject("result");
if (childEle != null) {
h5Faceid = childEle.getString("h5faceId");
}
}
}
if (!StringUtils.isEmpty(h5Faceid)) {
return getH5FaceLoginSign(h5Faceid, body.getLong("userId"), orderNo);
}
return ResponseResult.build(-1, "获取faceid失败", null);
} catch (Exception e) {
log.error("---> getH5Faceid failed, e:{}", e);
ResultUtil.buildResultWithResponseStatus(result, ResponseStatus.UNKNOW_SYSTEM_ERROR);
}
return result;
}
/**
* 获取启动H5人脸识别sign
* @param faceid
* @param userId
* @return
*/
public ResponseResult<JSONObject> getH5FaceLoginSign(String h5faceId, Long userId, String orderNo) {
ResponseResult<JSONObject> result = new ResponseResult<>();
try {
String nonceTicket = requestNonceTicket(userId);
String appId = webankConfigure.getAppId();
String version = ConfigureConst.VERSION;
String nonce = buildNonceStr();
List<String> eles = new ArrayList<>();
eles.add(nonceTicket);
eles.add(orderNo);
eles.add(appId);
eles.add(version);
eles.add(nonce);
eles.add(h5faceId);
eles.add(userId.toString());
String sign = sign(eles);
JSONObject data = new JSONObject();
data.put("webankAppId", appId);
data.put("version", version);
data.put("nonce", nonce);
data.put("orderNo", orderNo);
data.put("h5faceId", h5faceId);
data.put("url", "");
data.put("userId", userId.toString());
data.put("sign", sign);
log.info("get getH5FaceLoginSign success, data: {}", JSONObject.toJSONString(data));
result.setData(data);
} catch (Exception e) {
ResultUtil.buildResultWithResponseStatus(result, ResponseStatus.UNKNOW_SYSTEM_ERROR);
}
return result;
}
}
| [
"daiqw713@outlook.com"
] | daiqw713@outlook.com |
1b8e2b99ed75f3376ba4ccf35f5327a27c786d3a | cd29286fb47693a80623b6958e5e6d574d6403ca | /toby/src/springbook/user/template6/dao/DaoFactory.java | 0b1b17b66c0e480ff151af2ab111eb6abee92714 | [] | no_license | cholongbul/Tobyspring | e0b8dd4551a81d846fb88965b3a2e5363f2f191c | 1b1e991a281d057fae9af81a2251c1437ce3ce0c | refs/heads/master | 2023-04-26T01:19:32.288059 | 2021-05-23T05:57:32 | 2021-05-23T05:57:32 | 366,063,174 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,042 | java | package springbook.user.template6.dao;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
//카운팅 커넥션 의존관계 추가
//애플리케이션 컨텍스트 또는 빈 팩토리가 사용할 설정 정보라는 표시
@Configuration
public class DaoFactory {
@Bean
public UserDao userDao() {
UserDao userDao = new UserDaoDeleteAll();
userDao.setDataSource(dataSource());//수정자 메소드 주입
return userDao;
}
@Bean
public DataSource dataSource() {
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriverClass(com.mysql.jdbc.Driver.class);
dataSource.setUrl("jdbc:mysql://localhost:3306/springbook?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Seoul&useUnicode=true&characterEncoding=UTF8&");
dataSource.setUsername("root");
dataSource.setPassword("1234");
return dataSource;
}
} | [
"meyoub612@naver.com"
] | meyoub612@naver.com |
16590abe5a588e18af09e484adcc36fa5e0a94b2 | 30edb3f17a5116a379177846cb67c1428ff4c0ab | /Othello/src/Metrics.java | 7b7c54108e4774c4a176f5c49e97085cc146e2d3 | [] | no_license | lilannie/Othello | 61e7023e6a7389af812a5dc17bce178430f2fd35 | 3d8929399831d1591b26135d25482abfed4d33eb | refs/heads/master | 2021-01-11T04:41:18.065712 | 2016-10-17T10:26:07 | 2016-10-17T10:26:07 | 71,113,526 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,426 | java | import java.util.Hashtable;
import java.util.Set;
import java.util.TreeMap;
/**
* Stores key-value pairs for efficiency analysis.
*
* @author Ravi Mohan
* @author Ruediger Lunde
*/
public class Metrics {
private Hashtable<String, String> hash;
public Metrics() {
this.hash = new Hashtable<String, String>();
}
public void set(String name, int i) {
hash.put(name, Integer.toString(i));
}
public void set(String name, double d) {
hash.put(name, Double.toString(d));
}
public void incrementInt(String name) {
set(name, getInt(name) + 1);
}
public void set(String name, long l) {
hash.put(name, Long.toString(l));
}
public int getInt(String name) {
String value = hash.get(name);
return value != null ? Integer.parseInt(value) : 0;
}
public double getDouble(String name) {
String value = hash.get(name);
return value != null ? Double.parseDouble(value) : Double.NaN;
}
public long getLong(String name) {
String value = hash.get(name);
return value != null ? Long.parseLong(value) : 0l;
}
public String get(String name) {
return hash.get(name);
}
public Set<String> keySet() {
return hash.keySet();
}
/** Sorts the key-value pairs by key names and formats them as equations. */
public String toString() {
TreeMap<String, String> map = new TreeMap<String, String>(hash);
return map.toString();
}
}
| [
"anniesteenso@gmail.com"
] | anniesteenso@gmail.com |
b82052c14c1fb03754f8adecdd47d995e9116d83 | 37cd0c7259aa3235d7acfaf394acb9fc38781b81 | /src/test/java/com/lifeonwalden/etl4j/BaseTest.java | de832968c5c02302cf283b7cf13bafd06a741b23 | [
"Apache-2.0"
] | permissive | cmanlh/etl4j | 39e1749f9338ca1c52f7efbe56d02b6c25166ca7 | 5b13139699d5b5b53f746b52225c6446aa339c0d | refs/heads/master | 2021-01-01T05:22:41.835296 | 2016-05-17T14:49:41 | 2016-05-17T14:49:41 | 58,423,496 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,497 | java | package com.lifeonwalden.etl4j;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
public class BaseTest {
protected static final String CONNECTION_STRING = "jdbc:hsqldb:mem:testdb;shutdown=false";
protected static final String USER_NAME = "SA";
protected static final String PASSWORD = StringUtils.EMPTY;
@Before
public void setup() throws ClassNotFoundException, SQLException {
Class.forName("org.hsqldb.jdbcDriver");
Connection connection = DriverManager.getConnection(CONNECTION_STRING, USER_NAME, PASSWORD);
connection.createStatement().executeUpdate(
"create table \"User\" (\"id\" varchar(32), \"age\" int, \"income\" decimal(20,6), \"birthday\" datetime)");
connection.createStatement().executeUpdate(
"create table \"Book\" (\"id\" varchar(32), \"name\" varchar(32), \"publisher\" varchar(32), \"owner\" varchar(32))");
PreparedStatement ps = connection.prepareStatement("insert into \"User\" values(?,?,?,?)");
ps.setString(1, "1111");
ps.setInt(2, 50);
ps.setDouble(3, 5.6);
ps.setDate(4, new Date(System.currentTimeMillis()));
ps.addBatch();
ps.setString(1, "2222");
ps.setInt(2, 35);
ps.setDouble(3, 8.6);
ps.setDate(4, new Date(System.currentTimeMillis()));
ps.addBatch();
ps.executeBatch();
ps.setString(1, "3333");
ps.setInt(2, 35);
ps.setDouble(3, 8.6);
ps.setDate(4, null);
ps.addBatch();
ps.executeBatch();
ps.close();
ps = connection.prepareStatement("insert into \"Book\" values(?,?,?,?)");
ps.setString(1, "aaaa");
ps.setString(2, "AAAAAA");
ps.setString(3, "apublisher");
ps.setString(4, "1111");
ps.addBatch();
ps.setString(1, "bbbbb");
ps.setString(2, "BBBBBB");
ps.setString(3, "bpublisher");
ps.setString(4, "1111");
ps.executeBatch();
connection.close();
}
@After
public void clear() throws ClassNotFoundException, SQLException {
Class.forName("org.hsqldb.jdbcDriver");
Connection connection = DriverManager.getConnection(CONNECTION_STRING, USER_NAME, PASSWORD);
Statement stmt = connection.createStatement();
stmt.execute("DROP SCHEMA PUBLIC CASCADE");
connection.close();
}
}
| [
"cmanlh@163.com"
] | cmanlh@163.com |
9f196a1e0255d84c25456d75451f6082663a363d | 8472c045f19824a445e4c6693f103776a9d47c57 | /src/main/java/pl/perekmichal/models/database/dao/WeatherDao.java | 92a2e2f603e1f19833ee5364b3f4acdfe5d5645f | [] | no_license | PerekMichal/weather | 8f1cc20fb71235e92cf32ebf58abb05231817719 | 1dbd47628905337d00eea41e303a53b5ff1f940c | refs/heads/master | 2021-08-26T05:29:00.809694 | 2017-11-21T17:45:38 | 2017-11-21T17:45:38 | 111,559,066 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 419 | java | package pl.perekmichal.models.database.dao;
import pl.perekmichal.models.WeatherModel;
import java.util.List;
public interface WeatherDao {
void saveWeather (WeatherModel model);
List<WeatherModel> laodWeather(String city);
List<WeatherModel> laodWeather();
List<WeatherModel> laodWeather(float temp);
}
// DAO DATA ACCESS OBJECT // POMAGA UTWORZYC POLIMORFIZM // TRZYMAMY TUTAJ METODY DOSTĘPOWE
// | [
"perekmichal93@gmail.com"
] | perekmichal93@gmail.com |
12dc3a739c90d2b9230bee2a11490efec1c23ed5 | 5725405b6f788c5c57250b1c4d09a9aa56e14cc6 | /tapestry-core/src/main/java/org/apache/tapestry5/internal/services/PageTemplateLocator.java | 4e61c75b4dd19c5313cb7c6feeb2062e698f51bf | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"MIT",
"Apache-2.0",
"MIT-0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"MPL-1.1",
"CC-BY-2.5"
] | permissive | nirvdrum/tapestry5 | 614aff41a1b88ccfd5d907f9682d606b234089c9 | 773c7480d77826d80f50dee03057d56cab3ac824 | refs/heads/5.0 | 2022-12-23T01:42:32.675122 | 2009-01-13T17:54:26 | 2009-01-13T17:54:26 | 180,714 | 1 | 1 | Apache-2.0 | 2022-12-09T22:04:32 | 2009-05-13T00:17:00 | Java | UTF-8 | Java | false | false | 1,405 | java | // Copyright 2007 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal.services;
import org.apache.tapestry5.ioc.Resource;
import org.apache.tapestry5.model.ComponentModel;
import java.util.Locale;
/**
* Responsible for locating page templates in the web application context.
*/
public interface PageTemplateLocator
{
/**
* Given model, determines if the model is for a page (rather than a component) and if so, sees if there is a
* localized template for the page in the web application context.
*
* @param model the component model defining the page to search for
* @param locale the desired localization of the template
* @return the template resource, or null if not found or the model is not a page
*/
Resource findPageTemplateResource(ComponentModel model, Locale locale);
}
| [
"hlship@apache.org"
] | hlship@apache.org |
43d6efc341733fb95742b87488635582edaab279 | 67628bc0ac0aa0857b42293319e51215ea3f6bbb | /src/com/lineComparison/LineComparisonBuilder.java | e4e2a59f203b3eb7d442b6deddce983a5ecf736c | [] | no_license | pratappawar/LineComparisonComputation | 0ba3c34a9caf849fbd239e08e9f29c55f1ca071d | 0812711870f052429be2fd58f06c707c9b848f88 | refs/heads/master | 2023-04-19T05:23:24.268150 | 2021-04-28T15:25:28 | 2021-04-28T15:25:28 | 361,958,325 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,028 | java | package com.lineComparison;
import java.util.Scanner;
public class LineComparisonBuilder {
public static void main(String[] args) {
System.out.println("Welcome to line comparison computation problem!!");
LineComputation lc = new LineComputation();
lc.lineComputationEquality();
}
}
class LineComputation {
public void lineComputationEquality() {
Scanner sc = new Scanner(System.in);
System.out.print("plese Enter line co-ordinates x1=");
int x1 = sc.nextInt();
System.out.print("plese Enter line co-ordinates x2=");
int x2 = sc.nextInt();
System.out.print("plese Enter line co-ordinates y1=");
int y1 = sc.nextInt();
System.out.print("plese Enter line co-ordinates x2=");
int y2 = sc.nextInt();
int length_of_line1 = (int) (((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
int line1_length = (int) Math.sqrt(length_of_line1);
System.out.println("Length of The line1 is=" + line1_length);
System.out.print("plese Enter line co-ordinates x3=");
int x3 = sc.nextInt();
System.out.print("plese Enter line co-ordinates x4=");
int x4 = sc.nextInt();
System.out.print("plese Enter line co-ordinates y3=");
int y3 = sc.nextInt();
System.out.print("plese Enter line co-ordinates y4=");
int y4 = sc.nextInt();
int length_of_line2 = (int) (((x4 - x3) * (x4 - x3)) + ((y4 - y3) * (y4 - y3)));
int line2_length = (int) Math.sqrt(length_of_line2);
sc.close();
System.out.println("Length of The line2 is=" + line2_length);
Integer L1 = new Integer(line1_length);
Integer L2 = new Integer(line2_length);
// Using Equal Method
if (L1.equals(L2)) {
System.out.println("Both lines are equal");
} else {
System.out.println("Both lines are not equal");
}
// Using CompareTo method
int eq = L1.compareTo(L2);
System.out.println(eq);
if (eq == 0) {
System.out.println("Bothe lines are Equal ");
} else if (eq > 0) {
System.out.println("Line1 is Greater Than Line 2");
} else {
System.out.println("Line2 is Greater than Line1");
}
}
} | [
"pratappawar1997@gmail.com"
] | pratappawar1997@gmail.com |
34f2d23aae1ac1860fcac69a2e881e5e6f127850 | 850475f6fda2f19a229e2e40956262ff49222757 | /src/main/java/com/meteergin/mapbackend/api/nearbysearch/Geometry.java | a1e6aaa72c148d1d14fde28b561b697afa60b7ec | [] | no_license | meteergin/map-backend | df338463889433a824238fe224d248fca251a760 | 76f48f9941a2f0c2751d7a778e4b469e3e9d8cdb | refs/heads/master | 2023-09-04T18:23:13.440054 | 2021-11-23T10:48:39 | 2021-11-23T10:48:39 | 422,298,028 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 164 | java | package com.meteergin.mapbackend.api.nearbysearch;
import lombok.Data;
@Data
public class Geometry{
public Location location;
public Viewport viewport;
}
| [
"mete.ergin@outlook.com"
] | mete.ergin@outlook.com |
e325134653bf24bbe14e54b6f98c1dbaee8fc2a1 | 77c1deb1edc53a4932880daed29e4a59eb47a591 | /wadi/wadi-core/src/main/java/org/codehaus/wadi/replication/storage/ReplicaStorageFactory.java | c6233112e783fd22fe1082e8254fbabeedd68d84 | [] | no_license | codehaus/wadi | c3cd36d75ddbd684383412c611591c8b2d1e2f3a | 05479be4cfde94cbecab59f58ca8235bdd97a75c | refs/heads/master | 2023-07-20T00:34:33.892694 | 2009-11-01T07:46:21 | 2009-11-01T07:46:21 | 36,338,824 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 858 | java | /**
* Copyright 2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.wadi.replication.storage;
import org.codehaus.wadi.servicespace.ServiceSpace;
/**
*
* @version $Revision$
*/
public interface ReplicaStorageFactory {
ReplicaStorage factory(ServiceSpace serviceSpace);
}
| [
"gdamour@850eb8eb-920f-0410-90bf-d29e371206e5"
] | gdamour@850eb8eb-920f-0410-90bf-d29e371206e5 |
a0cb62aceb9f94e7fff8409452d36c4506007c90 | b15d93d25f6fe985470c225eb76d1132bcca87f4 | /org/quantlib/MidPointCdsEngine.java | 2ea72f2831eaba50816ec26e8858ef6909d2f74c | [] | no_license | nolan-symphony/quantlib-bonds | 14757a3d490c794b502f59c5ba392691802c4e00 | e77e0027fa6aa767c9ef9e23b79dbff8e959ba3e | refs/heads/main | 2023-08-24T07:03:16.157550 | 2021-10-26T15:32:42 | 2021-10-26T15:32:42 | 419,619,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,683 | java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 4.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.quantlib;
public class MidPointCdsEngine extends PricingEngine {
private transient long swigCPtr;
private transient boolean swigCMemOwnDerived;
protected MidPointCdsEngine(long cPtr, boolean cMemoryOwn) {
super(QuantLibJNI.MidPointCdsEngine_SWIGSmartPtrUpcast(cPtr), true);
swigCMemOwnDerived = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(MidPointCdsEngine obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void swigSetCMemOwn(boolean own) {
swigCMemOwnDerived = own;
super.swigSetCMemOwn(own);
}
@SuppressWarnings("deprecation")
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwnDerived) {
swigCMemOwnDerived = false;
QuantLibJNI.delete_MidPointCdsEngine(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public MidPointCdsEngine(DefaultProbabilityTermStructureHandle probability, double recoveryRate, YieldTermStructureHandle discountCurve) {
this(QuantLibJNI.new_MidPointCdsEngine(DefaultProbabilityTermStructureHandle.getCPtr(probability), probability, recoveryRate, YieldTermStructureHandle.getCPtr(discountCurve), discountCurve), true);
}
}
| [
"nolan.potier@symphony.com"
] | nolan.potier@symphony.com |
3c454ff19d595d32b6d3caffb23fcd43053f6b8a | de9723263c8d8a1bbcff2429c310b1c598744ce1 | /src/main/java/com/infomax/web/controllers/IndexController.java | 7673ceab244783646dd6548532ab62f23a307879 | [] | no_license | Filip-si/web | bfb077269da9d6a2ed28a0ccc37d00eac2231247 | 7615d794c8ae864317f65419b4abc7b07b3dab49 | refs/heads/master | 2023-05-07T06:40:06.901061 | 2021-06-02T11:35:33 | 2021-06-02T11:35:33 | 319,304,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,734 | java | package com.infomax.web.controllers;
import com.infomax.web.models.AppUser;
import com.infomax.web.services.AdminPanelServiceImpl;
import com.infomax.web.services.UserPrincipalDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
@RestController
public class IndexController {
@Autowired
private UserPrincipalDetailsService principalDetailsService;
@Autowired
private AdminPanelServiceImpl adminPanelService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView showPage(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("appUser", new AppUser());
modelAndView.addObject("loggedUser", principalDetailsService.getLoggedUser());
if(principalDetailsService.getLoggedUser() != null){
modelAndView.addObject("roleUser", principalDetailsService.isAdmin(principalDetailsService.getLoggedUser().getId()));
}
modelAndView.addObject("allNews", adminPanelService.getAll());
modelAndView.setViewName("index");
return modelAndView;
}
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView showIndex(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("appUser", new AppUser());
modelAndView.addObject("loggedUser", principalDetailsService.getLoggedUser());
if(principalDetailsService.getLoggedUser() != null){
modelAndView.addObject("roleUser", principalDetailsService.isAdmin(principalDetailsService.getLoggedUser().getId()));
}
modelAndView.addObject("allNews", adminPanelService.getAll());
modelAndView.setViewName("index");
return modelAndView;
}
@Transactional
@RequestMapping(
value = "/article/{title}",
produces = MediaType.APPLICATION_PDF_VALUE,
method = RequestMethod.GET)
public ResponseEntity showPDF(HttpServletResponse response, @PathVariable("title") String title) throws IOException{
byte[] decoder = Base64.getDecoder().decode(adminPanelService.findByTitle(title).getContent());
return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF).body(decoder);
}
@RequestMapping(value = "/login-error", method = RequestMethod.GET)
public ModelAndView loginError(Model model){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("loggedUser",principalDetailsService.getLoggedUser());
if(principalDetailsService.getLoggedUser() != null){
modelAndView.addObject("roleUser", principalDetailsService.isAdmin(principalDetailsService.getLoggedUser().getId()));
}
model.addAttribute("loginError", true);
modelAndView.setViewName("login");
return modelAndView;
}
@RequestMapping(value = "/about", method = RequestMethod.GET)
public ModelAndView showLogin(){
ModelAndView mav = new ModelAndView();
mav.addObject("loggedUser",principalDetailsService.getLoggedUser());
if(principalDetailsService.getLoggedUser() != null){
mav.addObject("roleUser", principalDetailsService.isAdmin(principalDetailsService.getLoggedUser().getId()));
}
mav.setViewName("about");
return mav;
}
}
| [
"filip270697@gmail.com"
] | filip270697@gmail.com |
3975314b84364b1b8f2787c9176e9fc89ff05e74 | 325d6251893afdd0961e2fbbde9937cdcd2e2252 | /ServiceLayer/src/main/java/ch/demo/helpers/LoggerProducer.java | be9e8b6e37f0b6e804713c9406b617f3940fa7d7 | [] | no_license | jean-morissette/jee6-demo | 51a880d6f5a8bf3042f4351f8dc0eb234c163735 | 20a1670fe7aa06c4d3c390a378593f80b1a4e0f1 | refs/heads/master | 2016-09-09T18:59:55.839446 | 2012-06-07T08:55:34 | 2012-06-07T08:55:34 | 35,716,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 740 | java | package ch.demo.helpers;
import java.io.Serializable;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Produce a slf4j logger.
* @author hostettler
*
*/
public class LoggerProducer implements Serializable {
/** The serial-id. */
private static final long serialVersionUID = -7352371086416154400L;
/**
* Produces an instance of a slf4j logger for the given injection point.
* @param injectionPoint to use
* @return a logger
*/
@Produces
public Logger getLogger(final InjectionPoint injectionPoint) {
return LoggerFactory.getLogger(injectionPoint.getBean().getBeanClass());
}
} | [
"steve.hostettler@e75a912d-c469-4da3-42e7-869463994cc8"
] | steve.hostettler@e75a912d-c469-4da3-42e7-869463994cc8 |
766fcf84d79db3fada81ba8ed4c9c7ce6bcbf4cf | 673dac4b783a2ab429b7151b40ffb062900f3616 | /src/ycel/data/CellContent.java | 3d0129026a4a4eeed5ea59eb55fda9dc41e02945 | [] | no_license | khalasn1/pco_projecto3 | 8feb9c554c004cb41a68cc1f2bb5d0d9b314f636 | 78acc19fa58282417dfa61176ed7a6a819f1eb54 | refs/heads/master | 2021-01-10T08:21:04.275349 | 2016-01-11T00:02:15 | 2016-01-11T00:02:15 | 52,614,467 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 474 | java | package ycel.data;
/**
* Interface para conteúdo de uma célula.
*/
public interface CellContent {
/**
* Devolve a fórmula associada ao conteúdo.
* @return Uma string que codifica o conteúdo
* da célula.
*/
String formula();
/**
* Avalia o conteúdo da célula.
* @param cv Objecto para leitura de outras
* células, caso necessário.
* @return Objecto resultante da avaliação.
*/
Object evaluate(CellValues cv);
}
| [
"sherby@bitbucket.org"
] | sherby@bitbucket.org |
561fab5dc2268f645efd33323d3c9b237d27fa27 | a46e2807d06dfe527bcc0a0591b37c03b8ecc90c | /app/src/test/java/com/example/alexandre/sinaisvitais/ExampleUnitTest.java | de4160ddfe1cc1c0dd9e52987888e80c0bbb60af | [] | no_license | alexandrealves27/sinaisvitaisfinal | bfa83bc8a983d51cfd94c9785ac6676f5e89236a | e6b625a61442c5c4fb32d1b07b445a399cfeadf8 | refs/heads/master | 2020-03-19T12:17:25.850820 | 2018-06-15T10:14:46 | 2018-06-15T10:14:46 | 136,508,305 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 395 | java | package com.example.alexandre.sinaisvitais;
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);
}
} | [
"alexandrealvesgoncalves27@gmail.com"
] | alexandrealvesgoncalves27@gmail.com |
5c7377a93eee25c0e628ce8534b72cca67239faf | d4fb8f5bd84fe76de0875a27a431b057d95bc239 | /core/src/main/java/com/caitiaobang/core/app/tools/popup/AutoLocatedPopup.java | 2d1249f81a8bd9823b94fe9c5e41b35447134fa5 | [] | no_license | printlybyte/yf_trajectory | 6fd81606fefd402a0d0daf76288b4695ed3dea1e | 923f55609e02b0fe0ff516c4939a9ce9e0b5199f | refs/heads/master | 2020-06-29T21:53:18.103278 | 2020-04-08T08:44:50 | 2020-04-08T08:44:50 | 200,633,905 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,088 | java | package com.caitiaobang.core.app.tools.popup;
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import com.caitiaobang.core.R;
import razerdp.basepopup.BasePopupWindow;
/**
* Created by 大灯泡 on 2016/11/23.
* <p>
* 自动定位的popup,空间不足显示在上面
*/
public class AutoLocatedPopup extends BasePopupWindow implements View.OnClickListener {
public AutoLocatedPopup(Context context) {
super(context);
setAutoLocatePopup(true);
bindEvent();
}
@Override
protected Animation onCreateShowAnimation() {
return getDefaultAlphaAnimation();
}
@Override
protected Animation onCreateDismissAnimation() {
return getDefaultAlphaAnimation(false);
}
@Override
public View onCreateContentView() {
return createPopupById(R.layout.popup_menu);
}
private void bindEvent() {
findViewById(R.id.tx_1).setOnClickListener(this);
findViewById(R.id.tx_2).setOnClickListener(this);
findViewById(R.id.tx_3).setOnClickListener(this);
}
@Override
public void onAnchorTop() {
//
}
@Override
public void onAnchorBottom() {
// ToastUtils.ToastMessage(getContext(), "显示在下方(上位置不足)");
}
@Override
public void onClick(View v) {
int i = v.getId();
int pos = 0;
if (i == R.id.tx_1) {
pos=1;
// ToastUtils.ToastMessage(getContext(), "click tx_1");
} else if (i == R.id.tx_2) {
pos=2;
// ToastUtils.ToastMessage(getContext(), "click tx_2");
} else if (i == R.id.tx_3) {
pos=3;
// ToastUtils.ToastMessage(getContext(), "click tx_3");
}
if (chickListioner != null) {
chickListioner.ChickPos(pos);
}
}
public void setOnChickListiner( ChickListioner c) {
chickListioner = c;
}
ChickListioner chickListioner;
public interface ChickListioner {
void ChickPos(int pos);
}
}
| [
"18701403668@163.com"
] | 18701403668@163.com |
dea876d4b027fe4f35361e2db5a06b2048690cf1 | 322d570318e0a0d876ec63791755d18b6effcca3 | /src/main/java/juniorSheet/cfB/PashmakAndFlowers.java | 14570d8fa2e665e27efad0dca268c0f1730f3cf4 | [] | no_license | hashiDrama/competitve-java | 8ea11ded04dc32ee1e7916bb5a12dab6dc5069f6 | a36cb305fd19e809efeaac136a5c60cdec9e7e89 | refs/heads/master | 2023-05-29T17:14:40.337979 | 2021-06-02T03:36:14 | 2021-06-02T03:36:14 | 197,377,897 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 782 | java | /*
* https://codeforces.com/contest/459/problem/B
*/
package juniorSheet.cfB;
import java.util.Scanner;
public class PashmakAndFlowers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] b = new int[n];
int max = 0, min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
b[i] = sc.nextInt();
min = Math.min(min, b[i]);
max = Math.max(max, b[i]);
}
System.out.print((max - min) + " ");
long mini = 0, maxi = 0;
for (int i = 0; i < n; i++) {
if (b[i] == min)
mini++;
if (b[i] == max)
maxi++;
}
if (max == min)
System.out.println((maxi * (maxi - 1)) / 2);
else
System.out.println(maxi * mini);
sc.close();
}
}
| [
"t-vikrant@talasecurity.io"
] | t-vikrant@talasecurity.io |
66f94e4a66d77941724f6d54381e66044342225f | 9f004c3df4413eb826c229332d95130a1d5c8457 | /src/tanmoy_Sarkar/WeekdayOrWeekends.java | 0c5c365a831366417ef138145744d711a57d483f | [] | no_license | MayurSTechnoCredit/JAVATechnoJuly2021 | dd8575c800e8f0cac5bab8d5ea32b25f7131dd0d | 3a422553a0d09b6a99e528c73cc2b8efe260a07a | refs/heads/master | 2023-08-22T14:43:37.980748 | 2021-10-16T06:33:34 | 2021-10-16T06:33:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,064 | java | package tanmoy_Sarkar;
public class WeekdayOrWeekends {
String arr[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
void result(int dayCount){
if(dayCount>=1 && dayCount<=5){
System.out.println("Your entered day is : " +arr[dayCount-1]);
System.out.println("weekday.");
}
else if(dayCount==6 || dayCount==7){
System.out.println("Your entered day is : " +arr[dayCount-1]);
System.out.println("weekend.");
}
else{
System.out.println("Invalid Input.");
}
}
void isValidBrowser(String browser){
if (browser.equals("Chrome") || browser.equals("Edge") || browser.equals("IE")){
System.out.println("Your browser is valid for the Exam.");
}
else{
System.out.println("Please install Chrome or Edge or IE.");
}
System.out.println("Thank you.");
}
public static void main(String args[]){
WeekdayOrWeekends weekdayorweekends = new WeekdayOrWeekends();
weekdayorweekends.result(3);
weekdayorweekends.result(6);
weekdayorweekends.result(11);
weekdayorweekends.result(-3);
}
}
| [
"s.tanmoy613@gmail.com"
] | s.tanmoy613@gmail.com |
9b6b889982ec62b12de68c4e17cc88dcc95128c9 | 7fdc79a942bbf80b0f9aecfc3a4bcad9bab75d09 | /java&jdbc/oct22/src/oct22/TestB.java | 9c52b9b490d0edbeb971527c65ddf3b218f60673 | [] | no_license | puttulkumari/USTGlobal-16-sept-2019-puttul-kumari | 96102162bdf752079818e6dca0f78f9a9f531554 | b0d63c42500b5260b6900b6550a13193bad2f0a2 | refs/heads/master | 2023-01-09T18:48:03.411362 | 2019-12-22T04:01:13 | 2019-12-22T04:01:13 | 215,547,477 | 0 | 0 | null | 2023-01-07T21:15:32 | 2019-10-16T12:52:07 | JavaScript | UTF-8 | Java | false | false | 372 | java | package oct22;
public class TestB {
static int a=25;
int x;
public static void add()
{
//only final access modifier is supported for local modifier
final int b;
b=20;
System.out.println(a);
System.out.println(b);
}
public static void main(String[] args) {
add();
TestB t=new TestB();
System.out.println("x value is "+t.x);
}
}
| [
"puttul.kumari01@gmail.com"
] | puttul.kumari01@gmail.com |
ea101b70b2a1a33b8b486df76f3af294afb378c1 | 9feb17c588ac5e222007df731a3a0cf9a00ce622 | /kiy-cloud/.svn/pristine/10/1069ef2b6ab5579135781f55bd7f783820476229.svn-base | 22a14287374f145e3a4c4c5a4f95ffa26059aafc | [] | no_license | crystalNi023/kiy-all | 1fdb8978a71384ffbc4a9290ec7a396bf0dfd3f9 | a23e19f46b3dcc2abf75104bcdcaaf74aa81bdfd | refs/heads/master | 2022-12-23T07:55:23.981652 | 2020-02-26T04:49:22 | 2020-02-26T04:49:22 | 243,160,398 | 1 | 0 | null | 2022-12-16T06:04:57 | 2020-02-26T03:33:54 | Java | UTF-8 | Java | false | false | 1,030 | package com.kiy.cloud.data;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.kiy.cloud.Config;
import com.kiy.cloud.Log;
/**
* 数据主控类
* @author HLX Tel:18996470535
* @date 2018年6月6日
* Copyright:Copyright(c) 2018
*/
public final class Data {
private static SqlSessionFactory factory;
private Data() {
}
public static SqlSessionFactory getSqlSessionFactory(){
return factory;
}
public static void initialize() {
Log.info("Data initialize ...");
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(Config.MYBATIS_CONFIG_URL);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
Log.error(e);
}
Log.info("Data initialized");
}
public static void stop() {
Log.info("Data stop ...");
factory = null;
Log.info("Data stopped");
}
} | [
"773701040@qq.com"
] | 773701040@qq.com | |
4d50ed8d1008c956d12abb3644eaf18569f8806a | ae07eee59f694482e6183cf7189e6f309d381859 | /jpost/src/main/java/jp/co/acms/jpost/base/common/utils/date/LocalDateConverter.java | a3acf86d164a0ff3593aa25e148f74a7a4c1136a | [] | no_license | horhenormanito/webapp-basecode | b3653e6b2b9097ee250a39c914dab7c3323f801c | f32484cf0cb7fafbe8319baa0e83cf7d18983426 | refs/heads/master | 2022-12-26T18:57:37.850323 | 2020-10-05T04:57:21 | 2020-10-05T04:57:21 | 300,512,996 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 890 | java |
package jp.co.acms.jpost.base.common.utils.date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import jp.co.acms.jpost.base.constant.WebConst;
/**
* 文字列の入力値をLocalDate型に変換する
*/
public class LocalDateConverter implements Converter<String, LocalDate> {
private final DateTimeFormatter formatter;
public LocalDateConverter(String dateFormat) {
this.formatter = DateTimeFormatter.ofPattern(dateFormat);
}
@Override
public LocalDate convert(String source) {
if (StringUtils.isEmpty(source)) {
return null;
}
if (source.length() == WebConst.LOCALDATE_FORMAT_YYYYMM.length()) {
return LocalDate.parse(source + "/01", formatter);
}
return LocalDate.parse(source, formatter);
}
}
| [
"n.carlon@fujitsu.com"
] | n.carlon@fujitsu.com |
5b31830f2d749eb59a0009b7a8f37c2bbcae384f | 1db1c1dc3e92b4f500078b61325ce4800cebb627 | /src/edu/ucsc/leeps/fire/FIREClientInterface.java | 30c372ba805467038813b0cf659a773637eb2972 | [
"BSD-2-Clause"
] | permissive | rauswarn/ConG | f63f1b495da2ec0ed125bbaf4d90ad88c3816804 | 35a8a2fa861d116e4a17fdb203896bc1cc3dca7b | refs/heads/master | 2020-03-24T05:00:07.519485 | 2017-09-19T21:50:50 | 2017-09-19T21:50:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 521 | java | /**
* Copyright (c) 2012, University of California
* All rights reserved.
*
* Redistribution and use is governed by the LICENSE.txt file included with this
* source code and available at http://leeps.ucsc.edu/cong/wiki/license
**/
package edu.ucsc.leeps.fire;
/**
*
* @author jpettit
*/
public interface FIREClientInterface {
public boolean readyForNextPeriod();
public void startPrePeriod();
public void startPeriod();
public void endPeriod();
public void tick(int elapsedMillis);
}
| [
"leepslab@gmail.com"
] | leepslab@gmail.com |
aedd884f8a287bd995a58d323798120da6d389fb | 4197b547b41c1d5c4a3c75bbda084c7bfe3dd024 | /mall-common/src/main/java/com/xch900910/mall/common/model/BaseModel.java | 61b29974be8d0ba36de9499e36c1f74aa1ad44c3 | [] | no_license | xch900910/mall | 53676d4cc993fb5c6a8fa51c19d4c1db6fe54c2d | 4df242eb473bc35464abf03e54184ca299b83ae4 | refs/heads/master | 2022-05-28T05:22:55.135784 | 2020-05-04T12:46:38 | 2020-05-04T12:46:38 | 261,173,148 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 261 | java | package com.xch900910.mall.common.model;
import lombok.Data;
/**
* @author xch900910
* @version 1.0
* @Desc
* @Date 2020/5/4 11:07
**/
@Data
public class BaseModel {
private String id;
private String createTime;
private String updateTime;
}
| [
"1159553819@qq.com"
] | 1159553819@qq.com |
b71f91e270451587e194acc421c6ab4ff12a0a00 | b5f0e3254e8f6cc5736b9855d61bb9784c7bb0d8 | /src/main/java/org/docksidestage/dockside/dbflute/allcommon/DBFluteConfig.java | 2704d4fddcce4654a201c87107d2ee05a753adeb | [
"Apache-2.0"
] | permissive | dbflute-test/dbflute-test-active-dockside | cd7d4e6125aad52fca743711d88c7204d3d337f5 | 997e80a8b9172e0460391618bdc5ec0089f7983c | refs/heads/master | 2023-08-06T08:06:06.340015 | 2023-07-19T18:42:11 | 2023-07-19T18:42:11 | 24,588,835 | 1 | 2 | Apache-2.0 | 2022-05-25T05:50:45 | 2014-09-29T09:48:15 | Java | UTF-8 | Java | false | false | 44,955 | java | package org.docksidestage.dockside.dbflute.allcommon;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dbflute.FunCustodial;
import org.dbflute.bhv.core.context.mapping.MappingDateTimeZoneProvider;
import org.dbflute.bhv.core.context.logmask.ErrorLogMaskProvider;
import org.dbflute.bhv.core.supplement.SequenceCacheKeyGenerator;
import org.dbflute.cbean.garnish.SpecifyColumnRequiredExceptDeterminer;
import org.dbflute.cbean.cipher.GearedCipherManager;
import org.dbflute.cbean.sqlclause.SqlClauseCreator;
import org.dbflute.dbmeta.name.SqlNameFilter;
import org.dbflute.dbway.DBDef;
import org.dbflute.exception.IllegalDBFluteConfigAccessException;
import org.dbflute.jdbc.DataSourceHandler;
import org.dbflute.jdbc.NotClosingConnectionWrapper;
import org.dbflute.jdbc.PhysicalConnectionDigger;
import org.dbflute.jdbc.SQLExceptionDigger;
import org.dbflute.jdbc.StatementConfig;
import org.dbflute.jdbc.ValueType;
import org.dbflute.outsidesql.factory.OutsideSqlExecutorFactory;
import org.dbflute.s2dao.valuetype.TnValueTypes;
import org.dbflute.system.QLog;
import org.dbflute.system.XLog;
import org.dbflute.twowaysql.DisplaySqlBuilder;
import org.dbflute.twowaysql.style.BoundDateDisplayTimeZoneProvider;
import org.dbflute.util.DfReflectionUtil;
import org.springframework.jdbc.datasource.DataSourceUtils;
/**
* @author DBFlute(AutoGenerator)
*/
public class DBFluteConfig {
// ===================================================================================
// Definition
// ==========
/** The logger instance for this class. (NotNull) */
private static final Logger _log = LoggerFactory.getLogger(DBFluteConfig.class);
/** Singleton instance. */
private static final DBFluteConfig _instance = new DBFluteConfig();
// ===================================================================================
// Attribute
// =========
// -----------------------------------------------------
// Configuration
// -------------
// condition-bean or parameter-bean
protected boolean _pagingCountLater = true;
protected boolean _pagingCountLeastJoin = true;
protected boolean _innerJoinAutoDetect = true;
protected boolean _orScopeQueryPurposeCheckWarningOnly = false; // since 1.2.7
protected boolean _thatsBadTimingDetect = true;
protected boolean _thatsBadTimingWarningOnly = false;
protected boolean _nullOrEmptyQueryAllowed = false;
protected boolean _emptyStringQueryAllowed = false;
protected boolean _emptyStringParameterAllowed = false;
protected boolean _overridingQueryAllowed = false;
protected boolean _invalidQueryAllowedWarning = false; // since 1.2.7
protected boolean _nonSpecifiedColumnAccessAllowed = false;
protected boolean _nonSpecifiedColumnAccessWarningOnly = false; // since 1.2.7
protected boolean _specifyColumnRequired = false; // since 1.1.2
protected SpecifyColumnRequiredExceptDeterminer _specifyColumnRequiredExceptDeterminer; // since 1.1.7
protected boolean _specifyColumnRequiredWarningOnly = false; // since 1.2.0
protected boolean _columnNullObjectAllowed = false;
protected boolean _columnNullObjectGearedToSpecify = false;
protected boolean _datetimePrecisionTruncationOfCondition = false;
protected boolean _disableSelectIndex;
protected boolean _queryUpdateCountPreCheck = false;
// logging
protected boolean _queryLogLevelInfo;
protected boolean _executeStatusLogLevelInfo;
protected String _logDatePattern;
protected String _logTimestampPattern;
protected String _logTimePattern;
protected BoundDateDisplayTimeZoneProvider _logTimeZoneProvider;
protected ErrorLogMaskProvider _errorLogMaskProvider; // since 1.2.7
// environment
protected StatementConfig _defaultStatementConfig;
protected Integer _cursorSelectFetchSize = null;
protected Integer _entitySelectFetchSize = null;
protected boolean _usePagingByCursorSkipSynchronizedFetchSize = false;
protected Integer _fixedPagingByCursorSkipSynchronizedFetchSize = null;
protected DataSourceHandler _dataSourceHandler;
protected PhysicalConnectionDigger _physicalConnectionDigger;
protected SQLExceptionDigger _sqlExceptionDigger;
protected String _outsideSqlPackage = null;
protected MappingDateTimeZoneProvider _mappingDateTimeZoneProvider; // since 1.1.0
// extension
protected SequenceCacheKeyGenerator _sequenceCacheKeyGenerator;
protected SqlClauseCreator _sqlClauseCreator;
protected SqlNameFilter _tableSqlNameFilter;
protected OutsideSqlExecutorFactory _outsideSqlExecutorFactory;
protected GearedCipherManager _gearedCipherManager;
// internal
protected boolean _internalDebug;
// -----------------------------------------------------
// Database Dependency
// -------------------
// -----------------------------------------------------
// Lock
// ----
protected boolean _locked = true; // at first locked
// ===================================================================================
// Constructor
// ===========
/**
* Constructor.
*/
private DBFluteConfig() { // adjusts default settings
_physicalConnectionDigger = new ImplementedPhysicalConnectionDigger();
_sqlExceptionDigger = new ImplementedSQLExceptionDigger();
if (_nonSpecifiedColumnAccessWarningOnly) { // since 1.2.7
FunCustodial.unlock();
FunCustodial.setNonSpecifiedColumnAccessWarningOnly(true);
FunCustodial.lock();
}
}
// ===================================================================================
// Singleton
// =========
/**
* Get singleton instance.
* @return Singleton instance. (NotNull)
*/
public static DBFluteConfig getInstance() {
return _instance;
}
// ===================================================================================
// Paging Select
// =============
public boolean isPagingCountLater() {
return _pagingCountLater;
}
public void setPagingCountLater(boolean pagingCountLater) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting pagingCountLater: " + pagingCountLater);
}
_pagingCountLater = pagingCountLater;
}
public boolean isPagingCountLeastJoin() {
return _pagingCountLeastJoin;
}
public void setPagingCountLeastJoin(boolean pagingCountLeastJoin) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting pagingCountLeastJoin: " + pagingCountLeastJoin);
}
_pagingCountLeastJoin = pagingCountLeastJoin;
}
// ===================================================================================
// Inner Join Auto Detect
// ======================
public boolean isInnerJoinAutoDetect() {
return _innerJoinAutoDetect;
}
public void setInnerJoinAutoDetect(boolean innerJoinAutoDetect) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting innerJoinAutoDetect: " + innerJoinAutoDetect);
}
_innerJoinAutoDetect = innerJoinAutoDetect;
}
// ===================================================================================
// CB Purpose Check
// ================
public boolean isOrScopeQueryPurposeCheckWarningOnly() { // since 1.2.7
return _orScopeQueryPurposeCheckWarningOnly;
}
public void setOrScopeQueryPurposeCheckWarningOnly(boolean orScopeQueryPurposeCheckWarningOnly) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting orScopeQueryPurposeCheckWarningOnly: " + orScopeQueryPurposeCheckWarningOnly);
}
_orScopeQueryPurposeCheckWarningOnly = orScopeQueryPurposeCheckWarningOnly;
}
// ===================================================================================
// That's-Bad-Timing Detect
// ========================
public boolean isThatsBadTimingDetect() {
return _thatsBadTimingDetect;
}
public void setThatsBadTimingDetect(boolean thatsBadTimingDetect) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting thatsBadTimingDetect: " + thatsBadTimingDetect);
}
_thatsBadTimingDetect = thatsBadTimingDetect;
}
public boolean isThatsBadTimingWarningOnly() { // since 1.2.7
return _thatsBadTimingWarningOnly;
}
public void setThatsBadTimingWarningOnly(boolean thatsBadTimingWarningOnly) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting thatsBadTimingWarningOnly: " + thatsBadTimingWarningOnly);
}
_thatsBadTimingWarningOnly = thatsBadTimingWarningOnly;
}
// ===================================================================================
// Invalid Query
// =============
public boolean isNullOrEmptyQueryAllowed() {
return _nullOrEmptyQueryAllowed;
}
/**
* Set whether null-or-empty query is allowed or not. <br>
* This configuration is only for ConditionBean.
* @param nullOrEmptyQueryAllowed The determination, true or false.
*/
public void setNullOrEmptyQueryAllowed(boolean nullOrEmptyQueryAllowed) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting nullOrEmptyQueryAllowed: " + nullOrEmptyQueryAllowed);
}
_nullOrEmptyQueryAllowed = nullOrEmptyQueryAllowed;
}
public boolean isEmptyStringQueryAllowed() {
return _emptyStringQueryAllowed;
}
/**
* Set whether an empty string for query is allowed or not. <br>
* This configuration is only for ConditionBean.
* @param emptyStringQueryAllowed The determination, true or false.
*/
public void setEmptyStringQueryAllowed(boolean emptyStringQueryAllowed) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting emptyStringQueryAllowed: " + emptyStringQueryAllowed);
}
_emptyStringQueryAllowed = emptyStringQueryAllowed;
}
public boolean isEmptyStringParameterAllowed() {
return _emptyStringParameterAllowed;
}
/**
* Set whether an empty string for parameter is allowed or not. <br>
* This configuration is only for ParameterBean.
* @param emptyStringParameterAllowed The determination, true or false.
*/
public void setEmptyStringParameterAllowed(boolean emptyStringParameterAllowed) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting emptyStringParameterAllowed: " + emptyStringParameterAllowed);
}
_emptyStringParameterAllowed = emptyStringParameterAllowed;
}
public boolean isOverridingQueryAllowed() {
return _overridingQueryAllowed;
}
/**
* Set whether overriding query is allowed or not. <br>
* This configuration is only for ConditionBean.
* @param overridingQueryAllowed The determination, true or false.
*/
public void setOverridingQueryAllowed(boolean overridingQueryAllowed) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting overridingQueryAllowed: " + overridingQueryAllowed);
}
_overridingQueryAllowed = overridingQueryAllowed;
}
public boolean isInvalidQueryAllowedWarning() {
return _invalidQueryAllowedWarning;
}
/**
* Set whether it shows warning log or not when invalid query is allowed. <br>
* This configuration is only for ConditionBean.
* @param invalidQueryAllowedWarning The determination, true or false.
*/
public void setInvalidQueryAllowedWarning(boolean invalidQueryAllowedWarning) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting invalidQueryAllowedWarning: " + invalidQueryAllowedWarning);
}
_invalidQueryAllowedWarning = invalidQueryAllowedWarning;
}
// ===================================================================================
// Non-Specified Access
// ====================
public boolean isNonSpecifiedColumnAccessAllowed() {
return _nonSpecifiedColumnAccessAllowed;
}
/**
* Set whether non-specified column access is allowed or not. <br>
* This configuration is only for ConditionBean.
* @param nonSpecifiedColumnAccessAllowed The determination, true or false.
*/
public void setNonSpecifiedColumnAccessAllowed(boolean nonSpecifiedColumnAccessAllowed) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting nonSpecifiedColumnAccessAllowed: " + nonSpecifiedColumnAccessAllowed);
}
_nonSpecifiedColumnAccessAllowed = nonSpecifiedColumnAccessAllowed;
}
public boolean isNonSpecifiedColumnAccessWarningOnly() { // since 1.2.7
return _nonSpecifiedColumnAccessWarningOnly;
}
// no setter because the option is complete in initialization process
// ===================================================================================
// SpecifyColumn Required
// ======================
public boolean isSpecifyColumnRequired() { // since 1.1.2
return _specifyColumnRequired;
}
public void setSpecifyColumnRequired(boolean specifyColumnRequired) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting specifyColumnRequired: " + specifyColumnRequired);
}
_specifyColumnRequired = specifyColumnRequired;
}
public SpecifyColumnRequiredExceptDeterminer getSpecifyColumnRequiredExceptDeterminer() { // since 1.1.7
return _specifyColumnRequiredExceptDeterminer;
}
public void setSpecifyColumnRequiredExceptDeterminer(SpecifyColumnRequiredExceptDeterminer specifyColumnRequiredExceptDeterminer) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting specifyColumnRequiredExceptDeterminer: " + specifyColumnRequiredExceptDeterminer);
}
_specifyColumnRequiredExceptDeterminer = specifyColumnRequiredExceptDeterminer;
}
public boolean isSpecifyColumnRequiredWarningOnly() { // since 1.2.0
return _specifyColumnRequiredWarningOnly;
}
public void setSpecifyColumnRequiredWarningOnly(boolean specifyColumnRequiredWarningOnly) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting specifyColumnRequiredWarningOnly: " + specifyColumnRequiredWarningOnly);
}
_specifyColumnRequiredWarningOnly = specifyColumnRequiredWarningOnly;
}
// ===================================================================================
// Column Null Object
// ==================
public boolean isColumnNullObjectAllowed() {
return _columnNullObjectAllowed;
}
/**
* Set whether column null object is allowed or not. <br>
* This configuration is only for ConditionBean.
* @param columnNullObjectAllowed The determination, true or false.
*/
public void setColumnNullObjectAllowed(boolean columnNullObjectAllowed) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting columnNullObjectAllowed: " + columnNullObjectAllowed);
}
_columnNullObjectAllowed = columnNullObjectAllowed;
}
public boolean isColumnNullObjectGearedToSpecify() {
return _columnNullObjectGearedToSpecify;
}
/**
* Set whether column null object is geared to specify or not. <br>
* This configuration is only for ConditionBean.
* @param columnNullObjectGearedToSpecify The determination, true or false.
*/
public void setColumnNullObjectGearedToSpecify(boolean columnNullObjectGearedToSpecify) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting columnNullObjectGearedToSpecify: " + columnNullObjectGearedToSpecify);
}
_columnNullObjectGearedToSpecify = columnNullObjectGearedToSpecify;
}
// ===================================================================================
// Date-time Precision
// ===================
public boolean isDatetimePrecisionTruncationOfCondition() {
return _datetimePrecisionTruncationOfCondition;
}
/**
* Set whether it truncates date-time precision of condition value or not. <br>
* This configuration is only for ConditionBean.
* @param datetimePrecisionTruncationOfCondition The determination, true or false.
*/
public void setDatetimePrecisionTruncationOfCondition(boolean datetimePrecisionTruncationOfCondition) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting datetimePrecisionTruncationOfCondition: " + datetimePrecisionTruncationOfCondition);
}
_datetimePrecisionTruncationOfCondition = datetimePrecisionTruncationOfCondition;
}
// ===================================================================================
// Select Index
// ============
public boolean isDisableSelectIndex() {
return _disableSelectIndex;
}
public void setDisableSelectIndex(boolean disableSelectIndex) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting disableSelectIndex: " + disableSelectIndex);
}
_disableSelectIndex = disableSelectIndex;
}
// ===================================================================================
// Query Update
// ============
public boolean isQueryUpdateCountPreCheck() {
return _queryUpdateCountPreCheck;
}
public void setQueryUpdateCountPreCheck(boolean queryUpdateCountPreCheck) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting queryUpdateCountPreCheck: " + queryUpdateCountPreCheck);
}
_queryUpdateCountPreCheck = queryUpdateCountPreCheck;
}
// ===================================================================================
// Query Log Level Info
// ====================
public void setQueryLogLevelInfo(boolean queryLogLevelInfo) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting queryLogLevelInfo: " + queryLogLevelInfo);
}
QLog.unlock();
QLog.setQueryLogLevelInfo(queryLogLevelInfo);
QLog.lock();
}
// ===================================================================================
// Execute Status Log Level Info
// =============================
public void setExecuteStatusLogLevelInfo(boolean executeStatusLogLevelInfo) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting executeStatusLogLevelInfo: " + executeStatusLogLevelInfo);
}
XLog.unlock();
XLog.setExecuteStatusLogLevelInfo(executeStatusLogLevelInfo);
XLog.lock();
}
// ===================================================================================
// Log Format
// ==========
public String getLogDatePattern() {
return _logDatePattern;
}
public void setLogDatePattern(String logDatePattern) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting logDatePattern: " + logDatePattern);
}
_logDatePattern = logDatePattern;
}
public String getLogTimestampPattern() {
return _logTimestampPattern;
}
public void setLogTimestampPattern(String logTimestampPattern) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting logTimestampPattern: " + logTimestampPattern);
}
_logTimestampPattern = logTimestampPattern;
}
public String getLogTimePattern() {
return _logTimePattern;
}
public void setLogTimePattern(String logTimePattern) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting logTimePattern: " + logTimePattern);
}
_logTimePattern = logTimePattern;
}
public BoundDateDisplayTimeZoneProvider getLogTimeZoneProvider() {
return _logTimeZoneProvider;
}
public void setLogTimeZoneProvider(BoundDateDisplayTimeZoneProvider logTimeZoneProvider) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting logTimeZoneProvider: " + logTimeZoneProvider);
}
_logTimeZoneProvider = logTimeZoneProvider;
}
// ===================================================================================
// Error Log Mask
// ==============
public ErrorLogMaskProvider getErrorLogMaskProvider() { // since 1.2.7
return _errorLogMaskProvider;
}
public void setErrorLogMaskProvider(ErrorLogMaskProvider errorLogMaskProvider) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting errorLogMaskProvider: " + errorLogMaskProvider);
}
_errorLogMaskProvider = errorLogMaskProvider;
}
// ===================================================================================
// Default StatementConfig
// =======================
public StatementConfig getDefaultStatementConfig() {
return _defaultStatementConfig;
}
public void setDefaultStatementConfig(StatementConfig defaultStatementConfig) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting defaultStatementConfig: " + defaultStatementConfig);
}
_defaultStatementConfig = defaultStatementConfig;
}
// ===================================================================================
// CursorSelect FetchSize
// ======================
public Integer getCursorSelectFetchSize() {
return _cursorSelectFetchSize;
}
public void setCursorSelectFetchSize(Integer cursorSelectFetchSize) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting cursorSelectFetchSize: " + cursorSelectFetchSize);
}
_cursorSelectFetchSize = cursorSelectFetchSize;
}
// ===================================================================================
// EntitySelect FetchSize
// ======================
public Integer getEntitySelectFetchSize() {
return _entitySelectFetchSize;
}
public void setEntitySelectFetchSize(Integer entitySelectFetchSize) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting entitySelectFetchSize: " + entitySelectFetchSize);
}
_entitySelectFetchSize = entitySelectFetchSize;
}
// ===================================================================================
// PagingSelect FetchSize
// ======================
public boolean isUsePagingByCursorSkipSynchronizedFetchSize() {
return _usePagingByCursorSkipSynchronizedFetchSize;
}
public void setUsePagingByCursorSkipSynchronizedFetchSize(boolean usePagingByCursorSkipSynchronizedFetchSize) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting usePagingByCursorSkipSynchronizedFetchSize: " + usePagingByCursorSkipSynchronizedFetchSize);
}
_usePagingByCursorSkipSynchronizedFetchSize = usePagingByCursorSkipSynchronizedFetchSize;
}
public Integer getFixedPagingByCursorSkipSynchronizedFetchSize() {
return _fixedPagingByCursorSkipSynchronizedFetchSize;
}
public void setFixedPagingByCursorSkipSynchronizedFetchSize(Integer fixedPagingByCursorSkipSynchronizedFetchSize) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting fixedPagingByCursorSkipSynchronizedFetchSize: " + fixedPagingByCursorSkipSynchronizedFetchSize);
}
_fixedPagingByCursorSkipSynchronizedFetchSize = fixedPagingByCursorSkipSynchronizedFetchSize;
}
// [DBFlute-0.9.0]
// ===================================================================================
// DataSource Handler
// ==================
/**
* @return The handler of data source. (NullAllowed)
*/
public DataSourceHandler getDataSourceHandler() {
return _dataSourceHandler;
}
/**
* @param dataSourceHandler The handler of data source. (NullAllowed)
*/
public void setDataSourceHandler(DataSourceHandler dataSourceHandler) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting dataSourceHandler: " + dataSourceHandler);
}
_dataSourceHandler = dataSourceHandler;
}
// [DBFlute-0.9.7.6]
// ===================================================================================
// PhysicalConnection Digger
// =========================
/**
* @return The digger of physical connection. (NotNull: has a default instance)
*/
public PhysicalConnectionDigger getPhysicalConnectionDigger() {
return _physicalConnectionDigger;
}
/**
* @param physicalConnectionDigger The digger of physical connection. (NotNull)
*/
public void setPhysicalConnectionDigger(PhysicalConnectionDigger physicalConnectionDigger) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting physicalConnectionDigger: " + physicalConnectionDigger);
}
if (physicalConnectionDigger == null) {
throw new IllegalArgumentException("The argument 'physicalConnectionDigger' should not be null.");
}
_physicalConnectionDigger = physicalConnectionDigger;
}
// [DBFlute-0.9.7.8]
// ===================================================================================
// SQLException Digger
// ===================
/**
* @return The digger of SQLException. (NotNull: has a default instance)
*/
public SQLExceptionDigger getSQLExceptionDigger() {
return _sqlExceptionDigger;
}
/**
* @param sqlExceptionDigger The digger of SQLException. (NotNull)
*/
public void setSQLExceptionDigger(SQLExceptionDigger sqlExceptionDigger) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting sqlExceptionDigger: " + sqlExceptionDigger);
}
if (sqlExceptionDigger == null) {
throw new IllegalArgumentException("The argument 'sqlExceptionDigger' should not be null.");
}
_sqlExceptionDigger = sqlExceptionDigger;
}
// ===================================================================================
// OutsideSql Package
// ==================
/**
* @return The package of outside SQL. (NullAllowed)
*/
public String getOutsideSqlPackage() {
return _outsideSqlPackage;
}
/**
* @param outsideSqlPackage The package of outside SQL. (NullAllowed)
*/
public void setOutsideSqlPackage(String outsideSqlPackage) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting outsideSqlPackage: " + outsideSqlPackage);
}
_outsideSqlPackage = outsideSqlPackage;
}
// [DBFlute-1.1.0]
// ===================================================================================
// Mapping Date TimeZone
// =====================
public MappingDateTimeZoneProvider getMappingDateTimeZoneProvider() { // since 1.1.0
return _mappingDateTimeZoneProvider;
}
public void setMappingDateTimeZoneProvider(MappingDateTimeZoneProvider mappingDateTimeZoneProvider) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting mappingDateTimeZoneProvider: " + mappingDateTimeZoneProvider);
}
_mappingDateTimeZoneProvider = mappingDateTimeZoneProvider;
}
// [DBFlute-0.9.6.4]
// ===================================================================================
// Sequence Cache
// ==============
/**
* @return The key generator of sequence cache. (NullAllowed)
*/
public SequenceCacheKeyGenerator getSequenceCacheKeyGenerator() {
return _sequenceCacheKeyGenerator;
}
/**
* @param sequenceCacheKeyGenerator The key generator of sequence cache. (NullAllowed)
*/
public void setSequenceCacheKeyGenerator(SequenceCacheKeyGenerator sequenceCacheKeyGenerator) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting sequenceCacheKeyGenerator: " + sequenceCacheKeyGenerator);
}
_sequenceCacheKeyGenerator = sequenceCacheKeyGenerator;
}
// [DBFlute-0.9.6.9]
// ===================================================================================
// SqlClause Creator
// =================
/**
* @return The creator of SQL clause. (NullAllowed)
*/
public SqlClauseCreator getSqlClauseCreator() {
return _sqlClauseCreator;
}
/**
* @param sqlClauseCreator The creator of SQL clause. (NullAllowed)
*/
public void setSqlClauseCreator(SqlClauseCreator sqlClauseCreator) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting sqlClauseCreator: " + sqlClauseCreator);
}
_sqlClauseCreator = sqlClauseCreator;
}
// [DBFlute-0.9.7.6]
// ===================================================================================
// TableSqlName Filter
// ===================
/**
* @return The SQL name filter for table. (NullAllowed)
*/
public SqlNameFilter getTableSqlNameFilter() {
return _tableSqlNameFilter;
}
/**
* Set the SQL name filter for table. <br>
* This setting should be called before container's initialization.
* (its exact meaning is: before class loading of DBMeta for table)
* @param tableSqlNameFilter The SQL name filter for table. (NullAllowed)
*/
public void setTableSqlNameFilter(SqlNameFilter tableSqlNameFilter) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting tableSqlNameFilter: " + tableSqlNameFilter);
}
_tableSqlNameFilter = tableSqlNameFilter;
}
// [DBFlute-0.9.7.0]
// ===================================================================================
// OutsideSql Executor
// ===================
public OutsideSqlExecutorFactory getOutsideSqlExecutorFactory() {
return _outsideSqlExecutorFactory;
}
public void setOutsideSqlExecutorFactory(OutsideSqlExecutorFactory outsideSqlExecutorFactory) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting outsideSqlExecutorFactory: " + outsideSqlExecutorFactory);
}
_outsideSqlExecutorFactory = outsideSqlExecutorFactory;
}
// [DBFlute-0.9.7.0]
// ===================================================================================
// Geared Cipher Manager
// =====================
public GearedCipherManager getGearedCipherManager() {
return _gearedCipherManager;
}
public void setGearedCipherManager(GearedCipherManager gearedCipherManager) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting gearedCipherManager: " + gearedCipherManager);
}
_gearedCipherManager = gearedCipherManager;
}
// ===================================================================================
// Database Dependency
// ===================
// ===================================================================================
// Internal Debug
// ==============
public boolean isInternalDebug() {
return _internalDebug;
}
public void setInternalDebug(boolean internalDebug) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Setting internalDebug: " + internalDebug);
}
_internalDebug = internalDebug;
}
// ===================================================================================
// Value Type
// ==========
/**
* Register the basic value type. <br>
* This setting is shared per DBMS in the same class loader.
* @param keyType The type as key. (NotNull)
* @param valueType The basic value type. (NotNull)
*/
public void registerBasicValueType(Class<?> keyType, ValueType valueType) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Registering basic valueType: " + keyType + " = " + valueType);
}
TnValueTypes.registerBasicValueType(currentDBDef(), keyType, valueType);
}
public void removeBasicValueType(Class<?> keyType) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Removing basic valueType: " + keyType);
}
TnValueTypes.removeBasicValueType(currentDBDef(), keyType);
}
/**
* Register the plug-in value type. <br>
* This setting is shared per DBMS in the same class loader.
* @param keyName The name as key. (NotNull)
* @param valueType The plug-in value type. (NotNull)
*/
public void registerPluginValueType(String keyName, ValueType valueType) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Registering plug-in valueType: " + keyName + " = " + valueType);
}
TnValueTypes.registerPluginValueType(currentDBDef(), keyName, valueType);
}
public void removePluginValueType(String keyName) {
assertUnlocked();
if (_log.isInfoEnabled()) {
_log.info("...Removing plug-in valueType: keyName=" + keyName);
}
TnValueTypes.removePluginValueType(currentDBDef(), keyName);
}
// ===================================================================================
// Configuration Lock
// ==================
public void lock() {
if (_locked) {
return;
}
if (_log.isInfoEnabled()) {
_log.info("...Locking the configuration of DBFlute");
}
_locked = true;
}
public void unlock() {
if (!_locked) {
return;
}
if (_log.isInfoEnabled()) {
_log.info("...Unlocking the configuration of DBFlute");
}
_locked = false;
}
public boolean isLocked() {
return _locked;
}
protected void assertUnlocked() {
if (!isLocked()) {
return;
}
throw new IllegalDBFluteConfigAccessException("The configuration of DBFlute is locked.");
}
// ===================================================================================
// Assist Helper
// =============
protected DBDef currentDBDef() {
return DBCurrent.getInstance().currentDBDef();
}
protected boolean isCurrentDBDef(DBDef currentDBDef) {
return DBCurrent.getInstance().isCurrentDBDef(currentDBDef);
}
// ===================================================================================
// Implemented Class
// =================
// -----------------------------------------------------
// Spring
// ------
public static class SpringTransactionalDataSourceHandler implements DataSourceHandler {
public Connection getConnection(DataSource ds) throws SQLException {
final Connection conn = getConnectionFromUtils(ds);
if (isConnectionTransactional(conn, ds)) {
return new NotClosingConnectionWrapper(conn);
} else {
return conn;
}
}
public Connection getConnectionFromUtils(DataSource ds) {
return DataSourceUtils.getConnection(ds);
}
public boolean isConnectionTransactional(Connection conn, DataSource ds) {
return DataSourceUtils.isConnectionTransactional(conn, ds);
}
}
// -----------------------------------------------------
// Physical Connection
// -------------------
public static class ImplementedPhysicalConnectionDigger implements PhysicalConnectionDigger {
public Connection digUp(Connection conn) throws SQLException {
Connection digged = unwrap(conn);
digged = resolveCommonsDBCP(digged);
return digged;
}
protected Connection unwrap(Connection conn) {
if (conn instanceof NotClosingConnectionWrapper) {
return ((NotClosingConnectionWrapper)conn).getActualConnection();
}
return conn;
}
protected Connection resolveCommonsDBCP(Connection conn) {
Connection resolved = conn;
if ("org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper".equals(resolved.getClass().getName())) {
resolved = getFieldConnection(resolved, "delegate");
}
if ("org.apache.commons.dbcp.PoolableConnection".equals(resolved.getClass().getName())) {
resolved = getFieldConnection(resolved, "_conn");
}
return resolved;
}
protected Connection getFieldConnection(Connection conn, String fieldName) {
Field field = DfReflectionUtil.getWholeField(conn.getClass(), fieldName);
return (Connection)DfReflectionUtil.getValueForcedly(field, conn);
}
}
// -----------------------------------------------------
// SQLException
// ------------
public static class ImplementedSQLExceptionDigger implements SQLExceptionDigger {
public SQLException digUp(Throwable cause) {
SQLException defaultFound = resolveDefault(cause);
if (defaultFound != null) {
return defaultFound;
}
return null;
}
protected SQLException resolveDefault(Throwable cause) {
Throwable nestedCause = cause.getCause();
if (nestedCause instanceof SQLException) {
return (SQLException)nestedCause;
}
return null;
}
}
// ===================================================================================
// Very Internal
// =============
// very internal (for suppressing warn about 'Not Use Import')
protected String xTms() { return Timestamp.class.getName(); }
protected String xDSc() { return DataSource.class.getName(); }
protected String xSQLEx() { return SQLException.class.getName(); }
protected String xDSqB() { return DisplaySqlBuilder.class.getName(); }
}
| [
"dbflute@gmail.com"
] | dbflute@gmail.com |
52680a19ea7d6c7a98b39daf8e9807f828021502 | c7233ae88a6b6393e44be192eb765376cd317c91 | /src/com/android/phone/InCallScreen.java | 26733ed54cded6b2a7567bd11a6d0c0ed0fec719 | [
"Apache-2.0"
] | permissive | teamgummy/packages_apps_Phone | 8cfcd3fb7540a9cfa529a0a2be36ff9342ac4b63 | 22d54c03def99b0ad32d8ae8b5c157ee1c0daa3e | refs/heads/master | 2020-06-04T15:42:33.107294 | 2012-03-29T16:10:33 | 2012-03-29T16:10:33 | 3,446,209 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 202,592 | 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 com.android.phone;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.os.AsyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.telephony.ServiceState;
import android.text.TextUtils;
import android.text.method.DialerKeyListener;
import android.util.EventLog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.CallManager;
import com.android.internal.telephony.Connection;
import com.android.internal.telephony.MmiCode;
import com.android.internal.telephony.Phone;
import com.android.phone.Constants.CallStatusCode;
import com.android.phone.InCallUiState.InCallScreenMode;
import com.android.phone.OtaUtils.CdmaOtaInCallScreenUiState;
import com.android.phone.OtaUtils.CdmaOtaScreenState;
import java.util.List;
/**
* Phone app "in call" screen.
*/
public class InCallScreen extends Activity
implements View.OnClickListener {
private static final String LOG_TAG = "InCallScreen";
private static final boolean DBG =
(PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2);
/**
* Intent extra used to specify whether the DTMF dialpad should be
* initially visible when bringing up the InCallScreen. (If this
* extra is present, the dialpad will be initially shown if the extra
* has the boolean value true, and initially hidden otherwise.)
*/
// TODO: Should be EXTRA_SHOW_DIALPAD for consistency.
static final String SHOW_DIALPAD_EXTRA = "com.android.phone.ShowDialpad";
/**
* Intent extra to specify the package name of the gateway
* provider. Used to get the name displayed in the in-call screen
* during the call setup. The value is a string.
*/
// TODO: This extra is currently set by the gateway application as
// a temporary measure. Ultimately, the framework will securely
// set it.
/* package */ static final String EXTRA_GATEWAY_PROVIDER_PACKAGE =
"com.android.phone.extra.GATEWAY_PROVIDER_PACKAGE";
/**
* Intent extra to specify the URI of the provider to place the
* call. The value is a string. It holds the gateway address
* (phone gateway URL should start with the 'tel:' scheme) that
* will actually be contacted to call the number passed in the
* intent URL or in the EXTRA_PHONE_NUMBER extra.
*/
// TODO: Should the value be a Uri (Parcelable)? Need to make sure
// MMI code '#' don't get confused as URI fragments.
/* package */ static final String EXTRA_GATEWAY_URI =
"com.android.phone.extra.GATEWAY_URI";
// Amount of time (in msec) that we display the "Call ended" state.
// The "short" value is for calls ended by the local user, and the
// "long" value is for calls ended by the remote caller.
private static final int CALL_ENDED_SHORT_DELAY = 200; // msec
private static final int CALL_ENDED_LONG_DELAY = 2000; // msec
// Amount of time that we display the PAUSE alert Dialog showing the
// post dial string yet to be send out to the n/w
private static final int PAUSE_PROMPT_DIALOG_TIMEOUT = 2000; //msec
// Amount of time that we display the provider's overlay if applicable.
private static final int PROVIDER_OVERLAY_TIMEOUT = 5000; // msec
// These are values for the settings of the auto retry mode:
// 0 = disabled
// 1 = enabled
// TODO (Moto):These constants don't really belong here,
// they should be moved to Settings where the value is being looked up in the first place
static final int AUTO_RETRY_OFF = 0;
static final int AUTO_RETRY_ON = 1;
// Message codes; see mHandler below.
// Note message codes < 100 are reserved for the PhoneApp.
private static final int PHONE_STATE_CHANGED = 101;
private static final int PHONE_DISCONNECT = 102;
private static final int EVENT_HEADSET_PLUG_STATE_CHANGED = 103;
private static final int POST_ON_DIAL_CHARS = 104;
private static final int WILD_PROMPT_CHAR_ENTERED = 105;
private static final int ADD_VOICEMAIL_NUMBER = 106;
private static final int DONT_ADD_VOICEMAIL_NUMBER = 107;
private static final int DELAYED_CLEANUP_AFTER_DISCONNECT = 108;
private static final int SUPP_SERVICE_FAILED = 110;
private static final int ALLOW_SCREEN_ON = 112;
private static final int REQUEST_UPDATE_BLUETOOTH_INDICATION = 114;
private static final int PHONE_CDMA_CALL_WAITING = 115;
private static final int REQUEST_CLOSE_SPC_ERROR_NOTICE = 118;
private static final int REQUEST_CLOSE_OTA_FAILURE_NOTICE = 119;
private static final int EVENT_PAUSE_DIALOG_COMPLETE = 120;
private static final int EVENT_HIDE_PROVIDER_OVERLAY = 121; // Time to remove the overlay.
private static final int REQUEST_UPDATE_SCREEN = 122;
private static final int PHONE_INCOMING_RING = 123;
private static final int PHONE_NEW_RINGING_CONNECTION = 124;
// When InCallScreenMode is UNDEFINED set the default action
// to ACTION_UNDEFINED so if we are resumed the activity will
// know its undefined. In particular checkIsOtaCall will return
// false.
public static final String ACTION_UNDEFINED = "com.android.phone.InCallScreen.UNDEFINED";
/** Status codes returned from syncWithPhoneState(). */
private enum SyncWithPhoneStateStatus {
/**
* Successfully updated our internal state based on the telephony state.
*/
SUCCESS,
/**
* There was no phone state to sync with (i.e. the phone was
* completely idle). In most cases this means that the
* in-call UI shouldn't be visible in the first place, unless
* we need to remain in the foreground while displaying an
* error message.
*/
PHONE_NOT_IN_USE
}
private boolean mRegisteredForPhoneStates;
private PhoneApp mApp;
private CallManager mCM;
// TODO: need to clean up all remaining uses of mPhone.
// (There may be more than one Phone instance on the device, so it's wrong
// to just keep a single mPhone field. Instead, any time we need a Phone
// reference we should get it dynamically from the CallManager, probably
// based on the current foreground Call.)
private Phone mPhone;
private BluetoothHandsfree mBluetoothHandsfree;
private BluetoothHeadset mBluetoothHeadset;
private BluetoothAdapter mAdapter;
private boolean mBluetoothConnectionPending;
private long mBluetoothConnectionRequestTime;
// Main in-call UI ViewGroups
private ViewGroup mInCallPanel;
// Main in-call UI elements:
private CallCard mCallCard;
// UI controls:
private InCallControlState mInCallControlState;
private InCallTouchUi mInCallTouchUi;
private RespondViaSmsManager mRespondViaSmsManager; // see internalRespondViaSms()
private ManageConferenceUtils mManageConferenceUtils;
// DTMF Dialer controller and its view:
private DTMFTwelveKeyDialer mDialer;
private DTMFTwelveKeyDialerView mDialerView;
private EditText mWildPromptText;
// Various dialogs we bring up (see dismissAllDialogs()).
// TODO: convert these all to use the "managed dialogs" framework.
//
// The MMI started dialog can actually be one of 2 items:
// 1. An alert dialog if the MMI code is a normal MMI
// 2. A progress dialog if the user requested a USSD
private Dialog mMmiStartedDialog;
private AlertDialog mMissingVoicemailDialog;
private AlertDialog mGenericErrorDialog;
private AlertDialog mSuppServiceFailureDialog;
private AlertDialog mWaitPromptDialog;
private AlertDialog mWildPromptDialog;
private AlertDialog mCallLostDialog;
private AlertDialog mPausePromptDialog;
private AlertDialog mExitingECMDialog;
// NOTE: if you add a new dialog here, be sure to add it to dismissAllDialogs() also.
// ProgressDialog created by showProgressIndication()
private ProgressDialog mProgressDialog;
// TODO: If the Activity class ever provides an easy way to get the
// current "activity lifecycle" state, we can remove these flags.
private boolean mIsDestroyed = false;
private boolean mIsForegroundActivity = false;
private boolean mIsForegroundActivityForProximity = false;
private PowerManager mPowerManager;
// For use with Pause/Wait dialogs
private String mPostDialStrAfterPause;
private boolean mPauseInProgress = false;
// Info about the most-recently-disconnected Connection, which is used
// to determine what should happen when exiting the InCallScreen after a
// call. (This info is set by onDisconnect(), and used by
// delayedCleanupAfterDisconnect().)
private Connection.DisconnectCause mLastDisconnectCause;
/** In-call audio routing options; see switchInCallAudio(). */
public enum InCallAudioMode {
SPEAKER, // Speakerphone
BLUETOOTH, // Bluetooth headset (if available)
EARPIECE, // Handset earpiece (or wired headset, if connected)
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (mIsDestroyed) {
if (DBG) log("Handler: ignoring message " + msg + "; we're destroyed!");
return;
}
if (!mIsForegroundActivity) {
if (DBG) log("Handler: handling message " + msg + " while not in foreground");
// Continue anyway; some of the messages below *want* to
// be handled even if we're not the foreground activity
// (like DELAYED_CLEANUP_AFTER_DISCONNECT), and they all
// should at least be safe to handle if we're not in the
// foreground...
}
switch (msg.what) {
case SUPP_SERVICE_FAILED:
onSuppServiceFailed((AsyncResult) msg.obj);
break;
case PHONE_STATE_CHANGED:
onPhoneStateChanged((AsyncResult) msg.obj);
break;
case PHONE_DISCONNECT:
onDisconnect((AsyncResult) msg.obj);
break;
case EVENT_HEADSET_PLUG_STATE_CHANGED:
// Update the in-call UI, since some UI elements (such
// as the "Speaker" button) may change state depending on
// whether a headset is plugged in.
// TODO: A full updateScreen() is overkill here, since
// the value of PhoneApp.isHeadsetPlugged() only affects a
// single onscreen UI element. (But even a full updateScreen()
// is still pretty cheap, so let's keep this simple
// for now.)
updateScreen();
// Also, force the "audio mode" popup to refresh itself if
// it's visible, since one of its items is either "Wired
// headset" or "Handset earpiece" depending on whether the
// headset is plugged in or not.
mInCallTouchUi.refreshAudioModePopup(); // safe even if the popup's not active
break;
case PhoneApp.MMI_INITIATE:
onMMIInitiate((AsyncResult) msg.obj);
break;
case PhoneApp.MMI_CANCEL:
onMMICancel();
break;
// handle the mmi complete message.
// since the message display class has been replaced with
// a system dialog in PhoneUtils.displayMMIComplete(), we
// should finish the activity here to close the window.
case PhoneApp.MMI_COMPLETE:
// Check the code to see if the request is ready to
// finish, this includes any MMI state that is not
// PENDING.
MmiCode mmiCode = (MmiCode) ((AsyncResult) msg.obj).result;
// if phone is a CDMA phone display feature code completed message
int phoneType = mPhone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
PhoneUtils.displayMMIComplete(mPhone, mApp, mmiCode, null, null);
} else if (phoneType == Phone.PHONE_TYPE_GSM) {
if (mmiCode.getState() != MmiCode.State.PENDING) {
if (DBG) log("Got MMI_COMPLETE, finishing InCallScreen...");
endInCallScreenSession();
}
}
break;
case POST_ON_DIAL_CHARS:
handlePostOnDialChars((AsyncResult) msg.obj, (char) msg.arg1);
break;
case ADD_VOICEMAIL_NUMBER:
addVoiceMailNumberPanel();
break;
case DONT_ADD_VOICEMAIL_NUMBER:
dontAddVoiceMailNumber();
break;
case DELAYED_CLEANUP_AFTER_DISCONNECT:
delayedCleanupAfterDisconnect();
break;
case ALLOW_SCREEN_ON:
if (VDBG) log("ALLOW_SCREEN_ON message...");
// Undo our previous call to preventScreenOn(true).
// (Note this will cause the screen to turn on
// immediately, if it's currently off because of a
// prior preventScreenOn(true) call.)
mApp.preventScreenOn(false);
break;
case REQUEST_UPDATE_BLUETOOTH_INDICATION:
if (VDBG) log("REQUEST_UPDATE_BLUETOOTH_INDICATION...");
// The bluetooth headset state changed, so some UI
// elements may need to update. (There's no need to
// look up the current state here, since any UI
// elements that care about the bluetooth state get it
// directly from PhoneApp.showBluetoothIndication().)
updateScreen();
break;
case PHONE_CDMA_CALL_WAITING:
if (DBG) log("Received PHONE_CDMA_CALL_WAITING event ...");
Connection cn = mCM.getFirstActiveRingingCall().getLatestConnection();
// Only proceed if we get a valid connection object
if (cn != null) {
// Finally update screen with Call waiting info and request
// screen to wake up
updateScreen();
mApp.updateWakeState();
}
break;
case REQUEST_CLOSE_SPC_ERROR_NOTICE:
if (mApp.otaUtils != null) {
mApp.otaUtils.onOtaCloseSpcNotice();
}
break;
case REQUEST_CLOSE_OTA_FAILURE_NOTICE:
if (mApp.otaUtils != null) {
mApp.otaUtils.onOtaCloseFailureNotice();
}
break;
case EVENT_PAUSE_DIALOG_COMPLETE:
if (mPausePromptDialog != null) {
if (DBG) log("- DISMISSING mPausePromptDialog.");
mPausePromptDialog.dismiss(); // safe even if already dismissed
mPausePromptDialog = null;
}
break;
case EVENT_HIDE_PROVIDER_OVERLAY:
mApp.inCallUiState.providerOverlayVisible = false;
updateProviderOverlay(); // Clear the overlay.
break;
case REQUEST_UPDATE_SCREEN:
updateScreen();
break;
case PHONE_INCOMING_RING:
onIncomingRing();
break;
case PHONE_NEW_RINGING_CONNECTION:
onNewRingingConnection();
break;
default:
Log.wtf(LOG_TAG, "mHandler: unexpected message: " + msg);
break;
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
// Listen for ACTION_HEADSET_PLUG broadcasts so that we
// can update the onscreen UI when the headset state changes.
// if (DBG) log("mReceiver: ACTION_HEADSET_PLUG");
// if (DBG) log("==> intent: " + intent);
// if (DBG) log(" state: " + intent.getIntExtra("state", 0));
// if (DBG) log(" name: " + intent.getStringExtra("name"));
// send the event and add the state as an argument.
Message message = Message.obtain(mHandler, EVENT_HEADSET_PLUG_STATE_CHANGED,
intent.getIntExtra("state", 0), 0);
mHandler.sendMessage(message);
}
}
};
@Override
protected void onCreate(Bundle icicle) {
Log.i(LOG_TAG, "onCreate()... this = " + this);
Profiler.callScreenOnCreate();
super.onCreate(icicle);
// Make sure this is a voice-capable device.
if (!PhoneApp.sVoiceCapable) {
// There should be no way to ever reach the InCallScreen on a
// non-voice-capable device, since this activity is not exported by
// our manifest, and we explicitly disable any other external APIs
// like the CALL intent and ITelephony.showCallScreen().
// So the fact that we got here indicates a phone app bug.
Log.wtf(LOG_TAG, "onCreate() reached on non-voice-capable device");
finish();
return;
}
mApp = PhoneApp.getInstance();
mApp.setInCallScreenInstance(this);
// set this flag so this activity will stay in front of the keyguard
int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
if (mApp.getPhoneState() == Phone.State.OFFHOOK) {
// While we are in call, the in-call screen should dismiss the keyguard.
// This allows the user to press Home to go directly home without going through
// an insecure lock screen.
// But we do not want to do this if there is no active call so we do not
// bypass the keyguard if the call is not answered or declined.
flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
}
getWindow().addFlags(flags);
// Also put the system bar (if present on this device) into
// "lights out" mode any time we're the foreground activity.
WindowManager.LayoutParams params = getWindow().getAttributes();
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
getWindow().setAttributes(params);
setPhone(mApp.phone); // Sets mPhone
mCM = mApp.mCM;
log("- onCreate: phone state = " + mCM.getState());
mBluetoothHandsfree = mApp.getBluetoothHandsfree();
if (VDBG) log("- mBluetoothHandsfree: " + mBluetoothHandsfree);
if (mBluetoothHandsfree != null) {
// The PhoneApp only creates a BluetoothHandsfree instance in the
// first place if BluetoothAdapter.getDefaultAdapter()
// succeeds. So at this point we know the device is BT-capable.
mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapter.getProfileProxy(getApplicationContext(), mBluetoothProfileServiceListener,
BluetoothProfile.HEADSET);
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Inflate everything in incall_screen.xml and add it to the screen.
setContentView(R.layout.incall_screen);
initInCallScreen();
registerForPhoneStates();
// No need to change wake state here; that happens in onResume() when we
// are actually displayed.
// Handle the Intent we were launched with, but only if this is the
// the very first time we're being launched (ie. NOT if we're being
// re-initialized after previously being shut down.)
// Once we're up and running, any future Intents we need
// to handle will come in via the onNewIntent() method.
if (icicle == null) {
if (DBG) log("onCreate(): this is our very first launch, checking intent...");
internalResolveIntent(getIntent());
}
Profiler.callScreenCreated();
if (DBG) log("onCreate(): exit");
}
private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
mBluetoothHeadset = (BluetoothHeadset) proxy;
if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
}
public void onServiceDisconnected(int profile) {
mBluetoothHeadset = null;
}
};
/**
* Sets the Phone object used internally by the InCallScreen.
*
* In normal operation this is called from onCreate(), and the
* passed-in Phone object comes from the PhoneApp.
* For testing, test classes can use this method to
* inject a test Phone instance.
*/
/* package */ void setPhone(Phone phone) {
mPhone = phone;
}
@Override
protected void onResume() {
if (DBG) log("onResume()...");
super.onResume();
mIsForegroundActivity = true;
mIsForegroundActivityForProximity = true;
final InCallUiState inCallUiState = mApp.inCallUiState;
if (VDBG) inCallUiState.dumpState();
// Touch events are never considered "user activity" while the
// InCallScreen is active, so that unintentional touches won't
// prevent the device from going to sleep.
mApp.setIgnoreTouchUserActivity(true);
// Disable the status bar "window shade" the entire time we're on
// the in-call screen.
mApp.notificationMgr.statusBarHelper.enableExpandedView(false);
// ...and update the in-call notification too, since the status bar
// icon needs to be hidden while we're the foreground activity:
mApp.notificationMgr.updateInCallNotification();
// Listen for broadcast intents that might affect the onscreen UI.
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
// Keep a "dialer session" active when we're in the foreground.
// (This is needed to play DTMF tones.)
mDialer.startDialerSession();
// Restore various other state from the InCallUiState object:
// Update the onscreen dialpad state to match the InCallUiState.
if (inCallUiState.showDialpad) {
showDialpadInternal(false); // no "opening" animation
} else {
hideDialpadInternal(false); // no "closing" animation
}
//
// TODO: also need to load inCallUiState.dialpadDigits into the dialpad
// If there's a "Respond via SMS" popup still around since the
// last time we were the foreground activity, make sure it's not
// still active!
// (The popup should *never* be visible initially when we first
// come to the foreground; it only ever comes up in response to
// the user selecting the "SMS" option from the incoming call
// widget.)
if (mRespondViaSmsManager != null) {
mRespondViaSmsManager.dismissPopup(); // safe even if already dismissed
}
// Display an error / diagnostic indication if necessary.
//
// When the InCallScreen comes to the foreground, we normally we
// display the in-call UI in whatever state is appropriate based on
// the state of the telephony framework (e.g. an outgoing call in
// DIALING state, an incoming call, etc.)
//
// But if the InCallUiState has a "pending call status code" set,
// that means we need to display some kind of status or error
// indication to the user instead of the regular in-call UI. (The
// most common example of this is when there's some kind of
// failure while initiating an outgoing call; see
// CallController.placeCall().)
//
boolean handledStartupError = false;
if (inCallUiState.hasPendingCallStatusCode()) {
if (DBG) log("- onResume: need to show status indication!");
showStatusIndication(inCallUiState.getPendingCallStatusCode());
// Set handledStartupError to ensure that we won't bail out below.
// (We need to stay here in the InCallScreen so that the user
// is able to see the error dialog!)
handledStartupError = true;
}
// Set the volume control handler while we are in the foreground.
final boolean bluetoothConnected = isBluetoothAudioConnected();
if (bluetoothConnected) {
setVolumeControlStream(AudioManager.STREAM_BLUETOOTH_SCO);
} else {
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
takeKeyEvents(true);
// If an OTASP call is in progress, use the special OTASP-specific UI.
boolean inOtaCall = false;
if (TelephonyCapabilities.supportsOtasp(mPhone)) {
inOtaCall = checkOtaspStateOnResume();
}
if (!inOtaCall) {
// Always start off in NORMAL mode
setInCallScreenMode(InCallScreenMode.NORMAL);
}
// Before checking the state of the CallManager, clean up any
// connections in the DISCONNECTED state.
// (The DISCONNECTED state is used only to drive the "call ended"
// UI; it's totally useless when *entering* the InCallScreen.)
mCM.clearDisconnected();
// Update the onscreen UI to reflect the current telephony state.
SyncWithPhoneStateStatus status = syncWithPhoneState();
// Note there's no need to call updateScreen() here;
// syncWithPhoneState() already did that if necessary.
if (status != SyncWithPhoneStateStatus.SUCCESS) {
if (DBG) log("- onResume: syncWithPhoneState failed! status = " + status);
// Couldn't update the UI, presumably because the phone is totally
// idle.
// Even though the phone is idle, though, we do still need to
// stay here on the InCallScreen if we're displaying an
// error dialog (see "showStatusIndication()" above).
if (handledStartupError) {
// Stay here for now. We'll eventually leave the
// InCallScreen when the user presses the dialog's OK
// button (see bailOutAfterErrorDialog()), or when the
// progress indicator goes away.
Log.i(LOG_TAG, " ==> syncWithPhoneState failed, but staying here anyway.");
} else {
// The phone is idle, and we did NOT handle a
// startup error during this pass thru onResume.
//
// This basically means that we're being resumed because of
// some action *other* than a new intent. (For example,
// the user pressing POWER to wake up the device, causing
// the InCallScreen to come back to the foreground.)
//
// In this scenario we do NOT want to stay here on the
// InCallScreen: we're not showing any useful info to the
// user (like a dialog), and the in-call UI itself is
// useless if there's no active call. So bail out.
Log.i(LOG_TAG, " ==> syncWithPhoneState failed; bailing out!");
dismissAllDialogs();
// Force the InCallScreen to truly finish(), rather than just
// moving it to the back of the activity stack (which is what
// our finish() method usually does.)
// This is necessary to avoid an obscure scenario where the
// InCallScreen can get stuck in an inconsistent state, somehow
// causing a *subsequent* outgoing call to fail (bug 4172599).
endInCallScreenSession(true /* force a real finish() call */);
return;
}
} else if (TelephonyCapabilities.supportsOtasp(mPhone)) {
if (inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL ||
inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED) {
if (mInCallPanel != null) mInCallPanel.setVisibility(View.GONE);
updateScreen();
return;
}
}
// InCallScreen is now active.
EventLog.writeEvent(EventLogTags.PHONE_UI_ENTER);
// Update the poke lock and wake lock when we move to
// the foreground.
//
// But we need to do something special if we're coming
// to the foreground while an incoming call is ringing:
if (mCM.getState() == Phone.State.RINGING) {
// If the phone is ringing, we *should* already be holding a
// full wake lock (which we would have acquired before
// firing off the intent that brought us here; see
// CallNotifier.showIncomingCall().)
//
// We also called preventScreenOn(true) at that point, to
// avoid cosmetic glitches while we were being launched.
// So now we need to post an ALLOW_SCREEN_ON message to
// (eventually) undo the prior preventScreenOn(true) call.
//
// (In principle we shouldn't do this until after our first
// layout/draw pass. But in practice, the delay caused by
// simply waiting for the end of the message queue is long
// enough to avoid any flickering of the lock screen before
// the InCallScreen comes up.)
if (VDBG) log("- posting ALLOW_SCREEN_ON message...");
mHandler.removeMessages(ALLOW_SCREEN_ON);
mHandler.sendEmptyMessage(ALLOW_SCREEN_ON);
// TODO: There ought to be a more elegant way of doing this,
// probably by having the PowerManager and ActivityManager
// work together to let apps request that the screen on/off
// state be synchronized with the Activity lifecycle.
// (See bug 1648751.)
} else {
// The phone isn't ringing; this is either an outgoing call, or
// we're returning to a call in progress. There *shouldn't* be
// any prior preventScreenOn(true) call that we need to undo,
// but let's do this just to be safe:
mApp.preventScreenOn(false);
}
mApp.updateWakeState();
// Restore the mute state if the last mute state change was NOT
// done by the user.
if (mApp.getRestoreMuteOnInCallResume()) {
// Mute state is based on the foreground call
PhoneUtils.restoreMuteState();
mApp.setRestoreMuteOnInCallResume(false);
}
Profiler.profileViewCreate(getWindow(), InCallScreen.class.getName());
if (VDBG) log("onResume() done.");
}
// onPause is guaranteed to be called when the InCallScreen goes
// in the background.
@Override
protected void onPause() {
if (DBG) log("onPause()...");
super.onPause();
if (mPowerManager.isScreenOn()) {
mIsForegroundActivityForProximity = false;
}
mIsForegroundActivity = false;
// Force a clear of the provider overlay' frame. Since the
// overlay is removed using a timed message, it is
// possible we missed it if the prev call was interrupted.
mApp.inCallUiState.providerOverlayVisible = false;
updateProviderOverlay();
// A safety measure to disable proximity sensor in case call failed
// and the telephony state did not change.
mApp.setBeginningCall(false);
// Make sure the "Manage conference" chronometer is stopped when
// we move away from the foreground.
mManageConferenceUtils.stopConferenceTime();
// as a catch-all, make sure that any dtmf tones are stopped
// when the UI is no longer in the foreground.
mDialer.onDialerKeyUp(null);
// Release any "dialer session" resources, now that we're no
// longer in the foreground.
mDialer.stopDialerSession();
// If the device is put to sleep as the phone call is ending,
// we may see cases where the DELAYED_CLEANUP_AFTER_DISCONNECT
// event gets handled AFTER the device goes to sleep and wakes
// up again.
// This is because it is possible for a sleep command
// (executed with the End Call key) to come during the 2
// seconds that the "Call Ended" screen is up. Sleep then
// pauses the device (including the cleanup event) and
// resumes the event when it wakes up.
// To fix this, we introduce a bit of code that pushes the UI
// to the background if we pause and see a request to
// DELAYED_CLEANUP_AFTER_DISCONNECT.
// Note: We can try to finish directly, by:
// 1. Removing the DELAYED_CLEANUP_AFTER_DISCONNECT messages
// 2. Calling delayedCleanupAfterDisconnect directly
// However, doing so can cause problems between the phone
// app and the keyguard - the keyguard is trying to sleep at
// the same time that the phone state is changing. This can
// end up causing the sleep request to be ignored.
if (mHandler.hasMessages(DELAYED_CLEANUP_AFTER_DISCONNECT)
&& mCM.getState() != Phone.State.RINGING) {
log("DELAYED_CLEANUP_AFTER_DISCONNECT detected, moving UI to background.");
endInCallScreenSession();
}
EventLog.writeEvent(EventLogTags.PHONE_UI_EXIT);
// Dismiss any dialogs we may have brought up, just to be 100%
// sure they won't still be around when we get back here.
dismissAllDialogs();
// Re-enable the status bar (which we disabled in onResume().)
mApp.notificationMgr.statusBarHelper.enableExpandedView(true);
// ...and the in-call notification too:
mApp.notificationMgr.updateInCallNotification();
// ...and *always* reset the system bar back to its normal state
// when leaving the in-call UI.
// (While we're the foreground activity, we disable navigation in
// some call states; see InCallTouchUi.updateState().)
mApp.notificationMgr.statusBarHelper.enableSystemBarNavigation(true);
// Unregister for broadcast intents. (These affect the visible UI
// of the InCallScreen, so we only care about them while we're in the
// foreground.)
unregisterReceiver(mReceiver);
// Re-enable "user activity" for touch events.
// We actually do this slightly *after* onPause(), to work around a
// race condition where a touch can come in after we've paused
// but before the device actually goes to sleep.
// TODO: The PowerManager itself should prevent this from happening.
mHandler.postDelayed(new Runnable() {
public void run() {
mApp.setIgnoreTouchUserActivity(false);
}
}, 500);
// Make sure we revert the poke lock and wake lock when we move to
// the background.
mApp.updateWakeState();
// clear the dismiss keyguard flag so we are back to the default state
// when we next resume
updateKeyguardPolicy(false);
}
@Override
protected void onStop() {
if (DBG) log("onStop()...");
super.onStop();
stopTimer();
Phone.State state = mCM.getState();
if (DBG) log("onStop: state = " + state);
if (state == Phone.State.IDLE) {
// when OTA Activation, OTA Success/Failure dialog or OTA SPC
// failure dialog is running, do not destroy inCallScreen. Because call
// is already ended and dialog will not get redrawn on slider event.
if ((mApp.cdmaOtaProvisionData != null) && (mApp.cdmaOtaScreenState != null)
&& ((mApp.cdmaOtaScreenState.otaScreenState !=
CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION)
&& (mApp.cdmaOtaScreenState.otaScreenState !=
CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG)
&& (!mApp.cdmaOtaProvisionData.inOtaSpcState))) {
// we don't want the call screen to remain in the activity history
// if there are not active or ringing calls.
if (DBG) log("- onStop: calling finish() to clear activity history...");
moveTaskToBack(true);
if (mApp.otaUtils != null) {
mApp.otaUtils.cleanOtaScreen(true);
}
}
}
}
@Override
protected void onDestroy() {
Log.i(LOG_TAG, "onDestroy()... this = " + this);
super.onDestroy();
// Set the magic flag that tells us NOT to handle any handler
// messages that come in asynchronously after we get destroyed.
mIsDestroyed = true;
mApp.setInCallScreenInstance(null);
// Clear out the InCallScreen references in various helper objects
// (to let them know we've been destroyed).
if (mCallCard != null) {
mCallCard.setInCallScreenInstance(null);
}
if (mInCallTouchUi != null) {
mInCallTouchUi.setInCallScreenInstance(null);
}
if (mRespondViaSmsManager != null) {
mRespondViaSmsManager.setInCallScreenInstance(null);
}
mDialer.clearInCallScreenReference();
mDialer = null;
unregisterForPhoneStates();
// No need to change wake state here; that happens in onPause() when we
// are moving out of the foreground.
if (mBluetoothHeadset != null) {
mAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
mBluetoothHeadset = null;
}
// Dismiss all dialogs, to be absolutely sure we won't leak any of
// them while changing orientation.
dismissAllDialogs();
// If there's an OtaUtils instance around, clear out its
// references to our internal widgets.
if (mApp.otaUtils != null) {
mApp.otaUtils.clearUiWidgets();
}
}
/**
* Dismisses the in-call screen.
*
* We never *really* finish() the InCallScreen, since we don't want to
* get destroyed and then have to be re-created from scratch for the
* next call. Instead, we just move ourselves to the back of the
* activity stack.
*
* This also means that we'll no longer be reachable via the BACK
* button (since moveTaskToBack() puts us behind the Home app, but the
* home app doesn't allow the BACK key to move you any farther down in
* the history stack.)
*
* (Since the Phone app itself is never killed, this basically means
* that we'll keep a single InCallScreen instance around for the
* entire uptime of the device. This noticeably improves the UI
* responsiveness for incoming calls.)
*/
@Override
public void finish() {
if (DBG) log("finish()...");
moveTaskToBack(true);
}
/**
* End the current in call screen session.
*
* This must be called when an InCallScreen session has
* complete so that the next invocation via an onResume will
* not be in an old state.
*/
public void endInCallScreenSession() {
if (DBG) log("endInCallScreenSession()... phone state = " + mCM.getState());
endInCallScreenSession(false);
}
/**
* Internal version of endInCallScreenSession().
*
* @param forceFinish If true, force the InCallScreen to
* truly finish() rather than just calling moveTaskToBack().
* @see finish()
*/
private void endInCallScreenSession(boolean forceFinish) {
log("endInCallScreenSession(" + forceFinish + ")... phone state = " + mCM.getState());
if (forceFinish) {
Log.i(LOG_TAG, "endInCallScreenSession(): FORCING a call to super.finish()!");
super.finish(); // Call super.finish() rather than our own finish() method,
// which actually just calls moveTaskToBack().
} else {
moveTaskToBack(true);
}
setInCallScreenMode(InCallScreenMode.UNDEFINED);
}
/* package */ boolean isForegroundActivity() {
return mIsForegroundActivity;
}
/* package */ boolean isForegroundActivityForProximity() {
return mIsForegroundActivityForProximity;
}
/* package */ void updateKeyguardPolicy(boolean dismissKeyguard) {
if (dismissKeyguard) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
}
private void registerForPhoneStates() {
if (!mRegisteredForPhoneStates) {
mCM.registerForPreciseCallStateChanged(mHandler, PHONE_STATE_CHANGED, null);
mCM.registerForDisconnect(mHandler, PHONE_DISCONNECT, null);
mCM.registerForMmiInitiate(mHandler, PhoneApp.MMI_INITIATE, null);
// register for the MMI complete message. Upon completion,
// PhoneUtils will bring up a system dialog instead of the
// message display class in PhoneUtils.displayMMIComplete().
// We'll listen for that message too, so that we can finish
// the activity at the same time.
mCM.registerForMmiComplete(mHandler, PhoneApp.MMI_COMPLETE, null);
mCM.registerForCallWaiting(mHandler, PHONE_CDMA_CALL_WAITING, null);
mCM.registerForPostDialCharacter(mHandler, POST_ON_DIAL_CHARS, null);
mCM.registerForSuppServiceFailed(mHandler, SUPP_SERVICE_FAILED, null);
mCM.registerForIncomingRing(mHandler, PHONE_INCOMING_RING, null);
mCM.registerForNewRingingConnection(mHandler, PHONE_NEW_RINGING_CONNECTION, null);
mRegisteredForPhoneStates = true;
}
}
private void unregisterForPhoneStates() {
mCM.unregisterForPreciseCallStateChanged(mHandler);
mCM.unregisterForDisconnect(mHandler);
mCM.unregisterForMmiInitiate(mHandler);
mCM.unregisterForMmiComplete(mHandler);
mCM.unregisterForCallWaiting(mHandler);
mCM.unregisterForPostDialCharacter(mHandler);
mCM.unregisterForSuppServiceFailed(mHandler);
mCM.unregisterForIncomingRing(mHandler);
mCM.unregisterForNewRingingConnection(mHandler);
mRegisteredForPhoneStates = false;
}
/* package */ void updateAfterRadioTechnologyChange() {
if (DBG) Log.d(LOG_TAG, "updateAfterRadioTechnologyChange()...");
// Reset the call screen since the calls cannot be transferred
// across radio technologies.
resetInCallScreenMode();
// Unregister for all events from the old obsolete phone
unregisterForPhoneStates();
// (Re)register for all events relevant to the new active phone
registerForPhoneStates();
// And finally, refresh the onscreen UI. (Note that it's safe
// to call requestUpdateScreen() even if the radio change ended up
// causing us to exit the InCallScreen.)
requestUpdateScreen();
}
@Override
protected void onNewIntent(Intent intent) {
log("onNewIntent: intent = " + intent + ", phone state = " + mCM.getState());
// We're being re-launched with a new Intent. Since it's possible for a
// single InCallScreen instance to persist indefinitely (even if we
// finish() ourselves), this sequence can potentially happen any time
// the InCallScreen needs to be displayed.
// Stash away the new intent so that we can get it in the future
// by calling getIntent(). (Otherwise getIntent() will return the
// original Intent from when we first got created!)
setIntent(intent);
// Activities are always paused before receiving a new intent, so
// we can count on our onResume() method being called next.
// Just like in onCreate(), handle the intent.
internalResolveIntent(intent);
}
private void internalResolveIntent(Intent intent) {
if (intent == null || intent.getAction() == null) {
return;
}
String action = intent.getAction();
if (DBG) log("internalResolveIntent: action=" + action);
// In gingerbread and earlier releases, the InCallScreen used to
// directly handle certain intent actions that could initiate phone
// calls, namely ACTION_CALL and ACTION_CALL_EMERGENCY, and also
// OtaUtils.ACTION_PERFORM_CDMA_PROVISIONING.
//
// But it doesn't make sense to tie those actions to the InCallScreen
// (or especially to the *activity lifecycle* of the InCallScreen).
// Instead, the InCallScreen should only be concerned with running the
// onscreen UI while in a call. So we've now offloaded the call-control
// functionality to a new module called CallController, and OTASP calls
// are now launched from the OtaUtils startInteractiveOtasp() or
// startNonInteractiveOtasp() methods.
//
// So now, the InCallScreen is only ever launched using the ACTION_MAIN
// action, and (upon launch) performs no functionality other than
// displaying the UI in a state that matches the current telephony
// state.
if (action.equals(intent.ACTION_MAIN)) {
// This action is the normal way to bring up the in-call UI.
//
// Most of the interesting work of updating the onscreen UI (to
// match the current telephony state) happens in the
// syncWithPhoneState() => updateScreen() sequence that happens in
// onResume().
//
// But we do check here for one extra that can come along with the
// ACTION_MAIN intent:
if (intent.hasExtra(SHOW_DIALPAD_EXTRA)) {
// SHOW_DIALPAD_EXTRA can be used here to specify whether the DTMF
// dialpad should be initially visible. If the extra isn't
// present at all, we just leave the dialpad in its previous state.
boolean showDialpad = intent.getBooleanExtra(SHOW_DIALPAD_EXTRA, false);
if (VDBG) log("- internalResolveIntent: SHOW_DIALPAD_EXTRA: " + showDialpad);
// If SHOW_DIALPAD_EXTRA is specified, that overrides whatever
// the previous state of inCallUiState.showDialpad was.
mApp.inCallUiState.showDialpad = showDialpad;
}
// ...and in onResume() we'll update the onscreen dialpad state to
// match the InCallUiState.
return;
}
if (action.equals(OtaUtils.ACTION_DISPLAY_ACTIVATION_SCREEN)) {
// Bring up the in-call UI in the OTASP-specific "activate" state;
// see OtaUtils.startInteractiveOtasp(). Note that at this point
// the OTASP call has not been started yet; we won't actually make
// the call until the user presses the "Activate" button.
if (!TelephonyCapabilities.supportsOtasp(mPhone)) {
throw new IllegalStateException(
"Received ACTION_DISPLAY_ACTIVATION_SCREEN intent on non-OTASP-capable device: "
+ intent);
}
setInCallScreenMode(InCallScreenMode.OTA_NORMAL);
if ((mApp.cdmaOtaProvisionData != null)
&& (!mApp.cdmaOtaProvisionData.isOtaCallIntentProcessed)) {
mApp.cdmaOtaProvisionData.isOtaCallIntentProcessed = true;
mApp.cdmaOtaScreenState.otaScreenState =
CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION;
}
return;
}
// Various intent actions that should no longer come here directly:
if (action.equals(OtaUtils.ACTION_PERFORM_CDMA_PROVISIONING)) {
// This intent is now handled by the InCallScreenShowActivation
// activity, which translates it into a call to
// OtaUtils.startInteractiveOtasp().
throw new IllegalStateException(
"Unexpected ACTION_PERFORM_CDMA_PROVISIONING received by InCallScreen: "
+ intent);
} else if (action.equals(Intent.ACTION_CALL)
|| action.equals(Intent.ACTION_CALL_EMERGENCY)) {
// ACTION_CALL* intents go to the OutgoingCallBroadcaster, which now
// translates them into CallController.placeCall() calls rather than
// launching the InCallScreen directly.
throw new IllegalStateException("Unexpected CALL action received by InCallScreen: "
+ intent);
} else if (action.equals(ACTION_UNDEFINED)) {
// This action is only used for internal bookkeeping; we should
// never actually get launched with it.
Log.wtf(LOG_TAG, "internalResolveIntent: got launched with ACTION_UNDEFINED");
return;
} else {
Log.wtf(LOG_TAG, "internalResolveIntent: unexpected intent action: " + action);
// But continue the best we can (basically treating this case
// like ACTION_MAIN...)
return;
}
}
private void stopTimer() {
if (mCallCard != null) mCallCard.stopTimer();
}
private void initInCallScreen() {
if (VDBG) log("initInCallScreen()...");
// Have the WindowManager filter out touch events that are "too fat".
getWindow().addFlags(WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES);
mInCallPanel = (ViewGroup) findViewById(R.id.inCallPanel);
// Initialize the CallCard.
mCallCard = (CallCard) findViewById(R.id.callCard);
if (VDBG) log(" - mCallCard = " + mCallCard);
mCallCard.setInCallScreenInstance(this);
// Initialize the onscreen UI elements.
initInCallTouchUi();
// Helper class to keep track of enabledness/state of UI controls
mInCallControlState = new InCallControlState(this, mCM);
// Helper class to run the "Manage conference" UI
mManageConferenceUtils = new ManageConferenceUtils(this, mCM);
// The DTMF Dialpad.
// TODO: Don't inflate this until the first time it's needed.
ViewStub stub = (ViewStub)findViewById(R.id.dtmf_twelve_key_dialer_stub);
stub.inflate();
mDialerView = (DTMFTwelveKeyDialerView) findViewById(R.id.dtmf_twelve_key_dialer_view);
if (DBG) log("- Found dialerView: " + mDialerView);
// Sanity-check that (regardless of the device) at least the
// dialer view is present:
if (mDialerView == null) {
Log.e(LOG_TAG, "onCreate: couldn't find dialerView", new IllegalStateException());
}
// Finally, create the DTMFTwelveKeyDialer instance.
mDialer = new DTMFTwelveKeyDialer(this, mDialerView);
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
}
/**
* Returns true if the phone is "in use", meaning that at least one line
* is active (ie. off hook or ringing or dialing). Conversely, a return
* value of false means there's currently no phone activity at all.
*/
private boolean phoneIsInUse() {
return mCM.getState() != Phone.State.IDLE;
}
private boolean handleDialerKeyDown(int keyCode, KeyEvent event) {
if (VDBG) log("handleDialerKeyDown: keyCode " + keyCode + ", event " + event + "...");
// As soon as the user starts typing valid dialable keys on the
// keyboard (presumably to type DTMF tones) we start passing the
// key events to the DTMFDialer's onDialerKeyDown. We do so
// only if the okToDialDTMFTones() conditions pass.
if (okToDialDTMFTones()) {
return mDialer.onDialerKeyDown(event);
// TODO: If the dialpad isn't currently visible, maybe
// consider automatically bringing it up right now?
// (Just to make sure the user sees the digits widget...)
// But this probably isn't too critical since it's awkward to
// use the hard keyboard while in-call in the first place,
// especially now that the in-call UI is portrait-only...
}
return false;
}
@Override
public void onBackPressed() {
if (DBG) log("onBackPressed()...");
// To consume this BACK press, the code here should just do
// something and return. Otherwise, call super.onBackPressed() to
// get the default implementation (which simply finishes the
// current activity.)
if (mCM.hasActiveRingingCall()) {
// The Back key, just like the Home key, is always disabled
// while an incoming call is ringing. (The user *must* either
// answer or reject the call before leaving the incoming-call
// screen.)
if (DBG) log("BACK key while ringing: ignored");
// And consume this event; *don't* call super.onBackPressed().
return;
}
// BACK is also used to exit out of any "special modes" of the
// in-call UI:
if (mDialer.isOpened()) {
hideDialpadInternal(true); // do the "closing" animation
return;
}
if (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.MANAGE_CONFERENCE) {
// Hide the Manage Conference panel, return to NORMAL mode.
setInCallScreenMode(InCallScreenMode.NORMAL);
requestUpdateScreen();
return;
}
// Nothing special to do. Fall back to the default behavior.
super.onBackPressed();
}
/**
* Handles the green CALL key while in-call.
* @return true if we consumed the event.
*/
private boolean handleCallKey() {
// The green CALL button means either "Answer", "Unhold", or
// "Swap calls", or can be a no-op, depending on the current state
// of the Phone.
final boolean hasRingingCall = mCM.hasActiveRingingCall();
final boolean hasActiveCall = mCM.hasActiveFgCall();
final boolean hasHoldingCall = mCM.hasActiveBgCall();
int phoneType = mPhone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
// The green CALL button means either "Answer", "Swap calls/On Hold", or
// "Add to 3WC", depending on the current state of the Phone.
CdmaPhoneCallState.PhoneCallState currCallState =
mApp.cdmaPhoneCallState.getCurrentCallState();
if (hasRingingCall) {
//Scenario 1: Accepting the First Incoming and Call Waiting call
if (DBG) log("answerCall: First Incoming and Call Waiting scenario");
internalAnswerCall(); // Automatically holds the current active call,
// if there is one
} else if ((currCallState == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
&& (hasActiveCall)) {
//Scenario 2: Merging 3Way calls
if (DBG) log("answerCall: Merge 3-way call scenario");
// Merge calls
PhoneUtils.mergeCalls(mCM);
} else if (currCallState == CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
//Scenario 3: Switching between two Call waiting calls or drop the latest
// connection if in a 3Way merge scenario
if (DBG) log("answerCall: Switch btwn 2 calls scenario");
internalSwapCalls();
}
} else if ((phoneType == Phone.PHONE_TYPE_GSM)
|| (phoneType == Phone.PHONE_TYPE_SIP)) {
if (hasRingingCall) {
// If an incoming call is ringing, the CALL button is actually
// handled by the PhoneWindowManager. (We do this to make
// sure that we'll respond to the key even if the InCallScreen
// hasn't come to the foreground yet.)
//
// We'd only ever get here in the extremely rare case that the
// incoming call started ringing *after*
// PhoneWindowManager.interceptKeyTq() but before the event
// got here, or else if the PhoneWindowManager had some
// problem connecting to the ITelephony service.
Log.w(LOG_TAG, "handleCallKey: incoming call is ringing!"
+ " (PhoneWindowManager should have handled this key.)");
// But go ahead and handle the key as normal, since the
// PhoneWindowManager presumably did NOT handle it:
// There's an incoming ringing call: CALL means "Answer".
internalAnswerCall();
} else if (hasActiveCall && hasHoldingCall) {
// Two lines are in use: CALL means "Swap calls".
if (DBG) log("handleCallKey: both lines in use ==> swap calls.");
internalSwapCalls();
} else if (hasHoldingCall) {
// There's only one line in use, AND it's on hold.
// In this case CALL is a shortcut for "unhold".
if (DBG) log("handleCallKey: call on hold ==> unhold.");
PhoneUtils.switchHoldingAndActive(
mCM.getFirstActiveBgCall()); // Really means "unhold" in this state
} else {
// The most common case: there's only one line in use, and
// it's an active call (i.e. it's not on hold.)
// In this case CALL is a no-op.
// (This used to be a shortcut for "add call", but that was a
// bad idea because "Add call" is so infrequently-used, and
// because the user experience is pretty confusing if you
// inadvertently trigger it.)
if (VDBG) log("handleCallKey: call in foregound ==> ignoring.");
// But note we still consume this key event; see below.
}
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
// We *always* consume the CALL key, since the system-wide default
// action ("go to the in-call screen") is useless here.
return true;
}
boolean isKeyEventAcceptableDTMF (KeyEvent event) {
return (mDialer != null && mDialer.isKeyEventAcceptable(event));
}
/**
* Overriden to track relevant focus changes.
*
* If a key is down and some time later the focus changes, we may
* NOT recieve the keyup event; logically the keyup event has not
* occured in this window. This issue is fixed by treating a focus
* changed event as an interruption to the keydown, making sure
* that any code that needs to be run in onKeyUp is ALSO run here.
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// the dtmf tones should no longer be played
if (VDBG) log("onWindowFocusChanged(" + hasFocus + ")...");
if (!hasFocus && mDialer != null) {
if (VDBG) log("- onWindowFocusChanged: faking onDialerKeyUp()...");
mDialer.onDialerKeyUp(null);
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// if (DBG) log("onKeyUp(keycode " + keyCode + ")...");
// push input to the dialer.
if ((mDialer != null) && (mDialer.onDialerKeyUp(event))){
return true;
} else if (keyCode == KeyEvent.KEYCODE_CALL) {
// Always consume CALL to be sure the PhoneWindow won't do anything with it
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// if (DBG) log("onKeyDown(keycode " + keyCode + ")...");
switch (keyCode) {
case KeyEvent.KEYCODE_CALL:
boolean handled = handleCallKey();
if (!handled) {
Log.w(LOG_TAG, "InCallScreen should always handle KEYCODE_CALL in onKeyDown");
}
// Always consume CALL to be sure the PhoneWindow won't do anything with it
return true;
// Note there's no KeyEvent.KEYCODE_ENDCALL case here.
// The standard system-wide handling of the ENDCALL key
// (see PhoneWindowManager's handling of KEYCODE_ENDCALL)
// already implements exactly what the UI spec wants,
// namely (1) "hang up" if there's a current active call,
// or (2) "don't answer" if there's a current ringing call.
case KeyEvent.KEYCODE_CAMERA:
// Disable the CAMERA button while in-call since it's too
// easy to press accidentally.
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_MUTE:
if (mCM.getState() == Phone.State.RINGING) {
// If an incoming call is ringing, the VOLUME buttons are
// actually handled by the PhoneWindowManager. (We do
// this to make sure that we'll respond to them even if
// the InCallScreen hasn't come to the foreground yet.)
//
// We'd only ever get here in the extremely rare case that the
// incoming call started ringing *after*
// PhoneWindowManager.interceptKeyTq() but before the event
// got here, or else if the PhoneWindowManager had some
// problem connecting to the ITelephony service.
Log.w(LOG_TAG, "VOLUME key: incoming call is ringing!"
+ " (PhoneWindowManager should have handled this key.)");
// But go ahead and handle the key as normal, since the
// PhoneWindowManager presumably did NOT handle it:
internalSilenceRinger();
// As long as an incoming call is ringing, we always
// consume the VOLUME keys.
return true;
}
break;
case KeyEvent.KEYCODE_MUTE:
onMuteClick();
return true;
// Various testing/debugging features, enabled ONLY when VDBG == true.
case KeyEvent.KEYCODE_SLASH:
if (VDBG) {
log("----------- InCallScreen View dump --------------");
// Dump starting from the top-level view of the entire activity:
Window w = this.getWindow();
View decorView = w.getDecorView();
decorView.debug();
return true;
}
break;
case KeyEvent.KEYCODE_EQUALS:
if (VDBG) {
log("----------- InCallScreen call state dump --------------");
PhoneUtils.dumpCallState(mPhone);
PhoneUtils.dumpCallManager();
return true;
}
break;
case KeyEvent.KEYCODE_GRAVE:
if (VDBG) {
// Placeholder for other misc temp testing
log("------------ Temp testing -----------------");
return true;
}
break;
}
if (event.getRepeatCount() == 0 && handleDialerKeyDown(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Handle a failure notification for a supplementary service
* (i.e. conference, switch, separate, transfer, etc.).
*/
void onSuppServiceFailed(AsyncResult r) {
Phone.SuppService service = (Phone.SuppService) r.result;
if (DBG) log("onSuppServiceFailed: " + service);
int errorMessageResId;
switch (service) {
case SWITCH:
// Attempt to switch foreground and background/incoming calls failed
// ("Failed to switch calls")
errorMessageResId = R.string.incall_error_supp_service_switch;
break;
case SEPARATE:
// Attempt to separate a call from a conference call
// failed ("Failed to separate out call")
errorMessageResId = R.string.incall_error_supp_service_separate;
break;
case TRANSFER:
// Attempt to connect foreground and background calls to
// each other (and hanging up user's line) failed ("Call
// transfer failed")
errorMessageResId = R.string.incall_error_supp_service_transfer;
break;
case CONFERENCE:
// Attempt to add a call to conference call failed
// ("Conference call failed")
errorMessageResId = R.string.incall_error_supp_service_conference;
break;
case REJECT:
// Attempt to reject an incoming call failed
// ("Call rejection failed")
errorMessageResId = R.string.incall_error_supp_service_reject;
break;
case HANGUP:
// Attempt to release a call failed ("Failed to release call(s)")
errorMessageResId = R.string.incall_error_supp_service_hangup;
break;
case UNKNOWN:
default:
// Attempt to use a service we don't recognize or support
// ("Unsupported service" or "Selected service failed")
errorMessageResId = R.string.incall_error_supp_service_unknown;
break;
}
// mSuppServiceFailureDialog is a generic dialog used for any
// supp service failure, and there's only ever have one
// instance at a time. So just in case a previous dialog is
// still around, dismiss it.
if (mSuppServiceFailureDialog != null) {
if (DBG) log("- DISMISSING mSuppServiceFailureDialog.");
mSuppServiceFailureDialog.dismiss(); // It's safe to dismiss() a dialog
// that's already dismissed.
mSuppServiceFailureDialog = null;
}
mSuppServiceFailureDialog = new AlertDialog.Builder(this)
.setMessage(errorMessageResId)
.setPositiveButton(R.string.ok, null)
.create();
mSuppServiceFailureDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
mSuppServiceFailureDialog.show();
}
/**
* Something has changed in the phone's state. Update the UI.
*/
private void onPhoneStateChanged(AsyncResult r) {
Phone.State state = mCM.getState();
if (DBG) log("onPhoneStateChanged: current state = " + state);
// There's nothing to do here if we're not the foreground activity.
// (When we *do* eventually come to the foreground, we'll do a
// full update then.)
if (!mIsForegroundActivity) {
if (DBG) log("onPhoneStateChanged: Activity not in foreground! Bailing out...");
return;
}
// Update the onscreen UI.
// We use requestUpdateScreen() here (which posts a handler message)
// instead of calling updateScreen() directly, which allows us to avoid
// unnecessary work if multiple onPhoneStateChanged() events come in all
// at the same time.
requestUpdateScreen();
// Make sure we update the poke lock and wake lock when certain
// phone state changes occur.
mApp.updateWakeState();
}
/**
* Updates the UI after a phone connection is disconnected, as follows:
*
* - If this was a missed or rejected incoming call, and no other
* calls are active, dismiss the in-call UI immediately. (The
* CallNotifier will still create a "missed call" notification if
* necessary.)
*
* - With any other disconnect cause, if the phone is now totally
* idle, display the "Call ended" state for a couple of seconds.
*
* - Or, if the phone is still in use, stay on the in-call screen
* (and update the UI to reflect the current state of the Phone.)
*
* @param r r.result contains the connection that just ended
*/
private void onDisconnect(AsyncResult r) {
Connection c = (Connection) r.result;
Connection.DisconnectCause cause = c.getDisconnectCause();
if (DBG) log("onDisconnect: connection '" + c + "', cause = " + cause);
boolean currentlyIdle = !phoneIsInUse();
int autoretrySetting = AUTO_RETRY_OFF;
boolean phoneIsCdma = (mPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA);
if (phoneIsCdma) {
// Get the Auto-retry setting only if Phone State is IDLE,
// else let it stay as AUTO_RETRY_OFF
if (currentlyIdle) {
autoretrySetting = android.provider.Settings.System.getInt(mPhone.getContext().
getContentResolver(), android.provider.Settings.System.CALL_AUTO_RETRY, 0);
}
}
// for OTA Call, only if in OTA NORMAL mode, handle OTA END scenario
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL)
&& ((mApp.cdmaOtaProvisionData != null)
&& (!mApp.cdmaOtaProvisionData.inOtaSpcState))) {
setInCallScreenMode(InCallScreenMode.OTA_ENDED);
updateScreen();
return;
} else if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED)
|| ((mApp.cdmaOtaProvisionData != null)
&& mApp.cdmaOtaProvisionData.inOtaSpcState)) {
if (DBG) log("onDisconnect: OTA Call end already handled");
return;
}
// Any time a call disconnects, clear out the "history" of DTMF
// digits you typed (to make sure it doesn't persist from one call
// to the next.)
mDialer.clearDigits();
// Under certain call disconnected states, we want to alert the user
// with a dialog instead of going through the normal disconnect
// routine.
if (cause == Connection.DisconnectCause.CALL_BARRED) {
showGenericErrorDialog(R.string.callFailed_cb_enabled, false);
return;
} else if (cause == Connection.DisconnectCause.FDN_BLOCKED) {
showGenericErrorDialog(R.string.callFailed_fdn_only, false);
return;
} else if (cause == Connection.DisconnectCause.CS_RESTRICTED) {
showGenericErrorDialog(R.string.callFailed_dsac_restricted, false);
return;
} else if (cause == Connection.DisconnectCause.CS_RESTRICTED_EMERGENCY) {
showGenericErrorDialog(R.string.callFailed_dsac_restricted_emergency, false);
return;
} else if (cause == Connection.DisconnectCause.CS_RESTRICTED_NORMAL) {
showGenericErrorDialog(R.string.callFailed_dsac_restricted_normal, false);
return;
}
if (phoneIsCdma) {
Call.State callState = mApp.notifier.getPreviousCdmaCallState();
if ((callState == Call.State.ACTIVE)
&& (cause != Connection.DisconnectCause.INCOMING_MISSED)
&& (cause != Connection.DisconnectCause.NORMAL)
&& (cause != Connection.DisconnectCause.LOCAL)
&& (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
showCallLostDialog();
} else if ((callState == Call.State.DIALING || callState == Call.State.ALERTING)
&& (cause != Connection.DisconnectCause.INCOMING_MISSED)
&& (cause != Connection.DisconnectCause.NORMAL)
&& (cause != Connection.DisconnectCause.LOCAL)
&& (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
if (mApp.inCallUiState.needToShowCallLostDialog) {
// Show the dialog now since the call that just failed was a retry.
showCallLostDialog();
mApp.inCallUiState.needToShowCallLostDialog = false;
} else {
if (autoretrySetting == AUTO_RETRY_OFF) {
// Show the dialog for failed call if Auto Retry is OFF in Settings.
showCallLostDialog();
mApp.inCallUiState.needToShowCallLostDialog = false;
} else {
// Set the needToShowCallLostDialog flag now, so we'll know to show
// the dialog if *this* call fails.
mApp.inCallUiState.needToShowCallLostDialog = true;
}
}
}
}
// Explicitly clean up up any DISCONNECTED connections
// in a conference call.
// [Background: Even after a connection gets disconnected, its
// Connection object still stays around for a few seconds, in the
// DISCONNECTED state. With regular calls, this state drives the
// "call ended" UI. But when a single person disconnects from a
// conference call there's no "call ended" state at all; in that
// case we blow away any DISCONNECTED connections right now to make sure
// the UI updates instantly to reflect the current state.]
Call call = c.getCall();
if (call != null) {
// We only care about situation of a single caller
// disconnecting from a conference call. In that case, the
// call will have more than one Connection (including the one
// that just disconnected, which will be in the DISCONNECTED
// state) *and* at least one ACTIVE connection. (If the Call
// has *no* ACTIVE connections, that means that the entire
// conference call just ended, so we *do* want to show the
// "Call ended" state.)
List<Connection> connections = call.getConnections();
if (connections != null && connections.size() > 1) {
for (Connection conn : connections) {
if (conn.getState() == Call.State.ACTIVE) {
// This call still has at least one ACTIVE connection!
// So blow away any DISCONNECTED connections
// (including, presumably, the one that just
// disconnected from this conference call.)
// We also force the wake state to refresh, just in
// case the disconnected connections are removed
// before the phone state change.
if (VDBG) log("- Still-active conf call; clearing DISCONNECTED...");
mApp.updateWakeState();
mCM.clearDisconnected(); // This happens synchronously.
break;
}
}
}
}
// Note: see CallNotifier.onDisconnect() for some other behavior
// that might be triggered by a disconnect event, like playing the
// busy/congestion tone.
// Stash away some info about the call that just disconnected.
// (This might affect what happens after we exit the InCallScreen; see
// delayedCleanupAfterDisconnect().)
// TODO: rather than stashing this away now and then reading it in
// delayedCleanupAfterDisconnect(), it would be cleaner to just pass
// this as an argument to delayedCleanupAfterDisconnect() (if we call
// it directly) or else pass it as a Message argument when we post the
// DELAYED_CLEANUP_AFTER_DISCONNECT message.
mLastDisconnectCause = cause;
// We bail out immediately (and *don't* display the "call ended"
// state at all) if this was an incoming call.
boolean bailOutImmediately =
((cause == Connection.DisconnectCause.INCOMING_MISSED)
|| (cause == Connection.DisconnectCause.INCOMING_REJECTED))
&& currentlyIdle;
// Note: we also do some special handling for the case when a call
// disconnects with cause==OUT_OF_SERVICE while making an
// emergency call from airplane mode. That's handled by
// EmergencyCallHelper.onDisconnect().
// TODO: one more case where we *shouldn't* bail out immediately:
// If the disconnect event was from an incoming ringing call, but
// the "Respond via SMS" popup is visible onscreen. (In this
// case, we let the popup stay up even after the incoming call
// stops ringing, to give people extra time to choose a response.)
//
// But watch out: if we allow the popup to stay onscreen even
// after the incoming call disconnects, then we'll *also* have to
// forcibly dismiss it if the InCallScreen gets paused in that
// state (like by the user pressing Power or the screen timing
// out).
if (bailOutImmediately) {
if (DBG) log("- onDisconnect: bailOutImmediately...");
// Exit the in-call UI!
// (This is basically the same "delayed cleanup" we do below,
// just with zero delay. Since the Phone is currently idle,
// this call is guaranteed to immediately finish this activity.)
delayedCleanupAfterDisconnect();
} else {
if (DBG) log("- onDisconnect: delayed bailout...");
// Stay on the in-call screen for now. (Either the phone is
// still in use, or the phone is idle but we want to display
// the "call ended" state for a couple of seconds.)
// Switch to the special "Call ended" state when the phone is idle
// but there's still a call in the DISCONNECTED state:
if (currentlyIdle
&& (mCM.hasDisconnectedFgCall() || mCM.hasDisconnectedBgCall())) {
if (DBG) log("- onDisconnect: switching to 'Call ended' state...");
setInCallScreenMode(InCallScreenMode.CALL_ENDED);
}
// Force a UI update in case we need to display anything
// special based on this connection's DisconnectCause
// (see CallCard.getCallFailedString()).
updateScreen();
// Some other misc cleanup that we do if the call that just
// disconnected was the foreground call.
final boolean hasActiveCall = mCM.hasActiveFgCall();
if (!hasActiveCall) {
if (DBG) log("- onDisconnect: cleaning up after FG call disconnect...");
// Dismiss any dialogs which are only meaningful for an
// active call *and* which become moot if the call ends.
if (mWaitPromptDialog != null) {
if (VDBG) log("- DISMISSING mWaitPromptDialog.");
mWaitPromptDialog.dismiss(); // safe even if already dismissed
mWaitPromptDialog = null;
}
if (mWildPromptDialog != null) {
if (VDBG) log("- DISMISSING mWildPromptDialog.");
mWildPromptDialog.dismiss(); // safe even if already dismissed
mWildPromptDialog = null;
}
if (mPausePromptDialog != null) {
if (DBG) log("- DISMISSING mPausePromptDialog.");
mPausePromptDialog.dismiss(); // safe even if already dismissed
mPausePromptDialog = null;
}
}
// Updating the screen wake state is done in onPhoneStateChanged().
// CDMA: We only clean up if the Phone state is IDLE as we might receive an
// onDisconnect for a Call Collision case (rare but possible).
// For Call collision cases i.e. when the user makes an out going call
// and at the same time receives an Incoming Call, the Incoming Call is given
// higher preference. At this time framework sends a disconnect for the Out going
// call connection hence we should *not* bring down the InCallScreen as the Phone
// State would be RINGING
if (mPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
if (!currentlyIdle) {
// Clean up any connections in the DISCONNECTED state.
// This is necessary cause in CallCollision the foreground call might have
// connections in DISCONNECTED state which needs to be cleared.
mCM.clearDisconnected();
// The phone is still in use. Stay here in this activity.
// But we don't need to keep the screen on.
if (DBG) log("onDisconnect: Call Collision case - staying on InCallScreen.");
if (DBG) PhoneUtils.dumpCallState(mPhone);
return;
}
}
// Finally, arrange for delayedCleanupAfterDisconnect() to get
// called after a short interval (during which we display the
// "call ended" state.) At that point, if the
// Phone is idle, we'll finish out of this activity.
int callEndedDisplayDelay =
(cause == Connection.DisconnectCause.LOCAL)
? CALL_ENDED_SHORT_DELAY : CALL_ENDED_LONG_DELAY;
mHandler.removeMessages(DELAYED_CLEANUP_AFTER_DISCONNECT);
mHandler.sendEmptyMessageDelayed(DELAYED_CLEANUP_AFTER_DISCONNECT,
callEndedDisplayDelay);
}
// Remove 3way timer (only meaningful for CDMA)
// TODO: this call needs to happen in the CallController, not here.
// (It should probably be triggered by the CallNotifier's onDisconnect method.)
// mHandler.removeMessages(THREEWAY_CALLERINFO_DISPLAY_DONE);
}
/**
* Brings up the "MMI Started" dialog.
*/
private void onMMIInitiate(AsyncResult r) {
if (VDBG) log("onMMIInitiate()... AsyncResult r = " + r);
// Watch out: don't do this if we're not the foreground activity,
// mainly since in the Dialog.show() might fail if we don't have a
// valid window token any more...
// (Note that this exact sequence can happen if you try to start
// an MMI code while the radio is off or out of service.)
if (!mIsForegroundActivity) {
if (VDBG) log("Activity not in foreground! Bailing out...");
return;
}
// Also, if any other dialog is up right now (presumably the
// generic error dialog displaying the "Starting MMI..." message)
// take it down before bringing up the real "MMI Started" dialog
// in its place.
dismissAllDialogs();
MmiCode mmiCode = (MmiCode) r.result;
if (VDBG) log(" - MmiCode: " + mmiCode);
Message message = Message.obtain(mHandler, PhoneApp.MMI_CANCEL);
mMmiStartedDialog = PhoneUtils.displayMMIInitiate(this, mmiCode,
message, mMmiStartedDialog);
}
/**
* Handles an MMI_CANCEL event, which is triggered by the button
* (labeled either "OK" or "Cancel") on the "MMI Started" dialog.
* @see onMMIInitiate
* @see PhoneUtils.cancelMmiCode
*/
private void onMMICancel() {
if (VDBG) log("onMMICancel()...");
// First of all, cancel the outstanding MMI code (if possible.)
PhoneUtils.cancelMmiCode(mPhone);
// Regardless of whether the current MMI code was cancelable, the
// PhoneApp will get an MMI_COMPLETE event very soon, which will
// take us to the MMI Complete dialog (see
// PhoneUtils.displayMMIComplete().)
//
// But until that event comes in, we *don't* want to stay here on
// the in-call screen, since we'll be visible in a
// partially-constructed state as soon as the "MMI Started" dialog
// gets dismissed. So let's forcibly bail out right now.
if (DBG) log("onMMICancel: finishing InCallScreen...");
endInCallScreenSession();
}
/**
* Handles the POST_ON_DIAL_CHARS message from the Phone
* (see our call to mPhone.setOnPostDialCharacter() above.)
*
* TODO: NEED TO TEST THIS SEQUENCE now that we no longer handle
* "dialable" key events here in the InCallScreen: we do directly to the
* Dialer UI instead. Similarly, we may now need to go directly to the
* Dialer to handle POST_ON_DIAL_CHARS too.
*/
private void handlePostOnDialChars(AsyncResult r, char ch) {
Connection c = (Connection) r.result;
if (c != null) {
Connection.PostDialState state =
(Connection.PostDialState) r.userObj;
if (VDBG) log("handlePostOnDialChar: state = " +
state + ", ch = " + ch);
switch (state) {
case STARTED:
mDialer.stopLocalToneIfNeeded();
if (mPauseInProgress) {
/**
* Note that on some devices, this will never happen,
* because we will not ever enter the PAUSE state.
*/
showPausePromptDialog(c, mPostDialStrAfterPause);
}
mPauseInProgress = false;
mDialer.startLocalToneIfNeeded(ch);
// TODO: is this needed, now that you can't actually
// type DTMF chars or dial directly from here?
// If so, we'd need to yank you out of the in-call screen
// here too (and take you to the 12-key dialer in "in-call" mode.)
// displayPostDialedChar(ch);
break;
case WAIT:
// wait shows a prompt.
if (DBG) log("handlePostOnDialChars: show WAIT prompt...");
mDialer.stopLocalToneIfNeeded();
String postDialStr = c.getRemainingPostDialString();
showWaitPromptDialog(c, postDialStr);
break;
case WILD:
if (DBG) log("handlePostOnDialChars: show WILD prompt");
mDialer.stopLocalToneIfNeeded();
showWildPromptDialog(c);
break;
case COMPLETE:
mDialer.stopLocalToneIfNeeded();
break;
case PAUSE:
// pauses for a brief period of time then continue dialing.
mDialer.stopLocalToneIfNeeded();
mPostDialStrAfterPause = c.getRemainingPostDialString();
mPauseInProgress = true;
break;
default:
break;
}
}
}
/**
* Pop up an alert dialog with OK and Cancel buttons to allow user to
* Accept or Reject the WAIT inserted as part of the Dial string.
*/
private void showWaitPromptDialog(final Connection c, String postDialStr) {
if (DBG) log("showWaitPromptDialogChoice: '" + postDialStr + "'...");
Resources r = getResources();
StringBuilder buf = new StringBuilder();
buf.append(r.getText(R.string.wait_prompt_str));
buf.append(postDialStr);
// if (DBG) log("- mWaitPromptDialog = " + mWaitPromptDialog);
if (mWaitPromptDialog != null) {
if (DBG) log("- DISMISSING mWaitPromptDialog.");
mWaitPromptDialog.dismiss(); // safe even if already dismissed
mWaitPromptDialog = null;
}
mWaitPromptDialog = new AlertDialog.Builder(this)
.setMessage(buf.toString())
.setPositiveButton(R.string.pause_prompt_yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (DBG) log("handle WAIT_PROMPT_CONFIRMED, proceed...");
c.proceedAfterWaitChar();
}
})
.setNegativeButton(R.string.pause_prompt_no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (DBG) log("handle POST_DIAL_CANCELED!");
c.cancelPostDial();
}
})
.create();
mWaitPromptDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
mWaitPromptDialog.show();
}
/**
* Pop up an alert dialog which waits for 2 seconds for each P (Pause) Character entered
* as part of the Dial String.
*/
private void showPausePromptDialog(final Connection c, String postDialStrAfterPause) {
Resources r = getResources();
StringBuilder buf = new StringBuilder();
buf.append(r.getText(R.string.pause_prompt_str));
buf.append(postDialStrAfterPause);
if (mPausePromptDialog != null) {
if (DBG) log("- DISMISSING mPausePromptDialog.");
mPausePromptDialog.dismiss(); // safe even if already dismissed
mPausePromptDialog = null;
}
mPausePromptDialog = new AlertDialog.Builder(this)
.setMessage(buf.toString())
.create();
mPausePromptDialog.show();
// 2 second timer
Message msg = Message.obtain(mHandler, EVENT_PAUSE_DIALOG_COMPLETE);
mHandler.sendMessageDelayed(msg, PAUSE_PROMPT_DIALOG_TIMEOUT);
}
private View createWildPromptView() {
LinearLayout result = new LinearLayout(this);
result.setOrientation(LinearLayout.VERTICAL);
result.setPadding(5, 5, 5, 5);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
TextView promptMsg = new TextView(this);
promptMsg.setTextSize(14);
promptMsg.setTypeface(Typeface.DEFAULT_BOLD);
promptMsg.setText(getResources().getText(R.string.wild_prompt_str));
result.addView(promptMsg, lp);
mWildPromptText = new EditText(this);
mWildPromptText.setKeyListener(DialerKeyListener.getInstance());
mWildPromptText.setMovementMethod(null);
mWildPromptText.setTextSize(14);
mWildPromptText.setMaxLines(1);
mWildPromptText.setHorizontallyScrolling(true);
mWildPromptText.setBackgroundResource(android.R.drawable.editbox_background);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.setMargins(0, 3, 0, 0);
result.addView(mWildPromptText, lp2);
return result;
}
private void showWildPromptDialog(final Connection c) {
View v = createWildPromptView();
if (mWildPromptDialog != null) {
if (VDBG) log("- DISMISSING mWildPromptDialog.");
mWildPromptDialog.dismiss(); // safe even if already dismissed
mWildPromptDialog = null;
}
mWildPromptDialog = new AlertDialog.Builder(this)
.setView(v)
.setPositiveButton(
R.string.send_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (VDBG) log("handle WILD_PROMPT_CHAR_ENTERED, proceed...");
String replacement = null;
if (mWildPromptText != null) {
replacement = mWildPromptText.getText().toString();
mWildPromptText = null;
}
c.proceedAfterWildChar(replacement);
mApp.pokeUserActivity();
}
})
.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
if (VDBG) log("handle POST_DIAL_CANCELED!");
c.cancelPostDial();
mApp.pokeUserActivity();
}
})
.create();
mWildPromptDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
mWildPromptDialog.show();
mWildPromptText.requestFocus();
}
/**
* Updates the state of the in-call UI based on the current state of
* the Phone. This call has no effect if we're not currently the
* foreground activity.
*
* This method is only allowed to be called from the UI thread (since it
* manipulates our View hierarchy). If you need to update the screen from
* some other thread, or if you just want to "post a request" for the screen
* to be updated (rather than doing it synchronously), call
* requestUpdateScreen() instead.
*/
private void updateScreen() {
if (DBG) log("updateScreen()...");
final InCallScreenMode inCallScreenMode = mApp.inCallUiState.inCallScreenMode;
if (VDBG) {
Phone.State state = mCM.getState();
log(" - phone state = " + state);
log(" - inCallScreenMode = " + inCallScreenMode);
}
// Don't update anything if we're not in the foreground (there's
// no point updating our UI widgets since we're not visible!)
// Also note this check also ensures we won't update while we're
// in the middle of pausing, which could cause a visible glitch in
// the "activity ending" transition.
if (!mIsForegroundActivity) {
if (DBG) log("- updateScreen: not the foreground Activity! Bailing out...");
return;
}
if (inCallScreenMode == InCallScreenMode.OTA_NORMAL) {
if (DBG) log("- updateScreen: OTA call state NORMAL...");
if (mApp.otaUtils != null) {
if (DBG) log("- updateScreen: mApp.otaUtils is not null, call otaShowProperScreen");
mApp.otaUtils.otaShowProperScreen();
}
return;
} else if (inCallScreenMode == InCallScreenMode.OTA_ENDED) {
if (DBG) log("- updateScreen: OTA call ended state ...");
// Wake up the screen when we get notification, good or bad.
mApp.wakeUpScreen();
if (mApp.cdmaOtaScreenState.otaScreenState
== CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION) {
if (DBG) log("- updateScreen: OTA_STATUS_ACTIVATION");
if (mApp.otaUtils != null) {
if (DBG) log("- updateScreen: mApp.otaUtils is not null, "
+ "call otaShowActivationScreen");
mApp.otaUtils.otaShowActivateScreen();
}
} else {
if (DBG) log("- updateScreen: OTA Call end state for Dialogs");
if (mApp.otaUtils != null) {
if (DBG) log("- updateScreen: Show OTA Success Failure dialog");
mApp.otaUtils.otaShowSuccessFailure();
}
}
return;
} else if (inCallScreenMode == InCallScreenMode.MANAGE_CONFERENCE) {
if (DBG) log("- updateScreen: manage conference mode (NOT updating in-call UI)...");
updateManageConferencePanelIfNecessary();
return;
} else if (inCallScreenMode == InCallScreenMode.CALL_ENDED) {
if (DBG) log("- updateScreen: call ended state...");
// Continue with the rest of updateScreen() as usual, since we do
// need to update the background (to the special "call ended" color)
// and the CallCard (to show the "Call ended" label.)
}
if (DBG) log("- updateScreen: updating the in-call UI...");
// Note we update the InCallTouchUi widget before the CallCard,
// since the CallCard adjusts its size based on how much vertical
// space the InCallTouchUi widget needs.
updateInCallTouchUi();
mCallCard.updateState(mCM);
updateDialpadVisibility();
updateProviderOverlay();
updateProgressIndication();
// Forcibly take down all dialog if an incoming call is ringing.
if (mCM.hasActiveRingingCall()) {
dismissAllDialogs();
} else {
// Wait prompt dialog is not currently up. But it *should* be
// up if the FG call has a connection in the WAIT state and
// the phone isn't ringing.
String postDialStr = null;
List<Connection> fgConnections = mCM.getFgCallConnections();
int phoneType = mCM.getFgPhone().getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
Connection fgLatestConnection = mCM.getFgCallLatestConnection();
if (mApp.cdmaPhoneCallState.getCurrentCallState() ==
CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
for (Connection cn : fgConnections) {
if ((cn != null) && (cn.getPostDialState() ==
Connection.PostDialState.WAIT)) {
cn.cancelPostDial();
}
}
} else if ((fgLatestConnection != null)
&& (fgLatestConnection.getPostDialState() == Connection.PostDialState.WAIT)) {
if(DBG) log("show the Wait dialog for CDMA");
postDialStr = fgLatestConnection.getRemainingPostDialString();
showWaitPromptDialog(fgLatestConnection, postDialStr);
}
} else if ((phoneType == Phone.PHONE_TYPE_GSM)
|| (phoneType == Phone.PHONE_TYPE_SIP)) {
for (Connection cn : fgConnections) {
if ((cn != null) && (cn.getPostDialState() == Connection.PostDialState.WAIT)) {
postDialStr = cn.getRemainingPostDialString();
showWaitPromptDialog(cn, postDialStr);
}
}
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
}
}
/**
* (Re)synchronizes the onscreen UI with the current state of the
* telephony framework.
*
* @return SyncWithPhoneStateStatus.SUCCESS if we successfully updated the UI, or
* SyncWithPhoneStateStatus.PHONE_NOT_IN_USE if there was no phone state to sync
* with (ie. the phone was completely idle). In the latter case, we
* shouldn't even be in the in-call UI in the first place, and it's
* the caller's responsibility to bail out of this activity by
* calling endInCallScreenSession if appropriate.
*
* This method directly calls updateScreen() in the normal "phone is
* in use" case, so there's no need for the caller to do so.
*/
private SyncWithPhoneStateStatus syncWithPhoneState() {
boolean updateSuccessful = false;
if (DBG) log("syncWithPhoneState()...");
if (DBG) PhoneUtils.dumpCallState(mPhone);
if (VDBG) dumpBluetoothState();
// Make sure the Phone is "in use". (If not, we shouldn't be on
// this screen in the first place.)
// An active or just-ended OTA call counts as "in use".
if (TelephonyCapabilities.supportsOtasp(mCM.getFgPhone())
&& ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL)
|| (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED))) {
// Even when OTA Call ends, need to show OTA End UI,
// so return Success to allow UI update.
return SyncWithPhoneStateStatus.SUCCESS;
}
// If an MMI code is running that also counts as "in use".
//
// TODO: We currently only call getPendingMmiCodes() for GSM
// phones. (The code's been that way all along.) But CDMAPhone
// does in fact implement getPendingMmiCodes(), so should we
// check that here regardless of the phone type?
boolean hasPendingMmiCodes =
(mPhone.getPhoneType() == Phone.PHONE_TYPE_GSM)
&& !mPhone.getPendingMmiCodes().isEmpty();
// Finally, it's also OK to stay here on the InCallScreen if we
// need to display a progress indicator while something's
// happening in the background.
boolean showProgressIndication = mApp.inCallUiState.isProgressIndicationActive();
if (mCM.hasActiveFgCall() || mCM.hasActiveBgCall() || mCM.hasActiveRingingCall()
|| hasPendingMmiCodes || showProgressIndication) {
if (VDBG) log("syncWithPhoneState: it's ok to be here; update the screen...");
updateScreen();
return SyncWithPhoneStateStatus.SUCCESS;
}
Log.i(LOG_TAG, "syncWithPhoneState: phone is idle (shouldn't be here)");
return SyncWithPhoneStateStatus.PHONE_NOT_IN_USE;
}
private void handleMissingVoiceMailNumber() {
if (DBG) log("handleMissingVoiceMailNumber");
final Message msg = Message.obtain(mHandler);
msg.what = DONT_ADD_VOICEMAIL_NUMBER;
final Message msg2 = Message.obtain(mHandler);
msg2.what = ADD_VOICEMAIL_NUMBER;
mMissingVoicemailDialog = new AlertDialog.Builder(this)
.setTitle(R.string.no_vm_number)
.setMessage(R.string.no_vm_number_msg)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (VDBG) log("Missing voicemail AlertDialog: POSITIVE click...");
msg.sendToTarget(); // see dontAddVoiceMailNumber()
mApp.pokeUserActivity();
}})
.setNegativeButton(R.string.add_vm_number_str,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (VDBG) log("Missing voicemail AlertDialog: NEGATIVE click...");
msg2.sendToTarget(); // see addVoiceMailNumber()
mApp.pokeUserActivity();
}})
.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
if (VDBG) log("Missing voicemail AlertDialog: CANCEL handler...");
msg.sendToTarget(); // see dontAddVoiceMailNumber()
mApp.pokeUserActivity();
}})
.create();
// When the dialog is up, completely hide the in-call UI
// underneath (which is in a partially-constructed state).
mMissingVoicemailDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mMissingVoicemailDialog.show();
}
private void addVoiceMailNumberPanel() {
if (mMissingVoicemailDialog != null) {
mMissingVoicemailDialog.dismiss();
mMissingVoicemailDialog = null;
}
if (DBG) log("addVoiceMailNumberPanel: finishing InCallScreen...");
endInCallScreenSession();
if (DBG) log("show vm setting");
// navigate to the Voicemail setting in the Call Settings activity.
Intent intent = new Intent(CallFeaturesSetting.ACTION_ADD_VOICEMAIL);
intent.setClass(this, CallFeaturesSetting.class);
startActivity(intent);
}
private void dontAddVoiceMailNumber() {
if (mMissingVoicemailDialog != null) {
mMissingVoicemailDialog.dismiss();
mMissingVoicemailDialog = null;
}
if (DBG) log("dontAddVoiceMailNumber: finishing InCallScreen...");
endInCallScreenSession();
}
/**
* Do some delayed cleanup after a Phone call gets disconnected.
*
* This method gets called a couple of seconds after any DISCONNECT
* event from the Phone; it's triggered by the
* DELAYED_CLEANUP_AFTER_DISCONNECT message we send in onDisconnect().
*
* If the Phone is totally idle right now, that means we've already
* shown the "call ended" state for a couple of seconds, and it's now
* time to endInCallScreenSession this activity.
*
* If the Phone is *not* idle right now, that probably means that one
* call ended but the other line is still in use. In that case, do
* nothing, and instead stay here on the InCallScreen.
*/
private void delayedCleanupAfterDisconnect() {
log("delayedCleanupAfterDisconnect()... Phone state = " + mCM.getState());
// Clean up any connections in the DISCONNECTED state.
//
// [Background: Even after a connection gets disconnected, its
// Connection object still stays around, in the special
// DISCONNECTED state. This is necessary because we we need the
// caller-id information from that Connection to properly draw the
// "Call ended" state of the CallCard.
// But at this point we truly don't need that connection any
// more, so tell the Phone that it's now OK to to clean up any
// connections still in that state.]
mCM.clearDisconnected();
// There are two cases where we should *not* exit the InCallScreen:
// (1) Phone is still in use
// or
// (2) There's an active progress indication (i.e. the "Retrying..."
// progress dialog) that we need to continue to display.
boolean stayHere = phoneIsInUse() || mApp.inCallUiState.isProgressIndicationActive();
if (stayHere) {
log("- delayedCleanupAfterDisconnect: staying on the InCallScreen...");
} else {
// Phone is idle! We should exit the in-call UI now.
if (DBG) log("- delayedCleanupAfterDisconnect: phone is idle...");
// And (finally!) exit from the in-call screen
// (but not if we're already in the process of pausing...)
if (mIsForegroundActivity) {
if (DBG) log("- delayedCleanupAfterDisconnect: finishing InCallScreen...");
// In some cases we finish the call by taking the user to the
// Call Log. Otherwise, we simply call endInCallScreenSession,
// which will take us back to wherever we came from.
//
// UI note: In eclair and earlier, we went to the Call Log
// after outgoing calls initiated on the device, but never for
// incoming calls. Now we do it for incoming calls too, as
// long as the call was answered by the user. (We always go
// back where you came from after a rejected or missed incoming
// call.)
//
// And in any case, *never* go to the call log if we're in
// emergency mode (i.e. if the screen is locked and a lock
// pattern or PIN/password is set), or if we somehow got here
// on a non-voice-capable device.
if (VDBG) log("- Post-call behavior:");
if (VDBG) log(" - mLastDisconnectCause = " + mLastDisconnectCause);
if (VDBG) log(" - isPhoneStateRestricted() = " + isPhoneStateRestricted());
// DisconnectCause values in the most common scenarios:
// - INCOMING_MISSED: incoming ringing call times out, or the
// other end hangs up while still ringing
// - INCOMING_REJECTED: user rejects the call while ringing
// - LOCAL: user hung up while a call was active (after
// answering an incoming call, or after making an
// outgoing call)
// - NORMAL: the other end hung up (after answering an incoming
// call, or after making an outgoing call)
if ((mLastDisconnectCause != Connection.DisconnectCause.INCOMING_MISSED)
&& (mLastDisconnectCause != Connection.DisconnectCause.INCOMING_REJECTED)
&& !isPhoneStateRestricted()
&& PhoneApp.sVoiceCapable) {
final Intent intent = mApp.createPhoneEndIntentUsingCallOrigin();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
if (VDBG) {
log("- Show Call Log (or Dialtacts) after disconnect. Current intent: "
+ intent);
}
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Don't crash if there's somehow no "Call log" at
// all on this device.
// (This should never happen, though, since we already
// checked PhoneApp.sVoiceCapable above, and any
// voice-capable device surely *should* have a call
// log activity....)
Log.w(LOG_TAG, "delayedCleanupAfterDisconnect: "
+ "transition to call log failed; intent = " + intent);
// ...so just return back where we came from....
}
// Even if we did go to the call log, note that we still
// call endInCallScreenSession (below) to make sure we don't
// stay in the activity history.
}
endInCallScreenSession();
}
// Reset the call origin when the session ends and this in-call UI is being finished.
mApp.setLatestActiveCallOrigin(null);
}
}
/**
* View.OnClickListener implementation.
*
* This method handles clicks from UI elements that use the
* InCallScreen itself as their OnClickListener.
*
* Note: Currently this method is used only for a few special buttons: the
* mButtonManageConferenceDone "Back to call" button, and the OTASP-specific
* buttons managed by OtaUtils.java. *Most* in-call controls are handled by
* the handleOnscreenButtonClick() method, via the InCallTouchUi widget.
*/
public void onClick(View view) {
int id = view.getId();
if (VDBG) log("onClick(View " + view + ", id " + id + ")...");
switch (id) {
case R.id.manage_done: // mButtonManageConferenceDone
if (VDBG) log("onClick: mButtonManageConferenceDone...");
// Hide the Manage Conference panel, return to NORMAL mode.
setInCallScreenMode(InCallScreenMode.NORMAL);
requestUpdateScreen();
break;
default:
// Presumably one of the OTASP-specific buttons managed by
// OtaUtils.java.
// (TODO: It would be cleaner for the OtaUtils instance itself to
// be the OnClickListener for its own buttons.)
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL
|| mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED)
&& mApp.otaUtils != null) {
mApp.otaUtils.onClickHandler(id);
} else {
// Uh oh: we *should* only receive clicks here from the
// buttons managed by OtaUtils.java, but if we're not in one
// of the special OTASP modes, those buttons shouldn't have
// been visible in the first place.
Log.w(LOG_TAG,
"onClick: unexpected click from ID " + id + " (View = " + view + ")");
}
break;
}
EventLog.writeEvent(EventLogTags.PHONE_UI_BUTTON_CLICK,
(view instanceof TextView) ? ((TextView) view).getText() : "");
// Clicking any onscreen UI element counts as explicit "user activity".
mApp.pokeUserActivity();
}
private void onHoldClick() {
final boolean hasActiveCall = mCM.hasActiveFgCall();
final boolean hasHoldingCall = mCM.hasActiveBgCall();
log("onHoldClick: hasActiveCall = " + hasActiveCall
+ ", hasHoldingCall = " + hasHoldingCall);
boolean newHoldState;
boolean holdButtonEnabled;
if (hasActiveCall && !hasHoldingCall) {
// There's only one line in use, and that line is active.
PhoneUtils.switchHoldingAndActive(
mCM.getFirstActiveBgCall()); // Really means "hold" in this state
newHoldState = true;
holdButtonEnabled = true;
} else if (!hasActiveCall && hasHoldingCall) {
// There's only one line in use, and that line is on hold.
PhoneUtils.switchHoldingAndActive(
mCM.getFirstActiveBgCall()); // Really means "unhold" in this state
newHoldState = false;
holdButtonEnabled = true;
} else {
// Either zero or 2 lines are in use; "hold/unhold" is meaningless.
newHoldState = false;
holdButtonEnabled = false;
}
// No need to forcibly update the onscreen UI; just wait for the
// onPhoneStateChanged() callback. (This seems to be responsive
// enough.)
// Also, any time we hold or unhold, force the DTMF dialpad to close.
hideDialpadInternal(true); // do the "closing" animation
}
/**
* Toggles in-call audio between speaker and the built-in earpiece (or
* wired headset.)
*/
public void toggleSpeaker() {
// TODO: Turning on the speaker seems to enable the mic
// whether or not the "mute" feature is active!
// Not sure if this is an feature of the telephony API
// that I need to handle specially, or just a bug.
boolean newSpeakerState = !PhoneUtils.isSpeakerOn(this);
log("toggleSpeaker(): newSpeakerState = " + newSpeakerState);
if (newSpeakerState && isBluetoothAvailable() && isBluetoothAudioConnected()) {
disconnectBluetoothAudio();
}
PhoneUtils.turnOnSpeaker(this, newSpeakerState, true);
// And update the InCallTouchUi widget (since the "audio mode"
// button might need to change its appearance based on the new
// audio state.)
updateInCallTouchUi();
}
/*
* onMuteClick is called only when there is a foreground call
*/
private void onMuteClick() {
boolean newMuteState = !PhoneUtils.getMute();
log("onMuteClick(): newMuteState = " + newMuteState);
PhoneUtils.setMute(newMuteState);
}
/**
* Toggles whether or not to route in-call audio to the bluetooth
* headset, or do nothing (but log a warning) if no bluetooth device
* is actually connected.
*
* TODO: this method is currently unused, but the "audio mode" UI
* design is still in flux so let's keep it around for now.
* (But if we ultimately end up *not* providing any way for the UI to
* simply "toggle bluetooth", we can get rid of this method.)
*/
public void toggleBluetooth() {
if (VDBG) log("toggleBluetooth()...");
if (isBluetoothAvailable()) {
// Toggle the bluetooth audio connection state:
if (isBluetoothAudioConnected()) {
disconnectBluetoothAudio();
} else {
// Manually turn the speaker phone off, instead of allowing the
// Bluetooth audio routing to handle it, since there's other
// important state-updating that needs to happen in the
// PhoneUtils.turnOnSpeaker() method.
// (Similarly, whenever the user turns *on* the speaker, we
// manually disconnect the active bluetooth headset;
// see toggleSpeaker() and/or switchInCallAudio().)
if (PhoneUtils.isSpeakerOn(this)) {
PhoneUtils.turnOnSpeaker(this, false, true);
}
connectBluetoothAudio();
}
} else {
// Bluetooth isn't available; the onscreen UI shouldn't have
// allowed this request in the first place!
Log.w(LOG_TAG, "toggleBluetooth(): bluetooth is unavailable");
}
// And update the InCallTouchUi widget (since the "audio mode"
// button might need to change its appearance based on the new
// audio state.)
updateInCallTouchUi();
}
/**
* Switches the current routing of in-call audio between speaker,
* bluetooth, and the built-in earpiece (or wired headset.)
*
* This method is used on devices that provide a single 3-way switch
* for audio routing. For devices that provide separate toggles for
* Speaker and Bluetooth, see toggleBluetooth() and toggleSpeaker().
*
* TODO: UI design is still in flux. If we end up totally
* eliminating the concept of Speaker and Bluetooth toggle buttons,
* we can get rid of toggleBluetooth() and toggleSpeaker().
*/
public void switchInCallAudio(InCallAudioMode newMode) {
log("switchInCallAudio: new mode = " + newMode);
switch (newMode) {
case SPEAKER:
if (!PhoneUtils.isSpeakerOn(this)) {
// Switch away from Bluetooth, if it was active.
if (isBluetoothAvailable() && isBluetoothAudioConnected()) {
disconnectBluetoothAudio();
}
PhoneUtils.turnOnSpeaker(this, true, true);
}
break;
case BLUETOOTH:
// If already connected to BT, there's nothing to do here.
if (isBluetoothAvailable() && !isBluetoothAudioConnected()) {
// Manually turn the speaker phone off, instead of allowing the
// Bluetooth audio routing to handle it, since there's other
// important state-updating that needs to happen in the
// PhoneUtils.turnOnSpeaker() method.
// (Similarly, whenever the user turns *on* the speaker, we
// manually disconnect the active bluetooth headset;
// see toggleSpeaker() and/or switchInCallAudio().)
if (PhoneUtils.isSpeakerOn(this)) {
PhoneUtils.turnOnSpeaker(this, false, true);
}
connectBluetoothAudio();
}
break;
case EARPIECE:
// Switch to either the handset earpiece, or the wired headset (if connected.)
// (Do this by simply making sure both speaker and bluetooth are off.)
if (isBluetoothAvailable() && isBluetoothAudioConnected()) {
disconnectBluetoothAudio();
}
if (PhoneUtils.isSpeakerOn(this)) {
PhoneUtils.turnOnSpeaker(this, false, true);
}
break;
default:
Log.wtf(LOG_TAG, "switchInCallAudio: unexpected mode " + newMode);
break;
}
// And finally, update the InCallTouchUi widget (since the "audio
// mode" button might need to change its appearance based on the
// new audio state.)
updateInCallTouchUi();
}
/**
* Handle a click on the "Show/Hide dialpad" button.
*/
private void onShowHideDialpad() {
if (VDBG) log("onShowHideDialpad()...");
if (mDialer.isOpened()) {
hideDialpadInternal(true); // do the "closing" animation
} else {
showDialpadInternal(true); // do the "opening" animation
}
}
// Internal wrapper around DTMFTwelveKeyDialer.openDialer()
private void showDialpadInternal(boolean animate) {
mDialer.openDialer(animate);
// And update the InCallUiState (so that we'll restore the dialpad
// to the correct state if we get paused/resumed).
mApp.inCallUiState.showDialpad = true;
}
// Internal wrapper around DTMFTwelveKeyDialer.closeDialer()
private void hideDialpadInternal(boolean animate) {
mDialer.closeDialer(animate);
// And update the InCallUiState (so that we'll restore the dialpad
// to the correct state if we get paused/resumed).
mApp.inCallUiState.showDialpad = false;
}
/**
* Handles button clicks from the InCallTouchUi widget.
*/
/* package */ void handleOnscreenButtonClick(int id) {
if (DBG) log("handleOnscreenButtonClick(id " + id + ")...");
switch (id) {
// Actions while an incoming call is ringing:
case R.id.incomingCallAnswer:
internalAnswerCall();
break;
case R.id.incomingCallReject:
hangupRingingCall();
break;
case R.id.incomingCallRespondViaSms:
internalRespondViaSms();
break;
// The other regular (single-tap) buttons used while in-call:
case R.id.holdButton:
onHoldClick();
break;
case R.id.swapButton:
internalSwapCalls();
break;
case R.id.endButton:
internalHangup();
break;
case R.id.dialpadButton:
onShowHideDialpad();
break;
case R.id.muteButton:
onMuteClick();
break;
case R.id.addButton:
PhoneUtils.startNewCall(mCM); // Fires off an ACTION_DIAL intent
break;
case R.id.mergeButton:
case R.id.cdmaMergeButton:
PhoneUtils.mergeCalls(mCM);
break;
case R.id.manageConferenceButton:
// Show the Manage Conference panel.
setInCallScreenMode(InCallScreenMode.MANAGE_CONFERENCE);
requestUpdateScreen();
break;
default:
Log.w(LOG_TAG, "handleOnscreenButtonClick: unexpected ID " + id);
break;
}
// Clicking any onscreen UI element counts as explicit "user activity".
mApp.pokeUserActivity();
// Just in case the user clicked a "stateful" UI element (like one
// of the toggle buttons), we force the in-call buttons to update,
// to make sure the user sees the *new* current state.
//
// Note that some in-call buttons will *not* immediately change the
// state of the UI, namely those that send a request to the telephony
// layer (like "Hold" or "End call".) For those buttons, the
// updateInCallTouchUi() call here won't have any visible effect.
// Instead, the UI will be updated eventually when the next
// onPhoneStateChanged() event comes in and triggers an updateScreen()
// call.
//
// TODO: updateInCallTouchUi() is overkill here; it would be
// more efficient to update *only* the affected button(s).
// (But this isn't a big deal since updateInCallTouchUi() is pretty
// cheap anyway...)
updateInCallTouchUi();
}
/**
* Update the network provider's overlay based on the value of
* InCallUiState.providerOverlayVisible.
* If false the overlay is hidden otherwise it is shown. A
* delayed message is posted to take the overalay down after
* PROVIDER_OVERLAY_TIMEOUT. This ensures the user will see the
* overlay even if the call setup phase is very short.
*/
private void updateProviderOverlay() {
final InCallUiState inCallUiState = mApp.inCallUiState;
if (VDBG) log("updateProviderOverlay: " + inCallUiState.providerOverlayVisible);
ViewGroup overlay = (ViewGroup) findViewById(R.id.inCallProviderOverlay);
if (inCallUiState.providerOverlayVisible) {
CharSequence template = getText(R.string.calling_via_template);
CharSequence text = TextUtils.expandTemplate(template,
inCallUiState.providerLabel,
inCallUiState.providerAddress);
TextView message = (TextView) findViewById(R.id.callingVia);
message.setText(text);
ImageView image = (ImageView) findViewById(R.id.callingViaIcon);
image.setImageDrawable(inCallUiState.providerIcon);
overlay.setVisibility(View.VISIBLE);
// Remove any zombie messages and then send a message to
// self to remove the overlay after some time.
mHandler.removeMessages(EVENT_HIDE_PROVIDER_OVERLAY);
Message msg = Message.obtain(mHandler, EVENT_HIDE_PROVIDER_OVERLAY);
mHandler.sendMessageDelayed(msg, PROVIDER_OVERLAY_TIMEOUT);
} else {
overlay.setVisibility(View.GONE);
}
}
/**
* Display a status or error indication to the user according to the
* specified InCallUiState.CallStatusCode value.
*/
private void showStatusIndication(CallStatusCode status) {
switch (status) {
case SUCCESS:
// The InCallScreen does not need to display any kind of error indication,
// so we shouldn't have gotten here in the first place.
Log.wtf(LOG_TAG, "showStatusIndication: nothing to display");
break;
case POWER_OFF:
// Radio is explictly powered off, presumably because the
// device is in airplane mode.
//
// TODO: For now this UI is ultra-simple: we simply display
// a message telling the user to turn off airplane mode.
// But it might be nicer for the dialog to offer the option
// to turn the radio on right there (and automatically retry
// the call once network registration is complete.)
showGenericErrorDialog(R.string.incall_error_power_off,
true /* isStartupError */);
break;
case EMERGENCY_ONLY:
// Only emergency numbers are allowed, but we tried to dial
// a non-emergency number.
// (This state is currently unused; see comments above.)
showGenericErrorDialog(R.string.incall_error_emergency_only,
true /* isStartupError */);
break;
case OUT_OF_SERVICE:
// No network connection.
showGenericErrorDialog(R.string.incall_error_out_of_service,
true /* isStartupError */);
break;
case NO_PHONE_NUMBER_SUPPLIED:
// The supplied Intent didn't contain a valid phone number.
// (This is rare and should only ever happen with broken
// 3rd-party apps.) For now just show a generic error.
showGenericErrorDialog(R.string.incall_error_no_phone_number_supplied,
true /* isStartupError */);
break;
case DIALED_MMI:
// Our initial phone number was actually an MMI sequence.
// There's no real "error" here, but we do bring up the
// a Toast (as requested of the New UI paradigm).
//
// In-call MMIs do not trigger the normal MMI Initiate
// Notifications, so we should notify the user here.
// Otherwise, the code in PhoneUtils.java should handle
// user notifications in the form of Toasts or Dialogs.
if (mCM.getState() == Phone.State.OFFHOOK) {
Toast.makeText(mApp, R.string.incall_status_dialed_mmi, Toast.LENGTH_SHORT)
.show();
}
break;
case CALL_FAILED:
// We couldn't successfully place the call; there was some
// failure in the telephony layer.
// TODO: Need UI spec for this failure case; for now just
// show a generic error.
showGenericErrorDialog(R.string.incall_error_call_failed,
true /* isStartupError */);
break;
case VOICEMAIL_NUMBER_MISSING:
// We tried to call a voicemail: URI but the device has no
// voicemail number configured.
handleMissingVoiceMailNumber();
break;
case CDMA_CALL_LOST:
// This status indicates that InCallScreen should display the
// CDMA-specific "call lost" dialog. (If an outgoing call fails,
// and the CDMA "auto-retry" feature is enabled, *and* the retried
// call fails too, we display this specific dialog.)
//
// TODO: currently unused; see InCallUiState.needToShowCallLostDialog
break;
case EXITED_ECM:
// This status indicates that InCallScreen needs to display a
// warning that we're exiting ECM (emergency callback mode).
showExitingECMDialog();
break;
default:
throw new IllegalStateException(
"showStatusIndication: unexpected status code: " + status);
}
// TODO: still need to make sure that pressing OK or BACK from
// *any* of the dialogs we launch here ends up calling
// inCallUiState.clearPendingCallStatusCode()
// *and*
// make sure the Dialog handles both OK *and* cancel by calling
// endInCallScreenSession. (See showGenericErrorDialog() for an
// example.)
//
// (showGenericErrorDialog() currently does this correctly,
// but handleMissingVoiceMailNumber() probably needs to be fixed too.)
//
// Also need to make sure that bailing out of any of these dialogs by
// pressing Home clears out the pending status code too. (If you do
// that, neither the dialog's clickListener *or* cancelListener seems
// to run...)
}
/**
* Utility function to bring up a generic "error" dialog, and then bail
* out of the in-call UI when the user hits OK (or the BACK button.)
*/
private void showGenericErrorDialog(int resid, boolean isStartupError) {
CharSequence msg = getResources().getText(resid);
if (DBG) log("showGenericErrorDialog('" + msg + "')...");
// create the clicklistener and cancel listener as needed.
DialogInterface.OnClickListener clickListener;
OnCancelListener cancelListener;
if (isStartupError) {
clickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
bailOutAfterErrorDialog();
}};
cancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
bailOutAfterErrorDialog();
}};
} else {
clickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
delayedCleanupAfterDisconnect();
}};
cancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
delayedCleanupAfterDisconnect();
}};
}
// TODO: Consider adding a setTitle() call here (with some generic
// "failure" title?)
mGenericErrorDialog = new AlertDialog.Builder(this)
.setMessage(msg)
.setPositiveButton(R.string.ok, clickListener)
.setOnCancelListener(cancelListener)
.create();
// When the dialog is up, completely hide the in-call UI
// underneath (which is in a partially-constructed state).
mGenericErrorDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mGenericErrorDialog.show();
}
private void showCallLostDialog() {
if (DBG) log("showCallLostDialog()...");
// Don't need to show the dialog if InCallScreen isn't in the forgeround
if (!mIsForegroundActivity) {
if (DBG) log("showCallLostDialog: not the foreground Activity! Bailing out...");
return;
}
// Don't need to show the dialog again, if there is one already.
if (mCallLostDialog != null) {
if (DBG) log("showCallLostDialog: There is a mCallLostDialog already.");
return;
}
mCallLostDialog = new AlertDialog.Builder(this)
.setMessage(R.string.call_lost)
.setIcon(android.R.drawable.ic_dialog_alert)
.create();
mCallLostDialog.show();
}
/**
* Displays the "Exiting ECM" warning dialog.
*
* Background: If the phone is currently in ECM (Emergency callback
* mode) and we dial a non-emergency number, that automatically
* *cancels* ECM. (That behavior comes from CdmaCallTracker.dial().)
* When that happens, we need to warn the user that they're no longer
* in ECM (bug 4207607.)
*
* So bring up a dialog explaining what's happening. There's nothing
* for the user to do, by the way; we're simply providing an
* indication that they're exiting ECM. We *could* use a Toast for
* this, but toasts are pretty easy to miss, so instead use a dialog
* with a single "OK" button.
*
* TODO: it's ugly that the code here has to make assumptions about
* the behavior of the telephony layer (namely that dialing a
* non-emergency number while in ECM causes us to exit ECM.)
*
* Instead, this warning dialog should really be triggered by our
* handler for the
* TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED intent in
* PhoneApp.java. But that won't work until that intent also
* includes a *reason* why we're exiting ECM, since we need to
* display this dialog when exiting ECM because of an outgoing call,
* but NOT if we're exiting ECM because the user manually turned it
* off via the EmergencyCallbackModeExitDialog.
*
* Or, it might be simpler to just have outgoing non-emergency calls
* *not* cancel ECM. That way the UI wouldn't have to do anything
* special here.
*/
private void showExitingECMDialog() {
Log.i(LOG_TAG, "showExitingECMDialog()...");
if (mExitingECMDialog != null) {
if (DBG) log("- DISMISSING mExitingECMDialog.");
mExitingECMDialog.dismiss(); // safe even if already dismissed
mExitingECMDialog = null;
}
// When the user dismisses the "Exiting ECM" dialog, we clear out
// the pending call status code field (since we're done with this
// dialog), but do *not* bail out of the InCallScreen.
final InCallUiState inCallUiState = mApp.inCallUiState;
DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
inCallUiState.clearPendingCallStatusCode();
}};
OnCancelListener cancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
inCallUiState.clearPendingCallStatusCode();
}};
// Ultra-simple AlertDialog with only an OK button:
mExitingECMDialog = new AlertDialog.Builder(this)
.setMessage(R.string.progress_dialog_exiting_ecm)
.setPositiveButton(R.string.ok, clickListener)
.setOnCancelListener(cancelListener)
.create();
mExitingECMDialog.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
mExitingECMDialog.show();
}
private void bailOutAfterErrorDialog() {
if (mGenericErrorDialog != null) {
if (DBG) log("bailOutAfterErrorDialog: DISMISSING mGenericErrorDialog.");
mGenericErrorDialog.dismiss();
mGenericErrorDialog = null;
}
if (DBG) log("bailOutAfterErrorDialog(): end InCallScreen session...");
// Now that the user has dismissed the error dialog (presumably by
// either hitting the OK button or pressing Back, we can now reset
// the pending call status code field.
//
// (Note that the pending call status is NOT cleared simply
// by the InCallScreen being paused or finished, since the resulting
// dialog is supposed to persist across orientation changes or if the
// screen turns off.)
//
// See the "Error / diagnostic indications" section of
// InCallUiState.java for more detailed info about the
// pending call status code field.
final InCallUiState inCallUiState = mApp.inCallUiState;
inCallUiState.clearPendingCallStatusCode();
// Force the InCallScreen to truly finish(), rather than just
// moving it to the back of the activity stack (which is what
// our finish() method usually does.)
// This is necessary to avoid an obscure scenario where the
// InCallScreen can get stuck in an inconsistent state, somehow
// causing a *subsequent* outgoing call to fail (bug 4172599).
endInCallScreenSession(true /* force a real finish() call */);
}
/**
* Dismisses (and nulls out) all persistent Dialogs managed
* by the InCallScreen. Useful if (a) we're about to bring up
* a dialog and want to pre-empt any currently visible dialogs,
* or (b) as a cleanup step when the Activity is going away.
*/
private void dismissAllDialogs() {
if (DBG) log("dismissAllDialogs()...");
// Note it's safe to dismiss() a dialog that's already dismissed.
// (Even if the AlertDialog object(s) below are still around, it's
// possible that the actual dialog(s) may have already been
// dismissed by the user.)
if (mMissingVoicemailDialog != null) {
if (VDBG) log("- DISMISSING mMissingVoicemailDialog.");
mMissingVoicemailDialog.dismiss();
mMissingVoicemailDialog = null;
}
if (mMmiStartedDialog != null) {
if (VDBG) log("- DISMISSING mMmiStartedDialog.");
mMmiStartedDialog.dismiss();
mMmiStartedDialog = null;
}
if (mGenericErrorDialog != null) {
if (VDBG) log("- DISMISSING mGenericErrorDialog.");
mGenericErrorDialog.dismiss();
mGenericErrorDialog = null;
}
if (mSuppServiceFailureDialog != null) {
if (VDBG) log("- DISMISSING mSuppServiceFailureDialog.");
mSuppServiceFailureDialog.dismiss();
mSuppServiceFailureDialog = null;
}
if (mWaitPromptDialog != null) {
if (VDBG) log("- DISMISSING mWaitPromptDialog.");
mWaitPromptDialog.dismiss();
mWaitPromptDialog = null;
}
if (mWildPromptDialog != null) {
if (VDBG) log("- DISMISSING mWildPromptDialog.");
mWildPromptDialog.dismiss();
mWildPromptDialog = null;
}
if (mCallLostDialog != null) {
if (VDBG) log("- DISMISSING mCallLostDialog.");
mCallLostDialog.dismiss();
mCallLostDialog = null;
}
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL
|| mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED)
&& mApp.otaUtils != null) {
mApp.otaUtils.dismissAllOtaDialogs();
}
if (mPausePromptDialog != null) {
if (DBG) log("- DISMISSING mPausePromptDialog.");
mPausePromptDialog.dismiss();
mPausePromptDialog = null;
}
if (mExitingECMDialog != null) {
if (DBG) log("- DISMISSING mExitingECMDialog.");
mExitingECMDialog.dismiss();
mExitingECMDialog = null;
}
}
/**
* Updates the state of the onscreen "progress indication" used in
* some (relatively rare) scenarios where we need to wait for
* something to happen before enabling the in-call UI.
*
* If necessary, this method will cause a ProgressDialog (i.e. a
* spinning wait cursor) to be drawn *on top of* whatever the current
* state of the in-call UI is.
*
* @see InCallUiState.ProgressIndicationType
*/
private void updateProgressIndication() {
// If an incoming call is ringing, that takes priority over any
// possible value of inCallUiState.progressIndication.
if (mCM.hasActiveRingingCall()) {
dismissProgressIndication();
return;
}
// Otherwise, put up a progress indication if indicated by the
// inCallUiState.progressIndication field.
final InCallUiState inCallUiState = mApp.inCallUiState;
switch (inCallUiState.getProgressIndication()) {
case NONE:
// No progress indication necessary, so make sure it's dismissed.
dismissProgressIndication();
break;
case TURNING_ON_RADIO:
showProgressIndication(
R.string.emergency_enable_radio_dialog_title,
R.string.emergency_enable_radio_dialog_message);
break;
case RETRYING:
showProgressIndication(
R.string.emergency_enable_radio_dialog_title,
R.string.emergency_enable_radio_dialog_retry);
break;
default:
Log.wtf(LOG_TAG, "updateProgressIndication: unexpected value: "
+ inCallUiState.getProgressIndication());
dismissProgressIndication();
break;
}
}
/**
* Show an onscreen "progress indication" with the specified title and message.
*/
private void showProgressIndication(int titleResId, int messageResId) {
if (DBG) log("showProgressIndication(message " + messageResId + ")...");
// TODO: make this be a no-op if the progress indication is
// already visible with the exact same title and message.
dismissProgressIndication(); // Clean up any prior progress indication
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getText(titleResId));
mProgressDialog.setMessage(getText(messageResId));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
mProgressDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
mProgressDialog.show();
}
/**
* Dismiss the onscreen "progress indication" (if present).
*/
private void dismissProgressIndication() {
if (DBG) log("dismissProgressIndication()...");
if (mProgressDialog != null) {
mProgressDialog.dismiss(); // safe even if already dismissed
mProgressDialog = null;
}
}
//
// Helper functions for answering incoming calls.
//
/**
* Answer a ringing call. This method does nothing if there's no
* ringing or waiting call.
*/
private void internalAnswerCall() {
log("internalAnswerCall()...");
// if (DBG) PhoneUtils.dumpCallState(mPhone);
final boolean hasRingingCall = mCM.hasActiveRingingCall();
if (hasRingingCall) {
Phone phone = mCM.getRingingPhone();
Call ringing = mCM.getFirstActiveRingingCall();
int phoneType = phone.getPhoneType();
if (phoneType == Phone.PHONE_TYPE_CDMA) {
if (DBG) log("internalAnswerCall: answering (CDMA)...");
if (mCM.hasActiveFgCall()
&& mCM.getFgPhone().getPhoneType() == Phone.PHONE_TYPE_SIP) {
// The incoming call is CDMA call and the ongoing
// call is a SIP call. The CDMA network does not
// support holding an active call, so there's no
// way to swap between a CDMA call and a SIP call.
// So for now, we just don't allow a CDMA call and
// a SIP call to be active at the same time.We'll
// "answer incoming, end ongoing" in this case.
if (DBG) log("internalAnswerCall: answer "
+ "CDMA incoming and end SIP ongoing");
PhoneUtils.answerAndEndActive(mCM, ringing);
} else {
PhoneUtils.answerCall(ringing);
}
} else if (phoneType == Phone.PHONE_TYPE_SIP) {
if (DBG) log("internalAnswerCall: answering (SIP)...");
if (mCM.hasActiveFgCall()
&& mCM.getFgPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA) {
// Similar to the PHONE_TYPE_CDMA handling.
// The incoming call is SIP call and the ongoing
// call is a CDMA call. The CDMA network does not
// support holding an active call, so there's no
// way to swap between a CDMA call and a SIP call.
// So for now, we just don't allow a CDMA call and
// a SIP call to be active at the same time.We'll
// "answer incoming, end ongoing" in this case.
if (DBG) log("internalAnswerCall: answer "
+ "SIP incoming and end CDMA ongoing");
PhoneUtils.answerAndEndActive(mCM, ringing);
} else {
PhoneUtils.answerCall(ringing);
}
}else if (phoneType == Phone.PHONE_TYPE_GSM){
// GSM: this is usually just a wrapper around
// PhoneUtils.answerCall(), *but* we also need to do
// something special for the "both lines in use" case.
final boolean hasActiveCall = mCM.hasActiveFgCall();
final boolean hasHoldingCall = mCM.hasActiveBgCall();
if (hasActiveCall && hasHoldingCall) {
if (DBG) log("internalAnswerCall: answering (both lines in use!)...");
// The relatively rare case where both lines are
// already in use. We "answer incoming, end ongoing"
// in this case, according to the current UI spec.
PhoneUtils.answerAndEndActive(mCM, ringing);
// Alternatively, we could use
// PhoneUtils.answerAndEndHolding(mPhone);
// here to end the on-hold call instead.
} else {
if (DBG) log("internalAnswerCall: answering...");
PhoneUtils.answerCall(ringing); // Automatically holds the current active call,
// if there is one
}
} else {
throw new IllegalStateException("Unexpected phone type: " + phoneType);
}
// Call origin is valid only with outgoing calls. Disable it on incoming calls.
mApp.setLatestActiveCallOrigin(null);
}
}
/**
* Answer the ringing call *and* hang up the ongoing call.
*/
private void internalAnswerAndEnd() {
if (DBG) log("internalAnswerAndEnd()...");
if (VDBG) PhoneUtils.dumpCallManager();
// In the rare case when multiple calls are ringing, the UI policy
// it to always act on the first ringing call.
PhoneUtils.answerAndEndActive(mCM, mCM.getFirstActiveRingingCall());
}
/**
* Hang up the ringing call (aka "Don't answer").
*/
/* package */ void hangupRingingCall() {
if (DBG) log("hangupRingingCall()...");
if (VDBG) PhoneUtils.dumpCallManager();
// In the rare case when multiple calls are ringing, the UI policy
// it to always act on the first ringing call.
PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall());
}
/**
* Silence the ringer (if an incoming call is ringing.)
*/
private void internalSilenceRinger() {
if (DBG) log("internalSilenceRinger()...");
final CallNotifier notifier = mApp.notifier;
if (notifier.isRinging()) {
// ringer is actually playing, so silence it.
notifier.silenceRinger();
}
}
/**
* Respond via SMS to the ringing call.
* @see RespondViaSmsManager
*/
private void internalRespondViaSms() {
log("internalRespondViaSms()...");
if (VDBG) PhoneUtils.dumpCallManager();
if (mRespondViaSmsManager == null) {
throw new IllegalStateException(
"got internalRespondViaSms(), but mRespondViaSmsManager was never initialized");
}
// In the rare case when multiple calls are ringing, the UI policy
// it to always act on the first ringing call.
Call ringingCall = mCM.getFirstActiveRingingCall();
mRespondViaSmsManager.showRespondViaSmsPopup(ringingCall);
// Silence the ringer, since it would be distracting while you're trying
// to pick a response. (Note that we'll restart the ringer if you bail
// out of the popup, though; see RespondViaSmsCancelListener.)
internalSilenceRinger();
}
/**
* Hang up the current active call.
*/
private void internalHangup() {
Phone.State state = mCM.getState();
log("internalHangup()... phone state = " + state);
// Regardless of the phone state, issue a hangup request.
// (If the phone is already idle, this call will presumably have no
// effect (but also see the note below.))
PhoneUtils.hangup(mCM);
// If the user just hung up the only active call, we'll eventually exit
// the in-call UI after the following sequence:
// - When the hangup() succeeds, we'll get a DISCONNECT event from
// the telephony layer (see onDisconnect()).
// - We immediately switch to the "Call ended" state (see the "delayed
// bailout" code path in onDisconnect()) and also post a delayed
// DELAYED_CLEANUP_AFTER_DISCONNECT message.
// - When the DELAYED_CLEANUP_AFTER_DISCONNECT message comes in (see
// delayedCleanupAfterDisconnect()) we do some final cleanup, and exit
// this activity unless the phone is still in use (i.e. if there's
// another call, or something else going on like an active MMI
// sequence.)
if (state == Phone.State.IDLE) {
// The user asked us to hang up, but the phone was (already) idle!
Log.w(LOG_TAG, "internalHangup(): phone is already IDLE!");
// This is rare, but can happen in a few cases:
// (a) If the user quickly double-taps the "End" button. In this case
// we'll see that 2nd press event during the brief "Call ended"
// state (where the phone is IDLE), or possibly even before the
// radio has been able to respond to the initial hangup request.
// (b) More rarely, this can happen if the user presses "End" at the
// exact moment that the call ends on its own (like because of the
// other person hanging up.)
// (c) Finally, this could also happen if we somehow get stuck here on
// the InCallScreen with the phone truly idle, perhaps due to a
// bug where we somehow *didn't* exit when the phone became idle
// in the first place.
// TODO: as a "safety valve" for case (c), consider immediately
// bailing out of the in-call UI right here. (The user can always
// bail out by pressing Home, of course, but they'll probably try
// pressing End first.)
//
// Log.i(LOG_TAG, "internalHangup(): phone is already IDLE! Bailing out...");
// endInCallScreenSession();
}
}
/**
* InCallScreen-specific wrapper around PhoneUtils.switchHoldingAndActive().
*/
private void internalSwapCalls() {
if (DBG) log("internalSwapCalls()...");
// Any time we swap calls, force the DTMF dialpad to close.
// (We want the regular in-call UI to be visible right now, so the
// user can clearly see which call is now in the foreground.)
hideDialpadInternal(true); // do the "closing" animation
// Also, clear out the "history" of DTMF digits you typed, to make
// sure you don't see digits from call #1 while call #2 is active.
// (Yes, this does mean that swapping calls twice will cause you
// to lose any previous digits from the current call; see the TODO
// comment on DTMFTwelvKeyDialer.clearDigits() for more info.)
mDialer.clearDigits();
// Swap the fg and bg calls.
// In the future we may provides some way for user to choose among
// multiple background calls, for now, always act on the first background calll.
PhoneUtils.switchHoldingAndActive(mCM.getFirstActiveBgCall());
// If we have a valid BluetoothHandsfree then since CDMA network or
// Telephony FW does not send us information on which caller got swapped
// we need to update the second call active state in BluetoothHandsfree internally
if (mCM.getBgPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA) {
BluetoothHandsfree bthf = mApp.getBluetoothHandsfree();
if (bthf != null) {
bthf.cdmaSwapSecondCallState();
}
}
}
/**
* Sets the current high-level "mode" of the in-call UI.
*
* NOTE: if newMode is CALL_ENDED, the caller is responsible for
* posting a delayed DELAYED_CLEANUP_AFTER_DISCONNECT message, to make
* sure the "call ended" state goes away after a couple of seconds.
*
* Note this method does NOT refresh of the onscreen UI; the caller is
* responsible for calling updateScreen() or requestUpdateScreen() if
* necessary.
*/
private void setInCallScreenMode(InCallScreenMode newMode) {
if (DBG) log("setInCallScreenMode: " + newMode);
mApp.inCallUiState.inCallScreenMode = newMode;
switch (newMode) {
case MANAGE_CONFERENCE:
if (!PhoneUtils.isConferenceCall(mCM.getActiveFgCall())) {
Log.w(LOG_TAG, "MANAGE_CONFERENCE: no active conference call!");
// Hide the Manage Conference panel, return to NORMAL mode.
setInCallScreenMode(InCallScreenMode.NORMAL);
return;
}
List<Connection> connections = mCM.getFgCallConnections();
// There almost certainly will be > 1 connection,
// since isConferenceCall() just returned true.
if ((connections == null) || (connections.size() <= 1)) {
Log.w(LOG_TAG,
"MANAGE_CONFERENCE: Bogus TRUE from isConferenceCall(); connections = "
+ connections);
// Hide the Manage Conference panel, return to NORMAL mode.
setInCallScreenMode(InCallScreenMode.NORMAL);
return;
}
// TODO: Don't do this here. The call to
// initManageConferencePanel() should instead happen
// automagically in ManageConferenceUtils the very first
// time you call updateManageConferencePanel() or
// setPanelVisible(true).
mManageConferenceUtils.initManageConferencePanel(); // if necessary
mManageConferenceUtils.updateManageConferencePanel(connections);
// The "Manage conference" UI takes up the full main frame,
// replacing the inCallPanel and CallCard PopupWindow.
mManageConferenceUtils.setPanelVisible(true);
// Start the chronometer.
// TODO: Similarly, we shouldn't expose startConferenceTime()
// and stopConferenceTime(); the ManageConferenceUtils
// class ought to manage the conferenceTime widget itself
// based on setPanelVisible() calls.
// Note: there is active Fg call since we are in conference call
long callDuration =
mCM.getActiveFgCall().getEarliestConnection().getDurationMillis();
mManageConferenceUtils.startConferenceTime(
SystemClock.elapsedRealtime() - callDuration);
mInCallPanel.setVisibility(View.GONE);
// No need to close the dialer here, since the Manage
// Conference UI will just cover it up anyway.
break;
case CALL_ENDED:
// Display the CallCard (in the "Call ended" state)
// and hide all other UI.
mManageConferenceUtils.setPanelVisible(false);
mManageConferenceUtils.stopConferenceTime();
// Make sure the CallCard (which is a child of mInCallPanel) is visible.
mInCallPanel.setVisibility(View.VISIBLE);
break;
case NORMAL:
if (isDialerOpened()) {
mInCallPanel.setVisibility(View.GONE);
} else {
mInCallPanel.setVisibility(View.VISIBLE);
}
mManageConferenceUtils.setPanelVisible(false);
mManageConferenceUtils.stopConferenceTime();
break;
case OTA_NORMAL:
mApp.otaUtils.setCdmaOtaInCallScreenUiState(
OtaUtils.CdmaOtaInCallScreenUiState.State.NORMAL);
mInCallPanel.setVisibility(View.GONE);
break;
case OTA_ENDED:
mApp.otaUtils.setCdmaOtaInCallScreenUiState(
OtaUtils.CdmaOtaInCallScreenUiState.State.ENDED);
mInCallPanel.setVisibility(View.GONE);
break;
case UNDEFINED:
// Set our Activities intent to ACTION_UNDEFINED so
// that if we get resumed after we've completed a call
// the next call will not cause checkIsOtaCall to
// return true.
//
// TODO(OTASP): update these comments
//
// With the framework as of October 2009 the sequence below
// causes the framework to call onResume, onPause, onNewIntent,
// onResume. If we don't call setIntent below then when the
// first onResume calls checkIsOtaCall via checkOtaspStateOnResume it will
// return true and the Activity will be confused.
//
// 1) Power up Phone A
// 2) Place *22899 call and activate Phone A
// 3) Press the power key on Phone A to turn off the display
// 4) Call Phone A from Phone B answering Phone A
// 5) The screen will be blank (Should be normal InCallScreen)
// 6) Hang up the Phone B
// 7) Phone A displays the activation screen.
//
// Step 3 is the critical step to cause the onResume, onPause
// onNewIntent, onResume sequence. If step 3 is skipped the
// sequence will be onNewIntent, onResume and all will be well.
setIntent(new Intent(ACTION_UNDEFINED));
// Cleanup Ota Screen if necessary and set the panel
// to VISIBLE.
if (mCM.getState() != Phone.State.OFFHOOK) {
if (mApp.otaUtils != null) {
mApp.otaUtils.cleanOtaScreen(true);
}
} else {
log("WARNING: Setting mode to UNDEFINED but phone is OFFHOOK,"
+ " skip cleanOtaScreen.");
}
mInCallPanel.setVisibility(View.VISIBLE);
break;
}
}
/**
* @return true if the "Manage conference" UI is currently visible.
*/
/* package */ boolean isManageConferenceMode() {
return (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.MANAGE_CONFERENCE);
}
/**
* Checks if the "Manage conference" UI needs to be updated.
* If the state of the current conference call has changed
* since our previous call to updateManageConferencePanel()),
* do a fresh update. Also, if the current call is no longer a
* conference call at all, bail out of the "Manage conference" UI and
* return to InCallScreenMode.NORMAL mode.
*/
private void updateManageConferencePanelIfNecessary() {
if (VDBG) log("updateManageConferencePanelIfNecessary: " + mCM.getActiveFgCall() + "...");
List<Connection> connections = mCM.getFgCallConnections();
if (connections == null) {
if (VDBG) log("==> no connections on foreground call!");
// Hide the Manage Conference panel, return to NORMAL mode.
setInCallScreenMode(InCallScreenMode.NORMAL);
SyncWithPhoneStateStatus status = syncWithPhoneState();
if (status != SyncWithPhoneStateStatus.SUCCESS) {
Log.w(LOG_TAG, "- syncWithPhoneState failed! status = " + status);
// We shouldn't even be in the in-call UI in the first
// place, so bail out:
if (DBG) log("updateManageConferencePanelIfNecessary: endInCallScreenSession... 1");
endInCallScreenSession();
return;
}
return;
}
int numConnections = connections.size();
if (numConnections <= 1) {
if (VDBG) log("==> foreground call no longer a conference!");
// Hide the Manage Conference panel, return to NORMAL mode.
setInCallScreenMode(InCallScreenMode.NORMAL);
SyncWithPhoneStateStatus status = syncWithPhoneState();
if (status != SyncWithPhoneStateStatus.SUCCESS) {
Log.w(LOG_TAG, "- syncWithPhoneState failed! status = " + status);
// We shouldn't even be in the in-call UI in the first
// place, so bail out:
if (DBG) log("updateManageConferencePanelIfNecessary: endInCallScreenSession... 2");
endInCallScreenSession();
return;
}
return;
}
// TODO: the test to see if numConnections has changed can go in
// updateManageConferencePanel(), rather than here.
if (numConnections != mManageConferenceUtils.getNumCallersInConference()) {
if (VDBG) log("==> Conference size has changed; need to rebuild UI!");
mManageConferenceUtils.updateManageConferencePanel(connections);
}
}
/**
* Updates the visibility of the DTMF dialpad (and its onscreen
* "handle", if applicable), based on the current state of the phone
* and/or the current InCallScreenMode.
*/
private void updateDialpadVisibility() {
//
// (1) The dialpad itself:
//
// If an incoming call is ringing, make sure the dialpad is
// closed. (We do this to make sure we're not covering up the
// "incoming call" UI, and especially to make sure that the "touch
// lock" overlay won't appear.)
if (mCM.getState() == Phone.State.RINGING) {
hideDialpadInternal(false); // don't do the "closing" animation
// Also, clear out the "history" of DTMF digits you may have typed
// into the previous call (so you don't see the previous call's
// digits if you answer this call and then bring up the dialpad.)
//
// TODO: it would be more precise to do this when you *answer* the
// incoming call, rather than as soon as it starts ringing, but
// the InCallScreen doesn't keep enough state right now to notice
// that specific transition in onPhoneStateChanged().
mDialer.clearDigits();
}
//
// (2) The main in-call panel (containing the CallCard):
//
// We need to hide the CallCard (which is a
// child of mInCallPanel) while the dialpad is visible.
//
if (isDialerOpened()) {
if (VDBG) log("- updateDialpadVisibility: dialpad open, hide mInCallPanel...");
CallCard.Fade.hide(mInCallPanel, View.GONE);
} else {
// Dialpad is dismissed; bring back the CallCard if
// it's supposed to be visible.
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.NORMAL)
|| (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.CALL_ENDED)) {
if (VDBG) log("- updateDialpadVisibility: dialpad dismissed, show mInCallPanel...");
CallCard.Fade.show(mInCallPanel);
}
}
}
/**
* @return true if the DTMF dialpad is currently visible.
*/
/* package */ boolean isDialerOpened() {
return (mDialer != null && mDialer.isOpened());
}
/**
* Called any time the DTMF dialpad is opened.
* @see DTMFTwelveKeyDialer.onDialerOpen()
*/
/* package */ void onDialerOpen() {
if (DBG) log("onDialerOpen()...");
// Update the in-call touch UI.
updateInCallTouchUi();
// Update any other onscreen UI elements that depend on the dialpad.
updateDialpadVisibility();
// This counts as explicit "user activity".
mApp.pokeUserActivity();
//If on OTA Call, hide OTA Screen
// TODO: This may not be necessary, now that the dialpad is
// always visible in OTA mode.
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL
|| mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED)
&& mApp.otaUtils != null) {
mApp.otaUtils.hideOtaScreen();
}
}
/**
* Called any time the DTMF dialpad is closed.
* @see DTMFTwelveKeyDialer.onDialerClose()
*/
/* package */ void onDialerClose() {
if (DBG) log("onDialerClose()...");
// OTA-specific cleanup upon closing the dialpad.
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL)
|| (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED)
|| ((mApp.cdmaOtaScreenState != null)
&& (mApp.cdmaOtaScreenState.otaScreenState ==
CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION))) {
if (mApp.otaUtils != null) {
mApp.otaUtils.otaShowProperScreen();
}
}
// Update the in-call touch UI.
updateInCallTouchUi();
// Update the visibility of the dialpad itself (and any other
// onscreen UI elements that depend on it.)
updateDialpadVisibility();
// This counts as explicit "user activity".
mApp.pokeUserActivity();
}
/**
* Determines when we can dial DTMF tones.
*/
private boolean okToDialDTMFTones() {
final boolean hasRingingCall = mCM.hasActiveRingingCall();
final Call.State fgCallState = mCM.getActiveFgCallState();
// We're allowed to send DTMF tones when there's an ACTIVE
// foreground call, and not when an incoming call is ringing
// (since DTMF tones are useless in that state), or if the
// Manage Conference UI is visible (since the tab interferes
// with the "Back to call" button.)
// We can also dial while in ALERTING state because there are
// some connections that never update to an ACTIVE state (no
// indication from the network).
boolean canDial =
(fgCallState == Call.State.ACTIVE || fgCallState == Call.State.ALERTING)
&& !hasRingingCall
&& (mApp.inCallUiState.inCallScreenMode != InCallScreenMode.MANAGE_CONFERENCE);
if (VDBG) log ("[okToDialDTMFTones] foreground state: " + fgCallState +
", ringing state: " + hasRingingCall +
", call screen mode: " + mApp.inCallUiState.inCallScreenMode +
", result: " + canDial);
return canDial;
}
/**
* @return true if the in-call DTMF dialpad should be available to the
* user, given the current state of the phone and the in-call UI.
* (This is used to control the enabledness of the "Show
* dialpad" onscreen button; see InCallControlState.dialpadEnabled.)
*/
/* package */ boolean okToShowDialpad() {
// The dialpad is available only when it's OK to dial DTMF
// tones given the current state of the current call.
return okToDialDTMFTones();
}
/**
* Initializes the in-call touch UI on devices that need it.
*/
private void initInCallTouchUi() {
if (DBG) log("initInCallTouchUi()...");
// TODO: we currently use the InCallTouchUi widget in at least
// some states on ALL platforms. But if some devices ultimately
// end up not using *any* onscreen touch UI, we should make sure
// to not even inflate the InCallTouchUi widget on those devices.
mInCallTouchUi = (InCallTouchUi) findViewById(R.id.inCallTouchUi);
mInCallTouchUi.setInCallScreenInstance(this);
// RespondViaSmsManager implements the "Respond via SMS"
// feature that's triggered from the incoming call widget.
mRespondViaSmsManager = new RespondViaSmsManager();
mRespondViaSmsManager.setInCallScreenInstance(this);
}
/**
* Updates the state of the in-call touch UI.
*/
private void updateInCallTouchUi() {
if (mInCallTouchUi != null) {
mInCallTouchUi.updateState(mCM);
}
}
/**
* @return the InCallTouchUi widget
*/
/* package */ InCallTouchUi getInCallTouchUi() {
return mInCallTouchUi;
}
/**
* Posts a handler message telling the InCallScreen to refresh the
* onscreen in-call UI.
*
* This is just a wrapper around updateScreen(), for use by the
* rest of the phone app or from a thread other than the UI thread.
*
* updateScreen() is a no-op if the InCallScreen is not the foreground
* activity, so it's safe to call this whether or not the InCallScreen
* is currently visible.
*/
/* package */ void requestUpdateScreen() {
if (DBG) log("requestUpdateScreen()...");
mHandler.removeMessages(REQUEST_UPDATE_SCREEN);
mHandler.sendEmptyMessage(REQUEST_UPDATE_SCREEN);
}
/**
* @return true if it's OK to display the in-call touch UI, given the
* current state of the InCallScreen.
*/
/* package */ boolean okToShowInCallTouchUi() {
// Note that this method is concerned only with the internal state
// of the InCallScreen. (The InCallTouchUi widget has separate
// logic to make sure it's OK to display the touch UI given the
// current telephony state, and that it's allowed on the current
// device in the first place.)
// The touch UI is available in the following InCallScreenModes:
// - NORMAL (obviously)
// - CALL_ENDED (which is intended to look mostly the same as
// a normal in-call state, even though the in-call
// buttons are mostly disabled)
// and is hidden in any of the other modes, like MANAGE_CONFERENCE
// or one of the OTA modes (which use totally different UIs.)
return ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.NORMAL)
|| (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.CALL_ENDED));
}
/**
* @return true if we're in restricted / emergency dialing only mode.
*/
public boolean isPhoneStateRestricted() {
// TODO: This needs to work IN TANDEM with the KeyGuardViewMediator Code.
// Right now, it looks like the mInputRestricted flag is INTERNAL to the
// KeyGuardViewMediator and SPECIFICALLY set to be FALSE while the emergency
// phone call is being made, to allow for input into the InCallScreen.
// Having the InCallScreen judge the state of the device from this flag
// becomes meaningless since it is always false for us. The mediator should
// have an additional API to let this app know that it should be restricted.
int serviceState = mCM.getServiceState();
return ((serviceState == ServiceState.STATE_EMERGENCY_ONLY) ||
(serviceState == ServiceState.STATE_OUT_OF_SERVICE) ||
(mApp.getKeyguardManager().inKeyguardRestrictedInputMode()));
}
//
// Bluetooth helper methods.
//
// - BluetoothAdapter is the Bluetooth system service. If
// getDefaultAdapter() returns null
// then the device is not BT capable. Use BluetoothDevice.isEnabled()
// to see if BT is enabled on the device.
//
// - BluetoothHeadset is the API for the control connection to a
// Bluetooth Headset. This lets you completely connect/disconnect a
// headset (which we don't do from the Phone UI!) but also lets you
// get the address of the currently active headset and see whether
// it's currently connected.
//
// - BluetoothHandsfree is the API to control the audio connection to
// a bluetooth headset. We use this API to switch the headset on and
// off when the user presses the "Bluetooth" button.
// Our BluetoothHandsfree instance (mBluetoothHandsfree) is created
// by the PhoneApp and will be null if the device is not BT capable.
//
/**
* @return true if the Bluetooth on/off switch in the UI should be
* available to the user (i.e. if the device is BT-capable
* and a headset is connected.)
*/
/* package */ boolean isBluetoothAvailable() {
if (VDBG) log("isBluetoothAvailable()...");
if (mBluetoothHandsfree == null) {
// Device is not BT capable.
if (VDBG) log(" ==> FALSE (not BT capable)");
return false;
}
// There's no need to ask the Bluetooth system service if BT is enabled:
//
// BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
// if ((adapter == null) || !adapter.isEnabled()) {
// if (DBG) log(" ==> FALSE (BT not enabled)");
// return false;
// }
// if (DBG) log(" - BT enabled! device name " + adapter.getName()
// + ", address " + adapter.getAddress());
//
// ...since we already have a BluetoothHeadset instance. We can just
// call isConnected() on that, and assume it'll be false if BT isn't
// enabled at all.
// Check if there's a connected headset, using the BluetoothHeadset API.
boolean isConnected = false;
if (mBluetoothHeadset != null) {
List<BluetoothDevice> deviceList = mBluetoothHeadset.getConnectedDevices();
if (deviceList.size() > 0) {
BluetoothDevice device = deviceList.get(0);
isConnected = true;
if (VDBG) log(" - headset state = " +
mBluetoothHeadset.getConnectionState(device));
if (VDBG) log(" - headset address: " + device);
if (VDBG) log(" - isConnected: " + isConnected);
}
}
if (VDBG) log(" ==> " + isConnected);
return isConnected;
}
/**
* @return true if a BT device is available, and its audio is currently connected.
*/
/* package */ boolean isBluetoothAudioConnected() {
if (mBluetoothHandsfree == null) {
if (VDBG) log("isBluetoothAudioConnected: ==> FALSE (null mBluetoothHandsfree)");
return false;
}
boolean isAudioOn = mBluetoothHandsfree.isAudioOn();
if (VDBG) log("isBluetoothAudioConnected: ==> isAudioOn = " + isAudioOn);
return isAudioOn;
}
/**
* Helper method used to control the onscreen "Bluetooth" indication;
* see InCallControlState.bluetoothIndicatorOn.
*
* @return true if a BT device is available and its audio is currently connected,
* <b>or</b> if we issued a BluetoothHandsfree.userWantsAudioOn()
* call within the last 5 seconds (which presumably means
* that the BT audio connection is currently being set
* up, and will be connected soon.)
*/
/* package */ boolean isBluetoothAudioConnectedOrPending() {
if (isBluetoothAudioConnected()) {
if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> TRUE (really connected)");
return true;
}
// If we issued a userWantsAudioOn() call "recently enough", even
// if BT isn't actually connected yet, let's still pretend BT is
// on. This makes the onscreen indication more responsive.
if (mBluetoothConnectionPending) {
long timeSinceRequest =
SystemClock.elapsedRealtime() - mBluetoothConnectionRequestTime;
if (timeSinceRequest < 5000 /* 5 seconds */) {
if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> TRUE (requested "
+ timeSinceRequest + " msec ago)");
return true;
} else {
if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> FALSE (request too old: "
+ timeSinceRequest + " msec ago)");
mBluetoothConnectionPending = false;
return false;
}
}
if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> FALSE");
return false;
}
/**
* Posts a message to our handler saying to update the onscreen UI
* based on a bluetooth headset state change.
*/
/* package */ void requestUpdateBluetoothIndication() {
if (VDBG) log("requestUpdateBluetoothIndication()...");
// No need to look at the current state here; any UI elements that
// care about the bluetooth state (i.e. the CallCard) get
// the necessary state directly from PhoneApp.showBluetoothIndication().
mHandler.removeMessages(REQUEST_UPDATE_BLUETOOTH_INDICATION);
mHandler.sendEmptyMessage(REQUEST_UPDATE_BLUETOOTH_INDICATION);
}
private void dumpBluetoothState() {
log("============== dumpBluetoothState() =============");
log("= isBluetoothAvailable: " + isBluetoothAvailable());
log("= isBluetoothAudioConnected: " + isBluetoothAudioConnected());
log("= isBluetoothAudioConnectedOrPending: " + isBluetoothAudioConnectedOrPending());
log("= PhoneApp.showBluetoothIndication: "
+ mApp.showBluetoothIndication());
log("=");
if (mBluetoothHandsfree != null) {
log("= BluetoothHandsfree.isAudioOn: " + mBluetoothHandsfree.isAudioOn());
if (mBluetoothHeadset != null) {
List<BluetoothDevice> deviceList = mBluetoothHeadset.getConnectedDevices();
if (deviceList.size() > 0) {
BluetoothDevice device = deviceList.get(0);
log("= BluetoothHeadset.getCurrentDevice: " + device);
log("= BluetoothHeadset.State: "
+ mBluetoothHeadset.getConnectionState(device));
}
} else {
log("= mBluetoothHeadset is null");
}
} else {
log("= mBluetoothHandsfree is null; device is not BT capable");
}
}
/* package */ void connectBluetoothAudio() {
if (VDBG) log("connectBluetoothAudio()...");
if (mBluetoothHandsfree != null) {
mBluetoothHandsfree.userWantsAudioOn();
}
// Watch out: The bluetooth connection doesn't happen instantly;
// the userWantsAudioOn() call returns instantly but does its real
// work in another thread. The mBluetoothConnectionPending flag
// is just a little trickery to ensure that the onscreen UI updates
// instantly. (See isBluetoothAudioConnectedOrPending() above.)
mBluetoothConnectionPending = true;
mBluetoothConnectionRequestTime = SystemClock.elapsedRealtime();
}
/* package */ void disconnectBluetoothAudio() {
if (VDBG) log("disconnectBluetoothAudio()...");
if (mBluetoothHandsfree != null) {
mBluetoothHandsfree.userWantsAudioOff();
}
mBluetoothConnectionPending = false;
}
/**
* Posts a handler message telling the InCallScreen to close
* the OTA failure notice after the specified delay.
* @see OtaUtils.otaShowProgramFailureNotice
*/
/* package */ void requestCloseOtaFailureNotice(long timeout) {
if (DBG) log("requestCloseOtaFailureNotice() with timeout: " + timeout);
mHandler.sendEmptyMessageDelayed(REQUEST_CLOSE_OTA_FAILURE_NOTICE, timeout);
// TODO: we probably ought to call removeMessages() for this
// message code in either onPause or onResume, just to be 100%
// sure that the message we just posted has no way to affect a
// *different* call if the user quickly backs out and restarts.
// (This is also true for requestCloseSpcErrorNotice() below, and
// probably anywhere else we use mHandler.sendEmptyMessageDelayed().)
}
/**
* Posts a handler message telling the InCallScreen to close
* the SPC error notice after the specified delay.
* @see OtaUtils.otaShowSpcErrorNotice
*/
/* package */ void requestCloseSpcErrorNotice(long timeout) {
if (DBG) log("requestCloseSpcErrorNotice() with timeout: " + timeout);
mHandler.sendEmptyMessageDelayed(REQUEST_CLOSE_SPC_ERROR_NOTICE, timeout);
}
public boolean isOtaCallInActiveState() {
if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL)
|| ((mApp.cdmaOtaScreenState != null)
&& (mApp.cdmaOtaScreenState.otaScreenState ==
CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION))) {
return true;
} else {
return false;
}
}
/**
* Handle OTA Call End scenario when display becomes dark during OTA Call
* and InCallScreen is in pause mode. CallNotifier will listen for call
* end indication and call this api to handle OTA Call end scenario
*/
public void handleOtaCallEnd() {
if (DBG) log("handleOtaCallEnd entering");
if (((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL)
|| ((mApp.cdmaOtaScreenState != null)
&& (mApp.cdmaOtaScreenState.otaScreenState !=
CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))
&& ((mApp.cdmaOtaProvisionData != null)
&& (!mApp.cdmaOtaProvisionData.inOtaSpcState))) {
if (DBG) log("handleOtaCallEnd - Set OTA Call End stater");
setInCallScreenMode(InCallScreenMode.OTA_ENDED);
updateScreen();
}
}
public boolean isOtaCallInEndState() {
return (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED);
}
/**
* Upon resuming the in-call UI, check to see if an OTASP call is in
* progress, and if so enable the special OTASP-specific UI.
*
* TODO: have a simple single flag in InCallUiState for this rather than
* needing to know about all those mApp.cdma*State objects.
*
* @return true if any OTASP-related UI is active
*/
private boolean checkOtaspStateOnResume() {
// If there's no OtaUtils instance, that means we haven't even tried
// to start an OTASP call (yet), so there's definitely nothing to do here.
if (mApp.otaUtils == null) {
if (DBG) log("checkOtaspStateOnResume: no OtaUtils instance; nothing to do.");
return false;
}
if ((mApp.cdmaOtaScreenState == null) || (mApp.cdmaOtaProvisionData == null)) {
// Uh oh -- something wrong with our internal OTASP state.
// (Since this is an OTASP-capable device, these objects
// *should* have already been created by PhoneApp.onCreate().)
throw new IllegalStateException("checkOtaspStateOnResume: "
+ "app.cdmaOta* objects(s) not initialized");
}
// The PhoneApp.cdmaOtaInCallScreenUiState instance is the
// authoritative source saying whether or not the in-call UI should
// show its OTASP-related UI.
OtaUtils.CdmaOtaInCallScreenUiState.State cdmaOtaInCallScreenState =
mApp.otaUtils.getCdmaOtaInCallScreenUiState();
// These states are:
// - UNDEFINED: no OTASP-related UI is visible
// - NORMAL: OTASP call in progress, so show in-progress OTASP UI
// - ENDED: OTASP call just ended, so show success/failure indication
boolean otaspUiActive =
(cdmaOtaInCallScreenState == OtaUtils.CdmaOtaInCallScreenUiState.State.NORMAL)
|| (cdmaOtaInCallScreenState == OtaUtils.CdmaOtaInCallScreenUiState.State.ENDED);
if (otaspUiActive) {
// Make sure the OtaUtils instance knows about the InCallScreen's
// OTASP-related UI widgets.
//
// (This call has no effect if the UI widgets have already been set up.
// It only really matters the very first time that the InCallScreen instance
// is onResume()d after starting an OTASP call.)
mApp.otaUtils.updateUiWidgets(this, mInCallPanel, mInCallTouchUi, mCallCard);
// Also update the InCallScreenMode based on the cdmaOtaInCallScreenState.
if (cdmaOtaInCallScreenState == OtaUtils.CdmaOtaInCallScreenUiState.State.NORMAL) {
if (DBG) log("checkOtaspStateOnResume - in OTA Normal mode");
setInCallScreenMode(InCallScreenMode.OTA_NORMAL);
} else if (cdmaOtaInCallScreenState ==
OtaUtils.CdmaOtaInCallScreenUiState.State.ENDED) {
if (DBG) log("checkOtaspStateOnResume - in OTA END mode");
setInCallScreenMode(InCallScreenMode.OTA_ENDED);
}
// TODO(OTASP): we might also need to go into OTA_ENDED mode
// in one extra case:
//
// else if (mApp.cdmaOtaScreenState.otaScreenState ==
// CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG) {
// if (DBG) log("checkOtaspStateOnResume - set OTA END Mode");
// setInCallScreenMode(InCallScreenMode.OTA_ENDED);
// }
} else {
// OTASP is not active; reset to regular in-call UI.
if (DBG) log("checkOtaspStateOnResume - Set OTA NORMAL Mode");
setInCallScreenMode(InCallScreenMode.OTA_NORMAL);
if (mApp.otaUtils != null) {
mApp.otaUtils.cleanOtaScreen(false);
}
}
// TODO(OTASP):
// The original check from checkIsOtaCall() when handling ACTION_MAIN was this:
//
// [ . . . ]
// else if (action.equals(intent.ACTION_MAIN)) {
// if (DBG) log("checkIsOtaCall action ACTION_MAIN");
// boolean isRingingCall = mCM.hasActiveRingingCall();
// if (isRingingCall) {
// if (DBG) log("checkIsOtaCall isRingingCall: " + isRingingCall);
// return false;
// } else if ((mApp.cdmaOtaInCallScreenUiState.state
// == CdmaOtaInCallScreenUiState.State.NORMAL)
// || (mApp.cdmaOtaInCallScreenUiState.state
// == CdmaOtaInCallScreenUiState.State.ENDED)) {
// if (DBG) log("action ACTION_MAIN, OTA call already in progress");
// isOtaCall = true;
// } else {
// if (mApp.cdmaOtaScreenState.otaScreenState !=
// CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED) {
// if (DBG) log("checkIsOtaCall action ACTION_MAIN, "
// + "OTA call in progress with UNDEFINED");
// isOtaCall = true;
// }
// }
// }
//
// Also, in internalResolveIntent() we used to do this:
//
// if ((mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_NORMAL)
// || (mApp.inCallUiState.inCallScreenMode == InCallScreenMode.OTA_ENDED)) {
// // If in OTA Call, update the OTA UI
// updateScreen();
// return;
// }
//
// We still need more cleanup to simplify the mApp.cdma*State objects.
return otaspUiActive;
}
/**
* Updates and returns the InCallControlState instance.
*/
public InCallControlState getUpdatedInCallControlState() {
if (VDBG) log("getUpdatedInCallControlState()...");
mInCallControlState.update();
return mInCallControlState;
}
public void resetInCallScreenMode() {
if (DBG) log("resetInCallScreenMode: setting mode to UNDEFINED...");
setInCallScreenMode(InCallScreenMode.UNDEFINED);
}
/**
* Updates the onscreen hint displayed while the user is dragging one
* of the handles of the RotarySelector widget used for incoming
* calls.
*
* @param hintTextResId resource ID of the hint text to display,
* or 0 if no hint should be visible.
* @param hintColorResId resource ID for the color of the hint text
*/
/* package */ void updateIncomingCallWidgetHint(int hintTextResId, int hintColorResId) {
if (VDBG) log("updateIncomingCallWidgetHint(" + hintTextResId + ")...");
if (mCallCard != null) {
mCallCard.setIncomingCallWidgetHint(hintTextResId, hintColorResId);
mCallCard.updateState(mCM);
// TODO: if hintTextResId == 0, consider NOT clearing the onscreen
// hint right away, but instead post a delayed handler message to
// keep it onscreen for an extra second or two. (This might make
// the hint more helpful if the user quickly taps one of the
// handles without dragging at all...)
// (Or, maybe this should happen completely within the RotarySelector
// widget, since the widget itself probably wants to keep the colored
// arrow visible for some extra time also...)
}
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
super.dispatchPopulateAccessibilityEvent(event);
mCallCard.dispatchPopulateAccessibilityEvent(event);
return true;
}
/**
* Manually handle configuration changes.
*
* We specify android:configChanges="orientation|keyboardHidden|uiMode" in
* our manifest to make sure the system doesn't destroy and re-create us
* due to the above config changes. Instead, this method will be called,
* and should manually rebuild the onscreen UI to keep it in sync with the
* current configuration.
*
*/
public void onConfigurationChanged(Configuration newConfig) {
if (DBG) log("onConfigurationChanged: newConfig = " + newConfig);
// Note: At the time this function is called, our Resources object
// will have already been updated to return resource values matching
// the new configuration.
// Watch out: we *can* still get destroyed and recreated if a
// configuration change occurs that is *not* listed in the
// android:configChanges attribute. TODO: Any others we need to list?
super.onConfigurationChanged(newConfig);
// Nothing else to do here, since (currently) the InCallScreen looks
// exactly the same regardless of configuration.
// (Specifically, we'll never be in landscape mode because we set
// android:screenOrientation="portrait" in our manifest, and we don't
// change our UI at all based on newConfig.keyboardHidden or
// newConfig.uiMode.)
// TODO: we do eventually want to handle at least some config changes, such as:
boolean isKeyboardOpen = (newConfig.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO);
if (DBG) log(" - isKeyboardOpen = " + isKeyboardOpen);
boolean isLandscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
if (DBG) log(" - isLandscape = " + isLandscape);
if (DBG) log(" - uiMode = " + newConfig.uiMode);
// See bug 2089513.
}
/**
* Handles an incoming RING event from the telephony layer.
*/
private void onIncomingRing() {
if (DBG) log("onIncomingRing()...");
// IFF we're visible, forward this event to the InCallTouchUi
// instance (which uses this event to drive the animation of the
// incoming-call UI.)
if (mIsForegroundActivity && (mInCallTouchUi != null)) {
mInCallTouchUi.onIncomingRing();
}
}
/**
* Handles a "new ringing connection" event from the telephony layer.
*/
private void onNewRingingConnection() {
if (DBG) log("onNewRingingConnection()...");
// This event comes in right at the start of the incoming-call
// sequence, exactly once per incoming call. We use this event to
// reset any incoming-call-related UI elements that might have
// been left in an inconsistent state after a prior incoming call.
// (Note we do this whether or not we're the foreground activity,
// since this event comes in *before* we actually get launched to
// display the incoming-call UI.)
// If there's a "Respond via SMS" popup still around since the
// last time we were the foreground activity, make sure it's not
// still active(!) since that would interfere with *this* incoming
// call.
// (Note that we also do this same check in onResume(). But we
// need it here too, to make sure the popup gets reset in the case
// where a call-waiting call comes in while the InCallScreen is
// already in the foreground.)
if (mRespondViaSmsManager != null) {
mRespondViaSmsManager.dismissPopup(); // safe even if already dismissed
}
}
private void log(String msg) {
Log.d(LOG_TAG, msg);
}
}
| [
"justin.a.rogers@gmail.com"
] | justin.a.rogers@gmail.com |
71e5146ebe1113bf83271f5f4568f5252a63c3a9 | f52ec556847bde11784873064c704d1bee8cfdd5 | /src/com/lovo/spring/ioc/dao/impl/GoodsDaoImpl.java | b18c394ae399021b3d5cb4b3d449b9515f68159b | [] | no_license | houmingsong/springIOCJ163 | 3911b216731f2d56e9377c5476f263dfde452e7c | ba75a6c89edaa2f5253dbd6927d9b346e9bdc9d5 | refs/heads/master | 2020-06-16T08:02:52.227270 | 2019-07-06T08:54:19 | 2019-07-06T08:54:19 | 195,518,621 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 942 | java | package com.lovo.spring.ioc.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.lovo.spring.ioc.dao.IGoodsDao;
import com.lovo.spring.ioc.util.GetUUID;
@Repository(value="goodsDao")
public class GoodsDaoImpl implements IGoodsDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void updateGoods(String goodsName, int goodsNum) {
String sql="update goods set goodsNum=(goodsNum-?) where goodsName=? ";
int i=1/0;
jdbcTemplate.update(sql, goodsNum,goodsName);
}
@Override
public void savaOrder(String goodsName, int goodsNum) {
String sql ="insert into g_order(orderId,orderNum,goodsName,goodsNum)values(?,?,?,?)";
jdbcTemplate.update(sql,
new Object[]{GetUUID.createUUID(),"g"+System.currentTimeMillis(),goodsName,goodsNum});
}
}
| [
"castle@192.168.1.111"
] | castle@192.168.1.111 |
c06135125cf8aeb20d4cd821c38ca5eb17df7d6f | ef98b4d5ec35f161bb6c3e9ebd3f20bbb401c370 | /app/src/main/java/br/com/caelum/cadastro/fragment/MapaFragment.java | 356733b7105e272991687976e755d33ba65f9676 | [] | no_license | BrunaTavares/AndroidAppCadastro | 276b4a4cc99409331ad168316443aca49ee24e10 | 6eec7c6b405019355138d68ed6311d60cba18967 | refs/heads/master | 2021-01-11T10:06:33.131555 | 2016-01-18T02:47:53 | 2016-01-18T02:47:53 | 49,679,911 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,270 | java | package br.com.caelum.cadastro.fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.Toast;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
import br.com.caelum.cadastro.R;
import br.com.caelum.cadastro.dao.AlunoDAO;
import br.com.caelum.cadastro.modelo.Aluno;
import br.com.caelum.cadastro.util.AtualizadorDeLocalização;
import br.com.caelum.cadastro.util.Localizador;
/**
* Created by Bruna on 15/01/16.
*/
public class MapaFragment extends SupportMapFragment {
@Override
public void onResume() {
super.onResume();
Localizador localizador = new Localizador(getActivity());
//LatLng local = localizador.getCordenada("Rua Vergueiro 3185 Vila Mariana");
//Log.i("MAPA","Coordenadas da Caelum: " + local);
//this.centralizaNo(local);
GoogleMap mapa = getMap();
//mapa.addMarker(new MarkerOptions().title("Caellum").snippet("Ensino e Inovação").position(local));
AlunoDAO dao = new AlunoDAO(getActivity());
List<Aluno> alunos = dao.getLista();
dao.close();
//busca alunos no banco
for(Aluno aluno: alunos){
LatLng localAluno = localizador.getCordenada(aluno.getEndereco());
if (localAluno!=null ) {
if(aluno.getCaminhoFoto()!= null ) {
Bitmap bm = BitmapFactory.decodeFile(aluno.getCaminhoFoto());
Bitmap bmReduzido = Bitmap.createScaledBitmap(bm, 100, 100, true);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bmReduzido);
mapa.addMarker(new MarkerOptions().title(aluno.getNome()).snippet(aluno.getEndereco()).position(localAluno).icon(bitmapDescriptor));
}else {
//Bitmap bm = BitmapFactory.decodeResource(R.drawable.ic_no_image);
//Bitmap bmReduzido = Bitmap.createScaledBitmap(bm, 100, 100, true);
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.ic_no_image);
mapa.addMarker(new MarkerOptions().title(aluno.getNome()).snippet(aluno.getEndereco()).position(localAluno).icon(bitmapDescriptor));
}
}else{
Toast.makeText(getActivity(),"Endereço:" + aluno.getEndereco() +" não localizado!",Toast.LENGTH_LONG).show();
}
}
AtualizadorDeLocalização atualizador = new AtualizadorDeLocalização(getActivity(),this);
}
public void centralizaNo(LatLng local){
CameraUpdate camera = CameraUpdateFactory.newLatLngZoom(local,20);
GoogleMap mapa = getMap();
mapa.moveCamera(camera);
mapa.addMarker(new MarkerOptions().title("Local Agora").position(local).draggable(true));
}
}
| [
"bruna_satavares@hotmail.com"
] | bruna_satavares@hotmail.com |
0e0cdbe95f40efec75b3873974a70129d5dd8fd9 | e0119155edf65e6207448f5ab760230566fc5714 | /java/GCN_MulticastClient.java | 2aac7d67044dda388e320d802dde118c578a8e65 | [] | no_license | LivTel/minor-access-systems | c2af823dd295840f8cba7aa51355bd34f9b9bac2 | ae269b6c49d8f376c6f9227821f0fce64d482106 | refs/heads/master | 2023-06-26T00:33:26.787526 | 2023-06-13T14:43:19 | 2023-06-13T14:43:19 | 23,577,417 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,772 | java | import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import ngat.util.*;
public class GCN_MulticastClient extends Thread {
public static final String DEFAULT_MCAST_ADDRESS = "224.103.114.98";
/** Input buffer - easily big enough at 256.*/
public final static int BUFFER_SIZE = 256;
public static final int SUSP_GRB = 0x00000001; /* Suspected GRB */
public static final int DEF_GRB = 0x00000002; /* Definitely a GRB */
public static final int NEAR_SUN = 0x00000004; /* Coords is near the Sun (<15deg) */
public static final int SOFT_SF = 0x00000008; /* Spectrum is soft, h_ratio > 2.0 */
public static final int SUSP_PE = 0x00000010; /* Suspected Particle Event */
public static final int DEF_PE = 0x00000020; /* Definitely a Particle Event */
public static final int X_X_X_X_XXX = 0x00000040; /* spare */
public static final int DEF_UNK = 0x00000080; /* Definitely an Unknown */
public static final int EARTHWARD = 0x00000100; /* Location towards Earth center */
public static final int SOFT_FLAG = 0x00000200; /* Small hardness ratio (>1.5) */
public static final int NEAR_SAA = 0x00000400; /* It is near/in the SAA region */
public static final int DEF_SAA = 0x00000800; /* Definitely an SAA region */
public static final int SUSP_SF = 0x00001000; /* Suspected Solar Flare */
public static final int DEF_SF = 0x00002000; /* Definitely a Solar Flare */
public static final int OP_FLAG = 0x00004000; /* Op-dets flag set */
public static final int DEF_NOT_GRB = 0x00008000; /* Definitely not a GRB event */
public static final int ISO_PE = 0x00010000; /* Datelowe Iso param is small (PE) */
public static final int ISO_GRB = 0x00020000; /* D-Iso param is large (GRB/SF) */
public static final int NEG_H_RATIO = 0x00040000; /* Negative h_ratio */
public static final int NEG_ISO_BC = 0x00080000; /* Negative iso_part[1] or iso_part[2]*/
public static final int NOT_SOFT = 0x00100000; /* Not soft flag, GRB or PE */
public static final int HI_ISO_RATIO = 0x00200000; /* Hi C3/C2 D-Iso ratio */
public static final int LOW_INTEN = 0x00400000; /* Inten too small to be a real GRB */
public static final int HETE_POSS_GRB = 0x00000010;
public static final int HETE_DEF_GRB = 0x00000020;
public static final int HETE_DEF_NOT_GRB = 0x00000040;
public static final int HETE_POSS_SGR = 0x00000100;
public static final int HETE_DEF_SGR = 0x00000200;
public static final int HETE_POSS_XRB = 0x00000400;
public static final int HETE_DEF_XRB = 0x00000800;
public static final int HETE_PROB_XRB = 0x10000000;
public static final int HETE_PROB_SGR = 0x20000000;
public static final int HETE_PROB_GRB = 0x40000000;
InetAddress host;
int port;
int seq;
int count;
long delay;
MulticastSocket socket = null;
DataOutputStream out = null;
ByteArrayOutputStream bout = null;
byte[] buffer = null;
public static void main(String args[]) {
if (args.length == 0) {
usage();
return;
}
CommandParser parser = new CommandParser("@");
try {
parser.parse(args);
} catch (ParseException px) {
System.err.println("Error parsing command arguments: "+px);
usage();
return;
}
double ra = 0.0;
double dec = 0.0;
double error = 0.0;
int trigflags = 0x00000000;
Date date = new Date();
String dstr = "";
String tstr = "";
int trignum = 0;
int mesgnum = 0;
ConfigurationProperties map = parser.getMap();
try {
ra = map.getDoubleValue("ra", 0.0);
dec = map.getDoubleValue("dec", 0.0);
error = map.getDoubleValue("error", 0.0);
tstr = map.getProperty("type", "DEF_UNK");
trignum = map.getIntValue("trigno", -1);
mesgnum = map.getIntValue("mesgno", -1);
} catch (Exception e) {}
// Parse the type.
if (tstr.indexOf("not a grb") != -1)
trigflags += HETE_DEF_NOT_GRB;
if (tstr.indexOf("definite grb") != -1)
trigflags += HETE_DEF_GRB;
if (tstr.indexOf("possible grb") != -1)
trigflags += HETE_POSS_GRB;
if (tstr.indexOf("probable grb") != -1)
trigflags += HETE_PROB_GRB;
if (tstr.indexOf("definite sgr") != -1)
trigflags += HETE_DEF_SGR;
if (tstr.indexOf("possible sgr") != -1)
trigflags += HETE_POSS_SGR;
if (tstr.indexOf("probable sgr") != -1)
trigflags += HETE_PROB_SGR;
if (tstr.indexOf("definite xrb") != -1)
trigflags += HETE_DEF_XRB;
if (tstr.indexOf("possible xrb") != -1)
trigflags += HETE_POSS_XRB;
if (tstr.indexOf("probable xrb") != -1)
trigflags += HETE_PROB_XRB;
dstr = map.getProperty("date", "");
SimpleDateFormat sdf = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss");
try {
date = sdf.parse(dstr);
System.err.println("Successfully Parsed date to: "+sdf.format(date)+" = "+date.getTime());
} catch (ParseException px) {
System.err.println("Error parsing date: "+px+" setting to now");
date = new Date();
}
String address = map.getProperty("host", DEFAULT_MCAST_ADDRESS);
InetAddress host = null;
try {
host = InetAddress.getByName(address);
} catch (Exception e) {
System.err.println("Error setting mcast address: "+e);
return;
}
int port = 8010;
try {
port = map.getIntValue("port", 8010);
} catch (Exception e) {}
boolean run = true;
long delay = map.getLongValue("run", -1L);
if (delay < 0L) {
delay = 2000L;
run = false;
} else
run = true;
GCN_MulticastClient client = new GCN_MulticastClient(host, port, delay);
if (run)
client.start();
else {
String alert = map.getProperty("alert", "none");
String update = map.getProperty("update", "none");
if (!alert.equals("none")) {
try {
client.connect();
client.sendHeteAlert(trigflags, error, date);
} catch (IOException iox) {
System.err.println("Error opening connection to server: "+iox);
return;
}
} else if
(!update.equals("none")) {
try {
client.connect();
client.sendHeteUpdate(ra, dec, error, date, trigflags, trignum, mesgnum);
} catch (IOException iox) {
System.err.println("Error opening connection to server: "+iox);
return;
}
}
}
}
public static void usage() {
System.err.println("USAGE: java GCN_Client [options]"+
"\n where the following options are supported:-"+
"\n @run <delay> Run the client in continuous mode."+
"\n @host <host-addr> Host address for the GCN Server."+
"\n @port <port> Port to connect to at the server."+
"\n @ra <ra> RA of a burst source (decimal degrees)."+
"\n @dec <dec> Declination of a burst source (decimal degrees)."+
"\n @type <type> Burst source category - one of:-"+
"\n possible/probable/not a/definite/ then grb/sgr/xrb"+
"\n May be concatenated. "+
"\n E.g. \"not a grb:probable xrb:possible sgr\"."+
"\n @error <size> Size of the error box (arc minutes)."+
"\n @date <date> Date of the burst (EEE dd MMM yyyy HH:mm:ss)."+
"\n @alert <id> Send a HETE alert with GRB-ID = id."+
"\n @update <id> Send a HETE update with ra and dec as specified."+
"\n @trigno <num> Burst trigger number."+
"\n @mesgno <num> Message sequence number (for trigno)");
}
public GCN_MulticastClient(InetAddress host, int port, long delay) {
super("GCN_SImulation");
this.host = host;
this.port = port;
this.delay = delay;
count = 0;
seq = 0;
}
protected void connect() throws IOException {
count++;
if (socket == null) {
socket = new MulticastSocket(port);
socket.joinGroup(host);
System.err.println("Opened mcast to: "+host+" : "+port);
}
}
protected void makeBuffer() throws IOException {
bout = new ByteArrayOutputStream(BUFFER_SIZE);
out = new DataOutputStream(bout);
}
protected void send() {
buffer = bout.toByteArray();
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, host, port);
socket.send(packet);
//logger.log(1, "Multicasted packet.");
} catch (IOException iox) {
//logger.log(2, "Error multicasting packet: "+iox);
}
}
/** Write the termination char.*/
protected void writeTerm() throws IOException {
out.writeByte(0);
out.writeByte(0);
out.writeByte(0);
out.writeByte(10);
}
/** Write the header. */
protected void writeHdr(int type, int seq) throws IOException {
out.writeInt(type);
out.writeInt(seq);
out.writeInt(1); // HOP_CNT
}
/** Write the SOD for date.*/
protected void writeSod(long time) throws IOException {
Date date = new Date(time);
int sod = (date.getHours()*3600 + date.getMinutes()*60 + date.getSeconds())*100;
System.err.println("SOD: "+sod);
out.writeInt(sod);
}
/** Write stuffing bytes. */
protected void writeStuff(int from, int to) throws IOException {
for (int i = from; i <= to; i++) {
out.writeInt(0);
}
}
class HeteAlert {
double error;
int type;
Date date;
HeteAlert(int type, double error, Date date) {
this.type = type;
this.error = error;
this.date = date;
}
public void writeAlert() throws IOException {
long now = System.currentTimeMillis();
Date date = new Date(now);
makeBuffer();
writeHdr(40, seq); // 0, 1, 2
writeSod(now); // 3
out.writeInt(1); // 4 - trig_seq_num
out.writeInt(11910+date.getDate()); // 5 - burst_tjd
out.writeInt((int)(now - 150L)); // 6 - burst_sod
writeStuff(7, 8); // 7, 8 - spare
//int trig_flags = GAMMA_TRIG | WXM_TRIG | PROB_GRB;
int trig_flags = 11;
out.writeInt(type); // 9 - trig_flags
out.writeInt(350); // 10 - gamma_cnts
out.writeInt(22786); // 11 - wxm_cnts
out.writeInt(5467); // 12 - sxc_cnts
out.writeInt((int)(now - 2450L)); // 13 - gamma_time
out.writeInt((int)(now - 2435L)); // 14 - wxm_time
out.writeInt((240 << 16) | 75); // 15 - sc_point
writeStuff(16, 38); // 16,, 38 spare
writeTerm(); // 39 - TERM.
send();
}
}
/** HETE UPDATE message. (Packet Type 41). */
class HeteUpdate {
int burstRA;
int burstDec;
double error;
int trigFlags;
Date date;
int trigNum;
int mesgNum;
HeteUpdate(double ra, double dec, double error, Date date, int trigFlags, int trigNum, int mesgNum) {
burstRA = (int)(ra*10000.0);
burstDec = (int)(dec*10000.0);
this.error = error;
this.trigFlags = trigFlags;
this.trigNum = trigNum;
this.mesgNum = mesgNum;
this.date = date;
}
public void write() throws IOException {
long now = date.getTime();
makeBuffer();
writeHdr(41, seq);// 0, 1, 2
writeSod(now); // 3
int tsn = (mesgNum << 16) | trigNum;
out.writeInt(tsn); // 4
int tjd = getTjd(date);
out.writeInt(tjd); // 5 - burst_tjd
// writeInt(burstTJD); // 5
writeSod(now); // 6
out.writeInt(burstRA); // 7
out.writeInt(burstDec); // 8
out.writeInt(trigFlags); // 9
int gammaCts = 1000;
out.writeInt(gammaCts); // 10
int wxmCts = 500;
out.writeInt(wxmCts); // 11
int sxcCts = 400;
out.writeInt(sxcCts); // 12
int gammaTime = 2000;
out.writeInt(gammaTime); // 13
int wxmTime = 1900;
out.writeInt(wxmTime); // 14
int scRA = 250000; // 25degs
int scDec = 150000; // +15degs
out.writeInt((scRA << 16) & scDec); // 15
int wxRA1 = burstRA;
int wxRA2 = burstRA;
int wxRA3 = burstRA;
int wxRA4 = burstRA;
int wxDec1 = burstDec;
int wxDec2 = burstDec;
int wxDec3 = burstDec;
int wxDec4 = burstDec;
out.writeInt(wxRA1); // 16
out.writeInt(wxDec1); // 17
out.writeInt(wxRA2); // 18
out.writeInt(wxDec2); // 19
out.writeInt(wxRA3); // 20
out.writeInt(wxDec3); // 21
out.writeInt(wxRA4); // 22
out.writeInt(wxDec4); // 23
int wxErrors = (30 << 16) & 5;
out.writeInt(wxErrors); // 24
int wxDmSig = 50;
out.writeInt(wxDmSig); // 25
int sxRA1 = burstRA;
int sxRA2 = burstRA;
int sxRA3 = burstRA;
int sxRA4 = burstRA;
int sxDec1 = burstDec;
int sxDec2 = burstDec;
int sxDec3 = burstDec;
int sxDec4 = burstDec;
out.writeInt(sxRA1); // 26
out.writeInt(sxDec1); // 27
out.writeInt(sxRA2); // 28
out.writeInt(sxDec2); // 29
out.writeInt(sxRA3); // 30
out.writeInt(sxDec3); // 31
out.writeInt(sxRA4); // 32
out.writeInt(sxDec4); // 33
int sxErrors = (3 << 16) & 1;
out.writeInt(sxErrors); // 34
int sxDmSig = 30;
out.writeInt(sxDmSig); // 35
int posFlags = 1;
out.writeInt(posFlags); // 36
int valid = 1; // BURST_VALID.
out.writeInt(valid); // 37
writeStuff(38,38); // 38
writeTerm(); // 39
send();
}
}
class Imalive {
public void writeImalive() throws IOException {
long now = System.currentTimeMillis();
Date date = new Date(now);
makeBuffer();
writeHdr(3, seq);
writeSod(now);
writeStuff(4, 38);
writeTerm();
send();
}
}
class SaxWfcGrbPos {
double ra;
double dec;
double error;
int type;
Date date;
SaxWfcGrbPos(double ra, double dec, int type, double error, Date date) {
this.ra = ra;
this.dec = dec;
this.type = type;
this.error = error;
this.date = date;
}
public void writeSax() throws IOException {
long now = System.currentTimeMillis();
makeBuffer();
writeHdr(34, seq); // 0, 1, 2
writeSod(now); // 3
writeStuff(4,4); // 4 - spare
out.writeInt(11910+date.getDate()); // 5 - burst_tjd
out.writeInt((int)(date.getTime() - 150L)); // 6 - burst_sod
out.writeInt((int)(ra*10000.0)); // 7 - burst RA [ x10000].
out.writeInt((int)(dec*10000.0)); // 8 - burst Dec [x10000].
out.writeInt((int)(Math.random()*10000.0)); // 9 - burst intens mCrab.
writeStuff(10, 10); // 10 - spare
out.writeInt((int)(error*10000.0)); // 11 - burst error
out.writeInt((int)(Math.random()*10000.0)); // 12 - burst conf [% x 100].
writeStuff(13, 17); // 13,, 17 - spare.
//int trig_id = SUSP_GRB;
out.writeInt(type); // 18 - trigger flags.
out.writeInt(5); // 19 - stuff.
writeStuff(20, 38); // 20,, 38 - spare.
writeTerm(); // 39 - TERM.
send();
}
}
public void sendHeteAlert(int type, double error, Date date) throws IOException {
HeteAlert alert = new HeteAlert(type, error, date);
alert.writeAlert();
}
public void sendHeteUpdate(double ra, double dec, double error, Date date, int trigflags, int trignum, int mesgnum) throws IOException {
HeteUpdate update = new HeteUpdate(ra, dec, error, date, trigflags, trignum, mesgnum);
update.write();
}
protected int getTjd(Date date) {
Calendar thenCal = Calendar.getInstance();
thenCal.set(Calendar.YEAR, 2003);
thenCal.set(Calendar.MONTH, Calendar.JANUARY);
thenCal.set(Calendar.DAY_OF_MONTH, 1);
thenCal.set(Calendar.HOUR, 0);
thenCal.set(Calendar.MINUTE, 0);
thenCal.set(Calendar.SECOND, 0);
long then = thenCal.getTime().getTime();
Calendar nowCal = Calendar.getInstance();
nowCal.setTime(date);
long now = nowCal.getTime().getTime();
long diff = now - then;
int tjd = 12640 + (int)(diff/86400000L);
System.err.println("Returning TJD: "+tjd);
return tjd;
}
}
| [
"snf@astro.livjm.ac.uk"
] | snf@astro.livjm.ac.uk |
24914fa95f367d218e1b8b5dcf203c97cf4f7ec8 | a083e2b3f1da5e35b3a57fd4c0faaeea894d7b1b | /trisIntent/app/src/main/java/com/example/miki/trisintent/Paroliere.java | 00de39edefc7d08bb481cd6fb084d1f17032965b | [] | no_license | leobig99/android | 5dc29be7c0aed0edb72626b6aef649af77559fb8 | 69f5e4efaf7b0175d212f102e90746e2c61efe44 | refs/heads/master | 2021-01-20T07:36:35.283581 | 2017-05-23T09:23:53 | 2017-05-23T09:23:53 | 90,017,886 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,677 | java | package com.example.miki.trisintent;
import java.util.Arrays;
import java.util.Random;
public class Paroliere {
protected String parola="";
protected boolean[] viste;
protected int tentativi=10;
protected int lunghezza=0;
protected boolean vittoria=false;
protected String [] s={"prova", "mela","banana","paroliere", "ciao come va"};
public Paroliere() {
Random gen =new Random();
parola=s[gen.nextInt(s.length-1)+1];
viste=new boolean [parola.length()];
Arrays.fill(viste,false);
viste[0]=true;
viste[parola.length()-1]=true;
lunghezza=parola.length()-2;
}
public void controlla(String c){
// if(c.equals(""))return;
if(c.length()==1){
char a=c.charAt(0);
for (int i=0; i<parola.length();i++){
if(parola.charAt(i)==a&&!viste[i]){
viste[i]=true;
lunghezza--;
}else{
tentativi--;
}
}
}else{
if(c.equals(parola)){
lunghezza=0;
vittoria=true;
}else{
tentativi--;
}
}
}
public boolean finito(){
if(tentativi<=0||lunghezza==0){
return true;
}else{
return false;
}
}
@Override
public String toString() {
String s="";
for (int i=0; i<parola.length(); i++){
if(viste[i]||parola.charAt(i)==' '){
s=s+parola.charAt(i);
}else{
s=s+"-";
}
}
return s;
}
}
| [
"leobig99@gmail.com"
] | leobig99@gmail.com |
4aff7089b23147bbb511e4ac56b88892182006c9 | c468c151b0eb555aa3ae338d2a0ae4112c2a892a | /RssReader/app/src/main/java/com/egorshenova/rss/mvp/splash/SplashContract.java | 9ba7deb0edb50be9514cac4cdd67422de682270f | [] | no_license | gorshenova/RSSReader | 9b0c0c53fb99a96fcaa01937eea83f660ae77480 | 9da1abe797126e964c2db589cc45e7bcc44321a9 | refs/heads/master | 2021-01-11T19:28:56.458331 | 2017-02-28T13:57:18 | 2017-02-28T13:57:18 | 79,376,871 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | package com.egorshenova.rss.mvp.splash;
import com.egorshenova.rss.mvp.abs.IBasePresenter;
import com.egorshenova.rss.mvp.abs.IBaseView;
/**
* Created by eyablonskaya on 22-Feb-17.
*/
public interface SplashContract {
interface View extends IBaseView{
void openHomeScreen();
}
interface Presenter extends IBasePresenter<View>{
void loadSavedFeeds();
}
}
| [
"eyablonskaya@geeksforless.net"
] | eyablonskaya@geeksforless.net |
3a6da38b3799b6274b1f1cb68dbc240b39f4a4d4 | d7b9c513fcccbf7353240cafaa5519aacaf907d1 | /src/main/java/pl/piomin/services/transaction/model/Bank.java | a389efc6c77beb6ec444a784217825b8400513a2 | [] | no_license | pushparajk/Chai4SoWell | 8652855419cc288cc45cb3b6fa9c53f02a0d5afe | 19473882be688a91c988d0b83d30d6cde71e876a | refs/heads/main | 2023-02-05T01:07:17.731976 | 2020-12-21T12:03:42 | 2020-12-21T12:03:42 | 309,893,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 648 | java | package pl.piomin.services.transaction.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "bank")
public class Bank {
@Id
private String id;
private String bankCode;
private String bankName;
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getBankCode()
{
return bankCode;
}
public void setBankCode(String bankCode)
{
this.bankCode = bankCode;
}
public String getBankName()
{
return bankName;
}
public void setBankName(String bankName)
{
this.bankName = bankName;
}
}
| [
"Silambarasan.Sethuraman@finastra.com"
] | Silambarasan.Sethuraman@finastra.com |
ade657807b96999dffc136b54970256b4d3d12af | c9dfb030c4f19e56130a4f7f0a0176c8c9245582 | /app/src/main/java/com/app/devchat/data/Network/FireBaseAPI.java | 79ccc149bba53392bd6c37355573a1d05872819e | [] | no_license | DroidGeeks/DevChat | b286188fa2ef3049a8ff80331ae99d67bb0eb65c | 96523df1dbfb7f1221bd1d836cf2c693a0ccc74f | refs/heads/master | 2020-05-25T04:04:13.841296 | 2019-05-19T07:06:17 | 2019-05-19T07:06:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,069 | java | package com.app.devchat.data.Network;
import android.util.Log;
import com.app.devchat.data.DataModels.Message;
import com.app.devchat.data.DataModels.User;
import com.app.devchat.data.NewMessagesCallback;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.ListenerRegistration;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import androidx.annotation.NonNull;
/**
* Api for accessing the Firebase realtime database
*/
@Singleton
public class FireBaseAPI implements NetworkHelper, EventListener<QuerySnapshot>, OnSuccessListener<QuerySnapshot>, OnCompleteListener{
private static final String TAG = FireBaseAPI.class.getSimpleName();
private final CollectionReference chatsRef;
private final CollectionReference usersRef;
private ListenerRegistration listenerRegistration;
private static NewMessagesCallback newMessagesCallback;
private static String userName;
public FireBaseAPI() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.getApp().setAutomaticResourceManagementEnabled(true);
chatsRef = db.collection("chats");
usersRef = db.collection("users");
}
/**
* Get only new messages from Firebase database newer date than the most recent message in the local database
*/
@Override
public void listenForNewMessages(Date date, NewMessagesCallback callback) {
if(newMessagesCallback == null ){
setNewMessagesCallback(callback);
}
updateOnNewMessageListener(date);
}
/**
* Updates the {@link EventListener} for listening for new message updates from
* the Firebase realtime database
* @param date is the date that is the basis of the listener's query
*/
private void updateOnNewMessageListener(Date date) {
if(listenerRegistration == null){
listenerRegistration = chatsRef.whereGreaterThan("time", new Timestamp(date)).addSnapshotListener(this);
}else{
// Replace old event listener and replace with new one that uses date of latest message in local database.
listenerRegistration.remove();
listenerRegistration = chatsRef.whereGreaterThan("time", new Timestamp(date)).addSnapshotListener(this);
}
}
/**
* Get all messages from from the messages collection with date newer than the given date
* @param date : Date of the most recent message in the local messages SQL database
* @param callback : Callback for communicating back with the App's {@link com.app.devchat.data.DataManager}
*/
@Override
public void getNewMessagesFromBackendDatabase(Date date, NewMessagesCallback callback) {
setNewMessagesCallback(callback);
chatsRef.whereGreaterThan("time", new Timestamp(date)).get().addOnSuccessListener(this);
}
/**
* Send new messages to the messages collection
*/
@Override
public void sendMessagesToBackendDatabase(ArrayList<Message> messages) {
for(Message message : messages){
//TODO implement success listener
chatsRef.add(message).addOnCompleteListener(this);
}
}
/**
* Sends the new User to the users collection
* @param user
*/
@Override
public void addNewUserToBackEndDatabase(User user) {
usersRef.add(user);
}
@Override
public void setUserName(String userName) {
FireBaseAPI.userName = userName;
}
public void setNewMessagesCallback(NewMessagesCallback callback){
newMessagesCallback = callback;
}
/**
* {@link OnSuccessListener} listener for listening for the completion of a data request
* query to the Firebase database.
* @param queryDocumentSnapshots : Response data from the Firebase database
*/
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(!queryDocumentSnapshots.getMetadata().isFromCache()){
List<DocumentSnapshot> snapshots = queryDocumentSnapshots.getDocuments();
ArrayList<Message> newMessages = new ArrayList<>();
for (DocumentSnapshot snapshot:snapshots){
String sender = snapshot.getString("sender");
if (sender != null && !sender.equals(userName)){
String key = snapshot.getId();
String text = snapshot.getString("text");
Date date = snapshot.getDate("time");
newMessages.add(new Message(key, text, date, sender));
}
}
if(newMessages.size() > 0 ){
// save new messages to local database
newMessagesCallback.onNewMessages(newMessages);
} else {
updateOnNewMessageListener(new Date());
}
}
}
/**
* Listener for listening for realtime new messages snapshots from Firebase database.
* @param queryDocumentSnapshots Document snapshots received from Firebase
* @param e
*/
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
if (e == null){
if(queryDocumentSnapshots != null && !queryDocumentSnapshots.getMetadata().isFromCache()){
// if the query snapshot is not from cache proceed to get new messages
List<DocumentSnapshot> snapshots = queryDocumentSnapshots.getDocuments();
ArrayList<Message> newMessages = new ArrayList<>();
for (DocumentSnapshot snapshot:snapshots){
String sender = snapshot.getString("sender");
if (sender != null && !sender.equals(userName)){
String key = snapshot.getId();
String text = snapshot.getString("text");
Date date = snapshot.getDate("time");
newMessages.add(new Message(key, text, date, sender));
}
}
if(newMessages.size() > 0 ){
newMessagesCallback.onNewMessages(newMessages);
}
Log.d(TAG, "snapshot from Firebase" + queryDocumentSnapshots.getMetadata().toString());
}
}else {
Log.e(TAG, e.getMessage());
}
}
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
}
}
}
| [
"tapsmuzira@gmail.com"
] | tapsmuzira@gmail.com |
164931a652ab8557435ff59c44aebb10bcbc7dd4 | 8872775d1e18ee0779bcd8540631643c71af03a6 | /src/main/java/com/citibank/utils/Constant.java | e2c007adf2ce86c2b528e5e1507dab32c3514eb3 | [] | no_license | liwangadd/CitiBankBg | 4ccf612bab4d4e5b24772e029f98e4778570f241 | 187771afd8a8ed0955f3b5a418edd71da9593f66 | refs/heads/master | 2021-07-18T13:12:45.396159 | 2017-10-26T11:05:23 | 2017-10-26T11:05:23 | 108,400,028 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 203 | java | package com.citibank.utils;
import java.io.File;
/**
* Created by liwang on 15-7-28.
*/
public class Constant {
public static String uploadPath = File.separator + "uploads" + File.separator;
}
| [
"liwangadd@gmail.com"
] | liwangadd@gmail.com |
73f429abfbdbe3c8d58e1b48639909df3a2733e4 | d78eaf6b75a9fb1c43cf7feb23dca7e563ca5dde | /src/main/java/com/sbkj/paipai/api/response/deal/SellerLeaveWordToDealResponse.java | e5a9760761c5f9144ccfcde6d8509f86b75b9b64 | [] | no_license | DommyShen/paipai | 7098d0ceba09e05f3fd96a43a7c3d7215cbb264b | 02eb149ee05952e2d080ecbdb4d98237aed55254 | refs/heads/master | 2016-09-06T19:52:11.747868 | 2015-05-04T09:35:48 | 2015-05-04T09:35:48 | 23,986,648 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 575 | java | package com.sbkj.paipai.api.response.deal;
import com.sbkj.paipai.api.PaipaiResponse;
/**
* 卖家通过调用本接口给订单留言,买卖家均可在订单详情中查看到该留言
* @author DOmmy
* create:2014-08-08
*/
public class SellerLeaveWordToDealResponse extends PaipaiResponse{
private static final long serialVersionUID = 2587701437762699289L;
/** 订单编码 */
private String dealCode;
public String getDealCode() {
return dealCode;
}
public void setDealCode(String dealCode) {
this.dealCode = dealCode;
}
}
| [
"1192447308@qq.com"
] | 1192447308@qq.com |
c620189c6c12ed5ad0d6ef7012377252a8310762 | bad098da77c1736d33e98f95040e4d895c8090ea | /Android App/app/src/androidTest/java/com/abhinav/personal/remotecamerashutter/ApplicationTest.java | e8292c837661dd34742568dfd25f0ff2595f377b | [] | no_license | epukaza/remoteShutterTiny45 | f4bee69d61c6ba147315029c3e89658cd6d4972a | ccf7ea80f7b3c2e0f43f338c49811b71f35a0b7c | refs/heads/master | 2020-12-25T18:20:21.837293 | 2014-10-09T01:38:56 | 2014-10-09T01:38:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 371 | java | package com.abhinav.personal.remotecamerashutter;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"abhinav.geek@gmail.com"
] | abhinav.geek@gmail.com |
f7b4762ac12b8f1c03da131f70a5d9daff3072ae | 5a597b1856c5d9c60f6a3e43cb8ab1e8f64d3aab | /Lab4/src/experimentalClasses/ExperimentController.java | ddcff5763abc3caecc1c75f53dfd370eed41b7ac | [
"Apache-2.0"
] | permissive | FrenzyExists/DataStructuresLab | 3faa14ba0c22b19aa48bacd8ddd5ca336bf27278 | 18afda78d0810c3b50a9c018dfb8865b46b5371c | refs/heads/main | 2023-03-23T01:21:05.930263 | 2021-03-20T08:00:08 | 2021-03-20T08:00:08 | 335,184,484 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,803 | java | package experimentalClasses;
import dataGenerator.DataGenerator;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.AbstractMap;
import java.util.ArrayList;
/**
* This class represents an object data type that is able to carry the
* necessary experiments to estimate execution times of particular
* strategies to solve the set intersections problem as in p1_40354020_172.
*
* f(x) <= cg(x), for all c <= k
*
* @author pedroirivera-vega
*
*/
public class ExperimentController{
private int initialSize; // initial size to be tested
private int repetitionsPerSize; // experimental repetitions per size
private int incrementalSizeStep; // change of sizes (size delta)
private int finalSize; // last size to be tested
private ArrayList<StrategiesTimeCollection<Integer>> resultsPerStrategy;
// The i-th position will contain a particular strategy being tested.
// At the end, the i-th position will also contain a list of
// pairs (n, t), where t is the estimated time for size n for
// the strategy at that position.
public ExperimentController(int is, int fs, int iss, int rps) {
initialSize = is;
repetitionsPerSize = rps;
incrementalSizeStep = iss;
finalSize = fs;
resultsPerStrategy = new ArrayList<>();
//JPanel pane = new JPanel(); // this was intended for a progress bar....
//pane.setLayout(new FlowLayout());
}
public void addStrategy(StrategiesTimeCollection<Integer> strategy) {
resultsPerStrategy.add(strategy);
}
public void run() throws CloneNotSupportedException {
if (resultsPerStrategy.isEmpty())
throw new IllegalStateException("No strategy has been added.");
for (int size=initialSize; size<=finalSize; size+=incrementalSizeStep) {
// For each strategy, reset the corresponding variable that will be used
// to store the sum of times that the particular strategy exhibits for
// the current size size
for (StrategiesTimeCollection<Integer> strategy : resultsPerStrategy)
strategy.resetSum();
// Run all trials for the current size.
for (int r = 0; r<repetitionsPerSize; r++) {
// The following will be the common dataset to be used in the current
// trial by all the strategies being tested.
Integer[] data = generateData(size);
// Apply each one of the strategies being tested using the previous
// dataset (of size size) as input; and, for each, estimate the time
// that the execution takes.
for (StrategiesTimeCollection<Integer> strategy : resultsPerStrategy) {
// no need to clone the data set to be used by each strategy since
// no modification of it is done in the process...
long startTime = System.nanoTime(); // System.currentTimeMillis(); // time before
strategy.runTrial(data.clone()); // run the particular strategy...
long endTime = System.nanoTime(); // System.currentTimeMillis(); // time after
// accumulate the estimated time (add it) to sum of times that
// the current strategy has exhibited on trials for datasets
// of the current size.
strategy.incSum((int) (endTime-startTime));
}
}
for (StrategiesTimeCollection<Integer> strategy : resultsPerStrategy) {
strategy.add(new AbstractMap.SimpleEntry<Integer, Float>
(size, (strategy.getSum()/((float) repetitionsPerSize))));
}
System.out.println(size);
}
}
private Integer[] generateData(int size) {
DataGenerator dg = new DataGenerator(size);
Integer[] data = dg.generateData();
return data;
}
public void saveResults() throws FileNotFoundException {
PrintStream out = new PrintStream(new File("experimentalResults", "allResults.txt"));
out.print("Size");
for (StrategiesTimeCollection<Integer> trc : resultsPerStrategy)
out.print("\t" + trc.getStrategyName());
out.println();
int numberOfExperiments = resultsPerStrategy.get(0).size();
for (int i=0; i<numberOfExperiments; i++) {
out.print(resultsPerStrategy.get(0).get(i).getKey());
for (StrategiesTimeCollection<Integer> trc : resultsPerStrategy)
out.print("\t" + trc.get(i).getValue());
out.println();
}
out.close();
}
}
| [
"frenzyexists@gmail.com"
] | frenzyexists@gmail.com |
7b1866718af68a90e421784e0b91150d32a6ca84 | 91e009f7cfe07f2ec6d06e653201b0bc8be8f1cc | /src/main/java/com/affirm/service/FacilityService.java | 23bbef17ecb43a7b14e9972cf85cfccd77d25934 | [] | no_license | bansalp004/allocate-loans | 73c1ffcb5ad2014e2dded7729fe7038d5aa3eeb0 | aa2badc3de989c4da0cbe460cb0688f115a3a67c | refs/heads/main | 2023-05-13T04:16:32.003183 | 2021-06-07T03:19:02 | 2021-06-07T03:19:02 | 374,235,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,296 | java | package com.affirm.service;
import com.affirm.model.Covenant;
import com.affirm.model.Facility;
import com.affirm.model.Loan;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
/**
* Solves multiple purposes
* 1. Parse facilities and covenant
* 2. Create mapping b/w facility and its covenant (from CSV Data)
* 3. Find appropriate facility for a given loan
*/
public class FacilityService {
private static final SortedMap<BigDecimal, List<Facility>> FACILITIES_BY_ASC_INTEREST_RATE = new TreeMap<>();
//populate each facility from file with its covenants
public void populateFacilitiesWithCovenant(File facilityFile, File covenantFile) throws IOException {
if (facilityFile == null || !facilityFile.exists()) {
throw new NullPointerException("Facility file doesn't exists ");
}
if (covenantFile == null || !covenantFile.exists()) {
throw new NullPointerException("Covenant File file doesn't exists ");
}
Map<Long, List<Facility>> facilitiesByBankId = new HashMap<>();
Map<Long, Facility> facilities = getLongFacilityMap(facilityFile, facilitiesByBankId);
populateFacilitiesWithCovenants(covenantFile, facilities, facilitiesByBankId);
}
Facility findFacilityForLoan(Loan loan) {
for (BigDecimal interestRate : FACILITIES_BY_ASC_INTEREST_RATE.keySet()) {
List<Facility> facilities = FACILITIES_BY_ASC_INTEREST_RATE.get(interestRate);
facilities.sort((m, n) -> (n.getAmount().compareTo(m.getAmount())));
for (Facility facility : facilities) {
if (facility.getAmount().compareTo(loan.getAmount()) < 0) {
break;
}
if (! facility.getBannedStates().contains(loan.getState())
&& facility.getMaxDefaultLikelihood().compareTo(loan.getDefaultLikelihood()) >= 0){
System.out.println("found facility loanId " + loan.getId() + " facilityId " + facility.getId());
//update facility total amount before returning back
facility.setAmount(facility.getAmount().subtract(loan.getAmount()));
return facility;
}
}
}
return null;
}
private Map<Long, Facility> getLongFacilityMap(File facilityFile, Map<Long, List<Facility>> bankFacilities) throws IOException {
CSVReader reader = new CSVReaderBuilder(new FileReader(facilityFile))
.withSkipLines(1)
.build();
String[] line;
Map<Long, Facility> facilities = new HashMap<>();
while ((line = reader.readNext()) != null) {
Facility facility = new Facility(
Long.parseLong(line[2]),
Long.parseLong(line[3]),
new BigDecimal(line[1]),
new BigDecimal(line[0]));
facilities.put(facility.getId(), facility);
if (CollectionUtils.isNotEmpty(bankFacilities.get(facility.getBank_id()))) {
bankFacilities.get(facility.getBank_id()).add(facility);
} else {
List<Facility> bankFacility = new ArrayList<>();
bankFacility.add(facility);
bankFacilities.put(facility.getBank_id(), bankFacility);
}
if (CollectionUtils.isNotEmpty(FACILITIES_BY_ASC_INTEREST_RATE.get(facility.getInterest_rate()))) {
FACILITIES_BY_ASC_INTEREST_RATE.get(facility.getInterest_rate()).add(facility);
} else {
List<Facility> bankFacility = new ArrayList<>();
bankFacility.add(facility);
FACILITIES_BY_ASC_INTEREST_RATE.put(facility.getInterest_rate(), bankFacility);
}
}
reader.close();
System.out.println("total facilities parsed as " + facilities.size());
return facilities;
}
private void populateFacilitiesWithCovenants(File covenantFile, Map<Long, Facility> facilities,
Map<Long, List<Facility>> bankFacilities) throws IOException {
CSVReader reader = new CSVReaderBuilder(new FileReader(covenantFile))
.withSkipLines(1)
.build();
String[] line;
while ((line = reader.readNext()) != null) {
Covenant covenant = new Covenant(
Long.parseLong(line[0]),
StringUtils.isBlank(line[1]) ? null : new BigDecimal(line[1]),
Long.parseLong(line[2]),
line[3]);
//set facility max default likelihood
if (covenant.getMax_default_likelihood() != null) {
if (covenant.getFacility_id() > 0) {
facilities.get(covenant.getFacility_id()).setMaxDefaultLikelihood(covenant.getMax_default_likelihood());
} else {
if (covenant.getBank_id() > 0) {
for (Facility facility : bankFacilities.get(covenant.getBank_id())) {
facilities.get(facility.getId()).setMaxDefaultLikelihood(covenant.getMax_default_likelihood());
}
}
}
}
//set facility banned states
if (StringUtils.isNotBlank(covenant.getBanned_state())) {
if (covenant.getFacility_id() > 0) {
facilities.get(covenant.getFacility_id()).addBannedState(covenant.getBanned_state());
} else {
if (covenant.getBank_id() > 0) {
for (Facility facility : bankFacilities.get(covenant.getBank_id())) {
facilities.get(facility.getId()).addBannedState(covenant.getBanned_state());
}
}
}
}
}
reader.close();
System.out.println("facilities with covenants are parsed and added");
}
}
| [
"pravin.bansal@mindstronghealth.com"
] | pravin.bansal@mindstronghealth.com |
4cea21db64ca09d77c42d7fb6559311640a9da58 | 2b9744074a5c6e3d92aaac753a4a7ee48663007b | /Programmers_algorithm/src/PerformanceTest/PerformanceTest.java | 474b03798e0a27063b1a200c3ad0393ed45dd54c | [] | no_license | leeyebin/Algorithm_study | da3c3c173965192d993d35d73c3ff4b50bf8467d | 1709d333e5e41fbc1815b4f0a4778816027caa57 | refs/heads/master | 2021-03-30T21:54:15.816917 | 2018-03-16T18:04:26 | 2018-03-16T18:04:26 | 125,061,882 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 983 | java | package PerformanceTest;
import java.util.ArrayList;
import java.util.List;
public class PerformanceTest {
private static final long MEGABYTE = 1024L * 1024L;
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
public static void main(String[] args) {
// I assume you will know how to create a object Person yourself...
List<Person> list = new ArrayList<Person>();
for (int i = 0; i <= 900000; i++) {
list.add(new Person("Jim", "Knopf"));
}
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
System.out.println("Used memory is megabytes: "
+ bytesToMegabytes(memory));
}
}
| [
"leeyebin007@gmail.com"
] | leeyebin007@gmail.com |
57f7f35718ab7bd822a53890d4395559d4b97a69 | 071e5d2896f8b0910271c5309e82d039a6baa0ea | /ultimoTp/src/parserIndicadores/ParseException.java | c19e6d14051459b708489d0863dd17b0e8ed5b34 | [] | no_license | meligomez/gr13 | fe7c9e8f7f990c354830c39fe179cf2743edc917 | e4c917db11b37674cbd3ada1bebab98233baf6a1 | refs/heads/master | 2021-08-29T18:36:49.352189 | 2017-12-14T16:31:12 | 2017-12-14T16:31:12 | 103,183,413 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,175 | java | /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */
/* JavaCCOptions:KEEP_LINE_COL=null */
package parserIndicadores;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
}
/** Constructor with message. */
public ParseException(String message) {
super(message);
}
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* It uses "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser) the correct error message
* gets displayed.
*/
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
static String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
/* JavaCC - OriginalChecksum=c236794c04ca093d5ed7c8bf8c6f4fd0 (do not edit this line) */
| [
"melisagomez.m@gmail.com"
] | melisagomez.m@gmail.com |
743f33fa045db649a951618f8aa5ad41deca29fa | cd91ae2c9aeae39f5af775cd4650019bd1d5da8c | /app/src/main/java/DataBaseSQLite/DBSQLiteOfPersonelInformations.java | 120bed2cd0f1ea1664ef342faaa97d0950fd5ec0 | [] | no_license | hems42/ESH_AJANDA | e98c9e5ce211c388561b78c3df73c149e546ff77 | a1ac1829b5da991f232540bd8fce2000f3bcd5b7 | refs/heads/main | 2023-03-30T02:26:13.978676 | 2021-03-31T19:41:13 | 2021-03-31T19:41:13 | 336,798,503 | 1 | 0 | null | null | null | null | ISO-8859-9 | Java | false | false | 32,564 | java | package DataBaseSQLite;
import Utils.CustomTime;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import Patient.Adress;
import Patient.PersonelInformations;
import Patient.Telefon;
import java.util.ArrayList;
public class DBSQLiteOfPersonelInformations extends SQLiteOpenHelper {
private static final int dataBaseVersion = 1;
private static final String dataBaseName =DataBaseExpressions.databaseNameOfPatient;
private static final String dataBasePatient_TC_NO = "TC_NO";
private static final String dataBasePatient_name = "AD";
private static final String dataBasePatient_surname = "SOYAD";
private static final String dataBasePatient_adress_description = "ADRES_ACIKLAMASI";
private static final String dataBasePatient_adress_city = "SEHIR";
private static final String dataBasePatient_adress_district = "ILCE";
private static final String dataBasePatient_adress_neighborhood = "MAHALLE";
private static final String dataBasePatient_adress_street = "SOKAK_CADDE";
private static final String dataBasePatient_adress_apartmant_name = "APARTMAN";
private static final String dataBasePatient_adress_door_number = "KAPI_NO";
private static final String dataBasePatient_tel_no_description = "TELEFON_NO_ACIKLAMASI";
private static final String dataBasePatient_tel_no1 = "TELEFON_NO_1";
private static final String dataBasePatient_tel_no2 = "TELEFON_NO_2";
private static final String dataBasePatient_created_date = "ISLEM_TARIHI";
// bu ikisini constructor la birlikte hangi tablo kullanacaksa o kullansın diye omnlara bıraktım...
private static String dataBasePatient_table_name = "PatientInformations";
public static String dataBasePatient_Create_Table = null;
String current_time=CustomTime.getTime();
public DBSQLiteOfPersonelInformations(@Nullable Context context) {
super(context, dataBaseName, null, dataBaseVersion);
// açıklama :
// burda aynı veri tabanının farklı tablolarını kullanayım diye base veri tabanı tasarladım ammma velakin bir türlü tablo ismini altı
//sınıftan aktaramadım ne yaptıysam null dönderdi table nama e sen öle yaparsa bende senin sorgu tablonu değiştiririm dsedim ve constructoruın içinde gelen
// table name i aldım sorgucümlesine çaktım ve table name ide bu şekilde güncellemiş oldum sıkıntı yok yani ::))))))))))
dataBasePatient_Create_Table = "CREATE TABLE IF NOT EXISTS "
+ dataBasePatient_table_name
+ " ( "
+ dataBasePatient_TC_NO
+ " TEXT NOT NULL, "
+ dataBasePatient_name
+ " TEXT, "
+ dataBasePatient_surname
+ " TEXT, "
+ dataBasePatient_adress_description
+ " TEXT, "
+dataBasePatient_adress_city
+ " TEXT, "
+dataBasePatient_adress_district
+ " TEXT, "
+dataBasePatient_adress_neighborhood
+ " TEXT, "
+dataBasePatient_adress_street
+ " TEXT, "
+dataBasePatient_adress_apartmant_name
+ " TEXT, "
+dataBasePatient_adress_door_number
+ " TEXT, "
+ dataBasePatient_tel_no_description
+ " TEXT, "
+ dataBasePatient_tel_no1
+ " TEXT, "
+ dataBasePatient_tel_no2
+ " TEXT, "
+ dataBasePatient_created_date
+ " TEXT );";
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(dataBasePatient_Create_Table);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + dataBasePatient_table_name);
this.onCreate(db);
}
// alt sınıflar için gerekli metodlar
public boolean addPatientInformation(PersonelInformations personelInformations) {
SQLiteDatabase db = this.getWritableDatabase();
if (db != null) {
ContentValues values = new ContentValues();
values.put(dataBasePatient_TC_NO, personelInformations.tc_no);
values.put(dataBasePatient_name, personelInformations.name);
values.put(dataBasePatient_surname, personelInformations.surname);
values.put(dataBasePatient_adress_description,personelInformations.adress_description);
values.put(dataBasePatient_adress_city, personelInformations.city);
values.put(dataBasePatient_adress_district, personelInformations.district);
values.put(dataBasePatient_adress_neighborhood, personelInformations.neighborhood);
values.put(dataBasePatient_adress_street, personelInformations.street);
values.put(dataBasePatient_adress_apartmant_name, personelInformations.apartmant_name);
values.put(dataBasePatient_adress_door_number, personelInformations.door_number);
values.put(dataBasePatient_tel_no_description, personelInformations.tel_no_description);
values.put(dataBasePatient_tel_no1, personelInformations.tel_no1);
values.put(dataBasePatient_tel_no2, personelInformations.tel_no2);
values.put(dataBasePatient_created_date, current_time); // işlem zamanınıve tarihini kendisi otoamtik atıcak
long i = db.insert(dataBasePatient_table_name, null, values);
db.close();
if (i > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public boolean addPatientAdress(Adress adress) {
SQLiteDatabase db = this.getWritableDatabase();
if (db != null) {
ContentValues values = new ContentValues();
values.put(dataBasePatient_TC_NO, adress.tc_no);
values.put(dataBasePatient_name, adress.name);
values.put(dataBasePatient_surname, adress.surname);
values.put(dataBasePatient_adress_description,adress.adress_description);
values.put(dataBasePatient_adress_city, adress.city);
values.put(dataBasePatient_adress_district, adress.district);
values.put(dataBasePatient_adress_neighborhood, adress.neighborhood);
values.put(dataBasePatient_adress_street, adress.street);
values.put(dataBasePatient_adress_apartmant_name, adress.apartmant_name);
values.put(dataBasePatient_adress_door_number, adress.door_number);
values.put(dataBasePatient_created_date, current_time); // işlem zamanınıve tarihini kendisi otoamtik atıcak
long i = db.insert(dataBasePatient_table_name, null, values);
db.close();
if (i > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public boolean addPatientTelefon(Telefon telefone) {
SQLiteDatabase db = this.getWritableDatabase();
if (db != null) {
ContentValues values = new ContentValues();
values.put(dataBasePatient_TC_NO, telefone.tc_no);
values.put(dataBasePatient_name, telefone.name);
values.put(dataBasePatient_surname, telefone.surname);
values.put(dataBasePatient_tel_no_description, telefone.tel_no_description);
values.put(dataBasePatient_tel_no1, telefone.tel_no1);
values.put(dataBasePatient_tel_no2, telefone.tel_no2);
values.put(dataBasePatient_created_date, current_time); // işlem zamanınıve tarihini kendisi otoamtik atıcak
long i = db.insert(dataBasePatient_table_name, null, values);
db.close();
if (i > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public boolean deletePatientInformation(PersonelInformations personelInformations) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(dataBasePatient_table_name, dataBasePatient_TC_NO + " = ?"
+ " AND " + dataBasePatient_adress_description + " =?" , new String[]{personelInformations.tc_no,personelInformations.adress_description});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean deletePatientAdress(Adress adress) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(dataBasePatient_table_name, dataBasePatient_TC_NO + " = ?"
+ " AND " + dataBasePatient_adress_description + " =?" , new String[]{adress.tc_no,adress.adress_description});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean deletePatientTelefon(Telefon telefone) {
SQLiteDatabase db = this.getWritableDatabase();
// string sorgusuyla yazılmış hali
// String query ="DELETE FROM "+ dataBasePatient_table_name + " WHERE " + dataBasePatient_TC_NO +"='"+telefone.tc_no+ "' AND "+ dataBasePatient_tel_no_description+"='"+telefone.tel_no_description+"'";
int i = db.delete(dataBasePatient_table_name, dataBasePatient_TC_NO + " = ?"
+ " AND " + dataBasePatient_tel_no_description + " =?" , new String[]{telefone.tc_no,telefone.tel_no_description});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean deleteAllPatientInformation(String tc_no) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(dataBasePatient_table_name, dataBasePatient_TC_NO + " = ?"
, new String[]{tc_no});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean deleteAllPatientAdress(String tc_no) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(dataBasePatient_table_name, dataBasePatient_TC_NO + " = ?"
, new String[]{tc_no});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean deleteAllPatientTelefon(String tc_no) {
SQLiteDatabase db = this.getWritableDatabase();
int i = db.delete(dataBasePatient_table_name, dataBasePatient_TC_NO + " = ?"
, new String[]{tc_no});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean updatePatientInformationBoth(PersonelInformations informations_old ,PersonelInformations informations_new) {
// dönen int değri güncellemeden etkilenen değr sayısıdır.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dataBasePatient_name, informations_new.name);
values.put(dataBasePatient_surname, informations_new.surname);
values.put(dataBasePatient_adress_description,informations_new.adress_description);
values.put(dataBasePatient_adress_city, informations_new.city);
values.put(dataBasePatient_adress_district, informations_new.district);
values.put(dataBasePatient_adress_neighborhood, informations_new.neighborhood);
values.put(dataBasePatient_adress_street, informations_new.street);
values.put(dataBasePatient_adress_apartmant_name, informations_new.apartmant_name);
values.put(dataBasePatient_adress_door_number, informations_new.door_number);
values.put(dataBasePatient_tel_no_description, informations_new.tel_no_description);
values.put(dataBasePatient_tel_no1, informations_new.tel_no1);
values.put(dataBasePatient_tel_no2, informations_new.tel_no2);
values.put(dataBasePatient_created_date, current_time); // işlem zamanınıve tarihini kendisi otoamtik atıcak
int i = db.update(dataBasePatient_table_name, values, dataBasePatient_TC_NO + " = ?"
+ " AND " + dataBasePatient_adress_description + " =?", new String[]{informations_old.tc_no,informations_old.adress_description});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean updatePatientAdress(Adress adress_old ,Adress adress_new) {
// dönen int değri güncellemeden etkilenen değr sayısıdır.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dataBasePatient_name, adress_new.name);
values.put(dataBasePatient_surname, adress_new.surname);
values.put(dataBasePatient_adress_description,adress_new.adress_description);
values.put(dataBasePatient_adress_city, adress_new.city);
values.put(dataBasePatient_adress_district, adress_new.district);
values.put(dataBasePatient_adress_neighborhood, adress_new.neighborhood);
values.put(dataBasePatient_adress_street, adress_new.street);
values.put(dataBasePatient_adress_apartmant_name, adress_new.apartmant_name);
values.put(dataBasePatient_adress_door_number, adress_new.door_number);
values.put(dataBasePatient_created_date,current_time); // işlem zamanınıve tarihini kendisi otoamtik atıcak
int i = db.update(dataBasePatient_table_name, values, dataBasePatient_TC_NO + " = ?"
+ " AND " + dataBasePatient_adress_description + " =?", new String[]{adress_old.tc_no,adress_old.adress_description});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public boolean updatePatientTelNumber(Telefon telefon_old ,Telefon telefon_new) {
// dönen int değri güncellemeden etkilenen değr sayısıdır.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dataBasePatient_name, telefon_new.name);
values.put(dataBasePatient_surname, telefon_new.surname);
values.put(dataBasePatient_tel_no_description, telefon_new.tel_no_description);
values.put(dataBasePatient_tel_no1, telefon_new.tel_no1);
values.put(dataBasePatient_tel_no2, telefon_new.tel_no2);
values.put(dataBasePatient_created_date,current_time); // işlem zamanınıve tarihini kendisi otoamtik atıcak
int i = db.update(dataBasePatient_table_name, values, dataBasePatient_TC_NO + " = ?"
+ " AND " + dataBasePatient_tel_no_description + " =?", new String[]{telefon_old.tc_no,telefon_old.tel_no_description});
db.close();
if (i > 0) {
return true;
} else {
return false;
}
}
public PersonelInformations getPersonelInformation(String patient_tc, String adress_description) {
SQLiteDatabase db = this.getReadableDatabase();
PersonelInformations personelInformations= new PersonelInformations();
String query = "SELECT * FROM " + dataBasePatient_table_name + " WHERE "+dataBasePatient_TC_NO+"=" + "'" +patient_tc +"' "
+ " AND " +dataBasePatient_adress_description+"=" + "'" +adress_description +"'";
;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
personelInformations.tc_no=cursor.getString(0);
personelInformations.name=cursor.getString(1);
personelInformations.surname=cursor.getString(2);
personelInformations.adress_description=cursor.getString(3);
personelInformations.city=cursor.getString(4);
personelInformations.district=cursor.getString(5);
personelInformations.neighborhood=cursor.getString(6);
personelInformations.street=cursor.getString(7);
personelInformations.apartmant_name=cursor.getString(8);
personelInformations.door_number=cursor.getInt(9);
personelInformations.tel_no_description=cursor.getString(10);
personelInformations.tel_no1=cursor.getString(11);
personelInformations.tel_no2=cursor.getString(12);
personelInformations.created_date =cursor.getString(13);
}
cursor.close();
if(personelInformations!=null)
{
return personelInformations;
}
else
{
return null;
}
}
public Adress getPatientAdress(String patient_tc, String adress_description) {
SQLiteDatabase db = this.getReadableDatabase();
Adress adress= new Adress();
String query = "SELECT * FROM " + dataBasePatient_table_name + " WHERE "+dataBasePatient_TC_NO+"=" + "'" +patient_tc +"' "
+ " AND " +dataBasePatient_adress_description+"=" + "'" +adress_description +"'";
;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
adress.tc_no=cursor.getString(0);
adress.name=cursor.getString(1);
adress.surname=cursor.getString(2);
adress.adress_description=cursor.getString(3);
adress.city=cursor.getString(4);
adress.district=cursor.getString(5);
adress.neighborhood=cursor.getString(6);
adress.street=cursor.getString(7);
adress.apartmant_name=cursor.getString(8);
adress.door_number=cursor.getString(9);
adress.created_date =cursor.getString(13);
}
cursor.close();
if(adress!=null)
{
return adress;
}
else
{
return null;
}
}
public Telefon getPatientTelefon(String patient_tc, String telefon_description) {
SQLiteDatabase db = this.getReadableDatabase();
Telefon telefon= new Telefon();
String query = "SELECT * FROM " + dataBasePatient_table_name + " WHERE "+dataBasePatient_TC_NO+"=" + "'" +patient_tc +"' "
+ " AND " +dataBasePatient_adress_description+"=" + "'" +telefon_description +"'";
;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
telefon.tc_no=cursor.getString(0);
telefon.name=cursor.getString(1);
telefon.surname=cursor.getString(2);
telefon.tel_no_description=cursor.getString(10);
telefon.tel_no1=cursor.getString(11);
telefon.tel_no2=cursor.getString(12);
telefon.created_date =cursor.getString(13);
}
cursor.close();
if(telefon!=null)
{
return telefon;
}
else
{
return null;
}
}
public ArrayList<PersonelInformations> getAllPatientInformations(String tc_no) {
SQLiteDatabase db = this.getReadableDatabase();
PersonelInformations personelInformations;
ArrayList<PersonelInformations> allPatient= new ArrayList<>();
String query = "SELECT * FROM " + dataBasePatient_table_name + " WHERE " + dataBasePatient_TC_NO + " =" + "'" +tc_no+"'";
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
{
personelInformations=new PersonelInformations();
personelInformations.tc_no=cursor.getString(0);
personelInformations.name=cursor.getString(1);
personelInformations.surname=cursor.getString(2);
personelInformations.adress_description=cursor.getString(3);
personelInformations.city=cursor.getString(4);
personelInformations.district=cursor.getString(5);
personelInformations.neighborhood=cursor.getString(6);
personelInformations.street=cursor.getString(7);
personelInformations.apartmant_name=cursor.getString(8);
personelInformations.door_number=cursor.getInt(9);
personelInformations.tel_no_description=cursor.getString(10);
personelInformations.tel_no1=cursor.getString(11);
personelInformations.tel_no2=cursor.getString(12);
personelInformations.created_date =cursor.getString(13);
allPatient.add(personelInformations);
}
}
while (cursor.moveToNext());
}
cursor.close();
if(allPatient!=null)
{
return allPatient;
}
else
{
return null;
}
}
public ArrayList<Adress> getAllPatientAdress(String tc_no) {
SQLiteDatabase db = this.getReadableDatabase();
Adress adress;
ArrayList<Adress> allAdresses= new ArrayList<>();
String query = "SELECT * FROM " + dataBasePatient_table_name + " WHERE " + dataBasePatient_TC_NO + " =" + "'" +tc_no+"'";
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
{
if(cursor.getString(3)!=null&&!cursor.getString(3).matches(""))
{
adress=new Adress();
adress.tc_no=cursor.getString(0);
adress.name=cursor.getString(1);
adress.surname=cursor.getString(2);
adress.adress_description=cursor.getString(3);
adress.city=cursor.getString(4);
adress.district=cursor.getString(5);
adress.neighborhood=cursor.getString(6);
adress.street=cursor.getString(7);
adress.apartmant_name=cursor.getString(8);
adress.door_number=cursor.getString(9);
adress.created_date =cursor.getString(13);
allAdresses.add(adress);
}
}
}
while (cursor.moveToNext());
}
cursor.close();
if(allAdresses!=null)
{
return allAdresses;
}
else
{
return null;
}
}
public ArrayList<Telefon> getAllPatientTelefons(String tc_no) {
SQLiteDatabase db = this.getReadableDatabase();
Telefon telefon;
ArrayList<Telefon> allTelefons= new ArrayList<>();
String query = "SELECT * FROM " + dataBasePatient_table_name + " WHERE " + dataBasePatient_TC_NO + " =" + "'" +tc_no+"'";
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
{
if(cursor.getString(10)!=null&&!cursor.getString(10).matches(""))
{
telefon=new Telefon();
telefon.tc_no=cursor.getString(0);
telefon.name=cursor.getString(1);
telefon.surname=cursor.getString(2);
telefon.tel_no_description=cursor.getString(10);
telefon.tel_no1=cursor.getString(11);
telefon.tel_no2=cursor.getString(12);
telefon.created_date =cursor.getString(13);
allTelefons.add(telefon);
}
}
}
while (cursor.moveToNext());
}
cursor.close();
if(allTelefons!=null)
{
return allTelefons;
}
else
{
return null;
}
}
public ArrayList<Adress> getAllPatientAdress() {
SQLiteDatabase db = this.getReadableDatabase();
Adress adress;
ArrayList<Adress> allAdresses= new ArrayList<>();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
{
adress=new Adress();
adress.tc_no=cursor.getString(0);
adress.name=cursor.getString(1);
adress.surname=cursor.getString(2);
adress.adress_description=cursor.getString(3);
adress.city=cursor.getString(4);
adress.district=cursor.getString(5);
adress.neighborhood=cursor.getString(6);
adress.street=cursor.getString(7);
adress.apartmant_name=cursor.getString(8);
adress.door_number=cursor.getString(9);
adress.created_date =cursor.getString(13);
allAdresses.add(adress);
}
}
while (cursor.moveToNext());
}
cursor.close();
if(allAdresses!=null)
{
return allAdresses;
}
else
{
return null;
}
}
public ArrayList<Telefon> getAllPatientTelefons() {
SQLiteDatabase db = this.getReadableDatabase();
Telefon telefon;
ArrayList<Telefon> allTelefons= new ArrayList<>();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
{
telefon=new Telefon();
telefon.tc_no=cursor.getString(0);
telefon.name=cursor.getString(1);
telefon.surname=cursor.getString(2);
telefon.tel_no_description=cursor.getString(10);
telefon.tel_no1=cursor.getString(11);
telefon.tel_no2=cursor.getString(12);
telefon.created_date =cursor.getString(13);
allTelefons.add(telefon);
}
}
while (cursor.moveToNext());
}
cursor.close();
if(allTelefons!=null)
{
return allTelefons;
}
else
{
return null;
}
}
public ArrayList<PersonelInformations> getAllPatientInformations() {
SQLiteDatabase db = this.getReadableDatabase();
PersonelInformations personelInformations;
ArrayList<PersonelInformations> allPatient= new ArrayList<>();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
{
personelInformations=new PersonelInformations();
personelInformations.tc_no=cursor.getString(0);
personelInformations.name=cursor.getString(1);
personelInformations.surname=cursor.getString(2);
personelInformations.adress_description=cursor.getString(3);
personelInformations.city=cursor.getString(4);
personelInformations.district=cursor.getString(5);
personelInformations.neighborhood=cursor.getString(6);
personelInformations.street=cursor.getString(7);
personelInformations.apartmant_name=cursor.getString(8);
personelInformations.door_number=cursor.getInt(9);
personelInformations.tel_no_description=cursor.getString(10);
personelInformations.tel_no1=cursor.getString(11);
personelInformations.tel_no2=cursor.getString(12);
personelInformations.created_date =cursor.getString(13);
allPatient.add(personelInformations);
}
}
while (cursor.moveToNext());
}
cursor.close();
if(allPatient!=null)
{
return allPatient;
}
else
{
return null;
}
}
public boolean isContainPatientInformation(PersonelInformations personelInformations) {
boolean sonuc=false;
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
if(personelInformations.tc_no.equals(cursor.getString(1)))
{
sonuc=true;
break;
}
}
while (cursor.moveToNext());
}
cursor.close();
return sonuc;
}
public boolean isContainPatientTelefon(Telefon telefon) {
boolean sonuc=false;
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
if(telefon.tc_no.equals(cursor.getString(1)))
{
sonuc=true;
break;
}
}
while (cursor.moveToNext());
}
cursor.close();
return sonuc;
}
public boolean isContainPatientTelefon(String tc_no,String telefon) {
boolean sonuc=false;
for(Telefon telefon_in:getAllPatientTelefons(tc_no))
{
if((telefon_in.tel_no1!=null&&telefon_in.tel_no1.matches(telefon))||(telefon_in.tel_no2!=null&&telefon_in.tel_no2.matches(telefon)))
{
sonuc=true;
}
}
/* SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
if(telefon.tc_no.equals(cursor.getString(1)))
{
sonuc=true;
break;
}
}
while (cursor.moveToNext());
}
cursor.close();*/
return sonuc;
}
public boolean isContainPatientAdress(String tc_no,String adress_description) {
boolean sonuc=false;
for(Adress adress_in:getAllPatientAdress(tc_no))
{
if(adress_in.adress_description.matches(adress_description))
{
sonuc=true;
}
}
/* SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + dataBasePatient_table_name;
Cursor cursor = db.rawQuery(query, null);
if (cursor!= null && cursor.getCount() > 0)
{
cursor.moveToFirst();
do {
if(telefon.tc_no.equals(cursor.getString(1)))
{
sonuc=true;
break;
}
}
while (cursor.moveToNext());
}
cursor.close();*/
return sonuc;
}
}
| [
"=eflatun126@gmail.com"
] | =eflatun126@gmail.com |
5088091d6c9442849a75ba91377e433d52bb81ad | 051044e5effe80f290386e9c57e262dbc52b3bf9 | /mobile/src/main/java/com/vitaliyhtc/opengl_es_investigation/opengl2/utils/OpenGLES20Utils.java | 69e1dac6a06c8bdd0304ec15d5e90df9a8febbdc | [] | no_license | VitaliyHTC/OpenGL_ES_investigation | f590d4a9cf7abd011adf96e92660771985bebdb8 | f5f28de15d35d7f301a47b081f99bad69c7f651c | refs/heads/master | 2021-07-02T06:33:08.707110 | 2017-09-21T15:22:03 | 2017-09-21T15:22:03 | 104,207,485 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,829 | java | package com.vitaliyhtc.opengl_es_investigation.opengl2.utils;
import android.opengl.GLES20;
import android.util.Log;
/**
* Created by vitaliyhtc on 22.08.17.
*/
public class OpenGLES20Utils {
private static final String TAG = "OpenGLES20Utils";
/**
* @param vertexShaderCode String with vertex shader code
* @param fragmentShaderCode String with fragment shader code
* @return ID of OpenGL Program
*/
public static int getProgram(String vertexShaderCode, String fragmentShaderCode) {
// prepare shaders and OpenGL program
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
int mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program
GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
GLES20.glLinkProgram(mProgram); // create OpenGL program executables
return mProgram;
}
/**
* Utility method for compiling a OpenGL shader.
* <p>
* <p><strong>Note:</strong> When developing shaders, use the checkGlError()
* method to debug shader coding errors.</p>
*
* @param type - Vertex or fragment shader type.
* @param shaderCode - String containing the shader code.
* @return - Returns an id for the shader.
*/
public static int loadShader(int type, String shaderCode) {
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
/**
* Utility method for debugging OpenGL calls. Provide the name of the call
* just after making it:
* <p>
* <pre>
* mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
* MyGLRenderer.checkGlError("glGetUniformLocation");</pre>
* <p>
* If the operation is not successful, the check throws an error.
*
* @param glOperation - Name of the OpenGL call to check.
*/
public static void checkGlError(String glOperation) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, glOperation + ": glError " + error);
throw new RuntimeException(glOperation + ": glError " + error);
}
}
/***************************************
* *********************************** *
***************************************/
}
| [
"vitaliyhtc@gmail.com"
] | vitaliyhtc@gmail.com |
77020be5b161a7dddd5ff70dca45019ff39e91b0 | b111b77f2729c030ce78096ea2273691b9b63749 | /db-example-large-multi-project/project20/src/test/java/org/gradle/test/performance/mediumjavamultiproject/project20/p103/Test2079.java | 45b9a9ef9e0f1fe98fd46b608f0505a242d1f506 | [] | no_license | WeilerWebServices/Gradle | a1a55bdb0dd39240787adf9241289e52f593ccc1 | 6ab6192439f891256a10d9b60f3073cab110b2be | refs/heads/master | 2023-01-19T16:48:09.415529 | 2020-11-28T13:28:40 | 2020-11-28T13:28:40 | 256,249,773 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,036 | java | package org.gradle.test.performance.mediumjavamultiproject.project20.p103;
import org.gradle.test.performance.mediumjavamultiproject.project20.p102.Production2052;
import org.gradle.test.performance.mediumjavamultiproject.project17.p87.Production1752;
import org.gradle.test.performance.mediumjavamultiproject.project17.p88.Production1765;
import org.gradle.test.performance.mediumjavamultiproject.project17.p88.Production1778;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test2079 {
Production2079 objectUnderTest = new Production2079();
@Test
public void testProperty0() throws Exception {
Production2052 value = new Production2052();
objectUnderTest.setProperty0(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() throws Exception {
Production2065 value = new Production2065();
objectUnderTest.setProperty1(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() throws Exception {
Production2078 value = new Production2078();
objectUnderTest.setProperty2(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() throws Exception {
Production1752 value = new Production1752();
objectUnderTest.setProperty3(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() throws Exception {
Production1765 value = new Production1765();
objectUnderTest.setProperty4(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() throws Exception {
Production1778 value = new Production1778();
objectUnderTest.setProperty5(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() throws Exception {
String value = "value";
objectUnderTest.setProperty6(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() throws Exception {
String value = "value";
objectUnderTest.setProperty7(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() throws Exception {
String value = "value";
objectUnderTest.setProperty8(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() throws Exception {
String value = "value";
objectUnderTest.setProperty9(value);
Thread.sleep(250);
assertEquals(value, objectUnderTest.getProperty9());
}
} | [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
6c0a575a48d483af02a5a8e7948aa01c152e4419 | 72451944f5e57ce17f60442783229f4b05d207d7 | /code/src/com/asiainfo/charge/dao/interfaces/IChargeNewMainDAO.java | 66041f5b121ca90f49e912cf08a9cbbd0e087030 | [] | no_license | amosgavin/db2app55 | ab1d29247be16bc9bbafd020e1a234f98bac1a39 | 61be5acb3143f5035f789cd0e0fd4e01238d9d7d | refs/heads/master | 2020-04-07T08:26:20.757572 | 2018-07-13T01:55:47 | 2018-07-13T01:55:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,142 | java | package com.asiainfo.charge.dao.interfaces;
import com.asiainfo.charge.ivalues.IBOChargeApplyMainValue;
import com.asiainfo.charge.ivalues.IBOChargeMainValue;
public interface IChargeNewMainDAO {
public void chargeStateToUse(String id)throws Exception, RuntimeException;
public void chargeStateToNoUse(String id)throws Exception, RuntimeException;
public IBOChargeMainValue IChargeMainshow(String id) throws Exception;
public IBOChargeMainValue[] IChargeNewMainByMessage(String id,String applyTime,String applyEndTime,String principle
,String isSubmit,String townname,String appname, int $STARTROWINDEX, int $ENDROWINDEX) throws Exception;
public int IChargeNewMainByMessageCount(String id,String applyTime,String applyEndTime,String principle
,String isSubmit,String townname,String appname) throws Exception;
public String saveChargeNewMain(IBOChargeMainValue chargeNewMainValue) throws Exception, RuntimeException;
public IBOChargeApplyMainValue[] getApplyMainsByMainId(String mainid) throws Exception, RuntimeException;
public void delChargeMain(String id) throws Exception, RuntimeException;
}
| [
"chendb@asiainfo.com"
] | chendb@asiainfo.com |
33ca7a9d3cc7ad6b30da04e6132c6643e94f76e8 | 3eaae3b201fcbb1eb13d2a9f8beba280819544ea | /src/main/java/algorithms/QuickSelect.java | 5568f69ac9367623efe12a9ab97b8d02be972214 | [] | no_license | arun786/PrepareAlgo | cfa5731e462cdcfbcaf8ff762de06a08f5916dcc | 727e66bda092a050e14312c640674352c778003f | refs/heads/master | 2021-06-30T14:47:37.358317 | 2019-06-19T08:06:53 | 2019-06-19T08:06:53 | 179,630,969 | 0 | 0 | null | 2020-10-13T12:42:02 | 2019-04-05T06:36:41 | Java | UTF-8 | Java | false | false | 1,433 | java | package algorithms;
import java.util.Random;
public class QuickSelect {
private int[] nums;
public QuickSelect(int[] nums) {
this.nums = nums;
}
public int select(int k) {
return select(0, nums.length - 1, k - 1);
}
private int select(int firstIndex, int lastIndex, int k) {
int pivot = partition(firstIndex, lastIndex);
if (pivot > k) {
return select(firstIndex, pivot - 1, k);
} else if (pivot < k) {
return select(pivot + 1, lastIndex, k);
}
return nums[k];
}
private int partition(int firstIndex, int lastIndex) {
int pivot = new Random().nextInt(lastIndex - firstIndex + 1) + firstIndex;
swap(pivot, lastIndex);
for (int i = firstIndex; i < lastIndex; i++) {
if (nums[i] < nums[lastIndex]) {
swap(i, firstIndex);
firstIndex++;
}
}
swap(firstIndex, lastIndex);
return firstIndex;
}
private void swap(int firstIndex, int lastIndex) {
int temp = nums[firstIndex];
nums[firstIndex] = nums[lastIndex];
nums[lastIndex] = temp;
}
public static void main(String[] args) {
int[] arrays = {1, 4, 2, 6, 8, -1};
QuickSelect quickSelect = new QuickSelect(arrays);
int select = quickSelect.select(1);
System.out.println(select);
}
}
| [
"adwiti1975@gmail.com"
] | adwiti1975@gmail.com |
6ad64e185f532c8048cde819a83f9b018d6f9279 | ea87e7258602e16675cec3e29dd8bb102d7f90f8 | /fest-swing/src/test/java/org/fest/swing/timing/SatisfiedCondition.java | 54e34156b8be0be883fcf9b3acf5e4cee41afa1d | [
"Apache-2.0"
] | permissive | codehaus/fest | 501714cb0e6f44aa1b567df57e4f9f6586311862 | a91c0c0585c2928e255913f1825d65fa03399bc6 | refs/heads/master | 2023-07-20T01:30:54.762720 | 2010-09-02T00:56:33 | 2010-09-02T00:56:33 | 36,525,844 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,323 | java | /*
* Created on Jul 31, 2009
*
* 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.
*
* Copyright @2009-2010 the original author or authors.
*/
package org.fest.swing.timing;
/**
* Understands a <code>{@link Condition}</code> that is satisfied after a given period of time.
*
* @author Alex Ruiz
*/
class SatisfiedCondition extends Condition {
boolean satisfied;
private final int timeToWaitTillSatisfied;
public SatisfiedCondition(int timeToWaitTillSatisfied) {
super("Satisfied condition");
this.timeToWaitTillSatisfied = timeToWaitTillSatisfied;
}
@Override public boolean test() {
try {
Thread.sleep(timeToWaitTillSatisfied);
} catch (InterruptedException e) {
e.printStackTrace();
}
satisfied = true;
return satisfied;
}
} | [
"alexruiz@0e018e5f-c563-0410-a877-f7675914c6cc"
] | alexruiz@0e018e5f-c563-0410-a877-f7675914c6cc |
8b9ef216a2708721fe0f8915c9c0e3225bd81c27 | 86e9e4f4fe0c0fced0870a5ce902b2e7357d0175 | /src/main/java/com/bin/system/controller/LoginfoController.java | 04273b27d6841f2ed085572edd6156d603359e1c | [] | no_license | zhubin1018/erp | eb25bcdb6f85ad73f7497a6f873d49a3ab8143ed | c01ec51383774ae9d709440c16f6601e2e81326f | refs/heads/master | 2022-06-28T22:30:58.655885 | 2020-03-23T08:39:17 | 2020-03-23T08:39:17 | 249,376,768 | 0 | 0 | null | 2022-02-09T22:23:40 | 2020-03-23T08:39:00 | Java | UTF-8 | Java | false | false | 1,992 | java | package com.bin.system.controller;
import com.baomidou.mybatisplus.extension.api.R;
import com.bin.system.common.ResultObj;
import com.bin.system.service.LoginfoService;
import com.bin.system.vo.LoginfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author 朱彬
* @date 2020/3/18 17:32
*/
@RestController
@RequestMapping("/loginfo")
public class LoginfoController {
@Autowired
private LoginfoService loginfoService;
/**
* 查询所有登录日志
* @return java.lang.Object
* @params [loginfoVo]
*/
@RequestMapping("/loadAllLoginfo")
public Object loadAllLoginfo(LoginfoVo loginfoVo) {
return this.loginfoService.queryAllLoginfo(loginfoVo);
}
/**
*删除
* @params [id]
* @return com.bin.system.common.ResultObj
*/
@RequestMapping("deleteLoginfo")
public ResultObj deleteLoginfo(Integer id){
try {
loginfoService.removeById(id);
return ResultObj.DELETE_SUCCESS;
}catch (Exception e){
e.printStackTrace();
return ResultObj.DELETE_ERROR;
}
}
/**
* 批量删除
*/
@RequestMapping("batchDeleteLoginfo")
public ResultObj batchDeleteLoginfo(Integer[] ids){
try {
if (ids!=null&&ids.length>0){
List<Integer> list = Arrays.asList(ids);
loginfoService.removeByIds(list);
return ResultObj.DELETE_SUCCESS;
}else {
return new ResultObj(-1,"传入ID不能为空");
}
}catch (Exception e){
e.printStackTrace();
return ResultObj.DELETE_SUCCESS;
}
}
}
| [
"2470718490@qq.com"
] | 2470718490@qq.com |
15029003498cac8abf4d8185a9231c566546ec31 | 8c1c66535e4c546812f6ce732bfaff7f517ddf72 | /familiar/src/main/java/devcom/familiar/controller/HomeController.java | 8ebf992e568b63a1732dbb37e6123c3b26f64324 | [] | no_license | TayvlPPM/Familiar | 575d63ebfec9ebf24b69bf69e8e8ddde3dc35da4 | f4e2857ac6a4c2e542572180d29e7cde76bc80b6 | refs/heads/master | 2020-09-30T01:07:15.444370 | 2019-12-13T13:32:47 | 2019-12-13T13:32:47 | 227,162,859 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 873 | java | package devcom.familiar.controller;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import devcom.familiar.model.User;
import devcom.familiar.service.TaskService;
import devcom.familiar.service.UserService;
@Controller
@RequestMapping("/home")
public class HomeController {
@Autowired
private TaskService taskService;
@Autowired
private UserService userService;
@GetMapping
public String getHomePage(Principal principal, Model model) {
User user = userService.findByUserName(principal.getName()).get();
model.addAttribute("tasks", taskService.findAllByUserId(user.getId()));
return "/home";
}
}
| [
"56160980+TayvlPPM@users.noreply.github.com"
] | 56160980+TayvlPPM@users.noreply.github.com |
8b8ec7eee2acb3da699ce51c093a4e00dc253532 | 82159a65b13fdfd538a17448f3a572a11489c564 | /app/src/main/java/com/danilov/supermanga/fragment/GenresFragment.java | 4ae20ffbf39ba59cdde1296efdd0f1a0860341ce | [
"Apache-2.0"
] | permissive | SammyVimes/manga | 130329f9cc7be733b6a2a2cb7021b9ad42a1c6f3 | 971f24e943239e9c1638d5da3c96b0cd33a96c88 | refs/heads/master | 2021-01-19T01:06:21.141338 | 2018-10-01T10:59:21 | 2018-10-01T10:59:21 | 53,887,772 | 30 | 13 | null | 2018-04-08T05:06:01 | 2016-03-14T20:02:52 | Java | UTF-8 | Java | false | false | 6,377 | java | package com.danilov.supermanga.fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.danilov.supermanga.R;
import com.danilov.supermanga.activity.MangaQueryActivity;
import com.danilov.supermanga.core.adapter.BaseAdapter;
import com.danilov.supermanga.core.application.MangaApplication;
import com.danilov.supermanga.core.model.Manga;
import com.danilov.supermanga.core.repository.RepositoryEngine;
import com.danilov.supermanga.core.repository.RepositoryException;
import com.danilov.supermanga.core.repository.RepositoryHolder;
import com.danilov.supermanga.core.util.Constants;
import com.danilov.supermanga.core.util.ServiceContainer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Semyon on 01.03.2015.
*/
public class GenresFragment extends BaseFragmentNative implements AdapterView.OnItemClickListener {
private GridView genresView;
private RepositoryEngine.Repository repository;
private RepositoryEngine engine = null;
private MangaQueryActivity queryActivity;
private Context context = null;
private List<RepositoryEngine.Genre> genres;
private boolean hasNoGenres = false;
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
view = inflater.inflate(R.layout.genres_fragment, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
if (savedInstanceState == null) {
String repositoryString = getArguments().getString(Constants.REPOSITORY_KEY);
RepositoryHolder repositoryHolder = ServiceContainer.getService(RepositoryHolder.class);
repository = repositoryHolder.valueOf(repositoryString);
engine = repository.getEngine();
} else {
//why I do not use getString with default value? Because it's API 12 :(
String repositoryString = savedInstanceState.getString(Constants.REPOSITORY_KEY);
if (repositoryString == null) {
repository = RepositoryEngine.DefaultRepository.READMANGA;
} else {
RepositoryHolder repositoryHolder = ServiceContainer.getService(RepositoryHolder.class);
repository = repositoryHolder.valueOf(repositoryString);
}
engine = repository.getEngine();
}
genresView = findViewById(R.id.genres);
queryActivity = (MangaQueryActivity) getActivity();
context = queryActivity.getApplicationContext();
genres = engine.getGenres();
if (genres.isEmpty()) {
genres = new ArrayList<>();
hasNoGenres = true;
genresView.setClickable(false);
genres.add(new RepositoryEngine.Genre(getString(R.string.sv_genre_search_not_supported)));
}
genresView.setAdapter(new GenresAdapter(context, -1, genres));
genresView.setOnItemClickListener(this);
super.onActivityCreated(savedInstanceState);
}
@Override
public void onSaveInstanceState(final Bundle outState) {
String repositoryString = repository.toString();
outState.putString(Constants.REPOSITORY_KEY, repositoryString);
super.onSaveInstanceState(outState);
}
@Override
public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, final long l) {
if (hasNoGenres) {
return;
}
RepositoryEngine.Genre genre = genres.get(i);
QueryTask task = new QueryTask();
task.execute(genre);
}
private class QueryTask extends AsyncTask<RepositoryEngine.Genre, Void, List<Manga>> {
private String error = null;
@Override
protected void onPreExecute() {
queryActivity.hideViewPager();
queryActivity.showProgressBar();
}
@Override
protected List<Manga> doInBackground(final RepositoryEngine.Genre... params) {
if (params == null || params.length < 1) {
return null;
}
try {
return engine.queryRepository(params[0]);
} catch (RepositoryException e) {
error = e.getMessage();
return null;
}
}
@Override
protected void onPostExecute(final List<Manga> foundManga) {
queryActivity.hideProgressBar();
if (foundManga == null) {
final Context context = MangaApplication.getContext();
Toast.makeText(context, context.getString(R.string.p_internet_error) + ": " + error, Toast.LENGTH_SHORT).show();
return;
}
queryActivity.showFoundMangaList(foundManga);
}
}
public class GenresAdapter extends BaseAdapter<Holder, RepositoryEngine.Genre> {
private List<RepositoryEngine.Genre> genres = null;
public GenresAdapter(final Context context, final int resource, final List<RepositoryEngine.Genre> objects) {
super(context, resource, objects);
this.genres = objects;
}
@Override
public void onBindViewHolder(final Holder holder, final int position) {
holder.getTextView().setText(genres.get(position).getName());
}
@Override
public Holder onCreateViewHolder(final ViewGroup viewGroup, final int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.genre_item, viewGroup, false);
return new Holder(v);
}
}
public class Holder extends BaseAdapter.BaseHolder {
private TextView textView;
protected Holder(final View view) {
super(view);
textView = (TextView) view;
}
public TextView getTextView() {
return textView;
}
public void setTextView(final TextView textView) {
this.textView = textView;
}
}
}
| [
"samvimes@yandex.ru"
] | samvimes@yandex.ru |
aaea5c19b23c2b963bf0ea6c444368abeacec00b | 2fc14d83e03104c5f8c1c52c68c47618884d2c76 | /src/be/intecbrussel/app/IOApp.java | 87b8cf871479185c4c5a6052eeb5a8cd5f020425 | [] | no_license | maysounaukal/File_IO | d123d0c3d300897ddd77e56f9dc5e977da810ea3 | cc7ba2adb64cbb16d1e94bb687e60cf388b5b1ac | refs/heads/master | 2020-12-01T22:36:46.142927 | 2019-12-29T19:33:17 | 2019-12-29T19:33:17 | 230,794,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,893 | java | package be.intecbrussel.app;
import java.io.File;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import be.intecbrussel.entities.ObjectFile;
import be.intecbrussel.utilities.FileTools;
public class IOApp {
public static void main(String[] args) {
try {
// 1) Creation of the sorted directory
FileTools.checkIfSortedDirExistElseCreate();
//FileTools is een klasse die er wordt aangemaakt, door aanroepen van de methode die in de klasse
//FileTools wordt bestaan
// 2) Creation of the unsorted path
Path unsortedPath = FileTools.checkIfUnsortedExistPathElseCreate();
//ook er wordt een unsorted path aangemaakt die de methode in KLasse FileTools wordt geplaatst
/**
3) Creation of a List with all the files and directories placed
under the "unsorted" directory.
*/
List<File> allPaths = FileTools.fillFileAndDir(new File(unsortedPath.toString()));
// om een lijst met alle bestanden en directories aan te maken met unsorted directory
// 4) The List "document" contains only the files under the "unsorted" directory.
List<File> documents = FileTools.keepOnlyDocuments(allPaths);
// deze list wordt gebruikt om alleen de files van unsorted pad te krijgen
/**
5) Creation of a List with all the ObjectFile's. An ObjectFile
contains all the useful properties of a particular file
*/
List<ObjectFile> listFileAttributes = FileTools.createListFileAttributes(documents);
// 6) Creation of the "extension file" directories
FileTools.createExtensionFileDirectory(listFileAttributes);
// 7) Copy of the files in the sorted directory
for (ObjectFile of : listFileAttributes) {
FileTools.checkIfFileExistElseCopy(of.getSourcePath(), of.getCompletePath());
}
// 8) Creation of the summary directory
FileTools.checkIfsummaryDirExistElseCreate();
/**
9) Before the creation of the summary file, the List listFileAttributes
is sorted by the extension of the files
*/
listFileAttributes.sort(Comparator.comparing(a -> a.getExtension()));
// 10) Creation and creation of the file summary.txt
FileTools.summaryFileCreation();
// 11) Number of files sorted
System.out.println(listFileAttributes.size() + " files have been placed in the sorted directory.");
} catch (Exception e) {
System.out.println("Whoops: " + e.getMessage());
}
}
}
| [
"someone.m_92@hotmail.com"
] | someone.m_92@hotmail.com |
534a87c2db492b75fd4f1bf72234b8745ea55157 | 18795c99cee672ff86dce75c7454a7d653fcf083 | /fpis/src/main/java/com/fon/fpis/controller/OtpremnicaZaKupcaController.java | 7d5a37812676e59578b46138a6dbff6393eb69a8 | [] | no_license | SaraBijelic/FPIS | 85b96f4ff9573e9d7c36b5862b6ac8e9647832bf | a146c687622802c9b25aaf1d802f98a62a3c6da3 | refs/heads/main | 2023-07-17T06:58:20.906591 | 2021-08-31T18:21:53 | 2021-08-31T18:21:53 | 401,796,795 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,025 | java | package com.fon.fpis.controller;
import com.fon.fpis.service.OtpremnicaZaKupcaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
@CrossOrigin(value = "*")
@RestController
@RequestMapping("api/otpremnicaZaKupca")
public class OtpremnicaZaKupcaController {
@Autowired
OtpremnicaZaKupcaService otpremnicaZaKupcaService;
@GetMapping
public ResponseEntity<?> getAllOtpremnice(){
return ResponseEntity.ok(otpremnicaZaKupcaService.findAllOtpremnica());
}
@GetMapping("/id/{id}")
public ResponseEntity<?> getOneOtpremnica(@PathVariable java.lang.Long id){
return ResponseEntity.ok(otpremnicaZaKupcaService.findOneOtpremnica(id));
}
@GetMapping("/{datum}")
public ResponseEntity<?> getAllDatumOtpremnice(@PathVariable Date datum){
return ResponseEntity.ok(otpremnicaZaKupcaService.findAllOtpremnicaDatum(datum));
}
}
| [
"89865772+SaraBijelic@users.noreply.github.com"
] | 89865772+SaraBijelic@users.noreply.github.com |
1c508b2b938c85d892f671f414e37f3e326dc16c | 2fdf845998d17a4ba0963a81800eb897c4fbd57c | /PaymentEngine.java | 00dbe07f8e2fa21b7526470a80763369c0d39ed8 | [] | no_license | shakilsustswe/interface_java_program | 47b970231d616557c9679d3a7ac7e27257260ddc | 3cc818128bdad904dcbac4f9c5cafc19c9acac07 | refs/heads/main | 2023-03-26T02:29:46.331091 | 2021-03-06T05:51:51 | 2021-03-06T05:54:10 | 345,016,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interface_;
/**
*
* @author Asus
*/
public class PaymentEngine {
public static void accept(Payment payment)
{
System.out.println("Accepting payment : "+payment.getAmount());
}
}
| [
"ashikulhasanshakil1@gmail.com"
] | ashikulhasanshakil1@gmail.com |
803c3ea508d13642bd3fd83ba79b8a55c5c1becc | cb66f547d2ebc0cff5706466ed73fd89cdd3d0fb | /parser/src/main/java/motion/blevast/parser/vast/AdParameters.java | 9ce14529b6d7155cf94c197f15b19f506b5aa182 | [] | no_license | Kalkidan/ble_vast | 5fd726c40334fe98e4a05ed7f36ab082c1aaab1c | 9feba386e731a4cd7e05f39549b345b2074cc8e3 | refs/heads/master | 2021-04-09T17:02:28.709062 | 2018-11-29T00:11:56 | 2018-11-29T00:11:56 | 125,862,014 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 422 | java | package motion.blevast.parser.vast;
import motion.blevast.parser.parser.Text;
/**
*
* Idea adopted from.
* <a herf = https://github.com/loopme/loopme-android-vpaid-sdk></a>
*
* Data to be passed into the companion ads
*/
public class AdParameters {
@Text private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| [
"get.kal.2010@gmail.com"
] | get.kal.2010@gmail.com |
12921d386d2998aabf42b2bcdbff2d6a58d0e6c7 | 642323b88f6a3f9050d3ce297b80c02715ba08db | /Java OOP Advanced/Generics/src/genericScale/Scale.java | 08122a3eb86426edecaf1989754d23b2e096717a | [] | no_license | VenelinBakalov/javaAdvanced | 5a9e418c6666f85fe8a8d1e65d587a863af367b9 | d890a84fa56af2e24669e60f48f6d776cf55e9ef | refs/heads/master | 2021-01-11T21:07:45.912758 | 2017-12-03T15:39:27 | 2017-12-03T15:39:27 | 79,252,307 | 8 | 8 | null | null | null | null | UTF-8 | Java | false | false | 469 | java | package genericScale;
/**
* Created by Venelin on 16.3.2017 г..
*/
public class Scale<T extends Comparable<T>> {
private T left;
private T right;
public Scale(T left, T right) {
this.left = left;
this.right = right;
}
public T getHeavier() {
if (left.compareTo(right) < 0) {
return right;
}
if (left.compareTo(right) > 0) {
return left;
}
return null;
}
}
| [
"vbakalov@vmware.com"
] | vbakalov@vmware.com |
aea87891b1341992a6ce2162fe1be6b7b94d5785 | 1a52892af24b1f5b9bdf8d1dfcdbee1ca1e7ea88 | /src/test/java/Specifications/ResponseSpecifications.java | 0c9e385cb7e7d8b8b3e5a8df2c6126b283a2ced0 | [] | no_license | Cerosh/RestAssuredLearnings | ff742e09d18c600cd24c297df1c4a790b80e3a3d | 98eb536ae439913265901b2c5785968a7d731b27 | refs/heads/main | 2023-05-14T05:19:14.055306 | 2021-06-06T10:31:49 | 2021-06-06T10:31:49 | 374,330,626 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,894 | java | package Specifications;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
public class ResponseSpecifications {
RequestSpecification requestSpecification;
ResponseSpecification responseSpecification;
@BeforeClass
public void setRequestSpecification() {
requestSpecification = RestAssured.
given().
baseUri("https://restful-booker.herokuapp.com/").
contentType(ContentType.JSON).
log().all();
}
@BeforeClass
public void setResponseSpecification() {
responseSpecification = requestSpecification.expect();
responseSpecification.
statusCode(200).
contentType(ContentType.JSON).
time(Matchers.lessThan(5000L));
}
@Test
public void requestUpdatingTheBooking_usingResponsetSpecifications() {
RestAssured.
given().
spec(requestSpecification).
basePath("booking").
body("{\n" + " \"firstname\" : \"Jim\",\n" + " \"lastname\" : \"Brown\",\n"
+ " \"totalprice\" : 111,\n" + " \"depositpaid\" : true,\n" + " \"bookingdates\" : {\n"
+ " \"checkin\" : \"2018-01-01\",\n" + " \"checkout\" : \"2019-01-01\"\n"
+ " },\n" + " \"additionalneeds\" : \"Breakfast\"\n" + "}").
when().
post().
then().
spec(responseSpecification);
}
@Test
public void requestPatchingTheBooking_usingResponseSpecifications() {
RestAssured.given().
spec(requestSpecification).
basePath("booking/{id}").
pathParam("id",4).body("{\n" + " \"firstname\" : \"Cerosh\",\n" + " \"lastname\" : \"Jacob\"\n" + "}").
header("Authorization", "Basic YWRtaW46cGFzc3dvcmQxMjM=").
when().
patch().
then().
log().
all().
spec(responseSpecification);
}
}
| [
"ceroshjacob@gmail.com"
] | ceroshjacob@gmail.com |
27885a62e46f5f711aaf8bc2ef5e3a0caf35c2a6 | 787e68d80f1febfc3c37e9e562b98a8b66e98f01 | /app/src/androidTest/java/mukul/com/gamearena/ExampleInstrumentedTest.java | 7125c85cb2ca160a60bfcd81ae694c37b8326820 | [] | no_license | mukultater/GameArena2 | 812198a09ceaa5a4c2fe5d00f4b5aee95d239bc9 | 78898815026aad515d3ded3c0188f767ad8970cd | refs/heads/master | 2021-05-01T10:54:29.065947 | 2018-02-11T09:56:47 | 2018-02-11T09:56:47 | 121,109,872 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 739 | java | package mukul.com.gamearena;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("mukul.com.gamearena", appContext.getPackageName());
}
}
| [
"marblesajanta@gmail.com"
] | marblesajanta@gmail.com |
eb92d50873f8a0270537882778806c3352949c01 | 4b25ec56d085590ceb8ce8b722979f70cf70250b | /P3.java | 79c91cf2f5866fe8b161626bfcf8e4e6dab86ae3 | [] | no_license | CoajaAndreea/Tema5mai | d3635e0a08b8f51a602ee1ca7a494eddc02e2622 | 2878b9dbf4d7ee615a5c1dd185558aed5906cd57 | refs/heads/master | 2020-03-16T11:37:05.829310 | 2018-05-09T13:27:47 | 2018-05-09T13:27:47 | 132,651,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 805 | java | public class P3 {
public static void main(String[] args) {
//initializari
int[] numereArray=new int[1000];
double mediaAritmetica;
int i=0;
double suma=numereArray[0];
//citirea primului numar
numereArray[0]=SkeletonJava.readIntConsole(" Introduceti primul numar ");
//citirea numerelor pana la intalnirea numarului 0
while (numereArray[i]!=0)
{
i++;
numereArray[i]=SkeletonJava.readIntConsole("Introduceti numere ");
}
for (int j=0;j<i;j++)
{
suma=suma+numereArray[j];
}
//calcularea mediei cu formula
mediaAritmetica=suma/(double)i;
//afisare
System.out.println("Media aritmetica este "+mediaAritmetica);
}
}
| [
"a.coaja@yahoo.ro"
] | a.coaja@yahoo.ro |
ed30208e017654b96d0fb665f4961243df035556 | a909be3ecfa318a32fdc91cbf781caf776ca05b5 | /java/Tema 6/Practica 3/T6P3Ej22/src/t6p3ej22/Clases/Artista.java | 41eb3a927f6af1fea7c8866763014b7bfda0f067 | [] | no_license | mariozaton01/Programacion | 01afaa114cf9d6391afc21552366130757e1dfe4 | 84e2f950ab68c2efbb3e4158bf96cf57bcbe39ae | refs/heads/master | 2020-08-27T23:15:28.111008 | 2020-05-25T20:32:26 | 2020-05-25T20:32:26 | 217,516,458 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,275 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package t6p3ej22.Clases;
import java.time.LocalDate;
import java.util.ArrayList;
/**
*
* @author mario
*/
public class Artista {
private String Nombre;
private LocalDate FechaNac;
private ArrayList <Obra> listaObras_Artista;
public Artista() {
}
public Artista(String Nombre, LocalDate FechaNac, ArrayList listaObras_Artista) {
this.Nombre = Nombre;
this.FechaNac = FechaNac;
this.listaObras_Artista= listaObras_Artista;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String Nombre) {
this.Nombre = Nombre;
}
public LocalDate getFechaNac() {
return FechaNac;
}
public void setFechaNac(LocalDate FechaNac) {
this.FechaNac = FechaNac;
}
public ArrayList<Obra> getListaObras_Artista() {
return listaObras_Artista;
}
public void setListaObras_Artista(ArrayList<Obra> listaObras_Artista) {
this.listaObras_Artista = listaObras_Artista;
}
}
| [
"mario.zaton@ikasle.egibide.org"
] | mario.zaton@ikasle.egibide.org |
f44971eab38614c38e2d3dec0acaf3536d203c87 | 7ae8f0fbc41eef920c248a29676bacb91daef8bd | /src/main/java/com/udemy/ecomdashboard/repositories/CompanyRevenueRepository.java | 663015a79226d22a54148bb4bee1b5d2b08db690 | [] | no_license | ninanguyen24/EcomDashboardUdemy | 27a47efa3fb0b0333fa25c3333d8995da9f341e8 | 637424d944599df7c2404513cbfd9aee0ce970f1 | refs/heads/main | 2023-03-30T06:52:21.315135 | 2021-04-03T19:49:04 | 2021-04-03T19:49:04 | 352,262,128 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 473 | java | package com.udemy.ecomdashboard.repositories;
import com.udemy.ecomdashboard.entity.CompanyRevenue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
//Jpa repository mapped with entity object
@Repository
@Qualifier(value = "companyRevenueRepository")
public interface CompanyRevenueRepository extends JpaRepository<CompanyRevenue, Long> {
}
| [
"nguyenn4@seattleu.edu"
] | nguyenn4@seattleu.edu |
80ab94fcdb5534813fa01cd90028996fd027eae1 | 29258fb65627f49c72fb94cbbd593a356379f1b8 | /src/main/java/com/jspxcms/core/service/impl/VoteMarkServiceImpl.java | 4fc4f135ae2f364d02115fba5de2b72964337a8a | [] | no_license | deep-coding/zhijia | cd117cf6430b14a00bbcd17c00ac94aaa3c8a176 | c1ea40e0b58bba4f2791bc7ad6f71afac6639827 | refs/heads/master | 2020-12-02T09:59:10.515713 | 2017-10-21T06:50:45 | 2017-10-21T06:50:45 | 96,669,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,180 | java | package com.jspxcms.core.service.impl;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.jspxcms.common.orm.Limitable;
import com.jspxcms.core.domain.Info;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jspxcms.core.domain.User;
import com.jspxcms.core.domain.VoteMark;
import com.jspxcms.core.repository.VoteMarkDao;
import com.jspxcms.core.service.UserService;
import com.jspxcms.core.service.VoteMarkService;
@Service
@Transactional(readOnly = true)
public class VoteMarkServiceImpl implements VoteMarkService {
private final static String CLASS_NAME_INFODIGG = "com.jspxcms.core.domain.InfoDigg";
private final static String CLASS_NAME_INFOFAV = "com.jspxcms.core.domain.InfoFav";
public boolean isUserVoted(String ftype, Integer fid, Integer userId,
Integer beforeHour) {
return isVoted(ftype, fid, userId, null, null, beforeHour);
}
public boolean isIpVoted(String ftype, Integer fid, String ip,
Integer beforeHour) {
return isVoted(ftype, fid, null, ip, null, beforeHour);
}
public boolean isCookieVoted(String ftype, Integer fid, String cookie,
Integer beforeHour) {
return isVoted(ftype, fid, null, null, cookie, beforeHour);
}
public boolean isVoted(String ftype, Integer fid, Integer userId,
String ip, String cookie, Integer beforeHour) {
Date after = null;
if (beforeHour != null) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -beforeHour);
after = cal.getTime();
}
return dao.countMark(ftype, fid, userId, ip, cookie, after) > 0;
}
public VoteMark get(Integer id) {
return dao.findOne(id);
}
@Transactional
public VoteMark mark(String ftype, Integer fid, Integer userId, String ip,
String cookie) {
try {
String className = "";
if (Info.FAV_MARK.equals(ftype)) {
className = CLASS_NAME_INFOFAV;
} else if (Info.DIGG_MARK.equals(ftype)) {
className = CLASS_NAME_INFODIGG;
}
VoteMark bean = (VoteMark) Class.forName(className).newInstance();
if (userId != null) {
User user = userService.get(userId);
bean.setUser(user);
}
bean.setFtype(ftype);
bean.setFid(fid);
bean.setIp(ip);
bean.setCookie(cookie);
return save(bean);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Transactional
public List<VoteMark> findList(String ftype, Integer fid, Integer userId, Limitable limitable) {
return dao.findList(ftype, fid, userId, limitable);
}
@Transactional
public Page<VoteMark> findPage(String ftype, Integer fid, Integer userId, Pageable pageable) {
return dao.findPage(ftype, fid, userId, pageable);
}
@Transactional
public int unmark(String ftype, Integer fid) {
return dao.unmark(ftype, fid);
}
@Transactional
public int unmark(String ftype, Integer fid, Integer userId) {
return dao.unmark(ftype, fid, userId);
}
@Transactional
public int unmark(String ftype, Integer fid, String cookie) {
return dao.unmark(ftype, fid, cookie);
}
@Transactional
public VoteMark save(VoteMark bean) {
bean.applyDefaultValue();
bean = dao.save(bean);
return bean;
}
@Transactional
public VoteMark update(VoteMark bean) {
bean.applyDefaultValue();
bean = dao.save(bean);
return bean;
}
@Transactional
public VoteMark delete(Integer id) {
VoteMark entity = dao.findOne(id);
dao.delete(entity);
return entity;
}
@Transactional
public VoteMark[] delete(Integer[] ids) {
VoteMark[] beans = new VoteMark[ids.length];
for (int i = 0; i < ids.length; i++) {
beans[i] = delete(ids[i]);
}
return beans;
}
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
private VoteMarkDao dao;
@Autowired
public void setDao(VoteMarkDao dao) {
this.dao = dao;
}
}
| [
"lidengqi@sheyuan.com"
] | lidengqi@sheyuan.com |
34769d7821f750cec8b53f378a0ad9d5b9f3983a | bdcfd9395419c01d2a6f97202668c17c16709a26 | /src/entities/Account2.java | b2f603a416de0f0c64e56a3713a52b72bfa9e5fb | [] | no_license | mucheniski/java-completo-2019 | 5735abb620752cd9443da7c6970bef9d4397eaa4 | 1c00e9341734f874de32d5124f13ab90252c221c | refs/heads/master | 2020-07-08T12:54:01.567453 | 2019-09-08T19:37:38 | 2019-09-08T19:37:38 | 203,678,197 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 672 | java | package entities;
public class Account2 {
private Integer number;
private String holder;
private Double balance;
public Account2() {
}
public Account2(Integer number, String holder) {
this.number = number;
this.holder = holder;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public String getHolder() {
return holder;
}
public void setHolder(String holder) {
this.holder = holder;
}
public Double getBalance() {
return balance;
}
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
} | [
"mucheniski@gmail.com"
] | mucheniski@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.