text stringlengths 10 2.72M |
|---|
package net.birelian.poc.di.guice.dao;
import net.birelian.poc.di.guice.model.Contact;
import java.util.*;
/**
* ContactDao implementation
*/
public class ContactDaoImpl implements ContactDao {
private final Map<Integer, Contact> contacts = new HashMap<>();
private Integer lastGeneratedId = 0;
public ContactDaoImpl() {
// Create test data
createTestData();
}
@Override
public Collection<Contact> findAll() {
return contacts.values();
}
@Override
public Contact findById(Integer id) {
return contacts.get(id);
}
@Override
public void save(Contact contact) {
// Add the contact if not exists
if (!contacts.containsValue(contact)) {
contact.setId(++lastGeneratedId);
contacts.put(contact.getId(), contact);
}
}
@Override
public void delete(Contact contact) {
contacts.remove(contact.getId());
}
@Override
public void deleteAll() {
contacts.clear();
}
@Override
public List<Contact> findBySurname(String surname) {
List<Contact> contactsFound = new ArrayList<>();
for (Contact contact : contacts.values()) {
if(contact.getSurname().equals(surname)) {
contactsFound.add(contact);
}
}
return contactsFound;
}
private void createTestData() {
Contact solidSnakeContact = new Contact("Solid", "Snake", "solidsnake@shadowmoses.net");
solidSnakeContact.setId(1);
contacts.put(1, solidSnakeContact);
Contact otaconContact = new Contact("Hal", "Emmerich", "hal.emmerich@otaku.net");
otaconContact.setId(2);
contacts.put(2, otaconContact);
Contact liquidSnakeContact = new Contact("Liquid", "Snake", "solidsnake@shadowmoses.net");
liquidSnakeContact.setId(1);
contacts.put(3, liquidSnakeContact);
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//Engine.java
//Manages a LaserBeam and generally connects the Lasers Module together.
//Sara Smolensky
//Started August 24 2000
//Updated November 20 2002
//Converted to X3D June 7 2008
//Grant Patten
//Version 3.0
package org.webtop.module.laser;
import org.webtop.util.*;
import org.web3d.x3d.sai.*;
import org.webtop.x3d.SAI;
import org.webtop.x3d.output.*;
import org.webtop.x3d.widget.ScalarWidget;
import org.webtop.x3d.widget.WheelWidget;
import org.webtop.x3d.widget.XDragWidget;
import org.webtop.component.*;
import org.webtop.wsl.client.*;
import org.webtop.wsl.script.*;
import org.webtop.wsl.event.*;
import org.webtop.x3d.widget.*;
public class Engine implements ScalarWidget.Listener/*implements WSLScriptListener, WSLPlayerListener*/ {
public static final float MIN_SPACE=Laser.MIN_SPACE; //minimum space between end of laser and screen (200)
public interface Widget {
public String getTip();
}
private Laser parent;
private Mirror mirror1;
//private Mirror2 mirror2;
private LaserBeam laserbeam;
private boolean widgetsOn=true;
private SFBool[] flipMirror=new SFBool[2];
private float length=0,
z=0, // distance from beam waist to the observation point
w1=0, //spot size on mirror 1
w2=0, //on mirror 2
lambda, //light's wavelength
L1, //distance from mirror 1 to waist
L2, //from 2 to waist
L3, //from 2 to screen
screenDist, //from 1 to screen
g1, //g-parameters
g2,
w0, //spot size at beam waist
zR, //Rayleigh beam length
R1,R2, //radii of curvature of mirrors
yp1,xp1,xp2,yp2,
radius_mirror1, //radii of mirrors
radius_mirror2,
mirror1_angle,
mirror2_angle;
// TEMxx
private StatusBar statusBar;
private boolean draggingWidget;
private String modStat,statStr=""; //String description of lasing-ness or not
public Engine(Laser laser) {
//First, setup the objects that depend only on us
parent=laser;
mirror1=new Mirror(parent.getSAI());
//mirror2=new Mirror2(parent.getEAI());
mirror1.drawMirror(radius_mirror1=8,mirror1_angle=0.2f);
//mirror2.drawMirror(radius_mirror2=8,mirror2_angle=0.2f);
flipMirror[0]=(SFBool) parent.getSAI().getField("Mirror1Flip","flip");
flipMirror[1]=(SFBool) parent.getSAI().getField("Mirror2Flip","flip");
laserbeam=new LaserBeam(this,parent.getSAI());
//The calculations for both xp1 and xp2 (currently in setLength()) will
//need to be moved if the mirrors ever are allowed to change shape.
xp1=(float) (Math.cos(mirror1_angle) * radius_mirror1);
//We need the control panel reference to create the widgets
//controlPanel=parent.getControlPanel();
statusBar=parent.getStatusBar();
//The control panel will respond by setting our input values.
parent.setEngine(this);
//Now get our own EAI references
//parent.getWSLPlayer().addListener(this);
render(true);
}
public void render(boolean drawbeam) {
//This may not be where this should go, but it works [Davis]
flipMirror[0].setValue(R1<0);
flipMirror[1].setValue(R2<0);
// Mirror g-parameters
g1=1 - (length / R1);
g2=1 - (length / R2);
DebugPrinter.println("Engine::render(): g1="+g1+", g2="+g2);
//Spot sizes on mirrors
w1=(float)(Math.sqrt((lambda/1e6*length)/Math.PI)*Math.pow(g2/(g1*(1-g1*g2)),0.25));
w2=(float)(Math.sqrt((lambda/1e6*length)/Math.PI)*Math.pow(g1/(g2*(1-g1*g2)),0.25));
DebugPrinter.println("Engine::render(): w1="+w1+", w2="+w2);
boolean stable=true;
if((g1*g2 < 0) || (g1*g2 > 1)) {
newStatus("Unstable resonator");
stable=false;
} else if(g1==0 && g2==0) { //Exceptional case
L1=length / 2;
L2=length / 2;
z=screenDist - (length / 2);
L3=screenDist - length;
w0=(float) (Math.pow(length*lambda/(1e6*2*Math.PI),0.5));
} else {
L1=(length*g2*(1-g1))/(g1+g2-(2*g1*g2));
z=screenDist - L1;
L2=length - L1;
L3=z + L1 - length;
// Spot size at beam waist
w0=(float) (Math.sqrt((lambda/1e6*length)/Math.PI)*Math.pow((g1*g2*(1-g1*g2))/(Math.pow((g1+g2-2*g1*g2),2)),0.25));
}
if(w1>Mirror.MIRROR_RADIUS || w2>Mirror.MIRROR_RADIUS) {
newStatus("Beam radius exceeds mirror radius");
stable=false;
}
if(stable) {
// Rayleigh length of the beam
zR=(float) ((Math.PI*w0*w0)/(lambda/1e6));
newStatus("");
calculate(drawbeam);
parent.updateLabels();
} else {
//status set appropriately above
laserbeam.setLasing(false);
parent.clearLabels();
}
}
private void calculate(boolean drawbeam) {
laserbeam.setLasing(true);
laserbeam.calculate();
if(drawbeam) laserbeam.drawBeam();
//something about far beam would go here if needed
laserbeam.drawSpot();
laserbeam.calculateLine();
}
//Listens For Changes in the Widget
public void valueChanged(ScalarWidget src, float value) {
setDragging(src,src.isActive());
}
//Sets low resolution mode if a widget is being dragged
public void setDragging(ScalarWidget source, boolean drag) {
if(draggingWidget==drag) return;
draggingWidget=drag;
laserbeam.setLowResolution(drag);
render(!(source == parent.screenDistWidget)); //Don't recalc beam for dist drag
}
public boolean isDragging() {return draggingWidget;}
public void setMouseOver(Widget source,boolean over) {
setModuleStatus(over?source.getTip():null);
}
private void newStatus(String stat) {
statStr=stat;
updateStatii();
}
//This sets the status bar's principal text but keeps the engine's status text around
public void setModuleStatus(String stat) {
modStat=stat;
updateStatii();
}
private void updateStatii() {
if(modStat==null||"".equals(modStat)) statusBar.setText(statStr);
else if("".equals(statStr)) statusBar.setText(modStat);
else statusBar.setText(modStat+" ("+statStr+")");
}
public void printAllData() {
DebugPrinter.println("Engine::printAllData()...\n wavelength="+lambda+"\tlength="+length+
"\n R1="+R1+"\tR2="+R2+"\tscreenDist="+screenDist+"\n---------"+
"\n z="+z+"\nw0="+w0+"\tzR="+zR+
"\n L1="+L1+"\tL2="+L2+"\tL3="+L3+
"\n xp2="+xp2);
}
public float getZ() {return z;}
public float getW0() {return w0;}
public float getzR() {return zR;}
public float getL1() {return L1;}
public float getL2() {return L2;}
public float getL3() {return L3;}
public void setScreenDist(float loc) {
screenDist=loc;
z=screenDist - L1;
parent.cavityLenField.setMax(loc-MIN_SPACE);
parent.cavityLenWidget.setMax((loc-MIN_SPACE)/100.0f);
if(!draggingWidget) parent.screenDistWidget.setValue(loc/100.0f);
}
public float getScreenDist() {return screenDist;}
public void setLength(float loc) {
length=loc;
//A length change requires recalculating Mirror2's position-ish thing:
xp2=(float) (length - Math.cos(mirror2_angle)*radius_mirror2);
laserbeam.setXPs(xp1,xp2);
parent.screenDistField.setMin(loc+MIN_SPACE);
parent.screenDistWidget.setMin((loc+MIN_SPACE)/100.0f);
if(!draggingWidget) parent.cavityLenWidget.setValue(loc/100.0f);
}
public float getLength() {return length;}
public void setLambda(float l) {
lambda=l;
if(!draggingWidget) parent.wavelengthWidget.setValue(l);
}
public float getLambda() {return lambda;}
public void setR1(float r1) {R1=r1;}
public float getR1() {return R1;}
public void setR2(float r2) {R2=r2;}
public float getR2() {return R2;}
public Laser getParent() {return parent;}
public LaserBeam getBeam() {return laserbeam;}
// -------------------------------------------------------------------------------
// WSL callbacks
// -------------------------------------------------------------------------------
/*
public WSLNode toWSLNode() {
WSLNode laser=new WSLNode("laser");
final WSLAttributeList atts=laser.getAttributes();
atts.add("wavelength", String.valueOf(lambda));
atts.add("radius1", String.valueOf(R1));
atts.add("radius2", String.valueOf(R2));
atts.add("length", String.valueOf(length));
atts.add("screen", String.valueOf(screenDist));
atts.add("aperture", String.valueOf(controlPanel.getAperture()));
atts.add("intensity", String.valueOf(controlPanel.getIntensity()));
atts.add("widgetsOn", String.valueOf(widgetsOn));
return laser;
}
private void setParameter(String target, String param, String value) {
float v=Float.NaN;
try{v=new Float(value).floatValue();}catch(NumberFormatException e){}
if("wavelength".equals(param))
controlPanel.setWavelength(v);
else if("radius1".equals(param))
controlPanel.setR1(v);
else if("radius2".equals(param))
controlPanel.setR2(v);
else if("length".equals(param))
controlPanel.setLength(v);
else if("screenDist".equals(param))
controlPanel.setScreen(v);
else if("reset".equals(param))
controlPanel.setDefaults();
else if("toggleWidgets".equals(param))
setWidgetsVisible(!widgetsOn);
else if("aperture".equals(param))
controlPanel.setAperture(Integer.parseInt(value));
else if("intensity".equals(param))
controlPanel.setIntensity(Integer.parseInt(value));
else if("resetIntensity".equals(param))
controlPanel.resetIntensity();
}
public void scriptActionFired(WSLScriptEvent event) {
int id=event.getID();
String target=event.getTarget();
String param=event.getParameter();
String value=event.getValue();
if(id==event.ACTION_PERFORMED || id==event.MOUSE_DRAGGED) {
setParameter(target, param, value);
}
}
public void initialize(WSLScriptEvent event) {
WSLAttributeList atts=event.getNode().getAttributes();
controlPanel.setWavelength(atts.getFloatValue("wavelength", WavelengthWidget.DEFAULT));
controlPanel.setR1(atts.getFloatValue("radius1", ControlPanel.DEF_ROC));
controlPanel.setR2(atts.getFloatValue("radius2", ControlPanel.DEF_ROC));
controlPanel.setScreen(ScreenDistanceWidget.MAX); //To allow any length
controlPanel.setLength(atts.getFloatValue("length", LengthWidget.DEFAULT));
controlPanel.setScreen(atts.getFloatValue("screen", ScreenDistanceWidget.DEFAULT));
controlPanel.setAperture(atts.getIntValue("aperture", 0));
controlPanel.setIntensity(atts.getIntValue("intensity", ControlPanel.DEF_INTENSITY));
setWidgetsVisible(atts.getBooleanValue("widgetsOn", true));
}
//Should this have anything in it? [Davis]
public void playerStateChanged(WSLPlayerEvent event) {
switch(event.getID()) {
case WSLPlayerEvent.PLAYER_STARTED: break; //disable stuff
case WSLPlayerEvent.PLAYER_STOPPED: break; //enable stuff
}
}
*/
}
|
package com.GestiondesClub.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
@Table(name="Ligne_devi")
@NamedQuery(name="LigneDevi.findAll", query="SELECT ld FROM LigneDevi ld")
public class LigneDevi {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@ManyToOne
@JoinColumn
MaterielExterne matExterne;
@JsonBackReference(value="les-demande-Finance")
@ManyToOne
@JoinColumn
DemandeFinancement demandeFinance;
private int quantite;
private float montant;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public MaterielExterne getMatExterne() {
return matExterne;
}
public void setMatExterne(MaterielExterne matExterne) {
this.matExterne = matExterne;
}
public DemandeFinancement getDemandeFinance() {
return demandeFinance;
}
public void setDemandeFinance(DemandeFinancement demandeFinance) {
this.demandeFinance = demandeFinance;
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public float getMontant() {
return montant;
}
public void setMontant(float montant) {
this.montant = montant;
}
}
|
package vostore.apptualidade;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Paint;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.mukeshsolanki.sociallogin.google.GoogleHelper;
import com.tfb.fbtoast.FBToast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import vostore.apptualidade.Consts.Const;
import vostore.apptualidade.Firebase.Usuario;
import vostore.apptualidade.helper.Preferencias;
import static vostore.apptualidade.Consts.Const.RC_SIGN_IN;
public class Login extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
ImageView top;
Animation fromlogo;
Button btnLogin,btnGoogle, btnFacebook;
private GoogleApiClient googleApiClient;
private CallbackManager mCallbackManager;
private static final String TAG = "FACELOG";
private FirebaseAuth mAuth,firebaseAuth;
private DatabaseReference databaseReference;
private EditText senhausuario,emailusuario;
private TextView cadastre;
HelperFacebook mFacebook;
GoogleHelper mGoogle;
private CallbackManager mCallBackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//verificarUsuarioLogado();
//Configurações do Login da Google
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//Fazendo Cast
cadastre = findViewById(R.id.textView5);
btnLogin = findViewById(R.id.botaoentrar);
top = findViewById(R.id.logologin);
fromlogo = AnimationUtils.loadAnimation(this, R.anim.fromlogo);
btnFacebook = findViewById(R.id.btn_facebook);
btnGoogle = findViewById(R.id.btn_google);
top.setAnimation(fromlogo);
senhausuario = findViewById(R.id.senhaid);
emailusuario = findViewById(R.id.emailid);
// Instanciando servidor
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
firebaseAuth = ConfiguracaoFirebase.getFirebaseAutenticacao();
//Aplicando uma linha inferior ao nome
cadastre.setPaintFlags(cadastre.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
//LoginManager.getInstance().logOut();
//Ação do Botão Google
btnGoogle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loginGoogle();
}
});
//Ação do Botão Facebook
btnFacebook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loginFacebook();
}
});
//Ação do nome Cadastre
cadastre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cadastrar();
}
});
//Ação do Login Normal
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
login();
}
});
}
// *-------- MÉTODOS ----------
private boolean validaremail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public boolean validarsenha(){
String contraseña;
contraseña = senhausuario.getText().toString();
if(contraseña.length()>=6 && contraseña.length()<=16){
return true;
}else return false;
}
private void verificarUsuarioLogado(){
mAuth = ConfiguracaoFirebase.getFirebaseAutenticacao();
if(mAuth.getCurrentUser()!= null ){
updateUI();
}
}
//Login com o Google
private void loginGoogle() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
Log.d(Const.TAG_LOGIN_GOOGLE, "Google login error", task.getException());
if (task.isSuccessful()) {
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
saveUser(currentUser, acct.getEmail());
} else
Toast.makeText(Login.this, "Authentication with Google failed.",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Const.RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed
Log.e(TAG, "Google Sign In failed.");
}
}
//Sem essa instrução , o login do facebook não irá funcionar
else
mCallbackManager.onActivityResult(requestCode, resultCode, data);
// mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
//Login Convencional
private void login(){
String email = emailusuario.getText().toString();
if (validaremail(email) && validarsenha()){
String senha = senhausuario.getText().toString();
mAuth.signInWithEmailAndPassword(email,senha)
.addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
// Toast.makeText(Login.this,"Login bem sucedido",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this,Inicio.class);
startActivity(intent);
finish();
//overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else{
Toast toast = new Toast(Login.this);
ImageView view = new ImageView(Login.this);
view.setImageResource(R.drawable.toast_erro);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(view);
toast.show();
// Toast.makeText(Login.this,"Não foi possível entrar no ambiente",Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(Login.this,"Erro de Login.",Toast.LENGTH_SHORT).show();
}
}
//Login com o Facebook
private void loginFacebook() {
mCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().logInWithReadPermissions(Login.this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
handleFacebookAccessToken(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Log.d(Const.TAG_LOGIN_FACEBOOK, "facebook:onCancel");
}
@Override
public void onError(FacebookException error) {
Log.d(Const.TAG_LOGIN_FACEBOOK, "facebook:onError", error);
}
});
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful())
Log.e(Const.TAG_LOGIN_FACEBOOK, "Facebook error", task.getException());
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
saveUser(user,null);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI();
}
// ...
}
});
}
//Salvar dos do usuário em uma classe
private void saveUser (FirebaseUser firebaseUser, String email){
FBToast.successToast(Login.this,"Login efetuado com sucesso!", FBToast.LENGTH_SHORT);
FirebaseUser currentUser = firebaseUser;
Preferencias preferencias = new Preferencias(Login.this);
preferencias.savePreferences(getString(R.string.id_user_app), firebaseUser.getUid());
preferencias.savePreferences(getString(R.string.username_app), firebaseUser.getDisplayName());
if (email != null) preferencias.savePreferences(getString(R.string.email_app), email);
Usuario user = new Usuario();
user.setId(firebaseUser.getUid());
user.setNome(currentUser.getDisplayName());
if (email != null)
user.setEmail(email);
user.saveUser();
updateUI();
}
//Abrir tela seguinte
private void updateUI(){
// Toast.makeText(Login.this, "Login Realizado", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, Inicio.class);
startActivity(intent);
finish();
}
//Abrir tela Cadastro
private void cadastrar(){
Intent intent = new Intent(Login.this,Cadastro.class);
startActivity(intent);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
//Utilizando Intent para estabelecer um ação no clique do botão "voltar", nativo dos dispositivos android
@Override
public void onBackPressed() {
Intent intent = new Intent(Login.this, Entrar.class);
startActivity(intent);
finish();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
FBToast.errorToast(Login.this,"Erro no Google Play Services",FBToast.LENGTH_SHORT);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public void onPause() {
super.onPause();
}
}
|
//accept any four no check and display the smollest value
import java.util.*;
class smollest1
{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
int a,b,c,d;
System.out.print("Enter any four no::-");
a=x.nextInt();
b=x.nextInt();
c=x.nextInt();
d=x.nextInt();
if(a<b)
if(a<c)
if(a<d)
System.out.println("Smollest value is::"+a);
else
System.out.println("Smollest value is::"+d);
else if(c<d)
System.out.println("Smollest value is::"+c);
else
System.out.println("Smollest value is::"+d);
else if(b<c)
if(b<d)
System.out.println("Smollest value is::"+b);
else
System.out.println("Smollest value is::"+d);
else if(c<d)
System.out.println("Smollest value is::"+c);
else
System.out.println("Smollest value is::"+d);
}//close of main
}//close of class |
// Generated by view binder compiler. Do not edit!
package com.designurway.idlidosa.databinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.viewbinding.ViewBinding;
import com.designurway.idlidosa.R;
import java.lang.NullPointerException;
import java.lang.Override;
import java.lang.String;
public final class FragmentSettingsBinding implements ViewBinding {
@NonNull
private final ConstraintLayout rootView;
@NonNull
public final CardView CardEdit;
@NonNull
public final CardView CardOffer;
@NonNull
public final CardView CardOrder;
@NonNull
public final CardView CardSupport;
@NonNull
public final CardView CardUpdate;
@NonNull
public final TextView Edit;
@NonNull
public final TextView EditSupport;
@NonNull
public final TextView Offer;
@NonNull
public final ConstraintLayout consEdtAd;
@NonNull
public final ConstraintLayout consHistory;
@NonNull
public final ConstraintLayout consRefer;
@NonNull
public final ConstraintLayout consSigout;
@NonNull
public final ConstraintLayout consSupport;
@NonNull
public final ConstraintLayout consTrack;
@NonNull
public final ConstraintLayout consUpdate;
@NonNull
public final ConstraintLayout constPickReward;
@NonNull
public final ImageView imagArrEdit;
@NonNull
public final ImageView imagArrOrdr;
@NonNull
public final ImageView imagArrRefer;
@NonNull
public final ImageView imagArrReward;
@NonNull
public final ImageView imagArrSignout;
@NonNull
public final ImageView imagArrSupport;
@NonNull
public final ImageView imagArrTrack;
@NonNull
public final ImageView imagArrUpdate;
@NonNull
public final ImageView imagEdit;
@NonNull
public final ImageView imagOrder;
@NonNull
public final ImageView imagRefer;
@NonNull
public final ImageView imagReward;
@NonNull
public final ImageView imagSignout;
@NonNull
public final ImageView imagSupport;
@NonNull
public final ImageView imagTrack;
@NonNull
public final ImageView imagUpdate;
@NonNull
public final TextView orderd;
private FragmentSettingsBinding(@NonNull ConstraintLayout rootView, @NonNull CardView CardEdit,
@NonNull CardView CardOffer, @NonNull CardView CardOrder, @NonNull CardView CardSupport,
@NonNull CardView CardUpdate, @NonNull TextView Edit, @NonNull TextView EditSupport,
@NonNull TextView Offer, @NonNull ConstraintLayout consEdtAd,
@NonNull ConstraintLayout consHistory, @NonNull ConstraintLayout consRefer,
@NonNull ConstraintLayout consSigout, @NonNull ConstraintLayout consSupport,
@NonNull ConstraintLayout consTrack, @NonNull ConstraintLayout consUpdate,
@NonNull ConstraintLayout constPickReward, @NonNull ImageView imagArrEdit,
@NonNull ImageView imagArrOrdr, @NonNull ImageView imagArrRefer,
@NonNull ImageView imagArrReward, @NonNull ImageView imagArrSignout,
@NonNull ImageView imagArrSupport, @NonNull ImageView imagArrTrack,
@NonNull ImageView imagArrUpdate, @NonNull ImageView imagEdit, @NonNull ImageView imagOrder,
@NonNull ImageView imagRefer, @NonNull ImageView imagReward, @NonNull ImageView imagSignout,
@NonNull ImageView imagSupport, @NonNull ImageView imagTrack, @NonNull ImageView imagUpdate,
@NonNull TextView orderd) {
this.rootView = rootView;
this.CardEdit = CardEdit;
this.CardOffer = CardOffer;
this.CardOrder = CardOrder;
this.CardSupport = CardSupport;
this.CardUpdate = CardUpdate;
this.Edit = Edit;
this.EditSupport = EditSupport;
this.Offer = Offer;
this.consEdtAd = consEdtAd;
this.consHistory = consHistory;
this.consRefer = consRefer;
this.consSigout = consSigout;
this.consSupport = consSupport;
this.consTrack = consTrack;
this.consUpdate = consUpdate;
this.constPickReward = constPickReward;
this.imagArrEdit = imagArrEdit;
this.imagArrOrdr = imagArrOrdr;
this.imagArrRefer = imagArrRefer;
this.imagArrReward = imagArrReward;
this.imagArrSignout = imagArrSignout;
this.imagArrSupport = imagArrSupport;
this.imagArrTrack = imagArrTrack;
this.imagArrUpdate = imagArrUpdate;
this.imagEdit = imagEdit;
this.imagOrder = imagOrder;
this.imagRefer = imagRefer;
this.imagReward = imagReward;
this.imagSignout = imagSignout;
this.imagSupport = imagSupport;
this.imagTrack = imagTrack;
this.imagUpdate = imagUpdate;
this.orderd = orderd;
}
@Override
@NonNull
public ConstraintLayout getRoot() {
return rootView;
}
@NonNull
public static FragmentSettingsBinding inflate(@NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
@NonNull
public static FragmentSettingsBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.fragment_settings, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
@NonNull
public static FragmentSettingsBinding bind(@NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.CardEdit;
CardView CardEdit = rootView.findViewById(id);
if (CardEdit == null) {
break missingId;
}
id = R.id.CardOffer;
CardView CardOffer = rootView.findViewById(id);
if (CardOffer == null) {
break missingId;
}
id = R.id.CardOrder;
CardView CardOrder = rootView.findViewById(id);
if (CardOrder == null) {
break missingId;
}
id = R.id.CardSupport;
CardView CardSupport = rootView.findViewById(id);
if (CardSupport == null) {
break missingId;
}
id = R.id.CardUpdate;
CardView CardUpdate = rootView.findViewById(id);
if (CardUpdate == null) {
break missingId;
}
id = R.id.Edit;
TextView Edit = rootView.findViewById(id);
if (Edit == null) {
break missingId;
}
id = R.id.EditSupport;
TextView EditSupport = rootView.findViewById(id);
if (EditSupport == null) {
break missingId;
}
id = R.id.Offer;
TextView Offer = rootView.findViewById(id);
if (Offer == null) {
break missingId;
}
id = R.id.consEdtAd;
ConstraintLayout consEdtAd = rootView.findViewById(id);
if (consEdtAd == null) {
break missingId;
}
id = R.id.consHistory;
ConstraintLayout consHistory = rootView.findViewById(id);
if (consHistory == null) {
break missingId;
}
id = R.id.consRefer;
ConstraintLayout consRefer = rootView.findViewById(id);
if (consRefer == null) {
break missingId;
}
id = R.id.consSigout;
ConstraintLayout consSigout = rootView.findViewById(id);
if (consSigout == null) {
break missingId;
}
id = R.id.consSupport;
ConstraintLayout consSupport = rootView.findViewById(id);
if (consSupport == null) {
break missingId;
}
id = R.id.consTrack;
ConstraintLayout consTrack = rootView.findViewById(id);
if (consTrack == null) {
break missingId;
}
id = R.id.consUpdate;
ConstraintLayout consUpdate = rootView.findViewById(id);
if (consUpdate == null) {
break missingId;
}
id = R.id.constPickReward;
ConstraintLayout constPickReward = rootView.findViewById(id);
if (constPickReward == null) {
break missingId;
}
id = R.id.imagArrEdit;
ImageView imagArrEdit = rootView.findViewById(id);
if (imagArrEdit == null) {
break missingId;
}
id = R.id.imagArrOrdr;
ImageView imagArrOrdr = rootView.findViewById(id);
if (imagArrOrdr == null) {
break missingId;
}
id = R.id.imagArrRefer;
ImageView imagArrRefer = rootView.findViewById(id);
if (imagArrRefer == null) {
break missingId;
}
id = R.id.imagArrReward;
ImageView imagArrReward = rootView.findViewById(id);
if (imagArrReward == null) {
break missingId;
}
id = R.id.imagArrSignout;
ImageView imagArrSignout = rootView.findViewById(id);
if (imagArrSignout == null) {
break missingId;
}
id = R.id.imagArrSupport;
ImageView imagArrSupport = rootView.findViewById(id);
if (imagArrSupport == null) {
break missingId;
}
id = R.id.imagArrTrack;
ImageView imagArrTrack = rootView.findViewById(id);
if (imagArrTrack == null) {
break missingId;
}
id = R.id.imagArrUpdate;
ImageView imagArrUpdate = rootView.findViewById(id);
if (imagArrUpdate == null) {
break missingId;
}
id = R.id.imagEdit;
ImageView imagEdit = rootView.findViewById(id);
if (imagEdit == null) {
break missingId;
}
id = R.id.imagOrder;
ImageView imagOrder = rootView.findViewById(id);
if (imagOrder == null) {
break missingId;
}
id = R.id.imagRefer;
ImageView imagRefer = rootView.findViewById(id);
if (imagRefer == null) {
break missingId;
}
id = R.id.imagReward;
ImageView imagReward = rootView.findViewById(id);
if (imagReward == null) {
break missingId;
}
id = R.id.imagSignout;
ImageView imagSignout = rootView.findViewById(id);
if (imagSignout == null) {
break missingId;
}
id = R.id.imagSupport;
ImageView imagSupport = rootView.findViewById(id);
if (imagSupport == null) {
break missingId;
}
id = R.id.imagTrack;
ImageView imagTrack = rootView.findViewById(id);
if (imagTrack == null) {
break missingId;
}
id = R.id.imagUpdate;
ImageView imagUpdate = rootView.findViewById(id);
if (imagUpdate == null) {
break missingId;
}
id = R.id.orderd;
TextView orderd = rootView.findViewById(id);
if (orderd == null) {
break missingId;
}
return new FragmentSettingsBinding((ConstraintLayout) rootView, CardEdit, CardOffer,
CardOrder, CardSupport, CardUpdate, Edit, EditSupport, Offer, consEdtAd, consHistory,
consRefer, consSigout, consSupport, consTrack, consUpdate, constPickReward, imagArrEdit,
imagArrOrdr, imagArrRefer, imagArrReward, imagArrSignout, imagArrSupport, imagArrTrack,
imagArrUpdate, imagEdit, imagOrder, imagRefer, imagReward, imagSignout, imagSupport,
imagTrack, imagUpdate, orderd);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
|
package cn.okay.page.officialwebsite.fourthpage;
import cn.okay.testbase.AbstractPage;
import cn.okay.tools.WaitTool;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
/**
* Created by yutz on 2018/8/24.
* 首页点击最新资讯,进入的这个单独的四级页
*/
public class NewestNewDetailedPage extends AbstractPage {
@FindBy(css=".title .clearfix")
WebElement newInformationMoudle;
public NewestNewDetailedPage(WebDriver driver) {
super(driver);
WaitTool.waitFor(driver,WaitTool.DEFAULT_WAIT_4_ELEMENT,newInformationMoudle);
}
}
|
package home;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class DataConverter {
public static String[][] convertToRawData(ArrayList<ArrayList<String>> data) {
String[][] rawData = new String[data.size()][];
int index = 0;
for (var dataPiece : data) {
rawData[index] = new String[dataPiece.size()];
rawData[index] = dataPiece.toArray(rawData[index]);
index++;
}
return rawData;
}
public static ArrayList<String> convertJsonToStrArrByKey(JSONArray jsonArr, String key) {
ArrayList<String> result = new ArrayList<>();
for (Object obj : jsonArr) {
JSONObject objJson = (JSONObject) obj;
result.add(objJson.get(key).toString());
}
return result;
}
public static ArrayList<String> convertObjArrToStrArr(ArrayList<Object> objArr) {
ArrayList<String> result = new ArrayList<>();
for (Object obj : objArr) {
result.add(obj.toString());
}
return result;
}
public static String getDateFromTimeStamp(String timeStamp) {
return timeStamp.substring(0, timeStamp.indexOf("T"));
}
public static String getTimeFromTimeStamp(String timeStamp) {
return timeStamp.substring(timeStamp.indexOf("T") + 1, timeStamp.indexOf("."));
}
}
|
package com.exception;
public class HrException extends RuntimeException{
public HrException() {
}
public HrException(String message) {
super(message);
}
}
|
package com.bharath.tasks.autoscout24.controller;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.nio.file.Files;
import java.nio.file.Paths;
@SpringBootTest
@AutoConfigureMockMvc
public class ReportControllerTest {
private MockMvc mockMvc;
@Autowired
public ReportControllerTest(MockMvc mockMvc) {
this.mockMvc = mockMvc;
}
@Test
public void testGetAverageListingPriceReport() throws Exception {
String expectedResult = "[\n" +
" {\n" +
" \"sellerType\": \"private\",\n" +
" \"averagePrice\": \"€ 26.081,-\"\n" +
" },\n" +
" {\n" +
" \"sellerType\": \"other\",\n" +
" \"averagePrice\": \"€ 25.318,-\"\n" +
" },\n" +
" {\n" +
" \"sellerType\": \"dealer\",\n" +
" \"averagePrice\": \"€ 25.038,-\"\n" +
" }\n" +
"]";
mockMvc.perform(MockMvcRequestBuilders.get("/reports/AvgListingPrice"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(expectedResult));
}
@Test
public void testGetMakeDistributionPercent() throws Exception {
String exptectedResult = "[\n" +
" {\n" +
" \"make\": \"Mercedes-Benz\",\n" +
" \"distributionPercent\": \"16%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"Toyota\",\n" +
" \"distributionPercent\": \"16%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"Audi\",\n" +
" \"distributionPercent\": \"14%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"Renault\",\n" +
" \"distributionPercent\": \"14%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"Mazda\",\n" +
" \"distributionPercent\": \"13%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"VW\",\n" +
" \"distributionPercent\": \"10%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"Fiat\",\n" +
" \"distributionPercent\": \"9%\"\n" +
" },\n" +
" {\n" +
" \"make\": \"BWM\",\n" +
" \"distributionPercent\": \"7%\"\n" +
" }\n" +
"]";
mockMvc.perform(MockMvcRequestBuilders.get("/reports/MakeDistributionPercent"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(exptectedResult));
}
@Test
public void testGetAvg30PercentMostContactedListingsPrice() throws Exception {
String expectedResult = "{\n" +
" \"price\": \"€ 24.908,-\"\n" +
"}";
mockMvc.perform(MockMvcRequestBuilders.get("/reports/Avg30PercentMostContactedListingsPrice"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(expectedResult));
}
@Test
public void testGetTop5ListingsPerMonth() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/reports/Top5ListingsPerMonth"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$[0].listings[0].totalAmountOfContacts", Matchers.is(21)));
}
@Test
public void testUploadListings() throws Exception {
MockMultipartFile file
= new MockMultipartFile(
"File",
"test.csv",
MediaType.TEXT_PLAIN_VALUE,
Files.readAllBytes(Paths.get("resources/csv/listings/listings.csv"))
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/reports/UploadListings").file(file))
.andExpect(MockMvcResultMatchers.status().isCreated())
.andExpect(MockMvcResultMatchers.content().string("Listing File uploaded successfully"));
}
@Test
public void testUploadContactListings() throws Exception {
MockMultipartFile file
= new MockMultipartFile(
"File",
"test.csv",
MediaType.TEXT_PLAIN_VALUE,
Files.readAllBytes(Paths.get("resources/csv/contacts/contacts.csv"))
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/reports/UploadContactListings").file(file))
.andExpect(MockMvcResultMatchers.status().isCreated())
.andExpect(MockMvcResultMatchers.content().string("Contacts File uploaded successfully"));
}
@Test
public void whenUploadContactListingsIncorrectFileExtension_then422StatusCode() throws Exception {
MockMultipartFile file
= new MockMultipartFile(
"File",
"test.ctx",
MediaType.TEXT_PLAIN_VALUE,
Files.readAllBytes(Paths.get("resources/csv/contacts/contacts.csv"))
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/reports/UploadContactListings").file(file))
.andExpect(MockMvcResultMatchers.status().isUnprocessableEntity());
}
@Test
public void whenUploadListingsIncorrectFileExtension_then422StatusCode() throws Exception {
MockMultipartFile file
= new MockMultipartFile(
"File",
"test.ctx",
MediaType.TEXT_PLAIN_VALUE,
"".getBytes()
);
mockMvc.perform(MockMvcRequestBuilders.multipart("/reports/UploadListings").file(file))
.andExpect(MockMvcResultMatchers.status().isUnprocessableEntity());
}
}
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.task;
import java.io.Serializable;
import org.springframework.util.Assert;
/**
* {@link TaskExecutor} implementation that executes each task <i>synchronously</i>
* in the calling thread.
*
* <p>Mainly intended for testing scenarios.
*
* <p>Execution in the calling thread does have the advantage of participating
* in its thread context, for example the thread context class loader or the
* thread's current transaction association. That said, in many cases,
* asynchronous execution will be preferable: choose an asynchronous
* {@code TaskExecutor} instead for such scenarios.
*
* @author Juergen Hoeller
* @since 2.0
* @see SimpleAsyncTaskExecutor
*/
@SuppressWarnings("serial")
public class SyncTaskExecutor implements TaskExecutor, Serializable {
/**
* Executes the given {@code task} synchronously, through direct
* invocation of it's {@link Runnable#run() run()} method.
* @throws IllegalArgumentException if the given {@code task} is {@code null}
*/
@Override
public void execute(Runnable task) {
Assert.notNull(task, "Runnable must not be null");
task.run();
}
}
|
package creational.abstractfactory.my;
import creational.abstractfactory.my.factory.*;
// 客户段代码
public class Main {
// 引用抽象工厂对象
static AbstractFactory factory;
public static void main(String[] args) {
configure();
businessLogic();
}
// 一般根据系统配置确定具体工厂
static void configure() {
// factory = new Factory1();
factory = new Factory2();
}
// 业务逻辑
public static void businessLogic() {
factory.reportProducFamilies();
}
}
|
package uk.co.tekkies.readings.model.content;
import android.util.Log;
import java.io.File;
public class KjvScourby2Mp3ContentLocator extends Mp3ContentLocator {
@Override
public String getTitle() {
return "Scourby KJV MP3(2)";
}
@Override
public String searchGetBaseFolderFromKeyFile(File potentialKeyFile) {
return potentialKeyFile.getParent();
}
@Override
public boolean searchConfirmKeyFileFound(String baseFolder) {
Boolean confirmed = false;
File prov15 = new File(baseFolder + "/20 Proverbs 015.mp3");
if (prov15.exists()) {
Log.v(TAG, "confirmKeyFileFound: Found: Prov 15");
File james3 = new File(baseFolder + "/59 James 003.mp3");
if (james3.exists()) {
Log.v(TAG, "confirmKeyFileFound: Found: James 3");
confirmed = true;
}
}
return confirmed;
}
@Override
public String searchGetKeyFileName() {
return "01 Genesis 001.mp3";
}
@Override
protected String getPassageSubPath(int passageId) {
switch (passageId)
{
case 1: return "01 Genesis 001.mp3";
case 2: return "01 Genesis 002.mp3";
case 3: return "01 Genesis 003.mp3";
case 4: return "01 Genesis 004.mp3";
case 5: return "01 Genesis 005.mp3";
case 6: return "01 Genesis 006.mp3";
case 7: return "01 Genesis 007.mp3";
case 8: return "01 Genesis 008.mp3";
case 9: return "01 Genesis 009.mp3";
case 10: return "01 Genesis 010.mp3";
case 11: return "01 Genesis 011.mp3";
case 12: return "01 Genesis 012.mp3";
case 13: return "01 Genesis 013.mp3";
case 14: return "01 Genesis 014.mp3";
case 15: return "01 Genesis 015.mp3";
case 16: return "01 Genesis 016.mp3";
case 17: return "01 Genesis 017.mp3";
case 18: return "01 Genesis 018.mp3";
case 19: return "01 Genesis 019.mp3";
case 20: return "01 Genesis 020.mp3";
case 21: return "01 Genesis 021.mp3";
case 22: return "01 Genesis 022.mp3";
case 23: return "01 Genesis 023.mp3";
case 24: return "01 Genesis 024.mp3";
case 25: return "01 Genesis 025.mp3";
case 26: return "01 Genesis 026.mp3";
case 27: return "01 Genesis 027.mp3";
case 28: return "01 Genesis 028.mp3";
case 29: return "01 Genesis 029.mp3";
case 30: return "01 Genesis 030.mp3";
case 31: return "01 Genesis 031.mp3";
case 32: return "01 Genesis 032.mp3";
case 33: return "01 Genesis 033.mp3";
case 34: return "01 Genesis 034.mp3";
case 35: return "01 Genesis 035.mp3";
case 36: return "01 Genesis 036.mp3";
case 37: return "01 Genesis 037.mp3";
case 38: return "01 Genesis 038.mp3";
case 39: return "01 Genesis 039.mp3";
case 40: return "01 Genesis 040.mp3";
case 41: return "01 Genesis 041.mp3";
case 42: return "01 Genesis 042.mp3";
case 43: return "01 Genesis 043.mp3";
case 44: return "01 Genesis 044.mp3";
case 45: return "01 Genesis 045.mp3";
case 46: return "01 Genesis 046.mp3";
case 47: return "01 Genesis 047.mp3";
case 48: return "01 Genesis 048.mp3";
case 49: return "01 Genesis 049.mp3";
case 50: return "01 Genesis 050.mp3";
case 51: return "02 Exodus 001.mp3";
case 52: return "02 Exodus 002.mp3";
case 53: return "02 Exodus 003.mp3";
case 54: return "02 Exodus 004.mp3";
case 55: return "02 Exodus 005.mp3";
case 56: return "02 Exodus 006.mp3";
case 57: return "02 Exodus 007.mp3";
case 58: return "02 Exodus 008.mp3";
case 59: return "02 Exodus 009.mp3";
case 60: return "02 Exodus 010.mp3";
case 61: return "02 Exodus 011.mp3";
case 62: return "02 Exodus 012.mp3";
case 63: return "02 Exodus 013.mp3";
case 64: return "02 Exodus 014.mp3";
case 65: return "02 Exodus 015.mp3";
case 66: return "02 Exodus 016.mp3";
case 67: return "02 Exodus 017.mp3";
case 68: return "02 Exodus 018.mp3";
case 69: return "02 Exodus 019.mp3";
case 70: return "02 Exodus 020.mp3";
case 71: return "02 Exodus 021.mp3";
case 72: return "02 Exodus 022.mp3";
case 73: return "02 Exodus 023.mp3";
case 74: return "02 Exodus 024.mp3";
case 75: return "02 Exodus 025.mp3";
case 76: return "02 Exodus 026.mp3";
case 77: return "02 Exodus 027.mp3";
case 78: return "02 Exodus 028.mp3";
case 79: return "02 Exodus 029.mp3";
case 80: return "02 Exodus 030.mp3";
case 81: return "02 Exodus 031.mp3";
case 82: return "02 Exodus 032.mp3";
case 83: return "02 Exodus 033.mp3";
case 84: return "02 Exodus 034.mp3";
case 85: return "02 Exodus 035.mp3";
case 86: return "02 Exodus 036.mp3";
case 87: return "02 Exodus 037.mp3";
case 88: return "02 Exodus 038.mp3";
case 89: return "02 Exodus 039.mp3";
case 90: return "02 Exodus 040.mp3";
case 91: return "03 Leviticus 001.mp3";
case 92: return "03 Leviticus 002.mp3";
case 93: return "03 Leviticus 003.mp3";
case 94: return "03 Leviticus 004.mp3";
case 95: return "03 Leviticus 005.mp3";
case 96: return "03 Leviticus 006.mp3";
case 97: return "03 Leviticus 007.mp3";
case 98: return "03 Leviticus 008.mp3";
case 99: return "03 Leviticus 009.mp3";
case 100: return "03 Leviticus 010.mp3";
case 101: return "03 Leviticus 011.mp3";
case 102: return "03 Leviticus 012.mp3";
case 103: return "03 Leviticus 013.mp3";
case 104: return "03 Leviticus 014.mp3";
case 105: return "03 Leviticus 015.mp3";
case 106: return "03 Leviticus 016.mp3";
case 107: return "03 Leviticus 017.mp3";
case 108: return "03 Leviticus 018.mp3";
case 109: return "03 Leviticus 019.mp3";
case 110: return "03 Leviticus 020.mp3";
case 111: return "03 Leviticus 021.mp3";
case 112: return "03 Leviticus 022.mp3";
case 113: return "03 Leviticus 023.mp3";
case 114: return "03 Leviticus 024.mp3";
case 115: return "03 Leviticus 025.mp3";
case 116: return "03 Leviticus 026.mp3";
case 117: return "03 Leviticus 027.mp3";
case 118: return "04 Numbers 001.mp3";
case 119: return "04 Numbers 002.mp3";
case 120: return "04 Numbers 003.mp3";
case 121: return "04 Numbers 004.mp3";
case 122: return "04 Numbers 005.mp3";
case 123: return "04 Numbers 006.mp3";
case 124: return "04 Numbers 007.mp3";
case 125: return "04 Numbers 008.mp3";
case 126: return "04 Numbers 009.mp3";
case 127: return "04 Numbers 010.mp3";
case 128: return "04 Numbers 011.mp3";
case 129: return "04 Numbers 012.mp3";
case 130: return "04 Numbers 013.mp3";
case 131: return "04 Numbers 014.mp3";
case 132: return "04 Numbers 015.mp3";
case 133: return "04 Numbers 016.mp3";
case 134: return "04 Numbers 017.mp3";
case 135: return "04 Numbers 018.mp3";
case 136: return "04 Numbers 019.mp3";
case 137: return "04 Numbers 020.mp3";
case 138: return "04 Numbers 021.mp3";
case 139: return "04 Numbers 022.mp3";
case 140: return "04 Numbers 023.mp3";
case 141: return "04 Numbers 024.mp3";
case 142: return "04 Numbers 025.mp3";
case 143: return "04 Numbers 026.mp3";
case 144: return "04 Numbers 027.mp3";
case 145: return "04 Numbers 028.mp3";
case 146: return "04 Numbers 029.mp3";
case 147: return "04 Numbers 030.mp3";
case 148: return "04 Numbers 031.mp3";
case 149: return "04 Numbers 032.mp3";
case 150: return "04 Numbers 033.mp3";
case 151: return "04 Numbers 034.mp3";
case 152: return "04 Numbers 035.mp3";
case 153: return "04 Numbers 036.mp3";
case 154: return "05 Deuteronomy 001.mp3";
case 155: return "05 Deuteronomy 002.mp3";
case 156: return "05 Deuteronomy 003.mp3";
case 157: return "05 Deuteronomy 004.mp3";
case 158: return "05 Deuteronomy 005.mp3";
case 159: return "05 Deuteronomy 006.mp3";
case 160: return "05 Deuteronomy 007.mp3";
case 161: return "05 Deuteronomy 008.mp3";
case 162: return "05 Deuteronomy 009.mp3";
case 163: return "05 Deuteronomy 010.mp3";
case 164: return "05 Deuteronomy 011.mp3";
case 165: return "05 Deuteronomy 012.mp3";
case 166: return "05 Deuteronomy 013.mp3";
case 167: return "05 Deuteronomy 014.mp3";
case 168: return "05 Deuteronomy 015.mp3";
case 169: return "05 Deuteronomy 016.mp3";
case 170: return "05 Deuteronomy 017.mp3";
case 171: return "05 Deuteronomy 018.mp3";
case 172: return "05 Deuteronomy 019.mp3";
case 173: return "05 Deuteronomy 020.mp3";
case 174: return "05 Deuteronomy 021.mp3";
case 175: return "05 Deuteronomy 022.mp3";
case 176: return "05 Deuteronomy 023.mp3";
case 177: return "05 Deuteronomy 024.mp3";
case 178: return "05 Deuteronomy 025.mp3";
case 179: return "05 Deuteronomy 026.mp3";
case 180: return "05 Deuteronomy 027.mp3";
case 181: return "05 Deuteronomy 028.mp3";
case 182: return "05 Deuteronomy 029.mp3";
case 183: return "05 Deuteronomy 030.mp3";
case 184: return "05 Deuteronomy 031.mp3";
case 185: return "05 Deuteronomy 032.mp3";
case 186: return "05 Deuteronomy 033.mp3";
case 187: return "05 Deuteronomy 034.mp3";
case 188: return "06 Joshua 001.mp3";
case 189: return "06 Joshua 002.mp3";
case 190: return "06 Joshua 003.mp3";
case 191: return "06 Joshua 004.mp3";
case 192: return "06 Joshua 005.mp3";
case 193: return "06 Joshua 006.mp3";
case 194: return "06 Joshua 007.mp3";
case 195: return "06 Joshua 008.mp3";
case 196: return "06 Joshua 009.mp3";
case 197: return "06 Joshua 010.mp3";
case 198: return "06 Joshua 011.mp3";
case 199: return "06 Joshua 012.mp3";
case 200: return "06 Joshua 013.mp3";
case 201: return "06 Joshua 014.mp3";
case 202: return "06 Joshua 015.mp3";
case 203: return "06 Joshua 016.mp3";
case 204: return "06 Joshua 017.mp3";
case 205: return "06 Joshua 018.mp3";
case 206: return "06 Joshua 019.mp3";
case 207: return "06 Joshua 020.mp3";
case 208: return "06 Joshua 021.mp3";
case 209: return "06 Joshua 022.mp3";
case 210: return "06 Joshua 023.mp3";
case 211: return "06 Joshua 024.mp3";
case 212: return "07 Judges 001.mp3";
case 213: return "07 Judges 002.mp3";
case 214: return "07 Judges 003.mp3";
case 215: return "07 Judges 004.mp3";
case 216: return "07 Judges 005.mp3";
case 217: return "07 Judges 006.mp3";
case 218: return "07 Judges 007.mp3";
case 219: return "07 Judges 008.mp3";
case 220: return "07 Judges 009.mp3";
case 221: return "07 Judges 010.mp3";
case 222: return "07 Judges 011.mp3";
case 223: return "07 Judges 012.mp3";
case 224: return "07 Judges 013.mp3";
case 225: return "07 Judges 014.mp3";
case 226: return "07 Judges 015.mp3";
case 227: return "07 Judges 016.mp3";
case 228: return "07 Judges 017.mp3";
case 229: return "07 Judges 018.mp3";
case 230: return "07 Judges 019.mp3";
case 231: return "07 Judges 020.mp3";
case 232: return "07 Judges 021.mp3";
case 233: return "08 Ruth 001.mp3";
case 234: return "08 Ruth 002.mp3";
case 235: return "08 Ruth 003.mp3";
case 236: return "08 Ruth 004.mp3";
case 237: return "09 I Samuel 001.mp3";
case 238: return "09 I Samuel 002.mp3";
case 239: return "09 I Samuel 003.mp3";
case 240: return "09 I Samuel 004.mp3";
case 241: return "09 I Samuel 005.mp3";
case 242: return "09 I Samuel 006.mp3";
case 243: return "09 I Samuel 007.mp3";
case 244: return "09 I Samuel 008.mp3";
case 245: return "09 I Samuel 009.mp3";
case 246: return "09 I Samuel 010.mp3";
case 247: return "09 I Samuel 011.mp3";
case 248: return "09 I Samuel 012.mp3";
case 249: return "09 I Samuel 013.mp3";
case 250: return "09 I Samuel 014.mp3";
case 251: return "09 I Samuel 015.mp3";
case 252: return "09 I Samuel 016.mp3";
case 253: return "09 I Samuel 017.mp3";
case 254: return "09 I Samuel 018.mp3";
case 255: return "09 I Samuel 019.mp3";
case 256: return "09 I Samuel 020.mp3";
case 257: return "09 I Samuel 021.mp3";
case 258: return "09 I Samuel 022.mp3";
case 259: return "09 I Samuel 023.mp3";
case 260: return "09 I Samuel 024.mp3";
case 261: return "09 I Samuel 025.mp3";
case 262: return "09 I Samuel 026.mp3";
case 263: return "09 I Samuel 027.mp3";
case 264: return "09 I Samuel 028.mp3";
case 265: return "09 I Samuel 029.mp3";
case 266: return "09 I Samuel 030.mp3";
case 267: return "09 I Samuel 031.mp3";
case 268: return "10 II Samuel 001.mp3";
case 269: return "10 II Samuel 002.mp3";
case 270: return "10 II Samuel 003.mp3";
case 271: return "10 II Samuel 004.mp3";
case 272: return "10 II Samuel 005.mp3";
case 273: return "10 II Samuel 006.mp3";
case 274: return "10 II Samuel 007.mp3";
case 275: return "10 II Samuel 008.mp3";
case 276: return "10 II Samuel 009.mp3";
case 277: return "10 II Samuel 010.mp3";
case 278: return "10 II Samuel 011.mp3";
case 279: return "10 II Samuel 012.mp3";
case 280: return "10 II Samuel 013.mp3";
case 281: return "10 II Samuel 014.mp3";
case 282: return "10 II Samuel 015.mp3";
case 283: return "10 II Samuel 016.mp3";
case 284: return "10 II Samuel 017.mp3";
case 285: return "10 II Samuel 018.mp3";
case 286: return "10 II Samuel 019.mp3";
case 287: return "10 II Samuel 020.mp3";
case 288: return "10 II Samuel 021.mp3";
case 289: return "10 II Samuel 022.mp3";
case 290: return "10 II Samuel 023.mp3";
case 291: return "10 II Samuel 024.mp3";
case 292: return "11 I Kings 001.mp3";
case 293: return "11 I Kings 002.mp3";
case 294: return "11 I Kings 003.mp3";
case 295: return "11 I Kings 004.mp3";
case 296: return "11 I Kings 005.mp3";
case 297: return "11 I Kings 006.mp3";
case 298: return "11 I Kings 007.mp3";
case 299: return "11 I Kings 008.mp3";
case 300: return "11 I Kings 009.mp3";
case 301: return "11 I Kings 010.mp3";
case 302: return "11 I Kings 011.mp3";
case 303: return "11 I Kings 012.mp3";
case 304: return "11 I Kings 013.mp3";
case 305: return "11 I Kings 014.mp3";
case 306: return "11 I Kings 015.mp3";
case 307: return "11 I Kings 016.mp3";
case 308: return "11 I Kings 017.mp3";
case 309: return "11 I Kings 018.mp3";
case 310: return "11 I Kings 019.mp3";
case 311: return "11 I Kings 020.mp3";
case 312: return "11 I Kings 021.mp3";
case 313: return "11 I Kings 022.mp3";
case 314: return "12 II Kings 001.mp3";
case 315: return "12 II Kings 002.mp3";
case 316: return "12 II Kings 003.mp3";
case 317: return "12 II Kings 004.mp3";
case 318: return "12 II Kings 005.mp3";
case 319: return "12 II Kings 006.mp3";
case 320: return "12 II Kings 007.mp3";
case 321: return "12 II Kings 008.mp3";
case 322: return "12 II Kings 009.mp3";
case 323: return "12 II Kings 010.mp3";
case 324: return "12 II Kings 011.mp3";
case 325: return "12 II Kings 012.mp3";
case 326: return "12 II Kings 013.mp3";
case 327: return "12 II Kings 014.mp3";
case 328: return "12 II Kings 015.mp3";
case 329: return "12 II Kings 016.mp3";
case 330: return "12 II Kings 017.mp3";
case 331: return "12 II Kings 018.mp3";
case 332: return "12 II Kings 019.mp3";
case 333: return "12 II Kings 020.mp3";
case 334: return "12 II Kings 021.mp3";
case 335: return "12 II Kings 022.mp3";
case 336: return "12 II Kings 023.mp3";
case 337: return "12 II Kings 024.mp3";
case 338: return "12 II Kings 025.mp3";
case 339: return "13 I Chronicles 001.mp3";
case 340: return "13 I Chronicles 002.mp3";
case 341: return "13 I Chronicles 003.mp3";
case 342: return "13 I Chronicles 004.mp3";
case 343: return "13 I Chronicles 005.mp3";
case 344: return "13 I Chronicles 006.mp3";
case 345: return "13 I Chronicles 007.mp3";
case 346: return "13 I Chronicles 008.mp3";
case 347: return "13 I Chronicles 009.mp3";
case 348: return "13 I Chronicles 010.mp3";
case 349: return "13 I Chronicles 011.mp3";
case 350: return "13 I Chronicles 012.mp3";
case 351: return "13 I Chronicles 013.mp3";
case 352: return "13 I Chronicles 014.mp3";
case 353: return "13 I Chronicles 015.mp3";
case 354: return "13 I Chronicles 016.mp3";
case 355: return "13 I Chronicles 017.mp3";
case 356: return "13 I Chronicles 018.mp3";
case 357: return "13 I Chronicles 019.mp3";
case 358: return "13 I Chronicles 020.mp3";
case 359: return "13 I Chronicles 021.mp3";
case 360: return "13 I Chronicles 022.mp3";
case 361: return "13 I Chronicles 023.mp3";
case 362: return "13 I Chronicles 024.mp3";
case 363: return "13 I Chronicles 025.mp3";
case 364: return "13 I Chronicles 026.mp3";
case 365: return "13 I Chronicles 027.mp3";
case 366: return "13 I Chronicles 028.mp3";
case 367: return "13 I Chronicles 029.mp3";
case 368: return "14 II Chronicles 001.mp3";
case 369: return "14 II Chronicles 002.mp3";
case 370: return "14 II Chronicles 003.mp3";
case 371: return "14 II Chronicles 004.mp3";
case 372: return "14 II Chronicles 005.mp3";
case 373: return "14 II Chronicles 006.mp3";
case 374: return "14 II Chronicles 007.mp3";
case 375: return "14 II Chronicles 008.mp3";
case 376: return "14 II Chronicles 009.mp3";
case 377: return "14 II Chronicles 010.mp3";
case 378: return "14 II Chronicles 011.mp3";
case 379: return "14 II Chronicles 012.mp3";
case 380: return "14 II Chronicles 013.mp3";
case 381: return "14 II Chronicles 014.mp3";
case 382: return "14 II Chronicles 015.mp3";
case 383: return "14 II Chronicles 016.mp3";
case 384: return "14 II Chronicles 017.mp3";
case 385: return "14 II Chronicles 018.mp3";
case 386: return "14 II Chronicles 019.mp3";
case 387: return "14 II Chronicles 020.mp3";
case 388: return "14 II Chronicles 021.mp3";
case 389: return "14 II Chronicles 022.mp3";
case 390: return "14 II Chronicles 023.mp3";
case 391: return "14 II Chronicles 024.mp3";
case 392: return "14 II Chronicles 025.mp3";
case 393: return "14 II Chronicles 026.mp3";
case 394: return "14 II Chronicles 027.mp3";
case 395: return "14 II Chronicles 028.mp3";
case 396: return "14 II Chronicles 029.mp3";
case 397: return "14 II Chronicles 030.mp3";
case 398: return "14 II Chronicles 031.mp3";
case 399: return "14 II Chronicles 032.mp3";
case 400: return "14 II Chronicles 033.mp3";
case 401: return "14 II Chronicles 034.mp3";
case 402: return "14 II Chronicles 035.mp3";
case 403: return "14 II Chronicles 036.mp3";
case 404: return "15 Ezra 001.mp3";
case 405: return "15 Ezra 002.mp3";
case 406: return "15 Ezra 003.mp3";
case 407: return "15 Ezra 004.mp3";
case 408: return "15 Ezra 005.mp3";
case 409: return "15 Ezra 006.mp3";
case 410: return "15 Ezra 007.mp3";
case 411: return "15 Ezra 008.mp3";
case 412: return "15 Ezra 009.mp3";
case 413: return "15 Ezra 010.mp3";
case 414: return "16 Nehemiah 001.mp3";
case 415: return "16 Nehemiah 002.mp3";
case 416: return "16 Nehemiah 003.mp3";
case 417: return "16 Nehemiah 004.mp3";
case 418: return "16 Nehemiah 005.mp3";
case 419: return "16 Nehemiah 006.mp3";
case 420: return "16 Nehemiah 007.mp3";
case 421: return "16 Nehemiah 008.mp3";
case 422: return "16 Nehemiah 009.mp3";
case 423: return "16 Nehemiah 010.mp3";
case 424: return "16 Nehemiah 011.mp3";
case 425: return "16 Nehemiah 012.mp3";
case 426: return "16 Nehemiah 013.mp3";
case 427: return "17 Esther 001.mp3";
case 428: return "17 Esther 002.mp3";
case 429: return "17 Esther 003.mp3";
case 430: return "17 Esther 004.mp3";
case 431: return "17 Esther 005.mp3";
case 432: return "17 Esther 006.mp3";
case 433: return "17 Esther 007.mp3";
case 434: return "17 Esther 008.mp3";
case 435: return "17 Esther 009.mp3";
case 436: return "17 Esther 010.mp3";
case 437: return "18 Job 001.mp3";
case 438: return "18 Job 002.mp3";
case 439: return "18 Job 003.mp3";
case 440: return "18 Job 004.mp3";
case 441: return "18 Job 005.mp3";
case 442: return "18 Job 006.mp3";
case 443: return "18 Job 007.mp3";
case 444: return "18 Job 008.mp3";
case 445: return "18 Job 009.mp3";
case 446: return "18 Job 010.mp3";
case 447: return "18 Job 011.mp3";
case 448: return "18 Job 012.mp3";
case 449: return "18 Job 013.mp3";
case 450: return "18 Job 014.mp3";
case 451: return "18 Job 015.mp3";
case 452: return "18 Job 016.mp3";
case 453: return "18 Job 017.mp3";
case 454: return "18 Job 018.mp3";
case 455: return "18 Job 019.mp3";
case 456: return "18 Job 020.mp3";
case 457: return "18 Job 021.mp3";
case 458: return "18 Job 022.mp3";
case 459: return "18 Job 023.mp3";
case 460: return "18 Job 024.mp3";
case 461: return "18 Job 025.mp3";
case 462: return "18 Job 026.mp3";
case 463: return "18 Job 027.mp3";
case 464: return "18 Job 028.mp3";
case 465: return "18 Job 029.mp3";
case 466: return "18 Job 030.mp3";
case 467: return "18 Job 031.mp3";
case 468: return "18 Job 032.mp3";
case 469: return "18 Job 033.mp3";
case 470: return "18 Job 034.mp3";
case 471: return "18 Job 035.mp3";
case 472: return "18 Job 036.mp3";
case 473: return "18 Job 037.mp3";
case 474: return "18 Job 038.mp3";
case 475: return "18 Job 039.mp3";
case 476: return "18 Job 040.mp3";
case 477: return "18 Job 041.mp3";
case 478: return "18 Job 042.mp3";
case 479: return "19 Psalm 001.mp3";
case 480: return "19 Psalm 002.mp3";
case 481: return "19 Psalm 003.mp3";
case 482: return "19 Psalm 004.mp3";
case 483: return "19 Psalm 005.mp3";
case 484: return "19 Psalm 006.mp3";
case 485: return "19 Psalm 007.mp3";
case 486: return "19 Psalm 008.mp3";
case 487: return "19 Psalm 009.mp3";
case 488: return "19 Psalm 010.mp3";
case 489: return "19 Psalm 011.mp3";
case 490: return "19 Psalm 012.mp3";
case 491: return "19 Psalm 013.mp3";
case 492: return "19 Psalm 014.mp3";
case 493: return "19 Psalm 015.mp3";
case 494: return "19 Psalm 016.mp3";
case 495: return "19 Psalm 017.mp3";
case 496: return "19 Psalm 018.mp3";
case 497: return "19 Psalm 019.mp3";
case 498: return "19 Psalm 020.mp3";
case 499: return "19 Psalm 021.mp3";
case 500: return "19 Psalm 022.mp3";
case 501: return "19 Psalm 023.mp3";
case 502: return "19 Psalm 024.mp3";
case 503: return "19 Psalm 025.mp3";
case 504: return "19 Psalm 026.mp3";
case 505: return "19 Psalm 027.mp3";
case 506: return "19 Psalm 028.mp3";
case 507: return "19 Psalm 029.mp3";
case 508: return "19 Psalm 030.mp3";
case 509: return "19 Psalm 031.mp3";
case 510: return "19 Psalm 032.mp3";
case 511: return "19 Psalm 033.mp3";
case 512: return "19 Psalm 034.mp3";
case 513: return "19 Psalm 035.mp3";
case 514: return "19 Psalm 036.mp3";
case 515: return "19 Psalm 037.mp3";
case 516: return "19 Psalm 038.mp3";
case 517: return "19 Psalm 039.mp3";
case 518: return "19 Psalm 040.mp3";
case 519: return "19 Psalm 041.mp3";
case 520: return "19 Psalm 042.mp3";
case 521: return "19 Psalm 043.mp3";
case 522: return "19 Psalm 044.mp3";
case 523: return "19 Psalm 045.mp3";
case 524: return "19 Psalm 046.mp3";
case 525: return "19 Psalm 047.mp3";
case 526: return "19 Psalm 048.mp3";
case 527: return "19 Psalm 049.mp3";
case 528: return "19 Psalm 050.mp3";
case 529: return "19 Psalm 051.mp3";
case 530: return "19 Psalm 052.mp3";
case 531: return "19 Psalm 053.mp3";
case 532: return "19 Psalm 054.mp3";
case 533: return "19 Psalm 055.mp3";
case 534: return "19 Psalm 056.mp3";
case 535: return "19 Psalm 057.mp3";
case 536: return "19 Psalm 058.mp3";
case 537: return "19 Psalm 059.mp3";
case 538: return "19 Psalm 060.mp3";
case 539: return "19 Psalm 061.mp3";
case 540: return "19 Psalm 062.mp3";
case 541: return "19 Psalm 063.mp3";
case 542: return "19 Psalm 064.mp3";
case 543: return "19 Psalm 065.mp3";
case 544: return "19 Psalm 066.mp3";
case 545: return "19 Psalm 067.mp3";
case 546: return "19 Psalm 068.mp3";
case 547: return "19 Psalm 069.mp3";
case 548: return "19 Psalm 070.mp3";
case 549: return "19 Psalm 071.mp3";
case 550: return "19 Psalm 072.mp3";
case 551: return "19 Psalm 073.mp3";
case 552: return "19 Psalm 074.mp3";
case 553: return "19 Psalm 075.mp3";
case 554: return "19 Psalm 076.mp3";
case 555: return "19 Psalm 077.mp3";
case 556: return "19 Psalm 078.mp3";
case 557: return "19 Psalm 079.mp3";
case 558: return "19 Psalm 080.mp3";
case 559: return "19 Psalm 081.mp3";
case 560: return "19 Psalm 082.mp3";
case 561: return "19 Psalm 083.mp3";
case 562: return "19 Psalm 084.mp3";
case 563: return "19 Psalm 085.mp3";
case 564: return "19 Psalm 086.mp3";
case 565: return "19 Psalm 087.mp3";
case 566: return "19 Psalm 088.mp3";
case 567: return "19 Psalm 089.mp3";
case 568: return "19 Psalm 090.mp3";
case 569: return "19 Psalm 091.mp3";
case 570: return "19 Psalm 092.mp3";
case 571: return "19 Psalm 093.mp3";
case 572: return "19 Psalm 094.mp3";
case 573: return "19 Psalm 095.mp3";
case 574: return "19 Psalm 096.mp3";
case 575: return "19 Psalm 097.mp3";
case 576: return "19 Psalm 098.mp3";
case 577: return "19 Psalm 099.mp3";
case 578: return "19 Psalm 100.mp3";
case 579: return "19 Psalm 101.mp3";
case 580: return "19 Psalm 102.mp3";
case 581: return "19 Psalm 103.mp3";
case 582: return "19 Psalm 104.mp3";
case 583: return "19 Psalm 105.mp3";
case 584: return "19 Psalm 106.mp3";
case 585: return "19 Psalm 107.mp3";
case 586: return "19 Psalm 108.mp3";
case 587: return "19 Psalm 109.mp3";
case 588: return "19 Psalm 110.mp3";
case 589: return "19 Psalm 111.mp3";
case 590: return "19 Psalm 112.mp3";
case 591: return "19 Psalm 113.mp3";
case 592: return "19 Psalm 114.mp3";
case 593: return "19 Psalm 115.mp3";
case 594: return "19 Psalm 116.mp3";
case 595: return "19 Psalm 117.mp3";
case 596: return "19 Psalm 118.mp3";
case 597: return "19 Psalm 119.mp3";
case 598: return "19 Psalm 120.mp3";
case 599: return "19 Psalm 121.mp3";
case 600: return "19 Psalm 122.mp3";
case 601: return "19 Psalm 123.mp3";
case 602: return "19 Psalm 124.mp3";
case 603: return "19 Psalm 125.mp3";
case 604: return "19 Psalm 126.mp3";
case 605: return "19 Psalm 127.mp3";
case 606: return "19 Psalm 128.mp3";
case 607: return "19 Psalm 129.mp3";
case 608: return "19 Psalm 130.mp3";
case 609: return "19 Psalm 131.mp3";
case 610: return "19 Psalm 132.mp3";
case 611: return "19 Psalm 133.mp3";
case 612: return "19 Psalm 134.mp3";
case 613: return "19 Psalm 135.mp3";
case 614: return "19 Psalm 136.mp3";
case 615: return "19 Psalm 137.mp3";
case 616: return "19 Psalm 138.mp3";
case 617: return "19 Psalm 139.mp3";
case 618: return "19 Psalm 140.mp3";
case 619: return "19 Psalm 141.mp3";
case 620: return "19 Psalm 142.mp3";
case 621: return "19 Psalm 143.mp3";
case 622: return "19 Psalm 144.mp3";
case 623: return "19 Psalm 145.mp3";
case 624: return "19 Psalm 146.mp3";
case 625: return "19 Psalm 147.mp3";
case 626: return "19 Psalm 148.mp3";
case 627: return "19 Psalm 149.mp3";
case 628: return "19 Psalm 150.mp3";
case 629: return "20 Proverbs 001.mp3";
case 630: return "20 Proverbs 002.mp3";
case 631: return "20 Proverbs 003.mp3";
case 632: return "20 Proverbs 004.mp3";
case 633: return "20 Proverbs 005.mp3";
case 634: return "20 Proverbs 006.mp3";
case 635: return "20 Proverbs 007.mp3";
case 636: return "20 Proverbs 008.mp3";
case 637: return "20 Proverbs 009.mp3";
case 638: return "20 Proverbs 010.mp3";
case 639: return "20 Proverbs 011.mp3";
case 640: return "20 Proverbs 012.mp3";
case 641: return "20 Proverbs 013.mp3";
case 642: return "20 Proverbs 014.mp3";
case 643: return "20 Proverbs 015.mp3";
case 644: return "20 Proverbs 016.mp3";
case 645: return "20 Proverbs 017.mp3";
case 646: return "20 Proverbs 018.mp3";
case 647: return "20 Proverbs 019.mp3";
case 648: return "20 Proverbs 020.mp3";
case 649: return "20 Proverbs 021.mp3";
case 650: return "20 Proverbs 022.mp3";
case 651: return "20 Proverbs 023.mp3";
case 652: return "20 Proverbs 024.mp3";
case 653: return "20 Proverbs 025.mp3";
case 654: return "20 Proverbs 026.mp3";
case 655: return "20 Proverbs 027.mp3";
case 656: return "20 Proverbs 028.mp3";
case 657: return "20 Proverbs 029.mp3";
case 658: return "20 Proverbs 030.mp3";
case 659: return "20 Proverbs 031.mp3";
case 660: return "21 Ecclesiastes 001.mp3";
case 661: return "21 Ecclesiastes 002.mp3";
case 662: return "21 Ecclesiastes 003.mp3";
case 663: return "21 Ecclesiastes 004.mp3";
case 664: return "21 Ecclesiastes 005.mp3";
case 665: return "21 Ecclesiastes 006.mp3";
case 666: return "21 Ecclesiastes 007.mp3";
case 667: return "21 Ecclesiastes 008.mp3";
case 668: return "21 Ecclesiastes 009.mp3";
case 669: return "21 Ecclesiastes 010.mp3";
case 670: return "21 Ecclesiastes 011.mp3";
case 671: return "21 Ecclesiastes 012.mp3";
case 672: return "22 Solomon 001.mp3";
case 673: return "22 Solomon 002.mp3";
case 674: return "22 Solomon 003.mp3";
case 675: return "22 Solomon 004.mp3";
case 676: return "22 Solomon 005.mp3";
case 677: return "22 Solomon 006.mp3";
case 678: return "22 Solomon 007.mp3";
case 679: return "22 Solomon 008.mp3";
case 680: return "23 Isaiah 001.mp3";
case 681: return "23 Isaiah 002.mp3";
case 682: return "23 Isaiah 003.mp3";
case 683: return "23 Isaiah 004.mp3";
case 684: return "23 Isaiah 005.mp3";
case 685: return "23 Isaiah 006.mp3";
case 686: return "23 Isaiah 007.mp3";
case 687: return "23 Isaiah 008.mp3";
case 688: return "23 Isaiah 009.mp3";
case 689: return "23 Isaiah 010.mp3";
case 690: return "23 Isaiah 011.mp3";
case 691: return "23 Isaiah 012.mp3";
case 692: return "23 Isaiah 013.mp3";
case 693: return "23 Isaiah 014.mp3";
case 694: return "23 Isaiah 015.mp3";
case 695: return "23 Isaiah 016.mp3";
case 696: return "23 Isaiah 017.mp3";
case 697: return "23 Isaiah 018.mp3";
case 698: return "23 Isaiah 019.mp3";
case 699: return "23 Isaiah 020.mp3";
case 700: return "23 Isaiah 021.mp3";
case 701: return "23 Isaiah 022.mp3";
case 702: return "23 Isaiah 023.mp3";
case 703: return "23 Isaiah 024.mp3";
case 704: return "23 Isaiah 025.mp3";
case 705: return "23 Isaiah 026.mp3";
case 706: return "23 Isaiah 027.mp3";
case 707: return "23 Isaiah 028.mp3";
case 708: return "23 Isaiah 029.mp3";
case 709: return "23 Isaiah 030.mp3";
case 710: return "23 Isaiah 031.mp3";
case 711: return "23 Isaiah 032.mp3";
case 712: return "23 Isaiah 033.mp3";
case 713: return "23 Isaiah 034.mp3";
case 714: return "23 Isaiah 035.mp3";
case 715: return "23 Isaiah 036.mp3";
case 716: return "23 Isaiah 037.mp3";
case 717: return "23 Isaiah 038.mp3";
case 718: return "23 Isaiah 039.mp3";
case 719: return "23 Isaiah 040.mp3";
case 720: return "23 Isaiah 041.mp3";
case 721: return "23 Isaiah 042.mp3";
case 722: return "23 Isaiah 043.mp3";
case 723: return "23 Isaiah 044.mp3";
case 724: return "23 Isaiah 045.mp3";
case 725: return "23 Isaiah 046.mp3";
case 726: return "23 Isaiah 047.mp3";
case 727: return "23 Isaiah 048.mp3";
case 728: return "23 Isaiah 049.mp3";
case 729: return "23 Isaiah 050.mp3";
case 730: return "23 Isaiah 051.mp3";
case 731: return "23 Isaiah 052.mp3";
case 732: return "23 Isaiah 053.mp3";
case 733: return "23 Isaiah 054.mp3";
case 734: return "23 Isaiah 055.mp3";
case 735: return "23 Isaiah 056.mp3";
case 736: return "23 Isaiah 057.mp3";
case 737: return "23 Isaiah 058.mp3";
case 738: return "23 Isaiah 059.mp3";
case 739: return "23 Isaiah 060.mp3";
case 740: return "23 Isaiah 061.mp3";
case 741: return "23 Isaiah 062.mp3";
case 742: return "23 Isaiah 063.mp3";
case 743: return "23 Isaiah 064.mp3";
case 744: return "23 Isaiah 065.mp3";
case 745: return "23 Isaiah 066.mp3";
case 746: return "24 Jeremiah 001.mp3";
case 747: return "24 Jeremiah 002.mp3";
case 748: return "24 Jeremiah 003.mp3";
case 749: return "24 Jeremiah 004.mp3";
case 750: return "24 Jeremiah 005.mp3";
case 751: return "24 Jeremiah 006.mp3";
case 752: return "24 Jeremiah 007.mp3";
case 753: return "24 Jeremiah 008.mp3";
case 754: return "24 Jeremiah 009.mp3";
case 755: return "24 Jeremiah 010.mp3";
case 756: return "24 Jeremiah 011.mp3";
case 757: return "24 Jeremiah 012.mp3";
case 758: return "24 Jeremiah 013.mp3";
case 759: return "24 Jeremiah 014.mp3";
case 760: return "24 Jeremiah 015.mp3";
case 761: return "24 Jeremiah 016.mp3";
case 762: return "24 Jeremiah 017.mp3";
case 763: return "24 Jeremiah 018.mp3";
case 764: return "24 Jeremiah 019.mp3";
case 765: return "24 Jeremiah 020.mp3";
case 766: return "24 Jeremiah 021.mp3";
case 767: return "24 Jeremiah 022.mp3";
case 768: return "24 Jeremiah 023.mp3";
case 769: return "24 Jeremiah 024.mp3";
case 770: return "24 Jeremiah 025.mp3";
case 771: return "24 Jeremiah 026.mp3";
case 772: return "24 Jeremiah 027.mp3";
case 773: return "24 Jeremiah 028.mp3";
case 774: return "24 Jeremiah 029.mp3";
case 775: return "24 Jeremiah 030.mp3";
case 776: return "24 Jeremiah 031.mp3";
case 777: return "24 Jeremiah 032.mp3";
case 778: return "24 Jeremiah 033.mp3";
case 779: return "24 Jeremiah 034.mp3";
case 780: return "24 Jeremiah 035.mp3";
case 781: return "24 Jeremiah 036.mp3";
case 782: return "24 Jeremiah 037.mp3";
case 783: return "24 Jeremiah 038.mp3";
case 784: return "24 Jeremiah 039.mp3";
case 785: return "24 Jeremiah 040.mp3";
case 786: return "24 Jeremiah 041.mp3";
case 787: return "24 Jeremiah 042.mp3";
case 788: return "24 Jeremiah 043.mp3";
case 789: return "24 Jeremiah 044.mp3";
case 790: return "24 Jeremiah 045.mp3";
case 791: return "24 Jeremiah 046.mp3";
case 792: return "24 Jeremiah 047.mp3";
case 793: return "24 Jeremiah 048.mp3";
case 794: return "24 Jeremiah 049.mp3";
case 795: return "24 Jeremiah 050.mp3";
case 796: return "24 Jeremiah 051.mp3";
case 797: return "24 Jeremiah 052.mp3";
case 798: return "25 Lamentations 001.mp3";
case 799: return "25 Lamentations 002.mp3";
case 800: return "25 Lamentations 003.mp3";
case 801: return "25 Lamentations 004.mp3";
case 802: return "25 Lamentations 005.mp3";
case 803: return "26 Ezekiel 001.mp3";
case 804: return "26 Ezekiel 002.mp3";
case 805: return "26 Ezekiel 003.mp3";
case 806: return "26 Ezekiel 004.mp3";
case 807: return "26 Ezekiel 005.mp3";
case 808: return "26 Ezekiel 006.mp3";
case 809: return "26 Ezekiel 007.mp3";
case 810: return "26 Ezekiel 008.mp3";
case 811: return "26 Ezekiel 009.mp3";
case 812: return "26 Ezekiel 010.mp3";
case 813: return "26 Ezekiel 011.mp3";
case 814: return "26 Ezekiel 012.mp3";
case 815: return "26 Ezekiel 013.mp3";
case 816: return "26 Ezekiel 014.mp3";
case 817: return "26 Ezekiel 015.mp3";
case 818: return "26 Ezekiel 016.mp3";
case 819: return "26 Ezekiel 017.mp3";
case 820: return "26 Ezekiel 018.mp3";
case 821: return "26 Ezekiel 019.mp3";
case 822: return "26 Ezekiel 020.mp3";
case 823: return "26 Ezekiel 021.mp3";
case 824: return "26 Ezekiel 022.mp3";
case 825: return "26 Ezekiel 023.mp3";
case 826: return "26 Ezekiel 024.mp3";
case 827: return "26 Ezekiel 025.mp3";
case 828: return "26 Ezekiel 026.mp3";
case 829: return "26 Ezekiel 027.mp3";
case 830: return "26 Ezekiel 028.mp3";
case 831: return "26 Ezekiel 029.mp3";
case 832: return "26 Ezekiel 030.mp3";
case 833: return "26 Ezekiel 031.mp3";
case 834: return "26 Ezekiel 032.mp3";
case 835: return "26 Ezekiel 033.mp3";
case 836: return "26 Ezekiel 034.mp3";
case 837: return "26 Ezekiel 035.mp3";
case 838: return "26 Ezekiel 036.mp3";
case 839: return "26 Ezekiel 037.mp3";
case 840: return "26 Ezekiel 038.mp3";
case 841: return "26 Ezekiel 039.mp3";
case 842: return "26 Ezekiel 040.mp3";
case 843: return "26 Ezekiel 041.mp3";
case 844: return "26 Ezekiel 042.mp3";
case 845: return "26 Ezekiel 043.mp3";
case 846: return "26 Ezekiel 044.mp3";
case 847: return "26 Ezekiel 045.mp3";
case 848: return "26 Ezekiel 046.mp3";
case 849: return "26 Ezekiel 047.mp3";
case 850: return "26 Ezekiel 048.mp3";
case 851: return "27 Daniel 001.mp3";
case 852: return "27 Daniel 002.mp3";
case 853: return "27 Daniel 003.mp3";
case 854: return "27 Daniel 004.mp3";
case 855: return "27 Daniel 005.mp3";
case 856: return "27 Daniel 006.mp3";
case 857: return "27 Daniel 007.mp3";
case 858: return "27 Daniel 008.mp3";
case 859: return "27 Daniel 009.mp3";
case 860: return "27 Daniel 010.mp3";
case 861: return "27 Daniel 011.mp3";
case 862: return "27 Daniel 012.mp3";
case 863: return "28 Hosea 001.mp3";
case 864: return "28 Hosea 002.mp3";
case 865: return "28 Hosea 003.mp3";
case 866: return "28 Hosea 004.mp3";
case 867: return "28 Hosea 005.mp3";
case 868: return "28 Hosea 006.mp3";
case 869: return "28 Hosea 007.mp3";
case 870: return "28 Hosea 008.mp3";
case 871: return "28 Hosea 009.mp3";
case 872: return "28 Hosea 010.mp3";
case 873: return "28 Hosea 011.mp3";
case 874: return "28 Hosea 012.mp3";
case 875: return "28 Hosea 013.mp3";
case 876: return "28 Hosea 014.mp3";
case 877: return "29 Joel 001.mp3";
case 878: return "29 Joel 002.mp3";
case 879: return "29 Joel 003.mp3";
case 880: return "30 Amos 001.mp3";
case 881: return "30 Amos 002.mp3";
case 882: return "30 Amos 003.mp3";
case 883: return "30 Amos 004.mp3";
case 884: return "30 Amos 005.mp3";
case 885: return "30 Amos 006.mp3";
case 886: return "30 Amos 007.mp3";
case 887: return "30 Amos 008.mp3";
case 888: return "30 Amos 009.mp3";
case 889: return "31 Obadiah 001.mp3";
case 890: return "32 Jonah 001.mp3";
case 891: return "32 Jonah 002.mp3";
case 892: return "32 Jonah 003.mp3";
case 893: return "32 Jonah 004.mp3";
case 894: return "33 Micah 001.mp3";
case 895: return "33 Micah 002.mp3";
case 896: return "33 Micah 003.mp3";
case 897: return "33 Micah 004.mp3";
case 898: return "33 Micah 005.mp3";
case 899: return "33 Micah 006.mp3";
case 900: return "33 Micah 007.mp3";
case 901: return "34 Nahum 001.mp3";
case 902: return "34 Nahum 002.mp3";
case 903: return "34 Nahum 003.mp3";
case 904: return "35 Habakkuk 001.mp3";
case 905: return "35 Habakkuk 002.mp3";
case 906: return "35 Habakkuk 003.mp3";
case 907: return "36 Zephaniah 001.mp3";
case 908: return "36 Zephaniah 002.mp3";
case 909: return "36 Zephaniah 003.mp3";
case 910: return "37 Haggai 001.mp3";
case 911: return "37 Haggai 002.mp3";
case 912: return "38 Zechariah 001.mp3";
case 913: return "38 Zechariah 002.mp3";
case 914: return "38 Zechariah 003.mp3";
case 915: return "38 Zechariah 004.mp3";
case 916: return "38 Zechariah 005.mp3";
case 917: return "38 Zechariah 006.mp3";
case 918: return "38 Zechariah 007.mp3";
case 919: return "38 Zechariah 008.mp3";
case 920: return "38 Zechariah 009.mp3";
case 921: return "38 Zechariah 010.mp3";
case 922: return "38 Zechariah 011.mp3";
case 923: return "38 Zechariah 012.mp3";
case 924: return "38 Zechariah 013.mp3";
case 925: return "38 Zechariah 014.mp3";
case 926: return "39 Malachi 001.mp3";
case 927: return "39 Malachi 002.mp3";
case 928: return "39 Malachi 003.mp3";
case 929: return "39 Malachi 004.mp3";
case 930: return "40 Matthew 001.mp3";
case 931: return "40 Matthew 002.mp3";
case 932: return "40 Matthew 003.mp3";
case 933: return "40 Matthew 004.mp3";
case 934: return "40 Matthew 005.mp3";
case 935: return "40 Matthew 006.mp3";
case 936: return "40 Matthew 007.mp3";
case 937: return "40 Matthew 008.mp3";
case 938: return "40 Matthew 009.mp3";
case 939: return "40 Matthew 010.mp3";
case 940: return "40 Matthew 011.mp3";
case 941: return "40 Matthew 012.mp3";
case 942: return "40 Matthew 013.mp3";
case 943: return "40 Matthew 014.mp3";
case 944: return "40 Matthew 015.mp3";
case 945: return "40 Matthew 016.mp3";
case 946: return "40 Matthew 017.mp3";
case 947: return "40 Matthew 018.mp3";
case 948: return "40 Matthew 019.mp3";
case 949: return "40 Matthew 020.mp3";
case 950: return "40 Matthew 021.mp3";
case 951: return "40 Matthew 022.mp3";
case 952: return "40 Matthew 023.mp3";
case 953: return "40 Matthew 024.mp3";
case 954: return "40 Matthew 025.mp3";
case 955: return "40 Matthew 026.mp3";
case 956: return "40 Matthew 027.mp3";
case 957: return "40 Matthew 028.mp3";
case 958: return "41 Mark 001.mp3";
case 959: return "41 Mark 002.mp3";
case 960: return "41 Mark 003.mp3";
case 961: return "41 Mark 004.mp3";
case 962: return "41 Mark 005.mp3";
case 963: return "41 Mark 006.mp3";
case 964: return "41 Mark 007.mp3";
case 965: return "41 Mark 008.mp3";
case 966: return "41 Mark 009.mp3";
case 967: return "41 Mark 010.mp3";
case 968: return "41 Mark 011.mp3";
case 969: return "41 Mark 012.mp3";
case 970: return "41 Mark 013.mp3";
case 971: return "41 Mark 014.mp3";
case 972: return "41 Mark 015.mp3";
case 973: return "41 Mark 016.mp3";
case 974: return "42 Luke 001.mp3";
case 975: return "42 Luke 002.mp3";
case 976: return "42 Luke 003.mp3";
case 977: return "42 Luke 004.mp3";
case 978: return "42 Luke 005.mp3";
case 979: return "42 Luke 006.mp3";
case 980: return "42 Luke 007.mp3";
case 981: return "42 Luke 008.mp3";
case 982: return "42 Luke 009.mp3";
case 983: return "42 Luke 010.mp3";
case 984: return "42 Luke 011.mp3";
case 985: return "42 Luke 012.mp3";
case 986: return "42 Luke 013.mp3";
case 987: return "42 Luke 014.mp3";
case 988: return "42 Luke 015.mp3";
case 989: return "42 Luke 016.mp3";
case 990: return "42 Luke 017.mp3";
case 991: return "42 Luke 018.mp3";
case 992: return "42 Luke 019.mp3";
case 993: return "42 Luke 020.mp3";
case 994: return "42 Luke 021.mp3";
case 995: return "42 Luke 022.mp3";
case 996: return "42 Luke 023.mp3";
case 997: return "42 Luke 024.mp3";
case 998: return "43 John 001.mp3";
case 999: return "43 John 002.mp3";
case 1000: return "43 John 003.mp3";
case 1001: return "43 John 004.mp3";
case 1002: return "43 John 005.mp3";
case 1003: return "43 John 006.mp3";
case 1004: return "43 John 007.mp3";
case 1005: return "43 John 008.mp3";
case 1006: return "43 John 009.mp3";
case 1007: return "43 John 010.mp3";
case 1008: return "43 John 011.mp3";
case 1009: return "43 John 012.mp3";
case 1010: return "43 John 013.mp3";
case 1011: return "43 John 014.mp3";
case 1012: return "43 John 015.mp3";
case 1013: return "43 John 016.mp3";
case 1014: return "43 John 017.mp3";
case 1015: return "43 John 018.mp3";
case 1016: return "43 John 019.mp3";
case 1017: return "43 John 020.mp3";
case 1018: return "43 John 021.mp3";
case 1019: return "44 Acts 001.mp3";
case 1020: return "44 Acts 002.mp3";
case 1021: return "44 Acts 003.mp3";
case 1022: return "44 Acts 004.mp3";
case 1023: return "44 Acts 005.mp3";
case 1024: return "44 Acts 006.mp3";
case 1025: return "44 Acts 007.mp3";
case 1026: return "44 Acts 008.mp3";
case 1027: return "44 Acts 009.mp3";
case 1028: return "44 Acts 010.mp3";
case 1029: return "44 Acts 011.mp3";
case 1030: return "44 Acts 012.mp3";
case 1031: return "44 Acts 013.mp3";
case 1032: return "44 Acts 014.mp3";
case 1033: return "44 Acts 015.mp3";
case 1034: return "44 Acts 016.mp3";
case 1035: return "44 Acts 017.mp3";
case 1036: return "44 Acts 018.mp3";
case 1037: return "44 Acts 019.mp3";
case 1038: return "44 Acts 020.mp3";
case 1039: return "44 Acts 021.mp3";
case 1040: return "44 Acts 022.mp3";
case 1041: return "44 Acts 023.mp3";
case 1042: return "44 Acts 024.mp3";
case 1043: return "44 Acts 025.mp3";
case 1044: return "44 Acts 026.mp3";
case 1045: return "44 Acts 027.mp3";
case 1046: return "44 Acts 028.mp3";
case 1047: return "45 Romans 001.mp3";
case 1048: return "45 Romans 002.mp3";
case 1049: return "45 Romans 003.mp3";
case 1050: return "45 Romans 004.mp3";
case 1051: return "45 Romans 005.mp3";
case 1052: return "45 Romans 006.mp3";
case 1053: return "45 Romans 007.mp3";
case 1054: return "45 Romans 008.mp3";
case 1055: return "45 Romans 009.mp3";
case 1056: return "45 Romans 010.mp3";
case 1057: return "45 Romans 011.mp3";
case 1058: return "45 Romans 012.mp3";
case 1059: return "45 Romans 013.mp3";
case 1060: return "45 Romans 014.mp3";
case 1061: return "45 Romans 015.mp3";
case 1062: return "45 Romans 016.mp3";
case 1063: return "46 I Corinthians 001.mp3";
case 1064: return "46 I Corinthians 002.mp3";
case 1065: return "46 I Corinthians 003.mp3";
case 1066: return "46 I Corinthians 004.mp3";
case 1067: return "46 I Corinthians 005.mp3";
case 1068: return "46 I Corinthians 006.mp3";
case 1069: return "46 I Corinthians 007.mp3";
case 1070: return "46 I Corinthians 008.mp3";
case 1071: return "46 I Corinthians 009.mp3";
case 1072: return "46 I Corinthians 010.mp3";
case 1073: return "46 I Corinthians 011.mp3";
case 1074: return "46 I Corinthians 012.mp3";
case 1075: return "46 I Corinthians 013.mp3";
case 1076: return "46 I Corinthians 014.mp3";
case 1077: return "46 I Corinthians 015.mp3";
case 1078: return "46 I Corinthians 016.mp3";
case 1079: return "47 II Corinthians 001.mp3";
case 1080: return "47 II Corinthians 002.mp3";
case 1081: return "47 II Corinthians 003.mp3";
case 1082: return "47 II Corinthians 004.mp3";
case 1083: return "47 II Corinthians 005.mp3";
case 1084: return "47 II Corinthians 006.mp3";
case 1085: return "47 II Corinthians 007.mp3";
case 1086: return "47 II Corinthians 008.mp3";
case 1087: return "47 II Corinthians 009.mp3";
case 1088: return "47 II Corinthians 010.mp3";
case 1089: return "47 II Corinthians 011.mp3";
case 1090: return "47 II Corinthians 012.mp3";
case 1091: return "47 II Corinthians 013.mp3";
case 1092: return "48 Galatians 001.mp3";
case 1093: return "48 Galatians 002.mp3";
case 1094: return "48 Galatians 003.mp3";
case 1095: return "48 Galatians 004.mp3";
case 1096: return "48 Galatians 005.mp3";
case 1097: return "48 Galatians 006.mp3";
case 1098: return "49 Ephesians 001.mp3";
case 1099: return "49 Ephesians 002.mp3";
case 1100: return "49 Ephesians 003.mp3";
case 1101: return "49 Ephesians 004.mp3";
case 1102: return "49 Ephesians 005.mp3";
case 1103: return "49 Ephesians 006.mp3";
case 1104: return "50 Philippians 001.mp3";
case 1105: return "50 Philippians 002.mp3";
case 1106: return "50 Philippians 003.mp3";
case 1107: return "50 Philippians 004.mp3";
case 1108: return "51 Colossians 001.mp3";
case 1109: return "51 Colossians 002.mp3";
case 1110: return "51 Colossians 003.mp3";
case 1111: return "51 Colossians 004.mp3";
case 1112: return "52 I Thessalonians 001.mp3";
case 1113: return "52 I Thessalonians 002.mp3";
case 1114: return "52 I Thessalonians 003.mp3";
case 1115: return "52 I Thessalonians 004.mp3";
case 1116: return "52 I Thessalonians 005.mp3";
case 1117: return "53 II Thessalonians 001.mp3";
case 1118: return "53 II Thessalonians 002.mp3";
case 1119: return "53 II Thessalonians 003.mp3";
case 1120: return "54 I Timothy 001.mp3";
case 1121: return "54 I Timothy 002.mp3";
case 1122: return "54 I Timothy 003.mp3";
case 1123: return "54 I Timothy 004.mp3";
case 1124: return "54 I Timothy 005.mp3";
case 1125: return "54 I Timothy 006.mp3";
case 1126: return "55 II Timothy 001.mp3";
case 1127: return "55 II Timothy 002.mp3";
case 1128: return "55 II Timothy 003.mp3";
case 1129: return "55 II Timothy 004.mp3";
case 1130: return "56 Titus 001.mp3";
case 1131: return "56 Titus 002.mp3";
case 1132: return "56 Titus 003.mp3";
case 1133: return "57 Philemon 001.mp3";
case 1134: return "58 Hebrews 001.mp3";
case 1135: return "58 Hebrews 002.mp3";
case 1136: return "58 Hebrews 003.mp3";
case 1137: return "58 Hebrews 004.mp3";
case 1138: return "58 Hebrews 005.mp3";
case 1139: return "58 Hebrews 006.mp3";
case 1140: return "58 Hebrews 007.mp3";
case 1141: return "58 Hebrews 008.mp3";
case 1142: return "58 Hebrews 009.mp3";
case 1143: return "58 Hebrews 010.mp3";
case 1144: return "58 Hebrews 011.mp3";
case 1145: return "58 Hebrews 012.mp3";
case 1146: return "58 Hebrews 013.mp3";
case 1147: return "59 James 001.mp3";
case 1148: return "59 James 002.mp3";
case 1149: return "59 James 003.mp3";
case 1150: return "59 James 004.mp3";
case 1151: return "59 James 005.mp3";
case 1152: return "60 I Peter 001.mp3";
case 1153: return "60 I Peter 002.mp3";
case 1154: return "60 I Peter 003.mp3";
case 1155: return "60 I Peter 004.mp3";
case 1156: return "60 I Peter 005.mp3";
case 1157: return "61 II Peter 001.mp3";
case 1158: return "61 II Peter 002.mp3";
case 1159: return "61 II Peter 003.mp3";
case 1160: return "62 I John 001.mp3";
case 1161: return "62 I John 002.mp3";
case 1162: return "62 I John 003.mp3";
case 1163: return "62 I John 004.mp3";
case 1164: return "62 I John 005.mp3";
case 1165: return "63 II John 001.mp3";
case 1166: return "64 III John 001.mp3";
case 1167: return "65 Jude 001.mp3";
case 1168: return "66 Revelation 001.mp3";
case 1169: return "66 Revelation 002.mp3";
case 1170: return "66 Revelation 003.mp3";
case 1171: return "66 Revelation 004.mp3";
case 1172: return "66 Revelation 005.mp3";
case 1173: return "66 Revelation 006.mp3";
case 1174: return "66 Revelation 007.mp3";
case 1175: return "66 Revelation 008.mp3";
case 1176: return "66 Revelation 009.mp3";
case 1177: return "66 Revelation 010.mp3";
case 1178: return "66 Revelation 011.mp3";
case 1179: return "66 Revelation 012.mp3";
case 1180: return "66 Revelation 013.mp3";
case 1181: return "66 Revelation 014.mp3";
case 1182: return "66 Revelation 015.mp3";
case 1183: return "66 Revelation 016.mp3";
case 1184: return "66 Revelation 017.mp3";
case 1185: return "66 Revelation 018.mp3";
case 1186: return "66 Revelation 019.mp3";
case 1187: return "66 Revelation 020.mp3";
case 1188: return "66 Revelation 021.mp3";
case 1189: return "66 Revelation 022.mp3";
case 1190: return "19 Psalm 119.mp3";
case 1191: return "19 Psalm 119.mp3";
case 1192: return "19 Psalm 119.mp3";
case 1193: return "19 Psalm 119.mp3";
default: return "";
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dream
*/
public abstract class MovablePiece extends GamePiece
{
public abstract int[] calcNewPos(int direction);
public abstract void moveToNewPos(int newRow, int newCol);
}
|
package walke.base;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import walke.base.tool.LogUtil;
import walke.base.tool.PermissionUtil;
import walke.base.tool.ToastUtil;
/**
* Created by Walke.Z on 2017/4/21.
* 这是底层(第一层)封装
*
*/
public class BaseActivity extends AppCompatActivity {
public BaseApp getBaseApp() {
return (BaseApp) getApplication();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//沉浸式状态栏
//StatusBarCompat.compat(this, Color.RED);
//hideVirtualButtons();
initState();
}
/**调用该方法后,虚拟案件就会被隐藏 从屏幕底部向上拉,可以再次显示
* 与布局xml文件 以下两个属性连用[而6.0异常]
* android:clipToPadding="true"
* android:fitsSystemWindows="true"
* 沉浸式导航栏(虚拟按键栏)会导致上下边界异常
*/
@SuppressLint("NewApi")
private void hideVirtualButtons() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE);
}
}
/**
* 在需要实现沉浸式状态栏的Activity的布局中添加以下参数
* android:fitsSystemWindows="true"
* android:clipToPadding="true"
*/
private void initState() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 只沉浸式状态栏,与布局xml文件 以下两个属性连用[而6.0也正常]
// android:clipToPadding="true"
// android:fitsSystemWindows="true"
//透明导航栏
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
/**
* @param editText 获取焦点
*/
public void editTextGetFocus(EditText editText) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
/*boolean isOpen=imm.isActive();//isOpen若返回true,则表示输入法打开
if (!isOpen) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}*/
//imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
public String replaceEmptyText(String emptyText,String tagText){
if (TextUtils.isEmpty(emptyText))
return tagText;
else
return emptyText;
}
/**
* @param editText 进入界面后,输入框获取焦点
* 需要延迟
*/
public void enterGetFocus(final EditText editText) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
editTextGetFocus(editText);
}
}, 200);
}
/** 初始化检查权限
* @param permissions
* @param requestCode
*/
protected void initPermission(String[] permissions, int requestCode) {
if (Build.VERSION.SDK_INT >= 23) {
if (PermissionUtil.checkPermissionSetLack(this, permissions)){
requestPermissions(permissions,requestCode);
}
}
}
public void showRequestPermissionDialog() {
/* DialogUtil.createTwoButtonDialog(this, "兑奖使用帮助","需允许摄像头进行扫一扫:", "取消", "设置", "", new DialogUtil.DialogTwoButtonClickListener() {
@Override
public void leftOnClick(WindowManager.LayoutParams lp, Dialog dialog) {
}
@Override
public void rightOnClick(WindowManager.LayoutParams lp, Dialog dialog) {
dialog.dismiss();
openSystemSetting();
}
});*/
}
/**
* 打开系统设置界面
*/
public void openSystemSetting() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
/**
* 清除应用的task栈,如果程序正常运行这会导致应用退回到桌面
*/
public final void exit() {
/** 进程会被kill掉 http://blog.csdn.net/chonbj/article/details/10182369 */
int currentVersion = android.os.Build.VERSION.SDK_INT;
if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
System.exit(0);
} else {// android2.1
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage(getPackageName());
}
//进程没被kill掉 使用finlish activity不一定会被gc回收掉
/*for (Iterator<Map.Entry<String, SoftReference<Activity>>> iterator = this.taskMap.entrySet().iterator(); iterator.hasNext(); ) {
SoftReference<Activity> activityReference = iterator.next().getValue();
Activity activity = activityReference.get();
if (activity != null) {
activity.finish();
}
}
this.taskMap.clear();*/
return;
}
protected void toast(String message){
if (!TextUtils.isEmpty(message))
ToastUtil.showToast(this,message);
}
protected void middleToast(String message){
if (!TextUtils.isEmpty(message))
ToastUtil.showMidlleToast(this,message);
}
protected void toastTime(String message,int time){
if (!TextUtils.isEmpty(message))
ToastUtil.showToastWithTime(this,message,time);
}
protected void logI(String message){
if (!TextUtils.isEmpty(message))
LogUtil.i(this.getClass().getSimpleName(),"-------------------> "+message);
}
protected void logD(String message){
if (!TextUtils.isEmpty(message))
LogUtil.d(this.getClass().getSimpleName(),"--------> "+message);
}
protected void logE(String message){
if (!TextUtils.isEmpty(message))
LogUtil.e(this.getClass().getSimpleName(),"--------- -----------> "+message);
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.util.List;
/**
* Text - stores text strings
*
* @author Brian Wellington
* @see <a href="https://tools.ietf.org/html/rfc1035">RFC 1035: Domain Names - Implementation and
* Specification</a>
*/
public class TXTRecord extends TXTBase {
TXTRecord() {}
/**
* Creates a TXT Record from the given data
*
* @param strings The text strings
* @throws IllegalArgumentException One of the strings has invalid escapes
*/
public TXTRecord(Name name, int dclass, long ttl, List<String> strings) {
super(name, Type.TXT, dclass, ttl, strings);
}
/**
* Creates a TXT Record from the given data
*
* @param string One text string
* @throws IllegalArgumentException The string has invalid escapes
*/
public TXTRecord(Name name, int dclass, long ttl, String string) {
super(name, Type.TXT, dclass, ttl, string);
}
}
|
package prj.designpatterns.observer.prototype;
/**
* 客户端
*
* @author LuoXin
*
*/
public class Client {
public static void main(String[] args) {
ISubject subject = new ConcreteSubject();
IObserver observer1 = new ConcreteObserver();
IObserver observer2 = new ConcreteObserver();
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObserver();
subject.deleteObserver(observer2);
subject.notifyObserver();
}
}
|
package pro.likada.rest.wrapper.autograph;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by abuca on 27.03.17.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class RTripStageWrapper {
@JsonProperty("Name")
private String name;
@JsonProperty("Alias")
private String alias;
@JsonProperty("Params")
private String[] params;
@JsonProperty("Items")
private RTripStageItemWrapper[] items;
@JsonProperty("Statuses")
private RParameterStatusWrapper[] statuses;
@JsonProperty("Total")
private Map<String,String > finalData;
public List<Double> getDistances(){
List<Double> distances = new ArrayList<>();
int position = Arrays.asList(params).indexOf(ResourceBundle.getBundle("autograph").getString("distance_col_name"));
if(position == -1){
return distances;
}
distances = Arrays.asList(items).stream()
.map(rTripStageItemWrapper -> rTripStageItemWrapper.getValues()[position])
.map(s -> Double.valueOf(s))
.collect(Collectors.toList());
return distances;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String[] getParams() {
return params;
}
public void setParams(String[] params) {
this.params = params;
}
public RParameterStatusWrapper[] getStatuses() {
return statuses;
}
public void setStatuses(RParameterStatusWrapper[] statuses) {
this.statuses = statuses;
}
public Map<String, String> getFinalData() {
return finalData;
}
public void setFinalData(Map<String, String> finalData) {
this.finalData = finalData;
}
public RTripStageItemWrapper[] getItems() {
return items;
}
public void setItems(RTripStageItemWrapper[] items) {
this.items = items;
}
}
|
package me.ewriter.chapter9;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import me.ewriter.chapter9.systeminfo.SystemInfoActivity;
import me.ewriter.chapter9.systemtest.AMProcessTestActivity;
import me.ewriter.chapter9.systemtest.PMTestActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void BtnSystemInfo(View view) {
startActivity(new Intent(this, SystemInfoActivity.class));
}
public void BtnPackageManager(View view) {
startActivity(new Intent(this, PMTestActivity.class));
}
public void BtnActivityManager(View view) {
startActivity(new Intent(this, AMProcessTestActivity.class));
}
}
|
package interware.coolapp.firebase.database;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
/**
* Created by chelixpreciado on 7/19/16.
*/
public class DBManager {
public static final String dbTagPrefs = "DB_TAG_PREFS";
private final String _is_first_time_in = "_is_first_time_in";
private SharedPreferences manager;
private SharedPreferences.Editor editor;
private DatabaseReference mDataBase;
public DBManager(Context context) {
manager = context.getSharedPreferences(dbTagPrefs, 0);
editor = manager.edit();
}
public DatabaseReference getmDataBase() {
if (mDataBase==null){
if (isFirstTimeIn()){
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
setFirstTimeIn(false);
}
mDataBase = FirebaseDatabase.getInstance().getReference();
}
return mDataBase;
}
public void setFirstTimeIn(boolean firstTimeIn){
editor.putBoolean(_is_first_time_in, firstTimeIn);
editor.commit();
}
public boolean isFirstTimeIn(){
return manager.getBoolean(_is_first_time_in, true);
}
}
|
package enums;
public enum MUTATION {
BUNNY(50, 2, "Bunny"), LION(50, 2, "Lion"), CHIM(100, 5, "Chim"), FANG(10000, 3, "Fangs");
public final int spontaneous;
public final int half;
public final String phenotype;
private MUTATION(int spontaneous, int half, String phenotype){
this.spontaneous = spontaneous;
this.half = half;
this.phenotype = phenotype;
}
@Override
public String toString(){
return phenotype;
}
}
|
package heylichen.sort.pq;
import heylichen.test.AppTestContext;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Random;
public class PriorityQueueTest extends AppTestContext {
@Autowired
private PriorityComparator<Integer> minIntPriorityComparator;
@Test
public void name2() {
int size = 16;
Random rand = new Random();
PriorityQueue<Integer> pq = new PriorityQueue(minIntPriorityComparator, size);
pq.insert(13);
pq.insert(34);
pq.insert(14);
pq.insert(17);
pq.insert(5);
pq.insert(3);
Deque<Integer> stack = new LinkedList<>();
while (!pq.isEmpty()) {
stack.add(pq.delMin());
}
System.out.println(stack);
}
@Test
public void name() {
int size = 16;
Random rand = new Random();
PriorityQueue<Integer> pq = new PriorityQueue(minIntPriorityComparator, size);
for (int i = 0; i < size; i++) {
pq.insert(rand.nextInt(100));
}
Deque<Integer> stack = new LinkedList<>();
while (!pq.isEmpty()) {
stack.add(pq.delMin());
}
System.out.println(stack);
}
} |
package com.example.simplemessage200619;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.function.Consumer;
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
public static final String EXTRA_MESSAGE = "com.example.SimpleMessage200619.nickname";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1950; i <= thisYear; i++) {
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);
Spinner spinYear = (Spinner)findViewById(R.id.yearspin);
spinYear.setAdapter(adapter);
}
public void sendRegisterRequest(View view) {
EditText nickname = (EditText) findViewById(R.id.editnickname);
EditText Pass1 = (EditText) findViewById(R.id.password);
EditText FN1 = (EditText) findViewById(R.id.firstname);
EditText LN1 = (EditText) findViewById(R.id.name);
Spinner GE1 = (Spinner) findViewById(R.id.gender_spinner);
Spinner BY1 = (Spinner) findViewById(R.id.yearspin);
String text=BY1.getSelectedItem().toString();
Integer yb = Integer.valueOf(text);
Intent intent = getIntent();
String message = intent.getStringExtra(RegisterActivity.EXTRA_MESSAGE);
UserProfile userProfile = new UserProfile();
setContentView(R.layout.activity_register);
userProfile.username=nickname.getText().toString();
userProfile.password= Pass1.getText().toString();
userProfile.firstName = FN1.getText().toString();
userProfile.lastName = LN1.getText().toString();
userProfile.gender = GE1.getSelectedItem().toString();
userProfile.yearOfBirth = yb;
// Log.e(TAG, userProfile.toString());
Consumer<ResponseStatus> myConsumer = new Consumer<ResponseStatus>() {
@Override
public void accept(ResponseStatus responseStatus) {
if (responseStatus.getStatus() == 1) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_register);
}
}
};
RestController.registerUser(getApplicationContext(), userProfile, myConsumer);
}
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
}
}
|
package ru.mephi.pesinessa.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties приложения для работы с Ignite
*/
@ConfigurationProperties(prefix = "ignite")
@Data
public class IgniteAppProperties {
/**
* Имя кеша
*/
private String cacheName;
/**
* Путь persistence хранилища
*/
private String storagePath;
/**
* Путь до скрипта insert для таблиц кэша
*/
private String sqlCreateScriptPath;
/**
* Путь до скрипта для очистки таблицы
*/
private String sqlDeleteScriptPath;
/**
* Путь до sqlline.sh ignite
*/
private String pathToSqlline;
}
|
package com.evan.graphics.command;
import android.graphics.Canvas;
import android.graphics.Rect;
import com.facebook.react.bridge.ReadableMap;
public class DrawImageCommand extends Command {
public DrawImageCommand(ReadableMap cmd, int canvasWidth, int canvasHeight, Rect previousRect) {
super(cmd, canvasWidth, canvasHeight, previousRect);
}
@Override
public PrepareHandler getPrepare() {
return null;
}
@Override
public void excute(Canvas canvas) {
}
}
|
/*
* Copyright © 2020-2022 ForgeRock AS (obst@forgerock.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.forgerock.sapi.gateway.ob.uk.common.datamodel.event;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Represents {@code OBEventPolling1SetErrs} in the OB data model. This class is stored within mongo (instead
* of the OB model), in order to make it easier to introduce new versions of the Read/Write API.
*
* <p>
* Note that this object is used across multiple versions of the Read/Write API, meaning that some values won't be
* populated. For this reason it is a mutable {@link Data} rather than an immutable {@link lombok.Value} one.
* </p>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FREventPollingError {
@JsonProperty("err")
@NotNull
@Size(
min = 1,
max = 40
)
private String error;
@JsonProperty("description")
@NotNull
@Size(
min = 1,
max = 256
)
private String description;
}
|
package com.example.demo.base1;
import com.example.demo.test.KejiDog;
import java.io.Serializable;
/**
* Created By RenBin6 on 2020/8/24 .
*/
public class User implements Serializable {
private String userName;
private String password;
private KejiDog pet;
public KejiDog getPet() {
return pet;
}
public void setPet(KejiDog pet) {
this.pet = pet;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package com.zantong.mobilecttx.model.repository;
import com.zantong.mobilecttx.base.bean.BaseResult;
import com.zantong.mobilecttx.base.bean.Result;
import com.zantong.mobilecttx.base.dto.BaseDTO;
import com.zantong.mobilecttx.card.dto.BindCarDTO;
import com.zantong.mobilecttx.chongzhi.bean.RechargeCouponResult;
import com.zantong.mobilecttx.chongzhi.bean.RechargeResult;
import com.zantong.mobilecttx.chongzhi.dto.RechargeDTO;
import com.zantong.mobilecttx.daijia.bean.DrivingOcrResult;
import com.zantong.mobilecttx.fahrschule.bean.AresGoodsResult;
import com.zantong.mobilecttx.fahrschule.bean.CreateOrderResult;
import com.zantong.mobilecttx.fahrschule.bean.GoodsDetailResult;
import com.zantong.mobilecttx.fahrschule.bean.MerchantAresResult;
import com.zantong.mobilecttx.fahrschule.bean.RecordCountResult;
import com.zantong.mobilecttx.fahrschule.dto.CreateOrderDTO;
import com.zantong.mobilecttx.home.bean.BannerResult;
import com.zantong.mobilecttx.home.bean.HomeCarResult;
import com.zantong.mobilecttx.home.bean.HomeResult;
import com.zantong.mobilecttx.home.bean.StartPicResult;
import com.zantong.mobilecttx.home.dto.HomeDataDTO;
import com.zantong.mobilecttx.order.bean.OrderDetailResult;
import com.zantong.mobilecttx.order.bean.OrderListResult;
import com.zantong.mobilecttx.user.bean.CouponFragmentResult;
import com.zantong.mobilecttx.user.bean.LoginInfoBean;
import com.zantong.mobilecttx.user.bean.MessageCountResult;
import com.zantong.mobilecttx.user.bean.MessageDetailResult;
import com.zantong.mobilecttx.user.bean.MessageResult;
import com.zantong.mobilecttx.user.bean.MessageTypeResult;
import com.zantong.mobilecttx.user.bean.UserCarsResult;
import com.zantong.mobilecttx.user.dto.MegDTO;
import com.zantong.mobilecttx.user.dto.MessageDetailDTO;
import com.zantong.mobilecttx.weizhang.bean.LicenseResponseBean;
import com.zantong.mobilecttx.weizhang.bean.PayOrderResult;
import com.zantong.mobilecttx.weizhang.dto.ViolationCarDTO;
import com.zantong.mobilecttx.weizhang.dto.ViolationPayDTO;
import okhttp3.MultipartBody;
import rx.Observable;
/**
* Created by jianghw on 2017/4/26.
*/
public interface IRemoteSource {
/**
* 查询所有消息
*
* @param bean
* @return
*/
Observable<MessageTypeResult> messageFindAll(BaseDTO bean);
/**
* 2.4.21获取消息详情列表
*
* @param bean
* @return
*/
Observable<MessageResult> findMessageDetailByMessageId(MegDTO bean);
/**
* 2.4.22获取消息详情
*
* @param bean
* @return
*/
Observable<MessageDetailResult> findMessageDetail(MessageDetailDTO bean);
/**
* 2.4.2查看优惠券信息
*/
Observable<CouponFragmentResult> usrCouponInfo(String usrnum, String couponStatus);
/**
* 驾驶证查分 cip.cfc.v001.01
*/
Observable<LicenseResponseBean> driverLicenseCheckGrade(String requestDTO);
/**
* 2.4.24删除消息
*
* @param megDTO
* @return
*/
Observable<MessageResult> deleteMessageDetail(MegDTO megDTO);
/**
* 2.4.27删除用户优惠券
*/
Observable<MessageResult> delUsrCoupon(String couponId, String userId);
/**
* https://ctkapptest.icbc-axa.com/ecip/mobilecall_call
*
* @param msg
* @return
*/
Observable<LoginInfoBean> loadLoginPost(String msg);
/**
* 40.app启动图片获取
*
* @param msg
* @return
*/
Observable<StartPicResult> startGetPic(String msg);
/**
* 57.获取指定类型优惠券
*/
Observable<RechargeCouponResult> getCouponByType(String userId, String type);
/**
* 10.创建加油订单
*/
Observable<RechargeResult> addOilCreateOrder(RechargeDTO rechargeDTO);
/**
* 加油充值
*/
Observable<PayOrderResult> onPayOrderByCoupon(String payUrl, String orderPrice, String payType);
/**
* 43.生成违章缴费订单
*/
Observable<PayOrderResult> paymentCreateOrder(ViolationPayDTO payDTO);
Observable<LicenseResponseBean> loadLoginPostTest(String msg);
/**
* 1.首页信息
*/
Observable<HomeResult> homePage(HomeDataDTO id);
/**
* cip.cfc.c003.01
*/
Observable<UserCarsResult> getRemoteCarInfo(String requestDTO);
/**
* 37.获取所有未读消息数量
*/
Observable<MessageCountResult> countMessageDetail(BaseDTO baseDTO);
/**
* 58.获取banner图片
*/
Observable<BannerResult> getBanner(String type);
/**
* 55.行驶证扫描接口
*/
Observable<DrivingOcrResult> uploadDrivingImg(MultipartBody.Part part);
/**
* 3.获取商户区域列表
*/
Observable<MerchantAresResult> getMerchantArea();
/**
* 4.获取区域商品列表
*/
Observable<AresGoodsResult> getAreaGoods(int areaCode);
/**
* 2.创建订单
*/
Observable<CreateOrderResult> createOrder(CreateOrderDTO createOrder);
/**
* 7.获取用户指定活动的统计总数
*/
Observable<RecordCountResult> getRecordCount(String type, String phone);
/**
* 48.绑定行驶证接口
*/
Observable<BaseResult> commitCarInfoToNewServer(BindCarDTO bindCarDTO);
/**
* cip.cfc.u005.01
*/
Observable<Result> commitCarInfoToOldServer(String msg);
/**
* 5.获取工行支付页面
*/
Observable<PayOrderResult> getBankPayHtml(String orderId, String orderPrice);
/**
* 8.查询订单列表
*/
Observable<OrderListResult> getOrderList(String userId);
/**
* 9.获取订单详情
*/
Observable<OrderDetailResult> getOrderDetail(String orderId);
/**
* 10.更新订单状态
*/
Observable<BaseResult> updateOrderStatus(String orderId, int orderStatus);
/**
* 6.获取商品详情
*/
Observable<GoodsDetailResult> getGoodsDetail(String goodsId);
/**
* 获取违章信息
*/
Observable<HomeCarResult> getTextNoticeInfo(String defaultUserID);
/**
* 处理违章信息
*/
Observable<BaseResult> handleViolations(ViolationCarDTO violationResult);
}
|
package com.esrinea.dotGeo.tracking.processor.component.tracking;
import com.esri.ges.processor.GeoEventProcessorDefinitionBase;
public class TrackingProcessorDefinition extends GeoEventProcessorDefinitionBase {
public TrackingProcessorDefinition() {
}
@Override
public String getName() {
return "TrackingProcessor";
}
@Override
public String getDomain() {
return "tracking.processor";
}
@Override
public String getVersion() {
return "10.2.2";
}
@Override
public String getLabel() {
return "Tracking Processor";
}
@Override
public String getDescription() {
return "Dot Geo Tracking Processor.";
}
@Override
public String getContactInfo() {
return "zenbaei@gmail.com";
}
} |
package edu.uag.iidis.scec.servicios;
import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.uag.iidis.scec.modelo.Seccion;
import edu.uag.iidis.scec.excepciones.*;
import edu.uag.iidis.scec.persistencia.SeccionDAO;
import edu.uag.iidis.scec.persistencia.hibernate.*;
public class ManejadorSecciones {
private Log log = LogFactory.getLog(ManejadorRoles.class);
private SeccionDAO dao;
public ManejadorSecciones() {
dao = new SeccionDAO();
}
public Collection listarSecciones() {
Collection resultado;
if (log.isDebugEnabled()) {
log.debug(">guardarUsuario(usuario)");
}
try {
HibernateUtil.beginTransaction();
resultado = dao.buscarTodos();
HibernateUtil.commitTransaction();
return resultado;
} catch (ExcepcionInfraestructura e) {
HibernateUtil.rollbackTransaction();
return null;
} finally {
HibernateUtil.closeSession();
}
}
public Collection buscarSecciones(String seccionBuscar) {
Collection resultado;
if (log.isDebugEnabled()) {
log.debug(">***Buscar Seccion:"+seccionBuscar);
}
try {
HibernateUtil.beginTransaction();
resultado = dao.buscarPorNombre(seccionBuscar);
HibernateUtil.commitTransaction();
return resultado;
} catch (ExcepcionInfraestructura e) {
HibernateUtil.rollbackTransaction();
return null;
} finally {
HibernateUtil.closeSession();
}
}
public Collection buscarSeccionesTest(Long seccionBuscar) {
Collection resultado;
if (log.isDebugEnabled()) {
log.debug(">***Buscar Seccion:"+seccionBuscar);
}
try {
HibernateUtil.beginTransaction();
resultado = dao.buscarPorTest(seccionBuscar);
HibernateUtil.commitTransaction();
return resultado;
} catch (ExcepcionInfraestructura e) {
HibernateUtil.rollbackTransaction();
return null;
} finally {
HibernateUtil.closeSession();
}
}
public void eliminarSeccion(Long id) {
if (log.isDebugEnabled()) {
log.debug(">eliminarSeccion(Seccion)");
}
try {
HibernateUtil.beginTransaction();
Seccion seccion = dao.buscarPorId(id, true);
if (seccion != null) {
dao.hazTransitorio(seccion);
}
HibernateUtil.commitTransaction();
} catch (ExcepcionInfraestructura e) {
HibernateUtil.rollbackTransaction();
if (log.isWarnEnabled()) {
log.warn("<ExcepcionInfraestructura");
}
} finally {
HibernateUtil.closeSession();
}
}
public int crearSeccion(Seccion seccion) {
int resultado;
if (log.isDebugEnabled()) {
log.debug(">guardarSeccion(Seccion)");
}
try {
HibernateUtil.beginTransaction();
if (dao.existeSeccion(seccion.getNombre())) {
resultado = 1; // Excepción. El nombre de Seccion ya existe
} else {
dao.hazPersistente(seccion);
resultado = 0; // Exito. El Seccion se creo satisfactoriamente.
}
HibernateUtil.commitTransaction();
} catch (ExcepcionInfraestructura e) {
HibernateUtil.rollbackTransaction();
if (log.isWarnEnabled()) {
log.warn("<ExcepcionInfraestructura");
}
resultado = 2; // Excepción. Falla en la infraestructura
} finally {
HibernateUtil.closeSession();
}
return resultado;
}
}
|
package ejercicio08;
import java.io.*;
/**
*
* @author Javier
*/
public class Ejercicio08 {
public static String invertir(String frase) {
char[] fraseChar = frase.toCharArray();
char[] fraseCharInv = new char[fraseChar.length];
int inv = fraseChar.length-1;
for (int i = 0; i < fraseChar.length; i++) {
fraseCharInv[i] = fraseChar[inv];
inv--;
}
return new String(fraseCharInv);
}
public static void main(String[] args) {
File archivo = new File("texto.txt");
String texto = null;
FileReader fr = null;
try {
fr = new FileReader(archivo);
BufferedReader br = new BufferedReader(fr);
texto = br.readLine();
System.out.println("Texto almacenado en la cadena: " +texto);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
if (fr != null) {
try {
fr.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
System.out.println(invertir(texto));
}
} |
package com.qifen.toyvpn;
import android.util.Log;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class PingTunnel {
private int mFd;
private int mUdpFd;
static final String TAG = "PingTunnel";
private PingTunnel(int fd, int udpfd) {
mFd = fd;
mUdpFd = udpfd;
}
static boolean enablePingTunnel() {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
os.writeBytes("echo 0 2147483647 > /proc/sys/net/ipv4/ping_group_range" + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
Log.i(TAG, "exit value = " + process.exitValue());
} catch (InterruptedException e) {
return false;
} catch (IOException e) {
return false;
}
/* Runtime.getRuntime().exec("su -c \"sysctl -w net.ipv4.ping_group_range='0 2147483647'\""); */
return true;
}
public static PingTunnel open(String mode) {
PingTunnelDevice.setDnsMode(mode);
int fd = PingTunnelDevice.do_open();
if (fd == -1 && enablePingTunnel()) {
fd = PingTunnelDevice.do_open();
}
if (fd == -1) return null;
int udpfd = PingTunnelDevice.do_open_udp();
return new PingTunnel(fd, udpfd);
}
public int getFd() {
return mFd;
}
public int getUdpFd() {
return mUdpFd;
}
public void close() {
PingTunnelDevice.do_close(mFd);
mFd = -1;
}
}
|
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.io.*;
/**
* The test class PlayListTest.
*
* @author (your name)
* @version (a version number or a date)
*/
public class PlayListTest
{
/**
* Default constructor for test class PlayListTest
*/
public PlayListTest()
{
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@Before
public void setUp()
{
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
@After
public void tearDown()
{
}
@Test
public void testConstructor()
{
Vector<Song> list = new Vector<Song>();
Vector<Song> list2 = new Vector<Song>();
list.add(new Song("Godzilla", 3, 52));
list.add(new Song("Dont Fear the Reaper", 5, 9));
PlayList playList = new PlayList(list);
PlayList empty = new PlayList();
assertEquals(list2, empty.getList());
assertEquals(list, playList.getList());
}
@Test
public void testSave()
{
Vector<Song> list = new Vector<Song>();
Song song = new Song("Godzilla", 3, 52);
Song song2 = new Song("Dont Fear the Reaper", 5, 9);
list.add(song);
list.add(song2);
PlayList playList = new PlayList(list);
try
{
File saveFile = new File("TestSave.txt");
playList.save(saveFile);
SongPool pool = new SongPool();
pool.loadFile(saveFile);
assertTrue(song.equals(pool.getSong(0)));
assertTrue(song2.equals(pool.getSong(1)));
}
catch(IOException e)
{
assertTrue(false);
}
}
@Test
public void testGetList()
{
Vector<Song> list = new Vector<Song>();
Song song = new Song("Godzilla", 3, 52);
Song song2 = new Song("Dont Fear the Reaper", 5, 9);
list.add(song);
list.add(song2);
PlayList playList = new PlayList(list);
assertEquals(list, playList.getList());
assertEquals(song, playList.getSong(0));
}
@Test
public void testLength()
{
Vector<Song> list = new Vector<Song>();
Song song = new Song("Godzilla", 3, 52);
Song song2 = new Song("Dont Fear the Reaper", 5, 9);
list.add(song);
list.add(song2);
PlayList playList = new PlayList(list);
assertFalse(playList.setLength(2));
assertTrue(playList.setLength(50));
assertEquals(50, playList.getLength().minutes());
assertEquals(541, playList.getTime().seconds());
assertEquals(2459, playList.timeLeft().seconds());
assertFalse(playList.exceedsTime(song2));
playList.addToList(song2);
assertFalse(playList.exceedsTime(song2));
}
@Test
public void testRemove()
{
Vector<Song> list = new Vector<Song>();
Song song = new Song("Godzilla", 3, 52);
Song song2 = new Song("Dont Fear the Reaper", 5, 9);
list.add(song);
list.add(song2);
PlayList playList = new PlayList(list);
assertEquals(541, playList.getTime().seconds());
playList.removeFromList(0);
assertEquals(309, playList.getTime().seconds());
}
@Test
public void testExceedsTime()
{
Vector<Song> list = new Vector<Song>();
Song song = new Song("Godzilla", 2699);
Song song2 = new Song("Dont Fear the Reaper", 5, 9);
PlayList playList = new PlayList();
assertFalse(playList.exceedsTime(song));
playList.addToList(song);
assertTrue(playList.exceedsTime(song2));
}
}
|
package com.arthur.bishi.xiecheng;
/**
* @title: No1
* @Author ArthurJi
* @Date: 2021/3/14 15:16
* @Version 1.0
*/
public class No1 {
}
|
package com.example.androidproject;
import java.io.Serializable;
import java.util.ArrayList;
public class Notesdata implements Serializable {
int id;
double lat,lng;
String category , notesTitle, description, date,audio;
public Notesdata(int id, String category, String notesTitle, String description, String date, double lat,double lng,String audio) {
this.id = id;
this.category = category;
this.notesTitle = notesTitle;
this.description = description;
this.date = date;
this.lat = lat;
this.lng = lng;
this.audio = audio;
}
public int getId() {
return id;
}
public String getCategory() {
return category;
}
public String getNotesTitle() {
return notesTitle;
}
public String getDescription() {
return description;
}
public String getDate() {
return date;
}
public double getLat() {
return lat;
}
public double getLng() {
return lng;
}
public String getAudio() {
return audio;
}
public static ArrayList<Notesdata> notesdata = new ArrayList<>();
}
|
package com.example.hyunyoungpark.myfavoriterestaurant_midterm;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
final int _REQ = 100;
final int RESULT_STORE = 0;
final int RESULT_CANCLED = 50;
ListView lv;
TextView tv;
ArrayList<Store> data_store = new ArrayList<Store>();
ArrayList<String> data_name = new ArrayList<String>();
ArrayAdapter<String> adapter;
Store store;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListView();
FireBaseHelper.getDatabaseReference().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// need setExtra here
// https://stackoverflow.com/questions/5265913/how-to-use-putextra-and-getextra-for-string-data
emptyListView();
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot snapshot : children) {
Store store = snapshot.getValue(Store.class);
data_store.add(store);
data_name.add(store.getName());
}
// Store store = dataSnapshot.getValue(Store.class);
// data_store.add(store);
// String rname = String.valueOf(store.getName());
// data_name.add(rname);
// tv.setText("Restaurants List (" + data_store.size() + ")");
setListView();
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void emptyListView() {
data_store.clear();
data_name.clear();
}
public void setListView() {
lv = (ListView) findViewById(R.id.listview);
tv = (TextView) findViewById(R.id.tv);
//read data from database just store name
//add the store name in arraylist data_name
// assign arraylist to adapter.
tv.setText("Restaurants List (" + data_name.size() + ")");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data_name);
lv.setAdapter(adapter);
Log.d("size ", "no " + adapter.getCount());
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
intent = new Intent(MainActivity.this, MainActivity3.class);
Log.d("size of list ", " i " + data_store.size());
intent.putExtra("store_main3", data_store.get(i));
startActivity(intent);
}
});
}
public void onClick(View v) {
if (v.getId() == R.id.addStore) {
intent = new Intent(MainActivity.this, MainActivity2.class);
startActivityForResult(intent, _REQ);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data_) {
super.onActivityResult(requestCode, resultCode, data_);
if (requestCode == _REQ) {
if (resultCode == RESULT_STORE) {
Store store = data_.getParcelableExtra("store");
//FireBaseHelper.add(store);
FireBaseHelper.add(store);
// data_store.add(store);
// data_name.add(store.name);
adapter.notifyDataSetChanged();
} else if (resultCode == RESULT_CANCLED) {
}
}
}
//
// @Override
// protected void onActivityResult(int requestCode, int resultCode, Intent data_) {
// Log.d("code ", " req= "+requestCode+" res = "+resultCode);
// super.onActivityResult(requestCode, resultCode, data_);
// if (requestCode == _REQ) {
// Log.d("code 1", " req= "+requestCode+" res = "+resultCode);
// if (resultCode == RESULT_STORE) {
// Log.d("code 2", " req= "+requestCode+" res = "+resultCode);
// Store store = data_.getParcelableExtra("store");
// //FireBaseHelper.add(store);
// FireBaseHelper.add(store);
//// data_store.add(store);
//// data_name.add(store.name);
// adapter.notifyDataSetChanged();
// } else if (resultCode == RESULT_CANCLED) {
//
// }
// }
// }
} |
package com.cpro.rxjavaretrofit.views.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cpro.rxjavaretrofit.R;
import com.cpro.rxjavaretrofit.entity.FileIdListEntity;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by lx on 2016/5/26.
*/
public class HomeworkSupervisionFilesAdapter extends RecyclerView.Adapter {
List<FileIdListEntity> list;
public void setList(List<FileIdListEntity> list){
this.list = list;
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_homework_supervision_files, parent, false);
return new FilesViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
FilesViewHolder filesViewHolder = (FilesViewHolder) holder;
filesViewHolder.tv_file_name.setText(list.get(position).getImageId().substring(list.get(position).getImageId().lastIndexOf("/")+1, list.get(position).getImageId().length()));
filesViewHolder.file_url = list.get(position).getImageId();
}
@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
public static class FilesViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_file_name)
TextView tv_file_name;
@BindView(R.id.tv_download_label)
public TextView tv_download_label;
@BindView(R.id.tv_disable_onclick)
public TextView tv_disable_onclick;
public String file_url;
public FilesViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
tv_download_label.getBackground().setAlpha(100);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.xag.util;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author agunga
*/
@CatchMyException
@Interceptor
public class CatchExceptionInterceptor {
private final Logger log = LoggerFactory.getLogger(Object.class);
@AroundInvoke
private Object intercept(InvocationContext ic) throws Exception {
try {
return ic.proceed();
} catch (Exception e) {
e.getMessage();
log.error("Exception");
return null;
}
}
}
|
package com.seva.Resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.seva.models.ItemDTO;
import com.seva.services.MenuService;
/***
*
* @author Joshua
*@Since 28-04-2016
*/
@RestController
@RequestMapping("/api")
public class MenuResource {
@Autowired
MenuService menuService;
@RequestMapping(value = "/menu", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ItemDTO>> getItems() {
return new ResponseEntity<List<ItemDTO>>(menuService.getItems(), HttpStatus.OK);
}
}
|
package us.team7pro.EventTicketsApp.Controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import us.team7pro.EventTicketsApp.Domain.User;
import us.team7pro.EventTicketsApp.Models.Event;
import us.team7pro.EventTicketsApp.Repositories.EventRepository;
import java.io.IOException;
@Controller
public class OrganizerController {
@Autowired
private EventRepository eventRepository;
@GetMapping("/organizerdashboard")
public String eventForm(Model model, @AuthenticationPrincipal User user) {
model.addAttribute("events", eventRepository.findByOrganizerID(user.getId()));
model.addAttribute("newEvent", new Event());
return "organizerdashboard";
}
@PostMapping("/submitNewEvent")
public String eventSubmit(@ModelAttribute Event newEvent, Model model, @AuthenticationPrincipal User user) {
System.out.println(newEvent.getEventCategory());
newEvent.setOrganizerID(user.getId());
newEvent.setStatus(false);
eventRepository.save(newEvent);
model.addAttribute("newEvent", newEvent);
return "redirect:/./organizerdashboard";
}
@RequestMapping(value="/deleteEvent", method = RequestMethod.GET)
public String deleteEvent(@RequestParam(name="eventID") int eventID){
Event event = eventRepository.findByEventID(eventID);
eventRepository.delete(event);
return "redirect:/organizerdashboard";
}
}
|
package io.cde.account.dao;
import io.cde.account.domain.Account;
import io.cde.account.domain.Email;
/**
* @author lcl
*/
public interface EmailDao {
/**
* 根据用户id和邮箱id判断该用户是否关联该邮箱.
*
* @param accountId 用户id
* @param emailId 邮箱id
* @return 返回该用户信息
*/
Account findAccountByEmailId(String accountId, String emailId);
/**
* 根据邮箱地址查询邮箱信息.
*
* @param email 邮箱地址
* @return 查询到则返回true,否则返回false
*/
boolean isEmailExisted(String email);
/**
* 修改邮箱信息.
*
* @param accountId 用户id
* @param emailId 邮箱id
* @param isVerified 是否认证字段
* @return 修改操作成功返回1,否则返回-1
*/
int updateEmail(String accountId, String emailId, boolean isVerified);
/**
* 设置默认邮箱是否是公开.
*
* @param accountId 用户id
* @param isPublic 是否公开
* @return 修改操作成功返回1,否者返回-1
*/
int updatePublicEmail(String accountId, boolean isPublic);
/**
* 为指定的用户添加邮箱.
*
* @param accountId 用户id
* @param email 要添加的邮箱的信息
* @return 添加操作成功返回1,否则返回-1
*/
int addEmail(String accountId, Email email);
/**
* 删除指定用户的邮箱信息.
*
* @param accountId 用户id
* @param emailId 邮箱id
* @return 删除操作成功返回1,否则返回-1
*/
int deleteEmail(String accountId, String emailId);
}
|
/*
* 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 CSC110_2014;
/**
*
* @author JanithWanni
*/
public class Question2_Savings extends Question2_Account{
public double iRate;
public Question2_Savings(){
this("654","Mr. Saving");
balance = 1000.0;
iRate = 0.1;
}
public Question2_Savings(String no, String na){
super(no,na);
balance = 2000.0;
iRate = 0.2;
}
public void printInfo(){
System.out.println("Int Rate:"+iRate);
System.out.println("int "+balance*iRate);
}
public static void main(String[] args) {
Question2_Savings s1 = new Question2_Savings();
s1.printInfo();
Question2_Savings s2 = new Question2_Savings("258", "Dr. Silva");
s2.printInfo();
}
}
|
package com.cg.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cg.entity.Movie;
import com.cg.service.InvalidMovieException;
import com.cg.service.MovieService;
@RestController
@RequestMapping("/movie")
public class MovieController {
@Autowired
private MovieService service;
@GetMapping(path="/{id}", produces = "application/json")
public Movie getMovie(@PathVariable int id) throws InvalidMovieException {
return service.fetch(id);
}
@PostMapping(path= "/add", consumes = "application/json", produces = "application/json")
public Movie saveMovie(@RequestBody Movie movie) {
return service.save(movie);
}
@GetMapping(produces = "application/json")
public List<Movie> getAllMovies(){
return service.getAll();
}
@DeleteMapping(value="/remove")
public boolean deleteMovie(@RequestParam int id) throws InvalidMovieException {
return service.delete(id);
}
@PutMapping(value="/update", consumes = "application/json", produces = "application/json")
public Movie updateMovie(@RequestBody Movie movie) {
return service.update(movie);
}
@GetMapping(path="/genre/{gen}", produces = "application/json")
public List<Movie> getByGenre(@PathVariable String gen){
return service.findByGenre(gen);
}
}
|
package com.example.uksk;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class next extends AppCompatActivity {
Button b1,b2,b3,b4,b5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
b1 = findViewById(R.id.button16);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(next.this,pet.class);
startActivity(intent);
}
});
b2 = findViewById(R.id.button4);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(next.this,room.class);
startActivity(intent);
}
});
b3 = findViewById(R.id.button6);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(next.this,intruder.class);
startActivity(intent);
}
});
b4 = findViewById(R.id.button5);
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(next.this,health.class);
startActivity(intent);
}
});
b5 = findViewById(R.id.button7);
b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(next.this,rewards.class);
startActivity(intent);
}
});
}
}
|
package nim_01;
import java.util.Scanner;
public class Main {
//Class Nim02 contains the Methods
private Nim02 mim02 = new Nim02();
public static void main(String[] args) {
nim02.play();
}
}
|
package com.design.factory.AbstractFactory;
public class MainTestAbstract {
public static void main(String[] args) {
System.out.println("------组装开始----------");
PizzaStore nyStore = new PizzaStoreNY(); //披萨店 + 纽约
Pizza pizza = nyStore.orderPizza("cheese"); //披萨店 + 纽约 + 奶酪
System.out.println("Ethan ordered a " + pizza + "\n");
pizza = nyStore.orderPizza("clam");
System.out.println("Ethan ordered a " + pizza + "\n"); //披萨店 + 纽约 + 蛤蜊
pizza = nyStore.orderPizza("pepperoni");
System.out.println("Ethan ordered a " + pizza + "\n"); //披萨店 + 纽约 + 蔬菜
pizza = nyStore.orderPizza("veggie");
System.out.println("Ethan ordered a " + pizza + "\n");
PizzaStore chicagoStore = new PizzaStoreChicago();
pizza = chicagoStore.orderPizza("cheese");
System.out.println("Joel ordered a " + pizza + "\n");
pizza = chicagoStore.orderPizza("clam");
System.out.println("Joel ordered a " + pizza + "\n");
pizza = chicagoStore.orderPizza("pepperoni");
System.out.println("Joel ordered a " + pizza + "\n");
pizza = chicagoStore.orderPizza("veggie");
System.out.println("Joel ordered a " + pizza + "\n");
}
}
|
package cham.test_project.process;
import cham.test_project.controller.Adapter;
import cham.test_project.data.Coordinates;
import cham.test_project.data.ServiceA;
import cham.test_project.data.ServiceB;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.commons.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import static org.apache.camel.language.constant.ConstantLanguage.constant;
public class UpdateData implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
// Получение списка параметров
HashMap<String, String> res = getConfig();
// Получение входного JSON
ServiceA json = exchange.getIn().getBody(ServiceA.class);
// Создание объекта для выходного JSON
ServiceB resultJson = new ServiceB();
// Получение даты и времени
String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
String time = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
// Добавление даты и времени в JSON
resultJson.setCreateDt(date + "T" + time + "Z");
// Получение координат
Coordinates coordinates = json.getCoordinates();
// Создание URL ссылки для парсера
String[] params = res.get("url").split("#");
String url = "";
for(String param: params)
if (param.equals("latitute"))
url += coordinates.getLatitude();
else if(param.equals("longitude"))
url += coordinates.getLongitude();
else
url += param;
// Заполнение температуры из парсера Яндекс Погоды в JSON
String temp = parseWether(res.get("token_name"), res.get("token"), url, res.get("data_path"));
// Если вернулось пустое значение температуры, значит ошибка в config файле и данные не валидны, отправляем пустое сообщение
if (temp.equals("")) {
exchange.getIn().setBody("");
return;
}
resultJson.setCurrencyTemp(parseWether(res.get("token_name"), res.get("token"), url, res.get("data_path")));
// Добавление сообщения в JSON
resultJson.setTxt(json.getMsg());
// Преобразование Object в StringJson и добавление в тело запроса
ObjectMapper mapper = new ObjectMapper();
exchange.getIn().setBody(mapper.writeValueAsString(resultJson));
}
// Получение конфигурации для парсинга данных с сайта погоды
private HashMap<String, String> getConfig(){
// Инициализация списка с настройками
HashMap<String, String> result = new HashMap<>();
try {
// Получение данных из файла
String json = "";
FileInputStream fis = new FileInputStream("config.txt");
int i = -1;
while ((i = fis.read()) != -1)
json += (char)i;
// Преобразование файла с параметрами в JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(json).get("weather_api");
// Получение параметров
result.put("token_name", actualObj.get("token_name").toString().split("\"")[1]);
result.put("token", actualObj.get("token").toString().split("\"")[1]);
result.put("url", actualObj.get("url").toString().split("\"")[1]);
result.put("data_path", actualObj.get("data_path").toString().split("\"")[1]);
// Обработка ошибок
}catch (IOException e){
LogFactory.getLog(Adapter.class).error("Invalid configuration " + e.getMessage());
}
return result;
}
private String parseWether(String token_name, String token, String link, String data_path){
try {
// Создание URL сайта парсера и добавление параметров
URL url = new URL(link);
// Инициализация подключения
URLConnection connection = url.openConnection();
// Добавление токена приложения
if(!token.isEmpty() && !token_name.isEmpty())
connection.setRequestProperty(token_name, token);
// Создание буфера для ответа и получение ответа
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = in.readLine();
// Преобразование String в JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(result);
// Отправляем значение fact.temp из JSON
String[] path = data_path.split(" ");
for (String node: path)
actualObj = actualObj.get(node);
return actualObj.toString();
// Обработка ошибок
} catch (MalformedURLException e) {
LogFactory.getLog(Adapter.class).error("Invalid url: " + e.getMessage());
} catch (IOException e) {
LogFactory.getLog(Adapter.class).error(e.getMessage());
}
return "";
}
}
|
package com.jam.jamoodle.model;
import org.apache.commons.lang3.text.WordUtils;
/**
* Created by Owner on 2/26/2017.
*/
public class Response {
private ContactInfo contactInfo;
private String answer;
public Response(final ContactInfo contactInfo, final String answer) {
this.contactInfo = contactInfo;
this.answer = answer;
}
public ContactInfo getContactInfo() {
return contactInfo;
}
public String getAnswer() {
return WordUtils.capitalize(answer);
}
}
|
/*
* Copyright (C) 2021 Tenisheva N.I.
*/
package com.entrepreneurship.rest.webservices.restfulwebservices.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.entrepreneurship.rest.webservices.restfulwebservices.repository.ActRepository;
import com.entrepreneurship.rest.webservices.restfulwebservices.model.Act;
/*
* It is for writing business logic for a Act class.
* version 1.0
* author Tenisheva N.I.
*/
@Service
@Transactional
public class ActService {
@Autowired
ActRepository actRepository;
public List<Act> getAllAtsByUser(String userName) {
return (List<Act>) actRepository.findListActsByUser(userName);
}
public List<Act> getAllContractActsByUser(String userName, Long id){
return actRepository.findContractActsByUser(userName, id);
}
public Act getAct(String userName, Long id){
return actRepository.findById(id).get();
}
public Act save (Act act){
return actRepository.save(act);
}
public void deleteById(long id) {
actRepository.deleteById(id);
}
}
|
package com.aidigame.hisun.imengstar.ui;
import java.io.File;
import java.util.ArrayList;
import com.aidigame.hisun.imengstar.PetApplication;
import com.aidigame.hisun.imengstar.adapter.UserPetsAdapter;
import com.aidigame.hisun.imengstar.bean.Animal;
import com.aidigame.hisun.imengstar.bean.Banner;
import com.aidigame.hisun.imengstar.bean.MyUser;
import com.aidigame.hisun.imengstar.bean.PetPicture;
import com.aidigame.hisun.imengstar.constant.Constants;
import com.aidigame.hisun.imengstar.http.HttpUtil;
import com.aidigame.hisun.imengstar.util.HandleHttpConnectionException;
import com.aidigame.hisun.imengstar.util.LogUtil;
import com.aidigame.hisun.imengstar.util.StringUtil;
import com.aidigame.hisun.imengstar.util.UiUtil;
import com.aidigame.hisun.imengstar.util.UserStatusUtil;
import com.aidigame.hisun.imengstar.view.HorizontalListView2;
import com.aidigame.hisun.imengstar.widget.ShowProgress;
import com.aidigame.hisun.imengstar.widget.fragment.ShareDialogFragment;
import com.aidigame.hisun.imengstar.R;
import com.example.android.bitmapfun.util.ImageCache;
import com.example.android.bitmapfun.util.ImageFetcher;
import com.example.android.bitmapfun.util.ImageWorker.LoadCompleteListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* 拉票卡片
* @author admin
*
*/
public class TicketCardActivity extends FragmentActivity implements OnClickListener{
private ImageView closeIv,iconIv,sexIv,first_iv,sec_iv,third_iv;
private TextView nameTv,myContriTv,ticketNumTv,moreTicketTv,goTicketTv,first_contri_tv,sec_contri_tv,third_contri_tv;
private ShowProgress showProgress;
private LinearLayout progresslayout,first_layout,sec_layout,third_layout,no_ticket_layout;
private Handler handler;
private View popupParent;
private RelativeLayout black_layout,whit_frame_layout,share_layout;
private Animal animal;
public static TicketCardActivity userCardActivity;
private int gold;
private Banner banner;
private int from;//1,照片详情
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
UiUtil.setScreenInfo(this);
UiUtil.setWidthAndHeight(this);
setContentView(R.layout.activity_ticket_card);
handler=HandleHttpConnectionException.getInstance().getHandler(this);
animal=(Animal)getIntent().getSerializableExtra("animal");
gold=getIntent().getIntExtra("gold", 0);
banner=(Banner)getIntent().getSerializableExtra("banner");
userCardActivity=this;
from=getIntent().getIntExtra("from", 0);
initView();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
StringUtil.umengOnPause(this);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
StringUtil.umengOnResume(this);
}
private void initView() {
// TODO Auto-generated method stub
closeIv=(ImageView)findViewById(R.id.close_iv);
iconIv=(ImageView)findViewById(R.id.user_icon);
sexIv=(ImageView)findViewById(R.id.sex_iv);
goTicketTv=(TextView)findViewById(R.id.goTicketTv);
goTicketTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
first_contri_tv=(TextView)findViewById(R.id.first_contri_tv);
first_iv=(ImageView)findViewById(R.id.first_iv);
first_layout=(LinearLayout)findViewById(R.id.first_layout);
whit_frame_layout=(RelativeLayout)findViewById(R.id.white_frame);
sec_contri_tv=(TextView)findViewById(R.id.sec_contri_tv);
sec_iv=(ImageView)findViewById(R.id.sec_iv);
sec_layout=(LinearLayout)findViewById(R.id.sec_layout);
third_contri_tv=(TextView)findViewById(R.id.third_contri_tv);
third_iv=(ImageView)findViewById(R.id.third_iv);
third_layout=(LinearLayout)findViewById(R.id.third_layout);
no_ticket_layout=(LinearLayout)findViewById(R.id.no_ticket_layout);
if(System.currentTimeMillis()/1000>banner.end_time){
goTicketTv.setVisibility(View.GONE);
}
popupParent=findViewById(R.id.popup_parent);
black_layout=(RelativeLayout)findViewById(R.id.black_layout);
nameTv=(TextView)findViewById(R.id.name_tv);
myContriTv=(TextView)findViewById(R.id.address_tv);
ticketNumTv=(TextView)findViewById(R.id.gold_tv);
moreTicketTv=(TextView)findViewById(R.id.button_tv);
progresslayout=(LinearLayout)findViewById(R.id.progress_layout);
showProgress=new ShowProgress(this, progresslayout);
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
final Animal temp=HttpUtil.ticketCardApi(TicketCardActivity.this, banner.star_id, animal, handler);
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
showProgress.progressCancel();
if(temp!=null){
TicketCardActivity.this.animal=temp;
animal.votePicture.star_title=banner.name;
setUserInfo(animal);
}
}
});
}
}).start();
closeIv.setOnClickListener(this);
iconIv.setOnClickListener(this);
moreTicketTv.setOnClickListener(this);
goTicketTv.setOnClickListener(this);
first_iv.setOnClickListener(this);
sec_iv.setOnClickListener(this);
third_iv.setOnClickListener(this);
}
public void setUserInfo(final Animal animal) {
nameTv.setText(animal.pet_nickName);
myContriTv.setText("(你贡献了"+animal.my_votes+"票)");
ticketNumTv.setText(""+animal.total_votes);
if(animal.a_gender==1){
//公
sexIv.setImageResource(R.drawable.male1);
}else if(animal.a_gender==2){
//母
sexIv.setImageResource(R.drawable.female1);
}else{
}
if(animal.topVoters==null||animal.topVoters.size()==0){
RelativeLayout.LayoutParams param=(RelativeLayout.LayoutParams)whit_frame_layout.getLayoutParams();
if(param!=null){
param.height=param.height-getResources().getDimensionPixelOffset(R.dimen.one_dip)*36*2;
whit_frame_layout.setLayoutParams(param);
}
first_layout.setVisibility(View.GONE);
sec_layout.setVisibility(View.GONE);
third_layout.setVisibility(View.GONE);
no_ticket_layout.setVisibility(View.VISIBLE);
}else{
if(animal.topVoters.size()>=1){
first_contri_tv.setText(""+animal.topVoters.get(0).give_ticket_num);
loadUserIcon(first_iv, animal.topVoters.get(0).u_iconUrl);
}
if(animal.topVoters.size()>=2){
sec_contri_tv.setText(""+animal.topVoters.get(1).give_ticket_num);
loadUserIcon(sec_iv, animal.topVoters.get(1).u_iconUrl);
}
if(animal.topVoters.size()>=3){
third_contri_tv.setText(""+animal.topVoters.get(2).give_ticket_num);
loadUserIcon(third_iv, animal.topVoters.get(2).u_iconUrl);
}
if(animal.topVoters.size()>=3){
}else if(animal.topVoters.size()>=2){
RelativeLayout.LayoutParams param=(RelativeLayout.LayoutParams)whit_frame_layout.getLayoutParams();
if(param!=null){
param.height=param.height-getResources().getDimensionPixelOffset(R.dimen.one_dip)*36;
whit_frame_layout.setLayoutParams(param);
}
third_layout.setVisibility(View.GONE);
}else if(animal.topVoters.size()>=1){
RelativeLayout.LayoutParams param=(RelativeLayout.LayoutParams)whit_frame_layout.getLayoutParams();
if(param!=null){
param.height=param.height-getResources().getDimensionPixelOffset(R.dimen.one_dip)*36*2;
whit_frame_layout.setLayoutParams(param);
}
sec_layout.setVisibility(View.GONE);
third_layout.setVisibility(View.GONE);
}
}
BitmapFactory.Options options2=new BitmapFactory.Options();
options2.inJustDecodeBounds=false;
options2.inSampleSize=4;
options2.inPreferredConfig=Bitmap.Config.RGB_565;
options2.inPurgeable=true;
options2.inInputShareable=true;
DisplayImageOptions displayImageOptions3=new DisplayImageOptions
.Builder()
.showImageOnLoading(R.drawable.pet_icon)
.showImageOnFail(R.drawable.pet_icon)
.cacheInMemory(false)
.cacheOnDisc(false)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
// .decodingOptions(options2)
.build();
ImageLoader imageLoader3=ImageLoader.getInstance();
int w=getResources().getDimensionPixelSize(R.dimen.one_dip)*72;
LogUtil.i("mi", "头像::"+Constants.ANIMAL_THUBMAIL_DOWNLOAD_TX+animal.pet_iconUrl+"@"+w+"w_"+w+"h_0l.jpg");
imageLoader3.displayImage(Constants.ANIMAL_THUBMAIL_DOWNLOAD_TX+animal.pet_iconUrl+"@"+w+"w_"+w+"h_0l.jpg", iconIv, displayImageOptions3);
ImageFetcher imageFetcher=new ImageFetcher(this, 0);
int h=Constants.screen_height-getResources().getDimensionPixelSize(R.dimen.one_dip)*52;
w=Constants.screen_width-getResources().getDimensionPixelSize(R.dimen.one_dip)*52;
imageFetcher.IP=imageFetcher.UPLOAD_THUMBMAIL_IMAGE;
imageFetcher.setImageCache(new ImageCache(this, animal.votePicture.url+"@"+w+"w_"+h+"h_"+"1l.jpg"));
imageFetcher.setLoadCompleteListener(new LoadCompleteListener() {
@Override
public void onComplete(Bitmap bitmap) {
// TODO Auto-generated method stub
}
@Override
public void getPath(String path) {
// TODO Auto-generated method stub
File f=new File(path);
animal.votePicture.petPicture_path=path;
}
});
imageFetcher.loadImage(animal.votePicture.url+"@"+w+"w_"+h+"h_"+"1l.jpg", new ImageView(this), /*options*/null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.close_iv:
if(isTaskRoot()){
if(HomeActivity.homeActivity!=null){
Intent intent=HomeActivity.homeActivity.getIntent();
if(intent!=null){
this.startActivity(intent);
finish();
return;
}
ActivityManager am=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
am.moveTaskToFront(HomeActivity.homeActivity.getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
}else{
Intent intent=new Intent(this,HomeActivity.class);
this.startActivity(intent);
}
}
userCardActivity=null;
this.finish();
System.gc();
break;
case R.id.user_icon:
if(NewPetKingdomActivity.petKingdomActivity!=null){
if(NewPetKingdomActivity.petKingdomActivity.loadedImage1!=null&&!NewPetKingdomActivity.petKingdomActivity.loadedImage1.isRecycled()){
NewPetKingdomActivity.petKingdomActivity.loadedImage1.recycle();
}
NewPetKingdomActivity.petKingdomActivity.loadedImage1=null;
NewPetKingdomActivity.petKingdomActivity.finish();
NewPetKingdomActivity.petKingdomActivity=null;
}
Intent intent=new Intent(this,NewPetKingdomActivity.class);
intent.putExtra("animal",animal);
startActivity(intent);
break;
case R.id.button_tv:
Intent intent2=new Intent(this,ShareActivity.class);
animal.votePicture.animal_totals_stars=animal.total_votes;
animal.votePicture.end_time=banner.end_time;
intent2.putExtra("PetPicture",animal.votePicture);
this.startActivity(intent2);
break;
case R.id.goTicketTv:
Intent in=new Intent(this,RecommendActivity.class);
in.putExtra("PetPicture", animal.votePicture);
in.putExtra("star_id", banner.star_id);
in.putExtra("star_title", banner.name);
in.putExtra("gold", gold);
this.startActivity(in);
break;
case R.id.first_iv:
Intent in2=new Intent(this,UserCardActivity.class);
in2.putExtra("user",animal.topVoters.get(0));
startActivity(in2);
break;
case R.id.sec_iv:
Intent in3=new Intent(this,UserCardActivity.class);
in3.putExtra("user",animal.topVoters.get(1));
startActivity(in3);
break;
case R.id.third_iv:
Intent in4=new Intent(this,UserCardActivity.class);
in4.putExtra("user",animal.topVoters.get(2));
startActivity(in4);
break;
}
}
public void loadUserIcon(ImageView iv,String url){
BitmapFactory.Options options2=new BitmapFactory.Options();
options2.inJustDecodeBounds=false;
options2.inSampleSize=4;
options2.inPreferredConfig=Bitmap.Config.RGB_565;
options2.inPurgeable=true;
options2.inInputShareable=true;
DisplayImageOptions displayImageOptions3=new DisplayImageOptions
.Builder()
.showImageOnLoading(R.drawable.user_icon)
.showImageOnFail(R.drawable.user_icon)
.cacheInMemory(false)
.cacheOnDisc(false)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
// .decodingOptions(options2)
.build();
ImageLoader imageLoader3=ImageLoader.getInstance();
int w=getResources().getDimensionPixelSize(R.dimen.one_dip)*54;
imageLoader3.displayImage(Constants.USER_THUBMAIL_DOWNLOAD_TX+url+"@"+w+"w_"+w+"h_0l.jpg", iv, displayImageOptions3);
}
}
|
package com.javaguru.studentservice.student.validation;
import com.javaguru.studentservice.core.exceptions.ItemNotFoundException;
public class StudentNotFoundException extends ItemNotFoundException {
public StudentNotFoundException(String message) {
super(StudentValidationMSG.STUDENT_NOT_FOUND);
}
}
|
package utilities;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.testng.Reporter;
public class GetPropVals {
public String getPropValue(String key) {
String result = "";
String propFileName = "";
InputStream inputStream = null;
try {
Properties prop = new Properties();
propFileName = "./data/config.properties";
inputStream = new FileInputStream(propFileName);
//inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
// inputStream = getClass().getResourceAsStream(propFileName);
prop.load(inputStream);
//Date time = new Date(System.currentTimeMillis());
// get the property value and print it out
result = prop.getProperty(key);
//String MOUrl = prop.getProperty("MOUrl");
//String DDUrl = prop.getProperty("DDUrl");
//String company3 = prop.getProperty("company3");
//result = "URL List = " + SITUrl + ", " + MOUrl + ", " + DDUrl;
//System.out.println(result + "\nProgram Ran on " + time);
return result;
} catch (IOException e) {
Reporter.log("<p><font face='verdana' color='red'>Error: Failed to get property value for key '" + key + "' from file '" + propFileName + "'.</font>");
try {
throw (e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
// finally {
// if (inputStream != null) {
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
return result;
}
}
|
package com.example.kibsoft.MyFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {@link Fragment} subclass.
*/
public class FragmentOne extends Fragment {
public FragmentOne() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_one, container, false);
final EditText userName = (EditText)view.findViewById(R.id.etName);
EditText userAge = (EditText)view.findViewById(R.id.etAge);
EditText userOccupation = (EditText)view.findViewById(R.id.etOccupation);
TextView textView= (TextView)view.findViewById(R.id.tvDisplay);
final Button bDisplay =view.findViewById(R.id.bTry);
bDisplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bDisplay.setText("Hello");
Toast.makeText(getContext(), "Anii: "+userName.getText().toString()+"", Toast.LENGTH_SHORT).show();
}
});
// Inflate the layout for this fragment
return view;
}
}
|
package jianzhioffer;
import jianzhioffer.utils.ListNode;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @ClassName : Solution25_2
* @Description : 合并 k 个排序链表
* leetcode 23: 返回合并后的排序链表。请分析和描述算法的复杂度。
* 字节手撕
*
* 方法1:暴力法
* 找出所有节点,放到一个数组中,对这个数组进行排序,然后遍历
*
* 方法2:优先队列
* 时间复杂度:O(n*log(k))O(n∗log(k)),n 是所有链表中元素的总和,k 是链表个数。
*
* 方法3:分冶
* 链表两两合并
*
* @Date : 2019/9/16 14:12
*/
public class Solution25_2 {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null || lists.length==0)
return null;
PriorityQueue<ListNode> queue=new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val-o2.val;
}
});
ListNode headFirst=new ListNode(-1);
ListNode head=headFirst;
//首先将各个链表的头节点加到优先队列中,先排一次
for (ListNode node:lists){
if (node!=null)
queue.add(node);
}
while (!queue.isEmpty()){
head.next=queue.poll(); //从优先队列中拿出最小的
head=head.next;
if (head.next!=null)
queue.add(head.next); //然后将拿出的这个的next放入优先队列
}
return headFirst.next;
}
//分冶
public ListNode mergeKLists2(ListNode[] lists) {
if (lists==null || lists.length==0)
return null;
return merge(lists,0,lists.length-1);
}
private ListNode merge(ListNode[] lists, int left, int right) {
if (left==right)
return lists[left];
int mid=left+(right-left)>>1;
ListNode l1=merge(lists,left,mid);
ListNode l2=merge(lists,mid+1,right);
return mergeTwoList(l1,l2);
}
private ListNode mergeTwoList(ListNode l1, ListNode l2) {
if (l1==null)
return l2;
if (l2==null)
return l1;
if (l1.val<l2.val){
l1.next=mergeTwoList(l1.next,l2);
return l2;
}else{
l2.next=mergeTwoList(l1,l2.next);
return l2;
}
}
}
|
package com.sun.xml.bind.v2.model.impl;
import com.sun.xml.bind.v2.model.core.PropertyKind;
import com.sun.xml.bind.v2.model.core.ValuePropertyInfo;
/**
* @author Kohsuke Kawaguchi
*/
class ValuePropertyInfoImpl<TypeT,ClassDeclT,FieldT,MethodT>
extends SingleTypePropertyInfoImpl<TypeT,ClassDeclT,FieldT,MethodT>
implements ValuePropertyInfo<TypeT,ClassDeclT> {
ValuePropertyInfoImpl(
ClassInfoImpl<TypeT,ClassDeclT,FieldT,MethodT> parent,
PropertySeed<TypeT,ClassDeclT,FieldT,MethodT> seed) {
super(parent,seed);
}
public PropertyKind kind() {
return PropertyKind.VALUE;
}
}
|
// Date: 4/29/2015 10:08:14 PM
// Template version 1.1
// Java generated by Techne
// Keep in mind that you still need to fill in some blanks
// - ZeuX
package org.bitbucket.alltra101ify.advancedsatelliteutilization.models.blockmodel;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
public class ModelCoreStabilizer extends ModelBase
{
//fields
ModelRenderer BaseB;
ModelRenderer BaseT;
ModelRenderer MiddleStabilizer;
public ModelRenderer Support1;
public ModelRenderer Support2;
public ModelRenderer Support4;
public ModelRenderer Support3;
public ModelCoreStabilizer()
{
textureWidth = 64;
textureHeight = 64;
BaseB = new ModelRenderer(this, 0, 0);
BaseB.addBox(0F, 0F, 0F, 16, 3, 16);
BaseB.setRotationPoint(-8F, 21F, -8F);
BaseB.setTextureSize(64, 64);
BaseB.mirror = true;
setRotation(BaseB, 0F, 0F, 0F);
BaseT = new ModelRenderer(this, 0, 19);
BaseT.addBox(0F, 0F, 0F, 16, 3, 16);
BaseT.setRotationPoint(-8F, 8F, -8F);
BaseT.setTextureSize(64, 64);
BaseT.mirror = true;
setRotation(BaseT, 0F, 0F, 0F);
MiddleStabilizer = new ModelRenderer(this, 16, 38);
MiddleStabilizer.addBox(0F, 0F, 0F, 2, 10, 2);
MiddleStabilizer.setRotationPoint(-1F, 11F, -1F);
MiddleStabilizer.setTextureSize(64, 64);
MiddleStabilizer.mirror = true;
setRotation(MiddleStabilizer, 0F, 0F, 0F);
Support1 = new ModelRenderer(this, 34, 38);
Support1.addBox(5F, 0F, -2F, 1, 10, 4);
Support1.setRotationPoint(0F, 11F, 0F);
Support1.setTextureSize(64, 64);
Support1.mirror = true;
setRotation(Support1, 0F, 0F, 0F);
Support2 = new ModelRenderer(this, 54, 38);
Support2.addBox(-6F, 0F, -2F, 1, 10, 4);
Support2.setRotationPoint(0F, 11F, 0F);
Support2.setTextureSize(64, 64);
Support2.mirror = true;
setRotation(Support2, 0F, 0F, 0F);
Support4 = new ModelRenderer(this, 44, 38);
Support4.addBox(-2F, 0F, 5F, 4, 10, 1);
Support4.setRotationPoint(0F, 11F, 0F);
Support4.setTextureSize(64, 64);
Support4.mirror = true;
setRotation(Support4, 0F, 0F, 0F);
Support3 = new ModelRenderer(this, 24, 38);
Support3.addBox(-2F, 0F, -6F, 4, 10, 1);
Support3.setRotationPoint(0F, 11F, 0F);
Support3.setTextureSize(64, 64);
Support3.mirror = true;
setRotation(Support3, 0F, 0F, 0F);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
BaseB.render(f5);
BaseT.render(f5);
MiddleStabilizer.render(f5);
Support1.render(f5);
Support2.render(f5);
Support4.render(f5);
Support3.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void renderModel(float f) {
BaseB.render(f);
BaseT.render(f);
MiddleStabilizer.render(f);
Support1.render(f);
Support2.render(f);
Support4.render(f);
Support3.render(f);
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity)
{
super.setRotationAngles(f, f1, f2, f3, f4, f5, entity);
}
}
|
/*
* 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 controller;
import DAO.pesanDAO;
import KeretaApi.DataKereta;
import KeretaApi.Menu;
import KeretaApi.PesanTiket;
import enkapsulasi.enkapsulasiLoket;
import enkapsulasi.enkapsulasiPesan;
import implement.implementPesan;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.List;
import javax.swing.JOptionPane;
import tabel.TabelPesan;
/**
*
* @author ASUS
*/
public class pesanController {
Dimension layar = Toolkit.getDefaultToolkit().getScreenSize();
private List<enkapsulasiPesan> List;
private static PesanTiket pesanPanel;
private static implementPesan implementPesan;
public pesanController(PesanTiket pesanPanel) {
this.pesanPanel = pesanPanel;
implementPesan = new pesanDAO();
lokasiform();
Tabel();
}
public void lokasiform(){
int x = layar.width / 2 -pesanPanel.getSize().width / 2;
int y = layar.height / 2 - pesanPanel.getSize().height / 2;
pesanPanel.setLocation(x, y);
}
//untuk menyimpan data
public void save(){
String nik = null;
String nama = null;
String alamat = null;
String gender = null;
String telepon = null;
if (pesanPanel.getNik2().getText().toString().equals("")){
nik = "null";
}else{
nik = pesanPanel.getNik2().getText().toString();
}
if (pesanPanel.getNama2().getText().toString().equals("")){
nama = "null";
}else{
nama = pesanPanel.getNama2().getText().toString();
}
if (pesanPanel.getAlamat2().getText().toString().equals("")){
alamat = "null";
}else{
alamat = pesanPanel.getAlamat2().getText().toString();
}
if (pesanPanel.getCbgender2().getSelectedItem().toString().equals("")){
gender = "null";
}else{
gender = pesanPanel.getCbgender2().getSelectedItem().toString();
}
if (pesanPanel.getTelepon2().getText().toString().equals("")){
telepon = "null";
}else{
telepon = pesanPanel.getTelepon2().getText().toString();
}
if (implementPesan.save(nik, nama, alamat, gender, telepon)){
JOptionPane.showMessageDialog(null, "Data Telah Ditambahkan");
Tabel();
}else{
JOptionPane.showMessageDialog(null, "Data Gagal Ditambahkan");
}
}
//untuk menghapus data
public void tombolDelete(){
if(implementPesan.delete(pesanPanel.getNik2().getText().toString())){
JOptionPane.showMessageDialog(null, "Data Telah Dihapus");
Tabel();
}else{
JOptionPane.showMessageDialog(null, "Data Gagal Dihapus");
}
}
//untuk mencari data
public void tombolSearch(){
String nik = null;
String nama = null;
String alamat = null;
String gender = null;
String telepon = null;
if (pesanPanel.getNik2().getText().toString().equals("")){
nik = "null";
}else{
nik = pesanPanel.getNik2().getText().toString();
}
if (pesanPanel.getNama2().getText().toString().equals("")){
nama = "null";
}else{
nama = pesanPanel.getNama2().getText().toString();
}
if (pesanPanel.getAlamat2().getText().toString().equals("")){
alamat = "null";
}else{
alamat = pesanPanel.getAlamat2().getText().toString();
}
if (pesanPanel.getCbgender2().getSelectedItem().toString().equals("")){
gender = "null";
}else{
gender = pesanPanel.getCbgender2().getSelectedItem().toString();
}
if (pesanPanel.getTelepon2().getText().toString().equals("")){
telepon = "null";
}else{
telepon = pesanPanel.getTelepon2().getText().toString();
}
List = implementPesan.search(nik, nama, alamat, gender, telepon);
pesanPanel.getTabelpesan().setModel(new TabelPesan(List));
JOptionPane.showMessageDialog(null,"Data Ditemukan");
//komponen("cari");
}
public void tombolUpdate(){
String nik = pesanPanel.getNik2().getText().toString();
String nama = pesanPanel.getNama2().getText().toString();
String alamat = pesanPanel.getAlamat2().getText().toString();
String gender = pesanPanel.getCbgender2().getSelectedItem().toString();
String telepon = pesanPanel.getTelepon2().getText().toString();
if (implementPesan.update(nik, nama, alamat, gender, telepon)) {
JOptionPane.showMessageDialog(null,"Data Berhasil Di Update");
Tabel();
} else {
JOptionPane.showMessageDialog(null, "Data gagal Diubah");
}
}
public void tombolReset(){
pesanPanel.getNik2().setText(null);
pesanPanel.getNama2().setText(null);
pesanPanel.getAlamat2().setText(null);
pesanPanel.getCbgender2().setSelectedItem("---");
pesanPanel.getTelepon2().setText(null);
}
public void klikTabel(java.awt.event.MouseEvent evt){
try {
int row = pesanPanel.getTabelpesan().rowAtPoint(evt.getPoint());
String nik = pesanPanel.getTabelpesan().getValueAt(row, 0).toString();
String nama = pesanPanel.getTabelpesan().getValueAt(row, 1).toString();
String alamat = pesanPanel.getTabelpesan().getValueAt(row, 2).toString();
String gender = pesanPanel.getTabelpesan().getValueAt(row, 3).toString();
String telepon = pesanPanel.getTabelpesan().getValueAt(row, 4).toString();
pesanPanel.getNik2().setText(String.valueOf(nik));
pesanPanel.getNama2().setText(String.valueOf(nama));
pesanPanel.getAlamat2().setText(String.valueOf(alamat));
pesanPanel.getCbgender2().setSelectedItem(String.valueOf(gender));
pesanPanel.getTelepon2().setText(String.valueOf(telepon));
} catch (Exception e) {
e.printStackTrace();
}
}
public void Tabel (){
List = implementPesan.getAllPesan();
pesanPanel.getTabelpesan().setModel(new TabelPesan(List));
}
public void tombolNext(){
enkapsulasiLoket.setSession_nik(pesanPanel.getNik2().getText());
enkapsulasiLoket.setSession_nama(pesanPanel.getNama2().getText());
new DataKereta().setVisible(true);
pesanPanel.setVisible(false);
}
public void tombolBack(){
new Menu().setVisible(true);
pesanPanel.setVisible(false);
}
public void Menu(){
new Menu().setVisible(true);
pesanPanel.setVisible(false);
}
public void DataKereta(){
new DataKereta().setVisible(true);
pesanPanel.setVisible(false);
}
}
|
package org.sdrc.collect.uphpmis.android.listeners;
import java.util.HashMap;
/**
* @author Ratikanta Pradhan (ratikanta@sdrc.co.in)
*/
public interface FetchAreaForXForm {
void fetchingAreaForXFormComplete(HashMap<Integer, String> result);
}
|
package Client;
import Dao.model.BuyGoods;
import Dao.model.SaleGoods;
import Dao.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpSession;
/**
* Created by Administrator on 2014/9/10 0010.
*/
@Controller
public class ShowTradeClient {
private static Logger logger = LoggerFactory.getLogger(ShowTradeClient.class);
@RequestMapping(value = "/showTrade",method = RequestMethod.GET)
public String showPersonalPage(ModelMap modelMap,HttpSession httpSession){
int userId = (Integer)httpSession.getAttribute("userId");
User user = new RestTemplate().getForObject(
"http://localhost:8080/user/info/{userId}",User.class,userId);
modelMap.addAttribute("user",user);
return "personalCenter";
}
@RequestMapping(value = "/showTradePage",method = RequestMethod.GET)
@ResponseBody
public SaleGoods[] showPublished(ModelMap model,
HttpSession httpSession){
int userId = (Integer)httpSession.getAttribute("userId");
model.addAttribute(new User());
SaleGoods[] saleGoodses = new RestTemplate().getForObject(
"http://localhost:8080/publishedInfo/saleGoods/{userId}",SaleGoods[].class,userId);
BuyGoods[] buyGoodses = new RestTemplate().getForObject(
"http://localhost:8080/publishedInfo/buyGoods/{userId}",BuyGoods[].class,userId);
return saleGoodses;
// model.addAttribute("saleGoodsList",saleGoodses);
// return "personalCenter";
}
}
|
package com.example.qobel.organizator;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Intent intent;
String[] permissions = new String[]{
Manifest.permission.INTERNET,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.VIBRATE,
Manifest.permission.RECORD_AUDIO,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this,LoginActivity.class);
this.getPermissions();
Button button = (Button) findViewById(R.id.loginMainButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(intent);
}
});
}
public void getPermissions(){
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//Log.v(TAG,"Permission is granted");
//return true;
} else {
//Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
//return false;
}
if (checkSelfPermission(android.Manifest.permission.INTERNET)
== PackageManager.PERMISSION_GRANTED) {
//Log.v(TAG,"Permission is granted");
//return true;
} else {
//Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 1);
//return false;
}
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//Log.v(TAG,"Permission is granted");
//return true;
} else {
//Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
//return false;
}
if (checkSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
== PackageManager.PERMISSION_GRANTED) {
//Log.v(TAG,"Permission is granted");
//return true;
} else {
//Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, 1);
//return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
//Log.v(TAG,"Permission is granted");
//return true;
}
}
}
|
package com.example.androidproject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
public class NotesAdapter extends ArrayAdapter {
Context mContext;
int layoutRes;
List<Notesdata> Notes;
// SQLiteDatabase mDatabase;
DatabaseHelper mDatabase;
public NotesAdapter(Context mContext, int layoutRes, List<Notesdata> Notes, DatabaseHelper mDatabase) {
super(mContext, layoutRes, Notes);
this.mContext = mContext;
this.layoutRes = layoutRes;
this.Notes = Notes;
this.mDatabase = mDatabase;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(layoutRes, null);
TextView title = v.findViewById(R.id.notes);
TextView DateTime = v.findViewById(R.id.dateTime);
final Notesdata notesdata = Notes.get(position);
title.setText(notesdata.getNotesTitle());
DateTime.setText(notesdata.getDate());
v.findViewById(R.id.listLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(mContext, NotesDetail.class);
i.putExtra("OBJ",notesdata);
mContext.startActivity(i);
}
});
v.findViewById(R.id.btn_delete_note).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteNote(notesdata);
}
});
return v;
}
private void deleteNote(final Notesdata notesdata) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mDatabase.deleteNote(notesdata.getId()))
loadNotesTitle(notesdata.getCategory());
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void loadNotesTitle(String cat) {
Cursor cursor = mDatabase.getAllNotes(cat);
System.out.println(Notes.size());
Notes.clear();
System.out.println(Notes.size());
if (cursor.moveToFirst()) {
do {
Notes.add(new Notesdata(
cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4),
cursor.getDouble(5),
cursor.getDouble(6),
cursor.getString(7)
));
System.out.println(Notes.size());
} while (cursor.moveToNext());
cursor.close();
}
System.out.println(Notes.size());
notifyDataSetChanged();
System.out.println(Notes.size());
}
}
|
import java.awt.Color;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageGrab {
private Robot bot;
private Rectangle chatLoc = new Rectangle();
public ImageGrab () {
this.bot = ArkBot.bot;
chatLoc.setBounds(12, 260, 450, 140);
}
public void Grab(Rectangle loc) {
BufferedImage img = bot.createScreenCapture(loc);
try {
ImageIO.write(img, "png", new File("ArkBotFiles/OCRImages/ImageGrab/grab.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void WhiteConvert() {
BufferedImage inputFile = null;
try {
inputFile = ImageIO.read(new File("ArkBotFiles/OCRImages/ImageGrab/grab.png"));
} catch (IOException e) {
e.printStackTrace();
}
for (int x = 0; x < inputFile.getWidth(); x++) {
for (int y = 0; y < inputFile.getHeight(); y++) {
int rgba = inputFile.getRGB(x, y);
Color col = new Color(rgba, true);
int wl = 182;
if (col.getRed() > wl && col.getGreen() > wl && col.getBlue() > wl) {
col = new Color(0, 0, 0);
} else {
col = new Color(255,255,255);
}
inputFile.setRGB(x, y, col.getRGB());
}
}
try {
File outputFile = new File("ArkBotFiles/OCRImages/ImageGrab/grabConvert.png");
ImageIO.write(inputFile, "png", outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void CyanConvert() {
BufferedImage inputFile = null;
try {
inputFile = ImageIO.read(new File("ArkBotFiles/OCRImages/ImageGrab/grab.png"));
} catch (IOException e) {
e.printStackTrace();
}
for (int x = 0; x < inputFile.getWidth(); x++) {
for (int y = 0; y < inputFile.getHeight(); y++) {
int rgba = inputFile.getRGB(x, y);
Color col = new Color(rgba, true);
if (col.getRed() == 0 && col.getGreen() > 250 && col.getBlue() > 250) {
col = new Color(0, 0, 0);
} else {
col = new Color(255,255,255);
}
inputFile.setRGB(x, y, col.getRGB());
}
}
try {
File outputFile = new File("ArkBotFiles/OCRImages/ImageGrab/grabConvert.png");
ImageIO.write(inputFile, "png", outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void GPSConvert() {
BufferedImage inputFile = null;
try {
inputFile = ImageIO.read(new File("ArkBotFiles/OCRImages/GPS/GPS5.png"));
} catch (IOException e) {
e.printStackTrace();
}
for (int x = 0; x < inputFile.getWidth(); x++) {
for (int y = 0; y < inputFile.getHeight(); y++) {
int rgba = inputFile.getRGB(x, y);
Color col = new Color(rgba, true);
int rl = 150;
int ul = 100;
int ll = 0;
int bl = 20;
if (col.getRed() > rl &&
col.getGreen() > ll && col.getGreen() < ul &&
col.getBlue() < bl) {
col = new Color(0, 0, 0);
} else {
col = new Color(255,255,255);
}
inputFile.setRGB(x, y, col.getRGB());
}
}
try {
File outputFile = new File("ArkBotFiles/OCRImages/ImageGrab/GPS5C.png");
ImageIO.write(inputFile, "png", outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.example.customcitydatabase;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
/**
* 定义DBManager类,用于事先从工程项目中导入数据库到手机
* 和用于返回一个SQLiteDatebase的实例给DBHelper
* @author Administrator
*
*/
public class DBManager {
private Context context;
private SQLiteDatabase database;
public static final String DB_NAME="cityid.db";//数据库名称
public static final String PACKAGE_NAME="com.example.customcitydatabase";//包名
public static final String DB_PATH="/data"+Environment.getDataDirectory().getAbsolutePath()
+"/"+PACKAGE_NAME;//数据库在手机里的路径,还没包含名称
public DBManager(Context context) {
this.context=context;
}
public SQLiteDatabase getDatabase(){
return this.database;
}
public void openDatabase(){
String dbFile=DB_PATH+"/"+DB_NAME;//数据库完整路径
try{
if(!new File(dbFile).exists()){//打开dbFile文件,如果不存在,就执行导入
InputStream in=context.getResources().openRawResource(R.raw.cityid);
//数据库文件放在工程项目的res/raw文件夹下
FileOutputStream fos=new FileOutputStream(dbFile);
byte[] buffer=new byte[1024];
int count=0;
while((count=in.read(buffer))>0){
fos.write(buffer, 0, count);
//从项目的raw文件夹下读取数据库资源然后写入到手机里dbFile路径下
}
fos.close();
in.close();
}
database=SQLiteDatabase.openOrCreateDatabase(dbFile, null);
}catch(FileNotFoundException e){
Log.v("customdatabase", "File not found!");
e.printStackTrace();
}catch(IOException e){
Log.v("customdatabase", "IOException");
e.printStackTrace();
}
}
public void closeDatabase(){
database.close();
}
}
|
package com.worldchip.bbpaw.media.camera.activity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.worldchip.bbpaw.media.camera.R;
import com.worldchip.bbpaw.media.camera.Interface.CameraInterface;
import com.worldchip.bbpaw.media.camera.utils.CameraConfig;
import com.worldchip.bbpaw.media.camera.utils.CameraManager;
import com.worldchip.bbpaw.media.camera.utils.CameraUtils;
import com.worldchip.bbpaw.media.camera.utils.Configure;
import com.worldchip.bbpaw.media.camera.utils.EffectData;
import com.worldchip.bbpaw.media.camera.utils.ImageTool;
import com.worldchip.bbpaw.media.camera.utils.LogUtil;
import com.worldchip.bbpaw.media.camera.utils.MediaRecordManager;
import com.worldchip.bbpaw.media.camera.utils.ScannerClient;
import com.worldchip.bbpaw.media.camera.utils.SimpleAudioPlayer;
import com.worldchip.bbpaw.media.camera.utils.Utils;
import com.worldchip.bbpaw.media.camera.view.CameraPreview;
import com.worldchip.bbpaw.media.camera.view.DMEffectsListAdapter;
import com.worldchip.bbpaw.media.camera.view.EffectListAdapter;
import com.worldchip.bbpaw.media.camera.view.EffectsView;
import com.worldchip.bbpaw.media.camera.view.GlobalAlertDialog;
public class CameraActivity extends Activity implements OnClickListener,
CameraInterface, OnErrorListener, OnInfoListener {
private static final String TAG = CameraActivity.class.getSimpleName();
// private SurfaceView mSurfaceView;
private CameraPreview mCameraPreview;
private EffectsView mEffectDrawView = null;
// private SurfaceHolder mSurfaceHolder;
private ImageView[] mToolImageViews = new ImageView[5];
private ImageView[] mToolImageBgViews = new ImageView[5];
private ImageView[] mEfficacyViews = new ImageView[5];
private ImageView[] mEfficacyBgViews = new ImageView[5];
private ImageView mCameraConvBtn;
private ImageView mBackBtn;
private ImageView mCenterShutterView;
private static final int CAMERA_MODE_INDEX = 0;
private static final int GALLERY_INDEX = 1;
private static final int SAVE_INDEX = 2;
private static final int SHUTTER_INDEX = 3;
private static final int MAGIC_INDEX = 4;
private static final int GENERAL_EFFECT_INDEX = 0;
private static final int DISTORTING_EFFECT_INDEX = 1;
private static final int INDIVIDUALITY_EFFECT_INDEX = 2;
private static final int GRAFFITI_EFFECT_INDEX = 3;
private static final int ACCESSORIES_EFFECT_INDEX = 4;
private int mCurrCameraFacing = CameraConfig.DEFAULT_CAMERA_FACING;
private int mCameraMode = CameraConfig.DEFAULT_CAMERA_MODE;
private MediaRecordManager mMediaRecordManager;
private PopupWindow mSpecialEfficacyPop;
private PopupWindow mEffectListPop;
private PopupWindow mDMEffectListPop;
private View mEffectListView;
private View mDMEffectListView;
private GridView mEffectGridView;
private EffectListAdapter mEffectAdapter;
private View mEfficacyRL;
private View mRightToolViews;
private boolean isEditState = false;
private ImageView mSwitchCamera;
private boolean isStartDefCamera = false;
// private Bitmap mFinalPic = null;
// private View mMainView;
public enum SpecicalEfficacy {
GENERAL, DISTORTING, INDIVIDUALITY, GRAFFITI, ACCESSORIES
}
/**
* CONVEXMIRROR1 凸镜效果 CONVEXMIRROR2 凹镜效果 DEFORM 变形效果
*
* @author Administrator
*
*/
public enum DistortingMirrorEffects {
CONVEXMIRROR1, CONVEXMIRROR2, DEFORM
}
public SpecicalEfficacy mEffectMode = SpecicalEfficacy.GENERAL;
public DistortingMirrorEffects mDistortingMirror = DistortingMirrorEffects.CONVEXMIRROR1;
private static final int UPDATE_RECORD_TIMER = 1;
private Timer mRecordTimer;
private RecordTimerTask mRecordTimerTask;
private int mRecordTimeCount = 0;
private TextView mRecoedTimeTV;
private DMEffectsListAdapter mDmEffectsAdapter = null;
private MyOrientationEventListener mOrientationListener = null;
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private boolean mHasEfficacyBeforShutter = false;
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case UPDATE_RECORD_TIMER:
boolean ongoing = (mCameraMode == CameraConfig.CAMERA_VIDEO_MODE);
if (ongoing) {
String timeStr = String.format(
getResources().getString(R.string.timer_format),
mRecordTimeCount / 3600,
(mRecordTimeCount % 3600) / 60,
mRecordTimeCount % 60);
mRecordTimeCount++;
if (mRecoedTimeTV != null) {
mRecoedTimeTV.setText(timeStr);
}
}
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mMediaRecordManager = MediaRecordManager.getInstance(this);
mMediaRecordManager.setOnInfoListener(this);
mMediaRecordManager.setOnErrorListener(this);
mOrientationListener = new MyOrientationEventListener(this);
if (!new File(CameraConfig.POTOS_FILES_PATH).exists()) {
new File(CameraConfig.POTOS_FILES_PATH).mkdirs();
}
Configure.init(this);
initViews();
initPreView();
initEfficacyViews();
initEffectListView();
hideSystemUI(this, true);
}
/**
* 隐藏菜单
*
* @param context
* @param flag
*/
public static void hideSystemUI(Context context, boolean flag) {
Intent intent = new Intent();
intent.setAction("cn.worldchip.www.UPDATE_SYSTEMUI");
intent.putExtra("hide_systemui", flag);
context.sendBroadcast(intent);
}
private void initViews() {
// TODO Auto-generated method stub
// mMainView = findViewById(R.id.camera_main_layout);
mRightToolViews = findViewById(R.id.right_tool_views);
mToolImageViews[CAMERA_MODE_INDEX] = (ImageView) findViewById(R.id.camera_mode);
mToolImageViews[GALLERY_INDEX] = (ImageView) findViewById(R.id.gallery_btn);
mToolImageViews[SAVE_INDEX] = (ImageView) findViewById(R.id.save_btn);
//mToolImageViews[SAVE_INDEX].setEnabled(false);
mToolImageViews[SHUTTER_INDEX] = (ImageView) findViewById(R.id.shutter_btn);
mToolImageViews[MAGIC_INDEX] = (ImageView) findViewById(R.id.magic_btn);
mToolImageBgViews[CAMERA_MODE_INDEX] = (ImageView) findViewById(R.id.camera_mode_bg);
//mToolImageBgViews[GALLERY_INDEX] = (ImageView) findViewById(R.id.gallery_bg);
mToolImageBgViews[SAVE_INDEX] = (ImageView) findViewById(R.id.save_bg);
mToolImageBgViews[SHUTTER_INDEX] = (ImageView) findViewById(R.id.shutter_bg);
mToolImageBgViews[MAGIC_INDEX] = (ImageView) findViewById(R.id.magic_bg);
mCameraConvBtn = (ImageView) findViewById(R.id.camera_converion);
if (CameraManager.isDoubleCamera()) {
mCameraConvBtn.setVisibility(View.VISIBLE);
} else {
mCameraConvBtn.setVisibility(View.GONE);
}
mBackBtn = (ImageView) findViewById(R.id.main_back_btn);
mCenterShutterView = (ImageView) findViewById(R.id.iv_center_shutter);
mSwitchCamera = (ImageView) findViewById(R.id.main_switch_camera_btn);
mToolImageViews[CAMERA_MODE_INDEX].setOnClickListener(this);
mToolImageViews[GALLERY_INDEX].setOnClickListener(this);
mToolImageViews[SAVE_INDEX].setOnClickListener(this);
mToolImageViews[SHUTTER_INDEX].setOnClickListener(this);
mToolImageViews[MAGIC_INDEX].setOnClickListener(this);
mCameraConvBtn.setOnClickListener(this);
mBackBtn.setOnClickListener(this);
mSwitchCamera.setOnClickListener(this);
updateCameraMode(mCameraMode);
mEffectDrawView = (EffectsView) findViewById(R.id.camera_effect_view);
// mEffectDrawView.setVisibility(View.INVISIBLE);
updateEffectMode(SpecicalEfficacy.GENERAL);
mRecoedTimeTV = (TextView) findViewById(R.id.video_record_timer);
Typeface typeFace = Typeface.createFromAsset(getAssets(),
"fonts/COMIC.TTF");
mRecoedTimeTV.setTypeface(typeFace);
}
private void initEfficacyViews() {
mEfficacyRL = LayoutInflater.from(this).inflate(
R.layout.special_efficacy_pop_layout, null);
mEfficacyViews[GENERAL_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.general_effect_img);
mEfficacyViews[DISTORTING_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.distorting_effect_btn);
mEfficacyViews[INDIVIDUALITY_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.individuality_effect_btn);
mEfficacyViews[GRAFFITI_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.graffiti_effect_btn);
mEfficacyViews[ACCESSORIES_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.accessories_effect_btn);
mEfficacyRL.findViewById(R.id.general_effect_btn).setOnClickListener(
this);
mEfficacyViews[DISTORTING_EFFECT_INDEX].setOnClickListener(this);
mEfficacyViews[INDIVIDUALITY_EFFECT_INDEX].setOnClickListener(this);
mEfficacyViews[GRAFFITI_EFFECT_INDEX].setOnClickListener(this);
mEfficacyViews[GRAFFITI_EFFECT_INDEX].setEnabled(false);
mEfficacyViews[ACCESSORIES_EFFECT_INDEX].setOnClickListener(this);
mEfficacyBgViews[GENERAL_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.general_effect_bg);
mEfficacyBgViews[DISTORTING_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.distorting_effect_bg);
mEfficacyBgViews[INDIVIDUALITY_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.individuality_effect_bg);
mEfficacyBgViews[GRAFFITI_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.graffiti_effect_bg);
mEfficacyBgViews[ACCESSORIES_EFFECT_INDEX] = (ImageView) mEfficacyRL
.findViewById(R.id.accessories_effect_bg);
}
private void initEffectListView() {
mEffectListView = LayoutInflater.from(CameraActivity.this).inflate(
R.layout.efficacy_list_layout, null);
mDMEffectListView = LayoutInflater.from(CameraActivity.this).inflate(
R.layout.dm_efficacy_list_layout, null);
mEffectGridView = (GridView) mEffectListView
.findViewById(R.id.effect_gridview);
mEffectAdapter = new EffectListAdapter(this, null);
}
@SuppressLint("NewApi")
private void initPreView() {
mCameraPreview = (CameraPreview) findViewById(R.id.camera_preview);
mCameraPreview.setSurfaceTextureListener(mCameraPreview);
mCameraPreview.setCallback(this);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
//SimpleAudioPlayer.getInstance(getApplication()).playEffect(
// SimpleAudioPlayer.CLICK_SOUND_KEY);
switch (view.getId()) {
case R.id.camera_mode:
if (mCameraMode == CameraConfig.CAMERA_VIDEO_MODE) {
if (mMediaRecordManager != null
&& mMediaRecordManager.isRecording() || isEditState) {
showDiscardDialog();
break;
} else {
updateCameraMode(CameraConfig.CAMERA_PHOTO_MODE);
}
} else {
if (isEditState) {
showDiscardDialog();
break;
} else {
clearAllEffect();
updateCameraMode(CameraConfig.CAMERA_VIDEO_MODE);
}
}
onCheckedButton(CAMERA_MODE_INDEX);
if (mSpecialEfficacyPop != null && mSpecialEfficacyPop.isShowing()) {
mSpecialEfficacyPop.dismiss();
}
break;
case R.id.gallery_btn:
//onCheckedButton(GALLERY_INDEX);
if (mSpecialEfficacyPop != null && mSpecialEfficacyPop.isShowing()) {
mSpecialEfficacyPop.dismiss();
}
try {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.worldchip.bbpaw.album",
"com.worldchip.bbpaw.album.activity.PhotosListActivity"));
intent.putExtra("files_path", CameraConfig.SAMPLE_FILE_DIR);
startActivity(intent);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Toast.makeText(this, R.string.open_gallery_error_msg,
Toast.LENGTH_SHORT).show();
}
break;
case R.id.save_btn:
mHasEfficacyBeforShutter = false;
stopPreview();
onCheckedButton(SAVE_INDEX);
mToolImageViews[SAVE_INDEX].setVisibility(View.INVISIBLE);
mToolImageBgViews[SAVE_INDEX].setVisibility(View.INVISIBLE);
if (mSpecialEfficacyPop != null && mSpecialEfficacyPop.isShowing()) {
mSpecialEfficacyPop.dismiss();
}
if (mCameraMode == CameraConfig.CAMERA_PHOTO_MODE) {
if (mEffectDrawView != null) {
mEffectDrawView.savePic();
}
} else {
if (mMediaRecordManager != null) {
mMediaRecordManager.onUpdateGallery();
}
}
startPreview();
break;
case R.id.shutter_btn:
isEditState = true;
if (mEffectDrawView != null) {
mHasEfficacyBeforShutter = mEffectDrawView.hasEffect();
}
onCheckedButton(SHUTTER_INDEX);
if (mSpecialEfficacyPop != null && mSpecialEfficacyPop.isShowing()) {
mSpecialEfficacyPop.dismiss();
}
if (mCameraMode == CameraConfig.CAMERA_PHOTO_MODE) {
mToolImageViews[SAVE_INDEX].setVisibility(View.VISIBLE);
mToolImageBgViews[SAVE_INDEX].setVisibility(View.VISIBLE);
mToolImageViews[SHUTTER_INDEX].setEnabled(false);
takePhoto();
} else {
if (mMediaRecordManager == null)
return;
if (mMediaRecordManager.isRecording()) {
mMediaRecordManager.stopVideoRecording();
// mToolImageViews[SAVE_INDEX].setVisibility(View.VISIBLE);
// mToolImageBgViews[SAVE_INDEX].setVisibility(View.VISIBLE);
//mToolImageViews[SAVE_INDEX].setEnabled(true);
// stopPreview();
//mToolImageViews[SHUTTER_INDEX].setEnabled(false); //by wuyong
//mToolImageViews[SAVE_INDEX].setEnabled(true);
isEditState = false;
mEfficacyViews[GRAFFITI_EFFECT_INDEX].setEnabled(true);
stopRecordingLight();
} else {
showStorageHint();
if (Utils.getAvailableSpace() < Utils.LOW_STORAGE) {
LogUtil.v(TAG,
"Storage issue, ignore the start request");
return;
}
mToolImageViews[SHUTTER_INDEX].setEnabled(false);
mMediaRecordManager.initializeRecorder();
mMediaRecordManager.startVideoRecording();
startReordingLight();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mToolImageViews[SHUTTER_INDEX].setEnabled(true);
}
}, 1200);
}
}
break;
case R.id.magic_btn:
if (mSpecialEfficacyPop != null && mSpecialEfficacyPop.isShowing()) {
mSpecialEfficacyPop.dismiss();
return;
}
onCheckedButton(MAGIC_INDEX);
showSpeciallyEfficacyToolPop();
break;
case R.id.general_effect_btn:
updateEffectMode(SpecicalEfficacy.GENERAL);
updateEfficacyButton(GENERAL_EFFECT_INDEX);
break;
case R.id.distorting_effect_btn:
updateEffectMode(SpecicalEfficacy.DISTORTING);
updateEfficacyButton(DISTORTING_EFFECT_INDEX);
showDMEffectsPop(view);
break;
case R.id.individuality_effect_btn:
updateEffectMode(SpecicalEfficacy.INDIVIDUALITY);
updateEfficacyButton(INDIVIDUALITY_EFFECT_INDEX);
showEffectListPop(SpecicalEfficacy.INDIVIDUALITY);
break;
case R.id.graffiti_effect_btn:
updateEffectMode(SpecicalEfficacy.GRAFFITI);
updateEfficacyButton(GRAFFITI_EFFECT_INDEX);
break;
case R.id.accessories_effect_btn:
updateEffectMode(SpecicalEfficacy.ACCESSORIES);
updateEfficacyButton(ACCESSORIES_EFFECT_INDEX);
showEffectListPop(SpecicalEfficacy.ACCESSORIES);
break;
case R.id.camera_converion:
if (mCurrCameraFacing == CameraConfig.CAMERA_FACING_FRONT) {
CameraManager.getInstance(CameraActivity.this).changeCamera(
CameraActivity.this, CameraConfig.CAMERA_FACING_BACK);
mCurrCameraFacing = CameraConfig.CAMERA_FACING_BACK;
} else {
CameraManager.getInstance(CameraActivity.this).changeCamera(
CameraActivity.this, CameraConfig.CAMERA_FACING_FRONT);
mCurrCameraFacing = CameraConfig.CAMERA_FACING_FRONT;
}
break;
case R.id.main_back_btn:
if (!isEditState) {
if (mCameraMode == CameraConfig.CAMERA_VIDEO_MODE) {
if (mMediaRecordManager != null) {
if (mMediaRecordManager.isRecording()) {
showDiscardDialog();
} else {
exitApp();
}
}
} else {
exitApp();
}
} else {
showDiscardDialog();
}
break;
case R.id.main_switch_camera_btn:
//startDefaultCamera();
hideSystemUI(this, false);
startDefaultCamera(CameraActivity.this,"com.android.camera2","com.android.camera.CameraActivity");
break;
}
}
private void updateCameraMode(int mode) {
if (mode == CameraConfig.CAMERA_PHOTO_MODE) {
if (mToolImageViews[CAMERA_MODE_INDEX] != null) {
mToolImageViews[CAMERA_MODE_INDEX]
.setImageResource(R.drawable.ic_take_photo);
}
if (mToolImageViews[SHUTTER_INDEX] != null) {
mToolImageViews[SHUTTER_INDEX]
.setImageResource(R.drawable.ic_take_photo_btn);
}
mToolImageViews[MAGIC_INDEX].setEnabled(true);
} else {
updateEffectMode(SpecicalEfficacy.GENERAL);
updateEfficacyButton(GENERAL_EFFECT_INDEX);
if (mToolImageViews[CAMERA_MODE_INDEX] != null) {
mToolImageViews[CAMERA_MODE_INDEX]
.setImageResource(R.drawable.ic_record_video);
}
if (mToolImageViews[SHUTTER_INDEX] != null) {
mToolImageViews[SHUTTER_INDEX]
.setImageResource(R.drawable.ic_record_video_btn);
}
mToolImageViews[MAGIC_INDEX].setEnabled(false);
}
mCameraMode = mode;
}
private void takePhoto() {
// TODO Auto-generated method stub
CameraManager cameraManager = CameraManager
.getInstance(CameraActivity.this);
Camera camera = cameraManager.getCamera();
int cameraId = cameraManager.getCameraId();
if (cameraId == CameraConfig.CAMERA_FACING_FRONT) {
int orientation = 0;
if (mOrientation == 0) {
orientation = mOrientation;
} else if (mOrientation == 90) {
orientation = mOrientation - 270;
} else if (mOrientation == 180) {
orientation = mOrientation + 180;
} else if (mOrientation == 270) {
orientation = mOrientation - 90;
}
int jpegRotation = CameraUtils.getJpegRotation(
cameraManager.getCameraId(), orientation);
if (camera != null) {
Parameters parameters = camera.getParameters();
parameters.setRotation(jpegRotation);
camera.setParameters(parameters);
}
}
if (camera != null) {
camera.takePicture(null, null, null, new JpegPictureCallback());
}
}
private final class JpegPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(byte[] jpegData,
android.hardware.Camera camera) {
if (mCenterShutterView != null) {
mCenterShutterView.setVisibility(View.INVISIBLE);
}
isEditState = true;
stopPreview();
Bitmap finalPic = null;
// Bitmap bitmap = BitmapFactory.decodeByteArray(jpegData, 0,
// jpegData.length);
Bitmap bitmap = ImageTool.creatFinalPictureTakenBitmap(jpegData);
Log.e("lee", "onPictureTaken bitmap weight = " + bitmap.getWidth()
+ " height == " + bitmap.getHeight());
//mToolImageViews[SAVE_INDEX].setEnabled(true);
if (mEffectMode == SpecicalEfficacy.DISTORTING) {// 哈哈镜模式
if (mDistortingMirror == DistortingMirrorEffects.CONVEXMIRROR1) {
finalPic = ImageTool.toHahajingConvex(bitmap,
(int) (bitmap.getHeight() / 4));
} else if (mDistortingMirror == DistortingMirrorEffects.CONVEXMIRROR2) {
finalPic = ImageTool.toShrink(bitmap,
bitmap.getWidth() / 2, bitmap.getHeight() / 2);
} else if (mDistortingMirror == DistortingMirrorEffects.DEFORM) {
finalPic = ImageTool.toWarp(bitmap,
(float) (bitmap.getWidth() / 2),
(float) (bitmap.getHeight() / 2));
}
if (mEffectDrawView != null) {
mEffectDrawView.drawPicEffectBitmap(finalPic);
}
} else {// 其他模式
finalPic = bitmap;
}
if (mEffectDrawView != null) {
mEffectDrawView.setPicBitmap(finalPic);
}
}
}
/*
* @Override public void surfaceChanged(SurfaceHolder holder, int format,
* int w, int h) { // TODO Auto-generated method stub Log.e("lee",
* "surfaceChanged ------------- "); new Thread(new Runnable() {
*
* @Override public void run() { // TODO Auto-generated method stub
* CameraManager
* .getInstance(CameraActivity.this).doOpenCamera(CameraActivity.this,
* CameraConfig.DEFAULT_CAMERA_FACING); } }).start(); }
*
* @Override public void surfaceCreated(SurfaceHolder arg0) { // TODO
* Auto-generated method stub }
*
* @Override public void surfaceDestroyed(SurfaceHolder arg0) { // TODO
* Auto-generated method stub Log.e("lee",
* "surfaceDestroyed ------------- ");
* CameraManager.getInstance(CameraActivity.this).doStopCamera(); }
*/
@Override
public void onCameraOpened(boolean isOpen) {
// TODO Auto-generated method stub
Log.e("lee", "onCameraOpened --isOpen == " + isOpen);
if (isOpen) {
CameraManager.getInstance(CameraActivity.this).doStartPreview(
mCameraPreview, this);
} else {
showErrorHint(getResources().getString(
R.string.camera_connect_error));
finish();
}
}
@Override
public void onError(String exception) {
// TODO Auto-generated method stub
if (exception != null) {
showErrorHint(exception);
}
}
private void showErrorHint(final String errorMessage) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(CameraActivity.this, errorMessage,
Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void onCheckedButton(int selectViewIndex) {
if (mToolImageBgViews == null)
return;
for (int i = 0; i < mToolImageBgViews.length; i++) {
if (i == GALLERY_INDEX) {
continue;
}
if (selectViewIndex == i) {
mToolImageBgViews[i]
.setBackgroundResource(R.drawable.ic_select_high_light);
} else {
mToolImageBgViews[i].setBackgroundDrawable(null);
}
}
}
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
if (mMediaRecordManager != null
&& mMediaRecordManager.isRecording())
mMediaRecordManager.stopVideoRecording();
} else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
if (mMediaRecordManager != null
&& mMediaRecordManager.isRecording())
mMediaRecordManager.stopVideoRecording();
// Show the toast.
Toast.makeText(CameraActivity.this,
R.string.video_reach_size_limit, Toast.LENGTH_LONG).show();
}
}
@Override
public void onError(MediaRecorder arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
mMediaRecordManager.stopVideoRecording();
showStorageHint();
}
private void showStorageHint() {
long storageSpace = Utils.getAvailableSpace();
String errorMessage = null;
if (storageSpace == Utils.UNAVAILABLE) {
errorMessage = getString(R.string.no_storage);
} else if (storageSpace == Utils.PREPARING) {
errorMessage = getString(R.string.preparing_sd);
} else if (storageSpace == Utils.UNKNOWN_SIZE) {
errorMessage = getString(R.string.access_sd_fail);
} else if (storageSpace < Utils.LOW_STORAGE) {
errorMessage = getString(R.string.spaceIsLow_content);
}
if (errorMessage != null) {
Toast.makeText(CameraActivity.this, errorMessage,
Toast.LENGTH_SHORT).show();
}
}
private void stopPreview() {
Camera camera = CameraManager.getInstance(CameraActivity.this)
.getCamera();
if (camera != null) {
camera.stopPreview();
mToolImageViews[SHUTTER_INDEX].setEnabled(false);
//mToolImageViews[SAVE_INDEX].setEnabled(true);
}
if (mCameraMode == CameraConfig.CAMERA_PHOTO_MODE) {
mEfficacyViews[GRAFFITI_EFFECT_INDEX].setEnabled(true);
}
if (mCameraPreview != null) {
mCameraPreview.setVisibility(View.GONE);
}
}
private void startPreview() {
Camera camera = CameraManager.getInstance(CameraActivity.this)
.getCamera();
if (camera != null) {
camera.startPreview();
mCenterShutterView.setVisibility(View.VISIBLE);
mToolImageViews[SHUTTER_INDEX].setEnabled(true);
}
//mToolImageViews[SAVE_INDEX].setEnabled(false);
mCenterShutterView.setImageResource(R.drawable.ic_center_shutter);
isEditState = false;
if (mCameraMode == CameraConfig.CAMERA_PHOTO_MODE) {
mEfficacyViews[GRAFFITI_EFFECT_INDEX].setEnabled(false);
if (mEffectDrawView != null) {
mEffectDrawView.release();
}
}
if (mCameraPreview != null) {
mCameraPreview.setVisibility(View.VISIBLE);
}
}
/**
* 显示特效工具
*/
private void showSpeciallyEfficacyToolPop() {
if (null == mRightToolViews)
return;
if (null == mEfficacyRL)
return;
mEfficacyRL.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int popupWidth = mEfficacyRL.getMeasuredWidth();
int popupHeight = mEfficacyRL.getMeasuredHeight();
if (mSpecialEfficacyPop == null) {
mSpecialEfficacyPop = new PopupWindow(mEfficacyRL, popupWidth,
popupHeight);
}
int[] location = new int[2];
mRightToolViews.getLocationOnScreen(location);
if (mSpecialEfficacyPop.isShowing())
mSpecialEfficacyPop.dismiss();
// mSpecialEfficacyPop.showAtLocation(mRightToolViews,
// Gravity.NO_GRAVITY, (location[0] - mRightToolViews.getWidth()),
// location[1] + (mRightToolViews.getHeight() - popupHeight)/2);
mSpecialEfficacyPop.showAtLocation(mRightToolViews, Gravity.TOP
| Gravity.RIGHT, Configure.SCREEN_WIDTH(this) - location[0], 0);
}
/**
* 特效list popwindow
*/
private void showEffectListPop(SpecicalEfficacy effect) {
if (null == mEffectListView)
return;
if (mDMEffectListPop != null && mDMEffectListPop.isShowing()) {
mDMEffectListPop.dismiss();
mDMEffectListPop = null;
}
if (mEffectListPop != null && mEffectListPop.isShowing()) {
mEffectListPop.dismiss();
mEffectListPop = null;
}
if (mEffectAdapter == null) {
mEffectAdapter = new EffectListAdapter(CameraActivity.this, null);
}
int[] effectResIds = null;
if (effect == SpecicalEfficacy.INDIVIDUALITY) {
effectResIds = EffectData.EFFECT_BACKGROUND_THUMB;
} else if (effect == SpecicalEfficacy.ACCESSORIES) {
effectResIds = EffectData.EFFECT_PROPS;
}
ArrayList<Integer> effectList = new ArrayList<Integer>();
for (int i = 0; i < effectResIds.length; i++) {
effectList.add(effectResIds[i]);
}
mEffectAdapter.setData(effectList);
mEffectAdapter.setSeclection(-1);
mEffectGridView.setAdapter(mEffectAdapter);
mEffectGridView
.setOnItemClickListener(new EffectListOnItemClickListener());
mEffectAdapter.notifyDataSetChanged();
PopupWindow popupWindow = creatPopupWindow(mEffectListView);
int[] location = new int[2];
if (mEfficacyRL != null) {
mEfficacyRL.getLocationOnScreen(location);
}
if (popupWindow != null) {
popupWindow.showAtLocation(mRightToolViews, Gravity.TOP
| Gravity.RIGHT,
Configure.SCREEN_WIDTH(this) - location[0], 0);
}
}
/**
* 显示哈哈镜特效pop
*/
private void showDMEffectsPop(View anchor) {
if (null == mDMEffectListView)
return;
if (mEffectListPop != null && mEffectListPop.isShowing()) {
mEffectListPop.dismiss();
mEffectListPop = null;
}
if (mDMEffectListPop != null && mDMEffectListPop.isShowing()) {
mDMEffectListPop.dismiss();
mDMEffectListPop = null;
mDmEffectsAdapter = null;
}
String[] dmEffects = getResources().getStringArray(
R.array.distorting_mirror_effects_list);
ArrayList<String> dmEffectList = new ArrayList<String>();
for (int i = 0; i < dmEffects.length; i++) {
dmEffectList.add(dmEffects[i]);
}
mDmEffectsAdapter = new DMEffectsListAdapter(CameraActivity.this,
dmEffectList);
GridView dmEffectGridView = (GridView) mDMEffectListView
.findViewById(R.id.dm_effect_gridview);
dmEffectGridView.setAdapter(mDmEffectsAdapter);
dmEffectGridView
.setOnItemClickListener(new EffectListOnItemClickListener());
if (mDMEffectListPop == null) {
mDMEffectListPop = new PopupWindow(mDMEffectListView,
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mDMEffectListPop.setOutsideTouchable(true);
mDMEffectListPop.setBackgroundDrawable(new ColorDrawable(0));
}
int[] location = new int[2];
if (mEfficacyRL != null) {
mEfficacyRL.getLocationOnScreen(location);
}
if (mDMEffectListPop != null) {
mDMEffectListPop.showAtLocation(mRightToolViews,
Gravity.CENTER_VERTICAL | Gravity.RIGHT,
Configure.SCREEN_WIDTH(this) - location[0], 0);
}
}
private PopupWindow creatPopupWindow(View contentView) {
if (contentView == null)
return null;
contentView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int popupWidth = contentView.getMeasuredWidth();
int popupHeight = contentView.getMeasuredHeight();
if (mEffectListPop == null) {
mEffectListPop = new PopupWindow(CameraActivity.this);
mEffectListPop.setWidth(popupWidth);
mEffectListPop.setHeight(popupHeight);
mEffectListPop.setOutsideTouchable(true);
mEffectListPop.setBackgroundDrawable(new ColorDrawable(0));
}
mEffectListPop.setContentView(contentView);
return mEffectListPop;
}
private void updateEfficacyButton(int selectViewIndex) {
if (mEfficacyBgViews == null)
return;
for (int i = 0; i < mEfficacyBgViews.length; i++) {
if (selectViewIndex == i) {
mEfficacyBgViews[i]
.setBackgroundResource(R.drawable.ic_select_high_light);
if (mToolImageViews != null) {
mToolImageViews[MAGIC_INDEX]
.setImageDrawable(mEfficacyViews[i].getDrawable());
}
} else {
mEfficacyBgViews[i].setBackgroundDrawable(null);
}
}
}
private void exitApp() {
// showGoldResultView();
TranslateAnimation transAnimation = new TranslateAnimation(0, 20, 0, 0);
transAnimation.setDuration(100);
transAnimation.setStartOffset(0);
transAnimation.setFillAfter(true);
transAnimation.setInterpolator(new LinearInterpolator());
transAnimation.setRepeatCount(6);
transAnimation.setRepeatMode(Animation.REVERSE);
transAnimation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
CameraActivity.this.finish();
}
});
mBackBtn.startAnimation(transAnimation);
}
private void updateEffectMode(SpecicalEfficacy efficacy) {
if (mEffectDrawView != null) {
mEffectDrawView.setCurrEffectMode(efficacy);
}
if (efficacy == SpecicalEfficacy.GENERAL) {
if (mEffectDrawView != null && !isEditState) {
mEffectDrawView.clearAllEffectDraw();
} else {
if (!mHasEfficacyBeforShutter) {
mEffectDrawView.clearAllEffectDraw();
}
}
} else if (efficacy == SpecicalEfficacy.GRAFFITI) {
if (mEffectDrawView != null && isEditState) {
mEffectDrawView.setGraffitiEnabled(true);
}
} else if (efficacy == SpecicalEfficacy.ACCESSORIES) {
if (mEffectDrawView != null) {
mEffectDrawView.creatDrawCanvas();
}
} else {
if (mEffectDrawView != null) {
mEffectDrawView.setGraffitiEnabled(false);
}
}
mEffectMode = efficacy;
}
private void discard() {
if (mCameraMode == CameraConfig.CAMERA_VIDEO_MODE) {
if (mMediaRecordManager != null) {
mMediaRecordManager.discardRecording();
}
} else {
// mFinalPic = null;
clearAllEffect();
}
isEditState = false;
mToolImageViews[SAVE_INDEX].setVisibility(View.INVISIBLE);
mToolImageBgViews[SHUTTER_INDEX].setVisibility(View.INVISIBLE);
startPreview();
}
private void clearAllEffect() {
if (mEffectDrawView != null) {
mEffectDrawView.clearAll();
}
mHasEfficacyBeforShutter = false;
}
class EffectListOnItemClickListener implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
SimpleAudioPlayer.getInstance(getApplication()).playEffect(
SimpleAudioPlayer.CLICK_SOUND_KEY);
if (mEffectMode == SpecicalEfficacy.ACCESSORIES) {
if (mEffectAdapter != null) {
mEffectAdapter.setSeclection(position);
}
int res = EffectData.EFFECT_PROPS[position];
if (mEffectDrawView != null) {
mEffectDrawView.setAccessoriesBitmap(res);
}
} else if (mEffectMode == SpecicalEfficacy.INDIVIDUALITY) {
if (mEffectAdapter != null) {
mEffectAdapter.setSeclection(position);
}
int res = EffectData.EFFECT_BACKGROUND[position];
if (mEffectDrawView != null) {
mEffectDrawView.onDrawEffectImage(res);
}
} else if (mEffectMode == SpecicalEfficacy.DISTORTING) {
if (mDmEffectsAdapter != null) {
mDmEffectsAdapter.setSeclection(position);
}
mDistortingMirror = getDMEffectMode(position);
}
}
}
private DistortingMirrorEffects getDMEffectMode(int position) {
if (position == 0) {
return DistortingMirrorEffects.CONVEXMIRROR1;
} else if (position == 1) {
return DistortingMirrorEffects.CONVEXMIRROR2;
} else if (position == 2) {
return DistortingMirrorEffects.DEFORM;
}
return DistortingMirrorEffects.CONVEXMIRROR1;
}
private void showDiscardDialog() {
// TODO Auto-generated method stub
GlobalAlertDialog d = new GlobalAlertDialog.Builder(this)
.setTitle(R.string.global_alert_dialog_title)
.setCancelable(true)
.setMessage(getResources().getString(R.string.discard_message))
.setNegativeButton("", new DialogInterface.OnClickListener() {// no
// button
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.setPositiveButton("", new DialogInterface.OnClickListener() {// yes
// button
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
if (mCameraMode == CameraConfig.CAMERA_VIDEO_MODE
&& mMediaRecordManager != null) {
if (mMediaRecordManager.isRecording()) {
mMediaRecordManager
.stopVideoRecording();
//mToolImageViews[SAVE_INDEX]
// .setEnabled(true);
stopRecordingLight();
}
}
discard();
}
}).create();
d.show();
}
@Override
public void onPreviewFrame(byte[] data) {
}
private AnimationDrawable mReordingLightAnim = null;
private void startReordingLight() {
ImageView recordingLight = (ImageView) findViewById(R.id.recording_light);
if (recordingLight != null) {
recordingLight.setVisibility(View.VISIBLE);
mReordingLightAnim = (AnimationDrawable) recordingLight
.getBackground();
mReordingLightAnim.start();
}
if (mRecoedTimeTV != null) {
mRecoedTimeTV.setVisibility(View.VISIBLE);
startRecordTimer();
}
}
private void stopRecordingLight() {
ImageView recordingLight = (ImageView) findViewById(R.id.recording_light);
if (recordingLight != null) {
recordingLight.setVisibility(View.GONE);
}
if (mReordingLightAnim != null) {
mReordingLightAnim.stop();
mReordingLightAnim = null;
}
if (mRecoedTimeTV != null) {
stopRecordTimer();
mRecoedTimeTV.setVisibility(View.GONE);
mRecordTimeCount = 0;
mRecoedTimeTV.setText("");
}
}
private void startRecordTimer() {
if (mRecordTimer != null) {
if (mRecordTimerTask != null) {
mRecordTimerTask.cancel(); // 将原任务从队列中移除
}
} else {
mRecordTimer = new Timer(true);
}
mRecordTimerTask = new RecordTimerTask(); // 新建一个任务
mRecordTimer.schedule(mRecordTimerTask, 0, 1000);
}
private void stopRecordTimer() {
if (mRecordTimer != null) {
if (mRecordTimerTask != null) {
mRecordTimerTask.cancel(); // 将原任务从队列中移除
}
}
}
public class RecordTimerTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
mHandler.sendEmptyMessage(UPDATE_RECORD_TIMER);
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
hideSystemUI(this, true);
if (isStartDefCamera) {
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isStartDefCamera = false;
if (mOrientationListener != null) {
mOrientationListener.enable();
}
CameraManager cameraManager = CameraManager.getInstance(this);
if (cameraManager != null && !cameraManager.isOpened()) {
cameraManager
.doOpenCamera(this, CameraConfig.DEFAULT_CAMERA_FACING);
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ScannerClient scannerClient = ScannerClient.getInstance();
if (scannerClient != null) {
MediaScannerConnection scannerConnection = scannerClient
.getScannerConnection();
if (scannerConnection != null && scannerConnection.isConnected()) {
scannerConnection.disconnect();
scannerClient.setConnected(false);
}
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mOrientationListener != null) {
mOrientationListener.disable();
}
CameraManager.getInstance(this).doStopCamera();
}
private class MyOrientationEventListener extends OrientationEventListener {
public MyOrientationEventListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN)
return;
mOrientation = CameraUtils.roundOrientation(orientation,
mOrientation);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
private void startDefaultCamera(Context context,String packageName,String className) {
if (TextUtils.isEmpty(packageName))
return;
if (mOrientationListener != null) {
mOrientationListener.disable();
}
CameraManager.getInstance(this).doStopCamera();
try {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, className));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
isStartDefCamera = true;
} catch (ActivityNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private String photoPathUrl = null;
private void startDefaultCamera() {
if (mOrientationListener != null) {
mOrientationListener.disable();
}
CameraManager.getInstance(this).doStopCamera();
/*
* Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
* startActivityForResult(intent, 2000);
*/
Intent intentPhote = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentPhote.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
photoPathUrl = getOriginalPhotopath();
File out = new File(photoPathUrl);
Uri uri = Uri.fromFile(out);
// 获取拍照后未压缩的原图片,并保存在uri路径中
intentPhote.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intentPhote, 2000);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2000 && resultCode == Activity.RESULT_OK) {
// saveResultDataPhoto(data);
// saveResultPhoto(getBitmapFromUrl(getOriginalPhotopath()));
if (photoPathUrl != null) {
Utils.updateGallery(CameraActivity.this, photoPathUrl);
}
}
if (mOrientationListener != null) {
mOrientationListener.enable();
}
CameraManager cameraManager = CameraManager.getInstance(this);
if (cameraManager != null && !cameraManager.isOpened()) {
cameraManager.doOpenCamera(this, CameraConfig.DEFAULT_CAMERA_FACING);
}
}
private Bitmap getBitmapFromUrl(String url) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
Bitmap bitmap = BitmapFactory.decodeFile(url);
// 防止OOM发生
options.inJustDecodeBounds = false;
return bitmap;
}
private String getOriginalPhotopath() {
File picFile = new File(CameraConfig.POTOS_FILES_PATH);
if (!picFile.exists()) {
picFile.mkdirs();
}
return Utils.createPicOuputFile(CameraActivity.this).toString();
// return CameraConfig.POTOS_FILES_PATH + "originalPhoto.jpg";
}
private void saveResultPhoto(Bitmap bitmap) {
if (bitmap != null) {
Log.e("xiaolp", "Width = " + bitmap.getWidth() + " Height = "
+ bitmap.getHeight());
File picOuputFile = Utils.createPicOuputFile(CameraActivity.this);
FileOutputStream out = null;
try {
Log.e("xiaolp",
"picOuputFile.getPath() = " + picOuputFile.getPath());
out = new FileOutputStream(picOuputFile.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
Utils.updateGallery(CameraActivity.this, picOuputFile.getPath());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void saveResultDataPhoto(Intent data) {
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
if (bitmap != null) {
Log.e("xiaolp", "width = " + bitmap.getWidth() + " height = "
+ bitmap.getHeight());
File picOuputFile = Utils.createPicOuputFile(CameraActivity.this);
FileOutputStream out = null;
try {
Log.e("xiaolp",
"picOuputFile.getPath() = " + picOuputFile.getPath());
out = new FileOutputStream(picOuputFile.getPath());
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
Utils.updateGallery(CameraActivity.this, picOuputFile.getPath());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
package com.baytie.baytie.Menu;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import com.baytie.baytie.Intro.Login;
import com.baytie.baytie.MyBaseFragmentActivity;
import com.baytie.baytie.R;
import com.baytie.common.Uitils;
import com.readystatesoftware.systembartint.SystemBarTintManager;
/**
* Created by Administrator on 9/14/2016.
*/
public class MenuSettings extends MyBaseFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_settings);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
// enable status bar tint
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(Color.parseColor("#70cd00"));
ImageButton btnBack = (ImageButton)findViewById(R.id.btn_settingBack);
ImageButton btnProfile = (ImageButton)findViewById(R.id.btn_setCustomerProfile);
ImageButton btnChangPW = (ImageButton)findViewById(R.id.btn_setChangPW);
ImageButton btnLanguage = (ImageButton)findViewById(R.id.btn_setLanguage);
ImageButton btnAddress = (ImageButton)findViewById(R.id.btn_setMyAddress);
ImageButton btnLogOut = (ImageButton)findViewById(R.id.btn_logout) ;
ImageButton btn_Subscription = (ImageButton)findViewById(R.id.btn_Subscription);
ImageButton btn_MobileNumber = (ImageButton)findViewById(R.id.btn_ChangeMobileNo);
ImageButton btn_termsAndConditions = (ImageButton)findViewById(R.id.btn_setPrivacy);
ImageButton btn_Privacy = (ImageButton)findViewById(R.id.btn_privacy);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuCustomerProfile.class);
startActivity(intent);
}
});
btnChangPW.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuChangePW.class);
startActivity(intent);
}
});
btnLanguage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuLanguageSet.class);
startActivity(intent);
}
});
btnAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuAddress.class);
startActivity(intent);
}
});
btn_MobileNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuMobileNumberChange.class);
startActivity(intent);
}
});
btn_Subscription.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuSubscription.class);
startActivity(intent);
}
});
//Terms And conditions
btn_termsAndConditions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuTermsCondition.class);
startActivity(intent);
}
});
//Privacy
btn_Privacy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MenuPrivacy.class);
startActivity(intent);
}
});
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uitils.storeAccessToken(MenuSettings.this, "");
Intent i=new Intent(getApplicationContext(), Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
}
}
|
package com.junzhao.shanfen.activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.junzhao.base.base.BaseAct;
import com.junzhao.shanfen.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
/**
* Created by Administrator on 2018/3/20 0020.
*
*
* 抽奖规则
*/
public class LZPaiHangBangRuleAty extends BaseAct{
// @ViewInject(R.id.tv_my_scope)
// TextView tv_my_scope;
@ViewInject(R.id.tv_text1)
TextView tv_text1;
String rule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aty_paihangbang_rule);
ViewUtils.inject(this);
if (getIntentData()!=null)rule= (String) getIntentData();
tv_text1.setText(rule);
// tv_my_scope.setText(Html.fromHtml("<u><font color='#FD8E38'>我的积分</font></u>"));
}
// @OnClick(R.id.tv_my_scope)
// public void onClick(View view){
// startAct(LZPaiHangBangRuleAty.this,AnswerScopeListActivity.class);
// }
@OnClick(R.id.titlebar_tv_left)
public void leftClick(View view) {
finish();
}
}
|
package myservlet.login;
import mybean.login.staffBean;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class alterstaffServlet extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //加载驱动
}
catch(Exception e){
System.out.println(e);
}
}
public String handleString(String s) { //处理乱码
try {
byte bb[]=s.getBytes("iso-8859-1");
s=new String(bb);
}catch(Exception e) {}
return s;
}
public void doPost(HttpServletRequest request,HttpServletResponse response) //返回原本信息
throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
String uri= "jdbc:sqlserver://localhost:1433;DatabaseName=JSPsx";
Connection con;
PreparedStatement sql;
ResultSet rs;
staffBean staffBean =new staffBean(); //创建Javabean模型
request.setAttribute("staffBean",staffBean);
String u = request.getParameter("alter");
try {
con=DriverManager.getConnection(uri,"sa","cjj123456789");
String update= "SELECT * FROM staffTable Where 员工编号="+"'"+u+"'"+"";
sql =con.prepareStatement(update);
rs =sql.executeQuery();
while(rs.next()) {
String staffNum=rs.getString("员工编号");
String staffName = rs.getString("姓名");
String staffSex = rs.getString("性别");
String staffAge = rs.getString("年龄");
String staffID = rs.getString("身份证号");
String staffLocation = rs.getString("户口所在地");
String staffPhong = rs.getString("联系电话");
String jobType = rs.getString("工作类型");
String staffPic = rs.getString("照片");
staffBean.setStaffNum(staffNum);
staffBean.setStaffName(staffName);
staffBean.setStaffSex(staffSex);
staffBean.setStaffAge(staffAge);
staffBean.setStaffID(staffID);
staffBean.setStaffLocation(staffLocation);
staffBean.setStaffPhong(staffPhong);
staffBean.setJobType(jobType);
staffBean.setStaffPic(staffPic);
if(staffSex.equals("男"))
staffBean.setXiangbie1("checked");
if(staffSex.equals("女"))
staffBean.setXingbie2("checked");
}
}catch(Exception e) {
System.out.println(e);
}
//response.sendRedirect("alterStaff.jsp");
RequestDispatcher dispatcher =
request.getRequestDispatcher("alterStaff.jsp");
dispatcher.forward(request, response); //转发 //转发
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.socket.config.annotation;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.util.MultiValueMap;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import org.springframework.web.socket.server.support.OriginHandshakeInterceptor;
import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler;
import org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler;
import org.springframework.web.socket.sockjs.transport.TransportHandler;
import org.springframework.web.socket.sockjs.transport.TransportType;
import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService;
import org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link WebMvcStompWebSocketEndpointRegistration}.
*
* @author Rossen Stoyanchev
*/
class WebMvcStompWebSocketEndpointRegistrationTests {
private final SubProtocolWebSocketHandler handler = new SubProtocolWebSocketHandler(mock(), mock());
private final TaskScheduler scheduler = mock();
@Test
void minimalRegistration() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
assertThat(((WebSocketHttpRequestHandler) entry.getKey()).getWebSocketHandler()).isNotNull();
assertThat(((WebSocketHttpRequestHandler) entry.getKey()).getHandshakeInterceptors()).hasSize(1);
assertThat(entry.getValue()).containsExactly("/foo");
}
@Test
void allowedOrigins() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
registration.setAllowedOrigins();
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
HttpRequestHandler handler = mappings.entrySet().iterator().next().getKey();
WebSocketHttpRequestHandler wsHandler = (WebSocketHttpRequestHandler) handler;
assertThat(wsHandler.getWebSocketHandler()).isNotNull();
assertThat(wsHandler.getHandshakeInterceptors()).hasSize(1);
assertThat(wsHandler.getHandshakeInterceptors().get(0).getClass()).isEqualTo(OriginHandshakeInterceptor.class);
}
@Test
void sameOrigin() {
WebMvcStompWebSocketEndpointRegistration registration = new WebMvcStompWebSocketEndpointRegistration(
new String[] {"/foo"}, this.handler, this.scheduler);
registration.setAllowedOrigins();
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
HttpRequestHandler handler = mappings.entrySet().iterator().next().getKey();
WebSocketHttpRequestHandler wsHandler = (WebSocketHttpRequestHandler) handler;
assertThat(wsHandler.getWebSocketHandler()).isNotNull();
assertThat(wsHandler.getHandshakeInterceptors()).hasSize(1);
assertThat(wsHandler.getHandshakeInterceptors().get(0).getClass()).isEqualTo(OriginHandshakeInterceptor.class);
}
@Test
void allowedOriginsWithSockJsService() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
String origin = "https://mydomain.com";
registration.setAllowedOrigins(origin).withSockJS();
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
SockJsHttpRequestHandler requestHandler = (SockJsHttpRequestHandler)mappings.entrySet().iterator().next().getKey();
assertThat(requestHandler.getSockJsService()).isNotNull();
DefaultSockJsService sockJsService = (DefaultSockJsService)requestHandler.getSockJsService();
assertThat(sockJsService.getAllowedOrigins().contains(origin)).isTrue();
assertThat(sockJsService.shouldSuppressCors()).isFalse();
registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
registration.withSockJS().setAllowedOrigins(origin);
mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
requestHandler = (SockJsHttpRequestHandler)mappings.entrySet().iterator().next().getKey();
assertThat(requestHandler.getSockJsService()).isNotNull();
sockJsService = (DefaultSockJsService)requestHandler.getSockJsService();
assertThat(sockJsService.getAllowedOrigins().contains(origin)).isTrue();
assertThat(sockJsService.shouldSuppressCors()).isFalse();
}
@Test
void allowedOriginPatterns() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
String origin = "https://*.mydomain.com";
registration.setAllowedOriginPatterns(origin).withSockJS();
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
SockJsHttpRequestHandler requestHandler = (SockJsHttpRequestHandler)mappings.entrySet().iterator().next().getKey();
assertThat(requestHandler.getSockJsService()).isNotNull();
DefaultSockJsService sockJsService = (DefaultSockJsService)requestHandler.getSockJsService();
assertThat(sockJsService.getAllowedOriginPatterns().contains(origin)).isTrue();
registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
registration.withSockJS().setAllowedOriginPatterns(origin);
mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
requestHandler = (SockJsHttpRequestHandler)mappings.entrySet().iterator().next().getKey();
assertThat(requestHandler.getSockJsService()).isNotNull();
sockJsService = (DefaultSockJsService)requestHandler.getSockJsService();
assertThat(sockJsService.getAllowedOriginPatterns().contains(origin)).isTrue();
}
@Test // SPR-12283
void disableCorsWithSockJsService() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
registration.withSockJS().setSuppressCors(true);
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
SockJsHttpRequestHandler requestHandler = (SockJsHttpRequestHandler)mappings.entrySet().iterator().next().getKey();
assertThat(requestHandler.getSockJsService()).isNotNull();
DefaultSockJsService sockJsService = (DefaultSockJsService)requestHandler.getSockJsService();
assertThat(sockJsService.shouldSuppressCors()).isTrue();
}
@Test
void handshakeHandlerAndInterceptor() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();
registration.setHandshakeHandler(handshakeHandler).addInterceptors(interceptor);
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
assertThat(entry.getValue()).containsExactly("/foo");
WebSocketHttpRequestHandler requestHandler = (WebSocketHttpRequestHandler) entry.getKey();
assertThat(requestHandler.getWebSocketHandler()).isNotNull();
assertThat(requestHandler.getHandshakeHandler()).isSameAs(handshakeHandler);
assertThat(requestHandler.getHandshakeInterceptors()).hasSize(2);
assertThat(requestHandler.getHandshakeInterceptors().get(0)).isEqualTo(interceptor);
assertThat(requestHandler.getHandshakeInterceptors().get(1).getClass()).isEqualTo(OriginHandshakeInterceptor.class);
}
@Test
void handshakeHandlerAndInterceptorWithAllowedOrigins() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();
String origin = "https://mydomain.com";
registration.setHandshakeHandler(handshakeHandler).addInterceptors(interceptor).setAllowedOrigins(origin);
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
assertThat(entry.getValue()).containsExactly("/foo");
WebSocketHttpRequestHandler requestHandler = (WebSocketHttpRequestHandler) entry.getKey();
assertThat(requestHandler.getWebSocketHandler()).isNotNull();
assertThat(requestHandler.getHandshakeHandler()).isSameAs(handshakeHandler);
assertThat(requestHandler.getHandshakeInterceptors()).hasSize(2);
assertThat(requestHandler.getHandshakeInterceptors().get(0)).isEqualTo(interceptor);
assertThat(requestHandler.getHandshakeInterceptors().get(1).getClass()).isEqualTo(OriginHandshakeInterceptor.class);
}
@Test
void handshakeHandlerInterceptorWithSockJsService() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();
registration.setHandshakeHandler(handshakeHandler).addInterceptors(interceptor).withSockJS();
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
assertThat(entry.getValue()).containsExactly("/foo/**");
SockJsHttpRequestHandler requestHandler = (SockJsHttpRequestHandler) entry.getKey();
assertThat(requestHandler.getWebSocketHandler()).isNotNull();
DefaultSockJsService sockJsService = (DefaultSockJsService) requestHandler.getSockJsService();
assertThat(sockJsService).isNotNull();
Map<TransportType, TransportHandler> handlers = sockJsService.getTransportHandlers();
WebSocketTransportHandler transportHandler = (WebSocketTransportHandler) handlers.get(TransportType.WEBSOCKET);
assertThat(transportHandler.getHandshakeHandler()).isSameAs(handshakeHandler);
assertThat(sockJsService.getHandshakeInterceptors()).hasSize(2);
assertThat(sockJsService.getHandshakeInterceptors().get(0)).isEqualTo(interceptor);
assertThat(sockJsService.getHandshakeInterceptors().get(1).getClass()).isEqualTo(OriginHandshakeInterceptor.class);
}
@Test
void handshakeHandlerInterceptorWithSockJsServiceAndAllowedOrigins() {
WebMvcStompWebSocketEndpointRegistration registration =
new WebMvcStompWebSocketEndpointRegistration(new String[] {"/foo"}, this.handler, this.scheduler);
DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler();
HttpSessionHandshakeInterceptor interceptor = new HttpSessionHandshakeInterceptor();
String origin = "https://mydomain.com";
registration.setHandshakeHandler(handshakeHandler)
.addInterceptors(interceptor).setAllowedOrigins(origin).withSockJS();
MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
assertThat(mappings).hasSize(1);
Map.Entry<HttpRequestHandler, List<String>> entry = mappings.entrySet().iterator().next();
assertThat(entry.getValue()).containsExactly("/foo/**");
SockJsHttpRequestHandler requestHandler = (SockJsHttpRequestHandler) entry.getKey();
assertThat(requestHandler.getWebSocketHandler()).isNotNull();
DefaultSockJsService sockJsService = (DefaultSockJsService) requestHandler.getSockJsService();
assertThat(sockJsService).isNotNull();
Map<TransportType, TransportHandler> handlers = sockJsService.getTransportHandlers();
WebSocketTransportHandler transportHandler = (WebSocketTransportHandler) handlers.get(TransportType.WEBSOCKET);
assertThat(transportHandler.getHandshakeHandler()).isSameAs(handshakeHandler);
assertThat(sockJsService.getHandshakeInterceptors()).hasSize(2);
assertThat(sockJsService.getHandshakeInterceptors().get(0)).isEqualTo(interceptor);
assertThat(sockJsService.getHandshakeInterceptors().get(1).getClass()).isEqualTo(OriginHandshakeInterceptor.class);
assertThat(sockJsService.getAllowedOrigins().contains(origin)).isTrue();
}
}
|
package net.gupt.ebuy.pojo;
/**
* 管理员实体类
* @author glf
*
*/
public class Admin {
private int id;//管理员ID
private String name;//名称
private String pass;//密码
private String header;//头像
private String phone;//电话
private String email;//邮箱
public Admin() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package endpoints;
import model.User;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import service.CryptoUtil;
import service.JWT;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
/* this class authenticates that the user is a
valid member and allowed to log in
*/
@WebServlet("/authenticate")
public class AuthenticationEndpoint extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// Get email/password from encrypted body
String body = IOUtils.toString(request.getReader());
byte[] bodyDecoded = Base64.getDecoder().decode(body);
byte[] decrypted = CryptoUtil.decrypt(bodyDecoded);
if (decrypted != null) {
String decryptedBody = new String(decrypted);
JSONObject obj = new JSONObject(decryptedBody);
String email = obj.getString("email");
String password = obj.getString("password");
String hashedPassword = CryptoUtil.getHash(password);
User user = null;
try {
// traditional login
if (email != null && hashedPassword != null) {
user = UserDao.fetchUser(email, hashedPassword);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
if (user != null) {
HashMap<String, Object> claims = new HashMap<>();
claims.put("username", user.getEmail());
claims.put("accountID", user.getId());
// about 8 hours until expiration
response.getWriter().write(JWT.createJWT("Auth API", claims, 15000));
}
else {
response.getWriter().write("access denied");
}
} catch (Exception e) {
response.getWriter().write("unexpected server error");
}
} else {
response.getWriter().write("access denied");
}
}
} |
package com.codecool.greencommitment.cmdProg;
import java.util.Scanner;
abstract class AbstractMenu {
private String title;
private String[] options;
private final Scanner sc = new Scanner(System.in);
AbstractMenu(String title, String[] options) {
this.title = title;
this.options = options;
}
Input getInput() {
return new Input(sc.nextLine());
}
void displayMenu() {
System.out.print(title);
for (String option:options) {
if (option.equals(options[options.length-1])) {
System.out.println(option);
} else {
System.out.print(option + ", ");
}
}
}
abstract void handleMenu();
}
|
package com.nanyin.services.impl;
import com.nanyin.config.util.PageHelper;
import com.nanyin.entity.DTO.PageQueryParams;
import com.nanyin.entity.DTO.UnitDto;
import com.nanyin.entity.QUnit;
import com.nanyin.entity.Unit;
import com.nanyin.repository.UnitRepository;
import com.nanyin.services.UnitService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UnitServiceImpl implements UnitService {
@Autowired
UnitRepository unitRepository;
@Autowired
JPAQueryFactory jpaQueryFactory;
@Override
public Page<Unit> findUnits(PageQueryParams pageQueryParams) throws Exception {
Integer offset = pageQueryParams.getOffset();
Integer limit = pageQueryParams.getLimit();
PageRequest pageRequest = PageHelper.generatePageRequest(offset, limit);
String search = pageQueryParams.getSearch();
Integer unitId = pageQueryParams.getUnit();
QUnit unit = QUnit.unit;
Predicate predicate = unit.isNotNull().or(unit.isNull());
predicate = search == null ? predicate : ExpressionUtils.and(predicate, unit.name.like("%" + search + "%"));
predicate = unitId == null ?
ExpressionUtils.and(predicate, unit.parent.id.isNull()) :
ExpressionUtils.and(predicate, unit.parent.id.eq(unitId).and(unit.id.ne(unitId)));
return unitRepository.findAll(predicate, pageRequest);
}
@Override
public List<Unit> findUnitTree() throws Exception {
return unitRepository.findAllByParentIsNull();
}
}
|
/*
* 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 controllers;
/**
*
* @author Slade
*/
public class Controller {
private DashboardController dashboardController;
private LoanController loanController;
private LoginRegisterController loginRegisterController;
private PersonalInfoProfileController personalInfoProfileController;
//Setting the variables goes here
public DashboardController getDashboardController() {
return dashboardController;
}
public LoanController getLoanController() {
return loanController;
}
public LoginRegisterController getLoginRegisterController() {
return loginRegisterController;
}
public PersonalInfoProfileController getPersonalInfoProfileController() {
return personalInfoProfileController;
}
public void setDashboardController(DashboardController tempDash) {
this.dashboardController = tempDash;
}
public void setLoanController(LoanController tempLoan) {
this.loanController = tempLoan;
}
public void setLoginRegisterController(LoginRegisterController tempLoginRegister) {
this.loginRegisterController = tempLoginRegister;
}
public void setPersonalInfoProfileController(PersonalInfoProfileController tempPip) {
this.personalInfoProfileController = tempPip;
}
}
|
package com.lenovohit.ssm.payment.web.rest;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.exception.BaseException;
import com.lenovohit.core.manager.GenericManager;
import com.lenovohit.core.utils.DateUtils;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.utils.StringUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.ssm.base.model.Machine;
import com.lenovohit.ssm.base.web.rest.SSMBaseRestController;
import com.lenovohit.ssm.payment.manager.AlipayManager;
import com.lenovohit.ssm.payment.manager.BankPayManager;
import com.lenovohit.ssm.payment.manager.CmbPayManager;
import com.lenovohit.ssm.payment.manager.HisPayManager;
import com.lenovohit.ssm.payment.manager.SingleePayManager;
import com.lenovohit.ssm.payment.manager.UnionPayManager;
import com.lenovohit.ssm.payment.manager.WxpayManager;
import com.lenovohit.ssm.payment.model.Order;
import com.lenovohit.ssm.payment.model.PayChannel;
import com.lenovohit.ssm.payment.model.Settlement;
import com.lenovohit.ssm.payment.support.alipay.utils.ZxingUtils;
import com.lenovohit.ssm.payment.support.wxPay.common.Util;
import com.lenovohit.ssm.payment.support.wxPay.protocol.pay_callback.PayCallbackResData;
import com.lenovohit.ssm.payment.utils.OrderSeqCalculator;
import com.lenovohit.ssm.payment.utils.SettleSeqCalculator;
import com.lenovohit.ssm.treat.model.DepositRecord;
import com.lenovohit.ssm.treat.model.ForegiftRecord;
import com.lenovohit.ssm.treat.model.HisOrder;
import com.lenovohit.ssm.treat.transfer.manager.HisEntityResponse;
import com.lenovohit.ssm.treat.transfer.manager.HisResponse;
/**
* 支付管理
*/
@RestController
@RequestMapping("/ssm/payment/pay")
public class PayRestController extends SSMBaseRestController {
@Autowired
private GenericManager<Settlement, String> settlementManager;
@Autowired
private GenericManager<Order, String> orderManager;
@Autowired
private GenericManager<PayChannel, String> payChannelManager;
@Autowired
private AlipayManager alipayManager;
@Autowired
private WxpayManager wxpayManager;
@Autowired
private UnionPayManager unionPayManager;
@Autowired
private SingleePayManager singleePayManager;
@Autowired
private BankPayManager bankPayManager;
@Autowired
private CmbPayManager cmbPayManager;
/**
* 现金预支付之前的操作
*/
private Settlement beforeCashPreCreate(Settlement settlement){
Order order = settlement.getOrder();
if(order != null && !StringUtils.isEmpty(order.getId())){
order = this.orderManager.get(order.getId());
if(null == order) throw new BaseException("不存在的订单号!");
}else {
throw new BaseException("不存在现金订单");
}
order.setRealAmt(order.getRealAmt().add(settlement.getAmt()));//此时记录真正支付的金额
order.setLastAmt(settlement.getAmt());
order = this.orderManager.save(order);
settlement.setOrder(order);
settlement.setStatus(Settlement.SETTLE_STAT_PAY_SUCCESS);
return settlement;
}
/**
* 预支付
* 记录结算单支付渠道,
* 设置结算单回调url,
* 根据支付渠道晚上结算单信息(例如微信支付宝获取二维码等信息)
* @param data
* @return Result
*/
@RequestMapping(value = "/preCreate", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forPreCreate(@RequestBody String data ){
Settlement settlement = JSONUtils.deserialize(data, Settlement.class);
log.info("预结算:"+ data);
try {
if("0000".equals(settlement.getPayChannelCode())){//现金先处理其订单信息
settlement = this.beforeCashPreCreate(settlement);
}
buildPaySettlement(settlement);// 金额 支付渠道 支付方式 支付者手机号码以及订单信息由前台传入,剩余信息进行组装
this.settlementManager.save(settlement);
precreateCall(settlement);
this.settlementManager.save(settlement);
return ResultUtils.renderSuccessResult(settlement);
} catch (Exception e) {
log.error("PayRestController preCreate exception", e);
e.printStackTrace();
return ResultUtils.renderFailureResult("系统异常,预支付失败!");
}
}
/**
* 根据二维码链接生成二维码图片
* @param id
* @param size
* @return
*/
@RequestMapping(value = "/showQrCode/{id}/{size}", method = RequestMethod.GET)
public String showQrCode(@PathVariable("id") String id, @PathVariable("size") int size ){
Settlement settlement = this.settlementManager.get(id);
if(null == settlement || StringUtils.isEmpty(settlement.getQrCode()))
return "";
OutputStream output = null;
try {
output = this.getResponse().getOutputStream();
ZxingUtils.getQRCodeImgeOs(settlement.getQrCode(), size, output);
} catch (Exception e) {
log.error("生成二维码信息失败!结算单号为【"+ settlement.getSettleNo() + "】");
e.printStackTrace();
} finally {
try {
if(output!=null){
output.flush();
output.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return "";
}
/**
* 支付宝回调
* 0.状态校验 1.结算单处理 2.订单处理 3.回调业务逻辑通知HIS
* @param settleId
* @param data
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/callback/alipay/{settleId}", method = RequestMethod.POST)
public String forAliPayCallback(@PathVariable("settleId") String settleId, @RequestBody String data ){
log.info("支付宝扫码支付-异步通知返回的数据如下:");
log.info(data);
String successRet = "success";
String failedRet = "failed";
Settlement settle = null;
try {
if(StringUtils.isEmpty(data) || StringUtils.isEmpty(settleId))
return failedRet;
Map<String,String> pm = parseUrlToMap(data);//支付宝有可能有WAIT_BUYER_PAY的回调,
String trade_status = pm.get("trade_status");
log.info("支付宝回调 状态 :" + trade_status);
if("WAIT_BUYER_PAY".equals(trade_status)){
log.info("支付宝回调 WAIT_BUYER_PAY ,跳过此次回调");
return failedRet;
}
//0. 状态检验
String uuid = com.lenovohit.core.utils.StringUtils.uuid();
this.settlementManager.executeSql("UPDATE SSM_SETTLEMENT SET FLAG = ? where ID=? and STATUS=? and FLAG is null", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
settle = this.settlementManager.findOne("from Settlement where flag=? and id=? and status=?", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
if(null == settle || !StringUtils.equals(Settlement.SETTLE_STAT_INITIAL, settle.getStatus()))
return successRet;
//1. 结算单处理
settle.getVariables().put("responseStr", data);
alipayManager.payCallBack(settle);
this.settlementManager.save(settle);
//2. 订单处理
Order order = settle.getOrder();
if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_SUCCESS) ||
StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FINISH)){
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
//3. His通知
HisEntityResponse<DepositRecord> bizResponse = (HisEntityResponse<DepositRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getSerialNumber());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,交易失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FAILURE)){
order.setStatus(Order.ORDER_STAT_CLOSED);
order.setFinishTime(DateUtils.getCurrentDate());
}
this.orderManager.save(order);
} catch (Exception e) {
log.error("支付宝支付回传交易失败,结算单号为【" + settle.getSettleNo() + "】");
log.error("PayRestController forAliPayCallback exception", e);
e.printStackTrace();
}
return successRet;
}
/**
* 微信预回调
* 0.状态校验 1.结算单处理 2.订单处理 3.回调业务逻辑通知HIS
* @param settleId
* @param data
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/callback/wxpay/", method = RequestMethod.POST)
public String forWXPayCallback(@RequestBody String data){
log.info("微信扫码支付-异步通知返回的数据如下:");
log.info(data);
String successRet = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
String failedRet = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[系统错误]]></return_msg></xml>";
Settlement settle = null;
try {
if(StringUtils.isEmpty(data))
return failedRet;
//将从API返回的XML数据映射到Java对象
PayCallbackResData payCallbackResData = (PayCallbackResData) Util.getObjectFromXML(data, PayCallbackResData.class);
if(payCallbackResData == null || StringUtils.isEmpty(payCallbackResData.getOut_trade_no()))
return failedRet;
//0. 状态检验
String uuid = com.lenovohit.core.utils.StringUtils.uuid();
this.settlementManager.executeSql("UPDATE SSM_SETTLEMENT SET FLAG = ? where SETTLE_NO=? and STATUS=? and FLAG is null", uuid, payCallbackResData.getOut_trade_no(), Settlement.SETTLE_STAT_INITIAL);
settle = this.settlementManager.findOne("from Settlement where flag=? and settleNo=? and status=?", uuid, payCallbackResData.getOut_trade_no(), Settlement.SETTLE_STAT_INITIAL);
if(null == settle || !StringUtils.equals(Settlement.SETTLE_STAT_INITIAL, settle.getStatus())){
return successRet;
}
//1. 结算单处理
settle.getVariables().put("responseStr", data);
settle.getVariables().put("responseObject", payCallbackResData);
wxpayManager.payCallBack(settle);
this.settlementManager.save(settle);
//2. 订单处理
Order order = settle.getOrder();
if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_SUCCESS) ||
StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FINISH)){
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
//3. His通知
HisEntityResponse<DepositRecord> bizResponse = (HisEntityResponse<DepositRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getSerialNumber());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,交易失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FAILURE)){
order.setStatus(Order.ORDER_STAT_CLOSED);
order.setFinishTime(DateUtils.getCurrentDate());
}
this.orderManager.save(order);
} catch (Exception e) {
log.error("微信支付回传交易失败,结算单号为【" + settle.getSettleNo() + "】");
log.error("PayRestController forWXPayCallback exception", e);
e.printStackTrace();
}
return successRet;
}
/**
* 银联回调,由前台页面发起
* 0.状态校验 1.结算单处理 2.订单处理 3.回调业务逻辑通知HIS
* @param settleId
* @param data
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/callback/unionpay/{settleId}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forUnionPayCallback(@PathVariable("settleId") String settleId, @RequestBody String data){
Settlement payInfo = JSONUtils.deserialize(data, Settlement.class);
Settlement settle = null;
log.info("银联支付-异步通知返回的数据如下:");
log.info(data);
try {
//0. 状态检验
String uuid = com.lenovohit.core.utils.StringUtils.uuid();
this.settlementManager.executeSql("UPDATE SSM_SETTLEMENT SET FLAG=? where ID=? and STATUS=? and FLAG is null", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
settle = this.settlementManager.findOne("from Settlement where flag=? and id=? and status=?", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
if(null == settle || !StringUtils.equals(Settlement.SETTLE_STAT_INITIAL, settle.getStatus()))
return ResultUtils.renderFailureResult("结算状态错误!");
//1. 结算单处理
settle.getVariables().put("responseStr", payInfo.getRespText());
singleePayManager.payCallBack(settle);
this.settlementManager.save(settle);
//2. 订单处理
Order order = settle.getOrder();
if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_SUCCESS)){
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
//3. His通知
if(Order.BIZ_TYPE_PREPAY.equals(order.getBizType())){//住院
HisEntityResponse<ForegiftRecord> bizResponse = (HisEntityResponse<ForegiftRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getReceipt());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,记录失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
}else{
HisEntityResponse<DepositRecord> bizResponse = (HisEntityResponse<DepositRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getSerialNumber());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,记录失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FAILURE)){
order.setStatus(Order.ORDER_STAT_CLOSED);
order.setFinishTime(DateUtils.getCurrentDate());
}
this.orderManager.save(order);
return ResultUtils.renderSuccessResult(settle);
} catch (BaseException be) {
log.error("银联支付失败,结算单号为【"+ settle.getSettleNo() + "】");
be.printStackTrace();
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
log.error("银联支付失败,结算单号为【"+ settle.getSettleNo() + "】");
log.error("PayRestController forUnionPayCallback exception", e);
e.printStackTrace();
return ResultUtils.renderFailureResult("银联支付失败!");
}
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/callback/singleepay/{settleId}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forSingleePayCallback(@PathVariable("settleId") String settleId, @RequestBody String data){
Settlement payInfo = JSONUtils.deserialize(data, Settlement.class);
Settlement settle = null;
log.info("银联支付-异步通知返回的数据如下:");
log.info(data);
try {
//0. 状态检验
String uuid = com.lenovohit.core.utils.StringUtils.uuid();
this.settlementManager.executeSql("UPDATE SSM_SETTLEMENT SET FLAG=? where ID=? and STATUS=? and FLAG is null", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
settle = this.settlementManager.findOne("from Settlement where flag=? and id=? and status=?", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
if(null == settle || !StringUtils.equals(Settlement.SETTLE_STAT_INITIAL, settle.getStatus()))
return ResultUtils.renderFailureResult("结算状态错误!");
//1. 结算单处理
settle.getVariables().put("responseStr", payInfo.getRespText());
singleePayManager.payCallBack(settle);
this.settlementManager.save(settle);
//2. 订单处理
Order order = settle.getOrder();
if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_SUCCESS)){
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
//3. His通知
if(Order.BIZ_TYPE_PREPAY.equals(order.getBizType())){//住院
HisEntityResponse<ForegiftRecord> bizResponse = (HisEntityResponse<ForegiftRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getReceipt());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,记录失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
}else{
HisEntityResponse<DepositRecord> bizResponse = (HisEntityResponse<DepositRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getSerialNumber());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,记录失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FAILURE)){
order.setStatus(Order.ORDER_STAT_CLOSED);
order.setFinishTime(DateUtils.getCurrentDate());
}
this.orderManager.save(order);
return ResultUtils.renderSuccessResult(settle);
} catch (BaseException be) {
log.error("银联支付失败,结算单号为【"+ settle.getSettleNo() + "】");
be.printStackTrace();
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
log.error("银联支付失败,结算单号为【"+ settle.getSettleNo() + "】");
log.error("PayRestController forUnionPayCallback exception", e);
e.printStackTrace();
return ResultUtils.renderFailureResult("银联支付失败!");
}
}
/**
* 余额回调,调用his扣款接口
* @param settleId
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/callback/balance/{settleId}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forBalanceCallback(@PathVariable("settleId") String settleId){
Settlement settle = null;
try {
//0. 状态检验
String uuid = com.lenovohit.core.utils.StringUtils.uuid();
this.settlementManager.executeSql("UPDATE SSM_SETTLEMENT SET FLAG = ? where ID=? and STATUS=? and FLAG is null", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
settle = this.settlementManager.findOne("from Settlement where flag=? and id=? and status=?", uuid, settleId, Settlement.SETTLE_STAT_INITIAL);
if(null == settle || !StringUtils.equals(Settlement.SETTLE_STAT_INITIAL, settle.getStatus()))
return ResultUtils.renderFailureResult("结算状态错误!");
Order order = settle.getOrder();
if(null == order || !StringUtils.equals(Order.ORDER_STAT_INITIAL, order.getStatus()))
return ResultUtils.renderFailureResult("订单状态错误!");
//交易信息
settle.setTradeTime(new Date());// 交易时间
settle.setStatus(Settlement.SETTLE_STAT_PAY_SUCCESS);
this.settlementManager.save(settle);
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);//支付成功
order.setTranTime(DateUtils.getCurrentDate());
this.orderManager.save(order);//交易成功
HisEntityResponse<ForegiftRecord> bizResponse = (HisEntityResponse<ForegiftRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getReceipt());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,记录失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态 "+ order.getStatus());
}
this.orderManager.save(order);
return ResultUtils.renderSuccessResult(settle);
} catch (BaseException be) {
be.printStackTrace();
log.error("现金支付失败,结算单号为【"+ settle.getSettleNo() + "】");
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
e.printStackTrace();
log.error("现金支付失败,结算单号为【"+ settle.getSettleNo() + "】");
log.error("PayRestController forBalanceCallback exception", e);
return ResultUtils.renderFailureResult("现金支付失败!");
}
}
/**
* 现金回调
* @param settleId
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/callback/cash/{settleId}", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forCashCallback(@PathVariable("settleId") String settleId){
Settlement settle = null;
try {
if(StringUtils.isEmpty(settleId)) return ResultUtils.renderFailureResult("结算单id不许为空");
String uuid = com.lenovohit.core.utils.StringUtils.uuid();
this.settlementManager.executeSql("UPDATE SSM_SETTLEMENT SET FLAG = ? where ID=? and STATUS=? and FLAG is null", uuid, settleId, Settlement.SETTLE_STAT_PAY_SUCCESS);
settle = this.settlementManager.findOne("from Settlement where flag=? and id=? and status=?", uuid, settleId, Settlement.SETTLE_STAT_PAY_SUCCESS);
if(null == settle) return ResultUtils.renderFailureResult("不存在的结算单");
if(!StringUtils.equals(Settlement.SETTLE_STAT_PAY_SUCCESS, settle.getStatus()))
return ResultUtils.renderFailureResult("结算状态错误!");
Order order = settle.getOrder();
if(null == order || !StringUtils.equals(Order.ORDER_STAT_INITIAL, order.getStatus()))
return ResultUtils.renderFailureResult("订单状态错误!");
//TODO逻辑有问题, 只充值到自助机了,HIS未记账
if(order.getRealAmt().compareTo(order.getAmt()) == -1){
order.setStatus(Order.ORDER_STAT_PAY_FAILURE);//支付成功
order.setTranTime(DateUtils.getCurrentDate());
order = this.orderManager.save(order);//交易成功
settle.setOrder(order);
return ResultUtils.renderFailureResult("支付金额不足");
}
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);//支付成功
order.setTranTime(DateUtils.getCurrentDate());
this.orderManager.save(order);
HisEntityResponse<DepositRecord> bizResponse = (HisEntityResponse<DepositRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getSerialNumber());
order.setBizTime(bizResponse.getEntity().getPaymentTime());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//HIS交易成功,交易成功!
log.info("【"+ order.getOrderNo() + "】业务回调成功,修改订单状态, "+ order.getStatus());
} else {
order.setBizTime(DateUtils.getCurrentDateTimeStr());
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//HIS交易失败,记录失败!
log.info("【"+ order.getOrderNo() + "】业务回调失败,修改订单状态, "+ order.getStatus());
}
this.orderManager.save(order);//交易成功
return ResultUtils.renderSuccessResult(settle);
} catch (BaseException be) {
be.printStackTrace();
log.error("现金支付失败,订单号为【"+ settle.getOrder().getId() + "】");
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
e.printStackTrace();
log.error("现金支付失败,订单号为【"+ settle.getOrder().getId() + "】");
log.error("PayRestController forCashCallback exception", e);
return ResultUtils.renderFailureResult("现金支付失败!");
}
}
/**
* 退款
* @param settleId
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/refund", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forRefund(@RequestBody String data ){
Settlement settle = JSONUtils.deserialize(data, Settlement.class);
try {
settle = this.settlementManager.get(settle.getId());
//0. 状态检验
if(null == settle || !StringUtils.equals(Settlement.SETTLE_STAT_INITIAL, settle.getStatus())){
log.info("结算状态错误!");
return ResultUtils.renderFailureResult("结算状态错误!");
}
//1. 结算单处理
this.refundCall(settle);
this.settlementManager.save(settle);
//2. 订单处理
Order order = settle.getOrder();
if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUND_SUCCESS)){//2.1 退款成功处理
order.setStatus(Order.ORDER_STAT_REFUND_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());
HisResponse bizResponse = bizAfterRefund(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//交易成功
log.info("业务回调成功,修改订单状态 "+ order.getStatus());
} else {
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//交易失败
log.info("业务回调失败,修改订单状态 "+ order.getStatus());
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUNDING)){//2.2 退款中处理
order.setStatus(Order.ORDER_STAT_REFUNDING);
order.setTranTime(DateUtils.getCurrentDate());
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUND_FAILURE)
||StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUND_CANCELED)){//2.3 退款失败处理 || 退款被退汇
order.setStatus(Order.ORDER_STAT_REFUND_FAILURE);
order.setTranTime(DateUtils.getCurrentDate());
HisEntityResponse<HisOrder> bizResponse = (HisEntityResponse<HisOrder>)bizAfterRefund(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
Order _order = new Order();
this.buildCancelOrder(_order, order);
_order.setTranTime(DateUtils.getCurrentDate());
_order.setBizNo(bizResponse.getEntity().getRechargeNumber());
_order.setBizTime(bizResponse.getEntity().getPaymentTime());
_order.setStatus(Order.ORDER_STAT_CANCEL);
this.orderManager.save(_order);
order.setStatus(Order.ORDER_STAT_CLOSED);//交易关闭
order.setFinishTime(DateUtils.getCurrentDate());
log.info("业务回调成功,修改订单状态 "+ order.getStatus());
} else {
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//交易失败
log.info("业务回调失败,修改订单状态 "+ order.getStatus());
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_EXCEPTIONAL)){
order.setStatus(Order.ORDER_STAT_EXCEPTIONAL);
order.setTranTime(DateUtils.getCurrentDate());
}
this.orderManager.save(order);
return ResultUtils.renderSuccessResult(order);
} catch (BaseException be) {
log.error("渠道【"+ settle.getPayChannelCode()+"】退款失败,结算单号为【"+ settle.getSettleNo() + "】");
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
log.error("渠道【"+ settle.getPayChannelCode()+"】退款失败,结算单号为【"+ settle.getSettleNo() + "】");
log.error("PayRestController forRefund exception", e);
e.printStackTrace();
return ResultUtils.renderFailureResult("退款后台处理失败!");
}
}
/**
* 结算单状态同步
* @param settleId
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/syncState/{settleId}",method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forSyncState(@PathVariable("settleId") String settleId){
Settlement settle = null;
try {
settle = this.settlementManager.get(settleId);
if(null == settle){
return ResultUtils.renderFailureResult("未找到对应结算单!!!");
}
//1. 结算单同步状态
buildSyncSateSettlement(settle);
syncStateCall(settle);
this.settlementManager.save(settle);
//2. 订单处理
Order order = settle.getOrder();
if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_SUCCESS) ||
StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FINISH)){//2.1 支付成功处理
//已经做过HIS交易的直接返回成功
if(StringUtils.equals(order.getStatus(), Order.ORDER_STAT_TRAN_SUCCESS) ||
StringUtils.equals(order.getStatus(), Order.ORDER_STAT_TRAN_FINISH)) {
return ResultUtils.renderSuccessResult(settle);
//登记HIS交易
} else {
order.setStatus(Order.ORDER_STAT_PAY_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
//3. His通知
HisEntityResponse<DepositRecord> bizResponse = (HisEntityResponse<DepositRecord>)bizAfterPay(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setBizNo(bizResponse.getEntity().getSerialNumber());
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//交易成功
log.info("业务回调成功,修改订单状态 "+ order.getStatus());
} else {
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//交易失败
log.info("业务回调失败,修改订单状态 "+ order.getStatus());
}
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_PAY_FAILURE)){//2.2 支付失败处理
order.setStatus(Order.ORDER_STAT_PAY_FAILURE);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUND_SUCCESS)){//2.3 退款成功处理
//已经做过HIS交易的直接返回成功
if(StringUtils.equals(order.getStatus(), Order.ORDER_STAT_TRAN_SUCCESS) ||
StringUtils.equals(order.getStatus(), Order.ORDER_STAT_TRAN_FINISH)) {
return ResultUtils.renderSuccessResult(settle);
//登记HIS交易
} else {
order.setStatus(Order.ORDER_STAT_REFUND_SUCCESS);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
HisResponse bizResponse = bizAfterRefund(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
order.setStatus(Order.ORDER_STAT_TRAN_SUCCESS);//交易成功
log.info("业务回调成功,修改订单状态 "+ order.getStatus());
} else {
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//交易失败
log.info("业务回调失败,修改订单状态 "+ order.getStatus());
}
}
} else if(StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUND_FAILURE) ||
StringUtils.equals(settle.getStatus(), Settlement.SETTLE_STAT_REFUND_CANCELED) ){//2.4 退款失败|| 退款被撤销
//考虑HIS已记账情况下的订单不通知HIS,需手工处理
if(StringUtils.equals(order.getStatus(), Order.ORDER_STAT_TRAN_SUCCESS) ||
StringUtils.equals(order.getStatus(), Order.ORDER_STAT_TRAN_FINISH) ||
StringUtils.equals(order.getStatus(), Order.ORDER_STAT_REFUND_CANCELED) ||
StringUtils.equals(order.getStatus(), Order.ORDER_STAT_CLOSED)) {
return ResultUtils.renderSuccessResult(settle);
//HIS未记账或者退款取消状态下
} else {
order.setStatus(Order.ORDER_STAT_REFUND_FAILURE);
order.setTranTime(DateUtils.getCurrentDate());
order.setRealAmt(settle.getAmt());//此时记录真正支付的金额
//解冻接口
HisEntityResponse<HisOrder> bizResponse = (HisEntityResponse<HisOrder>)bizAfterRefund(order, settle);
if( null != bizResponse && bizResponse.isSuccess()){
Order _order = new Order();
this.buildCancelOrder(_order, order);
_order.setTranTime(DateUtils.getCurrentDate());
_order.setBizNo(bizResponse.getEntity().getRechargeNumber());
_order.setBizTime(bizResponse.getEntity().getPaymentTime());
_order.setStatus(Order.ORDER_STAT_CANCEL);
this.orderManager.save(_order);
order.setStatus(Order.ORDER_STAT_CLOSED);//交易关闭
order.setFinishTime(DateUtils.getCurrentDate());
log.info("业务回调成功,修改订单状态 "+ order.getStatus());
} else {
order.setStatus(Order.ORDER_STAT_TRAN_FAILURE);//交易失败
log.info("业务回调失败,修改订单状态 "+ order.getStatus());
}
}
} else {
//其他状态,业务不做处理
}
this.orderManager.save(order);
return ResultUtils.renderSuccessResult(settle);
} catch (BaseException be) {
log.error("同步订单状态失败,结算单号为【"+ settle.getSettleNo() + "】");
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
log.error("同步订单状态失败,结算单号为【"+ settle.getSettleNo() + "】");
log.error("PayRestController forSyncState exception", e);
return ResultUtils.renderFailureResult("同步订单状态失败!");
}
}
/**
* 卡状态同步
* @param settleId
* @return
*/
@RequestMapping(value = "/card/state",method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forCardState(@RequestParam(value = "data", defaultValue = "") String data){
//生成充值结算单
Settlement baseInfo = JSONUtils.deserialize(data, Settlement.class);
try {
buildCardSettlement(baseInfo);
this.bankPayManager.queryCard(baseInfo);
return ResultUtils.renderSuccessResult(baseInfo);
} catch (BaseException be) {
log.error("卡状态查询失败,卡号为【"+ baseInfo.getPayerAccount() + "】");
return ResultUtils.renderFailureResult(be.getMessage());
} catch (Exception e) {
log.error("卡状态查询失败,卡号为【"+ baseInfo.getPayerAccount() + "】");
return ResultUtils.renderFailureResult("卡状态查询失败!");
}
}
/**
* 预支付调用
* @param order
* @throws Exception
*/
private void precreateCall(Settlement settle){
try {
if ("9999".equals(settle.getPayChannelCode())) {
alipayManager.precreate(settle);
} else if ("9998".equals(settle.getPayChannelCode())) {
wxpayManager.precreate(settle);
} else if ("0000".equals(settle.getPayChannelCode())) {
//现金没有预支付
} else if ("balance".equals(settle.getPayChannelCode())) {
//余额没有预支付
} else {
//银行没有预支付
}
} catch (Exception e) {
settle.setStatus(Settlement.SETTLE_STAT_CLOSED);
log.error("渠道【" +settle.getPayChannelCode()+"】结算单【"+settle.getSettleNo()+"】预支付系统异常,交易状态关闭!!!");
log.error("PayRestController precreateCall exception", e);
e.printStackTrace();
}
// TODO 后期考虑动态调用
}
/**
* 退款调用
* @param order
* @throws Exception
*/
private void refundCall(Settlement settle) {
try {
if ("9999".equals(settle.getPayChannelCode())) {
alipayManager.refund(settle);
} else if ("9998".equals(settle.getPayChannelCode())) {
wxpayManager.refund(settle);
} else if ("0308".equals(settle.getPayChannelCode())) {
cmbPayManager.refund(settle);
} else if ("0000".equals(settle.getPayChannelCode())) {
//现金没有退款
} else if ("balance".equals(settle.getPayChannelCode())) {
//余额没有退款
} else {
bankPayManager.refund(settle);
}
} catch (Exception e) {
settle.setStatus(Settlement.SETTLE_STAT_EXCEPTIONAL);
log.error("渠道【" +settle.getPayChannelCode()+"】结算单【"+settle.getSettleNo()+"】 退款系统异常,交易状态异常!!!");
log.error("PayRestController refundCall exception", e);
e.printStackTrace();
}
// TODO 后期考虑动态调用
}
/**
* 同步状态
* @param order
* @throws Exception
*/
private void syncStateCall(Settlement settle){
try {
if( "9999".equals(settle.getPayChannelCode())){
if(StringUtils.equals(Settlement.SETTLE_TYPE_PAY, settle.getSettleType())){
alipayManager.query(settle);
} else if(StringUtils.equals(Settlement.SETTLE_TYPE_REFUND, settle.getSettleType())){
alipayManager.refundQuery(settle);
}
} else if( "9998".equals(settle.getPayChannelCode())){
if(StringUtils.equals(Settlement.SETTLE_TYPE_PAY, settle.getSettleType())){
wxpayManager.query(settle);
} else if(StringUtils.equals(Settlement.SETTLE_TYPE_REFUND, settle.getSettleType())){
wxpayManager.refundQuery(settle);
}
} else if( "0308".equals(settle.getPayChannelCode())){
if(StringUtils.equals(Settlement.SETTLE_TYPE_PAY, settle.getSettleType())){
unionPayManager.query(settle);
} else if(StringUtils.equals(Settlement.SETTLE_TYPE_REFUND, settle.getSettleType())){
cmbPayManager.refundQuery(settle);
}
} else if( "0000".equals(settle.getPayChannelCode())){
} else if( "0105".equals(settle.getPayChannelCode())){//建行走新利
if(StringUtils.equals(Settlement.SETTLE_TYPE_PAY, settle.getSettleType())){
System.out.println("[大庆建设银行支付]");
singleePayManager.query(settle);
} else if(StringUtils.equals(Settlement.SETTLE_TYPE_REFUND, settle.getSettleType())){
}
}else {
if(StringUtils.equals(Settlement.SETTLE_TYPE_PAY, settle.getSettleType())){
unionPayManager.query(settle);
} else if(StringUtils.equals(Settlement.SETTLE_TYPE_REFUND, settle.getSettleType())){
bankPayManager.refundQuery(settle);
}
}
} catch (Exception e) {//同步操作,交易异常时不做状态更新
log.error("渠道【" +settle.getPayChannelCode()+"】结算单【"+settle.getSettleNo()+"】查询系统异常,交易状态不变!!!");
log.error("PayRestController syncStateCall exception", e);
e.printStackTrace();
}
// TODO 后期考虑动态调用
}
/*******************************************************************
* 工具方法 *
*******************************************************************/
private void buildPaySettlement(Settlement settlement) {
if (null == settlement) {
throw new NullPointerException("settlement should not be NULL!");
}
/**订单信息**/
if (null == settlement.getOrder() || StringUtils.isEmpty(settlement.getOrder().getId())) {
throw new NullPointerException("orderId should not be NULL!");
}
Order order = this.orderManager.get(settlement.getOrder().getId());
if (null == order){
throw new NullPointerException("order should not be NULL!");
}
settlement.setOrder(order);
/**基本信息**/
settlement.setSettleNo(SettleSeqCalculator.calculateCode(Settlement.SETTLE_TYPE_PAY));//结算单号
settlement.setSettleType(Settlement.SETTLE_TYPE_PAY);//结算类型
if(StringUtils.isEmpty(settlement.getStatus())){
settlement.setStatus(Settlement.SETTLE_STAT_INITIAL);//结算状态
}
if(StringUtils.isEmpty(settlement.getSettleTitle())){
settlement.setSettleTitle(order.getOrderTitle());
}
if(StringUtils.isEmpty(settlement.getSettleDesc())){
settlement.setSettleDesc(order.getOrderDesc());
}
if(StringUtils.isEmpty(settlement.getAmt()) || settlement.getAmt().compareTo(new BigDecimal(0)) != 1){
throw new NullPointerException("Amt should not be NULL Or not be <= 0");
}
//settlement.setqrCode;//预支付后生成
/**渠道信息 【 银联 支付宝 微信 现金】**/
if (StringUtils.isEmpty(settlement.getPayChannelCode())) {
throw new NullPointerException("payChannelCode should not be NULL!");
}
PayChannel payChannel = payChannelManager.findOne("from PayChannel where code = ?", settlement.getPayChannelCode());
if (null == payChannel){
throw new NullPointerException("payChannel should not be NULL!");
}
settlement.setPayChannel(payChannel);
settlement.setPayChannelId(payChannel.getId());
settlement.setPayChannelCode(payChannel.getCode());
settlement.setPayChannelName(payChannel.getName());
/**支付类型**/
if (StringUtils.isEmpty(settlement.getPayTypeCode())) {
throw new NullPointerException("payTypeCode should not be NULL!");
}
settlement.setPayTypeId("");
settlement.setPayTypeCode(settlement.getPayTypeCode());;
settlement.setPayTypeName("");
//付款人信息
//settlement.setPayerNo();//结算后赋值
//settlement.setPayerName();//结算后赋值
//settlement.setPayerAccount();//结算后赋值
//settlement.setPayerAcctType();//结算后赋值
//settlement.setPayerAcctBank();//结算后赋值
//settlement.setPayerPhone();//结算后赋值
//终端信息 支付后获取
//settlement.setTerminalId();//结算后赋值
//settlement.setTerminalCode();//结算后赋值
//settlement.setTerminalName();//结算后赋值
//settlement.setTerminalUser();//结算后赋值
//自助机信息
Machine machine = this.getCurrentMachine();
settlement.setMachineId(machine.getId());//自助机id
settlement.setMachineMac(machine.getMac());//自助机mac地址
settlement.setMachineCode(machine.getCode());
settlement.setMachineName(machine.getName());//自助机名称
settlement.setMachineUser(machine.getHisUser());
settlement.setMachineMngCode(machine.getMngCode());
//审计信息
settlement.setCreateTime(new Date());//创建时间
//settle.setOutTime("");//TODO 超时时间
}
private void buildSyncSateSettlement(Settlement settlement) {
if (null == settlement) {
throw new NullPointerException("settlement should not be NULL!");
}
if (StringUtils.isEmpty(settlement.getPayChannelCode())) {
throw new NullPointerException("payChannelCode should not be NULL!");
}
PayChannel payChannel = payChannelManager.findOne("from PayChannel where code = ?", settlement.getPayChannelCode());
if (null == payChannel){
throw new NullPointerException("payChannel should not be NULL!");
}
settlement.setPayChannel(payChannel);
}
private void buildCardSettlement(Settlement settlement) {
if (null == settlement) {
throw new NullPointerException("settlement should not be NULL!");
}
if (StringUtils.isEmpty(settlement.getPayChannelCode())) {
throw new NullPointerException("payChannelCode should not be NULL!");
}
if (StringUtils.isEmpty(settlement.getPayerAccount())) {
throw new NullPointerException("payerAccount should not be NULL!");
}
/**渠道信息 【 银联 支付宝 微信 现金】**/
if (StringUtils.isEmpty(settlement.getPayChannelCode())) {
throw new NullPointerException("payChannelCode should not be NULL!");
}
PayChannel payChannel = payChannelManager.findOne("from PayChannel where code = ?", settlement.getPayChannelCode());
if (null == payChannel){
throw new NullPointerException("payChannel should not be NULL!");
}
settlement.setPayChannel(payChannel);
settlement.setPayChannelId(payChannel.getId());
settlement.setPayChannelCode(payChannel.getCode());
settlement.setPayChannelName(payChannel.getName());
}
private void buildCancelOrder(Order _order, Order oriOrder) {
if (null == _order || null == oriOrder) {
throw new NullPointerException("_order or oriOrder should not be NULL!");
}
//订单基本信息
_order.setOrderNo(OrderSeqCalculator.calculateCode(Order.ORDER_TYPE_CANCEL));
_order.setOrderType(Order.ORDER_TYPE_CANCEL);
_order.setOrderTitle("患者 "+oriOrder.getPatientName()+" 自助机取消退款 " + oriOrder.getAmt() + " 元!");
_order.setOrderDesc("患者 "+oriOrder.getPatientName()+" 自助机取消退款 " + oriOrder.getAmt() + " 元!");
_order.setStatus(Order.ORDER_STAT_INITIAL);
_order.setAmt(oriOrder.getAmt());
//订单业务信息
_order.setBizType(Order.BIZ_TYPE_PRESTORE);//门诊预存
_order.setBizNo("");//发起取消是为null
_order.setBizBean("");
//订单机器信息
_order.setMachineId(oriOrder.getMachineId());
_order.setMachineMac(oriOrder.getMachineMac());
_order.setMachineCode(oriOrder.getMachineCode());
_order.setMachineName(oriOrder.getMachineName());
_order.setMachineUser(oriOrder.getMachineUser());
_order.setMachineMngCode(oriOrder.getMachineMngCode());
//订单用户信息
_order.setHisNo(oriOrder.getHisNo());
_order.setPatientNo(oriOrder.getPatientNo());
_order.setPatientName(oriOrder.getPatientName());
_order.setCreateTime(DateUtils.getCurrentDate());
_order.setOriOrder(oriOrder);
}
/**
* 根据 结算单支付情况回调业务
* @param order
* @throws Exception
*/
private HisResponse bizAfterPay(Order order, Settlement settle){
HisResponse hisResponse = null;
try {
HisPayManager hisOrderManager = (HisPayManager) this.getApplicationContext().getBean(order.getBizBean());
hisResponse = hisOrderManager.bizAfterPay(order, settle);
} catch (Exception e) {
log.error("支付成功后业务回调失败,结算单号【" + settle.getSettleNo() + "】,订单号【" + order.getOrderNo() + "】,业务类型【"
+ order.getBizType() + "】,业务单号【" + order.getBizNo() + "】");
e.printStackTrace();
}
return hisResponse;
}
/**
* 根据 结算单退款情况回调业务
* @param order
* @throws Exception
*/
private HisResponse bizAfterRefund(Order order, Settlement settle){
HisResponse hisResponse = null;
try {
HisPayManager hisOrderManager = (HisPayManager) this.getApplicationContext().getBean(order.getBizBean());
hisResponse = hisOrderManager.bizAfterRefund(order, settle);
} catch (Exception e) {
log.error("退款成功后业务回调失败,结算单号【" + settle.getSettleNo() + "】,订单号【" + order.getOrderNo() + "】,业务类型【"
+ order.getBizType() + "】,业务单号【" + order.getBizNo() + "】");
e.printStackTrace();
}
return hisResponse;
}
private Map<String, String> parseUrlToMap(String str){
Map<String, String> tm = new TreeMap<String, String>();
String[] ss = str.split("\\&");
for (String s : ss) {
String[] subs = s.split("\\=", 2);
tm.put(subs[0], subs[1]);
}
return tm;
}
}
|
package Medium;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author:choumei
* @date:2019/11/2422:24
* @Description: 请你来实现一个 atoi 函数,使其能将字符串转换成整数。
*
* 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。
*
* 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。
*
* 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。
*
* 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。
*
* 在任何情况下,若函数不能进行有效的转换时,请返回 0。
*
* 说明:
*
* 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231, 231 − 1]。如果数值超过这个范围,请返回 INT_MAX (231 − 1) 或 INT_MIN (−231) 。
*
* 示例 1:
*
* 输入: "42"
* 输出: 42
* 示例 2:
*
* 输入: " -42"
* 输出: -42
* 解释: 第一个非空白字符为 '-', 它是一个负号。
* 我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。
* 示例 3:
*
* 输入: "4193 with words"
* 输出: 4193
* 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。
* 示例 4:
*
* 输入: "words and 987"
* 输出: 0
* 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。
* 因此无法执行有效的转换。
* 示例 5:
*
* 输入: "-91283472332"
* 输出: -2147483648
* 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。
* 因此返回 INT_MIN (−231) 。
*
*/
public class stringToInteger_8 {
public static void main(String[] args) {
//System.out.println(myAutoi(" -5555533332dsd123fg24"));
System.out.println(stringToInteger(""));
}
public static int myAutoi(String str){
int rst = 0;
str = str.trim();
Pattern pattern = Pattern.compile("^[\\+\\-]?\\d+");
Matcher matcher = pattern.matcher(str);
if(matcher.find()){
try{
rst = Integer.parseInt(str.substring(matcher.start(),matcher.end()));
}catch(Exception e){
rst = str.charAt(0) == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
}
return rst;
}
//自解
public static Integer stringToInteger(String str){
str = str.trim();
if(str.length() == 0) return 0;
Integer rst = -1;
int flag = 1;
Pattern p = Pattern.compile("^\\d");
for(char curChar: str.toCharArray()){
Matcher m = p.matcher(curChar+"");
//第一个有效位为‘+’ ‘-’
if(rst == -1 && (curChar == '+' || curChar == '-' || curChar == ' ' || m.find() ) ){
switch (curChar){
case '+':
rst++;
flag = 1;
break;
case '-':
rst++;
flag = -1;
break;
case ' ':
break;
default:
rst++;
Integer n = Integer.parseInt(curChar+"");
rst = n;
}
}else if(rst != -1 ){
if(m.find()){
Integer n = Integer.parseInt(curChar+"");
if(flag > 0 && (rst > Integer.MAX_VALUE/10 || (rst == Integer.MAX_VALUE/10 && n > 7)) ) return Integer.MAX_VALUE;
if(flag < 0 && (-rst < Integer.MIN_VALUE/10 || (-rst == Integer.MIN_VALUE/10 && n > 8)) ) return Integer.MIN_VALUE;
rst = rst * 10 + n;
/*try{
rst = rst*10 + n;
}catch(Exception e){
return flag < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}*/
}else{
return flag * rst;
}
}else{
return 0;
}
}
return rst*flag;
}
}
|
package fr.skytasul.quests.utils.nms;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.ItemMeta;
import fr.skytasul.quests.BeautyQuests;
import fr.skytasul.quests.utils.ReflectUtils;
import io.netty.buffer.ByteBuf;
public abstract class NMS{
private ReflectUtils nmsReflect = ReflectUtils.fromPackage("net.minecraft.server." + getClass().getSimpleName());
private ReflectUtils craftReflect = ReflectUtils.fromPackage("org.bukkit.craftbukkit." + getClass().getSimpleName());
private Field unhandledTags;
private Method equalsCommon;
public NMS() {
if (!(this instanceof NullNMS)) {
try {
Class<?> itemMetaClass = craftReflect.fromName("inventory.CraftMetaItem");
unhandledTags = itemMetaClass.getDeclaredField("unhandledTags");
equalsCommon = itemMetaClass.getDeclaredMethod("equalsCommon", itemMetaClass);
unhandledTags.setAccessible(true);
equalsCommon.setAccessible(true);
}catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
public abstract Object bookPacket(ByteBuf buf);
public abstract double entityNameplateHeight(Entity en); // can be remplaced by Entity.getHeight from 1.11
public List<String> getAvailableBlockProperties(Material material){
throw new UnsupportedOperationException();
}
public List<String> getAvailableBlockTags() {
throw new UnsupportedOperationException();
}
public boolean equalsWithoutNBT(ItemMeta meta1, ItemMeta meta2) throws ReflectiveOperationException {
((Map<?, ?>) unhandledTags.get(meta1)).clear();
((Map<?, ?>) unhandledTags.get(meta2)).clear();
return (boolean) equalsCommon.invoke(meta1, meta2);
}
public ReflectUtils getNMSReflect(){
return nmsReflect;
}
public ReflectUtils getCraftReflect(){
return craftReflect;
}
public abstract void sendPacket(Player p, Object packet);
public static NMS getNMS() {
return nms;
}
public static boolean isValid() {
return versionValid;
}
public static int getMCVersion() {
return versionMajor;
}
public static int getNMSMinorVersion() {
return versionMinorNMS;
}
public static String getVersionString() {
return versionString;
}
private static boolean versionValid = false;
private static NMS nms;
private static int versionMajor;
private static int versionMinorNMS;
private static String versionString;
static {
versionString = Bukkit.getBukkitVersion().split("-R")[0];
String version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1);
String[] versions = version.split("_");
versionMajor = Integer.parseInt(versions[1]); // 1.X
if (versionMajor >= 17) {
// e.g. Bukkit.getBukkitVersion() -> 1.17.1-R0.1-SNAPSHOT
versions = versionString.split("\\.");
versionMinorNMS = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]);
}else versionMinorNMS = Integer.parseInt(versions[2].substring(1)); // 1.X.Y
try {
nms = (NMS) Class.forName("fr.skytasul.quests.utils.nms.v" + version).newInstance();
versionValid = true;
BeautyQuests.logger.info("Loaded valid Minecraft version " + version + ".");
}catch (ClassNotFoundException ex) {
BeautyQuests.logger.warning("The Minecraft version " + version + " is not supported by BeautyQuests.");
}catch (Exception ex) {
BeautyQuests.logger.warning("An error ocurred when loading Minecraft Server version " + version + " compatibilities.", ex);
}
if (!versionValid) {
nms = new NullNMS();
BeautyQuests.logger.warning("Some functionnalities of the plugin have not been enabled.");
}
}
}
|
package com.neo;
import com.neo.listener.ApplicationContextInitializedEventListener;
import com.neo.listener.ApplicationEnvironmentPreparedEventListener;
import com.neo.listener.ApplicationFailedEventListener;
import com.neo.listener.ApplicationPreparedEventListener;
import com.neo.listener.ApplicationReadyEventListener;
import com.neo.listener.ApplicationStartedEventListener;
import com.neo.listener.ApplicationStartingEventListener;
import com.neo.listener.ContextRefreshedEventListener;
import com.neo.listener.customer.MyEvent;
import java.util.stream.IntStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@Slf4j
@SpringBootApplication
public class HelloApplication {
@Bean
public ExitCodeGenerator exitCodeGenerator() {
log.info("application will be exit with code 42");
return () -> 42;
}
public static void main(String[] args) {
// SpringApplication.run(HelloApplication.class, args);
/*----------- Customizing SpringApplication -----------*/
SpringApplication springApplication = new SpringApplication(HelloApplication.class);
springApplication.addListeners(new ApplicationStartingEventListener());
springApplication.addListeners(new ApplicationEnvironmentPreparedEventListener());
springApplication.addListeners(new ApplicationContextInitializedEventListener());
springApplication.addListeners(new ApplicationPreparedEventListener());
springApplication.addListeners(new ApplicationStartedEventListener());
springApplication.addListeners(new ApplicationReadyEventListener());
springApplication.addListeners(new ApplicationFailedEventListener());
springApplication.addListeners(new ContextRefreshedEventListener());
ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
// execute event listener thread is sample with publish thread
IntStream.rangeClosed(1, 2).forEach(i -> configurableApplicationContext.publishEvent(MyEvent.of("No." + i)));
System.exit(SpringApplication.exit(configurableApplicationContext));
}
}
|
package com.thinkgem.jeesite.modules.cms.web;
import com.thinkgem.jeesite.common.config.Global;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.cms.entity.CmsArticleMovie;
import com.thinkgem.jeesite.modules.cms.service.CmsArticleMovieService;
/**
* 文章视频Controller
* @author gff
* @version 2018-05-18
*/
@Controller
@RequestMapping(value = "${adminPath}/cms/cmsArticleMovie")
public class CmsArticleMovieController extends BaseController {
private static final String FUNCTION_NAME_SIMPLE = "文章视频";
@Autowired
private CmsArticleMovieService cmsArticleMovieService;
@ModelAttribute
public CmsArticleMovie get(@RequestParam(required=false) String id) {
CmsArticleMovie entity = null;
if (StringUtils.isNotBlank(id)){
entity = cmsArticleMovieService.get(id);
}
if (entity == null){
entity = new CmsArticleMovie();
}
return entity;
}
@RequiresPermissions("cms:cmsArticleMovie:view")
@RequestMapping(value = {"list", ""})
public String list(CmsArticleMovie cmsArticleMovie, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<CmsArticleMovie> page = cmsArticleMovieService.findPage(new Page<CmsArticleMovie>(request, response), cmsArticleMovie);
model.addAttribute("page", page);
model.addAttribute("ename", "cmsArticleMovie");
setBase64EncodedQueryStringToEntity(request, cmsArticleMovie);
return "modules/cms/cmsArticleMovie/cmsArticleMovieList";
}
@RequiresPermissions("cms:cmsArticleMovie:view")
@RequestMapping(value = "form")
public String form(CmsArticleMovie cmsArticleMovie, Model model) {
model.addAttribute("cmsArticleMovie", cmsArticleMovie);
model.addAttribute("ename", "cmsArticleMovie");
return "modules/cms/cmsArticleMovie/cmsArticleMovieForm";
}
@RequiresPermissions("cms:cmsArticleMovie:edit")
@RequestMapping(value = "save")
public String save(CmsArticleMovie cmsArticleMovie, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, cmsArticleMovie)){
return form(cmsArticleMovie, model);
}
addMessage(redirectAttributes, StringUtils.isBlank(cmsArticleMovie.getId()) ? "保存"+FUNCTION_NAME_SIMPLE+"成功" : "修改"+FUNCTION_NAME_SIMPLE+"成功");
cmsArticleMovieService.save(cmsArticleMovie);
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
@RequiresPermissions("cms:cmsArticleMovie:edit")
@RequestMapping(value = "disable")
public String disable(CmsArticleMovie cmsArticleMovie, RedirectAttributes redirectAttributes) {
cmsArticleMovieService.disable(cmsArticleMovie);
addMessage(redirectAttributes, "禁用"+FUNCTION_NAME_SIMPLE+"成功");
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
@RequiresPermissions("cms:cmsArticleMovie:edit")
@RequestMapping(value = "delete")
public String delete(CmsArticleMovie cmsArticleMovie, RedirectAttributes redirectAttributes) {
cmsArticleMovieService.delete(cmsArticleMovie);
addMessage(redirectAttributes, "删除"+FUNCTION_NAME_SIMPLE+"成功");
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
@RequiresPermissions("cms:cmsArticleMovie:edit")
@RequestMapping(value = "deleteBatch")
public String deleteBatch(CmsArticleMovie cmsArticleMovie, RedirectAttributes redirectAttributes) {
cmsArticleMovieService.deleteByIds(cmsArticleMovie);
addMessage(redirectAttributes, "批量删除"+FUNCTION_NAME_SIMPLE+"成功");
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
/**
* 导出数据
*/
@RequiresPermissions("cms:cmsArticleMovie:edit")
@RequestMapping(value = "export", method = RequestMethod.POST)
public String exportFile(CmsArticleMovie cmsArticleMovie, HttpServletRequest request,
HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = FUNCTION_NAME_SIMPLE + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
new ExportExcel(FUNCTION_NAME_SIMPLE, CmsArticleMovie.class).setDataList(cmsArticleMovieService.findList(cmsArticleMovie)).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导出" + FUNCTION_NAME_SIMPLE + "失败!失败信息:" + e.getMessage());
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
}
/**
* 下载导入数据模板
*/
@RequiresPermissions("cms:cmsArticleMovie:view")
@RequestMapping(value = "import/template")
public String importFileTemplate(CmsArticleMovie cmsArticleMovie, HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = FUNCTION_NAME_SIMPLE + "导入模板.xlsx";
List<CmsArticleMovie> list = cmsArticleMovieService.findPage(new Page<CmsArticleMovie>(1, 5), new CmsArticleMovie()).getList();
if (list == null) {
list = Lists.newArrayList();
}
if (list.size() < 1) {
list.add(new CmsArticleMovie());
}
new ExportExcel(FUNCTION_NAME_SIMPLE, CmsArticleMovie.class).setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导入模板下载失败!失败信息:" + e.getMessage());
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
}
/**
* 导入数据<br>
*/
@RequiresPermissions("cms:cmsArticleMovie:edit")
@RequestMapping(value = "import", method = RequestMethod.POST)
public String importFile(CmsArticleMovie cmsArticleMovie, MultipartFile file, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
try {
long beginTime = System.currentTimeMillis();//1、开始时间
StringBuilder failureMsg = new StringBuilder();
ImportExcel ei = new ImportExcel(file, 1, 0);
List<CmsArticleMovie> list = ei.getDataList(CmsArticleMovie.class);
List<CmsArticleMovie> insertList=new ArrayList<CmsArticleMovie>();
List<CmsArticleMovie> subList=new ArrayList<CmsArticleMovie>();
int batchinsertSize=500;
int batchinsertCount=list.size()/batchinsertSize+(list.size()%batchinsertSize==0?0:1);
int addNum=0;
int updateNum=0;
int toIndex=0;
for(int i=0;i<batchinsertCount;i++)
{
insertList=new ArrayList<CmsArticleMovie>();
toIndex=(i+1)*batchinsertSize;
if(toIndex>list.size())
toIndex=list.size();
subList=list.subList(i*batchinsertSize, toIndex);
for(CmsArticleMovie zsJh : subList)
{
zsJh.preInsert();
insertList.add(zsJh);
}
if(insertList!=null&&insertList.size()>0)
{
//System.out.println("insertList size is :"+insertList.size());
cmsArticleMovieService.batchInsertUpdate(insertList);
addNum+=insertList.size();
}
}
long endTime = System.currentTimeMillis(); //2、结束时间
addMessage(redirectAttributes, "执行时间"+DateUtils.formatDateTime(endTime - beginTime)+",导入 "+addNum+"条"+FUNCTION_NAME_SIMPLE+"信息,"+failureMsg);
//System.out.println("执行时间:"+DateUtils.formatDateTime(endTime - beginTime));
} catch (Exception e) {
addMessage(redirectAttributes, "导入"+FUNCTION_NAME_SIMPLE+"信息失败!失败信息:"+e.getMessage());
}
return "redirect:"+adminPath+"/cms/cmsArticleMovie/?repage&" + StringUtils.trimToEmpty(getBase64DecodedQueryStringFromEntity(cmsArticleMovie));
}
} |
package kr.co.flyingturtle.repository.mapper;
import java.util.List;
import kr.co.flyingturtle.repository.vo.Memo;
public interface MemoMapper {
// 과목 조회
List<Memo> selectMemoSbj(int memberNo);
// 과목 조회 (1개)
Memo selectOneSbj(int sbjNo);
// 과목 생성
int insertMemoSbj(Memo memo);
// 과목 수정
void updateSbjName(Memo memo);
// 과목 삭제
void deleteMemoSbj(int sbjNo);
// 임시 -> 저장 (과목선택시)
void updateMemoSbj(Memo memo);
// 메모 조회
List<Memo> selectMemoList(Memo memo);
// 메모 조회(1개)
Memo selectOneMemo(int memoNo);
// 메모 등록
int insertMemo(Memo memo);
// 메모 수정
void updateMemo(Memo memo);
// 메모 삭제
void deleteMemo(int memoNo);
}
|
package cn.edu.nju.software.timemachine.action.user;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import cn.edu.nju.software.timemachine.action.BaseAction;
import cn.edu.nju.software.timemachine.entity.User;
import cn.edu.nju.software.timemachine.service.IUserService;
@Controller
@Scope("prototype")
public class ChangeInfoAction extends BaseAction{
/**
*
*/
private static final long serialVersionUID = 1L;
private String json;
@Autowired
private IUserService<User> userService;
public IUserService<User> getUserService() {
return userService;
}
public void setUserService(IUserService<User> userService) {
this.userService = userService;
}
public void changeInfo() throws Exception{
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject.toString());
String sex = jsonObject.getString("sex");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = jsonObject.getString("birthday");
Date birthday = format.parse(dateStr);
Calendar c=Calendar.getInstance();
c.setTime(birthday);
String city = jsonObject.getString("city");
String otherStuff = jsonObject.getString("remark");
String password = jsonObject.getString("password");
User user = userService.getUser((Long)session.get("userId"));
if(dateStr!="" && dateStr!=null){
user.getUserMeta().setBirthday(c);
}
if(sex!=null && sex !=""){
user.getUserMeta().setSex(sex);
}
if(city!=null && city!=""){
user.getUserMeta().setCity(city);
}
if(otherStuff != null && otherStuff !=""){
user.getUserMeta().setOtherStuff(otherStuff);
}
if(password!="" && password !=null){
user.setPassword(password);
}
if(userService.update(user)){
json = "{\"msg\":\"1\"}";
}else{
json = "{\"msg\":\"2\"}";
}
sendMsg(json);
}
public void setJson(String json) {
this.json = json;
}
public String getJson() {
return json;
}
}
|
package com.wgcisotto.creational.singleton;
import java.util.Objects;
public class DbSingletonLazyLoaded {
private DbSingletonLazyLoaded(){}
private static DbSingletonLazyLoaded instance = null;
public static DbSingletonLazyLoaded getInstance() {
if(Objects.isNull(instance)){
instance = new DbSingletonLazyLoaded();
}
return instance;
}
}
|
package MVC.controllers;
import java.awt.event.*;
import MVC.models.inventoryModel;
import MVC.views.addPartsView;
import MVC.views.showPartsView;
public class menuController implements ActionListener{
private inventoryModel model;
private showPartsView view;
private addPartsView addView;
//private addInvsView addinvView;
//private cProductView cProductView;
//private productController pController;
//private productModel proModel;
public menuController(inventoryModel model, showPartsView view){
this.model = model;
this.view = view;
//this.proModel = proModel;
}
@Override
public void actionPerformed(ActionEvent e){
String command = e.getActionCommand();
if (command.equals("Add new part")) {
addView = new addPartsView(model);//creates addPartsView
addPartController addController = new addPartController(model, addView);//creates addPartController
addView.registerListeners(addController);//register addPartController as listener
addView.setSize(400, 300);/* starts new addPartView*/
addView.setVisible(true);
//System.out.println("menuController = " +command);
} /*else if (command.equals("Add New Inventory Item")) {
addinvView = new addInvsView(model);
addInvController addInvController = new addInvController(model, addinvView);
addinvView.registerListeners(addInvController);
addinvView.setSize(400, 300);
addinvView.setVisible(true);
//System.out.println("menuController = " +command);
} else if (command.equals("Create Product")) {
//System.out.println("Creating Product button pushed");
cProductView = new cProductView(model, proModel);
productController pController = new productController(model, proModel, cProductView);
cProductView.registerListeners(pController);
cProductView.setSize(500, 200);
cProductView.setLocation(400, 300);
cProductView.setVisible(true);
}*/
}
}
|
package br.com.welson.clinic.persistence.model;
import javax.persistence.Entity;
@Entity
public class Employee extends User {
}
|
package pages;
import playKeyNoteTest.happyBirthdaySongTest;
public class notePage extends happyBirthdaySongTest {
public notePage enableSound() throws InterruptedException {
clickByXpath(prop.getProperty("ENABLE_SOUND"));
Thread.sleep(3000);
return this;
}
public notePage A_Note() throws InterruptedException {
clickByXpath(prop.getProperty("A_NOTE"));
return this;
}
public notePage B_Note() throws InterruptedException {
clickByXpath(prop.getProperty("B_NOTE"));
return this;
}
public notePage D_Note() throws InterruptedException {
clickByXpath(prop.getProperty("D_NOTE"));
return this;
}
public notePage E_Note() throws InterruptedException {
clickByXpath(prop.getProperty("E_NOTE"));
return this;
}
public notePage G_Note() throws InterruptedException {
clickByXpath(prop.getProperty("G_NOTE"));
return this;
}
public notePage tri_C_Note() throws InterruptedException {
clickByXpath(prop.getProperty("TRI_C_NOTE"));
return this;
}
public notePage tri_D_Note() throws InterruptedException {
clickByXpath(prop.getProperty("TRI_D_NOTE"));
return this;
}
public notePage F_sharp_Note() throws InterruptedException {
clickByXpath(prop.getProperty("F_SHARP_NOTE"));
return this;
}
}
|
package easii.com.br.iscoolapp.objetos;
/**
* Created by gustavo on 01/05/2017.
*/
public class Desafio {
private String nome;
private int tipo;
private String participantes;
public Desafio(String nome, int tipo, String participantes) {
this.nome = nome;
this.tipo = tipo;
this.participantes = participantes;
}
public Desafio(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getTipo() {
return tipo;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public String getParticipantes() {
return participantes;
}
public void setParticipantes(String participantes) {
this.participantes = participantes;
}
}
|
package layouts03;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JButton;
public class GridBagUno extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GridBagUno frame = new GridBagUno();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GridBagUno() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] {30, 0, 0, 0, 0, 0, 0};
gbl_contentPane.rowHeights = new int[] {30, 0, 0, 30, 30, 30, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
contentPane.setLayout(gbl_contentPane);
JLabel lblNewLabel = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 1;
contentPane.add(lblNewLabel, gbc_lblNewLabel);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.insets = new Insets(0, 0, 5, 5);
gbc_textField.gridx = 2;
gbc_textField.gridy = 1;
contentPane.add(textField, gbc_textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("aceptar");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.fill = GridBagConstraints.HORIZONTAL;
gbc_btnNewButton.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton.gridx = 3;
gbc_btnNewButton.gridy = 1;
contentPane.add(btnNewButton, gbc_btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 5);
gbc_btnNewButton_1.gridx = 4;
gbc_btnNewButton_1.gridy = 1;
contentPane.add(btnNewButton_1, gbc_btnNewButton_1);
JLabel lblNewLabel_1 = new JLabel(" ");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 5;
gbc_lblNewLabel_1.gridy = 1;
contentPane.add(lblNewLabel_1, gbc_lblNewLabel_1);
textField_1 = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.gridwidth = 2;
gbc_textField_1.insets = new Insets(0, 0, 5, 5);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 2;
contentPane.add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_2.gridx = 2;
gbc_lblNewLabel_2.gridy = 6;
contentPane.add(lblNewLabel_2, gbc_lblNewLabel_2);
textField_2 = new JTextField();
GridBagConstraints gbc_textField_2 = new GridBagConstraints();
gbc_textField_2.gridwidth = 2;
gbc_textField_2.insets = new Insets(0, 0, 5, 5);
gbc_textField_2.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_2.gridx = 3;
gbc_textField_2.gridy = 6;
contentPane.add(textField_2, gbc_textField_2);
textField_2.setColumns(10);
JButton btnNewButton_2 = new JButton("New button");
GridBagConstraints gbc_btnNewButton_2 = new GridBagConstraints();
gbc_btnNewButton_2.gridx = 6;
gbc_btnNewButton_2.gridy = 7;
contentPane.add(btnNewButton_2, gbc_btnNewButton_2);
}
}
|
package com.netcracker.entities;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "Passenger_Rating")
public class PassengerRating {
@Id
private Long userId;
@Column(name = "Average_Mark")
private Double averageMark;
@Column(name = "number_of_votes")
private Long numberOfVotes;
public PassengerRating() {
}
public PassengerRating(Long userId){
this.userId = userId;
}
public PassengerRating(
@NotNull Double averageMark,
@NotNull Long numberOfVotes
) {
this.averageMark = averageMark;
this.numberOfVotes = numberOfVotes;
}
public Double getAverageMark() {
return averageMark;
}
public Long getNumberOfVotes() {
return numberOfVotes;
}
public void setNumberOfVotes(Long numberOfVotes) {
this.numberOfVotes = numberOfVotes;
}
public void setAverageMark(Double averageMark) {
this.averageMark = averageMark;
}
}
|
package pt.sinfo.testDrive.domain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import pt.sinfo.testDrive.exception.TestDriveException;
public class DealerConstructorMethodTest {
private String id;
private String name;
private float latitude;
private float longitude;
private ArrayList<Vehicle> vehicles;
private HashSet<String> closed;
@Before
public void setUp() {
this.id = "ab49f56a-451d-4721-8319-efdca5e69680";
this.name = "name";
this.latitude = 0;
this.longitude = 0;
HashMap<String,ArrayList<Integer>> availability = new HashMap<String,ArrayList<Integer>>();
ArrayList<Integer> dayOne = new ArrayList<Integer>();
ArrayList<Integer> dayTwo = new ArrayList<Integer>();
dayOne.add(1000);dayOne.add(1030);
dayTwo.add(1000);dayTwo.add(1030);
availability.put("thursday",dayOne);
availability.put("Monday", dayTwo);
Vehicle vehicle = new Vehicle("id", "model", "fuel", "transmission", availability);
ArrayList<Vehicle> vehicleArray = new ArrayList<Vehicle>();
vehicleArray.add(vehicle);
this.vehicles = vehicleArray;
this.closed = new HashSet<String>();
}
@Test
public void success() {
Dealer testSubject = new Dealer(id, name, latitude, longitude, vehicles, closed);
Assert.assertEquals(this.id, testSubject.getId());
Assert.assertEquals(this.name, testSubject.getName());
Assert.assertEquals(this.vehicles, testSubject.getVehicles());
Assert.assertEquals(this.closed, testSubject.getClosed());
}
//TESTING FOR NULL ARGUMENTS
@Test(expected = TestDriveException.class)
public void nullID() {
new Dealer(null, name, latitude, longitude, vehicles, closed);
}
@Test(expected = TestDriveException.class)
public void nullName() {
new Dealer(id, null, latitude, longitude, vehicles, closed);
}
@Test(expected = TestDriveException.class)
public void nullVehicles() {
new Dealer(id, name, latitude, longitude, null, closed);
}
//TESTING FOR EMPTY ARGUMENTS
@Test(expected = TestDriveException.class)
public void emptyID() {
new Dealer("", name, latitude, longitude, vehicles, closed);
}
@Test(expected = TestDriveException.class)
public void emptyName() {
new Dealer(id, "", latitude, longitude, vehicles, closed);
}
}
|
package clase2SincronizmodeHilo;
import java.util.Collection;
import java.util.Collections;
public class Parte2 {
public static void main(String[] args) {
Cuenta cuenta = new Cuenta();
Cliente cliente1 = new Cliente(cuenta);
Cliente cliente2= new Cliente (cuenta);
//son conyuges x eso comparten cuenta
new Thread(cliente1).start();
new Thread(cliente2).start();
//qye diferencia existe entre HAshmap y Hastable
/*ambas son implementraciones de la interface MAP
Has<String, String>mapa1=new Hasmap();
mapa1.put("lu", "Lunes")
syso ( mapa.ger("lu"))
//
HashMap:
-Metodos mp sincronizados
-No sirve para multihilos
-Es màs veloz
HashTable:
-Metodos sincronizados totalmente
-Siver para multithread
-Es màs lento
-es una clase legacy
Collections:
-Provee utilidades para colleciones.
-Tiene un factory para armar colleciones parcialmente sincronizadas
//hastable esta preparado par multi hilo
Hastable<String, string>mapa2=new HAstable();
mapa2.put("luss", "Lunes");
syso ( mapa2.get("lu"));
*/
Map<String,String>mapa3=Collections.synchronizedMap(new HashMap());
mapa3.put("lu","lunes");
System.out.println(mapa3.get("lu"));
}
} |
package ideablog.model;
import java.util.Date;
public class Log {
private long id;
private long userId;
private String method;
private String description;
private String reqIp;
private Date opTime;
private String username;//扩展
private int role;//扩展
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getReqIp() {
return reqIp;
}
public void setReqIp(String reqIp) {
this.reqIp = reqIp;
}
public Date getOpTime() {
return opTime;
}
public void setOpTime(Date opTime) {
this.opTime = opTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
}
|
package com.example.asus.taskapp.Fragments;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.asus.taskapp.AccountUtils.LoginActivity;
import com.example.asus.taskapp.AccountUtils.RegisterActivity;
import com.example.asus.taskapp.Activities.AddUsers;
import com.example.asus.taskapp.Activities.EditUser;
import com.example.asus.taskapp.Adapters.UsersAdapter;
import com.example.asus.taskapp.Config;
import com.example.asus.taskapp.MainActivity;
import com.example.asus.taskapp.Model.Users;
import com.example.asus.taskapp.R;
import com.example.asus.taskapp.Utils.FetchData;
import com.example.asus.taskapp.Utils.RemoveRequest;
import com.example.asus.taskapp.Utils.UserAvailable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class HomeFragment extends Fragment implements UsersAdapter.UsersClickListener {
public SharedPreferences preferences;
public String token = "";
public String id = null;
public TextView teksView;
public TextView loadingTeks;
public FetchData fetchData;
public RecyclerView recyclerView;
public UsersAdapter usersAdapter;
public UsersAdapter.UsersClickListener listener;
public List<Users> userList = new ArrayList<>();
public SwipeRefreshLayout refreshLayout;
public FloatingActionButton fabs;
public SharedPreferences.Editor editor;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment , container , false);
if(new UserAvailable(getContext()).check_user_exist() == true){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Akun Anda Telah Dihapus / Ada Kesalahan Aplikasi \n Anda Akan Logout Otomatis");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
preferences = getActivity().getApplicationContext().getSharedPreferences("user_data",0);
editor = preferences.edit();
editor.clear();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
preferences = getActivity().getApplicationContext().getSharedPreferences("user_data",0);
if(preferences.getString("token",null) != null && preferences.getInt("id",0) != 0){
token = preferences.getString("token",null);
id = String.valueOf(preferences.getInt("id",0));
Log.d("id_data",String.valueOf(id));
} else {
Log.d("token","nul");
}
listener = this;
fabs = view.findViewById(R.id.fab_add_user);
fabs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity().getApplicationContext(),AddUsers.class);
startActivity(intent);
}
});
refreshLayout = view.findViewById(R.id.swipe_refresh);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
userList.clear();
load_data();
refreshLayout.setRefreshing(false);
}
});
loadingTeks = view.findViewById(R.id.loading_teks);
teksView = view.findViewById(R.id.no_data_teks);
recyclerView = view.findViewById(R.id.recyclerViewUsers);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
load_data();
return view;
}
public void load_data(){
fetchData = new FetchData(getContext() , new Config().getServerAddress() + "/users", FetchData.FetchType.USERS,token,true);
fetchData.setTextView(loadingTeks);
fetchData.setUsersListener(new FetchData.OnUsersListener() {
@Override
public void onUsersData(List<Users> usersList) {
if(usersList != null){
userList.clear();
userList = usersList;
usersAdapter = new UsersAdapter(userList , getContext() , listener);
recyclerView.setAdapter(usersAdapter);
} else {
recyclerView.setVisibility(View.GONE);
teksView.setVisibility(View.VISIBLE);
}
}
});
fetchData.execute();
}
@Override
public void onUserClicked(final Users users) {
final CharSequence[] sequences = {"Ubah" , "Hapus"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Pilihan");
builder.setItems(sequences, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch(i){
case 0:
Intent intent = new Intent(getContext() , EditUser.class);
intent.putExtra("id",users.getId());
startActivity(intent);
break;
case 1:
int id = preferences.getInt("id",0);
final String token = preferences.getString("token",null);
if(id == users.getId()){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Yakin ingin menghapus data ? Setelah \n Data Terhapus Anda Akan Logout Otomatis");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
RemoveRequests request = new RemoveRequests(new Config().getServerAddress() + "/users/" + String.valueOf(users.getId()),token);
request.execute();
SharedPreferences.Editor editor = preferences.edit();
editor.remove("id");
editor.remove("name");
editor.remove("image_path");
editor.remove("token");
editor.commit();
Intent inten = new Intent(getContext() , LoginActivity.class);
startActivity(inten);
getActivity().finish();
}
});
builder.setNegativeButton("Batal", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
RemoveRequest request = new RemoveRequest(new Config().getServerAddress() + "/users/" + users.getId() , getContext() , token , true);
request.setActivity(getActivity());
request.execute();
load_data();
if(userList.size() == 0){
MainActivity.ma.navigationView.setSelectedItemId(R.id.appbar_edit_user);
}
}
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public class RemoveRequests extends AsyncTask<String , Void , Integer> {
public ProgressDialog dialog;
public String uri;
public String token;
public RemoveRequests(String uri , String token){
this.uri = uri;
this.token = token;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Integer doInBackground(String... strings) {
int responseCode = 0;
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setRequestProperty("x-token",token);
connection.setRequestMethod("DELETE");
responseCode = connection.getResponseCode();
} catch(MalformedURLException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
return responseCode;
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
}
|
package sam;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
public class Main {
public static void main(String [] args) {
BigInteger base = new BigInteger("113");
BigInteger exponent = new BigInteger("12456");
Instant s = Instant.now();
BigInteger k = mod(base,exponent);
Instant e = Instant.now();
Duration d = Duration.between(s, e);
Instant s1 = Instant.now();
BigInteger l = base.pow(12456);
Instant e1 = Instant.now();
Duration d1 = Duration.between(s1, e1);
System.out.println(k);
System.out.format(" biginteger's: %02dh:%02dm:%02ds.%04dms ", d1.toHours(), d1.toMinutes(), d1.getSeconds(), d1.toMillis());
System.out.println();
System.out.println("Bit Length : " + k.toString(2).length());
System.out.format("our's: %02dh:%02dm:%02ds.%04dms ", d.toHours(), d.toMinutes(), d.getSeconds(), d.toMillis());
System.out.println();
}
public static BigInteger mod(BigInteger base, BigInteger exponent) {
String exponentBits = exponent.toString(2);
BigInteger res = new BigInteger(base.toString());
for (int i = 1; i < exponentBits.length(); i++) {
res = res.multiply(res) ;
if(exponentBits.charAt(i) == '1' ) {
res = res.multiply(base);
}
}
return res;
}
}
|
package uk.co.mtford.jalp.abduction.rules;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.co.mtford.jalp.JALP;
import uk.co.mtford.jalp.abduction.logic.instance.IInferableInstance;
import uk.co.mtford.jalp.abduction.logic.instance.equalities.EqualityInstance;
import uk.co.mtford.jalp.abduction.logic.instance.term.VariableInstance;
import uk.co.mtford.jalp.abduction.tools.UniqueIdGenerator;
import java.util.LinkedList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: mtford
* Date: 07/06/2012
* Time: 17:20
* To change this template use File | Settings | File Templates.
*/
public class E1Test {
public E1Test() {
}
@Before
public void noSetup() {
}
@After
public void noTearDown() {
}
/*
G = {X=Y}
Expect assignment of Y to X.
*/
@Test
public void test1() throws Exception {
UniqueIdGenerator.reset();
E1RuleNode ruleNode = new E1RuleNode();
List<IInferableInstance> goals = new LinkedList<IInferableInstance>();
VariableInstance X = new VariableInstance("X");
VariableInstance Y = new VariableInstance("Y");
EqualityInstance e = new EqualityInstance(X,Y);
goals.add(e);
ruleNode.setGoals(goals);
ruleNode.setQuery(new LinkedList<IInferableInstance>(ruleNode.getGoals()));
JALP.applyRule(ruleNode);
JALP.getVisualizer("debug/rules/E1/Test1",ruleNode);
}
}
|
/*
DiffusionLimitedAggregation -- a class within the Cellular Automaton Explorer.
Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package cellularAutomata.rules;
import java.awt.FlowLayout;
import java.util.Iterator;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import cellularAutomata.CurrentProperties;
import cellularAutomata.Cell;
import cellularAutomata.lattice.Lattice;
import cellularAutomata.rules.templates.IntegerMargolusTemplate;
import cellularAutomata.rules.util.RuleFolderNames;
import cellularAutomata.util.MinMaxIntPair;
import cellularAutomata.util.math.RandomSingleton;
/**
* Rule for diffusion limited aggregation. Essentially this is just the
* Diffusion rule, with any number of gasses. But there is also a special state
* that acts as a solid. Any other state that comes into contact with the solid
* will freeze in place. Uses the Margolus neighborhood but could be rewritten
* as a lattice gas with vector states.
*
* @author David Bahr
*/
public class DiffusionLimitedAggregation extends IntegerMargolusTemplate
{
/**
* The random percent of the gas used as an initial value if no other is
* specified.
*/
public static final int DEFAULT_RANDOM_PERCENT = 25;
// The state used for empty space
private static final int EMPTY_STATE = 0;
// the state used for the gas
private static final int GAS_STATE = 1;
// The state used for the solid
private static final int SOLID_STATE = 2;
// A string giving the name of an initial state
private static final String INIT_STATE_RANDOM_WITH_SEED = "random gas with seed";
// A string giving a tooltip for the INIT_STATE_RANDOM_WITH_SEED initial
// state
private static final String INIT_STATE_RANDOM_WITH_SEED_TOOLTIP = "<html>A random "
+ "distribution of the gas state <br>"
+ "with a single solid seed in the center. <br>"
+ "Set the random percent in the text field <br>" + "above.</html>";
// a label for the initial state panel
private static final String RANDOM_PERCENT_LABEL = "random percent gas: ";
// The tooltip for the random percent
private static final String RANDOM_PERCENT_TIP = "<html>"
+ "Percentage of the cells that will be randomly filled <br>"
+ "with non-empty states. For example, 80% means that <br>"
+ "20% of the cells will be blank, and the remainder will <br>"
+ "be filled. The filled sites are given values selected <br>"
+ "uniformly (equally) from each of the non-empty states.</html>";
// a display name for this class
private static final String RULE_NAME = "Diffusion Limited Aggregation";
// used to randomly choose a rearrangement
private static Random random = RandomSingleton.getInstance();
// selects the random percent
private static JSpinner randomPercentSpinner = null;
// a description of property choices that give the best results for this
// rule (e.g., which lattice, how many states, etc.)
private static final String BEST_RESULTS = "<html> <body><b>"
+ RULE_NAME
+ ".</b>"
+ "<p> "
+ "<b>For best results</b>, try a 200 by 200 or larger lattice with the \"random gas "
+ "with seed\" initial state. Choose a <b>20% to 30%</b> random percent (though this "
+ "number can be interesting to vary). Watch the crystal slowly grow around the seed "
+ "(the \"solid\"). Alternatively, select \"random gas with seed\" and draw a line "
+ "along the bottom. This will produce frost, like humid air condensing on a "
+ "windowpane in the winter. Or draw a few scattered solid seeds and watch them "
+ "crystallize and attempt to grow together (but look carefully -- they rarely succeed)."
+ leftClickInstructions + rightClickInstructions + "</body></html>";
// a tooltip description for this class
private String TOOLTIP = "<html> <body><b>"
+ RULE_NAME
+ ".</b> Grows crystals that look like frost on a windowpane.</body></html>";
/**
* Create the diffusion limited aggregation rule using the given cellular
* automaton properties.
* <p>
* When calling the parent constructor, the minimalOrLazyInitialization
* parameter must be included as shown. The boolean is intended to indicate
* when the constructor should build a rule with as small a footprint as
* possible. In order to load rules by reflection, the application must
* query this class for information like the display name, tooltip
* description, etc. At these times it makes no sense to build the complete
* rule which may have a large footprint in memory.
* <p>
* It is recommended that the constructor and instance variables do not
* initialize any memory intensive variables and that variables be
* initialized only when first needed (lazy initialization). Or all
* initializations in the constructor may be placed in an <code>if</code>
* statement.
*
* <pre>
* if(!minimalOrLazyInitialization)
* {
* ...initialize
* }
* </pre>
*
* @param minimalOrLazyInitialization
* When true, the constructor instantiates an object with as
* small a footprint as possible. When false, the rule is fully
* constructed. This variable should be passed to the super
* constructor <code>super(minimalOrLazyInitialization);</code>,
* but if uncertain, you may safely ignore this variable.
*/
public DiffusionLimitedAggregation(boolean minimalOrLazyInitialization)
{
super(minimalOrLazyInitialization);
}
/**
* Takes particles (or lack of) at each quadrant of the Margolus block and
* rearranges them randomly. The particles are conserved.
*
* @param northWestCellValue
* The current value of the northwest cell.
* @param northEastCellValue
* The current value of the northeast cell.
* @param southEastCellValue
* The current value of the southeast cell.
* @param southWestCellValue
* The current value of the southwest cell.
* @return An array of values representing the randomly rearranged
* particles.
*/
private int[] rearrangeTheBlock(int northWestCellValue,
int northEastCellValue, int southEastCellValue,
int southWestCellValue)
{
int[] newBlock = new int[4];
int randomRearrangement = random.nextInt(24);
if(randomRearrangement == 0)
{
// no rearrangement!
newBlock[0] = northWestCellValue;
newBlock[1] = northEastCellValue;
newBlock[2] = southEastCellValue;
newBlock[3] = southWestCellValue;
}
else if(randomRearrangement == 1)
{
newBlock[0] = northWestCellValue;
newBlock[1] = northEastCellValue;
newBlock[3] = southEastCellValue;
newBlock[2] = southWestCellValue;
}
else if(randomRearrangement == 2)
{
newBlock[0] = northWestCellValue;
newBlock[2] = northEastCellValue;
newBlock[1] = southEastCellValue;
newBlock[3] = southWestCellValue;
}
else if(randomRearrangement == 3)
{
newBlock[0] = northWestCellValue;
newBlock[2] = northEastCellValue;
newBlock[3] = southEastCellValue;
newBlock[1] = southWestCellValue;
}
else if(randomRearrangement == 4)
{
newBlock[0] = northWestCellValue;
newBlock[3] = northEastCellValue;
newBlock[1] = southEastCellValue;
newBlock[2] = southWestCellValue;
}
else if(randomRearrangement == 5)
{
newBlock[0] = northWestCellValue;
newBlock[3] = northEastCellValue;
newBlock[2] = southEastCellValue;
newBlock[1] = southWestCellValue;
}
else if(randomRearrangement == 6)
{
newBlock[1] = northWestCellValue;
newBlock[0] = northEastCellValue;
newBlock[2] = southEastCellValue;
newBlock[3] = southWestCellValue;
}
else if(randomRearrangement == 7)
{
newBlock[1] = northWestCellValue;
newBlock[0] = northEastCellValue;
newBlock[3] = southEastCellValue;
newBlock[2] = southWestCellValue;
}
else if(randomRearrangement == 8)
{
newBlock[1] = northWestCellValue;
newBlock[2] = northEastCellValue;
newBlock[0] = southEastCellValue;
newBlock[3] = southWestCellValue;
}
else if(randomRearrangement == 9)
{
newBlock[1] = northWestCellValue;
newBlock[2] = northEastCellValue;
newBlock[3] = southEastCellValue;
newBlock[0] = southWestCellValue;
}
else if(randomRearrangement == 10)
{
newBlock[1] = northWestCellValue;
newBlock[3] = northEastCellValue;
newBlock[0] = southEastCellValue;
newBlock[2] = southWestCellValue;
}
else if(randomRearrangement == 11)
{
newBlock[1] = northWestCellValue;
newBlock[3] = northEastCellValue;
newBlock[2] = southEastCellValue;
newBlock[0] = southWestCellValue;
}
else if(randomRearrangement == 12)
{
newBlock[2] = northWestCellValue;
newBlock[0] = northEastCellValue;
newBlock[1] = southEastCellValue;
newBlock[3] = southWestCellValue;
}
else if(randomRearrangement == 13)
{
newBlock[2] = northWestCellValue;
newBlock[0] = northEastCellValue;
newBlock[3] = southEastCellValue;
newBlock[1] = southWestCellValue;
}
else if(randomRearrangement == 14)
{
newBlock[2] = northWestCellValue;
newBlock[1] = northEastCellValue;
newBlock[0] = southEastCellValue;
newBlock[3] = southWestCellValue;
}
else if(randomRearrangement == 15)
{
newBlock[2] = northWestCellValue;
newBlock[1] = northEastCellValue;
newBlock[3] = southEastCellValue;
newBlock[0] = southWestCellValue;
}
else if(randomRearrangement == 16)
{
newBlock[2] = northWestCellValue;
newBlock[3] = northEastCellValue;
newBlock[0] = southEastCellValue;
newBlock[1] = southWestCellValue;
}
else if(randomRearrangement == 17)
{
newBlock[2] = northWestCellValue;
newBlock[3] = northEastCellValue;
newBlock[1] = southEastCellValue;
newBlock[0] = southWestCellValue;
}
else if(randomRearrangement == 18)
{
newBlock[3] = northWestCellValue;
newBlock[0] = northEastCellValue;
newBlock[1] = southEastCellValue;
newBlock[2] = southWestCellValue;
}
else if(randomRearrangement == 19)
{
newBlock[3] = northWestCellValue;
newBlock[0] = northEastCellValue;
newBlock[2] = southEastCellValue;
newBlock[1] = southWestCellValue;
}
else if(randomRearrangement == 20)
{
newBlock[3] = northWestCellValue;
newBlock[1] = northEastCellValue;
newBlock[0] = southEastCellValue;
newBlock[2] = southWestCellValue;
}
else if(randomRearrangement == 21)
{
newBlock[3] = northWestCellValue;
newBlock[1] = northEastCellValue;
newBlock[2] = southEastCellValue;
newBlock[0] = southWestCellValue;
}
else if(randomRearrangement == 22)
{
newBlock[3] = northWestCellValue;
newBlock[2] = northEastCellValue;
newBlock[0] = southEastCellValue;
newBlock[1] = southWestCellValue;
}
else if(randomRearrangement == 23)
{
newBlock[3] = northWestCellValue;
newBlock[2] = northEastCellValue;
newBlock[1] = southEastCellValue;
newBlock[0] = southWestCellValue;
}
return newBlock;
}
/**
* A rule for diffusion. Takes the occupied sites of the Margolus
* neighborhood and rearranges them randomly.
*
* @param northWestCellValue
* The current value of the northwest cell.
* @param northEastCellValue
* The current value of the northeast cell.
* @param southEastCellValue
* The current value of the southeast cell.
* @param southWestCellValue
* The current value of the southwest cell.
* @param numStates
* The number of states. In other words, the returned state can
* only have values between 0 and numStates - 1.
* @param generation
* The current generation of the CA.
* @return An array of states that corresponds to the 2 by 2 Margolus block.
* Array[0] is the northwest corner of the block, array[1] is the
* northeast corner of the block, array[2] is the southeast corner
* of the block, array[3] is the southwest corner of the block.
*/
protected int[] blockRule(int northWestCellValue, int northEastCellValue,
int southEastCellValue, int southWestCellValue, int numStates,
int generation)
{
int[] block = new int[4];
// check to see if any of the cells are solid
if(northWestCellValue == SOLID_STATE
|| northEastCellValue == SOLID_STATE
|| southEastCellValue == SOLID_STATE
|| southWestCellValue == SOLID_STATE)
{
// then any occupied cells must be changed to a solid state
if(northWestCellValue == GAS_STATE)
{
// change to the solid state
northWestCellValue = SOLID_STATE;
}
if(northEastCellValue == GAS_STATE)
{
// change to the solid state
northEastCellValue = SOLID_STATE;
}
if(southEastCellValue == GAS_STATE)
{
// change to the solid state
southEastCellValue = SOLID_STATE;
}
if(southWestCellValue == GAS_STATE)
{
// change to the solid state
southWestCellValue = SOLID_STATE;
}
block[0] = northWestCellValue;
block[1] = northEastCellValue;
block[2] = southEastCellValue;
block[3] = southWestCellValue;
}
else
{
// diffuse the particles!
// take the original block values (particles) and rearrange them
// randomly within the block. Conserves the values (particles).
// i.e., pick one of the 24 random rearrangements. And then we
// assign
// the rearrangement to an array representing the new Margolus
// block.
block = rearrangeTheBlock(northWestCellValue, northEastCellValue,
southEastCellValue, southWestCellValue);
}
return block;
}
/**
* Specifies that the number of states field should be disabled
*/
protected MinMaxIntPair getMinMaxAllowedStates(String latticeDescription)
{
// disables the “Number of States” text field
return null;
}
/**
* Specifies the state value that will be displayed
*/
protected Integer stateValueToDisplay(String latticeDescription)
{
// fixes the state value at 3
return new Integer(3);
}
/**
* A brief description (written in HTML) that describes what parameters will
* give best results for this rule (which lattice, how many states, etc).
* The description will be displayed on the properties panel. Using html
* permits line breaks, font colors, etcetera, as described in HTML
* resources. Regular line breaks will not work.
* <p>
* Recommend starting with the title of the rule followed by "For best
* results, ...". See Rule 102 for an example.
*
* @return An HTML string describing how to get best results from this rule.
* May be null.
*/
public String getBestResultsDescription()
{
return BEST_RESULTS;
}
/**
* When displayed for selection, the rule will be listed under specific
* folders specified here. The rule will always be listed under the "All
* rules" folder. And if the rule is contributed by a user and is placed in
* the userRules folder, then it will also be shown in a folder called "User
* rules". Any strings may be used; if the folder does not exist, then one
* will be created with the specified name. If the folder already exists,
* then that folder will be used.
* <p>
* By default, this returns null so that the rule is only placed in the
* default folder(s).
* <p>
* Child classes should override this method if they want the rule to appear
* in a specific folder. The "All rules" and "User rules" folder are
* automatic and do not need to be specified; they are always added.
*
* @return A list of the folders in which rule will be displayed for
* selection. May be null.
*/
public String[] getDisplayFolderNames()
{
String[] folders = {RuleFolderNames.PHYSICS_FOLDER,
RuleFolderNames.PROBABILISTIC_FOLDER,
RuleFolderNames.CLASSICS_FOLDER};
return folders;
}
/**
* A brief one or two-word string describing the rule, appropriate for
* display in a drop-down list.
*
* @return A string no longer than 15 characters.
*/
public String getDisplayName()
{
return RULE_NAME;
}
/**
* Gets an array of names for any initial states defined by the rule. In
* other words, if the rule has two initial states that it would like to
* define, then they are each given names and placed in an array of size 2
* that is returned by this method. The names are then displayed on the
* Properties panel. The CA will always have "single seed", "random", and
* "blank" for initial states. This array specifies additional initial
* states that should be displayed. The names should be unique. By default
* this returns null. Child classes should override the method if they wish
* to specify initial states that will appear on the Properties panel. Note:
* This method should be used in conjuction with the setInitialState method,
* also in this class.
*
* @return An array of names for initial states that are specified by the
* rule.
*/
public String[] getInitialStateNames()
{
return new String[] {INIT_STATE_RANDOM_WITH_SEED};
}
/**
* Gets an array of JPanels that will be displayed as part of this rule's
* initial states. The order and size should be the same as the the initial
* states in the getInitialStateNames() method. There is no requirement that
* any panel be displayed, and any of the array elements may be null. The
* entire array may be null.
* <p>
* Strongly recommended that graphics components on the JPanels be static so
* that they apply to all cells. Otherwise, the graphics displayed on the
* Initial State tab will not be the same graphics associated with each
* cell.
* <p>
* Note: This method should be used in conjuction with the
* getInitialStateNames and setInitialState methods, also in this class.
* <p>
* Child classes should override the default behavior which returns null,
* which displays no panel. See DiffusionLimitedAggregation as an example.
* <p>
* Values for components in the panel can be saved and reset from the
* properties. When creating the initial state in setInitialState(), just
* save the values using "properties.setProperty(key, value)". The next time
* the application is started, the values can be read in this method and
* used to set the components initial value. Read the value using
* "properties.getProperty(key);". This allows persistence across sessions.
* In other words, if the user closes the application, it can be reopened
* with the same values by reading the previously saved property values. To
* prevent property naming conflicts, please start every key with the class
* name of the rule. For example, key = "DiffusionLimitedAggregation:
* random" (see the DiffusionLimitedAggregation class).
*
* @return An array indicating what panels should be displayed as part of
* the initial states. If null, no panel will be displayed for any
* initial states that are specified by this rule. If any element of
* the arry is null, then no panel will be displayed for that
* corresponding initial state.
*/
public JPanel[] getInitialStateJPanels()
{
// get the percentage used the last time the program was run
int randomPercent = CurrentProperties.getInstance()
.getRandomPercentDiffusionGas();
// create a label
JLabel percentLabel = new JLabel(RANDOM_PERCENT_LABEL);
// create spinner for the random field
SpinnerNumberModel randomPercentModel = new SpinnerNumberModel(
randomPercent, 0, 100, 1);
randomPercentSpinner = new JSpinner(randomPercentModel);
randomPercentSpinner.setToolTipText(RANDOM_PERCENT_TIP);
// add listeners
// randomPercentSpinner.addChangeListener(listener);
// randomPercentSpinner.addChangeListener(this);
// ((JSpinner.NumberEditor) randomPercentSpinner.getEditor())
// .getTextField().getDocument().addDocumentListener(this);
// now create the panel that holds the spinner
JPanel initialStatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
initialStatePanel.add(percentLabel);
initialStatePanel.add(randomPercentSpinner);
JPanel[] arrayOfPanels = {initialStatePanel};
return arrayOfPanels;
}
/**
* Gets tool tips for any initial states defined by the rule. The tool tips
* should be given in the same order as the initial state names in the
* method getInitialStateNames. The tool tip array must be null or the same
* length as the array of initial state names. By default this returns null.
* Child classes should override the method if they wish to specify initial
* state tool tips that will appear on the Properties panel. Note: This
* method should be used in conjuction with the getInitialStateNames and
* setInitialState method, also in this class.
*
* @return An array of tool tips for initial states that are specified by
* the rule. May be null. Any element of the array may also be null,
* but if the length of the array is non-zero, then the length must
* be the same as the array returned by getInitialStateNames.
*/
public String[] getInitialStateToolTips()
{
return new String[] {INIT_STATE_RANDOM_WITH_SEED_TOOLTIP};
}
/**
* A brief description (written in HTML) that describes this rule. The
* description will be displayed as a tooltip. Using html permits line
* breaks, font colors, etcetera, as described in HTML resources. Regular
* line breaks will not work.
*
* @return An HTML string describing this rule.
*/
public String getToolTipDescription()
{
return TOOLTIP;
}
/**
* Gets an initial state that corresponds to the specified initialStateName.
* This method is optional and returns null by default.
* <p>
* If a rule wishes to define one or more initial states (different from the
* "single seed", "random", and "blank" that are already provided), then the
* name of the state is specified in the getInitialStateNames() method. The
* name is displayed on the Initial States tab, and if it is selected, then
* this method is called with that name. Based on the name, this method can
* then specify an initial state.
* <p>
* By default this returns null. Child classes should override the method if
* they wish to specify initial states that will appear on the Initial
* States tab.
* <p>
* The lattice parameter is used to retrieve an iterator over the cells and
* assign the initial values to the cells. An example is <code>
* //assigns the same double value to each cell.
* Iterator cellIterator = lattice.iterator();
* while(cellIterator.hasNext())
* {
* Cell cell = (Cell) cellIterator.next();
*
* // assign the value
* cell.getState().setValue(new Double(3.4));
* }
* </code>
* Here is another example that assigns values to the cell at both the
* current generation and previous generations. The number of generations in
* the stateHistory variable (below) would be determined by the method
* getRequiredNumberOfGenerations in this class. <code>
* //assign the same double value to each cell
* Double double = new Double(9.3);
* Iterator cellIterator = lattice.iterator();
* while(cellIterator.hasNext())
* {
* Cell cell = (Cell) cellIterator.next();
*
* // get the list of states for each cell
* ArrayList stateHistory = cell.getStateHistory();
* int historySize = stateHistory.size();
*
* // there may be more than one state required as initial conditions
* for(int i = 0; i < historySize; i++)
* {
* ((CellState) stateHistory.get(i)).setValue(double);
* }
* }
* </code>
* Another example is given in the Fractal rule. That example figures out
* the row and column number of each cell and assigns values based on their
* row and column.
* <p>
* Note: This method should be used in conjuction with the getInitialState
* method, also in this class.
* <p>
* The method getInitialStateJPanels() will create a panel (with components
* if desired) that is displayed on the Initial States tab. See
* DiffusionLimitedAggregation for an example. Values for components in this
* panel can be read and used by this method when setting the initial state.
* Values for components in the panel can also be saved in the properties.
* In this method, save the values using "properties.setProperty(key,
* value)". The next time the application is started, the values can be read
* in the method getInitialStateJPanels() and used to set the components
* initial value. Read the value using "properties.getProperty(key);". This
* allows persistence across sessions. In other words, if the user closes
* the application, it can be reopened with the same values by reading the
* previously saved property values. To prevent property naming conflicts,
* please start every key with the class name of the rule. For example, key =
* "DiffusionLimitedAggregation: random" (see the
* DiffusionLimitedAggregation class).
* <p>
* By default this method does nothing.
*
* @param initialStateName
* The name of the initial state (will be one of the names
* specified in the getInitialStateNames method).
* @param lattice
* The CA lattice. This will either be a one or two-dimensional
* lattice which holds the cells. The cells should be collected
* from the lattice and assigned initial values.
*/
public void setInitialState(String initialStateName, Lattice lattice)
{
// get the number of rows and columns
int numRows = CurrentProperties.getInstance().getNumRows();
int numCols = CurrentProperties.getInstance().getNumColumns();
// instantiate if necessary
if(randomPercentSpinner == null)
{
// spinner is instantiated in here
getInitialStateJPanels();
}
// get the percent that will be random
double percent = DEFAULT_RANDOM_PERCENT / 100.0;
try
{
randomPercentSpinner.commitEdit();
}
catch(Exception e)
{
// do nothing
}
Integer percentValueFromSpinner = (Integer) randomPercentSpinner
.getValue();
percent = percentValueFromSpinner.doubleValue() / 100.0;
// save the value for future reference (e.g., when the application is
// restarted)
CurrentProperties.getInstance().setRandomPercentDiffusionGas(
percentValueFromSpinner);
// the number of cells through which we have iterated
int cellNum = 0;
// iterate through each cell and set it's value
Iterator cellIterator = lattice.iterator();
while(cellIterator.hasNext())
{
// get each cell
Cell cell = (Cell) cellIterator.next();
// get the row and col of this cell
int row = cellNum / numRows; // integer division on purpose!
int col = cellNum % numCols;
// assign the value to the cell
if((row == numRows / 2) && (col == numCols / 2)
&& initialStateName.equals(INIT_STATE_RANDOM_WITH_SEED))
{
// then it's the cell in the middle, so assign the solid state
cell.getState().setValue(new Integer(SOLID_STATE));
}
else
{
// assign a gas state with the probability given by "percent"
if(random.nextDouble() < percent)
{
cell.getState().setValue(new Integer(GAS_STATE));
}
else
{
cell.getState().setValue(new Integer(EMPTY_STATE));
}
}
// increments the number of cells through which we have iterated
cellNum++;
}
}
}
|
package com.yuneec.flight_settings;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.yuneec.flightmode15.MainActivity;
import com.yuneec.flightmode15.R;
import com.yuneec.flightmode15.Utilities;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
public class QuickReview extends Activity implements OnClickListener, OnCheckedChangeListener, OnItemClickListener, OnItemLongClickListener {
private static final int SHOW_DIALOG_FILE_SELECTED_NUM = 5;
private static final String TAG = "QuickReview";
private Button mBtnCancel;
private Button mBtnDelete;
private boolean mInSelection = false;
private ListView mListView;
private TextView mNoVideoLabel;
private String[] mShortnameVideoList = null;
private ToggleButton mTogSelectAll;
private FilenameFilter mVideoFilter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
if (filename == null || filename.lastIndexOf(".avc") == -1) {
return false;
}
return true;
}
};
private class DeleteTask extends AsyncTask<ArrayList<String>, Void, Void> {
private DeleteTask() {
}
protected Void doInBackground(ArrayList<String>... params) {
QuickReview.this.deleteVideoInternal(params[0]);
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
QuickReview.this.refreshList();
Utilities.dismissProgressDialog();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(128);
setContentView(R.layout.quick_review_main);
this.mListView = (ListView) findViewById(R.id.listView);
this.mBtnCancel = (Button) findViewById(R.id.cancel);
this.mBtnDelete = (Button) findViewById(R.id.delete);
this.mTogSelectAll = (ToggleButton) findViewById(R.id.toggle_select);
this.mNoVideoLabel = (TextView) findViewById(R.id.no_video_label);
this.mBtnCancel.setOnClickListener(this);
this.mBtnDelete.setOnClickListener(this);
this.mTogSelectAll.setOnCheckedChangeListener(this);
this.mShortnameVideoList = loadList();
if (this.mShortnameVideoList != null && this.mShortnameVideoList.length > 0) {
this.mNoVideoLabel.setVisibility(4);
this.mListView.setVisibility(0);
this.mListView.setAdapter(new ArrayAdapter(this, R.layout.video_list_item, 16908308, this.mShortnameVideoList));
this.mListView.setOnItemClickListener(this);
this.mListView.setOnItemLongClickListener(this);
}
}
public void onClick(View v) {
if (v.equals(this.mBtnCancel)) {
exitSelectionMode();
} else if (v.equals(this.mBtnDelete)) {
deleteVideo();
}
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.equals(this.mTogSelectAll)) {
toggleSelectAll(isChecked);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String shortFileName = (String) parent.getItemAtPosition(position);
Intent intent = new Intent(this, QuickReviewPlayActivity.class);
intent.putExtra("short_file_name", shortFileName);
startActivity(intent);
}
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
enterSelectionMode();
return true;
}
private String[] loadList() {
File dir = new File(MainActivity.SAVED_LOCAL_VIDEO);
if (dir.exists()) {
return dir.list(this.mVideoFilter);
}
Log.i(TAG, "dir is not existed :/sdcard/FPV-Video/Local");
return null;
}
private void enterSelectionMode() {
this.mListView.setOnItemClickListener(null);
this.mListView.setOnItemLongClickListener(null);
this.mListView.setChoiceMode(2);
this.mListView.setAdapter(null);
this.mListView.setAdapter(new ArrayAdapter(this, R.layout.video_list_item_multiple_choice, 16908308, this.mShortnameVideoList));
this.mBtnCancel.setVisibility(0);
this.mBtnDelete.setVisibility(0);
this.mTogSelectAll.setVisibility(0);
this.mInSelection = true;
}
private void exitSelectionMode() {
this.mListView.setChoiceMode(0);
this.mListView.setAdapter(null);
this.mListView.setAdapter(new ArrayAdapter(this, R.layout.video_list_item, 16908308, this.mShortnameVideoList));
this.mListView.setOnItemClickListener(this);
this.mListView.setOnItemLongClickListener(this);
this.mBtnCancel.setVisibility(4);
this.mBtnDelete.setVisibility(4);
this.mTogSelectAll.setVisibility(4);
this.mInSelection = false;
}
private void deleteVideo() {
SparseBooleanArray checkedItemPositions = this.mListView.getCheckedItemPositions();
ArrayList<String> ToDeleteList = new ArrayList();
for (int i = 0; i < checkedItemPositions.size(); i++) {
int position = checkedItemPositions.keyAt(i);
if (checkedItemPositions.valueAt(i)) {
ToDeleteList.add((String) this.mListView.getItemAtPosition(position));
}
}
if (ToDeleteList.size() < 5) {
deleteVideoInternal(ToDeleteList);
refreshList();
return;
}
Utilities.showProgressDialog(this, null, getResources().getString(R.string.str_dialog_waiting), false, false);
new DeleteTask().execute(new ArrayList[]{ToDeleteList});
}
private void deleteVideoInternal(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
File file = new File(MainActivity.SAVED_LOCAL_VIDEO, (String) list.get(i));
Log.d(TAG, "To delete :" + file.getAbsolutePath());
if (!file.exists()) {
Log.w(TAG, "file not existed:" + file.getAbsolutePath());
} else if (!file.delete()) {
Log.w(TAG, "delete file fail:" + file.getAbsolutePath());
}
}
}
private void refreshList() {
this.mShortnameVideoList = loadList();
if (this.mShortnameVideoList == null || this.mShortnameVideoList.length <= 0) {
this.mNoVideoLabel.setVisibility(0);
this.mListView.setVisibility(4);
this.mBtnCancel.setVisibility(4);
this.mBtnDelete.setVisibility(4);
this.mTogSelectAll.setVisibility(4);
return;
}
exitSelectionMode();
}
private void toggleSelectAll(boolean selectAll) {
int count = this.mListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mListView.setItemChecked(i, selectAll);
}
}
}
|
package name.arbitrary.y2014.r2;
import name.arbitrary.CodeJamBase;
import java.util.ArrayList;
import java.util.List;
// Inefficient implementation, as it's quick to do and solves the given problem fast enough
public class B_UpAndDown extends CodeJamBase {
B_UpAndDown(String fileName) {
super(fileName);
}
public static void main(String[] args) {
new B_UpAndDown(args[0]).run();
}
@Override
protected String runCase() {
int n = Integer.parseInt(getLine());
String[] numStrs = getLine().split(" ");
assert n == numStrs.length;
List<Integer> nums = new ArrayList<Integer>();
for (String numStr : numStrs) {
nums.add(Integer.parseInt(numStr));
}
// We push the smallest numbers to the edges. Push them to the nearest edge and repeat.
int totalCost = 0;
while (!nums.isEmpty()) {
totalCost += moveMinimum(nums);
}
return "" + totalCost;
}
private int moveMinimum(List<Integer> nums) {
int len = nums.size();
int smallest = Integer.MAX_VALUE;
int idx = 0;
for (int i = 0; i < len; i++) {
int currVal = nums.get(i);
if (currVal < smallest) {
smallest = currVal;
idx = i;
}
}
// Equivalent to moving it to the end, and then removing...
nums.remove(idx);
// Find the cost of moving it to the nearest end.
return Math.min(idx, len - 1 - idx);
}
} |
package com.nixsolutions.micrometr.config;
import com.nixsolutions.micrometr.service.handlers.HelloWorldHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.http.MediaType.TEXT_PLAIN;
@Configuration
public class RoutingConfiguration {
@Bean
public RouterFunction<ServerResponse> routeExample(HelloWorldHandler exampleHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/example")
.and(RequestPredicates.accept(TEXT_PLAIN)), exampleHandler::hello);
}
}
|
package com.aof.component.prm.report;
import java.util.List;
public class DepartmentBLBean {
private String depid;
private String depdesc;
private List recordlist;
private int TotalTCV;
private int TYRevenue;
private Integer month[];
public DepartmentBLBean(String desc,List list)
{
// this.depid=id;
this.depdesc=desc;
this.recordlist=list;
month=new Integer[12];
for(int i=0;i<12;i++)
{
month[i]=new Integer(0);
}
}
public void setRevenue()
{
for(int i=0;i<recordlist.size();i++)
{
BackLogBean bean=(BackLogBean)recordlist.get(i);
TotalTCV+=(int)Math.round(bean.getPb().getTotalServiceValue().doubleValue());
TYRevenue+=(int)Math.round(bean.getThisyear().doubleValue());
Double[][] temp=bean.getMonth();
for(int j=0;j<12;j++){
if(month[j]==null)
System.out.println("department month is null");
else if(temp[0][j]==null)
System.out.println("record month is null");
else
month[j]=new Integer(month[j].intValue()+(int)Math.round(temp[0][j].doubleValue()));
}
}
}
public String getDepdesc() {
return depdesc;
}
public void setDepdesc(String depdesc) {
this.depdesc = depdesc;
}
public String getDepid() {
return depid;
}
public void setDepid(String depid) {
this.depid = depid;
}
public Integer[] getMonth() {
return month;
}
public void setMonth(Integer[] month) {
this.month = month;
}
public List getRecordlist() {
return recordlist;
}
public void setRecordlist(List recordlist) {
this.recordlist = recordlist;
}
public int getTotalTCV() {
return TotalTCV;
}
public void setTotalTCV(int totalTCV) {
TotalTCV = totalTCV;
}
public int getTYRevenue() {
return TYRevenue;
}
public void setTYRevenue(int revenue) {
TYRevenue = revenue;
}
}
|
package com.gaoshin.beans;
public class Poem extends Post {
}
|
package tracking;
public class Sweep {
private double signalFo[] = new double[100];
private double oscFo[] = new double[100];
private double trackError[] = new double[100];
public double[] getSignalFo() {
return signalFo;
}
public void setSignalFo(double[] signalFo) {
this.signalFo = signalFo;
}
public double[] getOscFo() {
return oscFo;
}
public void setOscFo(double[] oscFo) {
this.oscFo = oscFo;
}
public double[] getTrackError() {
return trackError;
}
public void setTrackError(double[] trackError) {
this.trackError = trackError;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.