text stringlengths 10 2.72M |
|---|
package Aplicacao;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import Entidades.Empregado;
import Entidades.EmpregadoTerc;
public class Programa {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
List<Empregado> lista = new ArrayList<>();
System.out.print("Entre com o numero de empregados: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
System.out.println("Empregado #" + i);
System.out.print("Tercerizado (y/n)? ");
char ch = sc.next().charAt(0);
System.out.print("Nome: ");
sc.nextLine();
String nome = sc.nextLine();
System.out.print("Horas: ");
int horas = sc.nextInt();
System.out.print("Valor por hora: ");
double valorPorHora = sc.nextDouble();
if (ch == 'y') {
System.out.print("Valor adicionar: ");
double cobrancaAdicional = sc.nextDouble();
lista.add(new EmpregadoTerc(nome, horas, valorPorHora, cobrancaAdicional));
} else {
lista.add(new Empregado(nome, horas, valorPorHora));
}
}
System.out.println();
System.out.println("Pagamentos: ");
for (Empregado emp : lista) {
System.out.println(emp.getNome() + " - $ " + String.format("%.2f", emp.pagamento()));
}
sc.close();
}
}
|
package com.eyequeue.lolabilities.util;
public class Constants {
public static final String LOCAL_MYSQL_URL = "jdbc:mysql://localhost:3306/lolspells?autoReconnect=true&useSSL=false";
public static final String LOCAL_MYSQL_USER = "root";
public static final String LOCAL_MYSQL_PASSWORD = "root";
public static final String OPENSHIFT_MYSQL_URL = "jdbc:mysql://mysql:3306/lolabilitiesdb?autoReconnect=true&useSSL=false";
public static final String OPENSHIFT_MYSQL_USER = "admin";
public static final String OPENSHIFT_MYSQL_PASSWORD = "OreNoDB";
}
|
/*
* 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 bookstore.GUI;
import bookstore.BLL.NhaXuatBanBLL;
import bookstore.Entity.NhaXuatBan;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.ImageIcon;
import static javax.swing.WindowConstants.HIDE_ON_CLOSE;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HieuNguyen
*/
public class jdNXB extends javax.swing.JDialog {
public static String idNXB = "";
NhaXuatBanBLL nxbdll = new NhaXuatBanBLL();
ArrayList<NhaXuatBan> lst = new ArrayList<>();
/**
* Creates new form jdNXB
*/
public jdNXB(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
binData("", "", "");
setIconImage(new ImageIcon(getClass().getResource("imgs/library.png")).getImage());
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
public void binData(String t, String w, String o) {
lst = nxbdll.getAll(t, w, o);
Vector col = new Vector();
col.add("Mã NXB");
col.add("Tên NXB");
col.add("Địa chỉ");
col.add("Điện thoại");
col.add("Email");
Vector data = new Vector();
for (NhaXuatBan i : lst) {
Vector row = new Vector();
row.add(i.getMaNXB());
row.add(i.getTenNXB());
row.add(i.getDiaChi());
row.add(i.getDienThoai());
row.add(i.getEmail());
data.add(row);
}
DefaultTableModel dtm = new DefaultTableModel(data, col);
tbNXB.setModel(dtm);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tbNXB = new javax.swing.JTable();
btnTimKiem = new javax.swing.JButton();
txtTimKiem = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Lựa Chọn Nhà Xuất Bản");
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
tbNXB.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tbNXB.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbNXBMouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
tbNXBMousePressed(evt);
}
});
jScrollPane1.setViewportView(tbNXB);
btnTimKiem.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
btnTimKiem.setText("Tìm Kiếm");
btnTimKiem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimKiemActionPerformed(evt);
}
});
txtTimKiem.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel1.setText("Tìm kiếm theo Tên Nhà Xuất Bản");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(txtTimKiem, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnTimKiem)
.addGap(49, 49, 49))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane1)
.addContainerGap())))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnTimKiem, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtTimKiem, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 791, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 382, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap()))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void tbNXBMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbNXBMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_tbNXBMouseClicked
private void btnTimKiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimKiemActionPerformed
// TODO add your handling code here:
String w = "tenNXB like N'" + "%" + txtTimKiem.getText() + "%" + "'";
binData("", w, "");
}//GEN-LAST:event_btnTimKiemActionPerformed
private void tbNXBMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbNXBMousePressed
// TODO add your handling code here:
if(evt.getClickCount() == 2){
idNXB = tbNXB.getValueAt(tbNXB.getSelectedRow(), 1).toString();
this.setVisible(false);
}
}//GEN-LAST:event_tbNXBMousePressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(jdNXB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jdNXB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jdNXB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jdNXB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
jdNXB dialog = new jdNXB(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnTimKiem;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbNXB;
private javax.swing.JTextField txtTimKiem;
// End of variables declaration//GEN-END:variables
}
|
package com.pwq.Stream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
/**
* Created by pwq on 2018/1/18.
*/
public class SequenceTest {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("pom.xml");
FileInputStream fis1 = new FileInputStream("pwq.txt");
FileOutputStream fos = new FileOutputStream("seqtest.txt");
SequenceInputStream sis = new SequenceInputStream(fis,fis1);
int x;
while ((x = sis.read())!=-1) {
fos.write(x);
}
fos.close();
sis.close();
}
}
|
package com.tech.interview.siply.redbus.service.implementation;
import com.tech.interview.siply.redbus.entity.dao.assets.Bus;
import com.tech.interview.siply.redbus.entity.dto.BusDTO;
import com.tech.interview.siply.redbus.repository.contract.assets.BusRepository;
import com.tech.interview.siply.redbus.service.contract.BusService;
import lombok.AllArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class BusServiceImpl implements BusService {
final ModelMapper modelMapper = new ModelMapper();
BusRepository busRepository;
@Override
public String addNewBus(BusDTO busDTO) {
Bus bus = new Bus(busDTO);
busRepository.save(bus);
return "Saved Bus";
}
@Override
public void deleteById(UUID busId) {
busRepository.deleteById(busId);
}
@Override
public BusDTO getById(UUID busId) {
return modelMapper.map(busRepository.findById(busId).get(), BusDTO.class);
}
@Override
public List<BusDTO> getByOwnerId(UUID ownerId) {
Pageable pageable = PageRequest.of(0, 10);
return busRepository.findAllByOwnerId(ownerId, pageable).stream().map(bus ->
modelMapper.map(bus, BusDTO.class)
).collect(Collectors.toList());
}
}
|
package com.swethasantosh.countriescapitals;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SearchView;
import java.util.ArrayList;
/**
* Created by Swetha on 2/29/2016.
*/
public class EuropeMainActivity extends Navigation_main
{
AsiaListAdapter adapter;
String[] capitals;
String[] countries;
int[] flagimages = {R.drawable.albania,
R.drawable.andorra,
R.drawable.armenia,
R.drawable.austria,
R.drawable.azerbaijan,
R.drawable.belarus,
R.drawable.belgium,
R.drawable.bosniahercegovina,
R.drawable.bulgaria,
R.drawable.croatia,
R.drawable.cyprus,
R.drawable.czechrepublic,
R.drawable.denmark,
R.drawable.estonia,
R.drawable.finland,
R.drawable.france,
R.drawable.georgia,
R.drawable.germany,
R.drawable.greece,
R.drawable.hungary,
R.drawable.iceland,
R.drawable.ireland,
R.drawable.italy,
R.drawable.kazakhstan,
R.drawable.kosovo,
R.drawable.latvia,
R.drawable.liechtenstein,
R.drawable.lithuania,
R.drawable.luxembourg,
R.drawable.macedonia,
R.drawable.malta,
R.drawable.moldova,
R.drawable.monaco,
R.drawable.montenegro,
R.drawable.netherlands,
R.drawable.norway,
R.drawable.poland,
R.drawable.portugal,
R.drawable.romania,
R.drawable.russia,
R.drawable.sanmarino,
R.drawable.serbia,
R.drawable.slovakia,
R.drawable.slovenia,
R.drawable.spain,
R.drawable.sweden,
R.drawable.switzerland,
R.drawable.turkey,
R.drawable.ukraine,
R.drawable.unitedkingdom,
R.drawable.vaticancity};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//setContentView(R.layout.activity_europe_list_adapter);
// setContentView(R.layout.activity_asia_adapter);
FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.framelayout); //Remember this is the FrameLayout area within your activity_main.xml
getLayoutInflater().inflate(R.layout.activity_asia_adapter, contentFrameLayout);
countries =this.getResources().getStringArray(R.array.EuropeCountries);
capitals = this.getResources().getStringArray(R.array.EuropeCapitals);
/* ListView list = (ListView)findViewById(R.id.Europelist);
list.setAdapter(new EuropeListAdapter(this));
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent2 = new Intent(getApplicationContext(),CountryInfo.class);
startActivity(intent2);
}
});
}*/
//final EditText search = (EditText)findViewById(R.id.search2);
final ListView list = (ListView)findViewById(R.id.Asialist);
adapter = new AsiaListAdapter(this,getAsiarow());
list.setAdapter(adapter);
/*
search.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
adapter.getFilter().filter(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
*/
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent2 = new Intent(getApplicationContext(),Europedetails.class);
intent2.putExtra("Position",position);
intent2.putExtra("Country",countries);
intent2.putExtra("Capital",capitals);
intent2.putExtra("Images",flagimages);
//intent2.putExtra("name","Europe");
startActivity(intent2);
}
});
}
private ArrayList<AsiaSingleRow> getAsiarow()
{
ArrayList<AsiaSingleRow> asiarow = new ArrayList<AsiaSingleRow>();
AsiaSingleRow asiaobj ;
for (int i=0;i<countries.length;i++)
{
asiaobj = new AsiaSingleRow(countries[i],capitals[i],flagimages[i]);
asiarow.add(asiaobj);
}
return asiarow;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_asia_adapter, menu);
/*
MenuItem searchItem = menu.findItem(R.id.search);
//SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchView searchView = (SearchView)searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText)
{
adapter.getFilter().filter(newText);
return false;
}
}); */
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package cn.lichuachua.blog.commom.util;
import cn.lichuachua.blog.commom.enums.BaseErrorCodeEnum;
import cn.lichuachua.blog.core.exception.SysException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author 李歘歘
* Json数据装换工具
*/
public class JsonUtil {
/**
* 对象装换为Json
*/
public static String toJson(Object o){
ObjectMapper objectMapper = new ObjectMapper();
try{
return o instanceof String ? o.toString() : objectMapper.writeValueAsString(o);
}catch (Exception e){
e.printStackTrace();
throw new SysException(BaseErrorCodeEnum.JSON_TRANS_ERROR);
}
}
/**
* JSON转化为对象
*/
public static<T> T toObject(String json,Class<T> clazz){
ObjectMapper objectMapper = new ObjectMapper();
try {
return clazz.equals(String.class) ? (T) json : objectMapper.readValue(json, clazz);
}catch (Exception e){
e.printStackTrace();
throw new SysException(BaseErrorCodeEnum.JSON_TRANS_ERROR);
}
}
}
|
package dk.jrpe.monitor.task;
import dk.jrpe.monitor.db.datasource.HttpAccessDataSource;
import dk.jrpe.monitor.db.httpaccess.to.HTTPAccessTO;
import dk.jrpe.monitor.service.chart.ChartEnum;
import dk.jrpe.monitor.service.chart.json.LineChartJSONAdapter;
import dk.jrpe.monitor.websocket.WebSocketHelper;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.Session;
/**
* Task for monitoring total HTTP Success/Failure access per minute.
* Reads the Datasource and generates output in JSON,
* which is sent to all clients. The JSON is adapted for the
* Chart.js library.
*
* One Chart is generated:
*
* 1. Line chart with two data sets. One for Success and one for Failed.
*
* @author Jörgen Persson
*/
public class HttpRequestsPerMinuteMonitorTask extends MonitoringTask {
public HttpRequestsPerMinuteMonitorTask(HttpAccessDataSource dataSource, List<Session> sessionList, int delay) {
super(dataSource, sessionList, delay);
}
@Override
public void run() {
try {
HashMap<String, List<HTTPAccessTO>> dataSetMap = new HashMap<>();
/* Create FROM and TO date (30 minutes in the past) */
ZonedDateTime now = ZonedDateTime.now().withSecond(0).withNano(0);
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
String date = formatter.format(now);
formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String to = formatter.format(now);
String from = formatter.format(now.minusMinutes(30));
List<HTTPAccessTO> successList = this.getDataSouce().getHttpSuccessPerMinute(date, from, to);
List<HTTPAccessTO> failedList = this.getDataSouce().getHttpFailedPerMinute(date, from, to);
dataSetMap.put("Success", successList);
dataSetMap.put("Failed", failedList);
/* Get JSON for the Line chart */
String json = LineChartJSONAdapter.toJSON(dataSetMap, 30);
ChartEnum lineChart = ChartEnum.valueOf(ChartEnum.LINE_SUCCESS_AND_FAILED.toString());
lineChart.setJson(json);
/* Send to all clients */
WebSocketHelper.sendChartListToAll(this.getSessionList(), lineChart);
} catch (Throwable ex) {
Logger.getLogger(WebSocketHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
/*
* Copyright (c) 2020 Nikifor Fedorov
* 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.
* SPDX-License-Identifier: Apache-2.0
* Contributors:
* Nikifor Fedorov and others
*/
package ru.krivocraft.tortoise.android;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;
import ru.krivocraft.tortoise.core.api.AudioFocus;
public class AndroidAudioFocus implements AudioFocus {
private final AudioManager manager;
private final AudioFocusListener androidListener;
public AndroidAudioFocus(ChangeListener listener, AudioManager manager) {
this.manager = manager;
this.androidListener = new AudioFocusListener(listener);
}
@Override
public void request() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
AudioAttributes playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(false)
.setOnAudioFocusChangeListener(androidListener)
.build();
manager.requestAudioFocus(focusRequest);
} else {
manager.requestAudioFocus(androidListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
}
@Override
public void release() {
manager.abandonAudioFocus(androidListener);
}
private static final class AudioFocusListener implements AudioManager.OnAudioFocusChangeListener {
private final AudioFocus.ChangeListener listener;
private AudioFocusListener(ChangeListener listener) {
this.listener = listener;
}
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
listener.mute();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
listener.silently();
break;
case AudioManager.AUDIOFOCUS_GAIN:
listener.gain();
break;
default:
//Do nothing
break;
}
}
}
}
|
/*
* 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 ejercicio03;
import java.util.Scanner;
/**
*
* @author Javier
*/
public class Ejercicio03 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner entrada = new Scanner(System.in);
System.out.print("Introduce el primer número: ");
int primero = entrada.nextInt();
System.out.print("Introduce el segundo número: ");
int segundo = entrada.nextInt();
System.out.print("Introduce el tercer número: ");
int tercero = entrada.nextInt();
if (primero > segundo && primero > tercero) {
System.out.println("El primer número es el mayor: " + primero);
}
else if (segundo >= primero && segundo >= tercero) {
// Añado el igual, si no cuando los dos primeros numero son el mismo
// los ignora y da como mayor el tercero siempre
System.out.println("El segundo número es el mayor: " + segundo);
}
else {
System.out.println("El tercer número es el mayor: " + tercero);
}
}
}
|
/*
* 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.validation;
import org.junit.jupiter.api.Test;
import org.springframework.beans.testfixture.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Unit tests for {@link ValidationUtils}.
*
* @author Juergen Hoeller
* @author Rick Evans
* @author Chris Beams
* @author Arjen Poutsma
* @since 08.10.2004
*/
public class ValidationUtilsTests {
private final Validator emptyValidator = Validator.forInstanceOf(TestBean.class, (testBean, errors) ->
ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY", "You must enter a name!"));
private final Validator emptyOrWhitespaceValidator = Validator.forInstanceOf(TestBean.class, (testBean, errors) ->
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", "You must enter a name!"));
@Test
public void testInvokeValidatorWithNullValidator() {
TestBean tb = new TestBean();
Errors errors = new SimpleErrors(tb);
assertThatIllegalArgumentException().isThrownBy(() ->
ValidationUtils.invokeValidator(null, tb, errors));
}
@Test
public void testInvokeValidatorWithNullErrors() {
TestBean tb = new TestBean();
assertThatIllegalArgumentException().isThrownBy(() ->
ValidationUtils.invokeValidator(emptyValidator, tb, null));
}
@Test
public void testInvokeValidatorSunnyDay() {
TestBean tb = new TestBean();
Errors errors = new SimpleErrors(tb);
ValidationUtils.invokeValidator(emptyValidator, tb, errors);
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY");
}
@Test
public void testValidationUtilsSunnyDay() {
TestBean tb = new TestBean("");
tb.setName(" ");
Errors errors = emptyValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isFalse();
tb.setName("Roddy");
errors = emptyValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isFalse();
// Should not raise exception
errors.failOnError(IllegalStateException::new);
}
@Test
public void testValidationUtilsNull() {
TestBean tb = new TestBean();
Errors errors = emptyValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY");
assertThatIllegalStateException()
.isThrownBy(() -> errors.failOnError(IllegalStateException::new))
.withMessageContaining("'name'").withMessageContaining("EMPTY");
}
@Test
public void testValidationUtilsEmpty() {
TestBean tb = new TestBean("");
Errors errors = emptyValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY");
assertThatIllegalStateException()
.isThrownBy(() -> errors.failOnError(IllegalStateException::new))
.withMessageContaining("'name'").withMessageContaining("EMPTY");
}
@Test
public void testValidationUtilsEmptyVariants() {
TestBean tb = new TestBean();
Errors errors = new SimpleErrors(tb);
ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"});
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg");
errors = new SimpleErrors(tb);
ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}, "msg");
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg");
assertThat(errors.getFieldError("name").getDefaultMessage()).isEqualTo("msg");
}
@Test
public void testValidationUtilsEmptyOrWhitespace() {
TestBean tb = new TestBean();
// Test null
Errors errors = emptyOrWhitespaceValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
// Test empty String
tb.setName("");
errors = emptyOrWhitespaceValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
// Test whitespace String
tb.setName(" ");
errors = emptyOrWhitespaceValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
// Test OK
tb.setName("Roddy");
errors = emptyOrWhitespaceValidator.validateObject(tb);
assertThat(errors.hasFieldErrors("name")).isFalse();
}
@Test
public void testValidationUtilsEmptyOrWhitespaceVariants() {
TestBean tb = new TestBean();
tb.setName(" ");
Errors errors = new SimpleErrors(tb);
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"});
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg");
errors = new SimpleErrors(tb);
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}, "msg");
assertThat(errors.hasFieldErrors("name")).isTrue();
assertThat(errors.getFieldError("name").getCode()).isEqualTo("EMPTY_OR_WHITESPACE");
assertThat(errors.getFieldError("name").getArguments()[0]).isEqualTo("arg");
assertThat(errors.getFieldError("name").getDefaultMessage()).isEqualTo("msg");
}
}
|
package com.worldchip.bbp.ect.activity;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.worldchip.bbp.ect.R;
import com.worldchip.bbp.ect.adapter.ImageAdapter;
import com.worldchip.bbp.ect.adapter.MyGallery;
import com.worldchip.bbp.ect.adapter.MyGallery.MYGalleryOnTounchListener;
import com.worldchip.bbp.ect.common.ChickenView;
import com.worldchip.bbp.ect.db.DataManager;
import com.worldchip.bbp.ect.entity.IconInfo;
import com.worldchip.bbp.ect.entity.LoginState;
import com.worldchip.bbp.ect.entity.UpdateBabyInfo;
import com.worldchip.bbp.ect.gwwheel.OnWheelScrollListener;
import com.worldchip.bbp.ect.gwwheel.WheelView;
import com.worldchip.bbp.ect.image.utils.ImageLoader;
import com.worldchip.bbp.ect.image.utils.ImageLoader.Type;
import com.worldchip.bbp.ect.service.ScanService;
import com.worldchip.bbp.ect.service.TimeTontrolService;
import com.worldchip.bbp.ect.util.AgeGroupBarAnimationUtils;
import com.worldchip.bbp.ect.util.BBPawAnimationUtils;
import com.worldchip.bbp.ect.util.BBPawAnimationUtils.MyAnimationListener;
import com.worldchip.bbp.ect.util.Configure;
import com.worldchip.bbp.ect.util.FishAnimationUtils;
import com.worldchip.bbp.ect.util.HttpCommon;
import com.worldchip.bbp.ect.util.HttpResponseCallBack;
import com.worldchip.bbp.ect.util.HttpUtils;
import com.worldchip.bbp.ect.util.JsonUtils;
import com.worldchip.bbp.ect.util.LunarCalendar;
import com.worldchip.bbp.ect.util.MD5Util;
import com.worldchip.bbp.ect.util.PangxieAnimationUtils;
import com.worldchip.bbp.ect.util.PictureUploadUtils;
import com.worldchip.bbp.ect.util.SettingAnimationUtils;
import com.worldchip.bbp.ect.util.Utils;
import com.worldchip.bbp.ect.view.BearDrawableAnim;
import com.worldchip.bbp.ect.view.CircleImageView;
import com.worldchip.bbp.ect.view.GlobalProgressDialog;
//import com.worldchip.bbp.ect.util.MD5Check;
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener, MYGalleryOnTounchListener, HttpResponseCallBack {
private static final int HTTP_UPDETE_CODE = 119;
private static final int UPDATE_BBPAW_ALLPHOTO = 2;
private static final int FIRST_SHOW_USER_EDIT = 7;
private static final int EDIT_BABYINFORMATION = 9;
private static final int UPDATE_BBPAW_AGEDUAN_THREE = 13;
private static final int UPDATE_BBPAW_AGEDUAN_FIVE = 14;
private static final int UPDATE_BBPAW_AGEDUAN_SEVEN = 15;
private static final int REFRESH_USER_VIEW = 16;
private static final int ANBLE_CLICK_NUMBER = 1010;
// private static final int UPDATE_BABYINFO=16;
/** 涓撻敓鏂ゆ嫹閿熸枻鎷疯閿熸枻鎷锋伅閿熸枻鎷烽敓鏂ゆ嫹 **/
public static final String INFORMATION_MAIN_TYPE = "102";
public static final String NOTIFY_MSG_MAIN_TYPE = "98";
public static final String RECEIVE_PUSH_MESSAGE_TYPE_KEY = "messageType";
public static final String RECEIVE_PUSH_MESSAGE_ACTION = "com.worldchip.bbpaw.client.manager.receivePushMessage";
public static final int REFRESH_UNREAD_COUNT = 12;
private boolean first ;
private int startCount = 0;
private Typeface mTypeface;
private RelativeLayout mHomeMain;
private MyGallery mGallery;
private Animation mGalleryAnim;
private ImageAdapter adapter;
private AnimationDrawable mAnimationDrawableElephantsErduo;
private ImageView mElephantErDuo, mPangXie;
private ImageView mFinshView;
private SoundPool soundPool = null;
private HashMap<Integer, Integer> mSoundMap = null;
private PopupWindow mEditInformation;
private TextView mBaby_name, mBaby_sex, mBoy_tv, mGirl_tv, mBaby_year,
mBaby_month, mBaby_ri, mBaby_fyear, mBaby_fmonth, mBaby_fri;
private RelativeLayout mSecand_edit_relayout, mFirst_relayout,
mPopuwidow_relayout, mPopuWindow_bg;
private LinearLayout mBabyYearLayout, mBabyMonthLayout, mBabyRiLayout;
private ImageView mBabyTete, mBaby_edit, mCancel_edit, mBabyMoren_edite;
private TextView mBb_nicheng, mBb_shengri, mBb_nicheng_edit,
mBb_shengri_edit, mBb_brithday_year_tv, mBb_brithday_month_tv,
mBb_brithday_ri_tv;
private RadioGroup mRaioGroup;
private SharedPreferences mBabyinfo, mShared, mFestival, mAccount;
private RadioButton mBoy_radiobtn, mGirl_radiobtn;
private EditText mBaby_editname;
private Button mSave, mYear, mMonth, mRi;
private WheelView mYearWheelView;
private WheelView mMonthWheelView;
private WheelView mDayWheelView;
private boolean mYearWheelViewShowing = false;
private boolean mMonthWheelViewShowing = false;
private boolean mDayWheelViewShowing = false;
private ChickenView[] mChickenViews = null;
private RelativeLayout mAgeGroupBar;
private CircleImageView mPhotoView = null;
private View mWindowRLView = null;
private TextView mNameTV;
private TextView mAgeTV;
private TextView mAgeSwitchTV;
// private boolean isTransitionDoorView = true;
private boolean isDisplayAgeGroupBar = false;
private TextView[] mAgeGroupBarView = null;
private static final int AGE_GROUP_BAR_01 = 0;
private static final int AGE_GROUP_BAR_02 = 1;
private static final int AGE_GROUP_BAR_03 = 2;
private static final int AGE_GROUP_BAR_COUNT = 3;
private static final int[] AGR_GROUP_BAR_RES = {
R.drawable.age_group_bg_01, R.drawable.age_group_bg_02,
R.drawable.age_group_bg_03 };
// private static final int DEFAULT_AGE_GROUP_SELECT = 1;
private static final int DEFAULT_AGE_GROUP_SELECT = 2;
private Resources mResources;
private static ImageView mBearIV = null;
private static ImageView mGrassIV = null;
private static ImageView mWavesIV = null;
private static final int START_ACTIVITY = 100;
private boolean isErduoClickEnable = true;
private boolean grassRunning = false;
private BearDrawableAnim mBearDrawableAnim = null;
private ImageView mImageViewWifi, mImageViewPower;
private IntentFilter mWifiIntentFilter, mIntentFilter;
private TextView mTvHourDecade, mTvHourUnits, mCountdownHourMaohao,
mTvMinuteDecade, mTvMinuteUnits, mCountdownMaohao, mTvSecondDecade,
mTvSecondUnits;
private MinuteCountDown mc;
private TimeQuanCountdownTimer tqct;
private RelativeLayout mRedMessage;
private TextView mMessageCount;
private MainPushMessageReceiver mPushMessageReceiver;
private LoginReceiver mLoginReceiver;
private Context mContext = null;
private static final int START_SETUPWIZARD = 101;
private ImageView mCh_UK;
private boolean isChange = true;
private String mLanguage;
private static final int CLICK_SOUND_KEY = 30;
private boolean mUserPhotoChange = false;
private static final int USER_EDIT_RESULT_NOTWORK = 0;
@SuppressWarnings("unused")
private static final int USER_EDIT_RESULT_SUCCESS = 1;
private static final int USER_EDIT_RESULT_FAILURE = 2;
private static final int START_PHOTO_UPLOAD = 1000;
private static final int USER_EDIT_COMPLETE = 1001;
private static final int PHOTO_UPLOAD_COMPLETE = 1002;
protected static final int INIT_DATA = 1003;
protected static final int RESUME_DATA = 1004;
protected static final int FESTIVAL_BLESS_PUSH = 1005;
public static boolean isIconClick = false;
private GlobalProgressDialog mGlobalProgressDialog;
private String mEditPhotoPath = null;
private SharedPreferences mPref;
private SharedPreferences.Editor editor;
public static int MODE = Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE;
public static final String PREFER_NAME = "save_account";
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FESTIVAL_BLESS_PUSH:
pushFestivalBless();
break;
case INIT_DATA:
initData();
LoginState loginState = LoginState.getInstance();
boolean isLogin = loginState.isLogin();
if (!isLogin) {
loginAccount();
}
break;
case RESUME_DATA:
resumeData();
break;
case FIRST_SHOW_USER_EDIT:
showUserInfo(true);
break;
case START_ACTIVITY:
if (mAnimationDrawableElephantsErduo != null) {
mAnimationDrawableElephantsErduo.stop();
}
isErduoClickEnable = true;
Utils.startApp(MainActivity.this,
"com.worldchip.bbp.bbpawmanager.cn",
"com.worldchip.bbp.bbpawmanager.cn.activity.MainActivity");
break;
case EDIT_BABYINFORMATION:
showUserInfo(false);
break;
case REFRESH_UNREAD_COUNT:
if (DataManager.getMessageValue(MainActivity.this) > 0) {
mRedMessage.setVisibility(View.VISIBLE);
mMessageCount.setText(String.valueOf(DataManager
.getMessageValue(MainActivity.this)));
} else {
mRedMessage.setVisibility(View.GONE);
}
break;
case UPDATE_BBPAW_AGEDUAN_THREE:
mAgeSwitchTV.setText(R.string.age_group_text01);
break;
case UPDATE_BBPAW_AGEDUAN_FIVE:
mAgeSwitchTV.setText(R.string.age_group_text02);
break;
case UPDATE_BBPAW_AGEDUAN_SEVEN:
mAgeSwitchTV.setText(R.string.age_group_text03);
break;
case START_SETUPWIZARD:
Utils.startApplication(MyApplication.getAppContext(),
"com.worldchip.bbpaw.bootsetting",
"com.worldchip.bbpaw.bootsetting.activity.MainActivity");
break;
case REFRESH_USER_VIEW:
refreshUserView();
break;
case START_PHOTO_UPLOAD:
startProgressDialog();
break;
case PHOTO_UPLOAD_COMPLETE:
String imageUrl = "";
if (msg.obj != null) {
imageUrl = (String) msg.obj;
commitUserChange(imageUrl);
} else {
commitUserChange(LoginState.getInstance().getPhotoUrl());
}
break;
case USER_EDIT_COMPLETE:
int result = msg.arg1;
stopProgressDialog();
if (result == USER_EDIT_RESULT_NOTWORK) {
Utils.showToastMessage(MyApplication.getAppContext(),
getString(R.string.network_error_text));
}
break;
case ANBLE_CLICK_NUMBER:
mSave.setClickable(true);
break;
case HTTP_UPDETE_CODE:
stopProgressDialog();
Bundle data = msg.getData();
String httpTag = null;
if (data != null) {
httpTag = data.getString("httpTag");
}
if (msg.arg1 == Configure.SUCCESS) {
if (httpTag == null)
return;
String results = data.getString("result");
String resultCode = JsonUtils.doParseValueForKey(results, "resultCode");
if (resultCode == null || TextUtils.isEmpty(resultCode)) {
return;
}
if (httpTag.equals(Configure.HTTP_TAG_UPDATE_BABYINFO)) {
UpdateBabyInfo updateBabyInfo = null;
if (Integer.parseInt(resultCode) == HttpUtils.HTTP_RESULT_CODE_SUCCESS) {
updateBabyInfo = JsonUtils
.updateBabyInfoJson2bean(results);
}
handResultMessge(Integer.parseInt(resultCode),
Configure.HTTP_TAG_UPDATE_BABYINFO, updateBabyInfo);
} else if (httpTag.equals(Configure.HTTP_TAG_LOGIN) ){
LoginState loginInfo = JsonUtils.doLoginJson2Bean(results);
Log.d("Wing", "------++++----> " + loginInfo.toString());
handResultMessge(loginInfo.getResultCode(), Configure.HTTP_TAG_LOGIN, loginInfo);
}
} else {
if (httpTag.equals(Configure.HTTP_TAG_UPDATE_BABYINFO)) {
Utils.showToastMessage(MyApplication.getAppContext(),
getString(R.string.update_password_failure));
} else if (httpTag.equals(Configure.HTTP_TAG_LOGIN)) {
Utils.showToastMessage(MainActivity.this, getString(R.string.login_failure));
}
}
break;
default:
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mPref = getSharedPreferences(PREFER_NAME, MODE);
editor = mPref.edit();
HttpCommon.hideSystemUI(MainActivity.this, true);
initView();
initHouseView();
mResources = getResources();
// startFinshAnim();//鱼的动画
mTypeface = Typeface.createFromAsset(getAssets(), "Droidhuakangbaoti.TTF");
adapter = new ImageAdapter(Utils.getGalleryImageList(), MainActivity.this);
mGallery.setAdapter(adapter);
mGallery.setSelection(1947);
mGallery.setOnItemSelectedListener(mGallerySelectListener);
mGallery.setOnItemClickListener(onItemClickListener);
mShared = getSharedPreferences("config", Context.MODE_PRIVATE);
startCount = mShared.getInt("startCount", 0);
if (startCount == 0) {
mShared.edit().putInt("startCount", 1).commit();
}else if (startCount == 1) {
mShared.edit().putInt("startCount", 2).commit();
}else if (startCount == 2) {
mShared.edit().putInt("startCount", 3).commit();
}
if (startCount < 3) {
Utils.initBBpawDataBases(MyApplication.getAppContext());
mHandler.sendEmptyMessageDelayed(START_SETUPWIZARD, 2000);
}
//注册接受登录广播
registerLoginReceiver();
}
//开机登录
private void loginAccount() {
String account = mAccount.getString("account", "");
String password = mAccount.getString("password", "");
String cpuSerial = Utils.getCpuSerial(this);
Log.d("Wing", "loginAccount: account=" + account + " password= " + password);
if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(password)) {
String httpUrl = Configure.LOGIN_URL
.replace("ACCOUNT", account)
.replace("PASSWORD", MD5Util.string2MD5(password))
.replace("DEVICE_ID", cpuSerial);
Log.d("Wing", "httpUrl == " + httpUrl);
HttpUtils.doPost(httpUrl, MainActivity.this,
Configure.HTTP_TAG_LOGIN);
} /*else {
Utils.showToastMessage(MainActivity.this,
getString(R.string.login_input_error));
}*/
}
private void registerLoginReceiver() {
mLoginReceiver = new LoginReceiver();
IntentFilter loginReceiverFilter = new IntentFilter();
loginReceiverFilter.addAction(Utils.LOGIN_SECCUSS_ACTION);
loginReceiverFilter.addAction(Utils.LOGIN_OUT_ACTICON);
registerReceiver(mLoginReceiver, loginReceiverFilter);
}
private void initData() {
chickenMove();
runBearAnim();
}
private void resumeData() {
// WIFI
mWifiIntentFilter = new IntentFilter();
mWifiIntentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
Intent intent = new Intent(MainActivity.this, TimeTontrolService.class);
startService(intent);
Intent intentScanService = new Intent(MainActivity.this, ScanService.class);
startService(intentScanService);
/*mLoginReceiver = new LoginReceiver();
IntentFilter loginReceiverFilter = new IntentFilter();
loginReceiverFilter.addAction(Utils.LOGIN_SECCUSS_ACTION);
loginReceiverFilter.addAction(Utils.LOGIN_OUT_ACTICON);
registerReceiver(mLoginReceiver, loginReceiverFilter);
*/
mPushMessageReceiver = new MainPushMessageReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(RECEIVE_PUSH_MESSAGE_ACTION);
registerReceiver(mPushMessageReceiver, filter);
mHandler.sendEmptyMessage(REFRESH_UNREAD_COUNT);
// runBearAnim();
if (wifiIntentReceiver != null) {
registerReceiver(wifiIntentReceiver, mWifiIntentFilter);
}
if (mIntentReceiver != null) {
registerReceiver(mIntentReceiver, mIntentFilter);
}
// mHandler.removeMessages(UPDATE_BBPAW_ALLPHOTO);
// mHandler.sendEmptyMessage(UPDATE_BBPAW_ALLPHOTO);
SharedPreferences preferences = getSharedPreferences("time_info", 0);
TimeTontrolService service = new TimeTontrolService();
if (preferences != null) {
// int countdownState = preferences.getInt("countdownState", 0);
// int quantumState = preferences.getInt("quantumState", 0);
// int dateTimeState = preferences.getInt("dateTimeState", 0);
boolean isTimeCountdownOK = preferences.getBoolean(
"isTimeCountdownOK", false);
boolean isTimeOK = preferences.getBoolean("isTimeOK", false);
boolean isDateOK = preferences.getBoolean("isDateOK", false);
if (isTimeCountdownOK) {
if (mc != null) {
mc.cancel();
}
service.onStartTime(false, MainActivity.this);
service.onStartTime(true, MainActivity.this);
int time = preferences.getInt("countdown", 0);
// 閿熺瓔闀夸负120閿熸枻鎷烽敓鏂ゆ嫹
mc = new MinuteCountDown(time * 1000, 1000);
mc.start();
}
if (isTimeOK) {
if (tqct != null) {
tqct.cancel();
}
service.onStartTimeQuantum(false, MainActivity.this);
service.onStartTimeQuantum(true, MainActivity.this);
String timequantumstart = preferences
.getString("startTime", "");
String timequantumend = preferences.getString("endTime", "");
int timequantumstarthour = Integer.parseInt(timequantumstart
.substring(0, 2));
int timequantumstartminit = Integer.parseInt(timequantumstart
.substring(3, 5));
int timequantumendhour = Integer.parseInt(timequantumend
.substring(0, 2));
int timequantumendminit = Integer.parseInt(timequantumend
.substring(3, 5));
int times;
if (timequantumstarthour == timequantumendhour) {
times = timequantumendminit - timequantumstartminit;
} else {
if (timequantumendminit >= timequantumstartminit) {
times = (timequantumendhour - timequantumstarthour) * 60
+ (timequantumendminit - timequantumstartminit);
} else {
times = ((timequantumendhour - timequantumstarthour) * 60 + timequantumendminit)
- timequantumstartminit;
}
}
}
if (isDateOK) {
service.onStartTimeQuantum(false, MainActivity.this);
service.onStartTimeQuantum(true, MainActivity.this);
}
}
startGrassAnim();
}
private void startGrassAnim() {
if (mGrassIV != null) {
SettingAnimationUtils.startAnimation(mGrassIV, 4000);
}
}
private void startFinshAnim() {
// ImageView finshView = (ImageView) findViewById(R.id.fish_iv);
RelativeLayout waterRL = (RelativeLayout) findViewById(R.id.water_rl);
if (mFinshView != null && waterRL != null) {
mFinshView.clearAnimation();
waterRL.clearAnimation();
FishAnimationUtils.startAnimation(mFinshView, waterRL,
FishAnimationUtils.START_NEXT_ANIMATION_OFFSET);
}
}
// 小熊动画
private void runBearAnim() {
if (mBearIV != null) {
if (mBearDrawableAnim != null) {
mBearDrawableAnim.stopAnimation();
}
mBearDrawableAnim = BearDrawableAnim.getInstance(mBearIV);
mBearDrawableAnim.setBearAnimGroup(Utils.BEAR_ANIM_DEFAULT_INDEX);
mBearDrawableAnim.startAnimation(1, 1000);
}
}
private void stopBearAnim() {
if (mBearDrawableAnim != null) {
mBearDrawableAnim.stopAnimation();
mBearDrawableAnim = null;
}
}
// 小屋
private void initHouseView() {
mAgeSwitchTV = (TextView) findViewById(R.id.age_switch_tv);
mWindowRLView = findViewById(R.id.door_rl_view);
mWindowRLView.setOnClickListener(this);
mAgeSwitchTV.setOnClickListener(this);
mAgeGroupBar = (RelativeLayout) findViewById(R.id.rl_age_group_bar);
mPhotoView = (CircleImageView) findViewById(R.id.photo_iv);
mNameTV = (TextView) mWindowRLView.findViewById(R.id.name_tv);
mNameTV.setSelected(true);
mAgeTV = (TextView) mWindowRLView.findViewById(R.id.age_tv);
mAgeGroupBarView = new TextView[AGE_GROUP_BAR_COUNT];
mAgeGroupBarView[AGE_GROUP_BAR_01] = (TextView) findViewById(R.id.ib_age_group_01);
mAgeGroupBarView[AGE_GROUP_BAR_02] = (TextView) findViewById(R.id.ib_age_group_02);
mAgeGroupBarView[AGE_GROUP_BAR_03] = (TextView) findViewById(R.id.ib_age_group_03);
mAgeGroupBarView[AGE_GROUP_BAR_01].setOnClickListener(this);
mAgeGroupBarView[AGE_GROUP_BAR_02].setOnClickListener(this);
mAgeGroupBarView[AGE_GROUP_BAR_03].setOnClickListener(this);
/*
* String[] ageGroups = getResources().getStringArray(
* R.array.age_group_arry);
* mAgeSwitchTV.setText(ageGroups[DEFAULT_AGE_GROUP_SELECT]);
* updateAgeGroupBar(DEFAULT_AGE_GROUP_SELECT);
*/
//refreshUserView();
}
private void initSoundPools() {
if (mSoundMap != null && mSoundMap.size() > 0) {
mSoundMap.clear();
}
if (soundPool == null) {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
}
if (mSoundMap == null) {
mSoundMap = new HashMap<Integer, Integer>();
}
mSoundMap.put(CLICK_SOUND_KEY, soundPool.load(this, R.raw.click, 1));
int[] appNameSounds = null;
int languageIndex = Utils.getLanguageInfo(MyApplication.getAppContext());
if (languageIndex == Utils.CH_LANGUAGE_INDEX) {
appNameSounds = Utils.APP_NAME_SOUNDS_RES_MAP_CN;
} else {
appNameSounds = Utils.APP_NAME_SOUNDS_RES_MAP_ENG;
}
if (appNameSounds != null && appNameSounds.length > 0) {
for (int i = 0; i < appNameSounds.length; i++) {
mSoundMap.put(i + 1, soundPool.load(MainActivity.this, appNameSounds[i], 1));
}
}
}
private void initView() {
mBabyinfo = getSharedPreferences("babyinfo", 0);
mFestival = getSharedPreferences("mfestival", MODE_PRIVATE);
mAccount = getSharedPreferences("save_account", MODE_PRIVATE);
//初始化声音池
initSoundPools();
// 閿熸枻鎷�
mBearIV = (ImageView) findViewById(R.id.ppaw_bear);
mBearIV.setOnTouchListener(this);
mGrassIV = (ImageView) findViewById(R.id.grass_iv);
mGrassIV.setOnClickListener(this);
mWavesIV = (ImageView) findViewById(R.id.waves_iv);
mHomeMain = (RelativeLayout) findViewById(R.id.home_main);
mGallery = (MyGallery) findViewById(R.id.gallery);
mGallery.setOnTounchListener(this);
mGalleryAnim = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
if (mGalleryAnim != null) {
mGallery.startAnimation(mGalleryAnim);
}
// 鱼儿
mFinshView = (ImageView) findViewById(R.id.fish_iv);
mFinshView.setOnClickListener(this);
// 大象耳朵
mElephantErDuo = (ImageView) findViewById(R.id.elephants_erduo);
mElephantErDuo.setImageResource(Utils.getResourcesId(
MyApplication.getAppContext(), "yuerbaodian_1", "drawable"));
mElephantErDuo.setOnClickListener(this);
// 螃蟹
mPangXie = (ImageView) findViewById(R.id.pangxie);
mPangXie.setOnClickListener(this);
// wifi
mImageViewWifi = (ImageView) findViewById(R.id.wifi_imageview);
mImageViewPower = (ImageView) findViewById(R.id.dianchi_imageview);
//
mTvHourDecade = (TextView) findViewById(R.id.mTvHourDecade);
// 鏃�(鍗佷綅閿熸枻鎷�
mTvHourUnits = (TextView) findViewById(R.id.mTvHourUnits);
// 鍐掗敓鏂ゆ嫹
mCountdownHourMaohao = (TextView) findViewById(R.id.countdown_HourMaohao);
// 閿熸枻鎷烽敓鎺ワ綇鎷峰崄浣嶉敓鏂ゆ嫹
mTvMinuteDecade = (TextView) findViewById(R.id.mTvMinuteDecade);
// 閿熸枻鎷烽敓鎺ワ綇鎷烽敓鏂ゆ嫹浣嶉敓鏂ゆ嫹
mTvMinuteUnits = (TextView) findViewById(R.id.mTvMinuteUnits);
// 鍐掗敓鏂ゆ嫹
mCountdownMaohao = (TextView) findViewById(R.id.countdown_maohao);
// 閿熻锛堝崄浣嶉敓鏂ゆ嫹
mTvSecondDecade = (TextView) findViewById(R.id.mTvSecondDecade);
// 閿熻锛堥敓鏂ゆ嫹浣嶉敓鏂ゆ嫹
mTvSecondUnits = (TextView) findViewById(R.id.mTvSecondUnits);
// 推送消息
mRedMessage = (RelativeLayout) findViewById(R.id.redmessage_relayout);
mMessageCount = (TextView) findViewById(R.id.message_tuisong);
mRedMessage.setVisibility(View.GONE);
// 中英文切换按钮
mCh_UK = (ImageView) findViewById(R.id.china_english_qiechuan);
mCh_UK.setOnClickListener(this);
updateLanguageButton(Utils.getLanguageInfo(MyApplication.getAppContext()));
//startGuid();
}
private void startGuid() {
boolean bootSettingsValue = Utils.getSetupWizardPreference(MyApplication.getAppContext());
SharedPreferences preferences = getSharedPreferences("user_info", 0);
boolean ectShowSetup = preferences.getBoolean("isSetupWizard", true);
boolean isSetupWizard = (bootSettingsValue && ectShowSetup ? true
: false);
Log.e("lee", "isSetupWizard == " + isSetupWizard
+ " bootSettingsValue == " + bootSettingsValue
+ " ectShowSetup == " + ectShowSetup);
if (isSetupWizard) {
preferences.edit().putBoolean("isSetupWizard", false).commit();
mHandler.sendEmptyMessageDelayed(START_SETUPWIZARD, 2000);
}
}
/**
* 閿熸枻鎷烽敓鏂ゆ嫹涓�閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷锋椂閿熸枻鎷烽敓鑺傝鎷烽敓鏂ゆ嫹 閿熺瓔闀夸负120閿熸枻鎷烽敓鏂ゆ嫹
*/
class MinuteCountDown extends CountDownTimer {
public MinuteCountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
mTvHourDecade.setBackgroundResource(R.drawable.countdown_zero);
mTvHourUnits.setBackgroundResource(R.drawable.countdown_zero);
mTvMinuteDecade.setBackgroundResource(R.drawable.countdown_zero);
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_zero);
mCountdownMaohao.setBackgroundResource(R.drawable.countdown_maohao);
mTvSecondDecade.setBackgroundResource(R.drawable.countdown_zero);
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_zero);
SharedPreferences preferences = getSharedPreferences("time_info", 0);
preferences.edit().putBoolean("isTimeCountdownOK", false).commit();
Intent intentStart = new Intent(MainActivity.this, PassLockActivity.class);
startActivity(intentStart);
// finish();
}
@Override
public void onTick(long millisUntilFinished) {
int sum_millisUntilFinished = (int) (millisUntilFinished - 1000);
int hour = (int) millisUntilFinished / (60 * 60 * 1000);
// int hour_decade = hour / 10;
int hour_units = hour % 10;
int minute = sum_millisUntilFinished / (60 * 1000);
int minute_decade = minute % 60 / 10;
int minute_units = minute % 10;
int second = sum_millisUntilFinished / 1000;
int second_decade = second % 60 / 10;
int second_units = second % 10;
mTvHourDecade.setBackgroundResource(R.drawable.countdown_zero);
mCountdownHourMaohao
.setBackgroundResource(R.drawable.countdown_maohao);
mCountdownMaohao.setBackgroundResource(R.drawable.countdown_maohao);
switch (hour_units) {
case 1:
mTvHourUnits.setBackgroundResource(R.drawable.countdown_one);
break;
case 0:
mTvHourUnits.setBackgroundResource(R.drawable.countdown_zero);
break;
default:
break;
}
switch (minute_decade) {
case 6:
mTvMinuteDecade.setBackgroundResource(R.drawable.countdown_six);
break;
case 5:
mTvMinuteDecade
.setBackgroundResource(R.drawable.countdown_five);
break;
case 4:
mTvMinuteDecade
.setBackgroundResource(R.drawable.countdown_four);
break;
case 3:
mTvMinuteDecade
.setBackgroundResource(R.drawable.countdown_three);
break;
case 2:
mTvMinuteDecade.setBackgroundResource(R.drawable.countdown_two);
break;
case 1:
mTvMinuteDecade.setBackgroundResource(R.drawable.countdown_one);
break;
case 0:
mTvMinuteDecade
.setBackgroundResource(R.drawable.countdown_zero);
break;
default:
break;
}
switch (minute_units) {
case 9:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_nine);
break;
case 8:
mTvMinuteUnits
.setBackgroundResource(R.drawable.countdown_eight);
break;
case 7:
mTvMinuteUnits
.setBackgroundResource(R.drawable.countdown_seven);
break;
case 6:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_six);
break;
case 5:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_five);
break;
case 4:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_four);
break;
case 3:
mTvMinuteUnits
.setBackgroundResource(R.drawable.countdown_three);
break;
case 2:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_two);
break;
case 1:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_one);
break;
case 0:
mTvMinuteUnits.setBackgroundResource(R.drawable.countdown_zero);
break;
default:
break;
}
switch (second_decade) {
case 6:
mTvSecondDecade.setBackgroundResource(R.drawable.countdown_six);
break;
case 5:
mTvSecondDecade
.setBackgroundResource(R.drawable.countdown_five);
break;
case 4:
mTvSecondDecade
.setBackgroundResource(R.drawable.countdown_four);
break;
case 3:
mTvSecondDecade
.setBackgroundResource(R.drawable.countdown_three);
break;
case 2:
mTvSecondDecade.setBackgroundResource(R.drawable.countdown_two);
break;
case 1:
mTvSecondDecade.setBackgroundResource(R.drawable.countdown_one);
break;
case 0:
mTvSecondDecade
.setBackgroundResource(R.drawable.countdown_zero);
break;
default:
break;
}
switch (second_units) {
case 9:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_nine);
break;
case 8:
mTvSecondUnits
.setBackgroundResource(R.drawable.countdown_eight);
break;
case 7:
mTvSecondUnits
.setBackgroundResource(R.drawable.countdown_seven);
break;
case 6:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_six);
break;
case 5:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_five);
break;
case 4:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_four);
break;
case 3:
mTvSecondUnits
.setBackgroundResource(R.drawable.countdown_three);
break;
case 2:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_two);
break;
case 1:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_one);
break;
case 0:
mTvSecondUnits.setBackgroundResource(R.drawable.countdown_zero);
break;
default:
break;
}
}
}
class TimeQuanCountdownTimer extends CountDownTimer {
public TimeQuanCountdownTimer(long millisInFuture,
long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
}
@Override
public void onTick(long millisUntilFinished) {
int sum_millisUntilFinished = (int) (millisUntilFinished - 1000);
int hour = (int) millisUntilFinished / (60 * 60 * 1000);
// int hour_decade = hour / 10;
int hour_units = hour % 10;
int minute = sum_millisUntilFinished / (60 * 1000);
int minute_decade = minute % 60 / 10;
int minute_units = minute % 10;
int second = sum_millisUntilFinished / 1000;
int second_decade = second % 60 / 10;
int second_units = second % 10;
}
}
/**
* 鍥剧墖閿熸枻鎷烽敓鏂ゆ嫹褰曢敓锟�
*/
private OnItemClickListener onItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
playSimpleSound(CLICK_SOUND_KEY);
IconInfo iconInfo = (IconInfo) parent.getAdapter().getItem(
position % Utils.GALLERY_VIEWS_COUNT);
isIconClick = true;
int key = iconInfo.getIndex() + 1;
String packageName = null;
String activityName = null;
switch (key) {
case 1:
if (Utils.isFastDoubleClick()) {
return;
}
//packageName = "com.worldchip.bbpaw.chinese.zhbx";
//activityName = "org.cocos2dx.cpp.AppActivity";
startActivity(new Intent(MainActivity.this, MyAppActivity.class));
break;
case 2:
if (Utils.isFastDoubleClick()) {
return;
}
packageName = "com.worldchip.bbpaw.chinese.ctjy";
activityName = "org.cocos2dx.cpp.AppActivity";
break;
case 3:
if (Utils.isFastDoubleClick()) {
return;
}
packageName = "com.worldchip.bbpaw.chinese.yyqh";
activityName = "org.cocos2dx.cpp.AppActivity";
break;
case 4:
if (Utils.isFastDoubleClick()){
return;
}
packageName = "com.worldchip.bbpaw.chinese.jyjy";
activityName = "org.cocos2dx.cpp.AppActivity";
break;
case 5:
if (Utils.isFastDoubleClick()) {
return;
}
packageName = "com.worldchip.bbpaw.chinese.whny";
activityName = "org.cocos2dx.cpp.AppActivity";
break;
case 6:
if (Utils.isFastDoubleClick()) {
return;
}
packageName = "com.worldchip.bbpaw.chinese.kxjy";
activityName = "org.cocos2dx.cpp.AppActivity";
break;
}
if (key >= 0 && mSoundMap != null && mSoundMap.size() > 0) {
playSimpleSound(key);
}
if (packageName != null && activityName != null) {
Utils.startApp(MainActivity.this, packageName, activityName);
}
}
};
private void chickenMove() {
boolean hasChicken = false;
for (int i = 0; i < mHomeMain.getChildCount(); i++) {
if (mHomeMain.getChildAt(i) instanceof ChickenView) {
hasChicken = true;
}
}
if (!hasChicken) {
addChicken();
} else {
if (mChickenViews != null) {
for (int i = 0; i < mChickenViews.length; i++) {
mChickenViews[i].start();
}
}
}
}
private void stopChickenMove() {
if (mChickenViews != null) {
for (int i = 0; i < mChickenViews.length; i++) {
mChickenViews[i].stop();
}
}
}
private OnItemSelectedListener mGallerySelectListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (!isIconClick) {
playSimpleSound(CLICK_SOUND_KEY);
Log.i("Lee", "-----------------playSimpleSound------+++++++++++>");
isIconClick = false;
}
mGallery.setSelection(position);
adapter.setSelectedPosition(position);
adapter.notifyDataSetChanged();
isIconClick = false;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
private String TAG;
/**
*
*
* @param view
*/
public void onClick(View view) {
switch (view.getId()) {
case R.id.china_english_qiechuan:
isIconClick = true;
changeLanguage();
// Intent intent=new Intent(MainActivity.this,
// PatriarchControlActivity.class);
// startActivity(intent);
break;
case R.id.fish_iv:
playSimpleSound(CLICK_SOUND_KEY);
startFinshAnim();
break;
case R.id.elephants_erduo:
if ( Utils.isFastDoubleClick() ) {
return;
}
playSimpleSound(7);
if (isErduoClickEnable) {
isErduoClickEnable = false;
if (mAnimationDrawableElephantsErduo == null) {
mElephantErDuo.setImageResource(Utils.getResourcesId(
MyApplication.getAppContext(), "elephant_erduo",
"anim"));
mAnimationDrawableElephantsErduo = (AnimationDrawable) mElephantErDuo
.getDrawable();
}
mAnimationDrawableElephantsErduo.start();
int duration = 0;
for (int i = 0; i < mAnimationDrawableElephantsErduo
.getNumberOfFrames(); i++) {
duration += mAnimationDrawableElephantsErduo.getDuration(i);
}
Log.e("lee", "duration == " + duration);
mHandler.sendEmptyMessageDelayed(START_ACTIVITY, duration);
}
break;
case R.id.pangxie:
playSimpleSound(CLICK_SOUND_KEY);
if (mPangXie != null && !PangxieAnimationUtils.isRunningAnimation()) {
PangxieAnimationUtils.startInRotateAnimation(mPangXie, 0);
}
break;
case R.id.door_rl_view:
playSimpleSound(CLICK_SOUND_KEY);
if (view.getId() == R.id.door_rl_view) {
mHandler.sendEmptyMessage(EDIT_BABYINFORMATION);
}
break;
case R.id.age_switch_tv:
playSimpleSound(8);
if (AgeGroupBarAnimationUtils.isRunningAnimation())
return;
if (isDisplayAgeGroupBar) {
AgeGroupBarAnimationUtils.startOutRotateAnimation(mAgeGroupBar,0);
} else {
AgeGroupBarAnimationUtils.startInRotateAnimation(mAgeGroupBar,0);
}
isDisplayAgeGroupBar = !isDisplayAgeGroupBar;
break;
case R.id.ib_age_group_01:
playSimpleSound(CLICK_SOUND_KEY);
updateAgeGroupBar(AGE_GROUP_BAR_01);
mHandler.sendEmptyMessage(UPDATE_BBPAW_AGEDUAN_THREE);
Log.e(TAG, "group 01..before value="+ DataManager.getAgeValue(MainActivity.this));
DataManager.setAgeValue(MainActivity.this, 0);
Log.e(TAG, "group 01..after value=" + DataManager.getAgeValue(MainActivity.this));
break;
case R.id.ib_age_group_02:
playSimpleSound(CLICK_SOUND_KEY);
updateAgeGroupBar(AGE_GROUP_BAR_02);
mHandler.sendEmptyMessage(UPDATE_BBPAW_AGEDUAN_FIVE);
DataManager.setAgeValue(MainActivity.this, 1);
break;
case R.id.ib_age_group_03:
playSimpleSound(CLICK_SOUND_KEY);
updateAgeGroupBar(AGE_GROUP_BAR_03);
mHandler.sendEmptyMessage(UPDATE_BBPAW_AGEDUAN_SEVEN);
DataManager.setAgeValue(MainActivity.this, 2);
break;
case R.id.grass_iv:
if ( Utils.isFastDoubleClick() ) {
return;
}
playSimpleSound(CLICK_SOUND_KEY);
// Utils.startApp(MainActivity.this,
// "com.worldchip.bbp.bbpawmanager",
// "com.worldchip.bbp.bbpawmanager.activity.MainActivity");
/*if (!grassRunning) {
grassRunning = true;
runGrassAnim(view);
}*/
runGrassAnim(view);
break;
default:
break;
}
}
private void changeLanguage() {
mLanguage = Locale.getDefault().getLanguage();
try {
Locale locale = null;
int languageIndex = 0;
if (!(mLanguage.equals("zh"))) {
locale = Locale.CHINA;
languageIndex = Utils.CH_LANGUAGE_INDEX;
} else {
locale = Locale.ENGLISH;
languageIndex = Utils.ENG_LANGUAGE_INDEX;
}
Utils.updateLanguage(locale);
updateLanguageButton(languageIndex);
} catch (Exception e) {
e.printStackTrace();
}
}
private void showUserInfo(boolean isEdit) {
if (mEditInformation != null) {
mEditInformation.dismiss();
mEditInformation = null;
}
if (mPopuwidow_relayout == null) {
mPopuwidow_relayout = (RelativeLayout) LayoutInflater.from(
MainActivity.this).inflate(R.layout.bb_edit_box_layout, null);
mPopuwidow_relayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
hideAllDateWheelView();
return false;
}
});
}
mEditInformation = new PopupWindow(mContext);
mEditInformation.setBackgroundDrawable(new ColorDrawable(0));
mEditInformation.setWidth(LayoutParams.MATCH_PARENT);
mEditInformation.setHeight(LayoutParams.MATCH_PARENT);
mEditInformation.setOutsideTouchable(false);
mEditInformation.setFocusable(true);
mEditInformation.setContentView(mPopuwidow_relayout);
mEditInformation.showAtLocation(findViewById(R.id.home_main),
Gravity.CENTER, 0, -30);
mPopuWindow_bg = (RelativeLayout) mPopuwidow_relayout
.findViewById(R.id.bb_bg_relayout);
// mPopuWindow_bg.setBackgroundResource(Utils.getResourcesId(MyApplication.getAppContext(),
// "zz_bbinfo_bg", "drawable"));
mCancel_edit = (ImageView) mPopuwidow_relayout
.findViewById(R.id.bb_cancel_btn);
mFirst_relayout = (RelativeLayout) mPopuwidow_relayout
.findViewById(R.id.bb_secand_relayout);
mSecand_edit_relayout = (RelativeLayout) mPopuwidow_relayout
.findViewById(R.id.baby_edit_secand_relayout);
mSave = (Button) mPopuwidow_relayout
.findViewById(R.id.baby_edit_save_btn);
mSave.setBackgroundResource(Utils.getResourcesId(
MyApplication.getAppContext(), "save_selector", "drawable"));
mBaby_edit = (ImageView) mPopuwidow_relayout
.findViewById(R.id.bb_edit_btn);
mBaby_edit.setBackgroundResource(Utils.getResourcesId(
MyApplication.getAppContext(), "edit_selector", "drawable"));
if (!isEdit) {
mFirst_relayout.setVisibility(View.VISIBLE);
mSecand_edit_relayout.setVisibility(View.GONE);
mSave.setVisibility(View.GONE);
mPopuWindow_bg.setBackgroundResource(Utils.getResourcesId(
MyApplication.getAppContext(), "zz_bbinfo_bg", "drawable"));
mBaby_edit.setVisibility(View.VISIBLE);
mBb_nicheng = (TextView) mPopuwidow_relayout.findViewById(R.id.babymingzi);
mBb_nicheng.setTypeface(mTypeface);
mBb_shengri = (TextView) mPopuwidow_relayout.findViewById(R.id.babyshengri);
mBb_shengri.setTypeface(mTypeface);
mBabyTete = (ImageView) mPopuwidow_relayout.findViewById(R.id.bb_touxiang);
mBaby_name = (TextView) mPopuwidow_relayout.findViewById(R.id.baby_name);
mBaby_sex = (TextView) mPopuwidow_relayout.findViewById(R.id.baby_sex);
mBaby_name.setTypeface(mTypeface);
mBaby_sex.setTypeface(mTypeface);
mBaby_fyear = (TextView) mPopuwidow_relayout.findViewById(R.id.baby_brithday_year);
mBaby_fyear.setTypeface(mTypeface);
if (LoginState.getInstance().isLogin()) {
if (mBabyinfo != null) {
ImageLoader imageLoader = ImageLoader.getInstance(1, Type.LIFO);
String photoUrl = "";
photoUrl = mBabyinfo.getString(Utils.USER_SHARD_PHOTO_KEY,"");
if (photoUrl != null && !TextUtils.isEmpty(photoUrl) && mBabyTete != null) {
imageLoader.loadImage(photoUrl, mBabyTete, true, false);
}
int sexIndex = mBabyinfo.getInt(Utils.USER_SHARD_SEX_KEY, -1);
if (mBaby_sex != null) {
if (sexIndex == 1) {
mBaby_sex.setText(R.string.babyinfo_man);
} else if (sexIndex == 0) {
mBaby_sex.setText(R.string.babyinfo_girl);
} else {
mBaby_sex.setText("");
}
}
if (mBaby_name != null) {
mBaby_name.setText(mBabyinfo.getString(
Utils.USER_SHARD_USERNAME_KEY, ""));
}
String birthdayTimestamp = mBabyinfo.getString(
Utils.USER_SHARD_BIRTHDAY_KEY, "");
if (birthdayTimestamp != null
&& !TextUtils.isEmpty(birthdayTimestamp)) {
String birthday = Utils.timeStamp2Date(
birthdayTimestamp,
Utils.USER_BIRTHDAY_TIME_FORMAT);
if (mBaby_fyear != null) {
mBaby_fyear.setText(birthday);
}
}
}
} else {
mBabyTete.setImageResource(R.drawable.app_default_photo);
if (mBaby_name != null) {
mBaby_name.setText(getString(R.string.default_username));
}
if (mBaby_fyear != null) {
mBaby_fyear.setText(getString(R.string.default_birthday));
}
int defaultSexIndex = (Integer
.parseInt(getString(R.string.default_sex)));
if (mBaby_sex != null) {
if (defaultSexIndex == 1) {
mBaby_sex.setText(R.string.babyinfo_man);
} else if (defaultSexIndex == 0) {
mBaby_sex.setText(R.string.babyinfo_girl);
} else {
mBaby_sex.setText("");
}
}
}
}
mCancel_edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playSimpleSound(CLICK_SOUND_KEY);
if (mEditInformation.isShowing()) {
mEditInformation.dismiss();
mEditInformation = null;
}
hideAllDateWheelView();
}
});
mBaby_edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
playSimpleSound(CLICK_SOUND_KEY);
if (LoginState.getInstance().isLogin()) {
if (mBabyinfo != null) {
showEditbabyinfo();
}
} else {
if (mEditInformation.isShowing()) {
mEditInformation.dismiss();
mEditInformation = null;
}
Utils.showToastMessage(MyApplication.getAppContext(),
getString(R.string.please_login_first));
}
}
});
}
private void showEditbabyinfo() {
mFirst_relayout.setVisibility(View.GONE);
mSecand_edit_relayout.setVisibility(View.VISIBLE);
mSave.setVisibility(View.VISIBLE);
mBaby_edit.setVisibility(View.GONE);
mPopuWindow_bg.setBackgroundResource(Utils.getResourcesId(
MyApplication.getAppContext(), "zz_bbinfo_edit_bg", "drawable"));
mBb_nicheng_edit = (TextView) mPopuwidow_relayout
.findViewById(R.id.baby_edit_mingzi);
//String niCheng = (String) mBb_nicheng_edit.getText();
mBb_nicheng_edit.setTypeface(mTypeface);
mBb_shengri_edit = (TextView) mPopuwidow_relayout
.findViewById(R.id.baby_edit_shengri);
mBb_shengri_edit.setTypeface(mTypeface);
mBoy_tv = (TextView) mPopuwidow_relayout.findViewById(R.id.baby_boy_tv);
mBoy_tv.setTypeface(mTypeface);
mGirl_tv = (TextView) mPopuwidow_relayout.findViewById(R.id.baby_girl_tv);
mGirl_tv.setTypeface(mTypeface);
mRaioGroup = (RadioGroup) mPopuwidow_relayout
.findViewById(R.id.baby_selector_sex_radiogroup);
mBoy_radiobtn = (RadioButton) mPopuwidow_relayout
.findViewById(R.id.baby_boy_radiobtn);
mGirl_radiobtn = (RadioButton) mPopuwidow_relayout
.findViewById(R.id.baby_girl_radiobtn);
if (mBabyinfo.getInt("user_sex", 0) == 1) {
mBoy_radiobtn.setChecked(true);
} else {
mGirl_radiobtn.setChecked(true);
}
mBaby_year = (TextView) mPopuwidow_relayout
.findViewById(R.id.baby_edit_brithday_year_text);
mBaby_year.setTypeface(mTypeface);
// if (!mBabyinfo.getString("babyyear", "").isEmpty()) {
// mBaby_year.setText(mBabyinfo.getString("babyyear", ""));
// }
mBaby_month = (TextView) mPopuwidow_relayout
.findViewById(R.id.baby_edit_brithday_month_text);
mBaby_month.setTypeface(mTypeface);
// if (!mBabyinfo.getString("babymonth", "").equals("")) {
// mBaby_month.setText(mBabyinfo.getString("babymonth", ""));
// }
mBaby_ri = (TextView) mPopuwidow_relayout
.findViewById(R.id.baby_edit_brithday_ri_text);
mBaby_ri.setTypeface(mTypeface);
// if (!mBabyinfo.getString("babyri", "").equals("")) {
// mBaby_ri.setText(mBabyinfo.getString("babyri", ""));
// }
String birthdayTimestamp = mBabyinfo.getString(
Utils.USER_SHARD_BIRTHDAY_KEY, "");
if (birthdayTimestamp != null && !TextUtils.isEmpty(birthdayTimestamp)) {
String birthday = Utils.timeStamp2Date(birthdayTimestamp,
Utils.USER_BIRTHDAY_TIME_FORMAT);
if (mBaby_year != null && mBaby_month != null && mBaby_ri != null) {
mBaby_year.setText(birthday.substring(0, 4));
mBaby_month.setText(birthday.substring(5, 7));
mBaby_ri.setText(birthday.substring(8, 10));
}
}
mYear = (Button) mPopuwidow_relayout
.findViewById(R.id.baby_edit_year_button);
mMonth = (Button) mPopuwidow_relayout
.findViewById(R.id.baby_edit_month_button);
mRi = (Button) mPopuwidow_relayout
.findViewById(R.id.baby_edit_ri_button);
mBabyYearLayout = (LinearLayout) mPopuwidow_relayout
.findViewById(R.id.baby_edit_brithday_year_linearlyout);
mBabyMonthLayout = (LinearLayout) mPopuwidow_relayout
.findViewById(R.id.baby_edit_brithday_month_linearlyout);
mBabyRiLayout = (LinearLayout) mPopuwidow_relayout
.findViewById(R.id.baby_edit_brithday_ri_linearlyout);
mBabyYearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
playSimpleSound(CLICK_SOUND_KEY);
showYearWheelView();
}
});
mBabyMonthLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
playSimpleSound(CLICK_SOUND_KEY);
showMonthWheelView();
}
});
mBabyRiLayout.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
playSimpleSound(CLICK_SOUND_KEY);
showDayWheelView();
}
});
mBaby_editname = (EditText) mPopuwidow_relayout.findViewById(R.id.baby_edit_name);
mBaby_editname.setTypeface(mTypeface);
mBaby_editname.setText(mBabyinfo.getString("user_name", ""));
mBaby_editname.setSelection(mBaby_editname.getText().length());
mBabyMoren_edite = (ImageView) mPopuwidow_relayout
.findViewById(R.id.bb_moren_touxiang);
String photoUrl=mBabyinfo.getString("user_photo", "");
ImageLoader imageLoader = ImageLoader.getInstance(1, Type.LIFO);
if(LoginState.getInstance().isLogin()){
if(mBabyinfo!=null){
imageLoader.loadImage(photoUrl, mBabyMoren_edite, true,false);
}
}else{
mBabyMoren_edite.setImageResource(R.drawable.app_default_photo);
}
mBabyMoren_edite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playSimpleSound(CLICK_SOUND_KEY);
startActivityForResult(new Intent(MainActivity.this,
ImageNameActivity.class), 500);
}
});
mSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
playSimpleSound(CLICK_SOUND_KEY);
mSave.setClickable(false);
mHandler.sendEmptyMessageDelayed(ANBLE_CLICK_NUMBER, 4000);
hideAllDateWheelView();
mEditPhotoPath = HttpCommon.getPathImage(getPackageName())
+ HttpCommon.ORIGINAL_PHOTO_TEMP_NAME;
uploadUserPhoto();
}
});
mRaioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup parent, int id) {
switch (id) {
case R.id.baby_boy_radiobtn:
playSimpleSound(CLICK_SOUND_KEY);
mBabyinfo.edit().putInt(Utils.USER_SHARD_SEX_KEY, 1).commit();
break;
case R.id.baby_girl_radiobtn:
playSimpleSound(CLICK_SOUND_KEY);
mBabyinfo.edit().putInt(Utils.USER_SHARD_SEX_KEY, 0).commit();
break;
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("lee", "MainActivity onActivityResult resultCode == "
+ resultCode + " data == " + data);
// super.onActivityResult(requestCode, resultCode, data);
try {
switch (resultCode) {
case 0:
Bitmap bitmap = HttpCommon.getImageBitmap(getPackageName());
Log.e("lee", "MainActivity onActivityResult bitmap == "+bitmap);
if (bitmap != null) {
if (mBabyMoren_edite != null) {
mBabyMoren_edite.setImageBitmap(bitmap);
}
}
break;
case Utils.LOAD_SYSTEM_IMAGE_REQUEST_CODE:
if (mBabyMoren_edite != null) {
mBabyMoren_edite.setImageBitmap(HttpCommon
.getImageBitmap(getPackageName()));
}
break;
case Utils.LOAD_CUSTOM_IMAGE_REQUEST_CODE:
if (mBabyMoren_edite != null) {
mBabyMoren_edite.setImageBitmap(HttpCommon
.getImageBitmap(getPackageName()));
}
break;
/*default:
if (requestCode == 100) {
if (data == null)
return;
Uri uri = data.getData();
Intent intent = new Intent();
intent.setAction("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// aspectX aspectY 閿熻鍖℃嫹鍙╄皨閿熸枻鎷烽敓锟�
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 閿熻瑁佺》鎷峰浘鐗囬敓鏂ゆ嫹閿燂拷
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("return-data", true);
MainActivity.this.startActivityForResult(intent, 200);
} else if (requestCode == 200) // 閿熸枻鎷烽敓鏂ゆ嫹鍥剧墖
{
if (data == null)
return;
// 閿熺煫纰夋嫹閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓锟�
Bitmap bmap = data.getParcelableExtra("data");
if (mBabyMoren_edite != null) {
mBabyMoren_edite.setImageBitmap(bmap);
}
// mNameAndImageBtn.setImageBitmap(bmap);
HttpCommon.SavaImage(bmap, getPackageName());
} else if (requestCode == 500) // 閿熸枻鎷烽敓鏂ゆ嫹鍥剧墖
{
if (data == null)
return;
// 閿熺煫纰夋嫹閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓锟�
Bitmap bmap = data.getParcelableExtra("data");
if (bmap == null) {
return;
}
if (mBabyMoren_edite != null) {
mBabyMoren_edite.setImageBitmap(bmap);
}
// mNameAndImageBtn.setImageBitmap(bmap);
HttpCommon.SavaImage(bmap, getPackageName());
}
break;*/
}
mUserPhotoChange = true;
}catch (Exception e) {
e.printStackTrace();
Utils.showToastMessage(MyApplication.getAppContext(),
getString(R.string.load_pic_error));
}
}
@Override
public void onResume() {
super.onResume();
mHandler.removeMessages(INIT_DATA);
mHandler.removeMessages(RESUME_DATA);
mHandler.removeMessages(FESTIVAL_BLESS_PUSH);
//加延迟解决卡的问题
mHandler.sendEmptyMessageDelayed(FESTIVAL_BLESS_PUSH, 1 * 1000);
mHandler.sendEmptyMessageDelayed(INIT_DATA, 1 * 1000);
mHandler.sendEmptyMessageDelayed(RESUME_DATA, 5 * 1000);
//打开ECT关闭Android界面中的声音
Intent intent = new Intent("com.android.music.musicservicecommand");
intent.putExtra("command", "stop");
mContext.sendBroadcast(intent);
//刷新小屋中用户信息
refreshUserView();
}
@Override
public void onPause() {
super.onPause();
stopBearAnim();
stopChickenMove();
try {
mHandler.removeMessages(INIT_DATA);
mHandler.removeMessages(RESUME_DATA);
if (mPushMessageReceiver != null) {
unregisterReceiver(mPushMessageReceiver);
}
if (wifiIntentReceiver != null) {
unregisterReceiver(wifiIntentReceiver);
}
if (mIntentReceiver != null) {
unregisterReceiver(mIntentReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onStop() {
/*if (mSoundMap != null) {
mSoundMap.clear();
}*/
/*if (soundPool != null) {
soundPool.release();
}*/
super.onStop();
}
private class YearAdapter extends com.worldchip.bbp.ect.gwwheel.AbstractWheelTextAdapter {
/**
* Constructor
*/
private YearAdapter(Context context) {
super(context, R.layout.country_layout, NO_RESOURCE);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
TextView tv = (TextView) view.findViewById(R.id.flag);
tv.setText(Utils.WHEEL_YEAR_ARR[index]);
if (mYearWheelView != null) {
int position = mYearWheelView.getCurrentItem();
if (index == position) {
tv.setTextColor(Utils.WHEELVIEW_TEXT_COLOR_SELECTED);
} else {
tv.setTextColor(Utils.WHEELVIEW_TEXT_COLOR_NORMAL);
}
}
return view;
}
@Override
public int getItemsCount() {
return Utils.WHEEL_YEAR_ARR.length;
}
@Override
protected CharSequence getItemText(int index) {
int postion = index;
if (index < 0) {
postion = Utils.WHEEL_YEAR_ARR.length + postion;
}
return Utils.WHEEL_YEAR_ARR[postion];
}
}
private class MonthAdapter extends
com.worldchip.bbp.ect.gwwheel.AbstractWheelTextAdapter {
/**
* Constructor
*/
private MonthAdapter(Context context) {
super(context, R.layout.country_layout, NO_RESOURCE);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
TextView tv = (TextView) view.findViewById(R.id.flag);
tv.setText(Utils.WHEEL_MONTH_ARR[index]);
if (mMonthWheelView != null) {
int position = mMonthWheelView.getCurrentItem();
if (index == position) {
tv.setTextColor(Utils.WHEELVIEW_TEXT_COLOR_SELECTED);
} else {
tv.setTextColor(Utils.WHEELVIEW_TEXT_COLOR_NORMAL);
}
}
return view;
}
@Override
public int getItemsCount() {
return Utils.WHEEL_MONTH_ARR.length;
}
@Override
protected CharSequence getItemText(int index) {
int postion = index;
if (index < 0) {
postion = Utils.WHEEL_MONTH_ARR.length + postion;
}
return Utils.WHEEL_MONTH_ARR[postion];
}
}
private class RiAdapter extends
com.worldchip.bbp.ect.gwwheel.AbstractWheelTextAdapter {
/**
* Constructor
*/
private RiAdapter(Context context) {
super(context, R.layout.country_layout, NO_RESOURCE);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
View view = super.getItem(index, cachedView, parent);
TextView tv = (TextView) view.findViewById(R.id.flag);
tv.setText(Utils.WHEEL_DAY_ARR[index]);
if (mDayWheelView != null) {
int position = mDayWheelView.getCurrentItem();
if (index == position) {
tv.setTextColor(Utils.WHEELVIEW_TEXT_COLOR_SELECTED);
} else {
tv.setTextColor(Utils.WHEELVIEW_TEXT_COLOR_NORMAL);
}
}
return view;
}
@Override
public int getItemsCount() {
return Utils.WHEEL_DAY_ARR.length;
}
@Override
protected CharSequence getItemText(int index) {
int postion = index;
if (index < 0) {
postion = Utils.WHEEL_DAY_ARR.length + postion;
}
return Utils.WHEEL_DAY_ARR[postion];
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (soundPool != null) {
soundPool.release();
}
if (mBearDrawableAnim != null) {
mBearDrawableAnim.stopAnimation();
}
try {
if (mLoginReceiver != null) {
unregisterReceiver(mLoginReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
//finish();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// if (operatingAnim != null && mHomeSun != null
// && operatingAnim.hasStarted()) {
// mHomeSun.clearAnimation();
// mHomeSun.startAnimation(operatingAnim);
// }
}
/**
* 閿熸枻鎷烽敓鍙槄鎷烽敓锟�
*/
private void addChicken() {
mChickenViews = new ChickenView[3];
for (int i = 0; i < mChickenViews.length; i++) {
final ChickenView chickenView = new ChickenView(MainActivity.this);
if (i == 0) {
Log.e(TAG, "width"+(int) mResources.getDimension(R.dimen.chicken_one_width));
chickenView.setPosition((int) mResources.getDimension(R.dimen.chicken_one_width),
(int) mResources.getDimension(R.dimen.chicken_one_height),
(int) mResources.getDimension(R.dimen.chicken_one_speed),
(int) mResources.getDimension(R.dimen.chicken_one_fangxiang));
} else if (i == 1) {
chickenView.setPosition((int) mResources.getDimension(R.dimen.chicken_two_width),
(int) mResources.getDimension(R.dimen.chicken_two_height),
(int) mResources.getDimension(R.dimen.chicken_two_speed),
(int) mResources.getDimension(R.dimen.chicken_two_fangxiang));
} else if (i == 2) {
chickenView.setPosition((int) mResources.getDimension(R.dimen.chicken_three_width),
(int) mResources.getDimension(R.dimen.chicken_three_height),
(int) mResources.getDimension(R.dimen.chicken_three_speed),
(int) mResources.getDimension(R.dimen.chicken_three_fangxiang));
}
mChickenViews[i] = chickenView;
chickenView.start();
mHomeMain.addView(chickenView);
}
}
@Override
protected void onStart() {
super.onStart();
HttpCommon.hideSystemUI(MainActivity.this, true);
}
private void updateAgeGroupBar(int index) {
for (int i = 0; i < AGE_GROUP_BAR_COUNT; i++) {
if (index == i) {
mAgeGroupBarView[i].setBackgroundDrawable(null);
} else {
mAgeGroupBarView[i].setBackgroundResource(AGR_GROUP_BAR_RES[i]);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mBearDrawableAnim != null) {
mBearDrawableAnim.onTouch(true);
}
break;
case MotionEvent.ACTION_UP:
if (mBearDrawableAnim != null) {
mBearDrawableAnim.onTouch(false);
}
break;
}
return super.onTouchEvent(event);
}
private void runGrassAnim(View view) {
// TODO Auto-generated method stub
BBPawAnimationUtils.runGrassAnimation(view, new MyAnimationListener() {
@Override
public void onAnimationEnd() {
// TODO Auto-generated method stub
Log.e("lee", "runGrassAnim onAnimationEnd -------");
//grassRunning = false;
startActivity(new Intent(MainActivity.this, SettingActivity.class));
overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
}
});
if (mWavesIV != null) {
BBPawAnimationUtils.runWavesDrawableAnim(mWavesIV);
}
}
@Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
/**
* WIFI閿熸枻鎷锋伅閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷�
*/
private BroadcastReceiver wifiIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int level = Math.abs(((WifiManager) getSystemService(WIFI_SERVICE))
.getConnectionInfo().getRssi());
mImageViewWifi.setImageResource(R.drawable.wifi_sel);
mImageViewWifi.setImageLevel(level);
}
};
// 閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷锋伅閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷� 閿熸枻鎷烽敓鏂ゆ嫹閿熸枻鎷烽敓鏂ゆ嫹
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra("status", 0);
int level = intent.getIntExtra("level", 0);
switch (status) {
case BatteryManager.BATTERY_STATUS_UNKNOWN:
mImageViewPower.setImageResource(R.drawable.stat_sys_battery);
mImageViewPower.getDrawable().setLevel(level);
break;
case BatteryManager.BATTERY_STATUS_CHARGING: // 閿熸枻鎷烽敓鏂ゆ嫹閿燂拷
mImageViewPower.setImageResource(R.anim.stata_chongdian);
AnimationDrawable animatinDrawbale = (AnimationDrawable) mImageViewPower.getDrawable();
animatinDrawbale.start();
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING: // 閿熻剼纰夋嫹閿熸枻鎷�
mImageViewPower.setImageResource(R.drawable.stat_sys_battery);
mImageViewPower.getDrawable().setLevel(level);
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING: // 鏈敓鏂ゆ嫹閿燂拷
mImageViewPower.setImageResource(R.drawable.stat_sys_battery);
mImageViewPower.getDrawable().setLevel(level);
break;
case BatteryManager.BATTERY_STATUS_FULL: // 閿熸枻鎷烽敓鏂ゆ嫹閿燂拷
mImageViewPower.setImageResource(R.drawable.state_fulldianliang);
mImageViewPower.getDrawable().setLevel(level);
break;
}
}
};
@Override
public void onGalleryTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mBearDrawableAnim != null) {
mBearDrawableAnim.onTouch(true);
}
break;
case MotionEvent.ACTION_UP:
if (mBearDrawableAnim != null) {
mBearDrawableAnim.onTouch(false);
}
break;
}
}
private class MainPushMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(RECEIVE_PUSH_MESSAGE_ACTION)) {
String messageType = intent.getStringExtra(RECEIVE_PUSH_MESSAGE_TYPE_KEY);
Log.e(TAG, "runyigechinese");
if (messageType.equals(INFORMATION_MAIN_TYPE)
|| messageType.equals(NOTIFY_MSG_MAIN_TYPE)) {
mHandler.sendEmptyMessage(REFRESH_UNREAD_COUNT);
}
}
}
}
private class LoginReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Utils.LOGIN_SECCUSS_ACTION)
|| action.equals(Utils.LOGIN_OUT_ACTICON)) {
updateUserShard();
}
}
}
private void updateUserShard() {
LoginState loginState = LoginState.getInstance();
if (mBabyinfo != null) {
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_USERNAME_KEY,
loginState.getUserName()).commit();
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_BIRTHDAY_KEY,
loginState.getBirthday()).commit();
mBabyinfo.edit()
.putInt(Utils.USER_SHARD_SEX_KEY, loginState.getSex())
.commit();
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_PHOTO_KEY,
loginState.getPhotoUrl()).commit();
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_AGEINDEX_KEY,
String.valueOf(loginState.getAgeIndex())).commit();
Log.d("Wing", "updateUserShard: " + loginState.getUserName() + "++" + loginState.getPhotoUrl());
}
Log.d("Wing", "updateUserShard_mBabyinfo: ");
mHandler.sendEmptyMessage(REFRESH_USER_VIEW);
}
private void refreshUserView() {
if (mBabyinfo != null && LoginState.getInstance().isLogin()) {
String photoUrl = mBabyinfo.getString(Utils.USER_SHARD_PHOTO_KEY, "");
ImageLoader imageLoader = ImageLoader.getInstance(1, Type.LIFO);
if (photoUrl != null && mPhotoView != null) {
imageLoader.loadImage(photoUrl, mPhotoView, true, false);
}
if (mNameTV != null) {
mNameTV.setText(mBabyinfo.getString(Utils.USER_SHARD_USERNAME_KEY, ""));
editor.putString("nick_name", mBabyinfo.getString(Utils.USER_SHARD_USERNAME_KEY,
getString(R.string.default_username))).commit();
}
String birthdayTimeStamp = mBabyinfo.getString(Utils.USER_SHARD_BIRTHDAY_KEY, "");
if (!TextUtils.isEmpty(birthdayTimeStamp)) {
int age = Utils.calculateAge(birthdayTimeStamp);
String[] ageGroups = getResources().getStringArray(
R.array.age_group_arry);
if (age == 0) {
age = 1;
}
if (age > 0) {
mAgeTV.setText(getString(R.string.age_str_format, age));
}
// 判断age修改mAgeSwitchTV
if (age <= 4) {
mAgeSwitchTV.setText(ageGroups[0]);
updateAgeGroupBar(AGE_GROUP_BAR_01);
DataManager.setAgeValue(MainActivity.this, 0);
}
if (age > 4 && age <= 5) {
mAgeSwitchTV.setText(ageGroups[1]);
updateAgeGroupBar(AGE_GROUP_BAR_02);
DataManager.setAgeValue(MainActivity.this, 1);
}
if (age > 5) {
mAgeSwitchTV.setText(ageGroups[2]);
updateAgeGroupBar(AGE_GROUP_BAR_03);
DataManager.setAgeValue(MainActivity.this, 2);
}
}
} else {
mPhotoView.setImageResource(R.drawable.app_default_photo);
if (mNameTV != null) {
mNameTV.setText(getString(R.string.default_username));
}
if (mAgeTV != null) {
mAgeTV.setText(getString(R.string.age_str_format, getString(R.string.default_age)));
}
String[] ageGroups = getResources().getStringArray(
R.array.age_group_arry);
mAgeSwitchTV.setText(ageGroups[DEFAULT_AGE_GROUP_SELECT]);
updateAgeGroupBar(DEFAULT_AGE_GROUP_SELECT);
}
}
private void updateLanguageButton(int index) {
if (Utils.getLanguageInfo(mContext) == Utils.CH_LANGUAGE_INDEX) {
mCh_UK.setBackgroundResource(R.drawable.china_selector);
} else {
mCh_UK.setBackgroundResource(R.drawable.english_selector);
}
}
private void hideAllDateWheelView() {
if (mYearWheelView != null) {
mYearWheelView.setVisibility(View.GONE);
mYearWheelViewShowing = false;
}
if (mMonthWheelView != null) {
mMonthWheelView.setVisibility(View.GONE);
mMonthWheelViewShowing = false;
}
if (mDayWheelView != null) {
mDayWheelView.setVisibility(View.GONE);
mDayWheelViewShowing = false;
}
}
private void showYearWheelView() {
if (mYearWheelView == null) {
mYearWheelView = (WheelView) mPopuwidow_relayout.findViewById(R.id.wheelview_year);
mYearWheelView.setVisibleItems(3);
mYearWheelView.setViewAdapter(new YearAdapter(MainActivity.this));
mYearWheelView.setCyclic(true);
mYearWheelView.setCurrentItem(1);
mYearWheelView.addScrollingListener(new OnWheelScrollListener() {
@Override
public void onScrollingStarted(WheelView wheel) {
}
@Override
public void onScrollingFinished(WheelView wheel) {
// TODO Auto-generated method stub
if (wheel != null) {
int index = wheel.getCurrentItem();
mBaby_year.setText(Utils.WHEEL_YEAR_ARR[index]);
}
}
});
}
if (!mYearWheelViewShowing) {
mYearWheelView.setVisibility(View.VISIBLE);
} else {
mYearWheelView.setVisibility(View.GONE);
}
mYearWheelViewShowing = !mYearWheelViewShowing;
}
private void showMonthWheelView() {
if (mMonthWheelView == null) {
mMonthWheelView = (WheelView) mPopuwidow_relayout.findViewById(R.id.wheelview_month);
mMonthWheelView.setVisibleItems(3);
mMonthWheelView.setViewAdapter(new MonthAdapter(MainActivity.this));
mMonthWheelView.setCyclic(true);
mMonthWheelView.setCurrentItem(1);
mMonthWheelView.addScrollingListener(new OnWheelScrollListener() {
@Override
public void onScrollingStarted(WheelView wheel) {
}
@Override
public void onScrollingFinished(WheelView wheel) {
// TODO Auto-generated method stub
if (wheel != null) {
int index = wheel.getCurrentItem();
mBaby_month.setText(Utils.WHEEL_MONTH_ARR[index]);
}
}
});
}
if (!mMonthWheelViewShowing) {
mMonthWheelView.setVisibility(View.VISIBLE);
} else {
mMonthWheelView.setVisibility(View.GONE);
}
mMonthWheelViewShowing = !mMonthWheelViewShowing;
}
private void showDayWheelView() {
if (mDayWheelView == null) {
mDayWheelView = (WheelView) mPopuwidow_relayout.findViewById(R.id.wheelview_ri);
mDayWheelView.setVisibleItems(3);
mDayWheelView.setViewAdapter(new RiAdapter(MainActivity.this));
mDayWheelView.setCyclic(true);
mDayWheelView.setCurrentItem(1);
mDayWheelView.addScrollingListener(new OnWheelScrollListener() {
@Override
public void onScrollingStarted(WheelView wheel) {
}
@Override
public void onScrollingFinished(WheelView wheel) {
// TODO Auto-generated method stub
if (wheel != null) {
int index = wheel.getCurrentItem();
mBaby_ri.setText(Utils.WHEEL_DAY_ARR[index]);
}
}
});
}
if (!mDayWheelViewShowing) {
mDayWheelView.setVisibility(View.VISIBLE);
} else {
mDayWheelView.setVisibility(View.GONE);
}
mDayWheelViewShowing = !mDayWheelViewShowing;
}
private void playSimpleSound(int key) {
try {
Integer soundIndex = mSoundMap.get(key);
soundPool.play(soundIndex, 1, 1, 0, 0, 1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
public void onStart(String httpTag) {
}
@Override
public void onSuccess(String result, String httpTag) {
Log.e("lee", "onSuccess response == " + result.toString()
+ " ----------->>>" + httpTag);
Message msg = new Message();
Bundle bundle = new Bundle();
msg.what = HTTP_UPDETE_CODE;
msg.arg1 = Configure.SUCCESS;
bundle.putString("httpTag", httpTag);
bundle.putString("result", result);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onFailure(Exception e, String httpTag) {
Log.e("lee", "onFailure response == " + e.toString()
+ " ----------->>>" + httpTag);
Message msg = new Message();
Bundle bundle = new Bundle();
msg.what = HTTP_UPDETE_CODE;
msg.arg1 = Configure.FAILURE;
bundle.putString("httpTag", httpTag);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void onFinish(int result, String httpTag) {
stopProgressDialog();
}
private void handResultMessge(int resultCode, String httpTag, Object result) {
String messageText = "";
Time time = new Time();
time.setToNow();
Log.e("lee", "handResultMessge resultCode == " + resultCode);
if (resultCode == HttpUtils.HTTP_RESULT_CODE_SUCCESS) {
if (httpTag.equals(Configure.HTTP_TAG_UPDATE_BABYINFO)) {
messageText = getString(R.string.update_password_suceecss);
if (result != null) {
UpdateBabyInfo info = (UpdateBabyInfo) result;
if (info != null) {
mFestival.edit().putInt("mbirthdayyear", time.year);
Log.d("TAG_UPDATE_BABYINFO", "mbirthdayyear ---- " + time.year);
LoginState loginState = LoginState.getInstance();
loginState.setUserName(info.getUsername());
loginState.setBirthday(info.getBrithday());
loginState.setPhotoUrl(info.getImagePath());
loginState.setSex(info.getSex());
Log.e("lee", "username" + info.getUsername()
+ " brithday" + info.getBrithday() + " sex"
+ info.getSex());
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_PHOTO_KEY,
info.getImagePath()).commit();
mBabyinfo
.edit()
.putInt(Utils.USER_SHARD_SEX_KEY, info.getSex())
.commit();
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_USERNAME_KEY,
info.getUsername()).commit();
mBabyinfo
.edit()
.putString(Utils.USER_SHARD_BIRTHDAY_KEY,
info.getBrithday()).commit();
refreshUserView();
}
}
if (mEditInformation.isShowing()) {
mEditInformation.dismiss();
mEditInformation = null;
}
}else if (httpTag.equals(Configure.HTTP_TAG_LOGIN)) {
MainActivity.this.sendBroadcast(new Intent(Utils.LOGIN_SECCUSS_ACTION));
if (result != null) {
LoginState loginState = (LoginState) result;
loginState.setLogin(true);
loginState.setAccount(mAccount.getString("account", ""));
}
}
} else {
HttpUtils.handleRequestExcption(resultCode);
}
if (!TextUtils.isEmpty(messageText)) {
Utils.showToastMessage(MyApplication.getAppContext(), messageText);
}
}
private void uploadUserPhoto() {
if (!mUserPhotoChange) {
Message msg = new Message();
msg.what = PHOTO_UPLOAD_COMPLETE;
msg.obj = null;
mHandler.sendMessage(msg);
return;
}
mHandler.sendEmptyMessage(START_PHOTO_UPLOAD);
mUserPhotoChange = false;
if (!HttpUtils.isNetworkConnected(MyApplication.getAppContext())) {
Message msg = new Message();
msg.arg1 = USER_EDIT_RESULT_NOTWORK;
mHandler.sendMessage(msg);
return;
}
Log.e("lee", "upload photoPath == " + mEditPhotoPath);
PictureUploadUtils.doPost(mEditPhotoPath, new HttpResponseCallBack() {
@Override
public void onSuccess(String result, String httpTag) {
// TODO Auto-generated method stub
Log.e("lee", "upload -- onSuccess == " + result);
Message msg = new Message();
msg.what = PHOTO_UPLOAD_COMPLETE;
msg.obj = result;
mHandler.sendMessage(msg);
}
@Override
public void onStart(String httpTag) {
}
@Override
public void onFinish(int result, String httpTag) {
}
@Override
public void onFailure(Exception e, String httpTag) {
// TODO Auto-generated method stub
if (e != null) {
Log.e(TAG, "upload -- onFailure ==>> " + e.toString());
}
Message msg = new Message();
msg.what = PHOTO_UPLOAD_COMPLETE;
mHandler.sendMessage(msg);
}
}, "upload");
}
private void startProgressDialog() {
if (mGlobalProgressDialog == null) {
mGlobalProgressDialog = GlobalProgressDialog.createDialog(this);
}
mGlobalProgressDialog.show();
}
private void stopProgressDialog() {
if (mGlobalProgressDialog != null) {
if (mGlobalProgressDialog.isShowing()) {
mGlobalProgressDialog.dismiss();
}
mGlobalProgressDialog = null;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Log.e(TAG, "-------- onKeyBack------>> ");
return true;
}
return super.onKeyDown(keyCode, event);
}
private void commitUserChange(String userPhotoUrl) {
String cpuSerial = Utils.getCpuSerial(getApplicationContext());
String account = LoginState.getInstance().getAccount();
String name = mBaby_editname.getText().toString().trim();
String brithday_year = mBaby_year.getText().toString();
mBabyinfo.edit().putString("babyyear", brithday_year).commit();
String brithday_month = mBaby_month.getText().toString();
mBabyinfo.edit().putString("babymonth", brithday_month).commit();
String brithday_ri = mBaby_ri.getText().toString();
mBabyinfo.edit().putString("babyri", brithday_ri).commit();
String brithday_date = brithday_year + "-" + brithday_month + "-" + brithday_ri;
LoginState logins = LoginState.getInstance();
String clientKey = logins.getClientKey();
String httpurl = Configure.UPDATE_BABYINFO
.replace("ACCOUNT", account)
.replace("ADMIN", name)
.replace("BRITHDAY", brithday_date)
.replace("IMAGEPATH", userPhotoUrl)
.replace("SEX", String.valueOf(mBabyinfo.getInt(Utils.USER_SHARD_SEX_KEY, 0)))
.replace("DEVICE_ID", cpuSerial)
.replace("CLIENT_KEY", clientKey);
Log.e("lee", "commitUserChange httpurl == " + httpurl);
if (httpurl != null && !TextUtils.isEmpty(httpurl)) {
HttpUtils.doPost(httpurl.trim(), MainActivity.this,
Configure.HTTP_TAG_UPDATE_BABYINFO);
}
}
private void pushFestivalBless() {
int birthdayMonth = 0;
int birthdayDay = 0;
if (LoginState.getInstance().isLogin()) {
if (mBabyinfo != null) {
String birthdayTimestamp = mBabyinfo.getString(
"user_birthday", "");
if (birthdayTimestamp != null && !TextUtils.isEmpty(birthdayTimestamp)) {
Date birthday = new Date(Long.valueOf(birthdayTimestamp));
birthdayMonth = birthday.getMonth() + 1;
birthdayDay = birthday.getDate();
}
}
}
LunarCalendar lunarCalendar = new LunarCalendar();
int lunarYear = lunarCalendar.getYear();
int lunarMonth = lunarCalendar.getMonth();
int lunarDay = lunarCalendar.getDay();
Time time = new Time();
time.setToNow();
int year = time.year;
int month = time.month + 1;
int day = time.monthDay;
int minute = time.minute;
int hour = time.hour;
int sec = time.second;
Intent mIntent = new Intent(MainActivity.this, FestivalActivity.class);
first = mFestival.getBoolean("first", true);
if (first) {
mFestival.edit().putInt("mbirthdayyear", year).commit();
mFestival.edit().putInt("myuandanyear", year).commit();
mFestival.edit().putInt("mchildrendayyear", year).commit();
mFestival.edit().putInt("mlunar_new_yearyear", lunarYear).commit();
mFestival.edit().putInt("mduanwuyear", lunarYear).commit();
mFestival.edit().putBoolean("first", false).commit();
}
if (month == birthdayMonth && day == birthdayDay) {
int y = mFestival.getInt("mbirthdayyear", 0);
if (y == year) {
mFestival.edit().putInt("mbirthdayyear", year + 1).commit();
mIntent.putExtra("flag", 0);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
}
}
if (month == 1 && day == 1 ) {
int y = mFestival.getInt("myuandanyear", 0);
if (y == year) {
mFestival.edit().putInt("myuandanyear", year + 1).commit();
mIntent.putExtra("flag", 1);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
}
}
if (month == 6 && day == 1 ){
int y = mFestival.getInt("mchildrendayyear", 0);
if (y == year) {
mFestival.edit().putInt("mchildrendayyear", year + 1).commit();
mIntent.putExtra("flag", 2);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
}
}
if (lunarMonth == 1 && lunarDay == 1 ) {
int y = mFestival.getInt("mlunar_new_yearyear", 0);
if (y == lunarYear) {
mFestival.edit().putInt("mlunar_new_yearyear", lunarYear + 1).commit();
mIntent.putExtra("flag", 3);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
}
}
if (lunarMonth == 5 && lunarDay == 5) {
int y = mFestival.getInt("mduanwuyear", 0);
if (y == lunarYear) {
mFestival.edit().putInt("mduanwuyear", lunarYear + 1).commit();
mIntent.putExtra("flag", 4);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
}
}
}
} |
package com.cloudinte.modules.xingzhengguanli.dao;
import java.util.List;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.cloudinte.modules.xingzhengguanli.entity.EducationProjectExpendAccording;
/**
* 项目支出立项依据DAO接口
* @author dcl
* @version 2019-12-13
*/
@MyBatisDao
public interface EducationProjectExpendAccordingDao extends CrudDao<EducationProjectExpendAccording> {
long findCount(EducationProjectExpendAccording educationProjectExpendAccording);
void batchInsert(List<EducationProjectExpendAccording> educationProjectExpendAccording);
void batchUpdate(List<EducationProjectExpendAccording> educationProjectExpendAccording);
void batchInsertUpdate(List<EducationProjectExpendAccording> educationProjectExpendAccording);
void disable(EducationProjectExpendAccording educationProjectExpendAccording);
void deleteByIds(EducationProjectExpendAccording educationProjectExpendAccording);
} |
package procedure;
import java.sql.*;
import conectBD.DB_Connection;
/**
* An Example of how works on JDBC with Procedures
* @author pablo
*/
public class QueryClients {
static DB_Connection db_Connection = new DB_Connection();
public static void main(String[] args) {
try {
Connection connection = db_Connection.getConnection();
// we call to our procedure, saved on the database
CallableStatement sentence = connection.prepareCall("{call SHOW_CLIENTS}");
ResultSet rSet = sentence.executeQuery();
while (rSet.next()) {
System.out.println(rSet.getString(1) + ", "+ rSet.getString(2) + ", " + rSet.getString(3));
}
rSet.close();
} catch (SQLException e) {
System.out.println("QueryClient Error: \n" +e.getMessage());
}
}
}
|
package loecraftpack.common.entity;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
public class EntityElectricBlock extends Entity
{
int maxAge;
int age;
public EntityElectricBlock(World par1World) {
super(par1World);
this.setSize(1.2f, 1.2f);
age = 0;
maxAge = 10;//ticks & frames
this.isImmuneToFire = true;
this.invulnerable = true;
}
public int getAge()
{
return age;
}
public int getMaxAge()
{
return maxAge;
}
@Override
public void onUpdate()
{
if (this.age++ >= this.maxAge)
{
this.setDead();
}
}
@Override
public boolean canBeCollidedWith()
{
return false;
}
@Override
public String getTexture()
{
return "/mods/loecraftpack/misc/electricSide.png";
}
public String getTextureSub()
{
return "/mods/loecraftpack/misc/electricBottom.png";
}
@Override
protected void entityInit() {
}
@Override
protected void readEntityFromNBT(NBTTagCompound nbttagcompound){}
@Override
protected void writeEntityToNBT(NBTTagCompound nbttagcompound){}
}
|
package com.siscom.service.model;
import java.util.Date;
import java.util.List;
public class Venda {
private int numVenda;
private Cliente cliente;
private Vendedor vendedor;
private List<ItemVenda> vendaItens;
private int formaPagto;//já criamos o enum FormaPgto
private Date dataVenda;
public int getNumVenda() {
return numVenda;
}
public void setNumVenda(int numVenda) {
this.numVenda = numVenda;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public Vendedor getVendedor() {
return vendedor;
}
public void setVendedor(Vendedor vendedor) {
this.vendedor = vendedor;
}
public List<ItemVenda> getVendaItens() {
return vendaItens;
}
public void setVendaItens(List<ItemVenda> vendaItens) {
this.vendaItens = vendaItens;
}
public int getFormaPagto() {
return formaPagto;
}
public void setFormaPagto(int formaPagto) {
this.formaPagto = formaPagto;
}
public Date getDataVenda() {
return dataVenda;
}
public void setDataVenda(Date dataVenda) {
this.dataVenda = dataVenda;
}
@Override
public String toString() {
return "Venda [numVenda=" + numVenda + ", cliente=" + cliente + ", vendedor=" + vendedor + ", vendaItens="
+ vendaItens + ", formaPagto=" + formaPagto + ", dataVenda=" + dataVenda + "]";
}
public Venda(int numVenda, Cliente cliente, Vendedor vendedor, List<ItemVenda> vendaItens, int formaPagto,
Date dataVenda) {
super();
this.numVenda = numVenda;
this.cliente = cliente;
this.vendedor = vendedor;
this.vendaItens = vendaItens;
this.formaPagto = formaPagto;
this.dataVenda = dataVenda;
}
}
|
/*
* 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 TiraLab.MetaStrat;
/**
* The default metastrategy, that just returns the move it was assigned with.
* returns the naive strategy move without rotating it at all.
* @author ColdFish
*/
public class P0 extends MetaStrategy{
}
|
package it.sparks.posttwitter.mail;
import it.sparks.utilities.logging.LOG;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
public class PostOnTwitter {
public static void main(String args[]) throws TwitterException {
LOG.traceIn();
// The factory instance is re-useable and thread safe.
Twitter twitter = TwitterFactory.getSingleton();
Status status = twitter.updateStatus("creating baeldung API");
LOG.info("Successfully updated the status to [" + status.getText() + "].");
LOG.traceOut();
}
}
|
package com.cbs.edu.jpa.examples.querying.criteria;
import com.cbs.edu.jpa.examples.querying.Employee;
import com.cbs.edu.jpa.examples.querying.criteria.ParamTest.ProductFilter.PriceFilter;
import lombok.Data;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import static java.util.Objects.nonNull;
public class ParamTest {
public static void main(String[] args) throws Exception {
ProductFilter productFilter = new ProductFilter();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.cbs.edu.jpa");
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = cb.createQuery(Employee.class);
Root<Employee> root = criteriaQuery.from(Employee.class);
criteriaQuery
.select(root);
List<Predicate> predicates = new ArrayList<>();
if (nonNull(productFilter)) {
String tittle = productFilter.getTittle();
if (nonNull(tittle)) {
predicates.add(cb.equal(root.get("tittle"), tittle));
}
PriceFilter priceFilter = productFilter.getPriceFilter();
if (nonNull(priceFilter)) {
Integer from = priceFilter.getFrom();
Integer to = priceFilter.getTo();
if (nonNull(from) && nonNull(to)) {
if (to > from) {
predicates.add(cb.between(root.get("price"), from, to));
} else {
throw new Exception();
}
} else {
if (nonNull(from)) {
predicates.add(cb.gt(root.get("price"), from));
}
if (nonNull(to)) {
predicates.add(cb.lt(root.get("price"), to));
}
}
}
criteriaQuery.where(predicates.toArray(new Predicate[]{}));
}
TypedQuery<Employee> query = em.createQuery(criteriaQuery);
List<Employee> resultList = query.getResultList();
System.out.println(resultList);
transaction.commit();
em.close();
emf.close();
}
@Data
static class ProductFilter {
private String tittle;
private PriceFilter priceFilter;
@Data
static class PriceFilter {
private Integer from;
private Integer to;
}
}
}
|
package com.coding4fun.gpa;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import com.coding4fun.adapters.NotesRVadapter;
import com.coding4fun.models.Note;
import com.coding4fun.models.NoteAudio;
import com.coding4fun.models.NotePicture;
import com.coding4fun.models.NoteText;
import com.coding4fun.models.NoteVideo;
import com.coding4fun.others.NotesSQLiteHelper;
import java.util.ArrayList;
import java.util.List;
import static android.app.Activity.RESULT_OK;
/**
* Created by coding4fun on 09-Oct-16.
*/
public class Notebook extends Fragment implements View.OnClickListener, View.OnTouchListener, GestureDetector.OnGestureListener {
RecyclerView rv;
NotesRVadapter adapter;
List<Note> notesList;
View addLL, rvLL;
GestureDetectorCompat gd;
ImageView pic,vid,txt,aud;
boolean flingUP=true, shown = true;
NotesSQLiteHelper sqlHelper;
Menu menu;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.notebook, container, false);
//define views here
rv = (RecyclerView) v.findViewById(R.id.notes_rv);
addLL = v.findViewById(R.id.addLL);
//rvLL = v.findViewById(R.id.rvLL);
pic = (ImageView) v.findViewById(R.id.add_note_picture);
vid = (ImageView) v.findViewById(R.id.add_note_video);
aud = (ImageView) v.findViewById(R.id.add_note_audio);
txt = (ImageView) v.findViewById(R.id.add_note_text);
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//code here
setHasOptionsMenu(true); //assign menu only for this fragment
gd = new GestureDetectorCompat(getContext(),this);
sqlHelper = new NotesSQLiteHelper(getContext());
addLL.setOnTouchListener(this);
aud.setOnClickListener(this);
pic.setOnClickListener(this);
vid.setOnClickListener(this);
txt.setOnClickListener(this);
initRV();
notesList = new ArrayList<>();
/*notesList.add(new NoteText("TEXT NOTE 1","20/10/2016","blaaaaaaaa blaaaaaaa blaaa"));
notesList.add(new NotePicture("PICTURE NOTE 1","22/10/2016","NO PATH - TEST",0));
notesList.add(new NoteAudio("AUDIO NOTE","25/10/2016","",0,0));
notesList.add(new NoteText("TEXT NOTE 2","25/10/2016","blaaaaaaaa aaaa blaaa"));
notesList.add(new NoteText("TEXT NOTE 2","25/10/2016","blaaaaaaaa aaaa blaaa"));*/
adapter = new NotesRVadapter(getContext(), notesList, sqlHelper);
rv.setAdapter(adapter);
new GetNotesTask().execute();
}
private void initRV(){
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setHasFixedSize(true);
DefaultItemAnimator anim = new DefaultItemAnimator();
anim.setAddDuration(500);
anim.setRemoveDuration(500);
rv.setItemAnimator(anim);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu = menu;
inflater.inflate(R.menu.notes_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_new_note:
if(shown) hide(333);
else show(333);
return true;
default:
return false;
}
}
void hide(int duration){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && flingUP) {
float h = addLL.getHeight();
float y = addLL.getY();
ObjectAnimator oa = ObjectAnimator.ofFloat(addLL, "y", y + (h-30));
oa.setDuration(duration);
oa.setInterpolator(new DecelerateInterpolator());
oa.start();
flingUP = false;
shown = false;
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.menu_add));
}
}
void show(int duration){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && !flingUP) {
float h = addLL.getHeight();
float y = addLL.getY();
ObjectAnimator oa = ObjectAnimator.ofFloat(addLL, "y", y - (h-30));
oa.setDuration(duration);
oa.setInterpolator(new DecelerateInterpolator());
oa.start();
flingUP = true;
shown = true;
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.minus));
}
}
@Override
public boolean onDown(MotionEvent motionEvent) {
return true;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
@Override
public void onLongPress(MotionEvent motionEvent) {
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
if (motionEvent1.getY() > motionEvent.getY()) hide(333);
else if(motionEvent1.getY() < motionEvent.getY()) show(333);
return true;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return gd.onTouchEvent(motionEvent);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.add_note_audio:
startActivityForResult(new Intent(getActivity(),RecordNote.class),77);
break;
case R.id.add_note_picture:
//getContext().startActivity(new Intent(getActivity(),PictureNote.class));
startActivityForResult(new Intent(getActivity(),PictureNote.class),88);
break;
case R.id.add_note_video:
startActivityForResult(new Intent(getActivity(),VideoNote.class),66);
break;
case R.id.add_note_text:
//getContext().startActivity(new Intent(getActivity(),TextNote.class));
startActivityForResult(new Intent(getActivity(),TextNote.class),99);
break;
default:
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Toast.makeText(getContext(), "onActivityResult", Toast.LENGTH_SHORT).show();
if(resultCode == RESULT_OK){
//Toast.makeText(getContext(), "OK", Toast.LENGTH_SHORT).show();
Note n = null;
if(requestCode == 99){
n = (NoteText) data.getSerializableExtra("noteObject");
} else if(requestCode == 88){
n = (NotePicture) data.getSerializableExtra("noteObject");
} else if(requestCode == 77){
n = (NoteAudio) data.getSerializableExtra("noteObject");
} else if(requestCode == 66){
n = (NoteVideo) data.getSerializableExtra("noteObject");
}
if(n != null) {
notesList.add(n);
if(notesList.size() == 1) adapter.notifyItemChanged(0);
else {
adapter.notifyItemInserted(notesList.size() - 1);
rv.scrollToPosition(notesList.size() - 1);
}
}
/*switch (requestCode){
case 99:
n = (NoteText) data.getSerializableExtra("noteObject");
notesList.add(n);
adapter.notifyItemInserted(notesList.size()-1);
rv.scrollToPosition(notesList.size()-1);
break;
default:
break;
}*/
}
}
class GetNotesTask extends AsyncTask<Void,Void,Void> {
List<Note> notes = new ArrayList<>();
@Override
protected void onPreExecute() {
super.onPreExecute();
notesList.add(null);
adapter.notifyItemInserted(0);
}
@Override
protected Void doInBackground(Void... voids) {
notes = sqlHelper.getAllNotes();
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
notesList.remove(0);
notesList.addAll(notes);
adapter.notifyDataSetChanged();
}
}
} |
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
public class SuperServer extends Thread {
private int id = 0;
private Socket socket = null;
private ObjectInputStream fromClient = null;
private ObjectOutputStream toClient = null;
public ClientStruct clientStruct;
public SuperServer(int id, Socket socket) {
super("SuperServer");
this.id = id;
this.socket = socket;
try {
fromClient = new ObjectInputStream(socket.getInputStream());
toClient = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
ArkBot.log.WriteLog("SERVER ERROR: Could not establish Object Stream./n" + e);
ArkBotGUI.GUIText("SERVER ERROR: Could not establish Object Stream./n" + e);
e.printStackTrace();
}
}
public void run() {
//Client State Test
try {
ClientStruct tempStruct = (ClientStruct)fromClient.readObject();
ArkBotState ste = tempStruct.getState();
clientStruct = tempStruct;
clientStruct.setState(ste);
ArkBotGUI.GUIText("Pilote:" + ste.piloter.pilot);
//clientStruct = (ClientStruct)fromClient.readObject();
Server.serverList.put(id, clientStruct);
ArkBotGUI.GUIText("Client Username: " + Server.serverList.get(id).getUser());
ArkBotGUI.GUIText("Client IP: " + Server.serverList.get(id).getAddr());
ArkBotGUI.GUIText("Breed State: " + Server.serverList.get(id).getState().breeder.breed);
ArkBotGUI.GUIText("Tame State: " + Server.serverList.get(id).getState().tame.taming);
ArkBotGUI.GUIText("Gather State: " + Server.serverList.get(id).getState().gatherer.gathering);
ArkBotGUI.GUIText("Healer State: " + Server.serverList.get(id).getState().healer.heal);
ArkBotGUI.GUIText("Autopilot State: " + Server.serverList.get(id).getState().piloter.pilot);
ArkBotGUI.GUIText("MeatSplitter State: " + Server.serverList.get(id).getState().splitter.split);
ArkBotGUI.refreshClientText();
} catch (ClassNotFoundException e) {
ArkBot.log.WriteLog("SERVER ERROR: Class not found./n" + e);
ArkBotGUI.GUIText("SERVER ERROR: Class not found./n" + e);
e.printStackTrace();
} catch (IOException e) {
ArkBot.log.WriteLog("SERVER ERROR: Could not recieve client struct./n" + e);
ArkBotGUI.GUIText("SERVER ERROR: Could not recieve client struct./n" + e);
e.printStackTrace();
}
System.out.println(Server.serverList.get(id).getState().connected);
while (Server.serverList.get(id).getState().connected) {
try {
clientStruct = (ClientStruct)fromClient.readObject();
clientStruct.setState(clientStruct.getState());
System.out.println(Server.serverList.get(id).getState().piloter.pilot + " " + clientStruct.getState().piloter.pilot);
// Only update when client changes
if (Server.serverList.get(id).getState() != null && Server.serverList.get(id).getState() != clientStruct.getState()) {
Server.serverList.put(id, clientStruct);
ArkBotGUI.GUIText("Client Username: " + Server.serverList.get(id).getUser());
ArkBotGUI.GUIText("Client IP: " + Server.serverList.get(id).getAddr());
ArkBotGUI.GUIText("Breed State: " + Server.serverList.get(id).getState().breeder.breed);
ArkBotGUI.GUIText("Tame State: " + Server.serverList.get(id).getState().tame.taming);
ArkBotGUI.GUIText("Gather State: " + Server.serverList.get(id).getState().gatherer.gathering);
ArkBotGUI.GUIText("Healer State: " + Server.serverList.get(id).getState().healer.heal);
ArkBotGUI.GUIText("Autopilot State: " + Server.serverList.get(id).getState().piloter.pilot);
ArkBotGUI.GUIText("MeatSplitter State: " + Server.serverList.get(id).getState().splitter.split);
ArkBotGUI.refreshClientText();
}
} catch (ClassNotFoundException e) {
ArkBot.log.WriteLog("SERVER ERROR: Class not found./n" + e);
ArkBotGUI.GUIText("SERVER ERROR: Class not found./n" + e);
e.printStackTrace();
} catch (IOException e) {
ArkBot.log.WriteLog("SERVER ERROR: Could not recieve client struct./n" + e);
ArkBotGUI.GUIText("SERVER ERROR: Could not recieve client struct./n" + e);
e.printStackTrace();
}
}
}
//implement your methods here
}
|
package ru.artur.trello.model;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "board")
public class Board {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@OneToMany(mappedBy = "board", fetch = FetchType.EAGER)
private List<BoardList> lists;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<BoardList> getLists() {
return lists;
}
public void setLists(List<BoardList> lists) {
this.lists = lists;
}
public void addList(BoardList boardList) {
lists.add(boardList);
}
}
|
/**
* <A activity for display content of txt files.>
* * Copyright (C) <2009> <Wang XinFeng,ACC http://androidos.cc/dev>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package cn.itcreator.android.reader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextPaint;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
import java.util.List;
import cn.itcreator.android.reader.domain.BookMark;
import cn.itcreator.android.reader.io.ReadFileRandom;
import cn.itcreator.android.reader.paramter.CR;
import cn.itcreator.android.reader.paramter.Constant;
import cn.itcreator.android.reader.util.BytesEncodingDetect;
import cn.itcreator.android.reader.util.CRDBHelper;
import cn.itcreator.android.reader.util.CopyOfTxtReader;
import cn.itcreator.android.reader.util.DateUtil;
/**
* <p>
* A activity for display content of txt files.
* </p>
*
* @author Wang XinFeng
* @version 1.0
*
*/
public class TxtActivity extends Activity {
/** ???????????w??????????? */
private final int REQUEST_CODE_SET_BAGKGROUD = 10;
/** ??????????????????????? */
private final int REQUEST_CODE_SET_FONT = 11;
/** dialog id */
private final int SAVEBOOKMARKSUCCESS = 11;
private final int SAVEBOOKMARKFAIL = 12;
private CopyOfTxtReader mTxtReader;
private ReadFileRandom mReaderBytes;
private ScrollView mScrollView;
private TextView mTextView;
private LinearLayout mLinearLayout;
private int mScreenWidth, mScreenHeigth;
private static final int CHANGEFONT = Menu.FIRST;
private static final int CHANGEBG = Menu.FIRST + 3;
private static final int SAVEBOOKMARK = Menu.FIRST + 4;
// ???????
private static final int CIRC_SCREEN = Menu.FIRST + 9;
private static final int BACK = Menu.FIRST + 6;
private static final int EXIT = Menu.FIRST + 7;
private static final int ABOUT = Menu.FIRST + 8;
// ?????
private static final int VIEWBOOKMARK = Menu.FIRST + 20;
/** save points when finger press */
private int mRawX = 0, mRawY = 0;
/** save points when the finger release */
private int mCurX = 0, mCurY = 0;
/** ????????????????GB2312 */
private String encoding = "GB3212";
/** ???????????? */
private CRDBHelper mHelper = null;
/** ??????? */
private boolean operateResult = true;
/**
* ????????
*/
private Toast mToast = null;
/** ????????? */
private int mLastPercent = 0;
/** ??????? */
private List<BookMark> mBookMarkList = null;
/** ?????????????? */
private BookMark mBookMark = null;
/** ?????????????????????? */
private int bmlocation = 0;
private final Handler mHandler = new Handler();
private String _mFilePath = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ???????????????????
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
Intent intent = getIntent();
if (intent == null) {
finish();
return;
}
Bundle bundle = intent.getExtras();
if (bundle == null) {
finish();
return;
}
_mFilePath = bundle.getString(Constant.FILE_PATH_KEY);
if (_mFilePath == null || _mFilePath.equals("")) {
finish();
return;
}
setFullScreen();
String tag = "onCreate";
Log.d(tag, "initialize the new Activity");
setContentView(R.layout.reader);
/** the phone component initialization */
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mTextView = (TextView) findViewById(R.id.textContent);
mLinearLayout = (LinearLayout) findViewById(R.id.textLayout);
// ??????????????
loadData();
// ??????
}
private void setFullScreen() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
/**
* ?????????????
*/
private void loadData() {
/** the screen heigth and width */
mScreenHeigth = this.getWindowManager().getDefaultDisplay().getHeight();
mScreenWidth = this.getWindowManager().getDefaultDisplay().getWidth();
/** text size color and background */
mTextView.setTextColor(Color.BLACK);
mTextView.setTextSize(Constant.FONT18);
mHelper = new CRDBHelper(this);
// ???????
if ("".equals(Constant.IMAGE_PATH)) {
mScrollView.setBackgroundResource(R.drawable.defautbg);
} else {
mScrollView.setBackgroundDrawable(Drawable
.createFromPath(Constant.IMAGE_PATH));
}
mReaderBytes = new ReadFileRandom(_mFilePath);
byte[] encodings = new byte[400];
mReaderBytes.readBytes(encodings);
mReaderBytes.close();
/** ???????????????? */
BytesEncodingDetect be = new BytesEncodingDetect();
this.encoding = BytesEncodingDetect.nicename[be
.detectEncoding(encodings)];
/** ?????????????? */
/** load the attribute for font */
TextPaint tp = mTextView.getPaint();
CR.fontHeight = mTextView.getLineHeight();
/** Ascii char width */
CR.upperAsciiWidth = (int) tp.measureText(Constant.UPPERASCII);
CR.lowerAsciiWidth = (int) tp.measureText(Constant.LOWERASCII);
/** Chinese char width */
CR.ChineseFontWidth = (int) tp.measureText(Constant.CHINESE
.toCharArray(), 0, 1);
Log.d("onCreateDialog CR.FontHeight:", "" + CR.fontHeight);
Log.d("onCreateDialog CR.AsciiWidth:", "" + CR.upperAsciiWidth);
Log.d("onCreateDialog CR.FontWidth:", "" + CR.ChineseFontWidth);
mTxtReader = new CopyOfTxtReader(mTextView, this, _mFilePath,
mScreenWidth, mScreenHeigth, encoding);
this.setTitle(_mFilePath + "-" + getString(R.string.app_name));
mScrollView.setOnKeyListener(mUpOrDown);
mScrollView.setOnTouchListener(mTouchListener);
showToast();
}
private OnKeyListener mUpOrDown = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (0 == mTxtReader.getFileLength()) {
return false;
}
/** scroll to down */
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
mScrollView.scrollTo(0, CR.fontHeight);
if (null != mTxtReader)
mTxtReader.displayNextToScreen(1);
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
mHandler.post(mScrollToBottom);
return true;
}
/** scroll to up */
if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
mScrollView.scrollTo(0, 0);
if (null != mTxtReader)
mTxtReader.displayPreToScreen(1);
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
return true;
}
/** page up */
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (null != mTxtReader)
mTxtReader.displayPreToScreen(15);
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
return true;
}
/** page down */
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
if (null != mTxtReader)
mTxtReader.displayNextToScreen(15);
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
};
private Runnable mScrollToBottom = new Runnable() {
public void run() {
int off = mLinearLayout.getMeasuredHeight()
- mScrollView.getHeight();
if (off > 0) {
mScrollView.scrollTo(0, off);
}
}
};
private OnTouchListener mTouchListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (0 == mTxtReader.getFileLength()) {
return false;
}
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mRawX = (int) event.getX();
mRawY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurX = (int) event.getX();
mCurY = (int) event.getY();
/** get the distance when move */
int upDownDistancey = mCurY - mRawY;
if (upDownDistancey < 0) {
mTxtReader.displayNextToScreen(Math.abs(upDownDistancey
/ (CR.fontHeight)));
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
mHandler.post(mScrollToBottom);
}
if (upDownDistancey > 0) {
mTxtReader
.displayPreToScreen((upDownDistancey / (CR.fontHeight)));
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
mScrollView.scrollTo(0, 0);
}
break;
case MotionEvent.ACTION_UP:
// page down and up
int leftRightDistancey = mCurX - mRawX;
if (leftRightDistancey < -50) {// ??????????????????????????????50px????????
mTxtReader.displayPreToScreen(10);
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
mScrollView.scrollTo(0, 0);
}
if (leftRightDistancey > 50) {
mTxtReader.displayNextToScreen(10);
showToast();
// Toast.makeText(CopyOfReaderCanvas.this,
// mTxtReader.getPercent()+Constant.PERCENTCHAR,
// Toast.LENGTH_SHORT).show();
mHandler.post(mScrollToBottom);
}
}
return true;
}
};
protected void onStop() {
super.onStop();
String tag = "onStop";
Log.d(tag, "stop the activity...");
if (mHelper != null) {
mHelper.close();
}
if (mTxtReader != null) {
mTxtReader.close();
}
}
protected void onDestroy() {
super.onDestroy();
String tag = "onDestroy";
Log.d(tag, "destroy the activity...");
if (mHelper != null) {
mHelper.close();
mHelper = null;
}
if (mTxtReader != null) {
mTxtReader.close();
mTxtReader = null;
}
}
protected void onPause() {
super.onPause();
String tag = "onPause";
Log.d(tag, "pause the activity...");
if (mHelper != null) {
mHelper.close();
}
if (mTxtReader != null) {
mTxtReader.close();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(1, CHANGEFONT, 0, R.string.changefont).setShortcut('3', 'a')
.setIcon(R.drawable.setfont);
menu.add(1, CHANGEBG, 1, R.string.changebg).setShortcut('3', 'c')
.setIcon(R.drawable.setbackgroud);
menu.add(2, SAVEBOOKMARK, 2, R.string.savebookmark).setShortcut('3',
'd').setIcon(R.drawable.addbookmark);
menu.add(2, VIEWBOOKMARK, 3, R.string.viewbookmark).setShortcut('3',
'q').setIcon(R.drawable.viewbookmark);
// ?????????
menu.add(2, CIRC_SCREEN, 3, R.string.circumgyrate)
.setShortcut('3', 'c').setIcon(R.drawable.circscreen);
menu.add(3, BACK, 5, R.string.back).setShortcut('3', 'x').setIcon(
R.drawable.uponelevel);
menu.add(3, EXIT, 6, R.string.exit).setShortcut('3', 'e').setIcon(
R.drawable.close);
menu.add(3, ABOUT, 7, R.string.about).setShortcut('3', 'o').setIcon(
android.R.drawable.star_big_on);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case CHANGEFONT:// change text size
// ???????????
Intent ifs = new Intent(getApplicationContext(),
FontSetActivity.class);
startActivityForResult(ifs, REQUEST_CODE_SET_FONT);
return true;
case CHANGEBG:// change background image
Intent ix = new Intent(getApplicationContext(), ImageBrowser.class);
// startActivity(ix);
startActivityForResult(ix, REQUEST_CODE_SET_BAGKGROUD);
return true;
case CIRC_SCREEN:// ?????????????
circumgyrateScreen();
return true;
case SAVEBOOKMARK:// save book mark
saveBookMarkDialog();
return true;
case VIEWBOOKMARK:// ??????
bookMarkView();
return true;
case EXIT:// exit system
this.finish();
return true;
case BACK:// back to browser file
setProgressBarIndeterminateVisibility(false);
Intent i = new Intent();
i.setClass(getApplicationContext(), FileBrowser.class);
startActivity(i);
setProgressBarIndeterminateVisibility(true);
this.finish();
return true;
case ABOUT:// about this software
showDialog(ABOUT);
return true;
default:
return true;
}
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case SAVEBOOKMARKSUCCESS:// save book mark successful
return saveBookMarkSuccess();
case SAVEBOOKMARKFAIL:// save book mark fail
return saveBookMarkFail();
case ABOUT:// about this software
return about();
default:
return null;
}
}
/**
* ??????????view
*
* @return ??????????true???????false
*/
private void saveBookMarkDialog() {
final Dialog d = new Dialog(TxtActivity.this);
d.setTitle(R.string.inputbmname);
d.setContentView(R.layout.bookmark_dialog);
final EditText et = (EditText) d.findViewById(R.id.bmet);
et.setText(mTxtReader.getCurrentLineString());
final int offset = mTxtReader.getCurrentLineOffset();
final Button sure = (Button) d.findViewById(R.id.bmsure);
final Button cancel = (Button) d.findViewById(R.id.bmcancel);
// ???????
sure.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String bmn = et.getText().toString();
if (bmn.length() < 1) {
d.dismiss();
d.show();
} else {
if (bmn.length() > 10) {
bmn.substring(0, 10);
}
BookMark bm = new BookMark();
bm.setBookId(Constant.BOOK_ID_IN_DATABASE);
bm.setMarkName(bmn);
bm.setCurrentOffset(offset);
bm.setSaveTime(DateUtil.dateToString(new Date()));
operateResult = mHelper.addBookMark(bm);
mHelper.close();
mHelper = new CRDBHelper(getApplicationContext());
if (operateResult) {
showDialog(SAVEBOOKMARKSUCCESS);
} else {
showDialog(SAVEBOOKMARKFAIL);
}
d.dismiss();
}
}
});
// ???????
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();
}
});
d.show();
System.gc();
}
/**
* ????????view
*/
private void bookMarkView() {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.bookmarklist);
final Button deletebtn = (Button) d.findViewById(R.id.deletebm);
final Button gobtn = (Button) d.findViewById(R.id.skipbm);
final Button cancelbtn = (Button) d.findViewById(R.id.cancelbm);
d.setTitle(getString(R.string.bookmarklist));
final ListView listv = (ListView) d.findViewById(R.id.bookmarklistview);
mBookMarkList = mHelper.queryAllBookMark(Constant.BOOK_ID_IN_DATABASE);
final ListAdapter listAdapter = new ArrayAdapter<BookMark>(this,
android.R.layout.simple_spinner_item, mBookMarkList);
listv.setAdapter(listAdapter);
listv.setSelection(0);
// ?????????
listv
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long location) {
bmlocation = (int) location;
mBookMark = mBookMarkList.get(bmlocation);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ?????????
deletebtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {// ??????????
String tag = "delete book mark ";
if (mBookMark != null) {
Log.d(tag, "start delete book mark");
boolean b = mHelper.deleteBookMark(mBookMark
.getBookMarkId());
if (b && mBookMarkList.size() > 0) {
mBookMarkList.remove(bmlocation);
listv.setAdapter(listAdapter);
mBookMark = null;
System.gc();
}
}
}
});
// ?????????
gobtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mBookMark != null) {// ??????
mTxtReader.readBufferByOffset(mBookMark.getCurrentOffset());
d.dismiss();
}
}
});
// ?????????
cancelbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
/**
* ???????????
*/
private void showToast() {
int x = mTxtReader.getPercent();
if (x > mLastPercent) {
mLastPercent = x;
mToast = Toast.makeText(TxtActivity.this, mLastPercent
+ Constant.PERCENTCHAR, Toast.LENGTH_SHORT);
mToast.setGravity(0, 0, 0);
mToast.show();
System.gc();
}
}
/**
* ??????????????????
*
* @return ???????????
*/
private Dialog saveBookMarkSuccess() {
return new AlertDialog.Builder(this).setPositiveButton(
getString(R.string.sure),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).setTitle(getString(R.string.saveresult)).setIcon(
R.drawable.success).setMessage(getString(R.string.savesuccess))
.create();
}
/**
* ?????????????????
*
* @return ???????????
*/
private Dialog saveBookMarkFail() {
return new AlertDialog.Builder(this).setPositiveButton(
getString(R.string.sure),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).setTitle(getString(R.string.saveresult)).setIcon(
R.drawable.fail).setMessage(getString(R.string.savefail))
.create();
}
/**
* ????????
*
* @return
*/
private Dialog about() {
return new AlertDialog.Builder(this).setPositiveButton(
getApplicationContext().getString(R.string.sure),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).setTitle(
getApplicationContext().getString(R.string.aboutcoolreader))
.setMessage(
getApplicationContext()
.getString(R.string.ourintroduce)).create();
}
/**
* ??????
*/
private void circumgyrateScreen() {
if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// ???????????????????????
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
/**
* ?????????????????????
*/
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
String tag = "onConfigurationChanged";
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
loadDataWhenCircScreen();
Log.d(tag, "configuration chanaged , land screen");
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
loadDataWhenCircScreen();
Log.d(tag, "configuration chanaged , common screen");
}
if (getResources().getConfiguration().keyboardHidden == Configuration.KEYBOARDHIDDEN_NO) {
// ?????
loadDataWhenCircScreen();
}
if (getResources().getConfiguration().keyboardHidden == Configuration.KEYBOARDHIDDEN_YES) {
// ??????
loadDataWhenCircScreen();
}
}
/**
* ????????????????????????????
*/
private void loadDataWhenCircScreen() {
String tag = "loadDataWhenCircScreen";
// ??????????
mScreenHeigth = this.getWindowManager().getDefaultDisplay().getHeight();
mScreenWidth = this.getWindowManager().getDefaultDisplay().getWidth();
Log.d(tag, "mScreenHeigth : " + mScreenHeigth);
Log.d(tag, "mScreenWidth : " + mScreenWidth);
// ????????????
int offset = mTxtReader.getCurrentLineOffset();
// ???
mTxtReader.close();
// ?????????
mTxtReader = new CopyOfTxtReader(mTextView, this, _mFilePath,
mScreenWidth, mScreenHeigth, encoding);
Log.d(tag, "create new stream for read file");
// ?????
Log.d(tag, "the offset when read file is :" + offset);
mTxtReader.readBufferByOffset(offset);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String tag = "onActivityResult";
Log.d(tag, "go into the activity result...");
if (requestCode == REQUEST_CODE_SET_BAGKGROUD
&& resultCode == RESULT_OK) {// ???????????????????request
// code
mScrollView.setBackgroundDrawable(Drawable
.createFromPath(Constant.IMAGE_PATH));
}
if (requestCode == REQUEST_CODE_SET_FONT && resultCode == RESULT_OK) {// ???????????
TextPaint tp = mTextView.getPaint();
if ((int) (tp.getTextSize()) != CR.textSize) {// ??????????????????????I????????????
tp.setTextSize(CR.textSize);
CR.fontHeight = mTextView.getLineHeight();
/** Ascii char width */
CR.upperAsciiWidth = (int) tp.measureText(Constant.UPPERASCII);
/** Chinese char width */
CR.ChineseFontWidth = (int) tp.measureText(Constant.CHINESE
.toCharArray(), 0, 1);
mTxtReader
.readBufferByOffset(mTxtReader.getCurrentLineOffset());
}
// ???????
if (resultCode == RESULT_OK) {
if (Constant.RED.equals(CR.textColor)) {
mTextView.setTextColor(Color.RED);
}
if (Constant.GRAY.equals(CR.textColor)) {
mTextView.setTextColor(Color.GRAY);
}
if (Constant.YELLOW.equals(CR.textColor)) {
mTextView.setTextColor(Color.YELLOW);
}
if (Constant.GREEN.equals(CR.textColor)) {
mTextView.setTextColor(Color.GREEN);
}
if (Constant.BLUE.equals(CR.textColor)) {
mTextView.setTextColor(Color.BLUE);
}
if (Constant.BLACK.equals(CR.textColor)) {
mTextView.setTextColor(Color.BLACK);
}
if (Constant.WHITE.equals(CR.textColor)) {
mTextView.setTextColor(Color.WHITE);
}
}
}
}
}
|
package com.zareca.spring.formework.annotation;
import java.lang.annotation.*;
/**
* @Auther: ly
* @Date: 2020/12/6 20:35
* @Description:
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ZAAutowired {
String value() default "";
}
|
package org.bk.consumer.controller;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.annotations.MonitorTags;
import org.bk.consumer.domain.Message;
import org.bk.consumer.domain.MessageAcknowledgement;
import org.bk.consumer.feign.PongClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PingController {
@Autowired
// @Qualifier("ribbonPongClient")
@Qualifier("hystrixPongClient")
private PongClient pongClient;
//@RequestMapping(value="/dispatch",method=RequestMethod.POST)
@RequestMapping("/dispatch")
public MessageAcknowledgement sendMessage(@RequestBody Message message) {
/** try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} **/
return this.pongClient.sendMessage(message);
}
}
|
package com.zd.christopher.transaction;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.zd.christopher.bean.Course;
import com.zd.christopher.dao.ICourseDAO;
@Service
public class CourseTransaction extends BaseTransaction<Course> implements ICourseTransaction
{
@Resource
private ICourseDAO courseDAO;
@PostConstruct
public void init()
{
entityClass = Course.class;
}
public Course findByNaturalId(Course entity)
{
return courseDAO.findByNaturalId(entity.getCourseId());
}
public List<Course> findByNaturalIds(Course[] entities)
{
List<String> idList = new ArrayList<String>();
for(Course course : entities)
idList.add(course.getCourseId());
return courseDAO.findByNaturalIds((String[]) idList.toArray());
}
public List<Course> findByNaturalIdsByPage(Course[] entities, Integer count, Integer page)
{
List<String> idList = new ArrayList<String>();
for(Course course : entities)
idList.add(course.getCourseId());
return courseDAO.findByNaturalIdsByPage((String[]) idList.toArray(), count, page);
}
public List<Course> findByNaturalName(Course entity)
{
return courseDAO.findByNaturalName(entity.getCourseName());
}
public List<Course> findByNaturalNameByPage(Course entity, Integer count, Integer page)
{
return courseDAO.findByNaturalNameByPage(entity.getCourseName(), count, page);
}
public List<Course> findByNaturalNames(Course[] entities)
{
List<String> nameList = new ArrayList<String>();
for(Course course : entities)
nameList.add(course.getCourseName());
return courseDAO.findByNaturalNames((String[]) nameList.toArray());
}
public List<Course> findByNaturalNamesByPage(Course[] entities, Integer count, Integer page)
{
List<String> nameList = new ArrayList<String>();
for(Course course : entities)
nameList.add(course.getCourseName());
return courseDAO.findByNaturalNamesByPage((String[]) nameList.toArray(), count, page);
}
}
|
package kr.or.ddit.interview.service;
import java.util.List;
import java.util.Map;
import kr.or.ddit.interview.dao.IInterviewDao;
import kr.or.ddit.successboard.dao.ISuccessBoardDao;
import kr.or.ddit.vo.CalendarVO;
import kr.or.ddit.vo.JoinVO;
import kr.or.ddit.vo.ProjectVO;
import kr.or.ddit.vo.SuccessBoardCommentVO;
import kr.or.ddit.vo.SuccessBoardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class InterviewServiceImpl implements IInterviewService {
// @Transactional(propagation=Propagation.REQUIRED, readOnly=true)
// @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Autowired
private IInterviewDao dao;
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<Map<String, String>> selectNotConfirmApplyList(
Map<String, String> params) throws Exception {
return dao.selectNotConfirmApplyList(params);
}
// ********************************************* JSON ********************************************* //
// 신청자 명단
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<Map<String, String>> selectConfirmApplyList(Map<String, String> params)
throws Exception {
return dao.selectConfirmApplyList(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> infographic(Map<String, String> params)
throws Exception {
return dao.infographic(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int hireMember(Map<String, String> params) throws Exception {
return dao.hireMember(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectMypageDeveloper(Map<String, String> params)
throws Exception {
return dao.selectMypageDeveloper(params);
}
// 면접 캘린더
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<CalendarVO> selectInterviewCalendar(
Map<String, String> params) throws Exception {
return dao.selectInterviewCalendar(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public String insertInterviewCalendar(Map<String, String> params)
throws Exception {
return dao.insertInterviewCalendar(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectMemberInfo(Map<String, String> params)
throws Exception {
return dao.selectMemberInfo(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int modifyInterviewCalendar(Map<String, String> params)
throws Exception {
return dao.modifyInterviewCalendar(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int deleteInterviewCalendar(Map<String, String> params)
throws Exception {
return dao.deleteInterviewCalendar(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectProjectApply(Map<String, String> params)
throws Exception {
return dao.selectProjectApply(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public String insertInterview(Map<String, String> params) throws Exception {
return dao.insertInterview(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectInterview(Map<String, String> params)
throws Exception {
return dao.selectInterview(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int updateInterview(Map<String, String> params) throws Exception {
return dao.updateInterview(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int updateInterviewCalendar(Map<String, String> params)
throws Exception {
return dao.updateInterviewCalendar(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int insertInterviewee(Map<String, String> params) throws Exception {
return dao.insertInterviewee(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int deleteProjectApply(Map<String, String> params) throws Exception {
return dao.deleteProjectApply(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectIntervieweeInfo(Map<String, String> params)
throws Exception {
return dao.selectIntervieweeInfo(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int deleteInterviewee(Map<String, String> params) throws Exception {
return dao.deleteInterviewee(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int insertProjectApply(Map<String, String> params) throws Exception {
return dao.insertProjectApply(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public int selectSuccessProjectCnt(Map<String, String> params)
throws Exception {
return dao.selectSuccessProjectCnt(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public int selectInsertPortfolioCnt(Map<String, String> params)
throws Exception {
return dao.selectInsertPortfolioCnt(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public int selectCareerCnt(Map<String, String> params) throws Exception {
return dao.selectCareerCnt(params);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public List<Map<String, String>> selectAttendInterview(
Map<String, String> params) throws Exception {
return dao.selectAttendInterview(params);
}
@Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
@Override
public int endInterviewSchedule(String id) throws Exception {
return dao.endInterviewSchedule(id);
}
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
@Override
public Map<String, String> selectCalendarInterview(String id)
throws Exception {
return dao.selectCalendarInterview(id);
}
}
|
package lesson6;
public class Main3 {
public static void main(String[] args) {
int[][] numbers = {{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1}};
for(int i = 0; i < numbers.length; i++){
for(int j =0; j <= i; j++){
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
}
|
package com.mmorg29.appointmentscheduler;
import com.mmorg29.dbtools.DBManager;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Formatter;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
/**
*
* @author mam
* Class is used to create secure password hashes and validate user login information.
* Due to database limitations, in particular the size of the password field (40), security is not as strong as it should be.
* Passwords are created using PBKDF2WithHmacSHA1 algorithm from the javax.crypto package.
* All methods are static to allow for use with out creating an instance of this class.
*/
public class SecurePassword {
public static void verifyUserAndPassword(String userName, String enteredPassword) throws InvalidLoginException {
try (DBManager dbManager = new DBManager(); Statement statement = dbManager.getStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM " + DBManager.USER_TABLE + " WHERE userName = '" + userName + "'");) {
//mam Make sure user is still active
if (rs.first() && rs.getBoolean("active")) {
//mam Always set User class data here to prevent requering database from LoginFormController class.
//This is safe here because if login failure occurs user will not have access to main application,
//and data will be set again when user retries login attempt.
User.getInstance().setUserData(rs.getString("userName"), rs.getInt("userId"));
String storedPassword = rs.getString(3);
if(!checkSecurePassword(enteredPassword, storedPassword)){
throw new InvalidLoginException();
}
} else {
throw new InvalidLoginException();
}
} catch (SQLException sqlEx) {
throw new InvalidLoginException();
}
}
public static String makeSecurePassword(String password) {
int iterations = 1000;
byte[] salt = getSalt();
char[] chars = password.toCharArray();
String passwordHash = securePasswordHash(iterations, salt, chars);
String saltString = toHex(salt);
return iterations + ":" + saltString + ":" + passwordHash;
}
private static boolean checkSecurePassword(String enteredPassword, String storedPassword) {
String[] storedPasswordParts = storedPassword.split(":");
//mam stored password was created from another program or method therefore contains only the password itself
//so check if it matches the entered password
if(storedPasswordParts.length == 1) {
return storedPassword.equals(enteredPassword);
}
int isHashed = Integer.parseInt(storedPasswordParts[2]);
if (isHashed == 1) {
int iterations = Integer.parseInt(storedPasswordParts[0]);
byte[] salt = fromHex(storedPasswordParts[1]);
char[] enteredPasswordChars = enteredPassword.toCharArray();
String enteredPasswordHash = securePasswordHash(iterations, salt, enteredPasswordChars);
return (storedPasswordParts[2] + ":" + storedPasswordParts[3]).equals(enteredPasswordHash);
} else {
//mam password was not able to be hashed when saved to DB so just check if it matches the entered password
return storedPasswordParts[3].equals(enteredPassword);
}
}
private static String securePasswordHash(int iterations, byte[] salt, char[] password) {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 64);
try {
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] passHash = secretKeyFactory.generateSecret(spec).getEncoded();
return 1 + ":" + toHex(passHash);
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
//mam 2017-08-10 Just return unsecure password with a 0 indicating no Hash was performed.
String pword = new String(password);
return 0 + ":" + pword;
}
}
private static byte[] getSalt() {
SecureRandom secureRandom = new SecureRandom();
byte[] salt = new byte[8];
secureRandom.nextBytes(salt);
return salt;
}
private static String toHex(byte[] input) {
StringBuilder stringBuilder = new StringBuilder(input.length * 2);
Formatter formatter = new Formatter(stringBuilder);
for (byte b : input) {
formatter.format("%02x", b);
}
return stringBuilder.toString();
}
private static byte[] fromHex(String input) {
byte[] output = new byte[input.length() / 2];
for (int i = 0; i < input.length(); i += 2) {
output[i / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)
+ Character.digit(input.charAt(i + 1), 16));
}
return output;
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.ideabus.contec_sdk.code.c;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.ideabus.contec_sdk.code.a.b;
@SuppressLint({ "NewApi" })
public class a
{
private a() {
}
public static com.ideabus.contec_sdk.code.c.a a() {
return a1.a;
}
public com.ideabus.contec_sdk.code.connect.a a(final Context context, final BluetoothDevice bluetoothDevice, final b b) {
com.ideabus.contec_sdk.code.connect.a a = null;
switch (bluetoothDevice.getType()) {
case 2: {
a = new com.ideabus.contec_sdk.code.connect.a(context, bluetoothDevice, b);
break;
}
}
return a;
}
public com.ideabus.contec_sdk.code.connect.b a(final UsbManager usbManager, final UsbDevice usbDevice, final b b) {
com.ideabus.contec_sdk.code.connect.b a = null;
switch (usbDevice.getProductId()) {
case 650: {
a = new com.ideabus.contec_sdk.code.connect.b(usbManager, usbDevice, b);
break;
}
}
return a;
}
private static class a1
{
private static final com.ideabus.contec_sdk.code.c.a a;
static {
a = new com.ideabus.contec_sdk.code.c.a();
}
}
}
|
/**
*
*/
package com.application.beans;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author Vikalp Patel(VikalpPatelCE)
*
*/
public class AnnouncementPagerHeader implements Parcelable {
private String mTitle;
private String mUnreadCount;
public AnnouncementPagerHeader() {
super();
// TODO Auto-generated constructor stub
}
public AnnouncementPagerHeader(String mTitle, String mUnreadCount) {
super();
this.mTitle = mTitle;
this.mUnreadCount = mUnreadCount;
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getmUnreadCount() {
return mUnreadCount;
}
public void setmUnreadCount(String mUnreadCount) {
this.mUnreadCount = mUnreadCount;
}
protected AnnouncementPagerHeader(Parcel in) {
mTitle = in.readString();
mUnreadCount = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mTitle);
dest.writeString(mUnreadCount);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<AnnouncementPagerHeader> CREATOR = new Parcelable.Creator<AnnouncementPagerHeader>() {
@Override
public AnnouncementPagerHeader createFromParcel(Parcel in) {
return new AnnouncementPagerHeader(in);
}
@Override
public AnnouncementPagerHeader[] newArray(int size) {
return new AnnouncementPagerHeader[size];
}
};
}
|
package com.hb.framework.superhelp.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
/**
*
* 文件工具类
* 负责处理文件的拷贝、上传、下载
* @author h
* @version 1.0
*
*/
public class FileUtil {
/**
* Method 递规创建文件夹
* @param folderPath
* @param targetPath
* @return String
*/
public static String createFolders(String folderPath, String targetPath) {
String txts = targetPath;
try {
String txt = "";
StringTokenizer st = new StringTokenizer(folderPath, "/");
for (int i = 0; st.hasMoreTokens(); i++) {
txt = st.nextToken().trim();
txts = createFolder(txts + "/" + txt);
}
} catch (Exception e) {
e.printStackTrace();
}
return txts;
}
/**
* Method 递规创建文件夹
* @param folderPath
* @return String
*/
private static String createFolder(String folderPath) {
String txt = folderPath;
try {
File file = new File(txt);
txt = folderPath;
if (!file.exists()) {
file.mkdir();
}
file = null;
} catch (Exception e) {
e.printStackTrace();
}
return txt;
}
/**
* 获取文件扩展名
* @param fileName
* @return
*/
public String getExtendFileName(String fileName) {
int i = fileName.lastIndexOf(".");
String extName = "";//文件扩展名
if (i > 0) {
extName = fileName.substring(i + 1).trim().toLowerCase();
}
return extName;
}
/**
* 获取文件名(不含扩展名)
* @param fileName
* @return
*/
public String getMainFileName(String fileName) {
int i = fileName.lastIndexOf(".");
String name = "";
if (i > 0) {
name = fileName.substring(0, i).trim();
}
return name;
}
/**
* 文件拷贝
* @param sourFileName 源文件(含文件和路径)
* @param descFileName 目标文件(含文件和路径)
* @return
*/
public boolean copyFile(String sourFileName, String descFileName) {
File sourFile = new File(sourFileName);
File descFile = new File(descFileName);
if (sourFile.exists()) {
if (descFile.exists()){
descFile.delete();//如果目标文件存在,删除目标文件
}
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(sourFile);
out = new FileOutputStream(descFile);
byte[] bytes = new byte[1024];
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
}
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
try {
if(in!= null){
in.close();
}
if(out!=null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 文件上传
* @param fileObject 要上传的文件对象
* @param uploadTime 上传时间
* @param multipartFile 要上传的文件对象(通过spring mvc模式上传的文件对象,fileObject和multipartFile二选一,其中一个为空)
* @param fileName 要上传的文件名(不含路径,只有文件名称)
* @param fileType 文件类型(person:个人信息附件;image:影像信息附件;archive:档案附件;business:业务附件)
* @param request 请求对象
* @return 保存后的文件目录
*/
public String uploadFile(String filedata, Date uploadTime, MultipartFile multipartFile, String fileName,String fileType,HttpServletRequest request) {
if ((filedata == null && multipartFile == null) || (filedata != null && multipartFile != null)) {
return null;
}
//保存真实路径
String upload_file_dir = request.getSession().getServletContext().getRealPath("/upload_file_dir");
//String upload_file_dir = "../upload_file_dir";//本机系统目录路径
//String upload_file_dir = "../../../../upload_file_dir";//Linux保存根目录路径
upload_file_dir += "/" + fileType;
//获取保存时间(年-月-日),用于创建目录
String date = new SimpleDateFormat("yyyy-MM-dd").format(uploadTime);
//创建目录
upload_file_dir += "/" + date;
System.out.println("保存路径"+upload_file_dir);
File dateDir = new File(upload_file_dir);
if (!dateDir.exists()) {
dateDir.mkdirs();//创建目录(含多级目录)
}
String saveFileName = null;
InputStream is = null;
OutputStream os = null;
try {
if(multipartFile != null){
is = multipartFile.getInputStream();
}else if(filedata != null){
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(filedata);
InputStream sbs = new ByteArrayInputStream(b);
is = sbs;
}
//获取保存时间
String currentTime = new SimpleDateFormat("yyyyMMdd-HH-mm-ss").format(uploadTime);
//构造新的文件名
//String rebuildFileName = currentTime+"_"+CharacterUtils.getRandomInteger(1000) + CharacterUtils.getSuffix(fileName);
String rebuildFileName = currentTime+fileName;
//构造要上传的文件
File toFile = new File(upload_file_dir, rebuildFileName);
os = new FileOutputStream(toFile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
saveFileName = date + "/" + rebuildFileName;
saveFileName = saveFileName.replace('\\', '/');
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
String dir = "upload_file_dir"+ "/" + fileType + "/" + date;
return dir;
}
/**
* 文件上传
* @param fileObject 要上传的文件对象
* @param multipartFile 要上传的文件对象(通过spring mvc模式上传的文件对象,fileObject和multipartFile二选一,其中一个为空)
* @param fileName 要上传的文件名(不含路径,只有文件名称)
* @param fileType 文件类型(archive:档案附件;business:业务附件)
* @param request 请求对象
* @return 保存后的文件名(经过处理的文件名)
*/
public String uploadFile2(File fileObject, FileInputStream fis, String fileName,String fileType,HttpServletRequest request) {
String upload_file_dir = request.getSession().getServletContext().getRealPath("/upload_file_dir");
upload_file_dir += "/" + fileType;
//获取时间(年-月-日),用于创建目录
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//创建目录
upload_file_dir += "/" + date;
File dateDir = new File(upload_file_dir);
if (!dateDir.exists()) {
dateDir.mkdirs();//创建目录(含多级目录)
}
String saveFileName = null;
InputStream is = null;
OutputStream os = null;
try {
if(fis != null){
is = fis;
}else if(fileObject != null){
is = new FileInputStream(fileObject);
}
//获取当前时间
String currentTime = new SimpleDateFormat("yyyyMMdd-HH-mm-ss").format(new Date());
//构造新的文件名
String rebuildFileName = currentTime+"_"+CharacterUtils.getRandomInteger(1000) + CharacterUtils.getSuffix(fileName);
//构造要上传的文件
File toFile = new File(upload_file_dir, rebuildFileName);
os = new FileOutputStream(toFile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
saveFileName = date + "/" + rebuildFileName;
saveFileName = saveFileName.replace('\\', '/');
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return saveFileName;
}
/**
* 文件下载
* @param fileName 文件名称(不含路径,如:说明.txt)
* @param filePath 文件路径(含文件名称,如:d:/2014/说明.txt)
* @param request 请求对象
* @param response 响应对象
*/
@SuppressWarnings("null")
public void download(String fileName,String filePath,InputStream filedata,HttpServletRequest request,HttpServletResponse response){
//文件输入流对象
InputStream inStream = null;
OutputStream os = null;
String type = "application/x-msdownload";
//文件扩展名
String extendName = "."+getExtendFileName(fileName);
//判断是否有后缀名
if (!extendName.equals("")) {
if (extendName.equalsIgnoreCase(".pdf")) {
type = "application/pdf";
} else if (extendName.equalsIgnoreCase(".doc") || extendName.equalsIgnoreCase(".docx")) {
type = "application/x-word";
} else if (extendName.equalsIgnoreCase(".xls") || extendName.equalsIgnoreCase(".xlsx")) {
type = "application/vnd.ms-excel";
} else if (extendName.equalsIgnoreCase(".bmp")) {
type = "image/bmp";
} else if (extendName.equalsIgnoreCase(".gif")) {
type = "image/gif";
} else if (extendName.equalsIgnoreCase(".jpe")|| extendName.equalsIgnoreCase(".jpeg")|| extendName.equalsIgnoreCase(".jpg")) {
type = "image/jpeg";
} else if (extendName.equalsIgnoreCase(".png")) {
type = "image/png";
} else if (extendName.equalsIgnoreCase(".txt")) {
type = "text/plain";
} else if (extendName.equalsIgnoreCase(".wps")) {
type = "application/x-word";
} else {
type = "application/x-msdownload";
}
}
try {
//缓冲区大小
int bufferSize = 1024;
if(filedata!=null){//判断文件是否存在
inStream = filedata;
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
//firefox浏览器
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}else{
if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
//IE浏览器
fileName = URLEncoder.encode(fileName, "UTF-8");
}else{//谷歌浏览器
fileName = URLEncoder.encode(fileName, "UTF-8");
}
}
response.reset();
//设置文件内容类型
response.setContentType(type);
response.setHeader("Location",fileName);
response.setHeader("Cache-Control", "max-age=0" );
//online用于页面打开文件;attachment则下载附件
response.setHeader("Content-Disposition","attachment; filename="+ fileName );
os = response.getOutputStream();
int c;
while((c=inStream.read())!=-1)
{
os.write(c);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inStream != null) {
inStream.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 在线预览文件
* 下载与在线预览的区别是设置不同的响应头时
* online用于页面打开文件;attachment则下载附件
* response.setHeader("Content-Disposition","online; filename=" + fileName);
* @param fileName 文件名称(不含路径,如:说明.txt)
* @param filePath 文件路径(含文件名称,如:d:/2014/说明.txt)
* @param request 请求对象
* @param response 响应对象
*/
public void readOnLine(String fileName,String filePath,HttpServletRequest request,HttpServletResponse response){
if(fileName==null || filePath==null){
return;
}
//文件输入流对象
FileInputStream inStream = null;
OutputStream os = null;
String type = "application/x-msdownload";
//文件扩展名
String extendName = "."+getExtendFileName(fileName);
//判断是否有后缀名
if (!extendName.equals("")) {
if (extendName.equalsIgnoreCase(".pdf")) {
type = "application/pdf";
} else if (extendName.equalsIgnoreCase(".doc") || extendName.equalsIgnoreCase(".docx")) {
type = "application/x-word";
} else if (extendName.equalsIgnoreCase(".xls") || extendName.equalsIgnoreCase(".xlsx")) {
type = "application/vnd.ms-excel";
} else if (extendName.equalsIgnoreCase(".bmp")) {
type = "image/bmp";
} else if (extendName.equalsIgnoreCase(".gif")) {
type = "image/gif";
} else if (extendName.equalsIgnoreCase(".jpe")|| extendName.equalsIgnoreCase(".jpeg")|| extendName.equalsIgnoreCase(".jpg")) {
type = "image/jpeg";
} else if (extendName.equalsIgnoreCase(".png")) {
type = "image/png";
} else if (extendName.equalsIgnoreCase(".txt")) {
type = "text/plain";
} else {
type = "application/x-msdownload";
}
}
try {
//缓冲区大小
int bufferSize = 1024;
File file = new File(filePath);
if(file!=null && file.exists()){//判断文件是否存在
inStream = new FileInputStream(file);
//文件长度
long len = file.length();
if (len == 0) {
len = 1;
}
byte buffer[] = new byte[bufferSize];
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0){
//firefox浏览器
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}else{
if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
//IE浏览器
fileName = URLEncoder.encode(fileName, "UTF-8");
}else{//谷歌浏览器
fileName = URLEncoder.encode(fileName, "UTF-8");
}
}
response.reset();
//设置文件内容类型
response.setContentType(type);
response.setHeader("Location",fileName);
response.setHeader("Cache-Control", "max-age=0" );
//注意:online用于页面打开文件;attachment则下载附件
response.setHeader("Content-Disposition","online; filename=" + fileName);
os = response.getOutputStream();
int k = 0;
while (k < len) {
//已读部分
int redLen = inStream.read(buffer, 0, bufferSize);
k += redLen;
if (redLen == -1) {
os.write(buffer, 0, 1);
k = 1;
} else{
os.write(buffer, 0, redLen);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inStream != null) {
inStream.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 删除文件夹里子文件
* @param foldName 文件夹名称
* @return
*/
public boolean deleteChildFile(String foldName) {
File foldFile = new File(foldName);
File[] fileList = foldFile.listFiles();
try {
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) { // 如果是文件夹,则递归
String str = fileList[i].getPath() + "/" + fileList[i].getName();
deleteFold(str); //递归
} else { //如果是文件
fileList[i].delete();
}
}
//foldFile.delete();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* 删除文件夹
* @param fileName 要删除的文件夹名称
* @return
*/
public boolean deleteFold(String fileName) {
File foldFile = new File(fileName);
File[] fileList = foldFile.listFiles();
try {
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) { // 如果是文件夹,则递归
String str = fileList[i].getPath() + "/" + fileList[i].getName();
deleteFold(str); // 递归
} else { // 如果是文件
fileList[i].delete();
}
}
foldFile.delete();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* 删除文件
*
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
try {
if (file.exists()) {
file.delete();
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
}
|
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-22
* Time: 下午6:53
* To change this template use File | Settings | File Templates.
*/
public class Queue<Item extends Comparable<Item>> {
private Node first;
private Node last;
private int size;
private class Node
{
Item item;
Node next;
}
public Queue()
{
}
public Queue(Queue<Item> other)
{
first = new Node();
Node pointThis = first;
Node pointOther = other.first;
while (pointOther != other.last)
{
pointThis.item = pointOther.item;
pointOther = pointOther.next;
pointThis.next = new Node();
pointThis = pointThis.next;
}
pointThis.item = pointOther.item;
last = pointThis;
size = other.size();
}
public boolean isEmpty()
{
return first == null;
}
public int size()
{
return size;
}
public void enqueue(Item item)
{
Node oldlast = last;
last = new Node();
last.item = item;
size++;
if(isEmpty())
first = last;
else oldlast.next = last;
}
public Item dequeue()
{
Node oldfirst = first;
first = first.next;
if(isEmpty())
{
last = null;
}
size --;
return oldfirst.item;
}
public void delete(int k)
{
int count = 0;
Node point = first;
while(point.next.next != null && count < k - 2)
{
point = point.next;
count++;
}
if(k == 1 && point == first)
first = first.next;
else if(count == k - 2)
point.next = point.next.next;
}
public boolean find(Item item)
{
Node point = first;
while (point!= null)
{
if(point.item.equals(item))
return true;
point = point.next;
}
return false;
}
public void removeAfter(Item item)
{
Node point = first;
while (point!= null)
{
if(point.item.equals(item))
{
point.next = null;
return;
}
point = point.next;
}
}
public void insertAfter(Item item1, Item item2)
{
Node point = first;
while (point!= null)
{
if(point.item.equals(item1))
{
Node newNode = new Node();
newNode.item = item2;
newNode.next = point.next;
point.next = newNode;
return;
}
point = point.next;
}
}
public void remove(Item item)
{
Node point = first;
while(point != null && point.next != null)
{
if(point.next.item.equals(item))
point.next = point.next.next;
else point = point.next;
}
if(first.item.equals(item))
first = first.next;
}
public Item max()
{
Node point = first;
if(isEmpty())
return null;
Item max = first.item;
point = point.next;
while (point != null)
{
if(point.item.compareTo(max) > 0)
max = point.item;
point = point.next;
}
return max;
}
public Item recursiveMax()
{
return recursive(first);
}
private Item recursive(Node start)
{
if(start == null)
return null;
Item max = recursive(start.next);
if(max == null || start.item.compareTo(max) > 0)
return start.item;
else return max;
}
public void print()
{
Node now = first;
while(now != null)
{
StdOut.print(now.item + " ");
now = now.next;
}
StdOut.println();
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.core.diagram.navigator;
import org.eclipse.gmf.runtime.common.ui.services.parser.IParser;
import org.eclipse.gmf.runtime.common.ui.services.parser.ParserOptions;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ITreePathLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.ViewerLabel;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.navigator.ICommonContentExtensionSite;
import org.eclipse.ui.navigator.ICommonLabelProvider;
import org.neuro4j.studio.core.JoinNode;
import org.neuro4j.studio.core.MapperNode;
import org.neuro4j.studio.core.Network;
import org.neuro4j.studio.core.OperatorInput;
import org.neuro4j.studio.core.OperatorOutput;
import org.neuro4j.studio.core.diagram.edit.parts.CallNodeDynamicFlowNameFlowNameEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.CallNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.DecisionNodeCompKeyOperatorDecisionEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.DecisionNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.EndNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.EndNodeNameEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.FollowByRelationNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.FollowByRelationNodeNameEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.JoinNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.LogicNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.LogicNodeNameEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.LoopNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.LoopNodeLabelEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.MapperNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.NetworkEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorInput2EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorInput3EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorInput4EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorInput5EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorInput7EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorInputEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput10EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput2EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput3EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput4EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput5EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput6EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput7EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput8EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutput9EditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutputEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.OperatorOutputNameEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.StartNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.StartNodeNameEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.ViewNodeEditPart;
import org.neuro4j.studio.core.diagram.edit.parts.ViewNodeViewNameDynamicViewNameEditPart;
import org.neuro4j.studio.core.diagram.part.Neuro4jDiagramEditorPlugin;
import org.neuro4j.studio.core.diagram.part.Neuro4jVisualIDRegistry;
import org.neuro4j.studio.core.diagram.providers.Neuro4jElementTypes;
import org.neuro4j.studio.core.diagram.providers.Neuro4jParserProvider;
/**
* @generated
*/
public class Neuro4jNavigatorLabelProvider extends LabelProvider implements
ICommonLabelProvider, ITreePathLabelProvider {
/**
* @generated
*/
static {
Neuro4jDiagramEditorPlugin
.getInstance()
.getImageRegistry()
.put("Navigator?UnknownElement", ImageDescriptor.getMissingImageDescriptor()); //$NON-NLS-1$
Neuro4jDiagramEditorPlugin
.getInstance()
.getImageRegistry()
.put("Navigator?ImageNotFound", ImageDescriptor.getMissingImageDescriptor()); //$NON-NLS-1$
}
/**
* @generated
*/
public void updateLabel(ViewerLabel label, TreePath elementPath) {
Object element = elementPath.getLastSegment();
if (element instanceof Neuro4jNavigatorItem
&& !isOwnView(((Neuro4jNavigatorItem) element).getView())) {
return;
}
label.setText(getText(element));
label.setImage(getImage(element));
}
/**
* @generated
*/
public Image getImage(Object element) {
if (element instanceof Neuro4jNavigatorGroup) {
Neuro4jNavigatorGroup group = (Neuro4jNavigatorGroup) element;
return Neuro4jDiagramEditorPlugin.getInstance().getBundledImage(
group.getIcon());
}
if (element instanceof Neuro4jNavigatorItem) {
Neuro4jNavigatorItem navigatorItem = (Neuro4jNavigatorItem) element;
if (!isOwnView(navigatorItem.getView())) {
return super.getImage(element);
}
return getImage(navigatorItem.getView());
}
return super.getImage(element);
}
/**
* @generated
*/
public Image getImage(View view) {
switch (Neuro4jVisualIDRegistry.getVisualID(view)) {
case FollowByRelationNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?FollowByRelationNode", Neuro4jElementTypes.FollowByRelationNode_2011); //$NON-NLS-1$
case OperatorInput2EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorInput", Neuro4jElementTypes.OperatorInput_3005); //$NON-NLS-1$
case LogicNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?LogicNode", Neuro4jElementTypes.LogicNode_2017); //$NON-NLS-1$
case NetworkEditPart.VISUAL_ID:
return getImage("Navigator?Diagram?http://www.neuro4j.org/neuro2?Network", Neuro4jElementTypes.Network_1000); //$NON-NLS-1$
case JoinNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?JoinNode", Neuro4jElementTypes.JoinNode_2002); //$NON-NLS-1$
case StartNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?StartNode", Neuro4jElementTypes.StartNode_2004); //$NON-NLS-1$
case OperatorOutput7EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3011); //$NON-NLS-1$
case OperatorOutput2EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3001); //$NON-NLS-1$
case ViewNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?ViewNode", Neuro4jElementTypes.ViewNode_2018); //$NON-NLS-1$
case OperatorOutput6EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3010); //$NON-NLS-1$
case OperatorOutput5EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3004); //$NON-NLS-1$
case MapperNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?MapperNode", Neuro4jElementTypes.MapperNode_2010); //$NON-NLS-1$
case OperatorOutputEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_2016); //$NON-NLS-1$
case CallNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?CallNode", Neuro4jElementTypes.CallNode_2008); //$NON-NLS-1$
case LoopNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?LoopNode", Neuro4jElementTypes.LoopNode_2006); //$NON-NLS-1$
case OperatorInput7EditPart.VISUAL_ID:
return getImage("Navigator?Link?http://www.neuro4j.org/neuro2?OperatorInput", Neuro4jElementTypes.OperatorInput_4009); //$NON-NLS-1$
case OperatorInput3EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorInput", Neuro4jElementTypes.OperatorInput_3006); //$NON-NLS-1$
case OperatorOutput10EditPart.VISUAL_ID:
return getImage("Navigator?Link?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_4008); //$NON-NLS-1$
case OperatorInput4EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorInput", Neuro4jElementTypes.OperatorInput_3007); //$NON-NLS-1$
case OperatorOutput9EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3013); //$NON-NLS-1$
case OperatorOutput3EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3002); //$NON-NLS-1$
case OperatorOutput8EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3012); //$NON-NLS-1$
case OperatorOutput4EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorOutput", Neuro4jElementTypes.OperatorOutput_3003); //$NON-NLS-1$
case EndNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?EndNode", Neuro4jElementTypes.EndNode_2005); //$NON-NLS-1$
case OperatorInput5EditPart.VISUAL_ID:
return getImage("Navigator?Node?http://www.neuro4j.org/neuro2?OperatorInput", Neuro4jElementTypes.OperatorInput_3008); //$NON-NLS-1$
case DecisionNodeEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?DecisionNode", Neuro4jElementTypes.DecisionNode_2007); //$NON-NLS-1$
case OperatorInputEditPart.VISUAL_ID:
return getImage("Navigator?TopLevelNode?http://www.neuro4j.org/neuro2?OperatorInput", Neuro4jElementTypes.OperatorInput_2013); //$NON-NLS-1$
}
return getImage("Navigator?UnknownElement", null); //$NON-NLS-1$
}
/**
* @generated
*/
private Image getImage(String key, IElementType elementType) {
ImageRegistry imageRegistry = Neuro4jDiagramEditorPlugin.getInstance()
.getImageRegistry();
Image image = imageRegistry.get(key);
if (image == null && elementType != null
&& Neuro4jElementTypes.isKnownElementType(elementType)) {
image = Neuro4jElementTypes.getImage(elementType);
imageRegistry.put(key, image);
}
if (image == null) {
image = imageRegistry.get("Navigator?ImageNotFound"); //$NON-NLS-1$
imageRegistry.put(key, image);
}
return image;
}
/**
* @generated
*/
public String getText(Object element) {
if (element instanceof Neuro4jNavigatorGroup) {
Neuro4jNavigatorGroup group = (Neuro4jNavigatorGroup) element;
return group.getGroupName();
}
if (element instanceof Neuro4jNavigatorItem) {
Neuro4jNavigatorItem navigatorItem = (Neuro4jNavigatorItem) element;
if (!isOwnView(navigatorItem.getView())) {
return null;
}
return getText(navigatorItem.getView());
}
return super.getText(element);
}
/**
* @generated
*/
public String getText(View view) {
if (view.getElement() != null && view.getElement().eIsProxy()) {
return getUnresolvedDomainElementProxyText(view);
}
switch (Neuro4jVisualIDRegistry.getVisualID(view)) {
case FollowByRelationNodeEditPart.VISUAL_ID:
return getFollowByRelationNode_2011Text(view);
case OperatorInput2EditPart.VISUAL_ID:
return getOperatorInput_3005Text(view);
case LogicNodeEditPart.VISUAL_ID:
return getLogicNode_2017Text(view);
case NetworkEditPart.VISUAL_ID:
return getNetwork_1000Text(view);
case JoinNodeEditPart.VISUAL_ID:
return getJoinNode_2002Text(view);
case StartNodeEditPart.VISUAL_ID:
return getStartNode_2004Text(view);
case OperatorOutput7EditPart.VISUAL_ID:
return getOperatorOutput_3011Text(view);
case OperatorOutput2EditPart.VISUAL_ID:
return getOperatorOutput_3001Text(view);
case ViewNodeEditPart.VISUAL_ID:
return getViewNode_2018Text(view);
case OperatorOutput6EditPart.VISUAL_ID:
return getOperatorOutput_3010Text(view);
case OperatorOutput5EditPart.VISUAL_ID:
return getOperatorOutput_3004Text(view);
case MapperNodeEditPart.VISUAL_ID:
return getMapperNode_2010Text(view);
case OperatorOutputEditPart.VISUAL_ID:
return getOperatorOutput_2016Text(view);
case CallNodeEditPart.VISUAL_ID:
return getCallNode_2008Text(view);
case LoopNodeEditPart.VISUAL_ID:
return getLoopNode_2006Text(view);
case OperatorInput7EditPart.VISUAL_ID:
return getOperatorInput_4009Text(view);
case OperatorInput3EditPart.VISUAL_ID:
return getOperatorInput_3006Text(view);
case OperatorOutput10EditPart.VISUAL_ID:
return getOperatorOutput_4008Text(view);
case OperatorInput4EditPart.VISUAL_ID:
return getOperatorInput_3007Text(view);
case OperatorOutput9EditPart.VISUAL_ID:
return getOperatorOutput_3013Text(view);
case OperatorOutput3EditPart.VISUAL_ID:
return getOperatorOutput_3002Text(view);
case OperatorOutput8EditPart.VISUAL_ID:
return getOperatorOutput_3012Text(view);
case OperatorOutput4EditPart.VISUAL_ID:
return getOperatorOutput_3003Text(view);
case EndNodeEditPart.VISUAL_ID:
return getEndNode_2005Text(view);
case OperatorInput5EditPart.VISUAL_ID:
return getOperatorInput_3008Text(view);
case DecisionNodeEditPart.VISUAL_ID:
return getDecisionNode_2007Text(view);
case OperatorInputEditPart.VISUAL_ID:
return getOperatorInput_2013Text(view);
}
return getUnknownElementText(view);
}
/**
* @generated
*/
private String getOperatorOutput_3001Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3001); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3004Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3004); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3012Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3012); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getDecisionNode_2007Text(View view) {
IParser parser = Neuro4jParserProvider
.getParser(
Neuro4jElementTypes.DecisionNode_2007,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(DecisionNodeCompKeyOperatorDecisionEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5008); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3003Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3003); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorInput_3006Text(View view) {
OperatorInput domainModelElement = (OperatorInput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getId());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3006); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3010Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3010); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getJoinNode_2002Text(View view) {
JoinNode domainModelElement = (JoinNode) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 2002); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getLogicNode_2017Text(View view) {
IParser parser = Neuro4jParserProvider.getParser(
Neuro4jElementTypes.LogicNode_2017,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(LogicNodeNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5005); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3011Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3011); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getEndNode_2005Text(View view) {
IParser parser = Neuro4jParserProvider.getParser(
Neuro4jElementTypes.EndNode_2005,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry.getType(EndNodeNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5002); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getViewNode_2018Text(View view) {
IParser parser = Neuro4jParserProvider
.getParser(
Neuro4jElementTypes.ViewNode_2018,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(ViewNodeViewNameDynamicViewNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5004); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getStartNode_2004Text(View view) {
IParser parser = Neuro4jParserProvider.getParser(
Neuro4jElementTypes.StartNode_2004,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(StartNodeNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5003); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getNetwork_1000Text(View view) {
Network domainModelElement = (Network) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getTitle());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 1000); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorInput_3007Text(View view) {
OperatorInput domainModelElement = (OperatorInput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getId());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3007); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorInput_3008Text(View view) {
OperatorInput domainModelElement = (OperatorInput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getId());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3008); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getLoopNode_2006Text(View view) {
IParser parser = Neuro4jParserProvider.getParser(
Neuro4jElementTypes.LoopNode_2006,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(LoopNodeLabelEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5006); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_2016Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 2016); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorInput_2013Text(View view) {
OperatorInput domainModelElement = (OperatorInput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getId());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 2013); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getMapperNode_2010Text(View view) {
MapperNode domainModelElement = (MapperNode) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 2010); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorInput_4009Text(View view) {
OperatorInput domainModelElement = (OperatorInput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getId());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 4009); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3013Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3013); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_4008Text(View view) {
IParser parser = Neuro4jParserProvider.getParser(
Neuro4jElementTypes.OperatorOutput_4008,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(OperatorOutputNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 6001); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getFollowByRelationNode_2011Text(View view) {
IParser parser = Neuro4jParserProvider.getParser(
Neuro4jElementTypes.FollowByRelationNode_2011, view
.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(FollowByRelationNodeNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5001); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorInput_3005Text(View view) {
OperatorInput domainModelElement = (OperatorInput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getId());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3005); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getOperatorOutput_3002Text(View view) {
OperatorOutput domainModelElement = (OperatorOutput) view.getElement();
if (domainModelElement != null) {
return String.valueOf(domainModelElement.getName());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("No domain element for view with visualID = " + 3002); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getCallNode_2008Text(View view) {
IParser parser = Neuro4jParserProvider
.getParser(
Neuro4jElementTypes.CallNode_2008,
view.getElement() != null ? view.getElement() : view,
Neuro4jVisualIDRegistry
.getType(CallNodeDynamicFlowNameFlowNameEditPart.VISUAL_ID));
if (parser != null) {
return parser.getPrintString(new EObjectAdapter(
view.getElement() != null ? view.getElement() : view),
ParserOptions.NONE.intValue());
} else {
Neuro4jDiagramEditorPlugin.getInstance().logError("Parser was not found for label " + 5007); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
}
/**
* @generated
*/
private String getUnknownElementText(View view) {
return "<UnknownElement Visual_ID = " + view.getType() + ">"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @generated
*/
private String getUnresolvedDomainElementProxyText(View view) {
return "<Unresolved domain element Visual_ID = " + view.getType() + ">"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @generated
*/
public void init(ICommonContentExtensionSite aConfig) {
}
/**
* @generated
*/
public void restoreState(IMemento aMemento) {
}
/**
* @generated
*/
public void saveState(IMemento aMemento) {
}
/**
* @generated
*/
public String getDescription(Object anElement) {
return null;
}
/**
* @generated
*/
private boolean isOwnView(View view) {
return NetworkEditPart.MODEL_ID.equals(Neuro4jVisualIDRegistry
.getModelID(view));
}
}
|
package lang;
public class InnerClassDemo {
public static void main(String[] args) {
OuterClass outerClass = new OuterClass();
System.out.println(outerClass.getOuterField());
System.out.println(outerClass.getInnerClass());
// Look strange, but legal
OuterClass.InnerClass innerClass = outerClass.new InnerClass();
innerClass.publicInnerMethod();
}
}
class OuterClass {
private String outerField;
private InnerClass innerClass;
public OuterClass() {
System.out.println("The same as Android? " + (this == OuterClass.this));
}
public String getOuterField() {
return outerField;
}
public InnerClass getInnerClass() {
return innerClass;
}
class InnerClass {
private void privateInnerMethod() {
System.out.println("private inner method" + outerField);
}
public void publicInnerMethod() {
System.out.println("public inner method");
}
}
} |
package jason.tcpdemo.funcs;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import jason.tcpdemo.R;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jason.tcpdemo.MainActivity;
/**
* Created by Chao on 2018-03-14.
*/
public class
FuncTest extends Activity {
private String TAG = "FuncTest";
public static Context context ;
private Button Y25a1,Y24b1,Y24a1,Y39b1,Y39a1,Y40b1,Y40a1,Y28b1,Y28a1,Y43b1,Y43a1,Y42b1,Y42a1;
private Button Y25a2,Y24b2,Y24a2,Y39b2,Y39a2,Y40b2,Y40a2,Y28b2,Y28a2,Y43b2,Y43a2,Y42b2,Y42a2;
private Button Y45b1,Y45a1,Y41a1,Y29a1,Y50c1,Y44a1;
private Button btnRoalSpeed1;
private TextView textDemotest;
private String strMessage;
private FuncTest.MyBtnClicker myBtnClicker = new FuncTest.MyBtnClicker();
private final MyHandler myHandler = new MyHandler(this);
private MyBroadcastReceiver myBroadcastReceiver = new FuncTest.MyBroadcastReceiver();
ExecutorService exec = Executors.newCachedThreadPool();
@SuppressLint("StaticFieldLeak")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlayout);
context = this;
TabHost tab = (TabHost) findViewById(android.R.id.tabhost);
//初始化TabHost容器
tab.setup();
//在TabHost创建标签,然后设置:标题/图标/标签页布局
tab.addTab(tab.newTabSpec("tab1").setIndicator("超起A" , null).setContent(R.id.tab1));
tab.addTab(tab.newTabSpec("tab2").setIndicator("超起B" , null).setContent(R.id.tab2));
tab.addTab(tab.newTabSpec("tab3").setIndicator("超起其他动作" , null).setContent(R.id.tab3));
bindID();
bindListener();
bindReceiver();
}
private class MyHandler extends android.os.Handler{
private WeakReference<FuncTest> mActivity;
MyHandler(FuncTest activity){
mActivity = new WeakReference<FuncTest>(activity);
}
@Override
public void handleMessage(Message msg) {
if (mActivity != null){
switch (msg.what){
case 1:
//txtRcv.append(msg.obj.toString());
String strShow=msg.obj.toString();
if(strShow.length()<20)
textDemotest.setText("连接成功!");
break;
case 2:
//txtSend.append(msg.obj.toString());
break;
}
}
}
}
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String mAction = intent.getAction();
switch (mAction){
case "tcpClientReceiver":
String msg = intent.getStringExtra("tcpClientReceiver");
Message message = Message.obtain();
message.what = 1;
message.obj = msg;
myHandler.sendMessage(message);
break;
}
}
}
private void bindReceiver(){
IntentFilter intentFilter = new IntentFilter("tcpClientReceiver");
registerReceiver(myBroadcastReceiver,intentFilter);
}
private class MyBtnClicker implements View.OnClickListener{
public void onClick(View view) {
Toast toast=null;
byte[] bytesSend=new byte[7];
bytesSend[0]=(byte)0xfe;
bytesSend[1]=(byte)0x02;
//{(byte)0xfe,(byte)0x02,(byte)0xff,(byte)0xff,(byte)0xff};
switch (view.getId()){
case R.id.btn_tcpClientConn:
Log.i(TAG, "onClick: 开始");
break;
//复位
case R.id.suspeed1:
//SendMessage("suAroalup");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"复位",Toast.LENGTH_LONG);
break;
//超起A
case R.id.Y45b1:
//SendMessage("suAroalup");
bytesSend[2]=(byte)0x80;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y45b1",Toast.LENGTH_LONG);
break;
case R.id.Y45a1:
//SendMessage("suAroaldown");
bytesSend[2]=(byte)0x40;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y45a1",Toast.LENGTH_LONG);
break;
case R.id.Y25a1:
//SendMessage("suAopen");
bytesSend[2]=(byte)0x20;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y25a1",Toast.LENGTH_LONG);
break;
case R.id.Y24b1:
//SendMessage("suAclose");
bytesSend[2]=(byte)0x08;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y24b1",Toast.LENGTH_LONG);
break;
case R.id.Y24a1:
//SendMessage("suAjlstretch");
bytesSend[2]=(byte)0x04;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y24a1",Toast.LENGTH_LONG);
break;
case R.id.Y41a1:
//SendMessage("suAjlretraction");
bytesSend[2]=(byte)0x02;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y41a1",Toast.LENGTH_LONG);
break;
case R.id.Y39b1:
//SendMessage("suAroalup");
bytesSend[2]=(byte)0x01;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y39b1",Toast.LENGTH_LONG);
break;
case R.id.Y39a1:
//SendMessage("suAroaldown");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x80;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y39a1",Toast.LENGTH_LONG);
break;
case R.id.Y40b1:
//SendMessage("suAopen");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x40;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y40b1",Toast.LENGTH_LONG);
break;
case R.id.Y40a1:
//SendMessage("suAclose");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x20;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y40a1",Toast.LENGTH_LONG);
break;
case R.id.Y29a1:
//SendMessage("suAjlstretch");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x10;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y29a1",Toast.LENGTH_LONG);
break;
case R.id.Y28b1:
//SendMessage("suAjlretraction");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x08;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y28b1",Toast.LENGTH_LONG);
break;
case R.id.Y28a1:
//SendMessage("suAjlretraction");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x04;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y28a1",Toast.LENGTH_LONG);
break;
case R.id.Y43b1:
//SendMessage("suBroalup");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x02;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"卷扬B起",Toast.LENGTH_LONG);
break;
case R.id.Y43a1:
//SendMessage("suBroaldown");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x01;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y43a1",Toast.LENGTH_LONG);
break;
case R.id.Y42b1:
//SendMessage("suBopen");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x80;
toast=Toast.makeText(getApplicationContext(),"Y42b1",Toast.LENGTH_LONG);
break;
case R.id.Y42a1:
//SendMessage("suBclose");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x40;
toast=Toast.makeText(getApplicationContext(),"Y42a1",Toast.LENGTH_LONG);
break;
case R.id.Y50c1:
//SendMessage("suBjlstretch");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x20;
toast=Toast.makeText(getApplicationContext(),"Y50c1",Toast.LENGTH_LONG);
break;
case R.id.Y44a1:
//SendMessage("suBjlretraction");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x10;
toast=Toast.makeText(getApplicationContext(),"Y44a1",Toast.LENGTH_LONG);
break;
//超起B
case R.id.Y25a2:
//SendMessage("suRangeUp");
bytesSend[2]=(byte)0x20;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y25a2",Toast.LENGTH_LONG);
break;
case R.id.Y24b2:
//SendMessage("suRangeDown");
bytesSend[2]=(byte)0x08;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y24b2",Toast.LENGTH_LONG);
break;
case R.id.Y24a2:
//SendMessage("suRoalFloat");
bytesSend[2]=(byte)0x04;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y24a2",Toast.LENGTH_LONG);
break;
case R.id.Y39b2:
//SendMessage("sujlLockChoose");
bytesSend[2]=(byte)0x01;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y39b2",Toast.LENGTH_LONG);
break;
case R.id.Y39a2:
//SendMessage("suLockPress");
bytesSend[2]=(byte)0x01;
bytesSend[3]=(byte)0x80;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y39a2",Toast.LENGTH_LONG);
break;
case R.id.Y40b2:
//SendMessage("suRoalDownPress");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x40;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y40b2",Toast.LENGTH_LONG);
break;
case R.id.Y40a2:
//SendMessage("suRangeUp");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x20;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y40a2",Toast.LENGTH_LONG);
break;
case R.id.Y28b2:
//SendMessage("suRangeDown");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x08;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y28b2",Toast.LENGTH_LONG);
break;
case R.id.Y28a2:
//SendMessage("suRoalFloat");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x04;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y28a2",Toast.LENGTH_LONG);
break;
case R.id.Y43b2:
//SendMessage("sujlLockChoose");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x02;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y43b2",Toast.LENGTH_LONG);
break;
case R.id.Y43a2:
//SendMessage("suLockPress");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x01;
bytesSend[4]=(byte)0x00;
toast=Toast.makeText(getApplicationContext(),"Y43a2",Toast.LENGTH_LONG);
break;
case R.id.Y42b2:
//SendMessage("suRoalDownPress");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x80;
toast=Toast.makeText(getApplicationContext(),"Y42b2",Toast.LENGTH_LONG);
break;
case R.id.Y42a2:
//SendMessage("suRoalDownPress");
bytesSend[2]=(byte)0x00;
bytesSend[3]=(byte)0x00;
bytesSend[4]=(byte)0x40;
toast=Toast.makeText(getApplicationContext(),"Y42a2",Toast.LENGTH_LONG);
break;
}
bytesSend[5]=(byte)0x0d;
bytesSend[6]=(byte)0x0a;
SendHexMessage(bytesSend);
showMyToast(toast,1000);
}
}
private void bindID(){
//卷扬速度 btnRoalSpeed1,btnRoalSpeed2,btnRoalSpeed3;
btnRoalSpeed1 = (Button) findViewById(R.id.suspeed1);
//btnsuARoalUP,btnsuARoalDown,btnsuAopen, btnsuAClose,btnsuALockOut,btnsuALockIn;
//Y25a1,Y24b1,Y24a1,
//超起A
Y25a1 = (Button) findViewById(R.id.Y25a1);
Y24b1 = (Button) findViewById(R.id.Y24b1);
Y24a1 = (Button) findViewById(R.id.Y24a1);
// Y39b1,Y39a1,Y40b1,
Y39b1 = (Button) findViewById(R.id.Y39b1);
Y39a1 = (Button) findViewById(R.id.Y39a1);
Y40b1 = (Button) findViewById(R.id.Y40b1);
// Y40a1,Y28b1,Y28a1,
Y40a1 = (Button) findViewById(R.id.Y40a1);
Y28b1 = (Button) findViewById(R.id.Y28b1);
Y28a1 = (Button) findViewById(R.id.Y28a1);
// Y43b1,Y43a1,Y42b1,Y42a1;
Y43b1 = (Button) findViewById(R.id.Y43b1);
Y43a1 = (Button) findViewById(R.id.Y43a1);
Y42b1 = (Button) findViewById(R.id.Y42b1);
Y42a1 = (Button) findViewById(R.id.Y42a1);
//btnsuBRoalUP,btnsuBRoalDown,btnsuBopen,btnsuBClose,btnsuBLockOut,btnsuBLockIn;
//超起B
//Y25a2,Y24b2,Y24a2,
Y25a2 = (Button) findViewById(R.id.Y25a2);
Y24b2 = (Button) findViewById(R.id.Y24b2);
Y24a2 = (Button) findViewById(R.id.Y24a2);
// Y39b2,Y39a2,Y40b2,
Y39b2 = (Button) findViewById(R.id.Y39b2);
Y39a2 = (Button) findViewById(R.id.Y39a2);
Y40b2 = (Button) findViewById(R.id.Y40b2);
// Y40a2,Y28b2,Y28a2,
Y40a2 = (Button) findViewById(R.id.Y40a2);
Y28b2 = (Button) findViewById(R.id.Y28b2);
Y28a2 = (Button) findViewById(R.id.Y28a2);
// Y43b2,Y43a2,Y42b2,Y42a2;
Y43b2 = (Button) findViewById(R.id.Y43b2);
Y43a2 = (Button) findViewById(R.id.Y43a2);
Y42b2 = (Button) findViewById(R.id.Y42b2);
Y42a2 = (Button) findViewById(R.id.Y42a2);
//超起其他动作
//btnsuRangeUp,btnsuRangeDown,btnsuRoalFloat, btnsuLockChoose,btnsuLockPress,btnsuRoalDownPress;
// Y45b1,Y45a1,Y41a1,
// Y29a1,Y50c1,Y44a1;
Y45b1 = (Button) findViewById(R.id.Y45b1);
Y45a1 = (Button) findViewById(R.id.Y45a1);
Y41a1 = (Button) findViewById(R.id.Y41a1);
Y29a1 = (Button) findViewById(R.id.Y29a1);
Y50c1 = (Button) findViewById(R.id.Y50c1);
Y44a1 = (Button) findViewById(R.id.Y44a1);
textDemotest=(TextView)findViewById(R.id.textDemo);
}
private void bindListener(){
// btnStartClient.setOnClickListener(myBtnClicker);
//卷扬速度 btnRoalSpeed1,btnRoalSpeed2,btnRoalSpeed3;
btnRoalSpeed1.setOnClickListener(myBtnClicker);
//btnsuARoalUP,btnsuARoalDown,btnsuAopen, btnsuAClose,btnsuALockOut,btnsuALockIn;
//超起A
Y25a1.setOnClickListener(myBtnClicker);
Y24b1.setOnClickListener(myBtnClicker);
Y24a1.setOnClickListener(myBtnClicker);
Y39b1.setOnClickListener(myBtnClicker);
Y39a1.setOnClickListener(myBtnClicker);
Y40b1.setOnClickListener(myBtnClicker);
Y40a1.setOnClickListener(myBtnClicker);
Y28b1.setOnClickListener(myBtnClicker);
Y28a1.setOnClickListener(myBtnClicker);
Y43b1.setOnClickListener(myBtnClicker);
Y43a1.setOnClickListener(myBtnClicker);
Y42b1.setOnClickListener(myBtnClicker);
Y42a1.setOnClickListener(myBtnClicker);
//btnsuBRoalUP,btnsuBRoalDown,btnsuBopen,btnsuBClose,btnsuBLockOut,btnsuBLockIn;
//Y25a2,Y24b2,Y24a2,
// Y39b2,Y39a2,Y40b2,
//超起B
Y25a2.setOnClickListener(myBtnClicker);
Y24b2.setOnClickListener(myBtnClicker);
Y24a2.setOnClickListener(myBtnClicker);
Y39b2.setOnClickListener(myBtnClicker);
Y39a2.setOnClickListener(myBtnClicker);
Y40b2.setOnClickListener(myBtnClicker);
// Y40a2,Y28b2,Y28a2,
// Y43b2,Y43a2,Y42b2,Y42a2;
Y40a2.setOnClickListener(myBtnClicker);
Y28b2.setOnClickListener(myBtnClicker);
Y28a2.setOnClickListener(myBtnClicker);
Y43b2.setOnClickListener(myBtnClicker);
Y43a2.setOnClickListener(myBtnClicker);
Y42b2.setOnClickListener(myBtnClicker);
Y42a2.setOnClickListener(myBtnClicker);
//超起其他动作
//btnsuRangeUp,btnsuRangeDown,btnsuRoalFloat, btnsuLockChoose,btnsuLockPress,btnsuRoalDownPress;
//Y45b1,Y45a1,Y41a1,
// Y29a1,Y50c1,Y44a1;
Y45b1.setOnClickListener(myBtnClicker);
Y45a1.setOnClickListener(myBtnClicker);
Y41a1.setOnClickListener(myBtnClicker);
Y29a1.setOnClickListener(myBtnClicker);
Y50c1.setOnClickListener(myBtnClicker);
Y44a1.setOnClickListener(myBtnClicker);
}
public void showMyToast(final Toast toast,final int cnt)
{
final Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
toast.show();
}
},0,500);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
toast.cancel();
timer.cancel();
}
},cnt);
}
private void SendMessage(String stringtosend)
{
strMessage=stringtosend;
Message message = Message.obtain();
message.what = 2;
message.obj = stringtosend;
myHandler.sendMessage(message);
exec.execute(new Runnable() {
@Override
public void run() {
MainActivity.tcpClient.send(strMessage);
}
});
}
private void SendHexMessage(byte[] bytestosend)
{
try {
final byte[] bb = bytestosend;
exec.execute(new Runnable() {
@Override
public void run() {
MainActivity.tcpClient.sendHex(bb);
}
});
}
catch (Exception e)
{
textDemotest.setText("连接失败!");
}
}
}
|
package com.yxkj.facexradix.netty.util;
import android.content.Context;
import android.util.Log;
import com.yxdz.commonlib.util.LogUtils;
import com.yxdz.commonlib.util.SPUtils;
import com.yxkj.facexradix.Constants;
import com.yxkj.facexradix.MyApplication;
import com.yxkj.facexradix.netty.Message;
import com.yxkj.facexradix.room.FacexDatabase;
import com.yxkj.facexradix.room.bean.Record;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import io.netty.channel.Channel;
public class ClientUtil {
public static boolean isOnCall = false;
public static String Receiver;
public static String Sender;
private static String TAG = "ClientUtil";
public static AtomicInteger count = new AtomicInteger(0);
public static ConcurrentHashMap<Integer, Message> msgMap = new ConcurrentHashMap<Integer, Message>();
public static int increase() {
return count.incrementAndGet();
}
public static void sendSn(Context context) {
}
/**
* 发送数据
*
* @param msg
* @return
*/
public static Message sendMessage(Message msg) {
Channel channel = ClientMain.getChannel();
if (channel != null && channel.isActive()) {
try {
//发送数据
int id = increase();
msg.setMsgId(id);
for (int i = 0; i < 3; ++i) {
Log.e(TAG, "发送数据:" + msg.toString());
channel.writeAndFlush(msg);
Thread.sleep((1 + i) * 500);
//检查结果是否已返回
if (msgMap.containsKey(id)) {
Message message = msgMap.get(id);
msgMap.clear();
return message;
}
}
} catch (InterruptedException e) {
}
}
return null;
}
// boolean aBoolean = SPUtils.getInstance().getBoolean(Constants.SERVER_CONNECT_STATS);
// if (!aBoolean){
// return msg;
// }
public static Message requestMessage(Message msg) {
Message result = null;
Channel channel = ClientMain.getChannel();
if (channel != null) {
try {
//发送数据
Log.e(TAG, "发送数据:" + msg.toString());
int id = msg.getMsgId();
channel.writeAndFlush(msg);
for (int i = 0; i < 10; i++) {
Thread.sleep(50);
if (msgMap.containsKey(id)) {
result = msgMap.get(id);
msgMap.remove(id);
break;
}
}
} catch (Exception e) {
Log.e(TAG, "异常:" + e.getMessage());
}
}
return result;
}
public static Message requestMessageForRecord(Message msg) {
Channel channel = ClientMain.getChannel();
if (channel != null) {
try {
//发送数据
Log.e(TAG, "发送数据:" + msg.toString());
channel.writeAndFlush(msg);
} catch (Exception e) {
Log.e(TAG, "异常:" + e.getMessage());
}
}
return null;
}
public static void sendMessage(String sendtype, int roomId) {
HashMap<String, Object> map = new HashMap<>();
map.put("sender", Sender);
map.put("receiver", Receiver);
HashMap<String, Object> forward = new HashMap<>();
forward.put("sendtype", sendtype);
forward.put("roomId", roomId);
map.put("forward", forward);
Message message = new Message();
message.setMsgId(increase());
message.setCode(302);
message.setData(map);
Channel channel = ClientMain.getChannel();
if (channel != null) {
channel.writeAndFlush(message);
}
}
public static void sendMessage(String sendtype) {
HashMap<String, Object> map = new HashMap<>();
map.put("sender", Sender);
map.put("receiver", Receiver);
HashMap<String, Object> forward = new HashMap<>();
forward.put("sendtype", sendtype);
map.put("forward", forward);
Message message = new Message();
message.setMsgId(increase());
message.setCode(302);
message.setData(map);
Channel channel = ClientMain.getChannel();
if (channel != null) {
channel.writeAndFlush(message);
}
}
public static void sendEventRecord(int eventCode) {
Message message = new Message();
HashMap<String, Object> map = new HashMap();
map.put("event", eventCode);
map.put("time", System.currentTimeMillis());
message.setMsgId(1);
message.setCode(115);
message.setData(map);
requestMessageForRecord(message);
}
public static void sendOpenRecord(String userId, int openType, int statu, String cardNo) {
new Thread(new Runnable() {
@Override
public void run() {
if (SPUtils.getInstance().getInt(Constants.DEVICE_CTRL_MODE, 0) == 1) {
return;
}
if (SPUtils.getInstance().getBoolean(Constants.SERVER_CONNECT_STATS, false)) {
Message message = new Message();
message.setMsgId(increase());
message.setCode(116);
HashMap<String, Object> map = new HashMap<>();
map.put("userId", userId);
map.put("openTime", System.currentTimeMillis());
// map.put("openType", 40+openType);
map.put("openType", openType);
map.put("statu", statu);
map.put("card", cardNo);
message.setData(map);
LogUtils.d(TAG, "发送回复:" + message.toString());
requestMessage(message);
} else {
Record record = new Record();
record.setCard(cardNo);
record.setUserId(userId);
record.setOpenTime(System.currentTimeMillis());
record.setStatu(statu);
record.setOpenType(openType);
FacexDatabase.getInstance(MyApplication.getAppContext()).getRecord().insert(record);
}
}
}).start();
}
static void sendOpenRecord(Record record) {
Message message = new Message();
HashMap<String, Object> map = new HashMap();
map.put("userId", record.getUserId());
map.put("openTime", record.getOpenTime());
map.put("openType", record.getOpenType());
map.put("statu", record.getStatu());
map.put("card", record.getCard());
message.setMsgId(increase());
message.setCode(116);
message.setData(map);
Channel channel = ClientMain.getChannel();
if (channel != null) {
channel.writeAndFlush(message);
}
}
}
|
/*
* 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 org.sales.view;
import java.util.*;
import javax.swing.table.DefaultTableModel;//for default table models
import org.sales.controller.ProductDAO;
import org.sales.controller.SalesDAO;
import org.sales.util.Global;
import org.sales.model.*;
public class SellProduct extends javax.swing.JInternalFrame {
/**
* Creates new form SellProduct
*/ DefaultTableModel model;
public SellProduct() {
initComponents();
jLabel_CurrentDate.setText(new Date().toString());
jLabel_User.setText(Global.user);
//model
model=new DefaultTableModel(null,new String []{"Id","Name","Price","Qty","Total"});
jTable_Sales.setModel(model);
}
//for grant Total
public void calculateTotal()
{
int rows =jTable_Sales.getRowCount();
double gTotal=0.0;
for(int i=0;i<rows;i++)
{
double total=Double.parseDouble(jTable_Sales.getValueAt(i,4).toString());
gTotal+=total;
}
jLabel_Total.setText(gTotal+" ");
}
private void printBill()
{
int count =jTable_Sales.getRowCount();
String str="Nameste Super market\n Newroad,Kathmandu\n";
for(int i=0;i<count;i++)
{
str+=jTable_Sales.getValueAt(i,0).toString()+" ";
str+=jTable_Sales.getValueAt(i,1).toString()+" ";
str+=jTable_Sales.getValueAt(i,2).toString()+" ";
str+=jTable_Sales.getValueAt(i,3).toString()+" ";
str+=jTable_Sales.getValueAt(i,4).toString()+" \n";
}
str+="Grand Total: "+jLabel_Total.getText();
str+="\n Thank You For ViSiting!!!";
BillPrint ob=new BillPrint();
ob.jTextArea_Bill.setLineWrap(true);
ob.jTextArea_Bill.setText(str);
try
{
ob.jTextArea_Bill.print();
}catch(Exception ex)
{
System.out.println(ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel_CurrentDate = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jTextField_Id = new javax.swing.JTextField();
jButton_SavePrint = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable_Sales = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jLabel_Total = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel_User = new javax.swing.JLabel();
jButton_Delete1 = new javax.swing.JButton();
setClosable(true);
jLabel_CurrentDate.setText("Current Date");
jLabel1.setText("Id");
jTextField_Id.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField_IdActionPerformed(evt);
}
});
jButton_SavePrint.setText("Save & Print");
jButton_SavePrint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_SavePrintActionPerformed(evt);
}
});
jTable_Sales.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(jTable_Sales);
jButton1.setText("Grand Total");
jLabel_Total.setText("Total");
jLabel2.setText("Logged in as :");
jLabel_User.setText("User");
jButton_Delete1.setText("Delete");
jButton_Delete1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_Delete1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel_CurrentDate)
.addGap(72, 72, 72))
.addGroup(layout.createSequentialGroup()
.addGap(97, 97, 97)
.addComponent(jButton1)
.addGap(65, 65, 65)
.addComponent(jLabel_Total, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel_User)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_SavePrint)
.addGap(43, 43, 43))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton_Delete1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(74, 74, 74)
.addComponent(jTextField_Id, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(119, 119, 119))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel_CurrentDate)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField_Id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton_Delete1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jLabel_Total))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel_User)
.addComponent(jLabel2)
.addComponent(jButton_SavePrint))
.addGap(19, 19, 19))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField_IdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_IdActionPerformed
int id=Integer.parseInt(jTextField_Id.getText());
ProductDAO pDAO=new ProductDAO();
Product ob=pDAO.fetchData(id);
if(ob.getId()>0)
//when ID does not matches the database Item in the Database
{
model.addRow(new Object[]{ob.getId(),ob.getName(),ob.getPrice(),"1",ob.getPrice()});
//calling the total function
calculateTotal();
}
}//GEN-LAST:event_jTextField_IdActionPerformed
private void jButton_Delete1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_Delete1ActionPerformed
int row=jTable_Sales.getSelectedRow();
model.removeRow(row);
calculateTotal();
}//GEN-LAST:event_jButton_Delete1ActionPerformed
private void jButton_SavePrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_SavePrintActionPerformed
List<Sales> list=new ArrayList();
int count=jTable_Sales.getRowCount();
for(int i=0;i<count;i++)
{
Sales ob=new Sales();
int pid=Integer.parseInt(jTable_Sales.getValueAt(i,0).toString());
int sid=Global.uid;
int qty=Integer.parseInt(jTable_Sales.getValueAt(i,3).toString());
java.util.Date d=new java.util.Date();
ob.setPid(pid);
ob.setSid(sid);
ob.setQty(qty);
ob.setDos(d);
list.add(ob);
}
SalesDAO sDAO=new SalesDAO();
sDAO.saveData(list);
//for printing Bills
printBill();
}//GEN-LAST:event_jButton_SavePrintActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_Delete1;
private javax.swing.JButton jButton_SavePrint;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel_CurrentDate;
private javax.swing.JLabel jLabel_Total;
private javax.swing.JLabel jLabel_User;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable_Sales;
private javax.swing.JTextField jTextField_Id;
// End of variables declaration//GEN-END:variables
}
|
package com.projctwash.com.proyek2_carwash.Admin;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
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.Toast;
import com.projctwash.com.proyek2_carwash.Adapter.RecyclerAdapterJenisMotor;
import com.projctwash.com.proyek2_carwash.Admin.cud.EditJenisMotorActivity;
import com.projctwash.com.proyek2_carwash.Admin.cud.NewJenisMotorActivity;
import com.projctwash.com.proyek2_carwash.Config.SessionManagement;
import com.projctwash.com.proyek2_carwash.Listener.ClickListener;
import com.projctwash.com.proyek2_carwash.Listener.RecyclerTouchListener;
import com.projctwash.com.proyek2_carwash.Model.GetKendaraan;
import com.projctwash.com.proyek2_carwash.Model.Kendaraan;
import com.projctwash.com.proyek2_carwash.R;
import com.projctwash.com.proyek2_carwash.Rest.ApiClient;
import com.projctwash.com.proyek2_carwash.Rest.ApiInterface;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class KategoriAdmin extends Fragment {
// init
private ApiInterface mApiInterface;
private RecyclerView mRecyclerView;
private RecyclerAdapterJenisMotor mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Kendaraan> mMotor;
private FloatingActionButton btn_add;
private Context mcon;
// sesion management
HashMap<String,String> user;
SessionManagement mSesion;
View v ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_kategori_admin, container, false);
init();
initialize_recycler();
return v;
}
private void init(){
mcon = getContext();
btn_add = v.findViewById(R.id.btn_addmotor);
mRecyclerView = v.findViewById(R.id.rcycler_jenismotor);
mLayoutManager = new GridLayoutManager(getContext(),2);
mRecyclerView.setLayoutManager(mLayoutManager);
mApiInterface = ApiClient.getClient().create(ApiInterface.class);
mSesion = new SessionManagement(getContext());
user = mSesion.getLevelInformation();
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getContext(),NewJenisMotorActivity.class);
startActivity(i);
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getContext(), mRecyclerView, new ClickListener() {
@Override
public void onClick(View view, int posi) {
Kendaraan kndraan = mMotor.get(posi);
Toast.makeText(getContext(),"harga : "+kndraan.getHarga(),Toast.LENGTH_SHORT).show();
}
@Override
public void onLongClick(View view, int posi) {
Kendaraan kndraan = mMotor.get(posi);
Intent i = new Intent(getContext(),EditJenisMotorActivity.class);
i.putExtra("id",kndraan.getId());
i.putExtra("nama",kndraan.getNama());
i.putExtra("harga",kndraan.getHarga());
i.putExtra("img",kndraan.getImg());
startActivity(i);
}
}));
}
public void initialize_recycler(){
Call<GetKendaraan> gKen = mApiInterface.getKendaraan();
gKen.enqueue(new Callback<GetKendaraan>() {
@Override
public void onResponse(Call<GetKendaraan> call, Response<GetKendaraan> response) {
List<Kendaraan> mJMotor = response.body().getListDataKendaraan();
mMotor =mJMotor;
Log.d("Retrofit Get", "Jumlah data Kontak: " +String.valueOf(mJMotor.size()));
mAdapter = new RecyclerAdapterJenisMotor(mJMotor,getContext());
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onFailure(Call<GetKendaraan> call, Throwable t) {
Log.e("Retrofit Get", t.toString());
}
});
}
}
|
package practico9;
public class E6 {
public static void main(String[] args) {
int dia = (int) (Math.random() * 31 + 1);
int mes = (int) (Math.random() * 12 + 1);
int anio = (int) (Math.random() * (2100 - 1900 + 1) + 1900);
System.out.println("dia: " + dia);
System.out.println("mes: " + mes);
System.out.println("aņo: " + anio);
switch (mes) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println("La fecha " + dia + "/" + mes + "/" + anio + " es valida");
break;
case 4:
case 6:
case 9:
case 11:
if (dia <= 30) {
System.out.println("La fecha " + dia + "/" + mes + "/" + anio + " es valida");
} else {
System.out.println("La fecha es invalida");
}
break;
case 2:
if (anio % 4 == 0) {
if (dia <= 29) {
System.out.println("La fecha " + dia + "/" + mes + "/" + anio + " es valida");
break;
} else {
System.out.println("La fecha es invalida");
}
}
if (dia <= 28) {
System.out.println("La fecha " + dia + "/" + mes + "/" + anio + " es valida");
} else {
System.out.println("La fecha es invalida");
}
break;
}
}
}
|
package uchet.service.positions;
import uchet.models.Position;
import java.util.List;
import java.util.Map;
public interface PositionService {
List<Position> getAll();
Map<String, String> addPosition(Position newPosition);
Map<String, String> updatePosition(Position position);
Map<String, String> deletePosition(String id);
List<Position> findByFilter(Map<String, String> filterParams);
}
|
package pwnbrew.sessions.wizard;
import pwnbrew.generic.gui.wizard.WizardPanelDescriptor;
public class HostSchedulerDescriptor extends WizardPanelDescriptor {
protected static final String NAME_Class = HostSchedulerDescriptor.class.getSimpleName();
public static final String IDENTIFIER = "HOST_SCHEDULER_PANEL";
//===============================================================
/**
* Constructor
* @param passedWizard
*/
public HostSchedulerDescriptor( HostCheckInWizard passedWizard) {
super(IDENTIFIER, new HostSchedulerPanel( passedWizard), passedWizard );
}
//===============================================================
/**
* Get the descriptor for the next panel
*
* @return
*/
@Override
public String getNextPanelDescriptor() {
String nextDescriptor = ConfirmationDescriptor.IDENTIFIER;
return nextDescriptor;
}
//===============================================================
/**
*
* @return
*/
@Override
public String getBackPanelDescriptor() {
String nextDescriptor = HostSelectionDescriptor.IDENTIFIER;
return nextDescriptor;
}
}
|
package dev.sim0n.caesium.manager;
import com.google.common.io.ByteStreams;
import dev.sim0n.caesium.Caesium;
import dev.sim0n.caesium.exception.CaesiumException;
import dev.sim0n.caesium.mutator.impl.ClassFolderMutator;
import dev.sim0n.caesium.mutator.impl.crasher.ImageCrashMutator;
import dev.sim0n.caesium.util.ByteUtil;
import dev.sim0n.caesium.util.wrapper.impl.ClassWrapper;
import lombok.Getter;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.tree.ClassNode;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
@Getter
public class ClassManager {
private final Caesium caesium = Caesium.getInstance();
private final MutatorManager mutatorManager = caesium.getMutatorManager();
private final Logger logger = Caesium.getLogger();
private final Map<ClassWrapper, String> classes = new HashMap<>();
private final Map<String, byte[]> resources = new HashMap<>();
private final ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
public void parseJar(File input) throws Exception {
logger.info("Loading classes...");
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
byte[] data = ByteStreams.toByteArray(zis);
String name = entry.getName();
if (name.endsWith(".class")) {
ClassNode classNode = ByteUtil.parseClassBytes(data);
classes.put(new ClassWrapper(classNode, false), name);
} else {
if (name.equals("META-INF/MANIFEST.MF")) {
String manifest = new String(data);
// delete this line
manifest = manifest.substring(0, manifest.length() - 2);
// watermark the manifest
manifest += String.format("Obfuscated-By: Caesium %s\r\n", Caesium.VERSION);
data = manifest.getBytes();
}
resources.put(name, data);
}
}
}
logger.info("Loaded {} classes for mutation", classes.size());
caesium.separator();
}
public void handleMutation() throws Exception {
try (ZipOutputStream out = new ZipOutputStream(outputBuffer)) {
Optional<ImageCrashMutator> imageCrashMutator = Optional.ofNullable(mutatorManager.getMutator(ImageCrashMutator.class));
Optional<ClassFolderMutator> classFolderMutator = Optional.ofNullable(mutatorManager.getMutator(ClassFolderMutator.class));
AtomicBoolean hideClasses = new AtomicBoolean(classFolderMutator.isPresent() && classFolderMutator.get().isEnabled());
imageCrashMutator.ifPresent(crasher -> {
if (!crasher.isEnabled())
return;
ClassWrapper wrapper = crasher.getCrashClass();
classes.put(wrapper, String.format("%s.class", wrapper.node.name));
});
classes.forEach((node, name) -> {
mutatorManager.handleMutation(node);
try {
if (hideClasses.get()) // turn them into folders
name += "/";
out.putNextEntry(new ZipEntry(name));
out.write(ByteUtil.getClassBytes(node.node));
if (hideClasses.get()) { // generate a bunch of fake classes
String finalName = name;
IntStream.range(0, 1 + caesium.getRandom().nextInt(10))
.forEach(i -> {
try {
out.putNextEntry(new ZipEntry(String.format("%scaesium_%d.class", finalName, i ^ 27)));
out.write(new byte[] { 0 });
} catch (Exception e) {
e.printStackTrace();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
});
resources.forEach((name, data) -> {
try {
out.putNextEntry(new ZipEntry(name));
out.write(data);
} catch (IOException e) {
e.printStackTrace();
}
});
}
mutatorManager.handleMutationFinish();
}
/**
* Exports {@param output}
* @param output The obfuscated file to export
* @throws CaesiumException If unable to write output data
*/
public void exportJar(File output) throws CaesiumException {
try {
FileOutputStream fos = new FileOutputStream(output);
fos.write(outputBuffer.toByteArray());
fos.close();
} catch (IOException e) {
throw new CaesiumException("Failed to write output data", e);
}
}
}
|
package ug.tch;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.lib.IdentityReducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* Find lines that match a particular pattern
* Implements basic `grep -F'
*/
public class Grep extends Configured implements Tool {
public static enum Counters {
NO_MATCH
}
public static class InnerMapper extends MapReduceBase implements
Mapper<LongWritable, Text, Text, NullWritable> {
String term;
@Override
public void configure(JobConf job) {
term = job.get("grep.term");
if(term == null) {
throw new RuntimeException("grep.term config param not found");
}
}
public void map(LongWritable key, Text value,
OutputCollector<Text, NullWritable> output, Reporter report)
throws IOException {
String line = value.toString();
if(line.indexOf(term) >= 0) {
output.collect(value, NullWritable.get());
} else {
report.incrCounter(Counters.NO_MATCH, 1);
}
}
}
public int run(String[] args) throws Exception {
if(args.length < 2) {
throw new Exception("Usage: " + this.getClass().getName() + " output term input [input...]");
}
Configuration conf = getConf();
Path output = new Path(args[0]);
conf.set("grep.term", args[1]);
JobConf job = new JobConf(conf);
job.setJarByClass(Grep.class);
job.setMapperClass(InnerMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NullWritable.class);
job.setReducerClass(IdentityReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);
FileOutputFormat.setOutputPath(job, output);
for (int i = 2; i < args.length; i++) {
Path input = new Path(args[i]);
FileInputFormat.addInputPath(job, input);
}
JobClient.runJob(job);
return 0;
}
public static void main(String[] args) throws Exception {
int rc = ToolRunner.run(new Grep(), args);
System.exit(rc);
}
} |
// http://xahlee.org/java-a-day/this.html
// “this” Keyword
class CL {
int x = 1;
CL me()
{
return this;
}
}
class OneNumber
{
int n;
void setValue(int n)
{
this.n = n;
}
}
class B
{
int n;
void setMe(int m)
{
C h = new C();
h.setValue(this, m);
}
}
class C
{
void setValue(B obj, int h)
{
obj.n = h;
}
}
public class Tutorial10
{
public static void main(String[] args)
{
CL cl = new CL();
System.out.println(cl.x);
System.out.println(cl.me().x);
System.out.println(cl.me().me().x);
OneNumber x = new OneNumber();
x.setValue(3);
System.out.println(x.n);
B y = new B();
y.setMe(4);
System.out.println(y.n);
}
}
|
package com.code515.report.report_demo.Service.Impl;
import com.code515.report.report_demo.Enums.UserStatusEnum;
import com.code515.report.report_demo.Service.CheckLoginService;
import com.code515.report.report_demo.Service.UserService;
import com.code515.report.report_demo.Utils.DesUtil;
import com.code515.report.report_demo.Utils.RequestAndResponseUtil;
import com.code515.report.report_demo.Entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.Cookie;
@Service
@Slf4j
public class CheckLoginServiceImpl implements CheckLoginService {
@Autowired
private UserService userService;
// Autowired
// private HttpServletRequest request;
@Override
public boolean verification_ADMIN() {
// ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// HttpServletRequest request = attributes.getRequest();
//HttpSession session = request.getSession();
Cookie[] cookies = RequestAndResponseUtil.getRequest().getCookies();
User user;
for(Cookie cookie : cookies){
if(cookie.getName().equals("username")){
user = userService.findByUserName(DesUtil.decrypt(cookie.getValue()));
if(user == null){
log.error("【验证用户失败】找不到用户:{}", DesUtil.decrypt(cookie.getValue()));
return false;
}
if(user.getUserStatus().equals(UserStatusEnum.ADMIN.getCode())){
log.info("【验证管理员身份成功】用户名:{}", DesUtil.decrypt(cookie.getValue()));
return true;
}
}
}
log.error("【验证用户失败】cookie不存在");
return false;
}
}
|
package exercises.chapter5.ex8;
/**
* @author Volodymyr Portianko
* @date.created 11.03.2016
*/
public class Exercise8 {
void method1() {
System.out.println("First method");
}
void method2() {
this.method1();
method1();
}
public static void main(String[] args) {
new Exercise8().method2();
}
}
|
package com.dian.diabetes.activity.sugar.adapter;
import java.util.List;
import com.dian.diabetes.activity.sugar.TotalChartFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.view.ViewGroup;
public class SugarTotalAdapter extends FragmentPagerAdapter {
private List<String> data;
public SugarTotalAdapter(FragmentManager fm, List<String> data) {
super(fm);
this.data = data;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TotalChartFragment f = (TotalChartFragment) super.instantiateItem(
container, position);
f.setRepaint();
return f;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Fragment getItem(int position) {
return TotalChartFragment.getInstance(data.get(position), position);
}
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
}
|
package com.trump.auction.back.auctionProd.service.impl;
import com.cf.common.util.page.PageUtils;
import com.cf.common.util.page.Paging;
import com.github.pagehelper.PageHelper;
import com.trump.auction.back.auctionProd.dao.read.AuctionInfoDao;
import com.trump.auction.back.auctionProd.model.AuctionInfo;
import com.trump.auction.back.auctionProd.service.AuctionInfoService;
import com.trump.auction.back.auctionProd.vo.AuctionCondition;
import com.trump.auction.back.util.common.Base64Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @description: 拍卖信息
* @author: zhangqingqiang
* @date: 2018-01-08 14:12
**/
@Service
@Slf4j
public class AuctionInfoServiceImpl implements AuctionInfoService {
@Autowired
private AuctionInfoDao auctionInfoDao;
@Override
public List<AuctionInfo> queryLastAuction(AuctionCondition condition) {
return auctionInfoDao.queryLastAuction(condition);
}
/**
* 查询列表
*
* @param params
* @return
*/
@Override
public Paging<AuctionInfo> findList(Map<String, Object> params) {
long startTime = System.currentTimeMillis();
log.info("findList invoke,StartTime:{},params:{}", startTime, params);
Paging<AuctionInfo> result = null;
try {
result = new Paging<>();
PageHelper.startPage(Integer.valueOf(String.valueOf(params.get("page") == null ? 1 : params.get("page"))),
Integer.valueOf(String.valueOf(params.get("limit") == null ? 10 : params.get("limit"))));
result = PageUtils.page(auctionInfoDao.findList(params));
} catch (NumberFormatException e) {
log.error("findList error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findList end,duration:{}", endTime - startTime);
return result;
}
/**
* 根据id查询正在拍详情
*
* @param id
* @return
*/
@Override
public AuctionInfo findAuctionInfoById(Integer id) {
long startTime = System.currentTimeMillis();
log.info("findAuctionInfoById invoke,StartTime:{},params:{}", startTime, id);
if (null == id) {
throw new IllegalArgumentException("findAuctionInfoById param id is null");
}
AuctionInfo result = null;
try {
result = auctionInfoDao.selectByPrimaryKey(id);
if (result != null) {
if(StringUtils.isNotBlank(result.getWinUserDesc())) {
result.setWinUserDesc(Base64Utils.decodeStr(result.getWinUserDesc()));
}
}
} catch (NumberFormatException e) {
log.error("findAuctionInfoById error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findAuctionInfoById end,duration:{}", endTime - startTime);
return result;
}
@Override
public List<AuctionInfo> queryAuctionByStatus(Integer status) {
return auctionInfoDao.queryAuctionByStatus(status);
}
@Override
public AuctionInfo queryLastOneAuctionByAuctionProdId(Integer id) {
return auctionInfoDao.queryLastOneAuctionByAuctionProdId(id);
}
}
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spring.config;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.ClientFailoverConfig;
import com.hazelcast.config.Config;
import com.hazelcast.spring.HazelcastClientBeanDefinitionParser;
import com.hazelcast.spring.HazelcastConfigBeanDefinitionParser;
import com.hazelcast.spring.HazelcastFailoverClientBeanDefinitionParser;
import java.util.function.Supplier;
/**
* Provides factory methods for {@link Config} and {@link ClientConfig}.
* This class is used in {@link HazelcastConfigBeanDefinitionParser},
* {@link HazelcastClientBeanDefinitionParser} and
* {@link HazelcastFailoverClientBeanDefinitionParser} to create
* `empty` configuration instances. This factory can be used to
* pre-configure the configuration instances, see
* {@code CustomSpringJUnit4ClassRunner} for the usage.
*/
public final class ConfigFactory {
private static volatile Supplier<Config> configSupplier = Config::new;
private static volatile Supplier<ClientConfig> clientConfigSupplier = ClientConfig::new;
private static volatile Supplier<ClientFailoverConfig> clientFailoverConfigSupplier = ClientFailoverConfig::new;
private ConfigFactory() {
}
static void setConfigSupplier(Supplier<Config> configSupplier) {
ConfigFactory.configSupplier = configSupplier;
}
static void setClientConfigSupplier(Supplier<ClientConfig> clientConfigSupplier) {
ConfigFactory.clientConfigSupplier = clientConfigSupplier;
}
static void setClientFailoverConfigSupplier(Supplier<ClientFailoverConfig> clientFailoverConfigSupplier) {
ConfigFactory.clientFailoverConfigSupplier = clientFailoverConfigSupplier;
}
public static Config newConfig() {
return configSupplier.get();
}
public static ClientConfig newClientConfig() {
return clientConfigSupplier.get();
}
public static ClientFailoverConfig newClientFailoverConfig() {
return clientFailoverConfigSupplier.get();
}
}
|
package ledennis.lib.inventoryserializer.v1_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import org.bukkit.Bukkit;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class Executor {
private static final String VERSION_KEY = "v1.1";
public static void serialize(Inventory inventory, File file) throws IOException {
if(!file.exists()) file.createNewFile();
if(file.isDirectory()) return;
serialize(inventory.getContents(), new PrintWriter(file));
}
public static void serialize(ItemStack[] items, PrintWriter out) {
String str = "";
str += VERSION_KEY + ":";
for(ItemStack item : items) {
str += serialize0(item);
str += "@";
}
str = str.substring(0, str.length() - 1);
out.println(str);
out.flush();
out.close();
}
@SuppressWarnings("deprecation")
public static String serialize0(ItemStack item) {
if(item == null) return "$NONE";
String str = MessageFormat.format("{0}:{1}:{2};",
item.getTypeId(),
item.getDurability(),
item.getAmount());
str = str.replaceAll(",", "");
if(item.getEnchantments().isEmpty()) {
str += "$NONE";
} else {
for(Entry<Enchantment, Integer> e : item.getEnchantments().entrySet()) {
str += e.getKey().getId() + "#" + e.getValue() + ":";
}
str = str.substring(0, str.length() - 1);
}
str += ";";
ItemMeta meta = item.getItemMeta();
if(!meta.hasDisplayName()) {
str += "$NONE:";
} else {
String name = formatString(meta.getDisplayName());
str += name + ":";
}
if(!meta.hasLore()) {
str += "$NONE";
} else {
List<String> lore = meta.getLore();
for(String line : lore) {
str += formatString(line) + "~";
}
str = str.substring(0, str.length() - 1);
}
return str;
}
@SuppressWarnings("deprecation")
public static Inventory deserialize(File file) {
if(!file.exists()) return null;
if(file.isDirectory()) return null;
Scanner in;
try {
in = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
if(!in.hasNextLine()) {
in.close();
return null;
}
String str = in.nextLine();
in.close();
if(str == null) return null;
if(str.equals("")) return null;
str = str.substring(VERSION_KEY.length() + 1);
String[] data = str.split("@");
ItemStack[] content = new ItemStack[data.length];
for(int i = 0; i < data.length; i++) {
String s = data[i];
ItemStack item;
if(s.equals("$NONE")) {
content[i] = null;
} else {
String[] var0 = s.split(";");
String general = var0[0];
String ench = var0[1];
String meta = var0[2];
// GENERAL
int[] var1 = toIntArray(general.split(":"));
item = new ItemStack(var1[0], var1[2], (short) var1[1]);
// ENCHANMENTS
if(!ench.equals("$NONE")) {
String[] var2 = ench.split(":");
for(String s981 : var2) {
int[] t981 = toIntArray(s981.split("#"));
item.addUnsafeEnchantment(Enchantment.getById(t981[0]), t981[1]);
}
}
// META
ItemMeta imeta = item.getItemMeta();
String[] var3 = meta.split(":");
if(!var3[0].equals("$NONE")) imeta.setDisplayName(var3[0]);
if(!var3[1].equals("$NONE")) {
List<String> lore = new ArrayList<>();
String[] t154 = var3[1].split("~");
for(String line : t154) {
lore.add(line);
}
imeta.setLore(lore);
}
item.setItemMeta(imeta);
// FINISH
content[i] = item;
}
}
Inventory inv = Bukkit.createInventory(null, content.length);
inv.setContents(content);
return inv;
}
private static int[] toIntArray(String[] in) {
int[] out = new int[in.length];
for(int i = 0; i < in.length; i++) {
out[i] = Integer.parseInt(in[i]);
}
return out;
}
private static String formatString(String in) {
char[] forbidden = {
';',
':',
'~',
'@'
};
for(char c : forbidden) {
if(in.contains(String.valueOf(c))) {
in = in.replace(c, ' ');
}
}
return in;
}
}
|
package zy.sample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import zy.inject.Injector;
import zy.inject.annotation.BindView;
/**
* @author zhangyuan
* created on 2018/5/30.
*/
public class SubActivity extends MainActivity {
@BindView(R.id.hello2)
TextView hello2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
Injector.inject(this);
hello.setText("Sub Inject Success");
hello.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SubActivity.this, InterfaceViewActivity.class);
startActivity(intent);
}
});
}
}
|
package com.gxtc.huchuan.ui.deal.liuliang.publicAccount;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.adapter.AccountPageAdapter;
import com.gxtc.huchuan.ui.deal.liuliang.publicAccount.MsgAnalyse.MsgAnalyseFragment;
import com.gxtc.huchuan.ui.deal.liuliang.publicAccount.TextAnalyse.TextTabFragment;
import com.gxtc.huchuan.ui.deal.liuliang.publicAccount.UserAnalyse.UserTabFragment;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
* 公众号信息
*/
public class AccountInfoActivity extends BaseTitleActivity {
@BindView(R.id.vp_account) ViewPager viewPager;
private String titles [] = {"用户分析","图文分析","消息分析"};
private SegmentTabLayout tabLayout;
private MsgAnalyseFragment mFragment;
private TextTabFragment tFragment;
private UserTabFragment uFragment;
private AccountPageAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_info);
}
@Override
public void initView() {
View head = LayoutInflater.from(this).inflate(R.layout.head_account, (ViewGroup) getBaseHeadView().getParentView(), false);
tabLayout = (SegmentTabLayout)head.findViewById(R.id.stl_account);
((RelativeLayout) getBaseHeadView().getParentView()).addView(head);
getBaseHeadView().showBackButton(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public void initListener() {
tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
@Override
public void onTabSelect(int position) {
viewPager.setCurrentItem(position);
}
@Override
public void onTabReselect(int position) {
}
});
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
tabLayout.setCurrentTab(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public void initData() {
mFragment = new MsgAnalyseFragment();
tFragment = new TextTabFragment();
uFragment = new UserTabFragment();
List<Fragment> fragments = new ArrayList<>();
fragments.add(uFragment);
fragments.add(tFragment);
fragments.add(mFragment);
adapter = new AccountPageAdapter(getSupportFragmentManager(),fragments);
viewPager.setAdapter(adapter);
tabLayout.setTabData(titles);
}
}
|
package fr.skytasul.quests.gui.creation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import fr.skytasul.quests.BeautyQuests;
import fr.skytasul.quests.QuestsConfiguration;
import fr.skytasul.quests.api.QuestsAPI;
import fr.skytasul.quests.api.events.QuestCreateEvent;
import fr.skytasul.quests.api.options.QuestOption;
import fr.skytasul.quests.api.options.QuestOptionCreator;
import fr.skytasul.quests.api.options.UpdatableOptionSet;
import fr.skytasul.quests.api.options.UpdatableOptionSet.Updatable;
import fr.skytasul.quests.api.stages.AbstractStage;
import fr.skytasul.quests.api.stages.StageCreation;
import fr.skytasul.quests.gui.CustomInventory;
import fr.skytasul.quests.gui.Inventories;
import fr.skytasul.quests.gui.ItemUtils;
import fr.skytasul.quests.gui.creation.stages.StagesGUI;
import fr.skytasul.quests.options.*;
import fr.skytasul.quests.players.PlayerAccount;
import fr.skytasul.quests.players.PlayerQuestDatas;
import fr.skytasul.quests.players.PlayersManager;
import fr.skytasul.quests.structure.Quest;
import fr.skytasul.quests.structure.QuestBranch;
import fr.skytasul.quests.utils.DebugUtils;
import fr.skytasul.quests.utils.Lang;
import fr.skytasul.quests.utils.Utils;
import fr.skytasul.quests.utils.XMaterial;
import fr.skytasul.quests.utils.nms.NMS;
public class FinishGUI extends UpdatableOptionSet<Updatable> implements CustomInventory {
private final QuestCreationSession session;
/* Temporary quest datas */
private Map<Integer, Item> clicks = new HashMap<>();
/* GUI variables */
public Inventory inv;
private Player p;
private Boolean keepPlayerDatas = null;
private UpdatableItem done;
public FinishGUI(QuestCreationSession session) {
this.session = session;
}
@Override
public Inventory open(Player p){
this.p = p;
if (inv == null){
String invName = Lang.INVENTORY_DETAILS.toString();
if (session.isEdition()) {
invName = invName + " #" + session.getQuestEdited().getID();
if (NMS.getMCVersion() <= 8 && invName.length() > 32) invName = Lang.INVENTORY_DETAILS.toString(); // 32 characters limit in 1.8
}
inv = Bukkit.createInventory(null, (int) Math.ceil((QuestOptionCreator.creators.values().stream().mapToInt(creator -> creator.slot).max().getAsInt() + 1) / 9D) * 9, invName);
for (QuestOptionCreator<?, ?> creator : QuestOptionCreator.creators.values()) {
QuestOption<?> option;
if (session.isEdition() && session.getQuestEdited().hasOption(creator.optionClass)) {
option = session.getQuestEdited().getOption(creator.optionClass).clone();
}else {
option = creator.optionSupplier.get();
}
UpdatableItem item = new UpdatableItem(creator.slot) {
@Override
public void click(Player p, ItemStack item, ClickType click) {
option.click(FinishGUI.this, p, item, slot, click);
}
@Override
public boolean clickCursor(Player p, ItemStack item, ItemStack cursor) {
return option.clickCursor(FinishGUI.this, p, item, cursor, slot);
}
@Override
public void update() {
if (option.shouldDisplay(FinishGUI.this)) {
inv.setItem(slot, option.getItemStack(FinishGUI.this));
}else inv.setItem(slot, null);
option.updatedDependencies(FinishGUI.this, inv.getItem(slot));
}
};
addOption(option, item);
clicks.put(creator.slot, item);
}
super.calculateDependencies();
for (QuestOption<?> option : this) {
if (option.shouldDisplay(this)) inv.setItem(option.getOptionCreator().slot, option.getItemStack(this));
}
int pageSlot = QuestOptionCreator.calculateSlot(3);
clicks.put(pageSlot, new Item(pageSlot) {
@Override
public void click(Player p, ItemStack item, ClickType click) {
session.openMainGUI(p);
}
});
inv.setItem(pageSlot, ItemUtils.itemLaterPage);
done = new UpdatableItem(QuestOptionCreator.calculateSlot(5)) {
@Override
public void update() {
boolean enabled = getOption(OptionName.class).getValue() != null;
XMaterial type = enabled ? XMaterial.GOLD_INGOT : XMaterial.NETHER_BRICK;
String itemName = (enabled ? ChatColor.GOLD : ChatColor.DARK_PURPLE).toString() + (session.isEdition() ? Lang.edit : Lang.create).toString();
String itemLore = QuestOption.formatDescription(Lang.createLore.toString()) + (enabled ? " §a✔" : " §c✖");
String[] lore = keepPlayerDatas == null || keepPlayerDatas.booleanValue() ? new String[] { itemLore } : new String[] { itemLore, "", Lang.resetLore.toString() };
ItemStack item = inv.getItem(slot);
if (item == null) {
inv.setItem(slot, ItemUtils.item(type, itemName, lore));
return;
}else if (!type.isSimilar(item)) {
type.setType(item);
ItemUtils.name(item, itemName);
}
ItemUtils.lore(item, lore);
}
@Override
public void click(Player p, ItemStack item, ClickType click) {
if (getOption(OptionName.class).getValue() != null) finish();
}
};
done.update();
clicks.put(done.slot, done);
getWrapper(OptionName.class).dependent.add(done);
}
if (session.areStagesEdited() && keepPlayerDatas == null) setStagesEdited();
inv = p.openInventory(inv).getTopInventory();
return inv;
}
public CustomInventory reopen(Player p){
Inventories.put(p, this, inv);
p.openInventory(inv);
return this;
}
@Override
public boolean onClick(Player p, Inventory inv, ItemStack current, int slot, ClickType click){
clicks.get(slot).click(p, current, click);
return true;
}
@Override
public boolean onClickCursor(Player p, Inventory inv, ItemStack current, ItemStack cursor, int slot) {
return clicks.get(slot).clickCursor(p, current, cursor);
}
private void finish(){
boolean keepPlayerDatas = Boolean.TRUE.equals(this.keepPlayerDatas);
Quest qu;
if (session.isEdition()) {
DebugUtils.logMessage(
"Editing quest " + session.getQuestEdited().getID() + " with keep datas: " + keepPlayerDatas);
session.getQuestEdited().remove(false, false);
qu = new Quest(session.getQuestEdited().getID(), session.getQuestEdited().getFile());
}else {
int id = -1;
if (session.hasCustomID()) {
if (QuestsAPI.getQuests().getQuests().stream().anyMatch(x -> x.getID() == session.getCustomID())) {
BeautyQuests.logger.warning("Cannot create quest with custom ID " + session.getCustomID() + " because another quest with this ID already exists.");
}else {
id = session.getCustomID();
BeautyQuests.logger.warning("A quest will be created with custom ID " + id + ".");
}
}
if (id == -1)
id = QuestsAPI.getQuests().getFreeQuestID();
qu = new Quest(id);
}
for (QuestOption<?> option : this) {
if (option.hasCustomValue()) qu.addOption(option);
}
QuestBranch mainBranch = new QuestBranch(qu.getBranchesManager());
qu.getBranchesManager().addBranch(mainBranch);
boolean failure = loadBranch(mainBranch, session.getMainGUI());
QuestCreateEvent event = new QuestCreateEvent(p, qu, session.isEdition());
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()){
qu.remove(false, true);
Utils.sendMessage(p, Lang.CANCELLED.toString());
}else {
if (session.areStagesEdited()) {
if (keepPlayerDatas) {
BeautyQuests.logger.warning("Players quests datas will be kept for quest #" + qu.getID()
+ " - this may cause datas issues.");
} else
BeautyQuests.getInstance().getPlayersManager().removeQuestDatas(session.getQuestEdited())
.whenComplete(BeautyQuests.logger
.logError("An error occurred while removing player datas after quest edition", p));
}
QuestsAPI.getQuests().addQuest(qu);
Utils.sendMessage(p, ((!session.isEdition()) ? Lang.SUCCESFULLY_CREATED : Lang.SUCCESFULLY_EDITED).toString(), qu.getName(), qu.getBranchesManager().getBranchesAmount());
Utils.playPluginSound(p, "ENTITY_VILLAGER_YES", 1);
BeautyQuests.logger.info("New quest created: " + qu.getName() + ", ID " + qu.getID() + ", by " + p.getName());
if (session.isEdition()) {
BeautyQuests.getInstance().getLogger().info("Quest " + qu.getName() + " has been edited");
if (failure) BeautyQuests.getInstance().createQuestBackup(qu.getFile().toPath(), "Error occurred while editing");
}
try {
qu.saveToFile();
}catch (Exception e) {
Lang.ERROR_OCCURED.send(p, "initial quest save");
BeautyQuests.logger.severe("Error when trying to save newly created quest.", e);
}
if (keepPlayerDatas) {
for (Player p : Bukkit.getOnlinePlayers()) {
PlayerAccount account = PlayersManager.getPlayerAccount(p);
if (account == null) continue;
if (account.hasQuestDatas(qu)) {
PlayerQuestDatas datas = account.getQuestDatas(qu);
datas.questEdited();
if (datas.getBranch() == -1) continue;
QuestBranch branch = qu.getBranchesManager().getBranch(datas.getBranch());
if (datas.isInEndingStages()) {
branch.getEndingStages().keySet().forEach(stage -> stage.joins(account, p));
}else branch.getRegularStage(datas.getStage()).joins(account, p);
}
}
}
QuestsAPI.propagateQuestsHandlers(handler -> {
if (session.isEdition())
handler.questEdit(qu, session.getQuestEdited(), keepPlayerDatas);
else handler.questCreate(qu);
});
}
Inventories.closeAndExit(p);
}
private boolean loadBranch(QuestBranch branch, StagesGUI gui) {
boolean failure = false;
for (StageCreation<?> creation : gui.getStageCreations()) {
try{
AbstractStage stage = creation.finish(branch);
if (creation.isEndingStage()) {
StagesGUI newGUI = creation.getLeadingBranch();
QuestBranch newBranch = null;
if (!newGUI.isEmpty()){
newBranch = new QuestBranch(branch.getBranchesManager());
branch.getBranchesManager().addBranch(newBranch);
failure |= loadBranch(newBranch, newGUI);
}
branch.addEndStage(stage, newBranch);
}else branch.addRegularStage(stage);
}catch (Exception ex) {
failure = true;
Lang.ERROR_OCCURED.send(p, " lineToStage");
BeautyQuests.logger.severe("An error occurred wheh creating branch from GUI.", ex);
}
}
return failure;
}
private void setStagesEdited() {
keepPlayerDatas = false;
int resetSlot = QuestOptionCreator.calculateSlot(6);
inv.setItem(resetSlot, ItemUtils.itemSwitch(Lang.keepDatas.toString(), false, QuestOption.formatDescription(Lang.keepDatasLore.toString())));
clicks.put(resetSlot, new Item(resetSlot) {
@Override
public void click(Player p, ItemStack item, ClickType click) {
keepPlayerDatas = ItemUtils.toggle(item);
done.update();
}
});
done.update();
}
abstract class Item {
protected final int slot;
protected Item(int slot) {
this.slot = slot;
}
public abstract void click(Player p, ItemStack item, ClickType click);
public boolean clickCursor(Player p, ItemStack item, ItemStack cursor) {
return true;
}
}
abstract class UpdatableItem extends Item implements Updatable {
protected UpdatableItem(int slot) {
super(slot);
}
}
public static void initialize(){
DebugUtils.logMessage("Initlializing default quest options.");
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("pool", 9, OptionQuestPool.class, OptionQuestPool::new, null));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("name", 10, OptionName.class, OptionName::new, null));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("description", 12, OptionDescription.class, OptionDescription::new, null));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("customItem", 13, OptionQuestItem.class, OptionQuestItem::new, QuestsConfiguration.getItemMaterial(), "customMaterial"));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("confirmMessage", 15, OptionConfirmMessage.class, OptionConfirmMessage::new, null));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("hologramText", 17, OptionHologramText.class, OptionHologramText::new, Lang.HologramText.toString()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("bypassLimit", 18, OptionBypassLimit.class, OptionBypassLimit::new, false));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("startableFromGUI", 19, OptionStartable.class, OptionStartable::new, false));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("failOnDeath", 20, OptionFailOnDeath.class, OptionFailOnDeath::new, false));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("cancellable", 21, OptionCancellable.class, OptionCancellable::new, true));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("cancelActions", 22, OptionCancelRewards.class, OptionCancelRewards::new, new ArrayList<>()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("hologramLaunch", 25, OptionHologramLaunch.class, OptionHologramLaunch::new, QuestsConfiguration.getHoloLaunchItem()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("hologramLaunchNo", 26, OptionHologramLaunchNo.class, OptionHologramLaunchNo::new, QuestsConfiguration.getHoloLaunchNoItem()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("scoreboard", 27, OptionScoreboardEnabled.class, OptionScoreboardEnabled::new, true));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("hideNoRequirements", 28, OptionHideNoRequirements.class, OptionHideNoRequirements::new, false));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("auto", 29, OptionAutoQuest.class, OptionAutoQuest::new, false));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("repeatable", 30, OptionRepeatable.class, OptionRepeatable::new, false, "multiple"));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("timer", 31, OptionTimer.class, OptionTimer::new, QuestsConfiguration.getTimeBetween()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("visibility", 32, OptionVisibility.class, OptionVisibility::new, Arrays.asList(OptionVisibility.VisibilityLocation.values()), "hid", "hide"));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("endSound", 34, OptionEndSound.class, OptionEndSound::new, QuestsConfiguration.getFinishSound()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("firework", 35, OptionFirework.class, OptionFirework::new, QuestsConfiguration.getDefaultFirework()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("requirements", 36, OptionRequirements.class, OptionRequirements::new, new ArrayList<>()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("startRewards", 38, OptionStartRewards.class, OptionStartRewards::new, new ArrayList<>(), "startRewardsList"));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("startMessage", 39, OptionStartMessage.class, OptionStartMessage::new, QuestsConfiguration.getPrefix() + Lang.STARTED_QUEST.toString()));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("starterNPC", 40, OptionStarterNPC.class, OptionStarterNPC::new, null, "starterID"));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("startDialog", 41, OptionStartDialog.class, OptionStartDialog::new, null));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("endRewards", 43, OptionEndRewards.class, OptionEndRewards::new, new ArrayList<>(), "rewardsList"));
QuestsAPI.registerQuestOption(new QuestOptionCreator<>("endMsg", 44, OptionEndMessage.class, OptionEndMessage::new, QuestsConfiguration.getPrefix() + Lang.FINISHED_BASE.toString()));
}
} |
package MVC.controllers.productControllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import MVC.models.inventoryModel;
import MVC.models.productModel;
import MVC.views.addPartsView;
import MVC.views.errorView;
import MVC.views.showPartsView;
import MVC.views.productsViews.addProductsView;
public class addProductController implements ActionListener{
private addProductsView view;
private productModel model;
//private showPartsView showView;
private String[] names;
private String error;
private ArrayList<String> namesArray = new ArrayList();
private errorView errorView;
public addProductController(productModel model, addProductsView addView){
this.view = addView;
this.model = model;
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();//gets command value from buttonPanel in addPartView
if (command.equals("Cancel")) {
view.closeWindow();//closes addPartView
}else if (command.equals("Add Part")){
String desc = view.getDesc();/*sets values from addPartView's text fields*/
String num = view.getNum();
model.addProduct(num, desc);
}
}
}
|
package ai.infrrd.guitarshop;
import ai.infrrd.electricity.Electricity;
import ai.infrrd.guitar.AcousticGuitar;
import ai.infrrd.guitar.ElectricGuitar;
import ai.infrrd.guitar.Guitar;
import java.util.ArrayList;
import java.util.Random;
import java.util.List;
import static java.util.Arrays.asList;
public class GuitarShop {
Electricity electricity = new Electricity();
public List<ElectricGuitar> guitarsList = new ArrayList();
private List<Salesman> freeSalesmenList = new ArrayList<>();
private List<Salesman> busySalesmenList = new ArrayList<>();
public GuitarShop() {
electricity.start();
for(int i=0;i<3;i++)
freeSalesmenList.add(new Salesman());
}
private static GuitarShop instance = new GuitarShop();
private Random randomGenerator = new Random();
List<Class<? extends Guitar>> guitars = asList(ElectricGuitar.class, AcousticGuitar.class);
int randomIndex = randomGenerator.nextInt(guitars.size());
Class currentGuitar = (guitars.get(randomIndex));
public static GuitarShop getInstance() {
return instance;
}
public synchronized Salesman assignSalesman() throws IllegalAccessException, InstantiationException {
Salesman tempSalesman = this.freeSalesmenList.size() >0 ? this.freeSalesmenList.remove(0) : null;
if(tempSalesman!=null) tempSalesman.setGuitar((Guitar) currentGuitar.newInstance());
if (tempSalesman != null) this.busySalesmenList.add(tempSalesman);
return tempSalesman;
}
public synchronized Salesman freeSalesman() {
return this.freeSalesmenList.size() >0 ? this.freeSalesmenList.remove(0) : null;
}
}
|
package dogs;
public class Main {
public static void main(String[] args) {
Labrador molly = new Labrador();
CoatDecorator ctd = new CoatDecorator(molly,Coat.DOUBLE);
ColourDecorator crd = new ColourDecorator(ctd,Colour.BROWN);
DogCharacteristics lab1 = crd;
lab1.breedPurpose();
lab1.coat();
lab1.size();
lab1.description();
}
}
|
/**
* <copyright>
* </copyright>
*
*
*/
package ssl.resource.ssl.grammar;
public class SslLineBreak extends ssl.resource.ssl.grammar.SslFormattingElement {
private final int tabs;
public SslLineBreak(ssl.resource.ssl.grammar.SslCardinality cardinality, int tabs) {
super(cardinality);
this.tabs = tabs;
}
public int getTabs() {
return tabs;
}
public String toString() {
return "!" + getTabs();
}
}
|
package pruebas;
import java.util.Scanner;
public class uso_tallas {
enum talla{
MINI("s"),MEDIANO("m"),GRANDE("g"),MUY_GRANDE("xl");
private talla(String abreviaturas){
this.abreviaturas=abreviaturas;
}
public String dame_abreviaturas(){
return abreviaturas;
}
private String abreviaturas;
}
public static void main(String[] args) {
Scanner entrada=new Scanner(System.in);
System.out.println("Escribe una talla: mini,mediano,grande, muy grande" );
String entrada_datos=entrada.next().toUpperCase();//pasa a mayusculas lo introducido en onsla
talla la_talla=Enum.valueOf(talla.class, entrada_datos);
System.out.println("Talla=" + la_talla);
System.out.println("Abreviatura=" + la_talla.dame_abreviaturas());
}
}
|
package com.isteel.myfaceit.ui.players.profile.profileInfo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import com.isteel.myfaceit.BR;
import com.isteel.myfaceit.R;
import com.isteel.myfaceit.ViewModelProviderFactory;
import com.isteel.myfaceit.data.model.ResponsePlayer;
import com.isteel.myfaceit.databinding.ProfileInfoFragmentBinding;
import com.isteel.myfaceit.ui.base.BaseFragment;
import com.isteel.myfaceit.utils.LogUtil;
import java.util.List;
import javax.inject.Inject;
public class ProfileInfoFragment extends BaseFragment<ProfileInfoFragmentBinding, ProfileInfoViewModel>
implements NavigatorPlayerProfileInfo{
private ProfileInfoFragmentBinding PersonalInfoFragmentBinding;
private ProfileInfoViewModel mViewModel;
@Inject
ViewModelProviderFactory factory;
private String id;
public static ProfileInfoFragment newInstance(String str) {
Bundle bundle = new Bundle();
bundle.putString("id",str);
ProfileInfoFragment profileInfoFragment = new ProfileInfoFragment();
profileInfoFragment.setArguments(bundle);
return profileInfoFragment;
}
@Override
public int getBindingVariable() {
return BR.viewModel;
}
@Override
public int getLayoutId() {
return R.layout.profile_info_fragment;
}
@Override
public ProfileInfoViewModel getViewModel() {
mViewModel = new ViewModelProvider(this,factory).get(ProfileInfoViewModel.class);
return mViewModel;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PersonalInfoFragmentBinding = getViewDataBinding();
Bundle bundle = this.getArguments();
assert bundle != null;
bundle.getString("id", "lox");
mViewModel.fetchData(bundle.getString("id", ""));
}
@Override
public void handleError(Throwable throwable) {
}
@Override
public void updatePlayer(ResponsePlayer.Player player) {
}
} |
package edu.wctc.dfb.bookwebappmaven.controller;
import edu.wctc.dfb.bookwebappmaven.model.Author;
import edu.wctc.dfb.bookwebappmaven.model.AuthorService;
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Dan
*/
@WebServlet(name = "AuthorController", urlPatterns = {"/AuthorController"})
public class AuthorController extends HttpServlet {
@Inject
private AuthorService authorService;
private String driver;
private String url;
private String username;
private String password;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//Helper method to initiate a db connection
configDbConnection();
try {
String destPage = "";
String action = request.getParameter("action");
switch (action) {
case "view":
destPage = "/authorList.jsp";
break;
case "update":
destPage = "/editList.jsp";
break;
case "new":
destPage = "/createAuthor.jsp";
break;
case "Create":
String name=request.getParameter("authorName");
authorService.createAuthor(name);
destPage="/authorList.jsp";
break;
case "Edit":
String[] authorIdToEdit=request.getParameterValues("authorID");
Author authorToEdit = authorService.findAuthorById(Integer.parseInt(authorIdToEdit[0]));
request.setAttribute("authorToEdit",authorToEdit) ;
destPage="/editAuthor.jsp";
break;
case "Remove":
String[] authorIdToDelete=request.getParameterValues("authorID");
authorService.deleteAuthorById(authorIdToDelete[0]);
destPage="/authorList.jsp";
break;
case "Save":
String newName=request.getParameter("authorName");
int authorId=Integer.parseInt(request.getParameter("authorId"));
authorService.updateAuthor(authorId,newName);
destPage="/authorList.jsp";
break;
case "Cancel":
destPage="/index.html";
break;
default:
destPage="/index.html";
break;
}
List authors = authorService.getAuthorList();
request.setAttribute("authorList", authors);
request.setAttribute("endOfList", authors.size());
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (Exception e) {
System.out.println("Fatal Error");
e.printStackTrace();
}
}
private void configDbConnection() {
authorService.getAuthorDAO().initDAO(driver, url, username, password);
}
@Override
public void init() throws ServletException {
driver = getServletContext().getInitParameter("db.driver.class");
url = getServletContext().getInitParameter("db.url");
username = getServletContext().getInitParameter("db.username");
password = getServletContext().getInitParameter("db.password");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package org.shujito.cartonbox.controller.task.listener;
import org.shujito.cartonbox.model.parser.XmlParser;
public interface OnXmlResponseReceivedListener
{ public void onResponseReceived(XmlParser<?> xp); }
|
package cellsociety_team10;
/**
* creates individual cell object for the grid
*
* @author Phil Foo, Lucy Zhang, Yumin Zhang
*
*/
public class Cell {
private int state;
private int x;
private int y;
private int extraState;
private double extraState2;
private double extraState3;
public Cell(){
x = 0;
y = 0;
state = 0;
extraState=0;
extraState2=0;
}
public Cell(int x, int y, int state) {
this.x = x;
this.y = y;
this.state = state;
extraState = 0;
extraState2 = 0;
extraState3 = 0;
}
public double getExtraState2() {
return extraState2;
}
public double getExtraState3() {
return extraState3;
}
public void setExtraState2(double extraState2) {
this.extraState2 = extraState2;
}
public void setExtraState3(double extraState3) {
this.extraState3 = extraState3;
}
public int getExtraState() {
return extraState;
}
public void setExtraState(int extraState) {
this.extraState = extraState;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
|
package com.nestis.interview.questions.service;
import java.util.List;
import com.nestis.interview.questions.entity.Question;
/**
* QuestionService. Manages all the operations regarding Question entities.
* @author nestis
*
*/
public interface QuestionService {
/**
* Returns all the questions within the range passed as parameter.
* @param questionIds Array containing the question ids to search.
* @return List.
*/
List<Question> getQuestions(List<Integer> questionIds);
/**
* Saves or updates the questions passed as parameter.
* @param questions List of Question to save/update.
* @return Boolean indicating if the operation was successful.
*/
boolean saveQuestions(List<Question> questions);
}
|
package com.alex;
import com.alex.pets.Wolf;
import org.junit.Assert;
import org.junit.Test;
public class WolfTest {
@Test
public void testWolfHaveCorrectName() {
Wolf wolf = new Wolf("Sif", "Demon");
Assert.assertEquals("Sif", wolf.getName());
}
@Test
public void theWolfHaveCorrectBreed() {
Wolf wolf = new Wolf("Sif", "Demon");
Assert.assertEquals("Demon", wolf.getBreed());
}
}
|
package dk.kyuff.webapp.resources;
/**
* User: swi
* Date: 11/10/14
* Time: 06.37
*/
import dk.kyuff.webapp.OrderDao;
import dk.kyuff.webapp.model.Order;
import javax.inject.Inject;
import javax.ws.rs.*;
import java.util.*;
@Path("orders")
@Produces("application/json")
@Consumes("application/json")
public class OrderResource {
@Inject
OrderDao dao;
public OrderResource() {
}
@GET
public List<Order> getAll() {
return dao.getAll();
}
@GET
@Path("{id}")
public Order getOne(@PathParam("id") long id) {
Order order = dao.find(id);
if (order == null) {
throw new WebApplicationException(404);
}
return order;
}
@POST
public Order create(Order order) {
return dao.persist(order);
}
@PUT
public Order update(Order order) {
return dao.update(order);
}
}
|
package com.protectthecarrots.Tools;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;
import com.protectthecarrots.TheCarrots;
/**
* Created by Pedro on 11/03/2018.
*/
public class BonusLife {
public Vector2 bonusLifePosition;
private Vector2 bonusLifeVelocity;
private float radius = 0.07f;
public Body body;
private BodyDef bdef = new BodyDef();
private FixtureDef fdef = new FixtureDef();
private CircleShape circleShape = new CircleShape();
private Texture bonusLifeTexture;
public BonusLife(World world, float positionX, float positionY) {
bonusLifeTexture = new Texture("bonus life.png");
bonusLifePosition = new Vector2( positionX , positionY );
bonusLifeVelocity = new Vector2( 0.0f, -10 / TheCarrots.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bdef);
circleShape.setRadius(radius);
fdef.shape = circleShape;
fdef.isSensor = true;
body.createFixture(fdef);
body.setUserData("bonuslife");
}
public void update(SpriteBatch sb, float dt){
bonusLifePosition.x += bonusLifeVelocity.x * dt;
bonusLifePosition.y += bonusLifeVelocity.y * dt;
body.setTransform( bonusLifePosition.x, bonusLifePosition.y , 0);
sb.draw(bonusLifeTexture, bonusLifePosition.x - radius, bonusLifePosition.y - radius, radius, radius);
}
} |
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Set your API Key
Map<String, String> apikey = new HashMap<>();
apikey.put("key", "AAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD");
apikey.put("secret", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
apikey.put("nonce", String.valueOf(0)); // if you get 422 code, you should increase this value.
PoloniexComm comm = new PoloniexComm(apikey);
try {
double xrpBal = comm.getBalance(PoloniexComm.COIN_XRP);
double totBal = comm.getCompleteBalance();
double btcPriceUsdt = comm.getMarketPrice(PoloniexComm.COIN_USDT, PoloniexComm.COIN_BTC);
System.out.println(""
+ "I have " + xrpBal + " XRP.\n"
+ "I have " + totBal + " BTC value in Poloniex.\n"
+ "1 BTC price is " + btcPriceUsdt + " USDT.\n"
);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
|
package com.demo.workshop.controller;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.demo.workshop.GameDemo;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.equations.Back;
/**
* Created by Ivan_Hernandez.
*/
public class UIController implements InputProcessor {
Vector3 touchPoint = new Vector3();
boolean dragging;
private Array<com.demo.workshop.ui.Button> uiCopmponents;
private com.demo.workshop.ui.Button uiSelected = null;
public UIController(Array<com.demo.workshop.ui.Button> screenUIComponents) {
this.uiCopmponents = screenUIComponents;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
touchPoint = GameDemo.getViewport().unproject(new Vector3(screenX,screenY,0));
dragging = true;
uiSelected = null;
for(com.demo.workshop.ui.Button ui : this.uiCopmponents) {
if (com.demo.workshop.utils.MathUtils.checkTouchCollision(touchPoint, ui.getBoundingRectangle())) {
uiSelected = ui;
System.out.println("Touched");
animateComponentIN(ui);
return true;
}
}
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
touchPoint = GameDemo.getViewport().unproject(new Vector3(screenX,screenY,0));
if (dragging && uiSelected != null) {
for (com.demo.workshop.ui.Button ui : this.uiCopmponents) {
if (com.demo.workshop.utils.MathUtils.checkTouchCollision(touchPoint, ui.getBoundingRectangle())) {
System.out.println("Touched");
if(ui == uiSelected) {
animateComponentOUT(ui, true);
dragging = false;
uiSelected = null;
return true;
}
}
}
}
if(uiSelected != null)
animateComponentOUT(uiSelected);
dragging = false;
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
/*
if (!dragging)
return false;
touchPoint = GameDemo.getViewport().unproject(new Vector3(screenX,screenY,0));
*/
return false;
}
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
public void animateComponentIN(com.demo.workshop.ui.Button component) {
component.setScale(1);
Tween.to(component, com.demo.workshop.utils.SpriteAccessor.SCALE_XY, 0.15f)
.target(1.15f, 1.15f)
.ease(Back.INOUT)
.start(GameDemo.getTweenManager());
System.out.println("Animate IN");
}
public void animateComponentOUT(final com.demo.workshop.ui.Button component) {
animateComponentOUT(component, false);
}
public void animateComponentOUT(final com.demo.workshop.ui.Button component, final boolean executeAction) {
Tween.to(component, com.demo.workshop.utils.SpriteAccessor.SCALE_XY, 0.2f)
.target(1f, 1f)
.ease(Back.INOUT)
.setCallback(new TweenCallback() {
@Override
public void onEvent(int i, BaseTween<?> baseTween) {
if(executeAction)
if(component instanceof com.demo.workshop.ui.Button)
((com.demo.workshop.ui.Button) component).executeAction();
}
})
.start(GameDemo.getTweenManager());
System.out.println("Animate OUT");
}
}
|
package com.limegroup.gnutella.gui.search.tests;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.frostwire.AzureusStarter;
import com.frostwire.search.CrawlPagedWebSearchPerformer;
import com.frostwire.search.SearchManager;
import com.frostwire.search.SearchManagerImpl;
import com.frostwire.search.SearchManagerListener;
import com.frostwire.search.SearchPerformer;
import com.frostwire.search.SearchResult;
import com.frostwire.search.VuzeMagnetDownloader;
import com.frostwire.search.WebSearchPerformer;
import com.frostwire.search.domainalias.DefaultDomainAliasManifestFetcher;
import com.frostwire.search.domainalias.DomainAliasManifest;
import com.frostwire.search.domainalias.DomainAliasManifestFetcherListener;
import com.limegroup.gnutella.gui.search.SearchEngine;
/**
* Performs searches on all domain aliases specified by given manifest.
*
* It will test every domain specified by the manifest, it will use the default domain
* to fetch the corresponding search engine and instantiate a search manager for each one of them.
*
* Once a search manager is there, it'll create a SearchListener which keeps track of wether or not
* the search returned any results or if it failed and it will write that down on a testScore (DomainTestScore) object for that test.
* We add all the test results to a final list of test results in case we need a summary of all the tests.
*
* The score is simply a percentage of the domains that returned results satisfactorily.
*
* @author gubatron
*
*/
public class DomainAliasManifestQA {
private static long searchTokenCounter = 1;
public static void main(String[] args) {
//Change here for a different manifest fetcher, or if you have a manifest object, just pass it to the test() method
//to begin your test.
new DefaultDomainAliasManifestFetcher(new DomainAliasManifestFetcherListener() {
@Override
public void onManifestNotFetched() {
}
@Override
public void onManifestFetched(DomainAliasManifest manifest) {
try {
test(manifest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).fetchManifest();
}
public static void test(DomainAliasManifest manifest) throws InterruptedException {
AzureusStarter.start();
Map<String, List<String>> aliases = manifest.aliases;
Set<Entry<String, List<String>>> entrySet = aliases.entrySet();
List<DomainTestScore> testScores = (List<DomainTestScore>) Collections.synchronizedList(new ArrayList<DomainTestScore>());
VuzeMagnetDownloader vuzeMagnetDownloader = new VuzeMagnetDownloader();
CrawlPagedWebSearchPerformer.setMagnetDownloader(vuzeMagnetDownloader);
for (Entry<String, List<String>> domainEntry : entrySet) {
String domainName = domainEntry.getKey();
List<String> domainAliases = domainEntry.getValue();
testDomainAliases(domainName, domainAliases, testScores);
}
AzureusStarter.getAzureusCore().stop();
}
private static void testDomainAliases(String domainName, List<String> domainAliases,List<DomainTestScore> testScores) throws InterruptedException {
SearchEngine SEARCH_ENGINE = SearchEngine.getSearchEngineByDefaultDomainName(domainName);
SEARCH_ENGINE.getDomainAliasManager().setAliases(domainAliases);
DomainTestScore testScore = new DomainTestScore(domainName, domainAliases);
CountDownLatch latch = new CountDownLatch(domainAliases.size()+1);
SearchManager searchManager = new SearchManagerImpl();
searchManager.registerListener(new SearchTestListener(testScores, testScore, latch));
//first search should be with default domain.
searchManager.perform(SEARCH_ENGINE.getPerformer(searchTokenCounter++,"love"));
for (String alias : domainAliases) {
SEARCH_ENGINE.getDomainAliasManager().setDomainNameToUse(alias);
System.out.println("Started search on " + SEARCH_ENGINE.getDomainAliasManager().getDomainNameToUse() + " in alias: " + alias);
searchManager.perform(SEARCH_ENGINE.getPerformer(searchTokenCounter++,"love"));
Thread.sleep(2000);
}
searchTokenCounter *= 10;
}
private static class DomainTestScore {
public final String originalDomainName;
public final Map<String, Boolean> domainAliasTestResults;
public DomainTestScore(String originalDomainName, List<String> domainAliases) {
this.originalDomainName = originalDomainName;
domainAliasTestResults = new HashMap<String, Boolean>();
domainAliasTestResults.put(originalDomainName, false);
for (String domainAlias : domainAliases) {
domainAliasTestResults.put(domainAlias, false);
}
}
public void recordTestResult(String domainName, boolean passed) {
domainAliasTestResults.put(domainName, passed);
}
public float getScore() {
Set<String> keySet = domainAliasTestResults.keySet();
int totalTests = domainAliasTestResults.size(); //original domain + aliases
int passed = 0;
for (String domain : keySet) {
if (domainAliasTestResults.get(domain)) {
passed++;
}
}
float result = 0;
if (totalTests > 0) {
result = (float) passed/totalTests;
}
return result;
}
@Override
public boolean equals(Object obj) {
return originalDomainName.equals(((DomainTestScore) obj).originalDomainName);
}
@Override
public int hashCode() {
return originalDomainName.hashCode();
}
}
private static class SearchTestListener implements SearchManagerListener, Runnable {
private final List<DomainTestScore> testScores;
private final DomainTestScore testScore;
private final CountDownLatch latch;
public SearchTestListener(List<DomainTestScore> testScores, DomainTestScore testScore, final CountDownLatch latch) {
this.testScores = testScores;
this.testScore = testScore;
this.latch = latch;
new Thread(this).start();
}
@Override
public void onResults(SearchPerformer performer, List<? extends SearchResult> results) {
WebSearchPerformer wsp = (WebSearchPerformer) performer;
System.out.println("onResults of "+ wsp.getDefaultDomainName() +"@" + wsp.getDomainNameToUse() + "!");
String domainName = wsp.getDomainNameToUse();
if (results != null) {
testScore.recordTestResult(domainName, true);
}
}
@Override
public void onFinished(long token) {
if (latch.getCount() > 0) {
latch.countDown();
System.out.println("Search #" + token + " finished. (latch for "+ testScore.originalDomainName + " has " + latch.getCount() + " counts left)");
}
}
@Override
public void run() {
System.out.println("SearchTestListener waiting for searches to finish...");
try {
latch.await(20,TimeUnit.SECONDS);
System.out.println("SearchTestListener done waiting...");
} catch (Throwable e) {
System.out.println("SearchTestListener latch timed out!");
}
System.out.println("Searches for " + testScore.originalDomainName + " are finished, calculating test scores:");
System.out.println("----------------------------------------------------------------------------------------");
System.out.println("Final Score: " + (testScore.getScore() * 100) + "%");
Set<Entry<String, Boolean>> entrySet = testScore.domainAliasTestResults.entrySet();
for (Entry<String,Boolean> testEntry : entrySet) {
System.out.println(" "+testScore.originalDomainName+"(@" + testEntry.getKey() + ") -> " + testEntry.getValue());
}
System.out.println("----------------------------------------------------------------------------------------");
testScores.add(testScore);
}
}
} |
import java.util.HashMap;
import java.util.Map;
public class FractionRecurring {
public static String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0)
return "0";
long numeratorLong = (long) numerator;
long denominatorLong = (long) denominator;
StringBuilder str1 = new StringBuilder();
StringBuilder str2 = new StringBuilder();
StringBuilder str3 = new StringBuilder();
Map<Long, Integer> map = new HashMap<>();
if (numeratorLong < 0 && denominatorLong > 0) {
numeratorLong *= -1;
str3.append('-');
} else if (numeratorLong > 0 && denominatorLong < 0) {
denominatorLong *= -1;
str3.append('-');
}
long divided = numeratorLong / denominatorLong;
long mod = numeratorLong % denominatorLong;
str1.append(divided);
if (mod == 0)
return str3.append(str1).toString();
str1.append('.');
numeratorLong = mod * 10;
while (numeratorLong != 0 && !map.containsKey(mod)) {
map.put(mod, str2.length());
divided = numeratorLong / denominatorLong;
str2.append(divided);
mod = numeratorLong % denominatorLong;
numeratorLong = mod * 10;
}
if (numeratorLong == 0)
return str3.append(str1).append(str2).toString();
return str3.append(str1).append(str2.insert(map.get(mod), "(")).append(")").toString();
}
public static void main(String args[]) {
System.out.println(fractionToDecimal(1, 214748364));
}
}
|
package com.github.tobby48.java.scene5.airport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;
import java.util.Vector;
/**
* 시뮬레이션에 대한 초기설정과 출력결과를 보여주는 클래스
*
* @author tobby48 2009. 06. 02
*/
public class Simulate {
/**
* 전체 시간 (여기서는 하루(86400초)
*/
private int MAX_MODEL_TIME;
/**
* 최종 결과를 저장할 ArrayList 객체
*/
private ArrayList<Plane> resultPlaneList;
/**
* Landing을 위한 Server 객체
*/
private Server arrivalServer;
/**
* Terminal을 위한 Server 객체
*/
private Server terminalServer;
/**
* Takeoff을 위한 Server 객체
*/
private Server takeoffServer;
/**
* 생성자 Main함수가 있는 클래스로부터 초기값들을 넘겨받은 뒤, 각각의 Server객체를 초기화한다.
*
* @param maxModelTime
* @param lqNs
* @param lqSt
* @param lqOt
* @param tqNs
* @param tqSt
* @param tqOt
* @param toqNs
* @param toqSt
* @param toqOt
*/
public Simulate(int maxModelTime, int lqNs, int lqSt, int lqOt, int tqNs,
int tqSt, int tqOt, int toqNs, int toqSt, int toqOt) {
// TODO Auto-generated constructor stub
this.MAX_MODEL_TIME = maxModelTime;
resultPlaneList = new ArrayList<Plane>();
arrivalServer = new Server(lqNs, lqSt, lqOt);
terminalServer = new Server(tqNs, tqSt, tqOt);
takeoffServer = new Server(toqNs, toqSt, toqOt);
}
/**
* data file 을 읽어서 arrival time 을 stack 에 추가하는 함수
*
* @param dataFile
* arrival time이 저장된 파일
*/
public void Init_Simulation(External_File dataFile) {
// TODO Auto-generated method stub
Vector<Integer> tempArrivalTime = new Vector<Integer>();
Vector<Character> tempAirplaneType = new Vector<Character>();
Integer id = new Integer(0);
/* 파일에서 arriveTime을 저장할 Stack */
Stack<Integer> arriveStack = new Stack<Integer>();
Stack<Character> airplaneStack = new Stack<Character>();
try {
/* data file 을 한 라인씩 읽어서 Stack에 저장 */
while (!dataFile.havehitEOF()) {
String[] tempArray = dataFile.getLine().split(" ");
arriveStack.add(Integer.parseInt(tempArray[0]));
airplaneStack.add(tempArray[1].charAt(0));
}
/* 정렬을 위한 임시벡터에 저장 */
while(!arriveStack.isEmpty())
tempArrivalTime.add(arriveStack.pop());
/* 정렬을 위한 임시벡터에 저장 */
while(!airplaneStack.isEmpty())
tempAirplaneType.add(airplaneStack.pop());
/* arrival time 으로 정렬 */
for (int i = 0; i < tempArrivalTime.size() - 1; i++) {
for (int j = i; j < tempArrivalTime.size(); j++) {
if (Integer.valueOf(tempArrivalTime.get(i)) > Integer.valueOf(tempArrivalTime.get(j))) {
Integer temp = tempArrivalTime.get(i);
tempArrivalTime.set(i, tempArrivalTime.get(j));
tempArrivalTime.set(j, temp);
Character tempChar = tempAirplaneType.get(i);
tempAirplaneType.set(i, tempAirplaneType.get(j));
tempAirplaneType.set(j, tempChar);
}
}
}
/* plane의 id값, 국내선인지 국제선인지 저장 */
while (id < tempArrivalTime.size()){
Plane plane = new Plane(tempArrivalTime.get(id));
plane.setId(id + 1);
plane.setAirlineType(tempAirplaneType.get(id));
resultPlaneList.add(plane);
id++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 시뮬레이션 동작을 수행하는 함수
*/
public void Run_Simulation() {
/* 초기화 */
Integer currentTime = new Integer(0);
Integer index = new Integer(0);
boolean stat = false;
// TODO Auto-generated method stub
/*
* while 구문 안쪽
* 1. 현재시간을 계속 증가
* 2. stack에 저장된 비행기의 arrival time을 가져와 arrival 대기 큐에 저장
* 3. stack에 있는 비행기를 추가하기 위해 arrival 큐에 비행기를 추가할수 있는지 여부를 체크
* 4. 비행기의 arrival(현재시간) 값 만큼 arrival queue을 업데이트 시킨다.
* 5. arrival queue에서 서비스시간 끝난 비행기에 대해서는 terminal queue로 이동(3번~5번 과정 순차적 체크)
* 6. takeoff queue까지 업데이트를 완료한 다음 1번과정 반복
*/
/* 최초 arrival time 값을 얻음 */
Plane plane = resultPlaneList.get(index);
/* 1일 동안의 비행 시뮬레이션 동작 */
while (currentTime <= MAX_MODEL_TIME) {
Plane tempPlane;
/* stack안의 arrival time을 모두 arrival 대기큐에 저장 */
if (!stat && currentTime.equals(plane.getArrivalTime())) {
arrivalServer.addPlane(plane, currentTime);
/* stack이 비어있다면 더이상 pop을 수행하지 않음 */
if (index < (resultPlaneList.size()-1))
plane = resultPlaneList.get(++index);
else
stat = true;
/* 동일한 도착시간을 가진 비행기를 처리하기 위해 현재시간을 증가시키지 않고 continue */
if(currentTime.equals(plane.getArrivalTime()))
continue;
}
/* 현재시간으로부터 각각의 Server객체들이 landing -> terminal -> takeoff 로의 이동
*
* landing 과정이 끝난 plane은 terminal로,
* terminal 과정이 끝난 plane은 takeoff로,
* takeoff 과정이 끝난 plane은 최종 plane객체들을 저장하는 ArrayList객체에 저장*/
while ((tempPlane = arrivalServer.upDate(0, currentTime)) != null)
terminalServer.addPlane(tempPlane, currentTime);
while ((tempPlane = terminalServer.upDate(1, currentTime)) != null)
takeoffServer.addPlane(tempPlane, currentTime);
while ((tempPlane = takeoffServer.upDate(2, currentTime)) != null);
currentTime++;
}
}
/**
* 시뮬레이션 결과값을 출력하는 함수
*/
public void End_Simulation() {
// TODO Auto-generated method stub
System.out.println("*******************************************");
System.out.println("*************** AIRPORT MODELING SIMULATION");
System.out.println("*******************************************");
System.out.println("\nMODELING PARAMETERS:");
System.out.println("=======================");
System.out.println("Total Time Of Simulation (Servers Operating) : "
+ MAX_MODEL_TIME + " seconds");
System.out.println("\nAirport Service\tNumber\tService Time\tServer");
System.out.println("Operation Type\tServers\tsecs.\tmin.\tScheduling");
System.out.println("===============\t=======\t============\t===========");
System.out.println("Landing Runways\t" + arrivalServer.getServerNum()
+ "\t" + arrivalServer.getServiceTime() + "\t"
+ +arrivalServer.getServiceTime() / 60 + "\t"
+ arrivalServer.getOsType());
System.out.println("Terminal Gates\t" + terminalServer.getServerNum()
+ "\t" + terminalServer.getServiceTime() + "\t"
+ +terminalServer.getServiceTime() / 60 + "\t"
+ terminalServer.getOsType());
System.out.println("Take-Off\t" + takeoffServer.getServerNum() + "\t"
+ takeoffServer.getServiceTime() + "\t"
+ +takeoffServer.getServiceTime() / 60 + "\t"
+ takeoffServer.getOsType());
System.out.println("\nINDIVIDUAL PLANE INFORMATION AT DEPARTURE: (All times in seconds)");
System.out.println("===========================================");
System.out.println("\n\tPlane\tInternational/\tTime\tTime\tLQ Wt.\tTime\tTime\tLQ Wt.\tTime\tTime\tLQ Wt.");
System.out.println("#\tID#\tDomestic Type\tIn LQ\tOut LQ\tTime\tIn LQ\tOut LQ\tTime\tIn LQ\tOut LQ\tTime");
System.out.println("==\t=====\t=============\t=====\t======\t======\t=====\t======\t======\t=====\t======\t======");
for (int i = 0; i < resultPlaneList.size(); i++) {
Plane plane = resultPlaneList.get(i);
System.out.println(i + 1 + "\t" + plane.getId() + "\t" + plane.getAirlineType() + "\t\t"
+ plane.getServiceStartTime(0) + "\t"
+ plane.getServiceEndTime(0) + "\t"
+ plane.getWaitingTime(0) + "\t"
+ plane.getServiceStartTime(1) + "\t"
+ plane.getServiceEndTime(1) + "\t"
+ plane.getWaitingTime(1) + "\t"
+ plane.getServiceStartTime(2) + "\t"
+ plane.getServiceEndTime(2) + "\t"
+ plane.getWaitingTime(2));
}
System.out.println("\nSUMMARY OF PLANE INFORMATION STATISTICS: (All times in seconds)");
System.out.println("========================================");
System.out.println("Number of Planes processed: " + resultPlaneList.size());
System.out.println("\nAirport Service\t\tTotal Wait\tAverage\t\tMaximum");
System.out.println("Operation Type\t\tTime\t\tWait Time\tWait Time");
System.out.println("===============\t\t==========\t============\t===========");
System.out.println("Landing Runways\t\t"
+ arrivalServer.getTotalWaitingTime() + "\t\t"
+ arrivalServer.getAvgWaitingTime() + "\t\t"
+ arrivalServer.getMaxWaitingTime());
System.out.println("Terminal Gates\t\t"
+ terminalServer.getTotalWaitingTime() + "\t\t"
+ terminalServer.getAvgWaitingTime() + "\t\t"
+ terminalServer.getMaxWaitingTime());
System.out.println("Take-Off Runways\t"
+ takeoffServer.getTotalWaitingTime() + "\t\t"
+ takeoffServer.getAvgWaitingTime() + "\t\t"
+ takeoffServer.getMaxWaitingTime());
System.out.println("\nSUMMARY OF SERVER INFORMATION STATISTICS: (All times in seconds)");
System.out.println("========================================");
System.out.println("\n Server Total Time Total Idle Percent");
System.out.println("Server Type # In Operation Time Idle Time");
System.out.println("================ ====== ============ =========== ==========");
System.out.println("Landing Server:");
for (int j = 0; j < arrivalServer.getServerNum(); j++) {
System.out.println("\t\t\t" + (j + 1) + "\t" + MAX_MODEL_TIME
+ "\t\t" + (MAX_MODEL_TIME - arrivalServer.getTotalIdleTime(j))
+ "\t\t" + ((MAX_MODEL_TIME - arrivalServer.getTotalIdleTime(j)) * 100 / MAX_MODEL_TIME)
+ "%");
}
System.out.println("Terminal Server:");
for (int j = 0; j < terminalServer.getServerNum(); j++) {
System.out.println("\t\t\t" + (j + 1) + "\t" + MAX_MODEL_TIME
+ "\t\t" + (MAX_MODEL_TIME - terminalServer.getTotalIdleTime(j))
+ "\t\t" + ((MAX_MODEL_TIME - terminalServer.getTotalIdleTime(j)) * 100 / MAX_MODEL_TIME)
+ "%");
}
System.out.println("Take-Off Server:");
for (int j = 0; j < takeoffServer.getServerNum(); j++) {
System.out.println("\t\t\t" + (j + 1) + "\t" + MAX_MODEL_TIME
+ "\t\t" + (MAX_MODEL_TIME - takeoffServer.getTotalIdleTime(j))
+ "\t\t" + ((MAX_MODEL_TIME - takeoffServer.getTotalIdleTime(j)) * 100 / MAX_MODEL_TIME)
+ "%");
}
}
} |
package io.oldwang.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import io.oldwang.R;
import io.oldwang.databinding.FragmentMyBinding;
/**
* 我的界面
* @author OldWang
* @date 2020/12/1
*/
public class MyFragment extends Fragment {
private FragmentMyBinding mBinding;
private Context mContext;
private boolean isShowUser = true;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_my, container, false);
mContext = getContext();
initView();
return mBinding.getRoot();
}
private void initView() {
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// 当前页面显示
isShowUser = isVisibleToUser;
}
}
|
/*
* 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.core.io.buffer;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.function.IntPredicate;
import org.springframework.util.Assert;
/**
* Provides a convenient implementation of the {@link DataBuffer} interface
* that can be overridden to adapt the delegate.
*
* <p>These methods default to calling through to the wrapped delegate object.
*
* @author Arjen Poutsma
* @since 5.2
*/
public class DataBufferWrapper implements DataBuffer {
private final DataBuffer delegate;
/**
* Create a new {@code DataBufferWrapper} that wraps the given buffer.
* @param delegate the buffer to wrap
*/
public DataBufferWrapper(DataBuffer delegate) {
Assert.notNull(delegate, "Delegate must not be null");
this.delegate = delegate;
}
/**
* Return the wrapped delegate.
*/
public DataBuffer dataBuffer() {
return this.delegate;
}
@Override
public DataBufferFactory factory() {
return this.delegate.factory();
}
@Override
public int indexOf(IntPredicate predicate, int fromIndex) {
return this.delegate.indexOf(predicate, fromIndex);
}
@Override
public int lastIndexOf(IntPredicate predicate, int fromIndex) {
return this.delegate.lastIndexOf(predicate, fromIndex);
}
@Override
public int readableByteCount() {
return this.delegate.readableByteCount();
}
@Override
public int writableByteCount() {
return this.delegate.writableByteCount();
}
@Override
public int capacity() {
return this.delegate.capacity();
}
@Override
@Deprecated
public DataBuffer capacity(int capacity) {
return this.delegate.capacity(capacity);
}
@Override
@Deprecated
public DataBuffer ensureCapacity(int capacity) {
return this.delegate.ensureCapacity(capacity);
}
@Override
public DataBuffer ensureWritable(int capacity) {
return this.delegate.ensureWritable(capacity);
}
@Override
public int readPosition() {
return this.delegate.readPosition();
}
@Override
public DataBuffer readPosition(int readPosition) {
return this.delegate.readPosition(readPosition);
}
@Override
public int writePosition() {
return this.delegate.writePosition();
}
@Override
public DataBuffer writePosition(int writePosition) {
return this.delegate.writePosition(writePosition);
}
@Override
public byte getByte(int index) {
return this.delegate.getByte(index);
}
@Override
public byte read() {
return this.delegate.read();
}
@Override
public DataBuffer read(byte[] destination) {
return this.delegate.read(destination);
}
@Override
public DataBuffer read(byte[] destination, int offset, int length) {
return this.delegate.read(destination, offset, length);
}
@Override
public DataBuffer write(byte b) {
return this.delegate.write(b);
}
@Override
public DataBuffer write(byte[] source) {
return this.delegate.write(source);
}
@Override
public DataBuffer write(byte[] source, int offset, int length) {
return this.delegate.write(source, offset, length);
}
@Override
public DataBuffer write(DataBuffer... buffers) {
return this.delegate.write(buffers);
}
@Override
public DataBuffer write(ByteBuffer... buffers) {
return this.delegate.write(buffers);
}
@Override
public DataBuffer write(CharSequence charSequence,
Charset charset) {
return this.delegate.write(charSequence, charset);
}
@Override
@Deprecated
public DataBuffer slice(int index, int length) {
return this.delegate.slice(index, length);
}
@Override
@Deprecated
public DataBuffer retainedSlice(int index, int length) {
return this.delegate.retainedSlice(index, length);
}
@Override
public DataBuffer split(int index) {
return this.delegate.split(index);
}
@Override
@Deprecated
public ByteBuffer asByteBuffer() {
return this.delegate.asByteBuffer();
}
@Override
@Deprecated
public ByteBuffer asByteBuffer(int index, int length) {
return this.delegate.asByteBuffer(index, length);
}
@Override
@Deprecated
public ByteBuffer toByteBuffer() {
return this.delegate.toByteBuffer();
}
@Override
@Deprecated
public ByteBuffer toByteBuffer(int index, int length) {
return this.delegate.toByteBuffer(index, length);
}
@Override
public void toByteBuffer(ByteBuffer dest) {
this.delegate.toByteBuffer(dest);
}
@Override
public void toByteBuffer(int srcPos, ByteBuffer dest, int destPos, int length) {
this.delegate.toByteBuffer(srcPos, dest, destPos, length);
}
@Override
public ByteBufferIterator readableByteBuffers() {
return this.delegate.readableByteBuffers();
}
@Override
public ByteBufferIterator writableByteBuffers() {
return this.delegate.writableByteBuffers();
}
@Override
public InputStream asInputStream() {
return this.delegate.asInputStream();
}
@Override
public InputStream asInputStream(boolean releaseOnClose) {
return this.delegate.asInputStream(releaseOnClose);
}
@Override
public OutputStream asOutputStream() {
return this.delegate.asOutputStream();
}
@Override
public String toString(Charset charset) {
return this.delegate.toString(charset);
}
@Override
public String toString(int index, int length, Charset charset) {
return this.delegate.toString(index, length, charset);
}
}
|
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class CSX_358_HW1_16103094 {
private static Scanner ss;
public static void main(String[] arg) throws IOException {
int[] arr = new int[15];
File file = new File("C:\\Users\\hp\\Desktop\\HW1-data.txt");
Scanner sc = new Scanner(file);
PrintWriter writer = new PrintWriter("C:\\Users\\hp\\Desktop\\out.txt", "UTF-8");
writer.println("* The Student Report Output File");
writer.println(" ------------------------------\n");
writer.println("Stdnt Id Ex -------- Assignments -------- Tot Mi Fin CL Pts Pct Gr");
writer.println("-------- -- ----------------------------- --- -- --- -- --- --- --");
while (sc.hasNextLine()) {
String St = sc.nextLine();
ss = new Scanner(St);
int i = 0;
while (ss.hasNextInt()) {
arr[i] = ss.nextInt();
i++;
}
//create object of type HWobject class
HWobject obj1 = new HWobject(arr);
//call assgn() function
String stres = obj1.assgn();
//write string returned by assgn() in output file
writer.println(stres);
}
writer.println("\n* Summary Report File");
writer.println(" -------------------\n");
//create object of type HWobject class
HWobject obj1 = new HWobject();
writer.println(obj1.Part2());
sc.close();
writer.close();
}
}
|
/*******************************************************************************
* Copyright 2013 SecureKey Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.openmidaas.library.common.network;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.openmidaas.library.MIDaaS;
import org.openmidaas.library.MIDaaS.VerifiedAttributeBundleCallback;
import org.openmidaas.library.authentication.AuthenticationManager;
import org.openmidaas.library.authentication.core.AccessToken;
import org.openmidaas.library.common.Constants;
import org.openmidaas.library.common.Constants.ATTRIBUTE_STATE;
import org.openmidaas.library.model.SubjectToken;
import org.openmidaas.library.model.core.AbstractAttribute;
import org.openmidaas.library.model.core.MIDaaSError;
import org.openmidaas.library.model.core.MIDaaSException;
import com.loopj.android.http.AsyncHttpResponseHandler;
public class AVSServer {
private static String TAG = "AVSServer";
private static boolean SERVER_WITH_SSL = false;
private static HashMap<String, String> headers = new HashMap<String, String>();
public static void setWithSSL(boolean val) {
SERVER_WITH_SSL = val;
}
public static void getAuthToken(SubjectToken subjectToken, String deviceToken, AsyncHttpResponseHandler responseHandler) throws JSONException {
if(subjectToken == null) {
MIDaaS.logError(TAG, "Subject token is missing");
throw new IllegalArgumentException("Subject token is missing");
}
if(deviceToken == null || deviceToken.isEmpty()) {
MIDaaS.logError(TAG, "Device token is missing");
throw new IllegalArgumentException("Device token is missing");
}
JSONObject data = new JSONObject();
data.put("subjectToken", subjectToken.getSignedToken());
data.put("deviceToken", deviceToken);
ConnectionManager.postRequest(SERVER_WITH_SSL, Constants.TOKEN_URL, null, data, responseHandler);
}
/**
* Registers a device with the AVS server
* @param deviceAuthToken the device authentication token
* @param responseHandler the callback once registration is complete
* @throws JSONException
*/
public static void registerDevice(String deviceToken,
AsyncHttpResponseHandler responseHandler) throws JSONException {
if(deviceToken == null || deviceToken.isEmpty()) {
throw new IllegalArgumentException("Device auth token is missing");
}
if(responseHandler == null) {
throw new IllegalArgumentException("Callback is missing");
}
ConnectionManager.postRequest(SERVER_WITH_SSL, Constants.REGISTRATION_URL, null, new JSONObject().put(Constants.AVSServerJSONKeys.DEVICE_TOKEN, deviceToken), responseHandler);
}
/**
* Starts verification for the specified attribute
* @param attribute the attribute for which verification needs to be started
* @param responseHandler the callback once verification has been started
* @throws JSONException
*/
public static void startAttributeVerification(AbstractAttribute<?> attribute,
AsyncHttpResponseHandler responseHandler) throws JSONException {
if(attribute == null) {
throw new IllegalArgumentException("Attribute is missing");
}
if(responseHandler == null) {
throw new IllegalArgumentException("Callback is missing");
}
AccessToken token = AuthenticationManager.getInstance().getAccessToken();
if(token == null) {
MIDaaS.logError(TAG, "Error getting access token. Access token is null");
responseHandler.onFailure(new MIDaaSException(MIDaaSError.ERROR_AUTHENTICATING_DEVICE), "");
} else {
JSONObject postData = getCommonAttributeDataAsJSONObject(attribute);
if(attribute.getVerificationMethod() != null && !(attribute.getVerificationMethod().isEmpty())) {
postData.put(Constants.AVSServerJSONKeys.VERIFICATION_METHOD, attribute.getVerificationMethod());
}
ConnectionManager.postRequest(SERVER_WITH_SSL, Constants.INIT_AUTH_URL, getAuthHeader(token), postData, responseHandler);
}
}
/**
* Completes verification for the specified attribute
* @param attribute the attribute for which verification needs to be completed
* @param verificationCode the verification code
* @param responseHandler the callback once verification is completed
* @throws JSONException
*/
public static void completeAttributeVerification(AbstractAttribute<?> attribute, String verificationCode,
AsyncHttpResponseHandler responseHandler) throws JSONException {
if(attribute == null) {
throw new IllegalArgumentException("Attribute is missing");
}
if(responseHandler == null) {
throw new IllegalArgumentException("Callback is missing");
}
AccessToken token = AuthenticationManager.getInstance().getAccessToken();
if(token == null) {
MIDaaS.logError(TAG, "Error getting access token. Access token is null");
responseHandler.onFailure(new MIDaaSException(MIDaaSError.ERROR_AUTHENTICATING_DEVICE), "");
} else {
JSONObject postData = getCommonAttributeDataAsJSONObject(attribute);
postData.put(Constants.AVSServerJSONKeys.CODE, verificationCode);
postData.put(Constants.AVSServerJSONKeys.VERIFICATION_TOKEN, attribute.getPendingData());
ConnectionManager.postRequest(SERVER_WITH_SSL, Constants.COMPLETE_AUTH_URL, getAuthHeader(token), postData, responseHandler);
}
}
/**
* Bundles the attributes for the app.
* @param clientId
* @param state
* @param verifiedAttributeMap
* @param responseHandler
* @throws JSONException
*/
public static void bundleVerifiedAttributes(String clientId, String state, Map<String, AbstractAttribute<?>> verifiedAttributeMap,
final VerifiedAttributeBundleCallback callback) {
JSONObject data = new JSONObject();
try {
data.put(Constants.RequestKeys.CLIENT_ID, clientId);
data.put(Constants.AttributeBundleKeys.ATTRIBUTES, new JSONObject());
if(state != null && !state.equals("")) {
data.put(Constants.RequestKeys.STATE, state);
}
for(Map.Entry<String, AbstractAttribute<?>> entry: verifiedAttributeMap.entrySet()) {
if(entry.getValue() != null) {
if(entry.getValue().getState().equals(ATTRIBUTE_STATE.VERIFIED)) {
if(entry.getValue().getSignedToken() != null) {
data.getJSONObject(Constants.AttributeBundleKeys.ATTRIBUTES).put(entry.getKey(), entry.getValue().getSignedToken());
} else {
callback.onError(new MIDaaSException(MIDaaSError.ATTRIBUTE_VALUE_ERROR));
}
} else {
MIDaaS.logError(TAG, "Trying to bundle an attribute that's not in a verified state.");
callback.onError(new MIDaaSException(MIDaaSError.ATTRIBUTE_STATE_ERROR));
}
} else {
MIDaaS.logError(TAG, "No entry value for the attribute " + entry.getKey());
callback.onError(new MIDaaSException(MIDaaSError.ATTRIBUTE_VALUE_ERROR));
return;
}
}
} catch(JSONException e) {
callback.onError(new MIDaaSException(MIDaaSError.INTERNAL_LIBRARY_ERROR));
}
AccessToken token = AuthenticationManager.getInstance().getAccessToken();
if(token == null) {
MIDaaS.logError(TAG, "Error getting access token. Access token is null");
callback.onError(new MIDaaSException(MIDaaSError.ERROR_AUTHENTICATING_DEVICE));
} else {
ConnectionManager.postRequest(SERVER_WITH_SSL, Constants.BUNDLE_ATTRIBUTES_URL, getAuthHeader(token), data, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
if(response == null || response.isEmpty()) {
MIDaaS.logError(TAG, "Server responded is empty.");
callback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
} else {
callback.onSuccess(response);
}
}
@Override
public void onFailure(Throwable e, String response){
MIDaaS.logError(TAG, "Server responded with error");
callback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
}
});
}
}
/**
* Helper method to get the authorization header
* @param token - the access token
* @return - the HTTP Authorization Bearer header
*/
private static HashMap<String, String> getAuthHeader(AccessToken token) {
headers.clear();
headers.put("Authorization", "Bearer "+token.toString());
return headers;
}
/**
* Helper method. Returns the type and value of an attribute in a JSON object
* @param attribute the attribute
* @return JSONObject containing type and value of the attribute
* @throws JSONException
*/
private static JSONObject getCommonAttributeDataAsJSONObject(AbstractAttribute<?> attribute) throws JSONException{
JSONObject postData = new JSONObject();
postData.put(Constants.AVSServerJSONKeys.TYPE, attribute.getName());
postData.put(Constants.AVSServerJSONKeys.VALUE, attribute.getValue());
return postData;
}
}
|
package com.example.jersey;
import java.util.ArrayList;
public class Signal {
private int type = 0;
private ArrayList<String> names;
public Signal(ArrayList<String> names){
this.names=names;
}
} |
package loecraftpack.packet;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.network.packet.Packet250CustomPayload;
public class PacketHelper
{
public static Packet250CustomPayload Make(String channel, Object... objects)
{
int bufferSize = 0;
for(Object o : objects)
{
Class clazz = o.getClass();
if (clazz == Byte.class)
bufferSize += 1;
else if (clazz == Integer.class)
bufferSize += 4;
else if (clazz == Float.class)
bufferSize += 4;
else if (clazz == Double.class)
bufferSize += 8;
else if (clazz == Long.class)
bufferSize += 8;
else if (clazz == String.class)
bufferSize += 2 + ((String)o).length()*2;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(bufferSize);
DataOutputStream outputStream = new DataOutputStream(bos);
try
{
for(Object o : objects)
{
Class clazz = o.getClass();
if (clazz == Byte.class)
outputStream.writeByte((Byte)o);
else if (clazz == Integer.class)
outputStream.writeInt((Integer)o);
else if (clazz == Float.class)
outputStream.writeFloat((Float)o);
else if (clazz == Double.class)
outputStream.writeDouble((Double)o);
else if (clazz == Long.class)
outputStream.writeLong((Long)o);
else if (clazz == String.class)
{
outputStream.writeShort(((String)o).length());
outputStream.writeChars((String)o);
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
Packet250CustomPayload packet = new Packet250CustomPayload(channel, bos.toByteArray());
return packet;
}
public static String readString(DataInputStream data)
{
StringBuilder str = new StringBuilder();
try
{
if (data.available() < 2)
return "";
short length = data.readShort();
for(int i = 0; i < length; i++)
{
str.append(data.readChar());
if (data.available() < 2)
break;
}
return str.toString();
}
catch(IOException e)
{
return "";
}
}
}
|
package com.cdkj.manager.system.dao;
import com.cdkj.common.base.model.dao.BaseMapper;
import com.cdkj.model.system.pojo.SysPermission;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface SysPermissionMapper extends BaseMapper<SysPermission, String> {
/**
* 获取用户权限字符串集合
* @param userId 用户
* @return 权限集
*/
List<String> listUserPerms(@Param(value = "userId") String userId);
/**
* 查询用户的权限清单
*
* @param userId 用户ID
* @return 权限清单
*/
List<SysPermission> listUserPermission(@Param(value = "userId") String userId);
/**
* 查询角色的权限清单
*
* @param roleId 角色ID
* @return 权限清单
*/
List<String> listRoleIdPermission(@Param(value = "roleId") String roleId);
/**
* 查询所有的有效权限字符串
*
* @return 权限清单
*/
List<String> listAllPerms();
/**
* 查询所有的有效权限
*
* @return 权限清单
*/
List<SysPermission> listAllPermission();
} |
package be.openclinic.finance;
public class InsuranceRule {
String insurarUid;
String prestationUid;
double quantity;
double days;
public String getInsurarUid() {
return insurarUid;
}
public void setInsurarUid(String insurarUid) {
this.insurarUid = insurarUid;
}
public String getPrestationUid() {
return prestationUid;
}
public void setPrestationUid(String prestationUid) {
this.prestationUid = prestationUid;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getDays() {
return days;
}
public void setDays(double days) {
this.days = days;
}
public InsuranceRule(String insurarUid, String prestationUid,
double quantity, double days) {
super();
this.insurarUid = insurarUid;
this.prestationUid = prestationUid;
this.quantity = quantity;
this.days = days;
}
}
|
package com.ymall.annotation;
import java.lang.annotation.*;
/**
* Created by zc on 2017/6/13.
* 需要管理员权限注解
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AdminReqired {
boolean validate() default true;
}
|
package com.marvell.updater;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.marvell.updater.net.DownloadThread;
import com.marvell.updater.net.DownloadThread.DownloadListener;
import com.marvell.updater.utils.Constants;
public class DownloadService extends Service {
private static final String TAG = "DownloadService";
public static final int DOWNLOAD_STARTED = 0;
public static final int DOWNLOAD_FINISH = 1;
public static final int DOWNLOAD_PERCENT = 2;
public static final int NETWORK_ERROR = 3;
public static final int SYSTEM_ERROR = 4;
private ArrayList<Thread> mDownloadList = new ArrayList<Thread>();
private DownloadThread mDownloadThread;
private String mLocalPath;
private NotificationManager mNotificationManager;
private Notification mNotification;
private long mTotalSize;
private long mDownloadSize;
private int mPercent;
private String mModel;
private String mBranch;
private String mDate;
private DownloadServiceListener mListener;
private Binder mLocalBinder = new LocalBinder();
public class LocalBinder extends Binder {
DownloadService getService() {
return DownloadService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
if (Constants.LOG_ON) Log.d(TAG, "onBind");
return mLocalBinder;
}
public void onCreate() {
super.onCreate();
if (Constants.LOG_ON) Log.d(TAG, "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (Constants.LOG_ON) Log.d(TAG, "onStart");
if (mDownloadList.size() > 0) {
Toast.makeText(DownloadService.this, R.string.downloading_alert, Toast.LENGTH_SHORT).show();
return;
}
String url = intent.getStringExtra(Constants.KEY_OTA_PATH);
mModel = intent.getStringExtra(Constants.TAG_MODEL);
mBranch = intent.getStringExtra(Constants.TAG_BRANCH);
mDate = intent.getStringExtra(Constants.TAG_DATE);
mDownloadThread = new DownloadThread(url);
mDownloadList.add(mDownloadThread);
mDownloadThread.setOnDownloadListener(new OtaDownloadListener());
mDownloadThread.start();
}
public void cancel() {
if(mDownloadThread != null && mDownloadThread.isAlive()) {
mDownloadThread.cancel();
mDownloadList.clear();
}
if (mNotificationManager != null) {
mNotificationManager.cancel(TAG, 1024);
}
}
public void setListener(DownloadServiceListener listener) {
this.mListener = listener;
}
public class OtaDownloadListener implements DownloadListener {
public void onDownloadFinish(String localPath) {
mDownloadList.clear();
mLocalPath = localPath;
if(mListener != null) {
mListener.onDownloadFinish();
}
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
}
public void onNetworkException() {
mHandler.sendEmptyMessage(NETWORK_ERROR);
}
public void onDownloadStarted() {
mHandler.sendEmptyMessage(DOWNLOAD_STARTED);
}
public void onDownloadPercent(int percent) {
if(mListener != null) {
mListener.onDownloadPercent(percent);
}
mPercent = percent;
mHandler.sendEmptyMessage(DOWNLOAD_PERCENT);
}
}
private Handler mHandler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case DOWNLOAD_FINISH:
if (mNotificationManager != null) {
mNotificationManager.cancel(TAG, 1024);
}
if (Constants.LOG_ON) Log.d(TAG, "=download finish");
Intent intent = new Intent("com.marvell.intent.UPDATE_CONFIRM");
intent.putExtra(Constants.KEY_OTA_PATH, mLocalPath);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
stopSelf();
break;
case DOWNLOAD_STARTED:
if (Constants.LOG_ON) Log.d(TAG, "=download started");
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotification = new Notification();
mNotification.icon = R.drawable.download_icon;
mNotification.contentView = new RemoteViews(getPackageName(), R.layout.download_notification);
Intent intent1 = new Intent(DownloadService.this, DownloadActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent1.putExtra(Constants.TAG_MODEL, mModel);
intent1.putExtra(Constants.TAG_BRANCH, mBranch);
intent1.putExtra(Constants.TAG_DATE, mDate);
PendingIntent contentIntent = PendingIntent.getActivity(DownloadService.this, 0, intent1, 0);
mNotification.contentIntent = contentIntent;
mNotification.contentView.setProgressBar(R.id.progress, 100, mPercent, false);
mNotification.contentView.setTextViewText(R.id.title, mDate);
mNotification.contentView.setTextViewText(R.id.percent, mPercent + "%");
mNotificationManager.notify(TAG, 1024, mNotification);
case DOWNLOAD_PERCENT:
if (Constants.LOG_ON) Log.d(TAG, "====mPercent = " + mPercent);
mNotification.contentView.setProgressBar(R.id.progress, 100, mPercent, false);
mNotification.contentView.setTextViewText(R.id.percent, mPercent + "%");
mNotificationManager.notify(TAG, 1024, mNotification);
break;
case NETWORK_ERROR:
Toast.makeText(DownloadService.this, R.string.network_error, Toast.LENGTH_SHORT).show();
break;
}
}
};
public interface DownloadServiceListener {
public void onDownloadPercent(int percent);
public void onDownloadFinish();
}
}
|
package co.sblock.events.listeners.inventory;
import co.sblock.Sblock;
import co.sblock.captcha.Captcha;
import co.sblock.captcha.CruxiteDowel;
import co.sblock.chat.Language;
import co.sblock.events.Events;
import co.sblock.events.listeners.SblockListener;
import co.sblock.machines.Machines;
import co.sblock.utilities.InventoryUtils;
import co.sblock.utilities.PermissionUtils;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
/**
* Listener for CraftItemEvents.
*
* @author Jikoo
*/
public class CraftItemListener extends SblockListener {
private final Events events;
private final Language lang;
private final Machines machines;
public CraftItemListener(Sblock plugin) {
super(plugin);
this.events = plugin.getModule(Events.class);
this.lang = plugin.getModule(Language.class);
this.machines = plugin.getModule(Machines.class);
PermissionUtils.addParent("sblock.events.creative.unfiltered", "sblock.felt");
}
/**
* EventHandler for CraftItemEvents on monitor priority.
*
* @param event the CraftItemEvent
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void onCraftItemMonitor(final CraftItemEvent event) {
if (event.getClick().isShiftClick()) {
new BukkitRunnable() {
@Override
public void run() {
((Player) event.getWhoClicked()).updateInventory();
}
}.runTask(getPlugin());
}
// TODO if Compounding Unionizer, set recipe
}
/**
* EventHandler for CraftItemEvents.
*
* @param event the CraftItemEvent
*/
@EventHandler(ignoreCancelled = true)
public void onCraftItem(final CraftItemEvent event) {
if (event.getWhoClicked().getGameMode() == GameMode.CREATIVE
&& !event.getWhoClicked().hasPermission("sblock.events.creative.unfiltered")
&& events.getCreativeBlacklist().contains(event.getCurrentItem().getType())) {
event.setCancelled(true);
return;
}
for (ItemStack is : event.getInventory().getMatrix()) {
if (is == null) {
continue;
}
Player clicked = (Player) event.getWhoClicked();
if (Captcha.isCard(is) || CruxiteDowel.isDowel(is)) {
event.setCancelled(true);
clicked.sendMessage(lang.getValue("events.craft.captcha"));
return;
}
for (ItemStack is1 : InventoryUtils.getUniqueItems(getPlugin())) {
if (is1.isSimilar(is)) {
event.setCancelled(true);
if (is.getItemMeta().hasDisplayName()) {
clicked.sendMessage(lang.getValue("events.craft.unique")
.replace("{PARAMETER}", is.getItemMeta().getDisplayName()));
}
return;
}
}
}
}
}
|
package com.tanon.abedjinan.springbootvue.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
import com.tanon.abedjinan.springbootvue.model.Todo;
import com.tanon.abedjinan.springbootvue.utils.LinkDTO;
import com.tanon.abedjinan.springbootvue.utils.TodoDTO;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface TodoMapper {
@Mapping(source = "id", target = "value")
TodoDTO toDTO(Todo todo);
@InheritInverseConfiguration
@Mapping(target = "id", ignore = true)
void fromDTO(TodoDTO dto, @MappingTarget Todo todo);
default LinkDTO todoToLinkDTO(Todo todo) {
return todo.asLink();
}
}
|
package com.lemonread.english.dagger2.component;
import android.app.Activity;
import com.lemonread.english.dagger2.module.ActivityModule;
import com.lemonread.english.dagger2.scope.ActivityScope;
import com.lemonread.english.demo.TestActivity;
import dagger.Component;
/**
* @desc
* @author zhao
* @time 2019/3/5 16:15
*/
@ActivityScope
@Component(modules = ActivityModule.class)
public interface ActivityComponent {
Activity getActivity();
void inject(TestActivity testActivity);
}
|
package net.droidlabs.viking.bindings.map.managers;
import com.google.android.gms.maps.GoogleMap;
import com.google.maps.android.clustering.ClusterItem;
import com.google.maps.android.clustering.ClusterManager;
public class ClusterItemManager<T extends ClusterItem>
extends MapEntityManagerBase<T> {
private ClusterManager<T> clusterManager;
public ClusterItemManager(MapResolver mapResolver, ClusterManager<T> clusterManager) {
super(mapResolver);
this.clusterManager = clusterManager;
}
@Override
protected T addToMap(T item, GoogleMap googleMap) {
clusterManager.addItem(item);
return item;
}
@Override
protected void removeFromMap(T entity, GoogleMap googleMap) {
clusterManager.removeItem(entity);
}
@Override
protected void updateOnMap(T entity, T item, GoogleMap googleMap) {
clusterManager.removeItem(entity);
clusterManager.addItem(item);
}
}
|
package com.spring.professional.exam.tutorial.module03.question02.standalone;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import com.spring.professional.exam.tutorial.module03.question02.standalone.service.EmployeeService;
@ComponentScan
public class Runner {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Runner.class);
context.registerShutdownHook();
EmployeeService employeeService = context.getBean(EmployeeService.class);
employeeService.printReport();
}
}
|
package ru.gnkoshelev.jbreak2018.perf_tests.strings;
import java.text.MessageFormat;
/**
* Created by kgn on 18.03.2018.
*/
public class MetricsFormat {
public static String formatThroughPattern(String metrics, int value, long timestamp) {
return String.format(
"%s %d %d",
metrics, value, timestamp);
}
public static String formatThroughConcatenation(String metrics, int value, long timestamp) {
return metrics + " " + value + " " + timestamp;
}
public static String formatThroughBuilder(String metrics, int value, long timestamp) {
return new StringBuilder(metrics)
.append(" ")
.append(value)
.append(" ")
.append(timestamp)
.toString();
}
public static String formatThroughMessageFormat(String metrics, int value, long timestamp) {
return MessageFormat.format(
"{0} {1} {2}",
metrics, String.valueOf(value), String.valueOf(timestamp));
}
}
|
package com.example.demo.exercise;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author qianchen
* @date 2020/1/9 15:47
*/
public class Proxy1 implements InvocationHandler {
/** 真实的对象 */
private Object target;
/**
* 绑定一个委托对象并返回一个代理对象
*
* @param target
* @return
*/
public Object bind(Object target) {
this.target = target;
Object proxy =
Proxy.newProxyInstance(
target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
return proxy;
}
/**
* 通过代理对象调用方法首先进入这个方法
* @param proxy 代理对象
* @param method 被调用方法
* @param args 方法参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("我是JDK代理");
Object result;
// 反射方法调用前
System.out.println("开始调用方法");
// 执行方法,相当于调用Impl的sayHello方法
result = method.invoke(target, "World");
// 反射方法调用后
System.out.println("调用方法完成");
return result;
}
}
|
package com.dq.police.controller.actions.Related;
import com.dq.police.controller.Action;
import com.dq.police.helpers.ConstraintsUtil;
import com.dq.police.model.PersistenceManager;
import com.dq.police.model.entities.Related;
import com.dq.police.view.View;
import lombok.AllArgsConstructor;
import java.util.List;
@AllArgsConstructor
public class FindRelatedAction extends Action {
private PersistenceManager persistence;
private View view;
@Override
public String execute() {
String id = view.getPropertyCancellable("identifier");
String val = view.getPropertyCancellable("identifier value");
List<String> results;
try {
results = persistence.find(id, Integer.valueOf(val), Related.class);
} catch (NumberFormatException e) {
results = persistence.find(id, val, Related.class);
}
view.showGroup("Related", results);
return ConstraintsUtil.OPERATION_SUCCESS_MESSAGE;
}
@Override
public String getName() {
return "Find Related";
}
}
|
package com.its.xfwdata.dao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.its.xfwdata.model.City;
import com.its.xfwdata.model.Weather;
public class WeatherDaoImpl implements WeatherDao {
private SqlSessionFactory sessionFactory = SessionFactory.getInstance()
.getSqlSessionFactory();
public List<Weather> selectAll() {
List<Weather> weatherList = new ArrayList<Weather>();
SqlSession session = null;
try {
session = sessionFactory.openSession();
weatherList = session.selectList("com.its.xfwdata.dao.WeatherDao.selectAll");
}catch (Exception e) {
System.out.println("selectAll Exception happened :"+e.getMessage());
} finally {
session.close();
}
return weatherList;
}
public List<Weather> GetEntityByDatetime(String date,long updateTime) {
List<Weather> weatherList = null;
SqlSession session = null;
try {
Weather args = new Weather();
args.setWeatherDate(date);
args.setUpdatetime(updateTime);
session = sessionFactory.openSession();
weatherList = session.selectList("com.its.xfwdata.dao.WeatherDao.getEntityByDatetime",args);
}catch (Exception e) {
System.out.println("selectAll Exception happened :"+e.getMessage());
} finally {
session.close();
}
return weatherList;
}
public int insert(Weather weather) {
SqlSession session = null;
int newId = 0;
try {
session = sessionFactory.openSession();
newId = session.insert("com.its.xfwdata.dao.WeatherDao.insert", weather);
session.commit();
} catch (Exception e) {
System.out.println("insert Exception happened :"+e.getMessage());
} finally {
session.close();
return newId;
}
}
public boolean delete(String citycode) {
SqlSession session = null;
boolean issuccess = false;
try {
session = sessionFactory.openSession();
session.delete("com.its.xfwdata.dao.WeatherDao.delete", citycode);
session.commit();
issuccess = true;
}catch (Exception e) {
System.out.println("delete Exception happened :"+e.getMessage());
} finally {
session.close();
return issuccess;
}
}
}
|
package ch.bfh.bti7301.w2013.battleship.gui;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.transform.Scale;
import ch.bfh.bti7301.w2013.battleship.game.Board;
import ch.bfh.bti7301.w2013.battleship.game.Board.BoardSizeListener;
import ch.bfh.bti7301.w2013.battleship.game.BoardListener;
import ch.bfh.bti7301.w2013.battleship.game.Coordinates;
import ch.bfh.bti7301.w2013.battleship.game.Game;
import ch.bfh.bti7301.w2013.battleship.game.Missile;
import ch.bfh.bti7301.w2013.battleship.game.Missile.MissileState;
import ch.bfh.bti7301.w2013.battleship.game.Ship;
public class BoardView extends Parent {
public static final int SIZE = 40;
private Map<Coordinates, MissileView> missileViews = new HashMap<>();
private List<ShipView> shipViews = new LinkedList<>();
private Group ships = new Group();
private Group missiles = new Group();
private double scaleFactor;
private Scale scale = new Scale();
private boolean blocked = false;
public BoardView(Game game, BoardType type) {
final Board board = type.getBoard(game);
draw(board);
// This is for the opponent's board. This has to move somewhere else
// later, I think
switch (type) {
case OPPONENT:
setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
if (blocked)
return;
else
blocked = true;
Missile m = new Missile(getCoordinates(e.getX(), e.getY()));
drawMissile(m);
try {
board.placeMissile(m);
} catch (RuntimeException r) {
r.printStackTrace();
blocked = false;
missileViews.get(m.getCoordinates()).setVisible(false);
}
}
});
break;
case LOCAL:
setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
final ShipView sv = getShipView(e);
if (sv == null)
return;
final double dx = e.getSceneX() / scaleFactor
- sv.getLayoutX();
final double dy = e.getSceneY() / scaleFactor
- sv.getLayoutY();
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
sv.setLayoutX(me.getSceneX() / scaleFactor - dx);
sv.setLayoutY(me.getSceneY() / scaleFactor - dy);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
Coordinates c = getCoordinates(sv.getLayoutX()
- getLayoutX(), sv.getLayoutY()
- getLayoutY());
Ship s = sv.getShip();
try {
if (c.equals(s.getStartCoordinates())) {
// this one was just a click
if (me.getButton() == MouseButton.PRIMARY)
board.getBoardSetup().moveShip(s,
s.getStartCoordinates(),
s.getDirection().rotateCCW());
else
board.getBoardSetup().moveShip(s,
s.getStartCoordinates(),
s.getDirection().rotateCW());
} else {
// this was an actual move
board.getBoardSetup().moveShip(s, c,
s.getDirection());
}
} catch (RuntimeException ignore) {
// The ship will be reset
ignore.printStackTrace();
}
sv.update();
sv.relocate(getX(s.getStartCoordinates()),
getY(s.getStartCoordinates()));
sv.setOnMouseDragged(null);
sv.setOnMouseReleased(null);
}
});
}
});
break;
}
board.addBoardListener(new BoardListener() {
@Override
public void stateChanged(final Missile m) {
Platform.runLater(new Runnable() {
@Override
public void run() {
// javaFX operations should go here
MissileView mv = missileViews.get(m.getCoordinates());
if (mv != null)
mv.update(m);
else
drawMissile(m);
if (m.getSunkShip() != null) {
addShip(m.getSunkShip());
}
if (m.getMissileState() != MissileState.FIRED)
blocked = false;
}
});
}
});
board.addSizeListener(new BoardSizeListener() {
@Override
public void onSizeChanged(int oldSize, int newSize) {
Platform.runLater(new Runnable() {
@Override
public void run() {
missileViews.clear();
missiles.getChildren().clear();
shipViews.clear();
ships.getChildren().clear();
Platform.runLater(new Runnable() {
@Override
public void run() {
scaleFactor = 14.4 / board.getBoardSize();
scale.setX(scaleFactor);
scale.setY(scaleFactor);
getChildren().clear();
draw(board);
}
});
}
});
}
});
scaleFactor = 14.4 / board.getBoardSize();
scale.setX(scaleFactor);
scale.setY(scaleFactor);
getTransforms().add(scale);
}
private void draw(Board board) {
final int rows, columns;
rows = columns = board.getBoardSize();
getChildren().add(getWater(rows, columns));
for (int i = 0; i <= rows; i++) {
getChildren().add(getLine(i * SIZE, 0, i * SIZE, SIZE * columns));
}
for (int i = 0; i <= columns; i++) {
getChildren().add(getLine(0, i * SIZE, SIZE * rows, i * SIZE));
}
getChildren().add(ships);
getChildren().add(missiles);
for (Ship ship : board.getPlacedShips()) {
addShip(ship);
}
for (Missile missile : board.getPlacedMissiles()) {
drawMissile(missile);
}
}
private ShipView getShipView(MouseEvent e) {
for (ShipView v : shipViews) {
if (v.getBoundsInParent().contains(e.getX(), e.getY())) {
return v;
}
}
return null;
}
public void addShip(Ship ship) {
ShipView sv = new ShipView(ship);
moveShip(sv, ship);
ships.getChildren().add(sv);
shipViews.add(sv);
}
private void moveShip(ShipView sv, Ship ship) {
sv.relocate(getX(ship.getStartCoordinates()),
getY(ship.getStartCoordinates()));
}
public Coordinates getCoordinates(double x, double y) {
return new Coordinates((int) (x / SIZE) + 1, (int) (y / SIZE) + 1);
}
private void drawMissile(Missile missile) {
MissileView mv = new MissileView(missile);
mv.relocate(getX(missile.getCoordinates()),
getY(missile.getCoordinates()));
missiles.getChildren().add(mv);
missileViews.put(missile.getCoordinates(), mv);
}
private double getX(Coordinates c) {
return SIZE * (c.x - 1);
}
private double getY(Coordinates c) {
return SIZE * (c.y - 1);
}
private Shape getWater(int rows, int columns) {
Rectangle water = new Rectangle(columns * SIZE, rows * SIZE);
water.setFill(Color.LIGHTBLUE);
return water;
}
private Line getLine(double x1, double y1, double x2, double y2) {
Line line = new Line(x1, y1, x2, y2);
line.setStrokeWidth(0.1);
return line;
}
public double getScaleFactor() {
return scaleFactor;
}
public static enum BoardType {
LOCAL, OPPONENT;
private Board getBoard(Game game) {
switch (this) {
case LOCAL:
return game.getLocalPlayer().getBoard();
case OPPONENT:
return game.getOpponent().getBoard();
}
throw new RuntimeException("This mustn't happen ;)");
}
}
}
|
package com.application.settings.orginal;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/**
* Created by json2pojo
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Fujifilm {
private String inplane;
private String outplane;
private String lockangle;
private String locksize;
private String detectmode;
private String processingmode;
private Long facesize;
private Long thresh;
private Long maxfacenumber;
public String getInplane() {
return inplane;
}
public void setInplane(String inplane) {
this.inplane = inplane;
}
public String getOutplane() {
return outplane;
}
public void setOutplane(String outplane) {
this.outplane = outplane;
}
public String getLockangle() {
return lockangle;
}
public void setLockangle(String lockangle) {
this.lockangle = lockangle;
}
public String getLocksize() {
return locksize;
}
public void setLocksize(String locksize) {
this.locksize = locksize;
}
public String getDetectmode() {
return detectmode;
}
public void setDetectmode(String detectmode) {
this.detectmode = detectmode;
}
public String getProcessingmode() {
return processingmode;
}
public void setProcessingmode(String processingmode) {
this.processingmode = processingmode;
}
public Long getFacesize() {
return facesize;
}
public void setFacesize(Long facesize) {
this.facesize = facesize;
}
public Long getThresh() {
return thresh;
}
public void setThresh(Long thresh) {
this.thresh = thresh;
}
public Long getMaxfacenumber() {
return maxfacenumber;
}
public void setMaxfacenumber(Long maxfacenumber) {
this.maxfacenumber = maxfacenumber;
}
}
|
package com.choco.sso.service;
import com.choco.common.entity.Admin;
/**
* Created by choco on 2021/1/5 22:29
*/
public interface SSOService {
/**
* 返回ticket
*/
String login(Admin admin);
/**
* 验证ticket
*/
Admin validate(String ticket);
/**
* 删除cookie
*/
void logout(String ticket);
}
|
package com.netty.bytebuf;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import java.util.Iterator;
public class ByteBufTest3 {
public static void main(String[] args) {
ByteBuf byteBuf = Unpooled.buffer(10);
ByteBuf byteBuf1 = Unpooled.directBuffer(10);
CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer();
compositeByteBuf.addComponents(byteBuf,byteBuf1);
compositeByteBuf.removeComponent(0);
// Iterator<ByteBuf> iterable = compositeByteBuf.iterator();
// while (iterable.hasNext()){
// System.out.println(iterable.next());
// }
//函数式编程
compositeByteBuf.forEach(System.out::println);
}
}
|
package dtu.cse.hanh.simplealarm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import java.util.Calendar;
/**
* Created by Hanh on 10/2/2014.
*/
public class SendAlarmRepeatingTester extends BaseTester {
private static String tag = "SendAlarmRepeatingTester";
public SendAlarmRepeatingTester(Context ctx, IReportBack target) {
super(ctx, target);
}
/**
* An alarm can invoke a broadcast request
* starting at specified time and at regular intervals.
*
* Uses the same intent as above but a distinct request id to avoid conflicts
* with the single shot alarm above
*
* Uses getDistinctPendingIntent() utility
*/
public void sendRepeatingAlarm(){
Calendar cal = Utils.getTimeAfterInSecs(30);
String s = Utils.getDateTimeString(cal);
this.mReportTo.reportBack(tag,"Scheduling Repeating alarm in 5 sec interval starting at: " + s);
// Get an intent to invoke the receiver
Intent intent = new Intent(this.mContext, TestReceiver.class);
intent.putExtra("message","Repeating Alarm");
PendingIntent pi = this.getDistinctPendingIntent(intent,2);
// Schedule the alarm!
AlarmManager am = (AlarmManager) this.mContext.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),5*1000,pi);
}
protected PendingIntent getDistinctPendingIntent(Intent intent, int requestId){
PendingIntent pi = PendingIntent.getBroadcast(
mContext,
requestId,
intent,
0);
return pi;
}
}
|
public class MyObj {
public int i = 0;
} |
package br.com.wasys.gfin.cheqfast.cliente.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import br.com.wasys.gfin.cheqfast.cliente.Dispositivo;
import br.com.wasys.gfin.cheqfast.cliente.R;
public class SplashActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
public static Intent newIntent(Context context) {
return new Intent(context, SplashActivity.class);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
start();
}
}, 2000);
}
private void start() {
Intent intent;
Dispositivo dispositivo = Dispositivo.current();
if (dispositivo != null) {
intent = MainActivity.newIntent(this);
} else {
intent = LoginActivity.newIntent(this);
}
startActivity(intent);
finish();
}
} |
package dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import dao.mapper.BoardMapper;
import dao.mapper.TilMapper;
import logic.TIL;
@Repository
public class TilDao {
@Autowired
private SqlSessionTemplate template;
private Map<String, Object> param = new HashMap<>();
public void insert(TIL til) {
template.getMapper(TilMapper.class).insert(til);
}
public int maxnum() {
return template.getMapper(TilMapper.class).maxnum();
}
public List<TIL> list() {
param.clear();
return template.getMapper(TilMapper.class).list(param);
}
public TIL selectOne(int no, int bno) {
param.clear();
param.put("no", no);
param.put("bno", bno);
return template.getMapper(TilMapper.class).selectOne(param);
}
public void delete(TIL til) {
template.getMapper(TilMapper.class).delete(til);
}
public void update(TIL til) {
template.getMapper(TilMapper.class).update(til);
}
public List<TIL> mytillist(String name) {
param.clear();
param.put("name", name);
return template.getMapper(TilMapper.class).mytillist(param);
}
public int getcount(Integer no, Integer bno) {
param.clear();
param.put("no",no);
param.put("bno",bno);
return template.getMapper(TilMapper.class).getcount(param);
}
}
|
package com.offbeat.apps.tasks.UI;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.offbeat.apps.tasks.R;
import com.offbeat.apps.tasks.Utils.Utils;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private static final int RC_SIGN_IN = 1001;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
ProgressDialog progressDialog;
Utils mUtils;
Map<String, Object> myTasks = new HashMap<>();
Map<String, Object> personalTasks = new HashMap<>();
private GoogleSignInClient mGoogleSignInClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.setLightStatusBar(this, getWindow().getDecorView(), this);
mUtils.setTypeFace(this);
setContentView(R.layout.activity_login);
progressDialog = new ProgressDialog(this);
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.login_token))
.requestEmail()
.requestId()
.requestProfile()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Log.w(TAG, "Google sign in failed", e);
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
progressDialog.setMessage("Logging in...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithCredential:success");
final FirebaseUser user = mAuth.getCurrentUser();
FirebaseFirestore mFirebaseFirestore = FirebaseFirestore.getInstance();
CollectionReference tasksReference = mFirebaseFirestore.collection(getString(R.string.tasks_collection));
final DocumentReference userReference = tasksReference.document(Objects.requireNonNull(mAuth.getUid()));
userReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
if (!task.getResult().exists()) {
Map<String, Object> userMap = new HashMap<>();
assert user != null;
userMap.put(getString(R.string.user_id), user.getUid());
userMap.put(getString(R.string.user_email), Objects.requireNonNull(user.getEmail()));
userMap.put(getString(R.string.user_fullname), Objects.requireNonNull(user.getDisplayName()));
userMap.put(getString(R.string.user_profile_picture), user.getPhotoUrl().toString());
myTasks.put(getString(R.string.title), getString(R.string.default_task_mytasks));
myTasks.put(getString(R.string.start_color), getString(R.string.start_orange_grad));
myTasks.put(getString(R.string.end_color), getString(R.string.end_orange_grad));
myTasks.put(getString(R.string.completed_tasks), 0);
myTasks.put(getString(R.string.incomplete_tasks), 0);
myTasks.put(getString(R.string.timestamp), Timestamp.now());
myTasks.put(getString(R.string.icon), 1);
personalTasks.put(getString(R.string.title), getString(R.string.default_task_personal));
personalTasks.put(getString(R.string.start_color), getString(R.string.start_purple_grad));
personalTasks.put(getString(R.string.end_color), getString(R.string.end_purple_grad));
personalTasks.put(getString(R.string.completed_tasks), 0);
personalTasks.put(getString(R.string.incomplete_tasks), 0);
personalTasks.put(getString(R.string.icon), 7);
personalTasks.put(getString(R.string.timestamp), Timestamp.now());
userReference.set(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
DocumentReference personaltask = userReference.collection(getString(R.string.tasks_collection)).document();
personalTasks.put(getString(R.string.id), personaltask.getId());
personaltask.set(personalTasks).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
DocumentReference mytasks = userReference.collection(getString(R.string.tasks_collection)).document();
myTasks.put(getString(R.string.id), mytasks.getId());
mytasks.set(myTasks).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
updateUI();
}
});
}
});
}
});
} else {
updateUI();
}
}
}
});
} else {
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
updateUI();
}
}
});
}
@Override
public void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null) {
updateUI();
}
}
private void updateUI() {
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.