text
stringlengths
10
2.72M
package com.jic.libin.leaderus.study002; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** * Created by andylee on 16/12/18. */ public class Trie { private int SIZE = 26; // 字典树的根 private TrieNode root; // 初始化字典树 Trie() { root = new TrieNode(); } // 字典树节点 private class TrieNode { // 有多少单词通过这个节点,即节点字符出现的次数 private int num; // 所有的儿子节点 private TrieNode[] son; // 是不是最后一个节点 private boolean isEnd; // 节点的值 private char val; TrieNode() { num = 1; son = new TrieNode[SIZE]; isEnd = false; } } // 建立字典树 public void insert(String str) { // 在字典树中插入一个单词 if (str == null || str.length() == 0) { return; } TrieNode node = root; char[] letters = str.toCharArray(); for (int i = 0, len = str.length(); i < len; i++) { int pos = letters[i] - 'a'; if (node.son[pos] == null) { node.son[pos] = new TrieNode(); node.son[pos].val = letters[i]; } else { node.son[pos].num++; } node = node.son[pos]; } node.isEnd = true; } // 计算单词前缀的数量 public int countPrefix(String prefix) { if (prefix == null || prefix.length() == 0) { return -1; } TrieNode node = root; char[] letters = prefix.toCharArray(); for (int i = 0, len = prefix.length(); i < len; i++) { int pos = letters[i] - 'a'; if (node.son[pos] == null) { return 0; } else { node = node.son[pos]; } } return node.num; } // 在字典树中查找一个完全匹配的单词. public boolean has(String str) { if (str == null || str.length() == 0) { return false; } TrieNode node = root; char[] letters = str.toCharArray(); for (int i = 0, len = str.length(); i < len; i++) { int pos = letters[i] - 'a'; if (node.son[pos] != null) { node = node.son[pos]; } else { return false; } } return node.isEnd; } // 前序遍历字典树. public void preTraverse(TrieNode node) { if (node != null) { System.out.print(node.val + "-"); for (TrieNode child : node.son) { preTraverse(child); } } } public TrieNode getRoot() { return this.root; } public static void main(String[] args) { char[] chars = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; Trie tree = new Trie(); String[] strs = new String[1000_0000]; for (int i = 0; i < 1000_0000; i++) { String name = String.valueOf(chars[ThreadLocalRandom.current().nextInt(26)]) + String.valueOf(chars[ThreadLocalRandom.current().nextInt(26)]) + String.valueOf(chars[ThreadLocalRandom.current().nextInt(26)]) + String.valueOf(chars[ThreadLocalRandom.current().nextInt(26)]); strs[i] = name; } String[] prefix = new String[26*26]; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { char chari= (char) (i+97); char charj= (char) (j+97); prefix[i*26+j] = String.valueOf(chari)+String.valueOf(charj); } } for (String str : strs) { tree.insert(str); } //System.out.println("判断blogchong是否为树枝:"+tree.has("blogchong")); //System.out.print("先序遍历字典树:"); tree.preTraverse(tree.getRoot()); System.out.println(); for (String pre : prefix) { int num = tree.countPrefix(pre); System.out.println(pre + " " + num); } } }
package web; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; //import org.testng.annotations.Test; import com.clc.automation.AutomationFrameworkProject1.AppConstant; import com.clc.automation.AutomationFrameworkProject1.AppConstant.userchoice; import com.clc.automation.AutomationFrameworkProject1.RootPageObject; public class Guru99Alert extends RootPageObject{ @FindBy(name="cusid") WebElement cust_id; @FindBy(name="submit") WebElement submit; @FindBy(name="res") WebElement reset; public void launchwebsiteguru99() { driver.get("http://demo.guru99.com/test/delete_customer.php"); submit.click(); } public void deleteConfirmationAlert(AppConstant.userchoice choice) { Alert alert=driver.switchTo().alert(); if(userchoice.ok.equals(choice)) { alert.accept(); } else { alert.dismiss(); } handleSimpleAlert(); } public void handleSimpleAlert() { try { TimeUnit.SECONDS.sleep(4); } catch(InterruptedException e) { e.printStackTrace(); } Alert alert=driver.switchTo().alert(); } @Override public boolean isPageLoaded() { // TODO Auto-generated method stub return false; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.davivienda.multifuncional.reintegros.helper; import com.davivienda.multifuncional.reintegros.general.ReintegrosMultifuncionalGeneralObjectContext; import com.davivienda.multifuncional.reintegros.general.ReintegrosMultifuncionalHelperInterface; import com.davivienda.multifuncional.tablas.procesos.session.ProcesoReintegrosMultiSessionLocal; import com.davivienda.multifuncional.tablas.reintegrosmultiefectivo.session.ReintegrosMultiEfectivoSessionLocal; import com.davivienda.sara.constantes.CodigoError; import com.davivienda.sara.constantes.EstadoReintegro; import com.davivienda.sara.constantes.RedCajero; import com.davivienda.multifuncional.reintegros.general.ReintegrosMultifuncionalHelperInterface; import com.davivienda.sara.entitys.Reintegrosmultiefectivo; import com.davivienda.utilidades.Constantes; import com.davivienda.utilidades.conversion.Cadena; import com.davivienda.utilidades.conversion.FormatoFecha; import com.davivienda.utilidades.conversion.JSon; import java.util.Collection; import java.util.Date; import java.util.logging.Level; import javax.ejb.EJBException; import org.json.JSONArray; import org.json.JSONObject; /** * * @author jediazs */ public class ReintegrosMultiGuadarRevServletHelper implements ReintegrosMultifuncionalHelperInterface { private ReintegrosMultiEfectivoSessionLocal session = null; private ProcesoReintegrosMultiSessionLocal procesoReintegrosMultiSessionLocal; private ReintegrosMultifuncionalGeneralObjectContext objectContext; private String respuestaJSon; boolean esCreado = false; public ReintegrosMultiGuadarRevServletHelper(ReintegrosMultiEfectivoSessionLocal session, ProcesoReintegrosMultiSessionLocal procesoReintegrosMultiSessionLocal, ReintegrosMultifuncionalGeneralObjectContext objectContext, boolean esCreado) { this.session = session; this.procesoReintegrosMultiSessionLocal = procesoReintegrosMultiSessionLocal; this.objectContext = objectContext; this.esCreado = esCreado; } public String obtenerDatos() { respuestaJSon = ""; String respuesta = ""; Collection<Reintegrosmultiefectivo> items = null; try { Date fechaInicial = null; Date fechaFinal = null; Integer codigoCajero = 0; try { actualizarJsonSelecionados(objectContext.getAtributoJsonArray("events")); } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (ex.getLocalizedMessage().contains("NoResultException")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_SIN_DATA); } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), "Error interno en la consulta"); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } // if (items == null || items.isEmpty()) { // respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); // } if (items != null && this.respuestaJSon.length() <= 1) { respuesta = aJSon(items); // paso los items a JSON } else { respuesta = this.respuestaJSon; } return respuesta; } private String aJSon(Collection<Reintegrosmultiefectivo> items) { String cadenaJSon = ""; try { Integer idRegistro = 0; JSONObject resp = new JSONObject(); JSONArray respItems = new JSONArray(); for (Reintegrosmultiefectivo item : items) { JSONObject itemJSon = new JSONObject(); itemJSon.put("idRegistro", ++idRegistro); itemJSon.put("codigoCajero", item.getTCodigocajero()); itemJSon.put("numeroTransaccion", item.getReintegrosmultiefectivoPK().getHTalon().toString()); itemJSon.put("numeroCuenta", item.getHNumerocuenta()); //itemJSon.put("numeroTarjeta", item.getTTarjeta()); itemJSon.put("fecha", com.davivienda.utilidades.conversion.Fecha.aCadena(item.getReintegrosmultiefectivoPK().getHFechasistema(), FormatoFecha.FECHA_HORA)); itemJSon.put("valor", com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getHValor())); itemJSon.put("valorAjustar", com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getValorajustado())); itemJSon.put("statusTransaccion", item.getTEstado()); itemJSon.put("valorAjustado", com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getValorajustado())); itemJSon.put("usuarioRevisa", item.getUsuariosrevisa()); itemJSon.put("redEnruta", RedCajero.getRedCajero(Cadena.aInteger(item.getHNumerocuenta().substring(0, 4))).toString()); itemJSon.put("checkSeleccion", true); } resp.put("identifier", "idRegistro"); resp.put("label", "codigoCajero"); resp.put("items", respItems); cadenaJSon = resp.toString(); } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); objectContext.getConfigApp().loggerApp.severe("No se puede pasar a JSON \n " + ex.getMessage()); cadenaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_PARSEAR_REGISTRO.getCodigo(), Constantes.MSJ_ERROR_INTERNO); } return cadenaJSon; } private void actualizarJsonSelecionados(JSONArray myArrayList) { objectContext.getConfigApp().loggerApp.log(Level.INFO, "ReintegrosMultiGuadarRevServletHelper - actualizarJsonSelecionados"); JSONObject itemJSon = null; Date fecha = null; Long valorajustado = null; String strValorAjustado = ""; Long valor = null; String strValor = ""; try { if (myArrayList != null) { for (int i = 0; i < myArrayList.length(); i++) { itemJSon = new JSONObject(myArrayList.getString(i)); if (itemJSon.get("checkSeleccion").toString().equals("true")) { strValorAjustado = itemJSon.get("valorAjustar").toString().replace(".", "").replace(",", ""); valorajustado = Cadena.aLong(strValorAjustado); strValor = itemJSon.get("valor").toString().replace(".", "").replace(",", ""); valor = Cadena.aLong(strValor); fecha = com.davivienda.utilidades.conversion.Cadena.aDate(itemJSon.get("fecha").toString(), FormatoFecha.FECHA_HORA); actualizarReintegro(Cadena.aInteger(itemJSon.get("codigoCajero").toString()), fecha, Cadena.aInteger(itemJSon.get("numeroTransaccion").toString()), valorajustado, itemJSon.get("numeroCuenta").toString(), valor); } } } } catch (org.json.JSONException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_PARSEAR_REGISTRO.getCodigo(), "Error leyendo arrayJson Grid", ex); } } private String actualizarReintegro(Integer codigoCajero, Date fechaProceso, Integer numeroTransaccion, Long valorajustado, String numeroCuenta, Long valor) { objectContext.getConfigApp().loggerApp.log(Level.INFO, "ReintegrosMultiGuadarRevServletHelper - actualizarReintegro"); String usuario = ""; String mensaje = ""; mensaje = respuestaJSon; usuario = objectContext.getIdUsuarioEnSesion(); Reintegrosmultiefectivo regReintegrosMultifuncional = null; try { regReintegrosMultifuncional = getReintegroXCuentaValor(codigoCajero, fechaProceso, numeroTransaccion, numeroCuenta, valor); objectContext.getConfigApp().loggerApp.log(Level.INFO, "ReintegrosMultiGuadarRevServletHelper - actualizarReintegro regReintegrosMultifuncional: " + regReintegrosMultifuncional); if (regReintegrosMultifuncional != null) { if (esCreado) { regReintegrosMultifuncional.setEstadoreintegro(EstadoReintegro.INICIADO.codigo); } else { regReintegrosMultifuncional.setEstadoreintegro(EstadoReintegro.REVISADOAUTORIZADO.codigo); } regReintegrosMultifuncional.setValorajustado(valorajustado); //OJO DESCOMENTAREAR EN PRUEBAS regReintegrosMultifuncional.setUsuariosrevisa(usuario); //guardar registro procesoReintegrosMultiSessionLocal.actualizarReintegro(regReintegrosMultifuncional); respuestaJSon = "Se guardaron los registros con Exito"; respuestaJSon = JSon.getJSonRespuesta(0, respuestaJSon); objectContext.getConfigApp().loggerApp.log(Level.INFO, respuestaJSon); } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), "Error interno en la consulta"); } return mensaje; } private Reintegrosmultiefectivo getReintegroXCuentaValor(Integer codigoCajero, Date fechaProceso, Integer numeroTransaccion, String numeroCuenta, Long valor) throws Exception { objectContext.getConfigApp().loggerApp.log(Level.INFO, "ReintegrosMultiGuadarRevServletHelper - getReintegroXCuentaValor"); Reintegrosmultiefectivo regReintegrosMulti = null; try { Date fechaHisto = objectContext.getConfigApp().FECHA_HISTORICAS_CONSULTA; regReintegrosMulti = session.getReintegroXCuentaValor(codigoCajero, fechaProceso, numeroTransaccion, numeroCuenta, valor, fechaHisto); } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), ex.getMessage()); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_ERROR); } if (ex.getLocalizedMessage().contains("NoResultException")) { //respuestaJSon = JSon.getJSonRespuesta(CodigoError.REGISTRO_NO_EXISTE.getCodigo(), "No hay registros que cumplan los criterios de la consulta"); respuestaJSon = JSon.getJSonRespuesta(CodigoError.ERROR_CONSULTANDO_ENTITYS.getCodigo(), Constantes.MSJ_QUERY_SIN_DATA); } } return regReintegrosMulti; } public String generarDiarioElectronicoXML() { throw new UnsupportedOperationException("Not supported yet."); } }
package de.cimdata.db_jsf.beans; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import de.cimdata.db_jsf.dao.DesignpatternDAO; import de.cimdata.db_jsf.model.Designpattern; @ManagedBean public class Bean { private List<Designpattern> list = new ArrayList<Designpattern>(); private DesignpatternDAO dao = new DesignpatternDAO(); @PostConstruct public void init() { setList(dao.findAll()); } public List<Designpattern> getList() { return list; } public void setList(List<Designpattern> list) { this.list = list; } }
package ortigiaenterprises.platerecognizer; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.hardware.Camera; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.googlecode.leptonica.android.ReadFile; import com.googlecode.tesseract.android.TessBaseAPI; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfRect; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Iterator; import java.util.List; import ortigiaenterprises.platerecognizer.common.GPSManager; import ortigiaenterprises.platerecognizer.common.Utils; import ortigiaenterprises.platerecognizer.interfaces.GPSCallback; import ortigiaenterprises.platerecognizer.interfaces.OnTaskCompleted; import ortigiaenterprises.platerecognizer.interfaces.viewInterface; import ortigiaenterprises.platerecognizer.language.LanguageCodeHelper; import ortigiaenterprises.platerecognizer.model.BitmapWithCentroid; import ortigiaenterprises.platerecognizer.server.InterfacciaServer; import ortigiaenterprises.platerecognizer.sqlDb.MyDBHandler; import ortigiaenterprises.platerecognizer.view.CameraPreview; public class MainActivity extends AppCompatActivity implements GPSCallback,OnTaskCompleted { private CameraPreview cameraPreview; private RelativeLayout layout; private PlateView plateView; private boolean cosoDaCambiare=false; Utils utils; public boolean isRunningTask = false; private TessBaseAPI baseApi; private static final String TAG = "MainActivity.java"; List<Point> platePointList; //Da vedere TextView resultOCR; TextView gpsInfo; private View resultView; private View parametersVIew; private boolean listshow= false; private String OPERATOR = "Operator000"; private String SURVEY = "Survey000"; private int MINLENGHT = 7; private int MAXLENGHT = 7; protected int pixelMap[]; protected Bitmap newBitmap; protected int downSampleLeft; protected int downSampleRight; protected int downSampleTop; protected int downSampleBottom; private Mat mRgba; private Mat mGray; private File mCascadeFile; private CascadeClassifier mJavaDetector; MatOfRect plates; private float mRelativePlateSize = 0.2f; private int mAbsolutePlateSize = 0; private GPSManager gpsManager = null; private double speed = 0.0; private double latitude = 0.0; private double longitude = 0.0; FloatingActionButton DBfab; FloatingActionButton fab; private int pageSegmentationMode = TessBaseAPI.PageSegMode.PSM_SPARSE_TEXT_OSD; private int ocrEngineMode = TessBaseAPI.OEM_TESSERACT_ONLY; private String characterBlacklist=""; private String characterWhitelist="ABCDEFGHILMNOPQRSTUVWYZ0123456789 "; private ProgressDialog dialog; // for initOcr - language download & unzip private ProgressDialog indeterminateDialog; // also for initOcr - init OCR engine private ArrayList<OcrRes> OcrResList; public List<Rect> currentPlates = new ArrayList<Rect>(); private boolean calculateOcr= false; private MyDBHandler DbHandler; private InterfacciaServer server; private int mInterval = 60000; // 30 seconds by default, can be changed later private Handler mHandler; private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { switch (status) { case LoaderCallbackInterface.SUCCESS: { Log.i(TAG, "OpenCV loaded successfully"); try { // Load Haar training result file from application resources // This file from opencv_traincascade tool. // Load res/cascade-europe.xml file InputStream is = getResources().openRawResource(R.raw.europe); File cascadeDir = getDir("cascade", Context.MODE_PRIVATE); mCascadeFile = new File(cascadeDir, "europe.xml"); // Load XML file according to R.raw.cascade FileOutputStream os = new FileOutputStream(mCascadeFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); mJavaDetector = new CascadeClassifier( mCascadeFile.getAbsolutePath()); mJavaDetector.load( mCascadeFile.getAbsolutePath() ); if (mJavaDetector.empty()) { Log.e(TAG, "Failed to load cascade classifier"); mJavaDetector = null; } else Log.i(TAG, "Loaded cascade classifier from " + mCascadeFile.getAbsolutePath()); cascadeDir.delete(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Failed to load cascade. Exception thrown: " + e); } } break; case LoaderCallbackInterface.INIT_FAILED: { } break; default: { super.onManagerConnected(status); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); Boolean checkOpenCV = OpenCVLoader.initAsync( OpenCVLoader.OPENCV_VERSION_3_1_0, getApplicationContext(), mLoaderCallback); cameraPreview = new CameraPreview(this, plateView); if(checkOpenCV) { try { layout = (RelativeLayout) findViewById(R.id.RelLayout); plateView = new PlateView(this); cameraPreview = new CameraPreview(this, plateView); layout.addView(cameraPreview, 1); layout.addView(plateView, 2); resultOCR = new TextView(getApplicationContext()); //resultOCR.setText("Welcome to UIT-ANPR"); //RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( // resultOCR.getLayoutParams()); //lp.addRule(RelativeLayout.CENTER_HORIZONTAL); //lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); //lp.setMargins(0, 0, 0, 10); //resultOCR.setTextSize(30); //resultOCR.setBackgroundColor(Color.WHITE); //resultOCR.setTextColor(Color.RED); //resultOCR.setTypeface(Typeface.DEFAULT, Typeface.BOLD); //resultOCR.setLayoutParams(lp); gpsInfo = (TextView) findViewById(R.id.gpsviewtext); gpsInfo.bringToFront(); //RelativeLayout.LayoutParams lpGPS = new RelativeLayout.LayoutParams( // gpsInfo.getLayoutParams()); //lpGPS.addRule(RelativeLayout.ALIGN_PARENT_LEFT); //lpGPS.addRule(RelativeLayout.ALIGN_PARENT_TOP); //lpGPS.setMargins(0, 0, 0, 10); //gpsInfo.setTextSize(15); //gpsInfo.setBackgroundColor(Color.WHITE); //gpsInfo.setTextColor(Color.RED); //gpsInfo.setTypeface(Typeface.DEFAULT, Typeface.BOLD); //gpsInfo.setLayoutParams(lpGPS); } catch (Exception e1) { Log.e("MissingOpenCVManager",e1.toString()); } gpsManager = new GPSManager(); gpsManager.startListening(getApplicationContext()); gpsManager.setGPSCallback(this); utils = new Utils(getBaseContext()); platePointList = new ArrayList<Point>(); } OcrResList = new ArrayList<OcrRes>(); resultView = findViewById(R.id.resultView); parametersVIew = findViewById(R.id.parametersView); initOcrEngine(); DbHandler = MyDBHandler.getInstance(this); initParameters(); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onClickBtn(); //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); } }); DBfab = (FloatingActionButton) findViewById(R.id.DBfab); DBfab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDatabase(); //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); } }); server = InterfacciaServer.getInstance(this); mHandler = new Handler(); } private void initParameters(){ Object[] parameters = DbHandler.getParameters(); OPERATOR =(String) parameters[0]; SURVEY = (String) parameters[1]; MINLENGHT=(int) parameters[2]; MAXLENGHT = (int) parameters[3]; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallback); if (cosoDaCambiare) { initParameters(); showDatabase(); } cosoDaCambiare=true; } public void onDestroy() { super.onDestroy(); } // This class is for Viewing a detected plate public class PlateView extends View implements Camera.PreviewCallback, OnTaskCompleted { public static final int SUBSAMPLING_FACTOR = 4; public Rect[] platesArray; List<Point> currentPlatePointList = new ArrayList<Point>(); public PlateView(MainActivity context) throws IOException { super(context); } public void onPreviewFrame(final byte[] data, final Camera camera) { try { Camera.Size size = camera.getParameters().getPreviewSize(); // Get image from camera and process it to see // are there any plate on it ? if(!listshow){ processImage(data, size.width, size.height);} camera.addCallbackBuffer(data); } catch (RuntimeException e) { // The camera has probably just been released, ignore. Log.e(TAG,e.toString()); } } protected void processImage(byte[] data, int width, int height) { // First, downsample our image and convert it into a grayscale int f = SUBSAMPLING_FACTOR; mRgba = new Mat(height, width, CvType.CV_8UC4); mGray = new Mat(height, width, CvType.CV_8UC1); Mat mYuv = new Mat(height +height/2, width, CvType.CV_8UC1); mYuv.put(0, 0, data); Imgproc.cvtColor(mYuv, mGray, Imgproc.COLOR_YUV420sp2GRAY); Imgproc.cvtColor(mYuv, mRgba, Imgproc.COLOR_YUV2RGB_NV21, 3); if (mAbsolutePlateSize == 0) { int heightGray = mGray.rows(); if (Math.round(heightGray * mRelativePlateSize) > 0) { mAbsolutePlateSize = Math.round(heightGray * mRelativePlateSize); } } // This variable is used to to store the detected plates in the result plates = new MatOfRect(); if (mJavaDetector != null) mJavaDetector.detectMultiScale( mGray, plates, 1.1, 2, 2, new Size(mAbsolutePlateSize, mAbsolutePlateSize), new Size() ); postInvalidate(); } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.GREEN); paint.setTextSize(20); if (plates != null && !listshow) { paint.setStrokeWidth(5); paint.setStyle(Paint.Style.STROKE); platesArray = plates.toArray(); currentPlates.clear(); for (int i = 0; i < platesArray.length; i++) { int x = platesArray[i].x; int y = platesArray[i].y; int w = platesArray[i].width + platesArray[i].width/2; int h = platesArray[i].height; // Draw a Green Rectangle surrounding the Number Plate ! // Congratulations ! You found the plate area :-) canvas.drawRect(x, y, (x + w), (y + h), paint); Point platePoint = new Point(platesArray[i].x, platesArray[i].y); currentPlatePointList.add(platePoint); currentPlates.add(platesArray[i]); } if (platesArray.length > 0) { platePointList.clear(); platePointList.addAll(currentPlatePointList); } else { platePointList.clear(); } // If isHasNewPlate --> get sub images (ROI) --> Add to Adapter // (from currentPlates) if ((calculateOcr) && !isRunningTask) { Log.e(TAG, "START DoOCR task!!!!"); new DoOCR(currentPlates, mRgba, this).execute(); } }else{ postInvalidate(); invalidate();} } public void updateResult(String result) { /* This function is not completed yet We will add the Neural network to recognize the numbers, characters in the plate later */ // TODO Auto-generated method stub resultOCR.setText(result); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()); String toFile = "Date: " + timeStamp + "\n"; toFile += "Latitude: " + latitude + "\n"; toFile += "Longitude: " + longitude + "\n"; //toFile += "Speed: " + String.valueOf(utils.roundDecimal(utils.convertSpeed(speed), 2)) + "km/h" + "\n"; toFile += "NP: " + result + "\n\n\n"; if(result!=null && !TextUtils.isEmpty(result) && result!=""){ FileWriter f; try{ f = new FileWriter(Environment.getExternalStorageDirectory() + "/UIT-ANPR.txt", true); Log.e("DON", "BAT DAU GHI FILE 2222"); f.write(toFile); f.flush(); f.close(); }catch (Exception e) { // TODO: handle exception } } //foundNumberPlate.setText(result); } public class DoOCR extends AsyncTask<Void, Bitmap, Boolean> { private List<Rect> currentPlatesOnAsy; private Mat originImageOnAsy; private OnTaskCompleted listener; public DoOCR(List<Rect> currentPlates, Mat originImage, OnTaskCompleted listener) { this.currentPlatesOnAsy = new ArrayList<Rect>(currentPlates); this.originImageOnAsy = originImage; this.listener = listener; } @Override protected void onPreExecute() { isRunningTask = true; baseApi.setPageSegMode(pageSegmentationMode); baseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, characterBlacklist); baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, characterWhitelist); //baseApi.readConfigFile(); } @Override protected Boolean doInBackground(Void... params) { try { Iterator<Rect> iterator = currentPlatesOnAsy.iterator();//per ogni rettangolo verde while (iterator.hasNext()) { Rect plateRect = iterator.next();//prendo il rettangolo su cui lavorare OcrRes result = null; if (baseApi.getPageSegMode() == TessBaseAPI.PageSegMode.PSM_SINGLE_CHAR) { Log.d("Single char", " ON"); result = performSingleCharOcrOnPlate(plateRect, originImageOnAsy); } else { Log.d("OCR on Whole Plate", baseApi.getPageSegMode() + ""); if (plateRect.width > 15 && plateRect.height > 15) result = performOcrPlate(plateRect, originImageOnAsy); } result.setText(result.getText().replaceAll("\n", "")); result.setText(result.getText().replaceAll(" ", "")); result.setText(result.getText().replaceAll("-", "")); Log.d("result", result.getText()); if (result != null && result.getText().length() >= MINLENGHT && result.getText().length() <= MAXLENGHT) { OcrResList.add(result); Log.d("message: ", result.getText() + " "); } } if (OcrResList.size() > 0) return true; else return false; }catch (Error e){ return false; } } @Override protected void onProgressUpdate(Bitmap... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(Boolean success) { isRunningTask = false; if (success){ calculateOcr=false; showOcrResults(OcrResList); Log.d("OCR:", " trovato qualcosa"); } else { Log.d("OCR:"," vuoto"); } } } } /** * This method is called to automatically crop the image so that whitespace * is removed. * * @param w * The width of the image. * @param h * The height of the image */ protected void findBounds(final int w, final int h) { // top line for (int y = 0; y < h; y++) { if (!hLineClear(y)) { this.downSampleTop = y; break; } } // bottom line for (int y = h - 1; y >= 0; y--) { if (!hLineClear(y)) { this.downSampleBottom = y; break; } } // left line for (int x = 0; x < w; x++) { if (!vLineClear(x)) { this.downSampleLeft = x; break; } } // right line for (int x = w - 1; x >= 0; x--) { if (!vLineClear(x)) { this.downSampleRight = x; break; } } } /** * This method is called internally to see if there are any pixels in the * given scan line. This method is used to perform autocropping. * * @param y * The horizontal line to scan. * @return True if there were any pixels in this horizontal line. */ protected boolean hLineClear(final int y) { final int w = this.newBitmap.getWidth(); for (int i = 0; i < w; i++) { if (this.pixelMap[(y * w) + i] != -1) { return false; } } return true; } /** * This method is called to determine .... * * @param x * The vertical line to scan. * @return True if there are any pixels in the specified vertical line. */ protected boolean vLineClear(final int x) { final int w = this.newBitmap.getWidth(); final int h = this.newBitmap.getHeight(); for (int i = 0; i < h; i++) { if (this.pixelMap[(i * w) + x] != -1) { return false; } } return true; } protected OcrRes performSingleCharOcrOnPlate(Rect plateRect,Mat originImageOnAsy){ BitmapWithCentroid tempBitmap; long start, timeRequired; start = System.currentTimeMillis(); Mat plateImage; List<BitmapWithCentroid> charList = new ArrayList<BitmapWithCentroid>(); int x = plateRect.x, y = plateRect.y, w = plateRect.width, h = plateRect.height; Rect roi = new Rect((int) (x), (int) (y), (int) (w), (int) (h)); plateImage = new Mat(roi.size(), originImageOnAsy.type()); plateImage = originImageOnAsy.submat(roi);//sottomatrice dell'immagine originale con le dimensioni di roi Mat plateImageResized = new Mat(); Imgproc.resize(plateImage, plateImageResized, new Size(680, 492)); Mat plateImageGrey = new Mat(); Imgproc.cvtColor(plateImageResized, plateImageGrey, Imgproc.COLOR_BGR2GRAY, 1); Imgproc.medianBlur(plateImageGrey, plateImageGrey, 3); //Imgproc.Canny(plateImageGrey, plateImageGrey, 1,3); Imgproc.adaptiveThreshold(plateImageGrey, plateImageGrey, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 85, 5); List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(plateImageGrey.rows(), plateImageGrey.cols(), CvType.CV_8UC1, new Scalar(0)); Imgproc.findContours(plateImageGrey, contours, hierarchy, Imgproc.CHAIN_APPROX_SIMPLE, Imgproc.RETR_LIST); timeRequired = System.currentTimeMillis() - start; Log.e(TAG, "Time for find countour: " + timeRequired); Log.e(TAG, "Start loop!!!" + contours.size()); start = System.currentTimeMillis(); for (int i = 0; i < contours.size(); i++) { List<Point> goodpoints = new ArrayList<Point>(); Mat contour = contours.get(i); int num = (int) contour.total(); int buff[] = new int[num * 2]; // [x1, y1, x2, y2, ...] contour.get(0, 0, buff); for (int q = 0; q < num * 2; q = q + 2) { goodpoints.add(new Point(buff[q], buff[q + 1])); } MatOfPoint points = new MatOfPoint(); points.fromList(goodpoints); Rect boundingRect = Imgproc.boundingRect(points); if (((boundingRect.height / boundingRect.width) >= 1.5) && ((boundingRect.height / boundingRect.width) <= 3.0) && ((boundingRect.height * boundingRect.width) >= 5000)) { int cx = boundingRect.x + (boundingRect.width / 2); int cy = boundingRect.y + (boundingRect.height / 2); Point centroid = new Point(cx, cy); if (centroid.y >= 120 && centroid.y <= 400 && centroid.x >= 100 && centroid.x <= 590) { int calWidth = (boundingRect.width + 5) - (boundingRect.width + 5) % 4; Rect cr = new Rect(boundingRect.x, boundingRect.y, calWidth, boundingRect.height); Mat charImage = new Mat( cr.size(), plateImageResized.type()); charImage = plateImageResized.submat(cr); // sottoimmagine per il singolo carattere Mat charImageGrey = new Mat(charImage.size(), charImage.type()); Imgproc.cvtColor(charImage, charImageGrey, Imgproc.COLOR_BGR2GRAY, 1); Imgproc.adaptiveThreshold(charImageGrey, charImageGrey, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 85, 5); Bitmap charImageBitmap = Bitmap.createBitmap( charImageGrey.width(), charImageGrey.height(), Bitmap.Config.ARGB_8888); org.opencv.android.Utils.matToBitmap( charImageGrey, charImageBitmap); tempBitmap = new BitmapWithCentroid( charImageBitmap, centroid); charList.add(tempBitmap); } } // } } timeRequired = System.currentTimeMillis() - start; Log.e(TAG, "Passed the loop"); Log.e(TAG, "Time for OCR: " + timeRequired); start = System.currentTimeMillis(); Collections.sort(charList); //SampleData data = new SampleData('?', DOWNSAMPLE_WIDTH, // DOWNSAMPLE_HEIGHT); String recognizedText = ""; Log.e("listachar: ", charList.size()+" "); for (int index = 0; index < charList.size(); index++) { newBitmap = charList.get(index).getBitmap(); baseApi.setImage(ReadFile.readBitmap(newBitmap)); recognizedText += baseApi.getUTF8Text(); //recognizedText += baseApi.getUTF8Text(); final int wi = newBitmap.getWidth(); final int he = newBitmap.getHeight(); pixelMap = new int[newBitmap.getHeight() * newBitmap.getWidth()]; newBitmap.getPixels(pixelMap, 0, newBitmap.getWidth(), 0, 0, newBitmap.getWidth(), newBitmap.getHeight()); findBounds(wi, he); /* ratioX = (double) (downSampleRight - downSampleLeft) / (double) data.getWidth(); ratioY = (double) (downSampleBottom - downSampleTop) / (double) data.getHeight(); for (int yy = 0; yy < data.getHeight(); yy++) { for (int xx = 0; xx < data.getWidth(); xx++) { if (downSampleRegion(xx, yy)) { data.setData(xx, yy, true); } else { data.setData(xx, yy, false); } } } final double input[] = new double[20 * 50]; int idx = 0; for (int yy = 0; yy < data.getHeight(); yy++) { for (int xx = 0; xx < data.getWidth(); xx++) { input[idx++] = data.getData(xx, yy) ? 0.5 : -0.5; } } */ double normfac[] = new double[1]; double synth[] = new double[1]; //int best = net.winner(input, normfac, synth); //recognizedText += net.getMap()[best]; Log.e(TAG, "Plate number:" + recognizedText); } //recognizedText = utils.formatPlateNumber(recognizedText); Log.e(TAG, "Plate number:" + recognizedText); timeRequired = System.currentTimeMillis() - start; Log.e(TAG, "Time: " + timeRequired); Bitmap bpResult = Bitmap.createBitmap(plateImage.width(),plateImage.height(),Bitmap.Config.ARGB_8888); org.opencv.android.Utils.matToBitmap( plateImage, bpResult); return new OcrRes(bpResult,recognizedText,plateRect); } public OcrRes performOcrPlate(Rect plateRect, Mat originImageOnAsy){ String recognizedText; long start, timeRequired; start = System.currentTimeMillis(); Mat plateImage; int x = plateRect.x, y = plateRect.y, w = plateRect.width, h = plateRect.height; Rect roi = new Rect((int) (x), (int) (y), (int) (w), (int) (h)); plateImage = new Mat(roi.size(), originImageOnAsy.type()); plateImage = originImageOnAsy.submat(roi);//sottomatrice dell'immagine originale con le dimensioni di roi Mat plateImageResized = new Mat(); Imgproc.resize(plateImage, plateImageResized, new Size(680, 550)); Mat plateImageGrey = new Mat(); Imgproc.cvtColor(plateImageResized, plateImageGrey, Imgproc.COLOR_BGR2GRAY, 1); Imgproc.GaussianBlur(plateImageGrey, plateImageGrey, new Size(3, 3), 3); Imgproc.adaptiveThreshold(plateImageGrey, plateImageGrey, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 85, 5); ////ROXANA + IOlaz Mat immagineclone = plateImageGrey.clone(); Imgproc.threshold(immagineclone, immagineclone, 0, 255, Imgproc.THRESH_OTSU+Imgproc.THRESH_BINARY); Mat element; //element=org.opencv.imgproc.Imgproc.getStructuringElement(Imgproc.MORPH_RECT,new Size(17,3)); // org.opencv.imgproc.Imgproc.morphologyEx(plateImageGrey,plateImageGrey,MOP_CLOSE,element); int erosion_size = 5; element=org.opencv.imgproc.Imgproc.getStructuringElement(Imgproc.MORPH_RECT,new Size(2 * erosion_size + 1, 2 * erosion_size + 1),new Point(erosion_size, erosion_size) ); org.opencv.imgproc.Imgproc.erode(immagineclone, immagineclone, element); //INIZIO FINDCONTOURS ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = new Mat(); // org.opencv.imgproc.Imgproc.findContours(immagineclone,contours,hierarchy,0,1); //ArrayList<MatOfPoint> contours_poly = new ArrayList<MatOfPoint>(); //contours_poly.addAll(contours); //ArrayList<Rect> boundRect= new ArrayList<>(); //MatOfPoint2f matofp1= new MatOfPoint2f(); //MatOfPoint2f matofp2= new MatOfPoint2f(); //NUOVA PARTE Mat mask=Mat.zeros(immagineclone.size(),CvType.CV_8UC1); org.opencv.imgproc.Imgproc.findContours(immagineclone,contours,hierarchy,Imgproc.RETR_TREE,Imgproc.CHAIN_APPROX_SIMPLE,new Point(0,0)); Rect newrect=new Rect(); for(int i=0;i <contours.size();i++) { if (contours.get(i).toList().size()>100) //&& contours.size()>i && contours_poly.size()>i && contours.get(i).toArray().length!=0 && contours_poly.get(i).toArray().length!=0) { //contours.get(i).convertTo(matofp1, CvType.CV_32FC2); //Imgproc.approxPolyDP(matofp1,matofp2, 3, true ); //matofp2.convertTo(contours_poly.get(i), CvType.CV_32S); // Rect appRect=Imgproc.boundingRect(contours_poly.get(i)); Rect appRect=Imgproc.boundingRect(contours.get(i)); Mat maskROI=new Mat(mask,appRect); maskROI.setTo(new Scalar(0,0,0)); Imgproc.drawContours(mask, contours,i, new Scalar(255, 255, 255), Core.FILLED); double r = (double)Core.countNonZero(maskROI)/(appRect.width*appRect.height);//numero pixel che non sono bianchi sull'immagine a cui applico la maschera if (r > .35 && (appRect.height > 8 && appRect.width > 8)) { if(appRect.area()>newrect.area()) newrect=appRect; //Imgproc.rectangle(plateImageGrey, appRect.br() , new Point( appRect.br().x-appRect.width ,appRect.br().y-appRect.height), new Scalar(255,0, 0)); } } } Mat matrect=plateImageGrey.submat(newrect); Imgproc.threshold(matrect, matrect, 0, 255,Imgproc.THRESH_OTSU+Imgproc.THRESH_BINARY); Bitmap plateImageBitmap = Bitmap.createBitmap( matrect.width(), matrect.height(), Bitmap.Config.ARGB_8888); org.opencv.android.Utils.matToBitmap( matrect, plateImageBitmap); baseApi.setImage(ReadFile.readBitmap(plateImageBitmap)); ////Roxana + Iolaz*/ //Imgproc.threshold(plateImageGrey,plateImageGrey,0,255, Imgproc.Ada); /*Bitmap plateImageBitmap = Bitmap.createBitmap( plateImageGrey.width(), plateImageGrey.height(), Bitmap.Config.ARGB_8888); org.opencv.android.Utils.matToBitmap( plateImageGrey, plateImageBitmap); baseApi.setImage(ReadFile.readBitmap(plateImageBitmap));*/ recognizedText = baseApi.getUTF8Text(); Log.d("UTF8: ", baseApi.getUTF8Text() + " "); timeRequired = System.currentTimeMillis() - start; Log.e(TAG, "Time for OCR on Plate: " + timeRequired); OcrRes FinalResult = new OcrRes(plateImageBitmap,recognizedText,plateRect); FinalResult.setMeanConfidence(baseApi.meanConfidence()); return FinalResult; } public void updateResult(String result) { //foundNumberPlate.setText(result); resultOCR.setText(result); } public void onGPSUpdate(Location location) { // TODO Auto-generated method stub latitude = location.getLatitude(); longitude = location.getLongitude(); speed = location.getSpeed(); //String speedString = String.valueOf(utils.roundDecimal(utils.convertSpeed(speed), 2)); String unitString = "km/h"; String gpsInfoText = "Lat: " + latitude + "\n"; gpsInfoText += "Long: " + longitude + "\n"; //gpsInfoText += "Speed: " + speedString + " " + unitString; gpsInfo.setText(gpsInfoText); } void initOcrEngine(){ baseApi = new TessBaseAPI(); if (dialog != null) { dialog.dismiss(); } dialog = new ProgressDialog(this); indeterminateDialog = new ProgressDialog(this); indeterminateDialog.setTitle("Please wait"); String languageName = LanguageCodeHelper.getOcrLanguageName(this, "eng"); File storageDirectory = getStorageDirectory(); if(storageDirectory!= null){ new OcrInitAsyncTask(this, baseApi, dialog, indeterminateDialog, "eng", languageName, TessBaseAPI.OEM_TESSERACT_ONLY) .execute(storageDirectory.toString()); } } private File getStorageDirectory() { //Log.d(TAG, "getStorageDirectory(): API level is " + Integer.valueOf(android.os.Build.VERSION.SDK_INT)); String state = null; try { state = Environment.getExternalStorageState(); } catch (RuntimeException e) { Log.e(TAG, "Is the SD card visible?", e); showErrorMessage("Error", "Required external storage (such as an SD card) is unavailable."); } if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // We can read and write the media // if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) > 7) { // For Android 2.2 and above try { return getExternalFilesDir(Environment.MEDIA_MOUNTED); } catch (NullPointerException e) { // We get an error here if the SD card is visible, but full Log.e(TAG, "External storage is unavailable"); showErrorMessage("Error", "Required external storage (such as an SD card) is full or unavailable."); } // } else { // // For Android 2.1 and below, explicitly give the path as, for example, // // "/mnt/sdcard/Android/data/edu.sfsu.cs.orange.ocr/files/" // return new File(Environment.getExternalStorageDirectory().toString() + File.separator + // "Android" + File.separator + "data" + File.separator + getPackageName() + // File.separator + "files" + File.separator); // } } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media Log.e(TAG, "External storage is read-only"); showErrorMessage("Error", "Required external storage (such as an SD card) is unavailable for data storage."); } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write Log.e(TAG, "External storage is unavailable"); showErrorMessage("Error", "Required external storage (such as an SD card) is unavailable or corrupted."); } return null; } void showErrorMessage(String title, String message) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setOnCancelListener(new FinishListener(this)) .setPositiveButton( "Done", new FinishListener(this)) .show(); } public void showOcrResults(ArrayList<OcrRes> aResults){ DBfab.hide(); fab.hide(); OcrRes[] array = aResults.toArray(new OcrRes[aResults.size()]); ArrayList<OcrRes> Lista = new ArrayList<OcrRes>(Arrays.asList(array)); customAdapter ocrAdapter = new customAdapter(getApplicationContext(),Lista); ListView ocrListView = (ListView)findViewById(R.id.ocrListView); ocrListView.setAdapter(ocrAdapter); Log.d("poi", "rto"); gpsInfo.setVisibility(View.GONE); plateView.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); parametersVIew.setVisibility(View.GONE); resultView.bringToFront(); listshow=true; ocrAdapter.inizializzaInterfaccia(new viewInterface() { @Override public void hideView() { onBackPressed(); } @Override public void Save(OcrRes valueToSave) { valueToSave.setOperator(OPERATOR); valueToSave.setSurvey(SURVEY); valueToSave.setLatitude(latitude); valueToSave.setLongitude(longitude); valueToSave.setDateTime(findDateTime()); DbHandler.insertTodb(valueToSave); } @Override public void Delete(OcrRes valueToDelete) { } @Override public void Info(String NumberPlate,String DateTime) { } }); } private void showDatabase(){ TextView operatorText = (TextView) findViewById(R.id.operatoreId); operatorText.setText(OPERATOR); TextView surveyText = (TextView) findViewById(R.id.surveyId); surveyText.setText(SURVEY); TextView minLengthText = (TextView) findViewById(R.id.minTarga); minLengthText.setText(Integer.toString(MINLENGHT)); TextView maxLength =(TextView) findViewById(R.id.maxTarga); maxLength.setText(Integer.toString(MAXLENGHT)); Button parametersButton = (Button) findViewById(R.id.button); parametersButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getBaseContext(), ModificaDbActivity.class); startActivity(i); } }); Button sincronizzaButton = (Button) findViewById(R.id.sincronizza); final ArrayList<OcrRes> arrayList = DbHandler.getDataFromDb(); sincronizzaButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { server.startRepeatingTask(); } }); if(arrayList.size()>0) { fab.hide(); DBfab.hide(); customDbAdapter dbAdapter = new customDbAdapter(getApplicationContext(), arrayList); ListView ocrListView = (ListView) findViewById(R.id.ocrListView); ocrListView.setAdapter(dbAdapter); dbAdapter.inizializzaInterfaccia(new viewInterface() { @Override public void hideView() { onBackPressed(); } @Override public void Save(OcrRes valueToSave) { } @Override public void Delete(OcrRes valueToDelete) { DbHandler.deleteTodb(valueToDelete.getText(), valueToDelete.getDateTime()); } @Override public void Info(String NumberPlate,String DateTime) { Intent i = new Intent(getBaseContext(), InfoDbActivity.class); i.putExtra("NumberPlate",NumberPlate); i.putExtra("DateTime",DateTime); startActivity(i); } }); }else{ Toast.makeText(getApplicationContext(),"database vuoto",Toast.LENGTH_SHORT).show(); } gpsInfo.setVisibility(View.GONE); resultView.setVisibility(View.VISIBLE); plateView.setVisibility(View.GONE); parametersVIew.setVisibility(View.VISIBLE); resultView.bringToFront(); listshow = true; } private String findDateTime(){ Calendar cal = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); return df.format(cal.getTime()); } public void onClickBtn(){ calculateOcr=true; } @Override public void onBackPressed() { if(listshow){ resultView.setVisibility(View.GONE); gpsInfo.setVisibility(View.VISIBLE); plateView.setVisibility(View.VISIBLE); parametersVIew.setVisibility(View.GONE); OcrResList.clear(); fab.show(); DBfab.show(); listshow=false; }else super.onBackPressed(); } }
package org.cellcore.code.engine.page.extractor.mcc; import org.cellcore.code.engine.page.extractor.AbstractPageDataExtractor; import org.cellcore.code.model.Currency; import org.cellcore.code.model.PriceSources; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.springframework.stereotype.Component; /** * * Copyright 2013 Freddy Munoz (freddy@cellcore.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. * * ============================================================== **/ @Component public class MCCPageDataExtractor extends AbstractPageDataExtractor { @Override protected String[] getOtherNames(Document doc) { String frName = doc.select("#blockContent").get(4).select("b").get(0).childNodes().get(0).attr("text"); return new String[]{frName}; } @Override public Currency getCurrency() { return Currency.EUR; } @Override protected String getName(Document doc) { return doc.select("#blockContent").get(3).select("b").get(0).childNodes().get(0).attr("text"); } @Override protected float getPrice(Document doc) { Elements tr = doc.select("#blockContent").get(5).select("tr"); float iPrice = Float.MAX_VALUE; for (int i = 0; i < tr.size(); i++) { try { String val = tr.get(i).getElementsByTag("td").get(3).childNodes().get(0).attr("text"); val = cleanPriceString(val); float price = Float.parseFloat(val); if (price < iPrice) { iPrice = price; } } catch (Throwable t) { } } if (iPrice == Float.MAX_VALUE) { iPrice = -1; } return iPrice; } @Override protected int getStock(Document doc) { Elements tr = doc.select("#blockContent").get(5).select("tr"); float iPrice = Float.MAX_VALUE; int iStock=0; for (int i = 0; i < tr.size(); i++) { try { String val = tr.get(i).getElementsByTag("td").get(3).childNodes().get(0).attr("text"); String stockV=tr.get(i).getElementsByTag("td").get(4).select("option").last().childNodes().get(0).attr("text"); val = cleanPriceString(val); float price = Float.parseFloat(val); if (price < iPrice) { iPrice = price; iStock=Integer.parseInt(stockV.replaceAll("\\(","").replaceAll("\\)","")); } } catch (Throwable t) { } } return iStock; } @Override public PriceSources getSource() { return PriceSources.MCC; } }
package cn.mldn.eusplatform.dao.impl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import cn.mldn.eusplatform.dao.IScheduleDAO; import cn.mldn.eusplatform.vo.Schedule; import cn.mldn.util.dao.abs.AbstractDAO; import cn.mldn.util.dbc.DatabaseConnection; public class ScheduleDAOImpl extends AbstractDAO implements IScheduleDAO { @Override public boolean doCreateEmpIntoSchedule(String eid, Long sid) throws SQLException { String sql = "insert into schedule_emp (sid,eid) values(?,?)"; Connection conn = DatabaseConnection.getConnection(); super.pstmt = conn.prepareStatement(sql); super.pstmt.setString(2, eid); super.pstmt.setLong(1, sid); return super.pstmt.executeUpdate()>0; } public Long getLastId() throws SQLException { String sql = "SELECT last_insert_id()" ; this.pstmt = this.conn.prepareStatement(sql) ; ResultSet rs = this.pstmt.executeQuery() ; if (rs.next()) { return rs.getLong(1) ; } return 0L ; } public Long getMaxSid()throws SQLException { String sql = "select max(sid) from schedule "; Connection conn = DatabaseConnection.getConnection(); super.pstmt = conn.prepareStatement(sql); ResultSet rs = super.pstmt.executeQuery(); while(rs.next()) { return rs.getLong(1); } return 0L; } @Override public boolean doCreate(Schedule vo) throws SQLException { String sql = "insert into schedule (seid,iid,title,sdate,subdate,audit,note)value(?,?,?,?,?,?,?)"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, vo.getSeid()); super.pstmt.setLong(2, vo.getIid()); super.pstmt.setString(3, vo.getTitle()); super.pstmt.setDate(4 , new java.sql.Date(vo.getSdate().getTime())); super.pstmt.setDate(5, new java.sql.Date(vo.getSubdate().getTime())); super.pstmt.setInt(6, vo.getAudit()); super.pstmt.setString(7, vo.getNote()); return super.pstmt.executeUpdate() > 0; } @Override public boolean doEdit(Schedule vo) throws SQLException { String sql = "update schedule set aeid = ?,auddate = ?,audit = ?,anote = ? where sid = ? "; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, vo.getAeid()); super.pstmt.setDate(2, new java.sql.Date(vo.getAuddate().getTime())); super.pstmt.setInt(3, vo.getAudit()); super.pstmt.setString(4, vo.getAnote()); super.pstmt.setLong(5, vo.getSid()); return super.pstmt.executeUpdate() > 0; } @Override public boolean doRemove(Long id) throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean doRemove(Set<Long> ids) throws SQLException { // TODO Auto-generated method stub return false; } @Override public Schedule findById(Long id) throws SQLException { String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule where sid = ? "; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, id); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); return vo; } return null; } @Override public List<Schedule> findAll() throws SQLException { List<Schedule> all = new ArrayList<>(); String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule "; super.pstmt = super.conn.prepareStatement(sql); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public List<Schedule> findAll(Long currentPage, Integer lineSize) throws SQLException { List<Schedule> all = new ArrayList<>(); String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule LIMIT ?,?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, (currentPage - 1) * lineSize); super.pstmt.setLong(2, lineSize); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public List<Schedule> findSplit(String column, String keyWord, Long currentPage, Integer lineSize) throws SQLException { List<Schedule> all = new ArrayList<>(); String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule WHERE " + column + " LIKE ? LIMIT ?,?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, "%" + keyWord + "%"); super.pstmt.setLong(2, (currentPage - 1) * lineSize); super.pstmt.setLong(3, lineSize); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public Long getAllCount() throws SQLException { String sql = "select count(*) from schedule"; super.pstmt = super.conn.prepareStatement(sql); ResultSet rs = super.pstmt.executeQuery(); if(rs.next()){ return rs.getLong(1); } return 0L; } @Override public Long getSplitCount(String column, String keyWord) throws SQLException { String sql = "select count(*) from schedule where ? like ?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, column); super.pstmt.setString(2, "%"+ keyWord +"%"); ResultSet rs = super.pstmt.executeQuery(); if(rs.next()){ return rs.getLong(1); } return 0L; } @Override public List<Schedule> findAllById(String eid) throws SQLException { List<Schedule> all = new ArrayList<>(); String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule where seid = ?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, eid); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public List<Schedule> findAllById(Long currentPage, Integer lineSize, String eid) throws SQLException { List<Schedule> all = new ArrayList<>(); String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule where seid = ? LIMIT ?,? "; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(2, (currentPage - 1) * lineSize); super.pstmt.setLong(3, lineSize); super.pstmt.setString(1,eid); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public List<Schedule> findSplitById(String column, String keyWord, Long currentPage, Integer lineSize, String eid) throws SQLException { List<Schedule> all = new ArrayList<>(); String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule WHERE " + column + " LIKE ? LIMIT ?,? and seid = ? "; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, "%" + keyWord + "%"); super.pstmt.setLong(2, (currentPage - 1) * lineSize); super.pstmt.setLong(3, lineSize); super.pstmt.setString(4, eid); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public Long getAllCountById(String eid) throws SQLException { String sql = "select count(*) from schedule where seid = ?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, eid); ResultSet rs = super.pstmt.executeQuery(); if(rs.next()){ return rs.getLong(1); } return 0L; } @Override public Long getSplitCountById(String column, String keyWord, String eid) throws SQLException { String sql = "select count(*) from schedule where ? like ? and seid = ?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, column); super.pstmt.setString(2, "%"+ keyWord +"%"); super.pstmt.setString(3, eid); ResultSet rs = super.pstmt.executeQuery(); if(rs.next()){ return rs.getLong(1); } return 0L; } @Override public boolean doRemoveBySidAndSeid(long sid, String seid) throws SQLException { String sql = "delete from schedule where sid = ? and seid = ?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, sid); super.pstmt.setString(2, seid); return super.pstmt.executeUpdate() > 0; } @Override public boolean doEditAuditBySidAndSeid(long sid, String seid) throws SQLException { String sql = "update schedule set audit = 3 where sid =? and seid =?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, sid); super.pstmt.setString(2, seid); return super.pstmt.executeUpdate() > 0; } @Override public Schedule findBySidAndSeid(long sid, String eid) throws SQLException { String sql = "select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule where sid = ? and seid = ?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, sid); super.pstmt.setString(2, eid); ResultSet rs = super.pstmt.executeQuery(); Schedule vo = null; while(rs.next()) { vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); } return vo; } @Override public List<Schedule> findAllByAuditAndSid(Set<Long> sids, Set<Integer> ids) throws SQLException { List<Schedule> all = new ArrayList<>(); StringBuffer sb = new StringBuffer("select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule where 1=1 ") ; if(sids != null && sids.size() != 0) { Iterator<Long> iterSid = sids.iterator() ; sb.append(" and sid in ("); while(iterSid.hasNext()) { sb.append(iterSid.next()).append(",") ; } sb.delete(sb.length()-1,sb.length()).append(")") ; } if(ids != null && ids.size() != 0) { Iterator<Integer> iterIds = ids.iterator() ; sb.append(" and audit in ("); while(iterIds.hasNext()) { sb.append(iterIds.next()).append(",") ; } sb.delete(sb.length()-1, sb.length()).append(")") ; } sb.append(" order by audit asc") ; super.pstmt = super.conn.prepareStatement(sb.toString()); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all ; } @Override public List<Schedule> findAllByAuditAndSid(Long currentPage, Integer lineSize, Set<Long> sids, Set<Integer> ids) throws SQLException { List<Schedule> all = new ArrayList<>(); StringBuffer sb = new StringBuffer("select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule where 1=1 ") ; if(sids != null && sids.size() != 0) { Iterator<Long> iterSid = sids.iterator() ; sb.append(" and sid in ("); while(iterSid.hasNext()) { sb.append(iterSid.next()).append(",") ; } sb.delete(sb.length()-1,sb.length()).append(")") ; } if(ids != null && ids.size() != 0) { Iterator<Integer> iterIds = ids.iterator() ; sb.append(" and audit in ("); while(iterIds.hasNext()) { sb.append(iterIds.next()).append(",") ; } sb.delete(sb.length()-1, sb.length()).append(")") ; } sb.append(" order by audit asc") ; sb.append(" limit ?,?") ; super.pstmt = super.conn.prepareStatement(sb.toString()); super.pstmt.setLong(1, (currentPage - 1) * lineSize); super.pstmt.setLong(2, lineSize); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public List<Schedule> findSplitByAuditAndSid(String column, String keyWord, Long currentPage, Integer lineSize, Set<Long> sids, Set<Integer> ids) throws SQLException { List<Schedule> all = new ArrayList<>(); StringBuffer sb = new StringBuffer("select sid,seid,aeid,iid,title,sdate,subdate,audit,note,auddate,anote,ecount from schedule WHERE " + column + " LIKE ? ") ; if(sids != null && sids.size() != 0) { Iterator<Long> iterSid = sids.iterator() ; sb.append(" and sid in ("); while(iterSid.hasNext()) { sb.append(iterSid.next()).append(",") ; } sb.delete(sb.length()-1,sb.length()).append(")") ; } if(ids != null && ids.size() != 0) { Iterator<Integer> iterIds = ids.iterator() ; sb.append(" and audit in ("); while(iterIds.hasNext()) { sb.append(iterIds.next()).append(",") ; } sb.delete(sb.length()-1, sb.length()).append(")") ; } sb.append(" order by audit asc") ; sb.append(" limit ?,?") ; super.pstmt = super.conn.prepareStatement(sb.toString()); super.pstmt.setString(1, "%" + keyWord + "%"); super.pstmt.setLong(2, (currentPage - 1) * lineSize); super.pstmt.setLong(3, lineSize); ResultSet rs = super.pstmt.executeQuery() ; while (rs.next()) { Schedule vo = new Schedule(); vo.setSid(rs.getLong(1)); vo.setSeid(rs.getString(2)); vo.setAeid(rs.getString(3)); vo.setIid(rs.getLong(4)); vo.setTitle(rs.getString(5)); vo.setSdate(rs.getDate(6)); vo.setSubdate(rs.getDate(7)); vo.setAudit(rs.getInt(8)); vo.setNote(rs.getString(9)); vo.setAuddate(rs.getDate(10)); vo.setAnote(rs.getString(11)); vo.setEcount(rs.getInt(12)); all.add(vo); } return all; } @Override public Long getAllCount(Set<Long> sids, Set<Integer> ids) throws Exception { StringBuffer sb = new StringBuffer("select count(*) from schedule where 1=1 ") ; if(sids != null && sids.size() != 0) { Iterator<Long> iterSid = sids.iterator() ; sb.append(" and sid in ("); while(iterSid.hasNext()) { sb.append(iterSid.next()).append(",") ; } sb.delete(sb.length()-1,sb.length()).append(")") ; } if(ids != null && ids.size() != 0) { Iterator<Integer> iterIds = ids.iterator() ; sb.append(" and audit in ("); while(iterIds.hasNext()) { sb.append(iterIds.next()).append(",") ; } sb.delete(sb.length()-1, sb.length()).append(")") ; } sb.append(" order by audit asc") ; super.pstmt = super.conn.prepareStatement(sb.toString()); ResultSet rs = super.pstmt.executeQuery(); if(rs.next()){ return rs.getLong(1); } return 0L; } @Override public Long getSplitCount(String column, String keyWord, Set<Long> sids, Set<Integer> ids) throws Exception { StringBuffer sb = new StringBuffer("select count(*) from schedule where ? like ? ") ; if(sids != null && sids.size() != 0) { Iterator<Long> iterSid = sids.iterator() ; sb.append(" and sid in ("); while(iterSid.hasNext()) { sb.append(iterSid.next()).append(",") ; } sb.delete(sb.length()-1,sb.length()).append(")") ; } if(ids != null && ids.size() != 0) { Iterator<Integer> iterIds = ids.iterator() ; sb.append(" and audit in ("); while(iterIds.hasNext()) { sb.append(iterIds.next()).append(",") ; } sb.delete(sb.length()-1, sb.length()).append(")") ; } sb.append(" order by audit asc") ; super.pstmt = super.conn.prepareStatement(sb.toString()); super.pstmt.setString(1, column); super.pstmt.setString(2, "%"+ keyWord +"%"); ResultSet rs = super.pstmt.executeQuery(); if(rs.next()){ return rs.getLong(1); } return 0L; } @Override public boolean doEditScheduleBySidAndSeid(Schedule vo) throws SQLException { String sql = "update schedule set sid = ?,seid = ?,iid = ?,title = ?,sdate = ?,subdate = ?,note = ? where sid =?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(8, vo.getSid()); super.pstmt.setLong(1, vo.getSid()); super.pstmt.setString(2, vo.getSeid()); //super.pstmt.setString(3, vo.getAeid()); super.pstmt.setLong(3, vo.getIid()); super.pstmt.setString(4, vo.getTitle()); super.pstmt.setDate(5, new java.sql.Date(vo.getSdate().getTime())); super.pstmt.setDate(6, new java.sql.Date(vo.getSubdate().getTime())); //super.pstmt.setInt(8, vo.getAudit()); super.pstmt.setString(7, vo.getNote()); //super.pstmt.setDate(9, new java.sql.Date(vo.getSdate().getTime())); //super.pstmt.setString(10, vo.getAnote()); //super.pstmt.setInt(11, vo.getEcount()); return super.pstmt.executeUpdate() >0; } @Override public boolean editAuditBySid(Long sid,Integer audit) throws Exception { String sql = "update schedule set audit = ? where sid =?" ; super.pstmt = super.conn.prepareStatement(sql) ; super.pstmt.setInt(1, audit); super.pstmt.setLong(2, sid); return super.pstmt.executeUpdate() > 0; } @Override public boolean increaseEcount(Long sid)throws SQLException{ String sql = "update schedule set ecount = ecount+1 where sid = ?"; super.conn = DatabaseConnection.getConnection(); super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, sid); return super.pstmt.executeUpdate()>0; // TODO Auto-generated method stub } public int getEmpCount(Long sid)throws SQLException{ String sql = "select count(*) from schedule_emp where sid=?"; Connection conn = null ; conn = DatabaseConnection.getConnection(); super.pstmt = conn.prepareStatement(sql); super.pstmt.setLong(1, sid); ResultSet rs = super.pstmt.executeQuery(); while(rs.next()) { return rs.getInt(1); } return 0; } public boolean deleteByEid(String eid)throws SQLException { String sql = "delete from schedule_emp where eid =?"; super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setString(1, eid); return super.pstmt.executeUpdate() > 0; } public void decreaseEcount(Long sid)throws SQLException{ String sql = "update schedule set ecount = ecount-1 where sid = ?"; super.conn = DatabaseConnection.getConnection(); super.pstmt = super.conn.prepareStatement(sql); super.pstmt.setLong(1, sid); super.pstmt.executeUpdate(); } }
package uz.pdp.appcodingbat.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import uz.pdp.appcodingbat.entity.Language; import uz.pdp.appcodingbat.entity.User; import uz.pdp.appcodingbat.payload.LanguageDto; import uz.pdp.appcodingbat.payload.Result; import uz.pdp.appcodingbat.payload.UserDto; import uz.pdp.appcodingbat.service.LanguageService; import uz.pdp.appcodingbat.service.UserService; import java.util.List; @RestController @RequestMapping("/api/user") public class UserController { @Autowired UserService userService; /** * GET USER LIST * * @return USER LIST */ @GetMapping public ResponseEntity<List<User>> get() { List<User> users = userService.get(); return ResponseEntity.ok(users); } /** * GET ONE USER BY ID * * @param id INTEGER * @return ONE USER */ @GetMapping("/{id}") public ResponseEntity<User> getById(@PathVariable Integer id) { User user = userService.getById(id); return ResponseEntity.status(user != null ? 200 : 409).body(user); } /** * DELETE USER BY ID * * @param id INTEGER * @return RESULT */ @DeleteMapping("/{id}") public ResponseEntity<Result> delete(@PathVariable Integer id) { Result result = userService.delete(id); return ResponseEntity.status(result.isSuccess() ? 200 : 405).body(result); } /** * ADD USER * * @param userDto EMAIL (String), PASSWORD (String) * @return RESULT */ @PostMapping public ResponseEntity<Result> add(@RequestBody UserDto userDto) { Result result = userService.add(userDto); return ResponseEntity.status(result.isSuccess() ? 201 : 409).body(result); } /** * EDIT USER BY ID * * @param id INTEGER * @param userDto EMAIL (String), PASSWORD (String) * @return RESULT */ @PutMapping("/{id}") public ResponseEntity<Result> edit(@PathVariable Integer id, @RequestBody UserDto userDto) { Result result = userService.edit(id, userDto); return ResponseEntity.status(result.isSuccess() ? 202 : 409).body(result); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package CSC110_2016; /** * * @author JanithWanni */ public class Barber extends Employee{ public void cut(){ System.out.println("Barber cuts hair"); } @Override public void paySalary(){ System.out.println("Barber's salary"); } }
//반복문 while (조건 ) 문장; package com.eomcs.basic.ex06; public class Exam0310 { public static void main(String[] args) { //무한루프 //while (true) //System.out.println("안녕"); // //while (true); //빈문장 //System.out.println("안녕"); int count = 0; int sum = 0; //가장 읽기 쉽게하자 // while (count-- > -10) { // System.out.println(count); // System.out.println("안녕"); //while //int temp = count; //count = count + 1; //boolean condition = temp < 10; //if (condition == ture) { //System.out.println("안녕"); //} //} // while (count++ < 20) { // //count++; // //sum = sum + count; // if ((count &0b01) == 1)//홀수 (> 0) // continue;//즉시 상위조건문으로 실행을 이동한다. // System.out.println(count); // if ((count % 2) != 0) // continue;//아래실행하지않고 즉시 상위조건문으로 실행을 이동한다. // System.out.println(count); // } // while (count++ < 20) { // if (count > 5) // break; // System.out.println(count); // // } // int i = 2; // int j = 1; // int result = 0; // loop: // while (i <= 9) { //nested // j =1 ; // while (j <= 9) { // System.out.printf("%d x %d = %d\n", i ,j ,i*j); // if (i == 5 && j == 5) // continue loop; // //라벨이 붙은 조건문으로 이동 // //break loop; 한번에 바깥 으로탈출 // j++; // } // i++; // } //반복문 while (조건) 문장 : do 문장 while(조건); // int i = 0; // int j = 1; // do { // System.out.println(i); // i++; // } while(i <10); int a = 1; do { System.out.print(a); a++; }while (a < 5);// 조건이 참일 때 까지 실행 //while 문은 조건이 참일 때 까지 실행 System.out.println("나감"); } }
package com.vinay.kafka.kafkaproducer.controller; import com.vinay.kafka.kafkaproducer.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class KafkaProducerController { @Autowired private KafkaTemplate<String, Person> kafkaTemplate; private static final String KAFKA_EXAMPLE = "kafka_example"; @GetMapping("/{message}") public String getPublish(@PathVariable String message) { Person person = new Person(); person.setId(1001L); person.setName(message); kafkaTemplate.send(KAFKA_EXAMPLE, person); return "Published successfully...!!!"; } }
package org.point85.domain.proficy; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.point85.domain.collector.OeeEvent; import org.point85.domain.i18n.DomainLocalizer; import org.point85.domain.persistence.PersistenceService; import org.point85.domain.polling.PollingClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; /** * A ProficyClient communicates with a historian via the REST API. It polls the * historian for tag values for new OEE events. * */ public class ProficyClient extends PollingClient { // logger private static final Logger logger = LoggerFactory.getLogger(ProficyClient.class); // token time left threshold private static final int EXPIRATION_THRESHOLD_SEC = 60; // REST URL private static final String REST_API = "/historian-rest-api/v1/"; // REST endpoints public static final String TAGS_ENDPOINT = "tags"; public static final String TAGS_LIST_ENDPOINT = "tagslist"; public static final String CURR_VALUE_ENDPOINT = "datapoints/currentvalue"; public static final String RAW_VALUE_ENDPOINT = "datapoints/raw"; public static final String WRITE_VALUE_ENDPOINT = "datapoints/create"; public static final String SAMPLED_ENDPOINT = "sampled"; // JSON parser private final Gson gson = new Gson(); // Oauth token private OauthBearerToken bearerToken; // listener to call back for tag data events private ProficyEventListener eventListener; // watch mode flag for trend chart private boolean watchMode = false; // time when polling started private Instant pollingStartTime = Instant.now(); /** * Construct a Proficy client * * @param dataSource {@link ProficySource} */ public ProficyClient(ProficySource dataSource) { this.dataSource = dataSource; } /** * Construct a Proficy client * * @param eventListener {@link ProficyEventListener} * @param dataSource {@link ProficySource} * @param sourceIds List of tag names to monitor * @param pollingPeriods List of polling periods for each tag */ public ProficyClient(ProficyEventListener eventListener, ProficySource dataSource, List<String> sourceIds, List<Integer> pollingPeriods) { super(dataSource, sourceIds, pollingPeriods); this.eventListener = eventListener; } private OauthBearerToken getBearerToken() throws Exception { if (isTokenExpiring()) { // get a fresh token String json = sendBasicAuthenticationRequest(); bearerToken = gson.fromJson(json, OauthBearerToken.class); bearerToken.setExpirationTime(LocalDateTime.now().plusSeconds(bearerToken.getExpiresIn())); } return bearerToken; } private boolean isTokenExpiring() { if (bearerToken == null) { return true; } return Duration.between(bearerToken.getExpirationTime(), LocalDateTime.now()) .getSeconds() < EXPIRATION_THRESHOLD_SEC; } private ProficySource getProficySource() { return (ProficySource) getDataSource(); } private String sendBasicAuthenticationRequest() throws Exception { String usernameColonPassword = getProficySource().getUserName() + ":" + getProficySource().getUserPassword(); String uaaUrl = "http://" + getProficySource().getHost() + ":" + getProficySource().getUaaHttpPort() + "/uaa/oauth/token?grant_type=client_credentials"; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes()); if (logger.isInfoEnabled()) { logger.info( "Sending UAA Oath token request to " + uaaUrl + " for user " + getProficySource().getUserName()); } BufferedReader httpResponseReader = null; try { // Connect to the web server endpoint URL serverUrl = new URL(uaaUrl); HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection(); // Set HTTP method as GET urlConnection.setRequestMethod("GET"); // Include the HTTP Basic Authentication payload urlConnection.addRequestProperty("Authorization", basicAuthPayload); // Read response from web server, which will trigger HTTP Basic Authentication // request to be sent. httpResponseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String lineRead = null; String json = null; while ((lineRead = httpResponseReader.readLine()) != null) { // just one line json = lineRead; } return json; } finally { if (httpResponseReader != null) { try { httpResponseReader.close(); } catch (IOException ioe) { // ignore } } } } private String buildUrl(String resource, Map<String, String> parameters) throws Exception { if (getProficySource().getHost() == null) { throw new Exception(DomainLocalizer.instance().getErrorString("proficy.no.host")); } Integer port = getProficySource().getHttpsPort() != null ? getProficySource().getHttpsPort() : getProficySource().getHttpPort(); if (port == null) { throw new Exception(DomainLocalizer.instance().getErrorString("proficy.no.port")); } String protocol = getProficySource().getHttpsPort() != null ? "https" : "http"; StringBuilder builder = new StringBuilder(); builder.append(protocol).append("://").append(getProficySource().getHost()).append(":").append(port) .append(REST_API); builder.append(resource); char separator = '?'; if (parameters != null) { for (Entry<String, String> entry : parameters.entrySet()) { builder.append(separator).append(entry.getKey()).append("=").append(entry.getValue()); separator = '&'; } } return builder.toString(); } private void checkSSLCertificateValidation() throws Exception { if (getProficySource().getValidateCertificate()) { if (logger.isInfoEnabled()) { logger.info("SSL certificate validation is enabled."); } return; } // disable certificate validation TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // not implemented } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // not implemented } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); if (logger.isInfoEnabled()) { logger.info("SSL certificate validation is disabled."); } } private String sendGetRequest(String resource, Map<String, String> parameters) throws Exception { checkSSLCertificateValidation(); HttpURLConnection conn = null; try { URL url = new URL(buildUrl(resource, parameters)); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "Bearer " + getBearerToken().getAccessToken()); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("GET"); if (logger.isInfoEnabled()) { logger.info("Sending GET request to " + url); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output; StringBuilder responseBuffer = new StringBuilder(); while ((output = in.readLine()) != null) { responseBuffer.append(output); } in.close(); return responseBuffer.toString(); } finally { if (conn != null) { conn.disconnect(); } } } private void sendPostRequest(String resource, Map<String, String> parameters, TagData body) throws Exception { checkSSLCertificateValidation(); HttpURLConnection conn = null; try { // POST event URL url = new URL(buildUrl(resource, parameters)); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + getBearerToken().getAccessToken()); conn.setRequestProperty("Content-Type", "application/json"); // serialize the body String payload = gson.toJson(body); if (logger.isInfoEnabled()) { logger.info("Sending POST request to " + url + "\n content: " + payload); } OutputStream os = conn.getOutputStream(); os.write(payload.getBytes()); os.flush(); checkResponseCode(conn); } finally { if (conn != null) { conn.disconnect(); } } } private Object serialize(String json, Class<?> klass) { return gson.fromJson(json, klass); } /** * Read the tag names matching the mask up to the number specified * * @param nameMask Name mask with wild card characters * @param maxNumber Maximum number of tag names to return * @return List of matching tag names * @throws Exception Exception */ public List<String> readTagNames(String nameMask, Integer maxNumber) throws Exception { Map<String, String> parameters = new HashMap<>(); if (nameMask != null && !nameMask.isEmpty()) { parameters.put("nameMask", nameMask); } if (maxNumber != null) { parameters.put("maxNumber", String.valueOf(maxNumber)); } // tags API String value = sendGetRequest(ProficyClient.TAGS_ENDPOINT, parameters); Tags tags = (Tags) serialize(value, Tags.class); return tags.getTags(); } /** * Read the tag details per the request parameters * * @param parameters {@link TagsListRequestParameters} * @return Tags list {@link TagsList} * @throws Exception Exception */ public TagsList readTagsList(TagsListRequestParameters parameters) throws Exception { String value = sendGetRequest(ProficyClient.TAGS_LIST_ENDPOINT, parameters.getParameters()); return (TagsList) serialize(value, TagsList.class); } private void checkErrorCode(int code, String context) throws Exception { if (code != ErrorCode.Success.getCode()) { ErrorCode errorCode = ErrorCode.fromInt(code); String msg = DomainLocalizer.instance().getErrorString(errorCode.name()); throw new Exception(context != null ? context + ": " + msg : msg); } } /** * Read the current value of the specified tags * * @param tagNames List of tag names * @return Tag values {@link TagValues} * @throws Exception Exception */ public TagValues readCurrentValue(List<String> tagNames) throws Exception { String tagList = ""; for (String tagName : tagNames) { if (!tagList.isEmpty()) { tagList += ";"; } tagList += tagName; } Map<String, String> parameters = new HashMap<>(); parameters.put("tagNames", tagList); String value = sendGetRequest(ProficyClient.CURR_VALUE_ENDPOINT, parameters); TagValues currentValues = (TagValues) serialize(value, TagValues.class); checkErrorCode(currentValues.getErrorCode(), null); for (TagData tagData : currentValues.getTagData()) { checkErrorCode(tagData.getErrorCode(), tagData.getTagName()); } return currentValues; } /** * Read the stored tag values for the specified time period and direction * * @param tagNames List of tag names to read * @param start Starting time instant * @param end Ending time instant * @param direction {@link TagDirection} * @param count Maximum number of values to read * @return Tag data values {@link TagValues} * @throws Exception Exception */ public TagValues readRawDatapoints(List<String> tagNames, Instant start, Instant end, TagDirection direction, Integer count) throws Exception { String startTime = start.truncatedTo(ChronoUnit.MILLIS).toString(); String endTime = end.truncatedTo(ChronoUnit.MILLIS).toString(); String tags = ""; // tag names for (int i = 0; i < tagNames.size(); i++) { if (i > 0) { tags += ";"; } tags += tagNames.get(i); } Map<String, String> parameters = new HashMap<>(); // fill out URL StringBuilder sb = new StringBuilder(); sb.append(ProficyClient.RAW_VALUE_ENDPOINT).append('/').append(tags).append('/').append(startTime).append('/') .append(endTime).append('/').append(direction.getDirection()); if (count != null) { sb.append('/').append(count); } String url = sb.toString(); String value = sendGetRequest(url, parameters); TagValues currentValues = (TagValues) serialize(value, TagValues.class); checkErrorCode(currentValues.getErrorCode(), null); for (TagData tagData : currentValues.getTagData()) { checkErrorCode(tagData.getErrorCode(), tagData.getTagName()); } return currentValues; } private void checkResponseCode(HttpURLConnection conn) throws Exception { int codeGroup = conn.getResponseCode() / 100; if (codeGroup != 2) { String msg = DomainLocalizer.instance().getErrorString("failed.code", conn.getResponseCode()); throw new Exception(msg); } // read the response json for an error BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output; StringBuilder sb = new StringBuilder(); while ((output = in.readLine()) != null) { sb.append(output); } in.close(); TagError tagError = gson.fromJson(sb.toString(), TagError.class); if (!tagError.getEnumeratedError().equals(ErrorCode.Success)) { String msg = DomainLocalizer.instance().getErrorString(tagError.getEnumeratedError().name()); if (tagError.getErrorMessage() != null && !tagError.getErrorMessage().isEmpty()) { msg += ": " + tagError.getErrorMessage(); } throw new Exception(msg); } } /** * Write the data value to the tag * * @param tagName Name of tag * @param value Data value * @throws Exception Exception */ public void writeTag(String tagName, Object value) throws Exception { TagSample sample = new TagSample(value); TagData tagData = new TagData(tagName); tagData.getSamples().add(sample); Map<String, String> parameters = new HashMap<>(); sendPostRequest(ProficyClient.WRITE_VALUE_ENDPOINT, parameters, tagData); } public ProficyEventListener getEventListener() { return eventListener; } public void setEventListener(ProficyEventListener eventListener) { this.eventListener = eventListener; } @Override protected void onPoll(String sourceId) throws Exception { if (sourceId == null) { return; } if (logger.isInfoEnabled()) { logger.info("Querying for new Proficy events for tag " + sourceId); } // query historian for new events // get last event for any of these tags if (!watchMode) { // go to database OeeEvent lastEvent = PersistenceService.instance().fetchLastEvent(sourceIds); if (lastEvent != null) { pollingStartTime = lastEvent.getStartTime().toInstant(); } } Instant end = Instant.now(); // fetch all events in this period. Start after the last poll TagValues tagValues = readRawDatapoints(sourceIds, pollingStartTime.plus(1, ChronoUnit.MILLIS), end, TagDirection.Forward, 0); // find max time stamp List<TagData> tagDataList = tagValues.getTagData(); Instant lastTimestamp = null; for (TagData data : tagDataList) { if (logger.isInfoEnabled() && !data.getSamples().isEmpty()) { logger.info("Found " + data.getSamples().size() + " samples for tag " + data.getTagName()); } for (TagSample sample : data.getSamples()) { Instant timestamp = sample.getTimeStampInstant(); if (lastTimestamp == null || timestamp.isAfter(lastTimestamp)) { lastTimestamp = timestamp; } } } if (lastTimestamp != null) { pollingStartTime = lastTimestamp; } // call the listener back for (TagData tagData : tagDataList) { if (!tagData.getSamples().isEmpty()) { eventListener.onProficyEvent(tagData); } } } public boolean isWatchMode() { return watchMode; } public void setWatchMode(boolean watchMode) { this.watchMode = watchMode; } }
package com.legaoyi.file.messagebody; import java.util.List; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 上传基本信息 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2019-05-20 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "1210_tjsatl" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class Tjsatl_2017_1210_MessageBody extends MessageBody { private static final long serialVersionUID = 7643584698183762496L; /** 报警标识号,终端ID **/ @JsonProperty("terminalId") private String terminalId; /** 报警标识号,时间 **/ @JsonProperty("alarmTime") private String alarmTime; /** 报警标识号,序号 **/ @JsonProperty("alarmSeq") private int alarmSeq; /** 报警标识号,预留 **/ @JsonProperty("alarmExt") private int alarmExt; /** 报警标识号,附件数量 **/ @JsonProperty("totalFile") private int totalFile; /** 报警编号 **/ @JsonProperty("alarmId") private String alarmId; /** 信息类型,0x00:正常报警文件信息,0x01:补传报警文件信息 **/ @JsonProperty("type") private int type; /** 附件信息列表 **/ @JsonProperty("fileList") private List<Map<String, Object>> fileList; public final String getTerminalId() { return terminalId; } public final void setTerminalId(String terminalId) { this.terminalId = terminalId; } public final String getAlarmTime() { return alarmTime; } public final void setAlarmTime(String alarmTime) { this.alarmTime = alarmTime; } public final int getAlarmSeq() { return alarmSeq; } public final void setAlarmSeq(int alarmSeq) { this.alarmSeq = alarmSeq; } public final int getAlarmExt() { return alarmExt; } public final void setAlarmExt(int alarmExt) { this.alarmExt = alarmExt; } public final int getTotalFile() { return totalFile; } public final void setTotalFile(int totalFile) { this.totalFile = totalFile; } public final String getAlarmId() { return alarmId; } public final void setAlarmId(String alarmId) { this.alarmId = alarmId; } public final int getType() { return type; } public final void setType(int type) { this.type = type; } public final List<Map<String, Object>> getFileList() { return fileList; } public final void setFileList(List<Map<String, Object>> fileList) { this.fileList = fileList; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package livraria.bo; import java.util.List; import livraria.persistence.LivroDao; import livraria.persistence.Dao; import livraria.vo.Categoria; import livraria.vo.Livro; /** * * @author Nilliam Ometto */ public class LivroBO { private Dao dao; private Livro livro; private List<Livro> livroList; private boolean isUpdate; public LivroBO() { this.dao = new LivroDao(); } public List<Livro> getAll() { return livroList = dao.getAll(); } public void setSelected(int index) { livro = livroList.get(index); } public Livro getLivro() { return livro; } public boolean removeSelected(int index) { return dao.remove(livroList.get(index)); } public void setUpdate(boolean isUpdate) { this.isUpdate = isUpdate; } public boolean isUpdate() { return isUpdate; } public boolean persistir(String ano, Categoria categoria, String editora, String idioma, String preco, String titulo, String infoAdic) { Livro c = isUpdate ? livro : new Livro(); c.setAno(ano); c.setCategoria(categoria); c.setEditora(editora); c.setIdioma(idioma); c.setPreco(Double.parseDouble(preco.replace("\\.", "").replace(',', '.'))); c.setTitulo(titulo); c.setInfoAdic(infoAdic); return dao.persistir(c); } public Integer getId() { return livro.getId(); } public String getTitulo() { return livro.getTitulo(); } public String getEditora() { return livro.getEditora(); } public Categoria getCategoria() { return livro.getCategoria(); } public String getAno() { return livro.getAno(); } public String getIdioma() { return livro.getIdioma(); } public Double getPreco() { return livro.getPreco(); } public String getInfoAdic() { return livro.getInfoAdic(); } }
/** * */ package org.escoladeltreball.thirdassignmenttopic; /** * @author iaw39443990 * */ public abstract class Tablet extends DeviceImpl { /** * @param marca * @param model * @param speed */ public Tablet(String marca, String model, int speed) { super(marca, model, speed); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see org.escoladeltreball.thirdassignmenttopic.Device#trunOn() */ @Override public void trunOn() { // TODO Auto-generated method stub } }
package com.project.springboot.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.project.springboot.entity.ProductType; import com.project.springboot.services.ProductTypeService; @CrossOrigin @RestController @RequestMapping("") public class ProductTypeController { @Autowired private ProductTypeService productTypeService; @RequestMapping(value = "/productTypes", method = RequestMethod.GET) public ResponseEntity<List<ProductType>> findAll() { List<ProductType> productTypes = productTypeService.findAll(); if (productTypes.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(productTypes, HttpStatus.OK); } @RequestMapping(value = "/productTypes/{id}", method = RequestMethod.GET) public ProductType getProductTypeById(@PathVariable("id") Integer id) { ProductType productType = productTypeService.findById(id); return productType; } // @RequestMapping(value = "/productTypes/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) // public ResponseEntity<ProductType> getProductTypesById(@PathVariable("id") Integer id) { // Optional<ProductType> productTypes = productTypeService.findById(id); // // if (!productTypes.isPresent()) { // return new ResponseEntity<>(productTypes.get(), HttpStatus.NO_CONTENT); // } // return new ResponseEntity<>(productTypes.get(), HttpStatus.OK); // } @RequestMapping(value = "/productTypes", method = RequestMethod.POST) public ResponseEntity<ProductType> createProductTypes(@RequestBody ProductType productTypes, UriComponentsBuilder builder) { productTypeService.save(productTypes); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/productTypes/{id}").buildAndExpand(productTypes.getId()).toUri()); return new ResponseEntity<>(productTypes, HttpStatus.CREATED); } @RequestMapping(value = "/productTypes/{id}", method = RequestMethod.PUT) public ProductType updateProductTypes(@PathVariable("id") Integer id, @RequestBody @Validated ProductType productTypes) { productTypeService.findById(id); return productTypeService.save(productTypes); } @RequestMapping(value = "/productTypes/{id}", method = RequestMethod.DELETE) public void deleteProductTypes(@PathVariable("id") Integer id) { ProductType productType = productTypeService.findById(id); productTypeService.delete(productType.getId()); } }
package org.androware.androbeans; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import org.androware.androbeans.beans.Flow; import org.androware.androbeans.beans.Top; import org.androware.androbeans.utils.FilterLog; import org.androware.androbeans.utils.ResourceUtils; public class MainActivity extends Activity { public final static String TAG = "main"; public void l(String s) { FilterLog.inst().log(TAG, s); } public void l(String tag, String s) { FilterLog.inst().log(tag, s); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ResourceUtils.R = R.class; FilterLog.inst().activateTag(TAG); FilterLog.inst().activateTag(JsonObjectWriter.TAG); try { Top top = (Top) ObjectReaderFactory.getInstance(this).makeAndRunMapReader(Top.makeTextMap(), Top.class); l(top.toString()); Flow flow = (Flow) ObjectReaderFactory.getInstance().makeAndRunLinkedJsonReader("test_merge", Flow.class); l(flow.toStringTest()); ObjectWriterFactory.getInstance(this).writeJsonObjectToExternalFile("xyz.js", flow); } catch (ObjectReadException e) { } catch (ObjectWriteException e) { } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent contextWrapper in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.cunoraz.continuouscrollable; import android.animation.ValueAnimator; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.IntDef; import android.util.AttributeSet; import android.util.Log; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import com.cunoraz.library.R; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by cuneytcarikci on 17/08/2017. */ public class ContinuousScrollableImageView extends LinearLayout { //<editor-fold desc="DEFAULT_DIRECTION = LEFT"> public static final int UP = 0; public static final int RIGHT = 1; public static final int DOWN = 2; public static final int LEFT = 3; @IntDef({UP, RIGHT, DOWN, LEFT}) @Retention(RetentionPolicy.SOURCE) @interface Directions { } @Directions int DEFAULT_DIRECTION = LEFT; //</editor-fold> //<editor-fold desc="DEFAULT_ASYMPTOTE = HORIZONTAL"> public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; @IntDef({HORIZONTAL, VERTICAL}) @Retention(RetentionPolicy.SOURCE) @interface Asymptote { } @Asymptote int DEFAULT_ASYMPTOTE = HORIZONTAL; //</editor-fold> //<editor-fold desc="DEFAULT_SCALE_TYPE = CENTER"> public static final int MATRIX = 0; public static final int FIT_XY = 1; public static final int FIT_START = 2; public static final int FIT_CENTER = 3; public static final int FIT_END = 4; public static final int CENTER = 5; public static final int CENTER_CROP = 6; public static final int CENTER_INSIDE = 7; @IntDef({MATRIX, FIT_XY, FIT_START, FIT_CENTER, FIT_END, CENTER, CENTER_CROP, CENTER_INSIDE}) @Retention(RetentionPolicy.SOURCE) @interface ScaleType { } @ScaleType int DEFAULT_SCALE_TYPE = FIT_CENTER; //</editor-fold> private final int DEFAULT_RESOURCE_ID = -1; private final int DEFAULT_DURATION = 3000; private int DIRECTION_MULTIPLIER = -1; private int duration; private int resourceId; private int direction; private int scaleType; private ValueAnimator animator; private ImageView firstImage; private ImageView secondImage; private boolean isBuilt = false; public static final String TAG = ContinuousScrollableImageView.class.getSimpleName(); public ContinuousScrollableImageView(Context context) { super(context); init(context); } public ContinuousScrollableImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ContinuousScrollableImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setViewAttributes(context, attrs, defStyleAttr); init(context); } private void setViewAttributes(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ContinuousScrollableImageView, defStyleAttr, 0); resourceId = array.getResourceId(R.styleable.ContinuousScrollableImageView_imageSrc, DEFAULT_RESOURCE_ID); direction = array.getInt(R.styleable.ContinuousScrollableImageView_direction, DEFAULT_DIRECTION); duration = array.getInt(R.styleable.ContinuousScrollableImageView_duration, DEFAULT_DURATION); scaleType = array.getInt(R.styleable.ContinuousScrollableImageView_scaleType, DEFAULT_SCALE_TYPE); setDirectionFlags(direction); array.recycle(); } private void setDirectionFlags(int direction) { switch (direction) { case UP: DIRECTION_MULTIPLIER = 1; DEFAULT_ASYMPTOTE = VERTICAL; break; case RIGHT: DIRECTION_MULTIPLIER = -1; DEFAULT_ASYMPTOTE = HORIZONTAL; break; case DOWN: DIRECTION_MULTIPLIER = -1; DEFAULT_ASYMPTOTE = VERTICAL; break; case LEFT: DIRECTION_MULTIPLIER = 1; DEFAULT_ASYMPTOTE = HORIZONTAL; break; } } /** * @param context */ private void init(Context context) { inflate(context, R.layout.continuos_scrollable_imageview_layout, this); build(); } /** * Set duration in ms * * @param duration */ public void setDuration(int duration) { this.duration = duration; isBuilt = false; build(); } /** * set scrolling direction * * @param direction */ public void setDirection(@Directions int direction) { this.direction = direction; isBuilt = false; setDirectionFlags(direction); build(); } /** * @param resourceId */ public void setResourceId(int resourceId) { this.resourceId = resourceId; firstImage.setImageResource(this.resourceId); secondImage.setImageResource(this.resourceId); } /** * set image scale type * * @param scaleType */ public void setScaleType(@ScaleType int scaleType) { if (firstImage == null || secondImage == null) { throw new NullPointerException(); } ImageView.ScaleType type = ImageView.ScaleType.CENTER; switch (scaleType) { case MATRIX: type = ImageView.ScaleType.MATRIX; break; case FIT_XY: type = ImageView.ScaleType.FIT_XY; break; case FIT_START: type = ImageView.ScaleType.FIT_START; break; case FIT_CENTER: type = ImageView.ScaleType.FIT_CENTER; break; case FIT_END: type = ImageView.ScaleType.FIT_END; break; case CENTER: type = ImageView.ScaleType.CENTER; break; case CENTER_CROP: type = ImageView.ScaleType.CENTER_CROP; break; case CENTER_INSIDE: type = ImageView.ScaleType.CENTER_INSIDE; break; } this.scaleType = scaleType; firstImage.setScaleType(type); secondImage.setScaleType(type); } private void build() { if (isBuilt) return; isBuilt = true; setImages(); if (animator != null) animator.removeAllUpdateListeners(); animator = ValueAnimator.ofFloat(0.0f, DIRECTION_MULTIPLIER * (-1.0f)); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setInterpolator(new LinearInterpolator()); animator.setDuration(duration); switch (DEFAULT_ASYMPTOTE) { case HORIZONTAL: animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { { float progress = DIRECTION_MULTIPLIER * (-(float) animation.getAnimatedValue()); float width = DIRECTION_MULTIPLIER * (-firstImage.getWidth()); float translationX = width * progress; firstImage.setTranslationX(translationX); secondImage.setTranslationX(translationX - width); } } }); break; case VERTICAL: animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { { float progress = DIRECTION_MULTIPLIER * (-(float) animation.getAnimatedValue()); float height = DIRECTION_MULTIPLIER * (-firstImage.getHeight()); float translationY = height * progress; firstImage.setTranslationY(translationY); secondImage.setTranslationY(translationY - height); } } }); break; } animator.start(); } private void setImages() { if (resourceId == -1) { Log.e(TAG, "image must be initialized before it can be used. You can use in XML like this: (app:imageSrc=\"@drawable/yourImage\") "); return; } firstImage = this.findViewById(R.id.first_image); secondImage = this.findViewById(R.id.second_image); firstImage.setImageResource(resourceId); secondImage.setImageResource(resourceId); setScaleType(scaleType); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (animator != null) animator.cancel(); } public static final class Builder { private ContinuousScrollableImageView scrollableImageView; public Builder(Activity activity) { scrollableImageView = new ContinuousScrollableImageView(activity); } public Builder setDuration(int duration) { scrollableImageView.setDuration(duration); return this; } public Builder setResourceId(int resourceId) { scrollableImageView.setResourceId(resourceId); return this; } public Builder setDirection(@Directions int direction) { scrollableImageView.setDirection(direction); return this; } public Builder setScaleType(@ScaleType int scaleType) { scrollableImageView.setScaleType(scaleType); return this; } public ContinuousScrollableImageView build() { return scrollableImageView; } } }
package br.com.saulofarias.customerapi.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonFormat; import com.sun.istack.NotNull; @Entity @Table(name = "customer") public class Customer implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(length = 50, nullable = false) private String name; @Column(length = 1, nullable = false) private Character sex; @JsonFormat(pattern = "yyyy-MM-dd") private Date dateBirth; private Integer age; @OneToOne() @JoinColumn(name = "city", referencedColumnName = "id", nullable = false) @NotNull private City city; public Customer() { } public Customer(Long id, String name, Character sex, Date dateBirth, Integer age, City city) { this.id = id; this.name = name; this.sex = sex; this.dateBirth = dateBirth; this.age = age; this.city = city; } 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 Character getSex() { return sex; } public void setSex(Character sex) { this.sex = sex; } public Date getDateBirth() { return dateBirth; } public void setDateBirth(Date dateBirth) { this.dateBirth = dateBirth; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } }
package p0200; public class P0215 { private int iAge; private String sNom; public P0215(int age, String Nom) { this.iAge = age; this.sNom = Nom; } public void crie() { System.out.printf("Wouaf Wouaf (Je m'appel %s et j'ai %d jours) !!\n",sNom,iAge); } public void dors() { iAge = iAge + 1; // age++ System.out.printf("ZZzzz, %s ce repose\n",sNom); } public static void main(String[] args) { P0215 chien1; P0215 chien2; P0215 chien3; chien1 = new P0215(5, "Medor"); chien2 = new P0215(10, "Rex"); chien3 = new P0215(2, "Ziki"); chien1.crie(); chien1.dors(); chien1.dors(); chien1.crie(); chien2.crie(); chien3.dors(); chien3.dors(); chien3.crie(); } }
package com.example.selectandcrop.Model; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.example.selectandcrop.Interfaces.ListItemClickListener; import com.example.selectandcrop.R; import com.yanzhenjie.album.AlbumFile; import java.io.File; import java.util.ArrayList; public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.MyViewHolder> { private LayoutInflater inflater; private ArrayList<AlbumFilePOJO> imageModelArrayList; final private ListItemClickListener mOnClickListener; int selectedPosition=-1; public FruitAdapter(Context ctx, ArrayList<AlbumFilePOJO> imageModelArrayList, ListItemClickListener mOnClickListener){ inflater = LayoutInflater.from(ctx); this.imageModelArrayList = imageModelArrayList; this.mOnClickListener = mOnClickListener; } @Override public FruitAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.recycler_item, parent, false); MyViewHolder holder = new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(FruitAdapter.MyViewHolder holder, final int position) { if(selectedPosition==position) holder.backgroundLayout.setBackgroundColor(Color.parseColor("#88cccc")); else holder.backgroundLayout.setBackgroundColor(Color.parseColor("#ffffff")); File imgFile = new File(imageModelArrayList.get(position).getmPath()); if(imgFile.exists()){ Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); holder.iv.setImageBitmap(myBitmap); } //holder.iv.setImageBitmap(Integer.parseInt(imageModelArrayList.get(position).getPath())); // holder.time.setText(imageModelArrayList.get(position).getName()); } @Override public int getItemCount() { return imageModelArrayList.size(); } class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ CardView backgroundLayout; ImageView iv; public MyViewHolder(View itemView) { super(itemView); backgroundLayout=(CardView)itemView.findViewById(R.id.card_view); iv = (ImageView) itemView.findViewById(R.id.iv); itemView.setOnClickListener(this); } @Override public void onClick(View v) { int position = getAdapterPosition(); selectedPosition=position; mOnClickListener.onListItemClick(itemView,position); notifyDataSetChanged(); } } }
package app.letsqit.com.compiler.processor; import app.letsqit.com.annotations.annotations.AutoDSL; /** * Created by gilgoldzweig on 08/07/2017. */ @AutoDSL public class Testgggg { }
package com.myth.springboot.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.myth.springboot.entity.Msg; import com.myth.springboot.entity.Student; import com.myth.springboot.entity.Teacher; import com.myth.springboot.entity.User; import com.myth.springboot.service.StudentService; import com.myth.springboot.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.websocket.server.PathParam; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class StudentController { @Autowired StudentService studentService; @Autowired UserService userService; /** * 学生业务 * * @return */ @RequestMapping("/selectStudentByName") @ResponseBody public Map selectStudentByName(String s_name){ PageHelper.startPage(1,10); Student student=new Student(); student.setS_name(s_name); List<Student> list=studentService.selectStudentByName(s_name); PageInfo pageInfo = new PageInfo(list,5); Map<String,Object> map = new HashMap<>(); map.put("data",pageInfo); return map; } @RequestMapping("/studentAdd") @ResponseBody public Msg studentAdd(@PathParam("user_name") String user_name, @PathParam("name") String name, @PathParam("sex") String sex, @PathParam("c_id") String c_id) { System.out.println(user_name); List<Student> students = studentService.studentSelect(new Student(user_name)); if (!students.isEmpty()) { return Msg.success().add("msg", "该生信息已存在!!!"); } List<User> users = userService.userSelect(new User(user_name)); if (users.isEmpty()) { return Msg.success().add("msg", "无此用户!"); } if (users.get(0).getType_id().equals("3")) { Student student = new Student(user_name, name, sex, c_id); int i = studentService.studentInsert(student); if (i > 0) { return Msg.success().add("msg", "添加学生详情成功"); } else { return Msg.success().add("msg", "添加学生详情失败"); } } else { return Msg.success().add("msg", "权限和信息不匹配!"); } } @RequestMapping("/studentList") @ResponseBody public Msg studentList() { Student s = new Student(); List<Student> students = studentService.studentSelect(s); //mv.addObject("students", student); return Msg.success().add("student", students); } @RequestMapping("/studentListWithPage") @ResponseBody public Map studentList(String page, String limit) { PageHelper.startPage(Integer.valueOf(page).intValue(), Integer.valueOf(limit).intValue()); Student s = new Student(); List<Student> student = studentService.studentSelect(s); PageInfo pageInfo = new PageInfo(student, 5); //mv.addObject("students", student); Map<String, Object> map = new HashMap<>(); map.put("data", pageInfo); return map; } /* 得到当前id的学生的所有信息 */ @RequestMapping("/studentGetById") public ModelAndView studentGetById(String id) { ModelAndView mv = new ModelAndView("student/student-update"); Student s = new Student(); int s_id = Integer.valueOf(id).intValue(); s.setS_id(s_id); List<Student> student = studentService.studentSelect(s); Student ss = student.get(0); mv.addObject("student", ss); return mv; } /* 修改学生信息 */ @RequestMapping("/studentUpdate") @ResponseBody public Msg studentUpdate(String id, String name, String sex, String c_id) { Integer s_id = Integer.valueOf(id).intValue(); Student student = new Student(s_id, name, sex, c_id); int i = studentService.studentUpdateById(student); if (i > 0) { return Msg.success().add("msg", "学生信息修改成功"); } else { return Msg.success().add("msg", "学生信息修改失败!!!!"); } } /* 通过id删除学生 */ @RequestMapping("/studentDelete") @ResponseBody public Msg studentDelete(String id) { //System.out.println(id1); Integer s_id; s_id = Integer.valueOf(id).intValue(); Student student = new Student(); student.setS_id(s_id); int i = studentService.studentDeleteById(student); if (i > 0) { return Msg.success().add("msg", "学生详情删除成功"); } else { return Msg.success().add("msg", "学生详情删除失败"); } } @RequestMapping("/studentDeleteMany") @ResponseBody public Msg studentDeleteMany(String id) { String str[] = id.split(","); String s = ""; for (int i = 0; i < str.length; i++) { Integer s_id = Integer.valueOf(str[i]).intValue(); Student student = new Student(); student.setS_id(s_id); int j = studentService.studentDeleteById(student); if (j > 0) { s += str[i] + "学生详情删除成功"; } else { s += str[i] + "学生详情删除失败"; } } return Msg.success().add("msg", s); } }
/** * @author DengYouming * @since 2016-7-29 下午2:25:54 */ package org.hpin.webservice.util; import java.util.Comparator; /** * ASCII码比较器 * @author DengYouming * @since 2016-7-29 下午2:25:54 */ public class AsciiComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { return compareOneByOne(o1, o2); } /** * 逐字比较字符串ascii码 * @param o1 * @param o2 * @return int * @author DengYouming * @since 2016-7-29 下午4:33:42 */ private static int compareOneByOne(String o1, String o2){ int res = 0; if(o1!=null&&o1.length()>0&&o2!=null&&o2.length()>0){ int len = o1.length()<=o2.length()?o1.length():o2.length(); for (int i = 0; i < len; i++) { if(o1.charAt(i)==o2.charAt(i)){ if(i==len-1){ if(o1.length()>o2.length()){ res = 1; break; }else{ res = -1; break; } } continue; } if(o1.charAt(i)>o2.charAt(i)){ res = 1; break; }else{ res = -1; break; } } } return res; } }
/** * */ package com.example.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; /** * @author djain * */ @Entity @Table(name = "SalesEntry") public class SalesEntry { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="SalesId") private Integer salesId; @Column(name="DateofSale") private Date dateOfSale; @OneToOne @JoinColumn(name = "ProductID") private ProductTable product; @Column(name="SaleAmount") private Double saleAmount; /** * @return the salesId */ public Integer getSalesId() { return salesId; } /** * @param salesId the salesId to set */ public void setSalesId(Integer salesId) { this.salesId = salesId; } /** * @return the dateOfSale */ public Date getDateOfSale() { return dateOfSale; } /** * @param dateOfSale the dateOfSale to set */ public void setDateOfSale(Date dateOfSale) { this.dateOfSale = dateOfSale; } /** * @return the saleAmount */ public Double getSaleAmount() { return saleAmount; } /** * @param saleAmount the saleAmount to set */ public void setSaleAmount(Double saleAmount) { this.saleAmount = saleAmount; } /** * @return the product */ public ProductTable getProduct() { return product; } /** * @param product the product to set */ public void setProduct(ProductTable product) { this.product = product; } }
package com.rednovo.ace.widget.gift; import android.content.Context; import android.os.Build; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.animation.PropertyValuesHolder; import com.rednovo.ace.R; import com.rednovo.libs.common.ScreenUtils; import com.rednovo.libs.common.ShowUtils; /** * Created by lilong on 16/5/9. * 花束礼物动画布局 */ public class FlowerGiftView extends BaseGiftView { private StartView startFirst; private StartView startSecond; private StartView startThird; private StartView startFourth; private StartView startFifth; private StartView startSixth; private StartView startSeventh; private StartView startEighth; private AnimatorSet animatorSet; public FlowerGiftView(Context context) { super(context, R.layout.flower_layout); startFirst = (StartView) findViewById(R.id.start_first); startSecond = (StartView) findViewById(R.id.start_second); startThird = (StartView) findViewById(R.id.start_third); startFourth = (StartView) findViewById(R.id.start_fourth); startFifth = (StartView) findViewById(R.id.start_fifth); startSixth = (StartView) findViewById(R.id.start_sixth); startSeventh = (StartView) findViewById(R.id.start_seventh); startEighth = (StartView) findViewById(R.id.start_eighth); } @Override public void startAnimation(ViewGroup speciaGiftContainer, AnimationEndListener animationEndListener) { super.startAnimation(speciaGiftContainer, animationEndListener); if(speciaGiftContainer.getChildAt(0) instanceof FlowerGiftView) { giftView.setVisibility(View.VISIBLE); } else { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.BOTTOM; params.bottomMargin = ShowUtils.dip2px(mContext, 60); speciaGiftContainer.addView(this); this.setLayoutParams(params); } startAnimation(animationEndListener); } private void startAnimation(final AnimationEndListener animationEndListener) { PropertyValuesHolder transY = PropertyValuesHolder.ofFloat("translationY", ScreenUtils.getScreenHeight(mContext), 0F); PropertyValuesHolder alphaIn = PropertyValuesHolder.ofFloat("alpha", 0F, 1.0F); PropertyValuesHolder alphaOut = PropertyValuesHolder.ofFloat("alpha", 1.0F, 0F); // 1.花束移入屏幕伴随淡入动画 ObjectAnimator viewIn = ObjectAnimator.ofPropertyValuesHolder(this, transY, alphaIn); viewIn.setDuration(800); viewIn.setInterpolator(new DecelerateInterpolator()); // 2.花束停留在屏幕中 ObjectAnimator emptyAnim = ObjectAnimator.ofFloat(this, "alpha", 1.0F, 1.0F); emptyAnim.setDuration(3000); emptyAnim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { // 3.1花束移入动画停止时,启动花束上星星闪烁动画 startFirst.setAnima(View.VISIBLE); startSecond.setAnima(View.VISIBLE); startThird.setAnima(View.VISIBLE); startFourth.setAnima(View.VISIBLE); startFifth.setAnima(View.VISIBLE); startSixth.setAnima(View.VISIBLE); startSeventh.setAnima(View.VISIBLE); startEighth.setAnima(View.VISIBLE); } @Override public void onAnimationEnd(Animator animation) { // 3.2花束开始退出屏幕时隐藏星星 startFirst.setAnima(View.GONE); startSecond.setAnima(View.GONE); startThird.setAnima(View.GONE); startFourth.setAnima(View.GONE); startFifth.setAnima(View.GONE); startSixth.setAnima(View.GONE); startSeventh.setAnima(View.GONE); startEighth.setAnima(View.GONE); } }); // 4.花束淡出屏幕动画 ObjectAnimator viewOut = ObjectAnimator.ofPropertyValuesHolder(this, alphaOut); viewOut.setDuration(800); viewOut.setInterpolator(new LinearInterpolator()); viewOut.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { giftView.setVisibility(View.GONE); isRunning = false; if(animationEndListener != null) { animationEndListener.onAnimationEnd(); } } }); animatorSet = new AnimatorSet(); animatorSet.playSequentially(viewIn, emptyAnim, viewOut); animatorSet.start(); } @Override public void recyclResource() { ((ImageView)giftView.findViewById(R.id.iv_flower_bouquet)).setImageResource(0); removeAllViews(); } @Override public void cancleAnimation() { if(animatorSet != null) { animatorSet.cancel(); } } }
package com.stepefinition; import org.base.LibGlobal; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class Hotelpojo extends LibGlobal { public Hotelpojo() { PageFactory.initElements(driver, this); } @FindBy(name = "location") private WebElement txtloc; @FindBy(id = "hotels") private WebElement txthotel; @FindBy(name = "room_type") private WebElement txtroom; @FindBy(id = "room_nos") private WebElement txtnos; @FindBy(id = "datepick_in") private WebElement txtdatepickin; public WebElement getTxtloc() { return txtloc; } public WebElement getTxthotel() { return txthotel; } public WebElement getTxtroom() { return txtroom; } public WebElement getTxtnos() { return txtnos; } public WebElement getTxtdatepickin() { return txtdatepickin; } public WebElement getTxtdatepickout() { return txtdatepickout; } public WebElement getTxtadult() { return txtadult; } public WebElement getTxtchild() { return txtchild; } @FindBy(id = "datepick_out") private WebElement txtdatepickout; @FindBy(id = "adult_room") private WebElement txtadult; @FindBy(id = "child_room") private WebElement txtchild; @FindBy(id = "continue") private WebElement continuebutton; public WebElement getContinuebutton() { return continuebutton; } public void hotelpage(String data, String data1, String data2, String data3, String data4, String data5, String data6, String data7) { selectByVisibletext(getTxtloc(), data); selectByVisibletext(getTxthotel(), data1); selectByVisibletext(getTxtnos(), data2); selectByVisibletext(getTxtnos(), data3); selectByVisibletext(getTxtdatepickin(), data4); selectByVisibletext(getTxtdatepickout(), data5); selectByVisibletext(getTxtadult(), data6); selectByVisibletext(getTxtchild(), data7); } public void clickbtn() { click1(getContinuebutton()); } }
package com.example.tmbdmovies.Adapters; import android.view.View; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.tmbdmovies.R; public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView title,duration,release_date; ImageView imageView; RatingBar ratingBar; OnMovieListner onMovieListner; public MovieViewHolder(@NonNull View itemView) { super(itemView); } public MovieViewHolder(@NonNull View itemView, OnMovieListner onMovieListner) { super(itemView); this.onMovieListner = onMovieListner; title = itemView.findViewById(R.id.txtMovieTitle); duration = itemView.findViewById(R.id.txtMovieDuration); release_date = itemView.findViewById(R.id.txtMovieRealse); imageView = itemView.findViewById(R.id.movie_img); ratingBar = itemView.findViewById(R.id.rating_bar); itemView.setOnClickListener(this::onClick); } @Override public void onClick(View v) { onMovieListner.onMovieClick(getAdapterPosition()); } }
package com.spark.collecteLait.Repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.spark.collecteLait.model.entity.Chauffeur; @Repository public interface ChauffeurRepository extends CrudRepository<Chauffeur, Long> { }
package org.davidmoten.io.extras; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import org.junit.Test; public class BoundedBufferedReaderTest { @Test public void testTestReader() throws IOException { Reader r = createReader(2, 3); String s = toString(r); assertEquals("ab\nc\n", s); } @Test public void testBoundNotMetUnlimitedMaxBufferSize() throws IOException { String s = toString(createReader(5, 10000)); BoundedBufferedReader b = new BoundedBufferedReader(createReader(5, 10000)); String s2 = toString(b); assertEquals(s, s2); } @Test public void testBoundNotMetLargeMaxBufferSize() throws IOException { String s = toString(createReader(5, 10000)); BoundedBufferedReader b = new BoundedBufferedReader(createReader(5, 10000), 512, 1000000); String s2 = toString(b); assertEquals(s, s2); } @Test public void testBoundMet() throws IOException { System.out.println(toString(createReader(26, 100))); BoundedBufferedReader b = new BoundedBufferedReader(createReader(26, 100), 8, 8); String line = "abcdefgh\n"; assertEquals(line + line + line + line, toString(b)); } @Test(expected = IllegalArgumentException.class) public void testNegativeMaxLineLengthThrows() throws IOException { try (BoundedBufferedReader b = new BoundedBufferedReader(createReader(26, 100), 8, -1)) { } } @Test public void testOutOfMemoryErrorDoesNotOccur() throws IOException { long length = Long.parseLong(System.getProperty("n", Integer.toString(Integer.MAX_VALUE/10))); try (BoundedBufferedReader b = new BoundedBufferedReader(createReader(length, length), 8192, 4)) { assertEquals("abcd", b.readLine()); } } private static String toString(Reader r) throws IOException { StringBuilder b = new StringBuilder(); try (BufferedReader br = new BufferedReader(r)) { String line = null; while ((line = br.readLine()) != null) { b.append(line); b.append("\n"); } } return b.toString(); } private static String toString(BoundedBufferedReader br) throws IOException { StringBuilder b = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { b.append(line); b.append("\n"); } return b.toString(); } private static Reader createReader(long lineLength, long length) { return new Reader() { final char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); long index = 0; long lineCharsCount = 0; @Override public int read(char[] cbuf, int off, int len) throws IOException { if (index == length) { return -1; } for (int i = off; i < off + len; i++) { if (index == length) { return i - off; } else if (lineCharsCount == lineLength) { cbuf[i] = '\n'; lineCharsCount = 0; } else { cbuf[i] = chars[(int) (index % chars.length)]; lineCharsCount++; index++; } } return len; } @Override public void close() throws IOException { // do nothing } }; } }
package com.example.administrator.cookman.ui.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.example.administrator.cookman.IView.ICookSearchResultView; import com.example.administrator.cookman.R; import com.example.administrator.cookman.model.entity.CookEntity.CookDetail; import com.example.administrator.cookman.model.entity.tb_cook.TB_CustomCategory; import com.example.administrator.cookman.presenter.CookSearchResultPresenter; import com.example.administrator.cookman.presenter.Presenter; import com.example.administrator.cookman.ui.adapter.CookListAdapter; import com.example.administrator.cookman.ui.component.twinklingrefreshlayout.Footer.BottomProgressView; import com.example.administrator.cookman.ui.component.twinklingrefreshlayout.RefreshListenerAdapter; import com.example.administrator.cookman.ui.component.twinklingrefreshlayout.TwinklingRefreshLayout; import com.example.administrator.cookman.utils.ToastUtil; import java.util.ArrayList; import butterknife.Bind; public class CookSearchResultActivity extends BaseSwipeBackActivity implements ICookSearchResultView { @Bind(R.id.toolbar) public Toolbar toolbar; @Bind(R.id.refresh_layout) public TwinklingRefreshLayout twinklingRefreshLayout; @Bind(R.id.recyclerview_list) public RecyclerView recyclerList; private int totalPages; private String name; private ArrayList<CookDetail> list; private CookListAdapter cookListAdapter; private CookSearchResultPresenter cookSearchResultPresenter; @Override protected Presenter getPresenter(){ return null; } @Override protected int getLayoutId(){ return R.layout.activity_cook_search_result; } @Override protected void init(Bundle savedInstanceState){ setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayUseLogoEnabled(false); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(true); Intent intent = getIntent(); name = intent.getStringExtra(Intent_Key_Name); totalPages = intent.getIntExtra(Intent_Key_TotalPages, 0); list = intent.getParcelableArrayListExtra(Intent_Key_List); getSupportActionBar().setTitle(name); recyclerList.setLayoutManager(new LinearLayoutManager(recyclerList.getContext())); cookListAdapter = new CookListAdapter(this); recyclerList.setAdapter(cookListAdapter); twinklingRefreshLayout.setOverScrollRefreshShow(false); twinklingRefreshLayout.setEnableRefresh(false); twinklingRefreshLayout.setEnableLoadmore(true); BottomProgressView bottomProgressView = new BottomProgressView(twinklingRefreshLayout.getContext()); bottomProgressView.setAnimatingColor(getResources().getColor(R.color.colorPrimary)); twinklingRefreshLayout.setBottomView(bottomProgressView); twinklingRefreshLayout.setOverScrollBottomShow(true); twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() { @Override public void onRefresh(final TwinklingRefreshLayout refreshLayout) { } @Override public void onLoadMore(final TwinklingRefreshLayout refreshLayout) { cookSearchResultPresenter.loadMore(); } }); cookListAdapter.setDataList(list); cookListAdapter.notifyDataSetChanged(); cookSearchResultPresenter = new CookSearchResultPresenter(this, name, totalPages, this); } @Override public void onBackPressed() { boolean success = getSupportFragmentManager().popBackStackImmediate(); if (!success) super.onBackPressed(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } @Override public void onCookSearchLoadMoreSuccess(ArrayList<CookDetail> list){ twinklingRefreshLayout.finishLoadmore(); cookListAdapter.addItems(list); } @Override public void onCookSearchLoadMoreFaile(String msg){ twinklingRefreshLayout.finishLoadmore(); ToastUtil.showToast(this, msg); } @Override public void onCookSearchLoadMoreNoData(){ ToastUtil.showToast(this, getString(R.string.toast_msg_no_more_data)); } private final static String Intent_Key_Name = "name"; private final static String Intent_Key_TotalPages = "totalPages"; private final static String Intent_Key_List = "list"; public static void startActivity(Activity activity, String name, int totalPages, ArrayList<CookDetail> list){ Intent intent = new Intent(activity, CookSearchResultActivity.class); intent.putExtra(Intent_Key_Name, name); intent.putExtra(Intent_Key_TotalPages, totalPages); intent.putParcelableArrayListExtra(Intent_Key_List, list); activity.startActivity(intent); } }
package com.trump.auction.goods.domain; import lombok.Data; import lombok.ToString; import java.io.Serializable; import java.util.Date; /** * Created by 罗显 on 2017/12/21. * 商品库存使用表 */ @Data @ToString public class ProductInventoryLogRecord implements Serializable { private static final long serialVersionUID = -8450599589288041194L; private Integer id; private Integer productId; private Integer updProductNum; private Integer oldProductNum; private Integer colorId; private Integer skuId; private Integer type; private Date createTime; private Date updateTime; private Integer userId; private String userIp; }
package io.hankki.auth.domain.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; @Builder(toBuilder = true) @AllArgsConstructor(access = AccessLevel.PACKAGE) @NoArgsConstructor(access = AccessLevel.PACKAGE) @Getter @EqualsAndHashCode @ToString @Entity public class HankkiUserEntity { @Id @Column(nullable = false, unique = true, length = 100) private String userId; @Column(nullable = false, length = 100) private String userPw; @Column(nullable = false, length = 100) private String userName; }
package client; public class Driver { public static void main(String[] args) { new TCP_Client("192.168.0.178", 2000); } }
package com.kbi.qwertech.api.entities; import com.kbi.qwertech.api.data.COLOR; import com.kbi.qwertech.api.registry.MobSpeciesRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.BiomeDictionary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Subtype { private HashMap<String, Object> extraTags = new HashMap<String, Object>(); public short[] minLimits = new short[8]; public short[] maxLimits = new short[8]; public short[] preferred = new short[8]; public String[] sounds; public int primaryColorMin; public int primaryColorMax; public int secondaryColorMin; public int secondaryColorMax; private String primaryTexture = ""; private String secondaryTexture = ""; private String overlayTexture = ""; private String commonName = ""; private boolean isNatural = false; private final Species assignedSpecies; private ArrayList<BiomeGenBase> biomes = new ArrayList<BiomeGenBase>(); public Subtype(Species species) { assignedSpecies = species; sounds = new String[]{"", "", "", "", ""}; } private Object model; @SideOnly(Side.CLIENT) public net.minecraft.client.model.ModelBase getModel() { if (model != null) { return (net.minecraft.client.model.ModelBase) model; } return assignedSpecies.getModel(); } @SideOnly(Side.CLIENT) public Subtype setModel(net.minecraft.client.model.ModelBase modelType) { model = modelType; return this; } public Subtype addBiome(BiomeGenBase biome) { if (!biomes.contains(biome)) { biomes.add(biome); List<Subtype> thisBiome = assignedSpecies.spawnMap.get(biome); if (thisBiome == null || thisBiome.size() < 1) { thisBiome = new ArrayList<Subtype>(); } thisBiome.add(this); assignedSpecies.spawnMap.put(biome, thisBiome); MobSpeciesRegistry.addBiomeForSpecies(assignedSpecies.getMobType(), assignedSpecies, biome); } return this; } public Subtype addBiome(BiomeDictionary.Type biomeType) { BiomeGenBase[] results = BiomeDictionary.getBiomesForType(biomeType); for (int q = 0; q < results.length; q++) { if (!biomes.contains(results[q])) { biomes.add(results[q]); List<Subtype> thisBiome = assignedSpecies.spawnMap.get(results[q]); if (thisBiome == null || thisBiome.size() < 1) { thisBiome = new ArrayList<Subtype>(); } thisBiome.add(this); assignedSpecies.spawnMap.put(results[q], thisBiome); MobSpeciesRegistry.addBiomeForSpecies(assignedSpecies.getMobType(), assignedSpecies, results[q]); } } return this; } public Subtype removeBiome(BiomeGenBase biome) { if (biomes.contains(biome)) { biomes.remove(biome); List<Subtype> thisBiome = assignedSpecies.spawnMap.get(biome); if (thisBiome.contains(this)) { thisBiome.remove(this); } assignedSpecies.spawnMap.put(biome, thisBiome); } return this; } public boolean getCanSpawn(BiomeGenBase biome) { return getNatural() && biomes.contains(biome); } public Subtype setNatural(boolean isNatural) { this.isNatural = isNatural; return this; } public boolean getNatural() { return isNatural; } @Override public String toString() { return getCommonName(); } public String getCommonName() { return commonName; } public Subtype setCommonName(String name) { commonName = name; return this; } public String getLivingSound() { return sounds[0]; } public Subtype setLivingSound(String sound) { sounds[0] = sound; return this; } public String getHurtSound() { return sounds[1]; } public Subtype setHurtSound(String sound) { sounds[1] = sound; return this; } public String getDeathSound() { return sounds[2]; } public Subtype setDeathSound(String sound) { sounds[2] = sound; return this; } public String getAngrySound() { return sounds[3]; } public Subtype setAngrySound(String sound) { sounds[3] = sound; return this; } public String getHungrySound() { return sounds[4]; } public Subtype setHungrySound(String sound) { sounds[4] = sound; return this; } public Subtype setPrimaryColor(String color) { if (COLOR.colorDictionary.containsKey(color)) { int colorValue = COLOR.colorDictionary.get(color); int min = Math.max((colorValue >> 16 & 255) - 20, 0) * (int)Math.pow(2, 16); min = min + Math.max((colorValue >> 8 & 255) - 20, 0) * (int)Math.pow(2, 8); min = min + Math.max((colorValue & 255) - 20, 0); int max = Math.min((colorValue >> 16 & 255) + 20, 255) * (int)Math.pow(2, 16); max = max + Math.min((colorValue >> 8 & 255) + 20, 255) * (int)Math.pow(2, 8); max = max + Math.min((colorValue & 255) + 20, 255); setPrimaryColors(min, max); } else { System.out.println("Could not find color " + color); } return this; } public Subtype setPrimaryColors(int color1, int color2) { primaryColorMin = color1; primaryColorMax = color2; return this; } public Subtype setPrimaryColors(String color1, String color2) { if (COLOR.colorDictionary.containsKey(color1) && COLOR.colorDictionary.containsKey(color2)) { setPrimaryColors(COLOR.colorDictionary.get(color1), COLOR.colorDictionary.get(color2)); } else { System.out.println("Could not find both " + color1 + " and " + color2); } return this; } public Subtype setSecondaryColor(String color) { if (COLOR.colorDictionary.containsKey(color)) { int colorValue = COLOR.colorDictionary.get(color); int min = Math.max((colorValue >> 16 & 255) - 20, 0) * (int)Math.pow(2, 16); min = min + Math.max((colorValue >> 8 & 255) - 20, 0) * (int)Math.pow(2, 8); min = min + Math.max((colorValue & 255) - 20, 0); int max = Math.min((colorValue >> 16 & 255) + 20, 255) * (int)Math.pow(2, 16); max = max + Math.min((colorValue >> 8 & 255) + 20, 255) * (int)Math.pow(2, 8); max = max + Math.min((colorValue & 255) + 20, 255); setSecondaryColors(min, max); } else { System.out.println("Could not find color " + color); } return this; } public Subtype setSecondaryColors(int color1, int color2) { secondaryColorMin = color1; secondaryColorMax = color2; return this; } public Subtype setSecondaryColors(String color1, String color2) { if (COLOR.colorDictionary.containsKey(color1) && COLOR.colorDictionary.containsKey(color2)) { setSecondaryColors(COLOR.colorDictionary.get(color1), COLOR.colorDictionary.get(color2)); } else { System.out.println("Could not find both " + color1 + " and " + color2 + " in the color database"); } return this; } public String getPrimaryTexture() { return primaryTexture; } public Subtype setPrimaryTexture(String pT) { primaryTexture = pT; return this; } public String getSecondaryTexture() { return secondaryTexture; } public Subtype setSecondaryTexture(String sT) { secondaryTexture = sT; return this; } public String getOverlayTexture() { return overlayTexture;} public Subtype setOverlayTexture(String oT) { overlayTexture = oT; return this; } public Subtype setTexturePath(String tP) { primaryTexture = tP + "_primary.png"; secondaryTexture = tP + "_secondary.png"; overlayTexture = tP + "_overlay.png"; return this; } public Subtype setSize(int min, int pref, int max) { minLimits[0] = (short)min; preferred[0] = (short)pref; maxLimits[0] = (short)max; return this; } public Subtype setStrength(int min, int pref, int max) { minLimits[1] = (short)min; preferred[1] = (short)pref; maxLimits[1] = (short)max; return this; } public Subtype setStamina(int min, int pref, int max) { minLimits[2] = (short)min; preferred[2] = (short)pref; maxLimits[2] = (short)max; return this; } public Subtype setSmart(int min, int pref, int max) { minLimits[3] = (short)min; preferred[3] = (short)pref; maxLimits[3] = (short)max; return this; } public Subtype setSnarl(int min, int pref, int max) { minLimits[4] = (short)min; preferred[4] = (short)pref; maxLimits[4] = (short)max; return this; } public Subtype setMutable(int min, int pref, int max) { minLimits[5] = (short)min; preferred[5] = (short)pref; maxLimits[5] = (short)max; return this; } public Subtype setFertility(int min, int pref, int max) { minLimits[6] = (short)min; preferred[6] = (short)pref; maxLimits[6] = (short)max; return this; } public Subtype setMaturity(int min, int pref, int max) { minLimits[7] = (short)min; preferred[7] = (short)pref; maxLimits[7] = (short)max; return this; } public short getMinSize() { return minLimits[0]; } public short getMinStrength() { return minLimits[1]; } public short getMinStamina() { return minLimits[2]; } public short getMinSmart() { return minLimits[3]; } public short getMinSnarl() { return minLimits[4]; } public short getMinMutable() { return minLimits[5]; } public short getMinFertility() { return minLimits[6]; } public short getMinMaturity() { return minLimits[7]; } public int getMinPrimaryColor() { return primaryColorMin; } public int getMinSecondaryColor() { return secondaryColorMin; } public short getPrefSize() { return preferred[0]; } public short getPrefStrength() { return preferred[1]; } public short getPrefStamina() { return preferred[2]; } public short getPrefSmart() { return preferred[3]; } public short getPrefSnarl() { return preferred[4]; } public short getPrefMutable() { return preferred[5]; } public short getPrefFertility() { return preferred[6]; } public short getPrefMaturity() { return preferred[7]; } public short getMaxSize() { return maxLimits[0]; } public short getMaxStrength() { return maxLimits[1]; } public short getMaxStamina() { return maxLimits[2]; } public short getMaxSmart() { return maxLimits[3]; } public short getMaxSnarl() { return maxLimits[4]; } public short getMaxMutable() { return maxLimits[5]; } public short getMaxFertility() { return maxLimits[6]; } public short getMaxMaturity() { return maxLimits[7]; } public int getMaxPrimaryColor() { return primaryColorMax; } public int getMaxSecondaryColor() { return secondaryColorMax; } public boolean hasTag(String tag) { return extraTags.containsKey(tag); } public Subtype addTag(String tag, Object obby) { extraTags.put(tag, obby); return this; } public Object getTag(String tag) { if (extraTags.containsKey(tag)) { return extraTags.get(tag); } return null; } }
package be.openclinic.healthrecord; import be.mxs.common.util.db.MedwanQuery; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; public class FunctionCategoryRisk { private int functionCategoryId; private int riskId; private Timestamp updatetime; public int getFunctionCategoryId() { return functionCategoryId; } public void setFunctionCategoryId(int functionCategoryId) { this.functionCategoryId = functionCategoryId; } public int getRiskId() { return riskId; } public void setRiskId(int riskId) { this.riskId = riskId; } public Timestamp getUpdatetime() { return updatetime; } public void setUpdatetime(Timestamp updatetime) { this.updatetime = updatetime; } public void deleteCategoryRisk(){ PreparedStatement ps = null; String sDelete = "DELETE FROM FunctionCategoryRisks WHERE functionCategoryId = ?"; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ ps = oc_conn.prepareStatement(sDelete); ps.setInt(1,this.getFunctionCategoryId()); ps.execute(); ps.close(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(ps!=null)ps.close(); oc_conn.close(); }catch(Exception e){ e.printStackTrace(); } } } public void addCategoryRisk(){ PreparedStatement ps = null; String sUpdate = " INSERT INTO FunctionCategoryRisks(riskId,functionCategoryId,updatetime)"+ " VALUES(?,?,?)"; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ ps = oc_conn.prepareStatement(sUpdate); ps.setInt(1,this.getRiskId()); ps.setInt(2,this.getFunctionCategoryId()); ps.setTimestamp(3,this.getUpdatetime()); ps.executeUpdate(); ps.close(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(ps!=null)ps.close(); oc_conn.close(); }catch(Exception e){ e.printStackTrace(); } } } public static boolean isChecked(String sRiskId,String sFunctionCategoryId){ PreparedStatement ps = null; ResultSet rs = null; boolean bChecked = false; String sSelect = " SELECT functionCategoryId FROM FunctionCategoryRisks"+ " WHERE riskId = ? AND functionCategoryId = ?"; Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ ps = oc_conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(sRiskId)); ps.setInt(2,Integer.parseInt(sFunctionCategoryId)); rs = ps.executeQuery(); if(rs.next()){ bChecked = true; } rs.close(); ps.close(); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); oc_conn.close(); }catch(Exception e){ e.printStackTrace(); } } return bChecked; } }
package four.loop; import java.util.Arrays; /** * <li>LOOPS ili PETLJE * <li>2. NIZOVA</li> */ public class ArrayLoopDemo { public static void main(String[] args) { String[] names = {"Adi", "Almir", "Nevena", "Amer", "Harun", "Jasmin", "Damir", "Ajša", "Emil", "Adna", "Emir"}; /*int i = 0;//initialization while(i<names.length){ String name = names[i]; System.out.println(name); i++; }*/ /*for(int i = 0; i<names.length; i++){ String name = names[i]; System.out.println(name); }*/ //ENHANCED FOR LOOP --> Java for(String name: names) { System.out.println(name); } } }
package exercicio05; public interface FabricadeCarros { CarroSedan criarCarroSdedan(); CarroPopular criarCarroPopular(); }
package lanzador; import interfazGrafica.*; /** * * @author Master */ public class Main { /** * * @param args */ public static void main(String[] args) { Bienvenida bienvenida= new Bienvenida(); }}
package br.com.cubo.sps.process; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import br.com.cubo.sps.vo.Match; public class MatchConverterTest { private int countKillEvents; private String matchId; private MatchConverter converter; private List<String> eventLineList; @Before public void init(){ converter = new MatchConverter(); matchId = "11348965"; countKillEvents = 2; eventLineList = new ArrayList<String>(); eventLineList.add("23/04/2013 15:34:22 - New match 11348965 has started"); eventLineList.add("23/04/2013 15:36:04 - Roman killed Nick using M16"); eventLineList.add("23/04/2013 15:36:33 - <WORLD> killed Nick by DROWN"); eventLineList.add("23/04/2013 15:39:22 - Match 11348965 has ended"); } @Test public void converter(){ Match match = converter.convert(eventLineList); Assert.assertEquals(matchId, match.getId()); Assert.assertEquals(countKillEvents, match.getEventKillList().size()); } }
package com.love.step.controller; import com.alibaba.fastjson.JSON; import com.love.step.config.RunConfig; import com.love.step.constant.RedisConstant; import com.love.step.dto.UserDTO; import com.love.step.service.UserService; import com.love.step.utils.RedisUtils; import com.love.step.utils.ResultUtil; import com.love.step.vo.ResultVO; import com.love.step.vo.RunVo; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.cache.CacheProperties; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; @RestController @RequestMapping("/auth") public class LoginController { @Autowired private RunConfig runConfig; @Autowired private RedisUtils redisUtils; @Autowired private UserService userService; @PostMapping("/login") public ResultVO login(@RequestParam("code") String code){ Map<String,Object> resultMap = new HashMap<>(); // 通过code 获取sessionkey 和 openid CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration. HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+runConfig.getAppid()+"&secret="+runConfig.getAppsecret()+"&js_code="+code+"&grant_type=authorization_code"); try { String srtResult = ""; HttpResponse httpResponse = httpCilent.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200){ srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果 //System.out.println(srtResult); RunVo runVo = JSON.parseObject(srtResult,RunVo.class); System.out.println(JSON.toJSON(runVo).toString()); if(null != runVo && StringUtils.isNotBlank(runVo.getSession_key()) && StringUtils.isNotBlank(runVo.getOpenid())){ UserDTO userDTO = new UserDTO(); userDTO.setOpenid(runVo.getOpenid()); // 保存到数据库 resultMap = userService.addUserInfo(userDTO); if(null != resultMap){ // 生成Token String token = UUID.randomUUID().toString(); resultMap.put("token",token); // 保存到redis中 openid sessionkey redisUtils.set(String.format(RedisConstant.TOKEN_PREFIX,token),runVo.getOpenid()); redisUtils.set(String.format(RedisConstant.SESSION_KEY_PREFIX,token),runVo.getSession_key()); System.out.println(redisUtils.get(String.format(RedisConstant.TOKEN_PREFIX,token))); }else{ return ResultUtil.error(); } } }else{ return ResultUtil.error(); } } catch (Exception e) { e.printStackTrace(); return ResultUtil.error(); }finally { try { httpCilent.close();//释放资源 } catch (IOException e) { e.printStackTrace(); } } return ResultUtil.success(resultMap); } }
package latihan6; public class SInformasi extends Fakultas { public SInformasi(){ super.setDosen("\n - Achmad Basuki, S.T, M.MG, Ph.D \n - Bayu Priyambadha, S.Kom, M.Kom \n - Dahnial Syauqy, S.T., M.T., M.Sc. \n - Eko Sakti P., S.Kom, M.Kom"); super.setKeminatan("\n - Sistem Informasi \n - Rekayasa Perangkat Lunak"); super.setKetua("Suprapto, ST., MT"); super.setLab("\n - Sistem Komputer dan Robotika \n - Jaringan Komputer \n - Rekayasa Perangkat Lunak \n - Sistem Informasi \n - Mobile Apps \n - Komputer Dasar \n - Komputasi Cerdas dan Visualisasi"); } }
package com.itheima.day_20.service; import com.itheima.day_20.domain.User; public interface UserService { //根据用户名查找用户 User findUser(String username); }
package priv.yaowl.java.singleton; public class Test { public static void main(String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); System.out.println(s1 == s2); System.out.println(s1 + "==" + s2); SingletonSys ss1 = SingletonSys.getInstance(); SingletonSys ss2 = SingletonSys.getInstance(); System.out.println(ss1 == ss2); System.out.println(ss1 + "==" + ss2); // 对比,Singleton是在第一次调用的时候初始化, SingletonSys是加载的时候就初始化了。 } }
package Utils; import java.awt.*; public class Variables { private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); public static final double SCREEN_WIDTH= screenSize.width; public static final double SCREEN_HEIGHT = screenSize.height; public static final String USER_HOME_PATH=System.getProperty("user.home")+"\\"; public static final String FILE_SEPARATOR =System.getProperty("file.separator"); public static final String DEFAULT_CSV_FILE_PATH = "src"+FILE_SEPARATOR+"CSVFiles"+FILE_SEPARATOR; public static final String DEFAULT_SKILL_PARSER_FILE_PATH = "src"+FILE_SEPARATOR+"SkillParserFiles"+FILE_SEPARATOR; }
package com.zzping.fix.entity; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; import java.util.Date; public class FixLabelApply implements Serializable { private String fixLabelApplyId; private String userId; private String userType; private String userNo; private String userName; private String originLabel; private String originLabelDetail; private String applyLabel; private String applyLabelDetail; private String rejectReason; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date createTime; private Date updateTime; private static final long serialVersionUID = 1L; public String getFixLabelApplyId() { return fixLabelApplyId; } public void setFixLabelApplyId(String fixLabelApplyId) { this.fixLabelApplyId = fixLabelApplyId == null ? null : fixLabelApplyId.trim(); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType == null ? null : userType.trim(); } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getOriginLabel() { return originLabel; } public void setOriginLabel(String originLabel) { this.originLabel = originLabel == null ? null : originLabel.trim(); } public String getOriginLabelDetail() { return originLabelDetail; } public void setOriginLabelDetail(String originLabelDetail) { this.originLabelDetail = originLabelDetail == null ? null : originLabelDetail.trim(); } public String getApplyLabel() { return applyLabel; } public void setApplyLabel(String applyLabel) { this.applyLabel = applyLabel == null ? null : applyLabel.trim(); } public String getApplyLabelDetail() { return applyLabelDetail; } public void setApplyLabelDetail(String applyLabelDetail) { this.applyLabelDetail = applyLabelDetail == null ? null : applyLabelDetail.trim(); } public String getRejectReason() { return rejectReason; } public void setRejectReason(String rejectReason) { this.rejectReason = rejectReason == null ? null : rejectReason.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", fixLabelApplyId=").append(fixLabelApplyId); sb.append(", userId=").append(userId); sb.append(", userType=").append(userType); sb.append(", userNo=").append(userNo); sb.append(", userName=").append(userName); sb.append(", originLabel=").append(originLabel); sb.append(", originLabelDetail=").append(originLabelDetail); sb.append(", applyLabel=").append(applyLabel); sb.append(", applyLabelDetail=").append(applyLabelDetail); sb.append(", rejectReason=").append(rejectReason); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package com.designpattern.dp6proxypattern.staticproxyPlus; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 1.DynamicDataSourceEntry 负责切换数据源 * 2.OrderService 实现IOrderSerice接口,负责调用OrderDao(被代理类) * 3.OrderDao 负责具体的订单Order的增删改查 * 4.OrderServiceStaticProxy 实现IOrderService接口是代理类,持有DynamicDataSourceEntry和OrderService的引用 * 负责调用DynamicDataSourceEntry来切换数据源,然后调用OrderService执行业务 * 5.Order订单类 */ public class Test { public static void main(String[] args) { // 创建订单 Order order = new Order(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); try { Date date = sdf.parse("2017/02/01"); order.setCreateTime(date.getTime()); // 创建代理类 负责 确定数据库,并调用OrderService.createOrder()方法将新订单插入数据库 IOrderService orderServiceStaticProxy = new OrderServiceStaticProxy(new OrderService()); orderServiceStaticProxy.createOrder(order); } catch (ParseException e) { e.printStackTrace(); } } }
package com.java8.files; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /** * @author Neeraj Kr * * * */ public class FileExample { public static void main(String args[]) throws IOException { File files = new File("/home/neeraj/Development"); // Get all the fileNames in a given Directory String[] filesNamesList = files.list(); // Get all the files in a given Directory File[] filesArray = files.listFiles(); // Print all the files names for (String s : filesNamesList) { System.out.println(s); } // Print all the File for (File f : filesArray) { System.out.println(f); } // Java 8 - Declarative style of Coding System.out.println(" Java 8 Style of Declarative Coding "); // We first created a Path instance from the string using the get() // method of the Paths convenience class. Then, using the list() method // of the Files // utility class (in the java.nio.file package) we got a new // CloseableStream to // iterate over the files in the given path. We then used the internal // iterator, forEach() , on // it to print the filenames. Files.list(Paths.get("/home/neeraj/Development")).forEach(System.out::println); //If we want only the subdirectories in the current directory instead of a listing //of all the files, we can use the filter() method.the filter() method expects a Predicate , //which returns a boolean result Files.list(Paths.get("/home/neeraj/Development")).filter(Files::isDirectory).forEach(System.out::println); } }
package king_tokyo_power_up.game.card; /** * Evolution type enum defines different types of evolution cards. */ public enum EvolutionType { /** * Permanent evolution is an evolution that you keep throughout the king_tokyo_power_up.game. */ PERMANENT_EVOLUTION("Permanent Evolution"), /** * Temporary evolution is an evolution that is played when received and then discarded. */ TEMPORARY_EVOLUTION("Temporary Evolution"), /** * Gift evolution is an evolution that is put onto another monster, has a bad effects. */ GIFT_EVOLUTION("Gift Evolution"); /** * The string representation of enum. */ private String string; /** * Evolution type enum constructor. * @param str the name of evolution type */ EvolutionType(String str) { this.string = str; } @Override public String toString() { return string; } }
package c01.todoteamname.project.SPORTCRED; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; public class GetGameFeed implements HttpHandler { private final String API_URL = "https://www.balldontlie.io/api/v1/games?"; private final Map<String, Integer> mapOfTeams= new HashMap<String, Integer>() {{ put("Atlanta Hawks", 1); put("Boston Celtics", 2); put("Brooklyn Nets", 3); put("Charlotte Hornets", 4); put("Chicago Bulls", 5); put("Cleveland Cavaliers", 6); put("Dallas Mavericks", 7); put("Denver Nuggets", 8); put("Detroit Pistons", 9); put("Golden State Warriors", 10); put("Houston Rockets", 11); put("Indiana Pacers", 12); put("LA Clippers", 13); put("Los Angeles Lakers", 14); put("Memphis Grizzlies", 15); put("Miami Heat", 16); put("Milwaukee Bucks", 17); put("Minnesota Timberwolves", 18); put("New Orleans Pelicans", 19); put("New York Knicks", 20); put("Oklahoma City Thunder", 21); put("Orlando Magic", 22); put("Philadelphia 76ers", 23); put("Phoenix Suns", 24); put("Portland Trail Blazers", 25); put("Sacramento Kings", 26); put("San Antonio Spurs", 27); put("Toronto Raptors", 28); put("Utah Jazz", 29); put("Washington Wizards", 30); }}; @Override public void handle(HttpExchange r) throws IOException { try { if (r.getRequestMethod().equals("POST")) { handlePost(r); } } catch (Exception e) { } } private void handlePost(HttpExchange r) throws IOException, JSONException { String body = Utils.convert(r.getRequestBody()); JSONObject deserialized = new JSONObject(body); if (deserialized.has("season") && deserialized.has("page")) { String season = deserialized.getString("season"); int page = deserialized.getInt("page"); String team = null; if (deserialized.has("team")) { team = deserialized.getString("team"); } JSONObject gameData = getGameData(season, team, page); if (gameData == null) { r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); r.sendResponseHeaders(500, -1); } else { if (gameData.getJSONArray("data").length() == 0) { r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); r.sendResponseHeaders(400, -1); } else { r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); r.sendResponseHeaders(200, gameData.toString().length()); OutputStream os = r.getResponseBody(); os.write(gameData.toString().getBytes()); os.close(); } } } else { r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); r.sendResponseHeaders(400, -1); } } private JSONObject getGameData(String season, String team, int page) { try { String urlWithParams = API_URL + "seasons[]=" + season + "&page=" + page; if (team != null) { Integer teamID = mapOfTeams.get(team); if (teamID != null) { urlWithParams += "&team_ids[]=" + teamID.toString(); } else { return null; } } URL url = new URL(urlWithParams); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("GET"); InputStream is = http.getInputStream(); JSONObject jsonFromGET = new JSONObject(Utils.convert(is)); return jsonFromGET; } catch (Exception e) { return null; } } }
package com.trump.auction.pals.api.model; import com.cf.common.utils.ServiceResult; import lombok.Data; @Data public class PayServiceResult extends ServiceResult { public static String ERROR = "-100"; private String token; private String noAgree; public PayServiceResult(String code) { super(code); } public PayServiceResult(String code, String msg) { super(code, msg); } }
package com.xt.together.json; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.xt.together.constant.constant; import com.xt.together.model.Food; import com.xt.together.model.FoodLike; import com.xt.together.model.FriendsCirCleUser; import com.xt.together.model.FriendsCircle; import com.xt.together.model.Invite; import com.xt.together.model.Restaurant; import com.xt.together.model.Trends; import com.xt.together.model.TrendsLike; public class JsonAnalyze { public Restaurant[] jsonNearbyRestaurantAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Restaurant[] newrestaurant = null; try { JSONObject restaurantInfo = new JSONObject(jsonString); status = restaurantInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = restaurantInfo.getJSONArray("data"); newrestaurant = new Restaurant[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ Log.e(constant.DEBUG_TAG, "we get the dataarray length"+dataArray.length()); JSONObject jo = (JSONObject)dataArray.opt(i); if(jo == null){ Log.e(constant.DEBUG_TAG, "3333333"); } Log.e(constant.DEBUG_TAG, jo.getString("id")); newrestaurant[i] = new Restaurant(jo.getString("id"),jo.getString("name"), jo.getString("average"), jo.getString("like"), jo.getString("specialty"), jo.getString("address"), jo.getString("phone"), jo.getString("image")); } } } catch (JSONException e) { // TODO Auto-generated catch block Log.e(constant.DEBUG_TAG, "something wrong"); e.printStackTrace(); } return newrestaurant; } public Food[] jsonFoodAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Food[] newFood = null; try { JSONObject restaurantInfo = new JSONObject(jsonString); status = restaurantInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = restaurantInfo.getJSONArray("data"); newFood = new Food[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); newFood[i] = new Food(jo.getString("name"), null, null, null, null,jo.getString("address"), jo.getString("description")); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newFood; } public JSONArray jsonWeiboFansAnalyze(String jsonString){ if(null == jsonString){ return null; } JSONArray friendids = null; try { JSONObject restaurantInfo = new JSONObject(jsonString); friendids = restaurantInfo.getJSONArray("ids"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return friendids; } public String[] jsonFriendsAnalyze(String jsonString){ if(null == jsonString){ return null; } String[] friendsName = null; try { JSONObject friendsInfo = new JSONObject(jsonString); JSONArray friendsArray = friendsInfo.getJSONArray("users"); friendsName = new String[friendsArray.length()]; for(int i = 0 ; i < friendsArray.length(); i++){ JSONObject jo = (JSONObject)friendsArray.opt(i); friendsName[i] = "@" +jo.getString("screen_name"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return friendsName; } public String[] jsonFriendsHeadAnalyze(String jsonString){ if(null == jsonString){ return null; } String[] friendsName = null; try { JSONObject friendsInfo = new JSONObject(jsonString); JSONArray friendsArray = friendsInfo.getJSONArray("users"); friendsName = new String[friendsArray.length()]; for(int i = 0 ; i < friendsArray.length(); i++){ JSONObject jo = (JSONObject)friendsArray.opt(i); friendsName[i] = jo.getString("profile_image_url"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return friendsName; } public String[] jsonFriendsIdAnalyze(String jsonString){ if(null == jsonString){ return null; } String[] friendsName = null; try { JSONObject friendsInfo = new JSONObject(jsonString); JSONArray friendsArray = friendsInfo.getJSONArray("users"); friendsName = new String[friendsArray.length()]; for(int i = 0 ; i < friendsArray.length(); i++){ JSONObject jo = (JSONObject)friendsArray.opt(i); friendsName[i] = jo.getString("idstr"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return friendsName; } /* * 分析从mytrends获得的json,是一个双重数组 */ public Trends[] jsonMyTrendsAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Trends[] trends = null; try { JSONObject TrendsInfo = new JSONObject(jsonString); status = TrendsInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ Log.e("com.xt.together", "we start to analyze"); JSONArray dataArray = TrendsInfo.getJSONArray("data"); Log.e(constant.DEBUG_TAG, "we get the length" + dataArray.length()); trends = new Trends[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); String id = jo.getString("id"); String name = jo.getString("name"); JSONArray likeArray = jo.getJSONArray("like"); TrendsLike[] trendslike = new TrendsLike[likeArray.length()]; for(int j = 0; j < likeArray.length(); j++){ JSONObject likejo = (JSONObject)likeArray.opt(j); String likeid = likejo.getString("id"); String likename = likejo.getString("name"); String likehead = likejo.getString("head"); trendslike[j] = new TrendsLike(likeid, likename, likehead); } String address = jo.getString("address"); String description = jo.getString("description"); String image = jo.getString("image"); trends[i] = new Trends(id, name, address, description, trendslike, image); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return trends; } public Food[] jsonFoodLikeAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Food[] newFood = null; try { JSONObject restaurantInfo = new JSONObject(jsonString); status = restaurantInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = restaurantInfo.getJSONArray("data"); newFood = new Food[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); newFood[i] = new Food(jo.getString("name"), null, null, null, jo.getString("image"),jo.getString("address"), jo.getString("description")); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newFood; } public Restaurant[] jsonStoreAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Restaurant[] newRestaurant = null; try { JSONObject restaurantInfo = new JSONObject(jsonString); status = restaurantInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = restaurantInfo.getJSONArray("data"); newRestaurant = new Restaurant[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); newRestaurant[i] = new Restaurant(jo.getString("name"), jo.getString("average"), jo.getString("like"), jo.getString("specialty"), jo.getString("address"), jo.getString("phone"), jo.getString("image") ); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newRestaurant; } public String jsonIDAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; String HttpId = ""; try { JSONObject IDInfo = new JSONObject(jsonString); status = IDInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ HttpId = IDInfo.getString("data"); return HttpId; }else{ JSONObject DataInfo = IDInfo.getJSONObject("data"); HttpId = DataInfo.getString("id"); return HttpId; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public Food[] jsonNearbyFoodAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Food[] newFood = null; try { JSONObject foodInfo = new JSONObject(jsonString); status = foodInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = foodInfo.getJSONArray("data"); newFood = new Food[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); JSONArray likeArray = jo.getJSONArray("like"); FoodLike[] newFoodLike = new FoodLike[likeArray.length()]; for(int j = 0; j < likeArray.length(); j++){ JSONObject likejo = (JSONObject)likeArray.opt(j); newFoodLike[j] = new FoodLike(likejo.getString("id"), likejo.getString("name"), likejo.getString("head")); } newFood[i] = new Food(jo.getString("id"),jo.getString("name"), jo.getString("shop"), jo.getString("price"), jo.getString("share"), jo.getString("image"), jo.getString("address"), jo.getString("description"), newFoodLike); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newFood; } public boolean jsonAddFoodLikeAnalyze(String jsonString){ boolean isAddSuccess = false; try { JSONObject status = new JSONObject(jsonString); String isStatus = status.getString("status"); if("0" == isStatus){ isAddSuccess = true; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isAddSuccess; } public boolean jsonAddStoreAnalyze(String jsonString){ boolean isAddSuccess = false; try { JSONObject status = new JSONObject(jsonString); String isStatus = status.getString("status"); if("0" == isStatus){ isAddSuccess = true; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isAddSuccess; } public FriendsCircle[] jsonFriendsCircleAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; FriendsCircle[] newFriendsCircle = null; try { JSONObject FriendsCircleInfo = new JSONObject(jsonString); status = FriendsCircleInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = FriendsCircleInfo.getJSONArray("data"); newFriendsCircle = new FriendsCircle[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); JSONArray likeArray = jo.getJSONArray("like"); FoodLike[] newFoodLike = new FoodLike[likeArray.length()]; for(int j = 0; j < likeArray.length(); j++){ JSONObject likejo = (JSONObject)likeArray.opt(j); newFoodLike[j] = new FoodLike(likejo.getString("id"), likejo.getString("name"), likejo.getString("head")); } JSONObject jouser = jo.getJSONObject("user"); FriendsCirCleUser muser = new FriendsCirCleUser(jouser.getString("id"), jouser.getString("name"), jouser.getString("head")); newFriendsCircle[i] = new FriendsCircle(jo.getString("name"), jo.getString("address"), jo.getString("description"), jo.getString("image"), muser, newFoodLike); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newFriendsCircle; } public Invite[] jsonInviteAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Invite[] newInvite = null; try { JSONObject inviteInfo = new JSONObject(jsonString); status = inviteInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = inviteInfo.getJSONArray("data"); newInvite = new Invite[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); JSONArray invitedArray = jo.getJSONArray("invited"); String invitedString = ""; for(int j = 0; j < invitedArray.length(); j++){ JSONObject joinvited = (JSONObject)invitedArray.opt(j); String invitedname = joinvited.getString("name"); invitedname = invitedname.replace("@", ""); invitedString += invitedname; } newInvite[i] = new Invite(jo.getString("id"), jo.getString("name"), jo.getString("address"), jo.getString("date"), null, invitedString, jo.getString("phone"),jo.getString("image") ); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newInvite; } public Invite[] jsonInvitedAnalyze(String jsonString){ if(null == jsonString){ return null; } int status = -1; Invite[] newInvite = null; try { JSONObject inviteInfo = new JSONObject(jsonString); status = inviteInfo.getInt("status"); if(status == -1){ Log.e("com.xt.together", "we haven't got the json message"); }else if(status == 1){ Log.e("com.xt.together", "we have got the wrong message"); return null; }else{ JSONArray dataArray = inviteInfo.getJSONArray("data"); newInvite = new Invite[dataArray.length()]; for(int i = 0; i < dataArray.length(); i++){ JSONObject jo = (JSONObject)dataArray.opt(i); JSONArray invitedArray = jo.getJSONArray("invited"); String invitedString = ""; for(int j = 0; j < invitedArray.length(); j++){ JSONObject joinvited = (JSONObject)invitedArray.opt(j); String invitedname = joinvited.getString("name"); invitedname = invitedname.replace("@", ""); invitedString += invitedname; } newInvite[i] = new Invite(jo.getString("id"), jo.getString("name"), jo.getString("address"), jo.getString("date"), null, invitedString, jo.getString("phone"),jo.getString("image") ); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newInvite; } }
package com.guang.bishe.controller; import com.guang.bishe.domain.Address; import com.guang.bishe.domain.Orders; import com.guang.bishe.domain.User; import com.guang.bishe.service.AddressService; import com.guang.bishe.service.OrderService; import com.guang.bishe.service.RegistService; import com.guang.bishe.service.UserService; import com.guang.bishe.service.dto.ShopResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller public class UserController { @Autowired private AddressService addressService; @Autowired private RegistService registService; @Autowired private UserService userService; /** * 跳转用户信息更改页面 * * @return */ @RequestMapping("/updateUser") public String editProfile(HttpServletRequest request, Model model) { User user = (User) request.getSession().getAttribute("user"); if (!"1".equals(user.getUserRol())) { List<Address> addressList = addressService.getAddressByUserId(user.getUserId()); model.addAttribute("addressList", addressList); } return "updateUser"; } /** * 更改用户信息 * * @param request * @param model * @param user * @param addressId * @param addressAddress * @param hpmename * @return */ @RequestMapping(value = "updateUser", method = RequestMethod.POST) public String updateUser(HttpServletRequest request, Model model, User user, String[] addressId, String[] addressAddress, String[] hpmename) { //校验数据 if (user.getUserPassword() == null || user.getUserPassword() == "") { model.addAttribute("errss1", "密码不能为空"); //判断用户是否为买家 checkUserRol(user, model); return "updateUser"; } else if (user.getUserPassword().length() < 6) { model.addAttribute("errss1", "密码长度不能小于6"); checkUserRol(user, model); return "updateUser"; } else if (user.getUserNickname() == null || user.getUserNickname() == "") { model.addAttribute("errss3", "昵称不能为空"); checkUserRol(user, model); return "updateUser"; } else if (user.getUserRealname() == null || user.getUserRealname() == "") { model.addAttribute("errss4", "真实姓名不能为空"); checkUserRol(user, model); return "updateUser"; } else if (user.getUserPhone() == null || user.getUserPhone() == "") { model.addAttribute("errss5", "电话不能为空"); checkUserRol(user, model); return "updateUser"; } registService.updateUser(user); if (user.getUserRol().equals("0")) { for (int i = 0; i < addressId.length; i++) { if (addressAddress[i] == null || addressAddress[i] == "") { model.addAttribute("errss6", "地址不能为空"); return "updateUser"; } } addressService.updateAdressAll(addressId, addressAddress); if (hpmename != null) { addressService.insertSomAdress(hpmename, user.getUserId()); } } model.addAttribute("view","index"); model.addAttribute("message","修改个人信息成功!"); return "success"; } private void checkUserRol(User user, Model model) { if (!"1".equals(user.getUserRol())) { //获取该用户的所有地址 List<Address> addressList = addressService.getAddressByUserId(user.getUserId()); model.addAttribute("addressList", addressList); } } /** * 删除地址 * * @param id * @return */ @RequestMapping("/deleteAddress") @ResponseBody public String deleteAddress(Long id) { addressService.deleteAddress(id); return "success"; } /** * 更改此地址为默认地址 * * @param id * @return */ @RequestMapping("/updateDefaultAddress") public String updateDefaultAddress(Long id) { addressService.updateDefaultAddress(id); return "redirect:updateUser"; } /** * 订单收货 * * @return */ @GetMapping("/userReceiveOrder") public String userReceiveOrder(Long id, Integer action, HttpServletRequest request) { User user = (User) request.getSession().getAttribute("user"); if (null == user) { return "login"; } if (action == 2) { userService.updateOrder(id, "3"); } return "redirect:menu"; } /** * 评价订单view */ @GetMapping("messageOrder") public String messageOrder(Long id, Model model, HttpServletRequest request) { User user = (User) request.getSession().getAttribute("user"); if (null == user) { return "login"; } model.addAttribute("id", id); return "message"; } /** * 评价订单 */ @PostMapping("messageOrder") public String messageOrder(Orders orders, Model model, HttpServletRequest request) { User user = (User) request.getSession().getAttribute("user"); if (null == user) { return "login"; } userService.updateOrder(orders); model.addAttribute("view", "menu"); model.addAttribute("message", "评价成功!"); return "success"; } /** * 查看评价订单 */ @RequestMapping(value = "selectMessageOrder", method = RequestMethod.GET) public String selectMessageOrder(Long orderId, Model model, HttpServletRequest request) { User user = (User) request.getSession().getAttribute("user"); if (null == user) { return "login"; } Orders orders = userService.selectOrderByOrderId(orderId); model.addAttribute("orders", orders); model.addAttribute("action", 2); model.addAttribute("role", user.getUserRol()); return "message"; } }
public class Field { static final int SIZE = 10; char[][] position = new char[SIZE][SIZE]; Field() { Main.data.generateField(); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { position[i][j] = '.'; } } } public void showField() { Main.data.seeField(); // for (char[] points : position) { // for (char point : points) { // System.out.print(point); // } // System.out.println(); // } } //setStatusOfPosition public void setStatusOfPosition(int x, int y, char status) { Main.data.setInPosition(x+1,y+1,status); position [x][y] = status; } public boolean isEmpty(int x, int y){ if(x>= SIZE ||y>= SIZE) return false; return position[x][y]=='.'; } public boolean isEmptySurroundings(int x, int y){ if(!isEmpty(x, y)) return false; for(int i=x-1; i<=x+1; i++){ for (int j = y-1; j <=y+1; j++) { if(i>=0&&j>=0&&i< SIZE &&j< SIZE) if (!isEmpty(i,j))return false; } } return true; } public boolean hasAnyShip(){ return Main.data.anyCharD(); } // public boolean hasAnyShip() { // for (char[] points : position) { // for (char point : points) { // if(point=='D') return true; // } // } // return false; // } }
package jakebellotti.steamvrlauncher.ui; import java.awt.Desktop; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Optional; import java.util.Scanner; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import jakebellotti.steamvrlauncher.Config; import jakebellotti.steamvrlauncher.SteamConstants; import jakebellotti.steamvrlauncher.SteamUtils; import jakebellotti.steamvrlauncher.SteamVRLauncher; import jakebellotti.steamvrlauncher.io.SteamDBParser; import jakebellotti.steamvrlauncher.io.SteamVRAppsFileParser; import jakebellotti.steamvrlauncher.model.ApplicationsListViewModifier; import jakebellotti.steamvrlauncher.model.FileModificationHistory; import jakebellotti.steamvrlauncher.model.HeadMountedDisplay; import jakebellotti.steamvrlauncher.model.ScreenResolution; import jakebellotti.steamvrlauncher.model.SteamApp; import jakebellotti.steamvrlauncher.model.SteamAppSettings; import jakebellotti.steamvrlauncher.model.SteamVRApp; import jakebellotti.steamvrlauncher.model.alvm.ImageTileApplicationsListViewModifier; import jakebellotti.steamvrlauncher.model.alvm.LabelApplicationsListViewModifier; import jakebellotti.steamvrlauncher.model.hmd.HTCViveHMD; import jakebellotti.steamvrlauncher.resources.Resources; import jakebellotti.steamvrlauncher.ui.tab.AboutTabController; import jakebellotti.steamvrlauncher.ui.tab.SettingsTabController; import javafx.application.Platform; import javafx.collections.ListChangeListener; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Cursor; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Slider; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.stage.Stage; import jblib.javafx.Alerts; import jblib.javafx.JavaFXUtils; /** * TODO add a way to delete file modification history (when the program gets * used too much it will start to lag) * * TODO save the currently selected list view mode * * @author Jake Bellotti * */ public class ApplicationGUIController { private final Stage stage; private final ArrayList<SteamApp> loadedApps = new ArrayList<>(); //Tab controller instances private final AboutTabController aboutTabController; private final SettingsTabController settingsTabController; @FXML private AnchorPane rootPane; @FXML private TabPane rootTabPane; @FXML private Button rescanSteamFoldersButton; @FXML private Label gamesLabel; @FXML private ListView<SteamApp> gamesListView; @FXML private Label renderTargetMultiplierLabel; @FXML private Label currentRenderTargetMultiplierLabel; @FXML private Label savedRenderTargetMultiplierLabel; @FXML private TextField searchApplicationsTextField; @FXML private Button upApplicationsButton; @FXML private Button downApplicationsButton; @FXML private Slider renderTargetMultiplierSlider; @FXML private TextField currentRenderTargetMultiplierTextField; @FXML private TextField savedRenderTargetMultiplierTextField; @FXML private ImageView plusRTMImageView; @FXML private ImageView minusRTMImageView; @FXML private CheckBox reprojectionCheckBox; @FXML private Label currentGameLabel; @FXML private Button launchApplicationButton; @FXML private Button saveApplicationButton; @FXML private ImageView currentApplicationImageView; @FXML private HBox currentAppImageHBox; @FXML private AnchorPane currentAppImagePane; @FXML private ListView<FileModificationHistory> fileVersionHistoryListView; @FXML private TextArea fileHistoryModifiedTextArea; @FXML private TextArea fileHistoryOriginalTextArea; @FXML private Button revertFileModificationButton; @FXML private TextField outputResolutionTextField; @FXML private Label outputResolutionLabel; @FXML private ComboBox<ApplicationsListViewModifier> applicationsListViewLookComboBox; public ApplicationGUIController(final Stage stage) { this.stage = stage; this.aboutTabController = new AboutTabController(this); this.settingsTabController = new SettingsTabController(this); } public static final Stage load() { final Stage stage = new Stage(); try { final FXMLLoader loader = new FXMLLoader(); stage.setTitle("Steam Enhanced Launcher - Version " + Config.VERSION + " - Jake Bellotti"); loader.setController(new ApplicationGUIController(stage)); stage.setScene(new Scene( loader.load(ApplicationGUIController.class.getResource("ApplicationGUI.fxml").openStream()))); } catch (Exception e) { e.printStackTrace(); } return stage; } @FXML public void initialize() { // TODO add tabs addTabs(); // Set cursors this.minusRTMImageView.setCursor(Cursor.HAND); this.plusRTMImageView.setCursor(Cursor.HAND); this.launchApplicationButton.setCursor(Cursor.HAND); this.saveApplicationButton.setCursor(Cursor.HAND); this.upApplicationsButton.setCursor(Cursor.HAND); this.downApplicationsButton.setCursor(Cursor.HAND); this.rescanSteamFoldersButton.setCursor(Cursor.HAND); this.revertFileModificationButton.setCursor(Cursor.HAND); // Set control event handlers this.downApplicationsButton.setOnMouseClicked(this::downApplicationsButtonMouseClicked); this.upApplicationsButton.setOnMouseClicked(this::upApplicationsButtonMouseClicked); this.minusRTMImageView.setOnMousePressed(this::minusRTMImageViewMousePressed); this.launchApplicationButton.setOnMouseClicked(this::launchApplicationButtonMouseClicked); this.plusRTMImageView.setOnMousePressed(this::plusRTMImageViewMousePressed); this.saveApplicationButton.setOnMouseClicked(this::saveApplicationButtonMouseClicked); searchApplicationsTextField.setOnKeyReleased(this::searchApplicationsTextFieldKeyReleased); fileVersionHistoryListView.getSelectionModel().selectedItemProperty() .addListener(l -> fileVersionHistoryListViewItemSelected()); revertFileModificationButton.setOnMouseClicked(this::revertFileModificationButtonMouseClicked); this.rescanSteamFoldersButton.setOnMouseClicked(this::rescanSteamFoldersButtonMouseClicked); this.applicationsListViewLookComboBox.getSelectionModel().selectedItemProperty() .addListener(l -> this.applicationsListViewLookComboBoxItemSelected()); addOutputResolutionEventHandlers(); // Set property value listeners this.currentApplicationImageView.fitWidthProperty().bind(currentAppImageHBox.widthProperty()); this.renderTargetMultiplierSlider.valueProperty().addListener(l -> renderTargetMultiplierSliderValueChanged()); this.reprojectionCheckBox.selectedProperty().addListener(l -> this.updateCurrentSettings()); gamesListView.getItems().addListener((ListChangeListener<SteamApp>) e -> gamesListViewListChanged()); gamesListView.getSelectionModel().selectedItemProperty().addListener(l -> gamesListViewItemSelected()); // Add data setImages(); changeListView(); refreshApps(); settingsTabController.refreshSteamFolders(); refreshFileModificationHistory(); // TODO add the event handlers for this addSteamAppListViewComboBoxData(); updateControls(false); // Select default data gamesListView.getSelectionModel().selectFirst(); this.fileVersionHistoryListView.getSelectionModel().selectFirst(); this.applicationsListViewLookComboBox.getSelectionModel().selectFirst(); } private final void addTabs() { rootTabPane.getTabs().add(createTab("Settings", settingsTabController, "SettingsTab.fxml")); rootTabPane.getTabs().add(createTab("About", aboutTabController, "AboutTab.fxml")); } private final Tab createTab(final String tabName, final Object controller, final String resourceName) { // TODO implement final Tab toReturn = new Tab(tabName); try { final FXMLLoader loader = new FXMLLoader(); loader.setController(controller); toReturn.setContent(loader.load(controller.getClass().getResource(resourceName).openStream())); } catch (Exception e) { e.printStackTrace(); } return toReturn; } private final void applicationsListViewLookComboBoxItemSelected() { final ApplicationsListViewModifier selected = applicationsListViewLookComboBox.getSelectionModel() .getSelectedItem(); if (selected != null) { selected.setModification(this.gamesListView); } } private final void addSteamAppListViewComboBoxData() { this.applicationsListViewLookComboBox.getItems().clear(); this.applicationsListViewLookComboBox.getItems().add(new ImageTileApplicationsListViewModifier()); this.applicationsListViewLookComboBox.getItems().add(new LabelApplicationsListViewModifier()); } private final HeadMountedDisplay getSelectedHeadMountedDisplay() { // TODO return the selected one, this is just temporary return new HTCViveHMD(); } private final void addOutputResolutionEventHandlers() { // TODO on hover, on click, when off hover this.outputResolutionTextField.setOnMouseEntered(e -> { this.outputResolutionTextField.setStyle("-fx-text-fill: white; -fx-background-color:black;"); this.outputResolutionTextField.setText("Compare"); this.outputResolutionTextField.setCursor(Cursor.HAND); }); this.outputResolutionTextField.setOnMouseExited(e -> { this.outputResolutionTextField.setStyle(""); final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected != null) this.updateTargetResolution(selected.getCurrentSettings().getRenderTargetMultiplier()); }); } private final void updateTargetResolution(final int renderTargetMultiplier) { // TODO add a way to change current HMD // TODO just make it go by the current apps settings, rather than // supplying the value final HeadMountedDisplay selected = getSelectedHeadMountedDisplay(); if (selected != null) { final ScreenResolution resolution = selected.calculateOutputResolution(renderTargetMultiplier); this.outputResolutionTextField .setText(resolution.getResolutionWidth() + " x " + resolution.getResolutionHeight()); } } private final void rescanSteamFoldersButtonMouseClicked(final MouseEvent e) { // TODO implement file rescanning // TODO clean this up, make it more readable SteamVRLauncher.getConnection().selectAllSteamVRManifestFiles().forEach(manifest -> { if (!manifest.asFile().exists()) { Alerts.showErrorAlert("File not found", "Steam VR Apps Manifest file not found", "Make sure your steam folders are indexed and this file exists."); return; } final Optional<ArrayList<SteamVRApp>> found = SteamVRAppsFileParser.parseManifest(manifest.asFile()); found.ifPresent(o -> { final ArrayList<String> gameNames = new ArrayList<>(); o.forEach(s -> gameNames.add(s.getAppKey())); final ArrayList<String> uniqueNames = SteamVRLauncher.getConnection().selectUniqueSteamApps(gameNames); final Iterator<SteamVRApp> iterator = o.iterator(); while (iterator.hasNext()) { final SteamVRApp current = iterator.next(); if (!uniqueNames.contains(current.getAppKey())) iterator.remove(); } if (o.size() == 0) { Alerts.showInformationAlert("Rescan Steam Folders", "No new applications were added", ""); return; } final AnchorPane loadingScreen = LoadingOverlayController.getSingleton().getRoot(); rootPane.getChildren().add(loadingScreen); loadingScreen.toFront(); loadingScreen.prefWidthProperty().bind(rootPane.widthProperty()); loadingScreen.prefHeightProperty().bind(rootPane.heightProperty()); SteamVRLauncher.submitRunnable(() -> { Platform.runLater(() -> LoadingOverlayController.getSingleton().getCurrentTaskLabel() .setText("Saving " + o.size() + " games")); final HashMap<Integer, SteamVRApp> gameIDs = new HashMap<>(); for (SteamVRApp currentApp : o) { final int appDatabaseID = SteamVRLauncher.getConnection().insertSteamApp(manifest.getId(), currentApp); if (appDatabaseID > 0) { gameIDs.put(appDatabaseID, currentApp); } } final Iterator<Integer> iter = gameIDs.keySet().iterator(); while (iter.hasNext()) { final Integer currentKey = iter.next(); final SteamVRApp currentApp = gameIDs.get(currentKey); Platform.runLater(() -> LoadingOverlayController.getSingleton().getCurrentTaskLabel() .setText("Downloading image for '" + currentApp.getName() + "'")); final Optional<InputStream> result = SteamDBParser.getImage(currentApp); if (result.isPresent()) { final int imageID = SteamVRLauncher.getConnection().insertImage(result.get()); if (imageID > 0) { SteamVRLauncher.getConnection().assignImageToSteamApp(currentKey, imageID); } } } Platform.runLater(() -> rootPane.getChildren().remove(loadingScreen)); refreshApps(); settingsTabController.refreshSteamFolders(); } , "Indexing steam apps"); Alerts.showInformationAlert("Rescan Steam Folders", "New applications were added", "" + o.size() + " new applications were added."); }); }); } private final void revertFileModificationButtonMouseClicked(final MouseEvent event) { // TODO implement file reverting final FileModificationHistory selected = fileVersionHistoryListView.getSelectionModel().getSelectedItem(); if (selected == null) return; if (!selected.asFile().exists()) { // TODO maybe add an option to recreate the file? Alerts.showErrorAlert("File not found", "The file '" + selected.asFile().getName() + "' does not exist.", "The file could not be reverted to it's original contents."); return; } try (FileWriter writer = new FileWriter(selected.asFile())) { writer.write(selected.getOldContent()); writer.close(); Alerts.showInformationAlert("Success", "File contents have been reverted", "Successfully reverted the file '" + selected.asFile().getName() + "' to its original contents."); } catch (Exception e) { Alerts.showErrorAlert("Error", "An error occurred when reverting the file", "Cause: " + e.getMessage()); } } private final void fileVersionHistoryListViewItemSelected() { final FileModificationHistory selected = fileVersionHistoryListView.getSelectionModel().getSelectedItem(); final boolean selectedExists = selected != null; this.revertFileModificationButton.setVisible(selectedExists); this.fileHistoryOriginalTextArea.setVisible(selectedExists); this.fileHistoryModifiedTextArea.setVisible(selectedExists); if (!selectedExists) { this.fileHistoryOriginalTextArea.clear(); this.fileHistoryModifiedTextArea.clear(); return; } this.fileHistoryOriginalTextArea.setText(selected.getOldContent()); this.fileHistoryModifiedTextArea.setText(selected.getNewContent()); } private final void minusRTMImageViewMousePressed(final MouseEvent e) { final double currentWidth = this.minusRTMImageView.getFitWidth(); this.minusRTMImageView.setFitWidth(0.85d * currentWidth); this.minusRTMImageView.setOnMouseReleased(released -> { this.minusRTMImageView.setFitWidth(currentWidth); decreaseRTM(); }); } private final void renderTargetMultiplierSliderValueChanged() { final String rtm = "" + renderTargetMultiplierSlider.getValue(); final int decimalPoint = rtm.indexOf("."); final String value = rtm.substring(0, decimalPoint + 2); this.currentRenderTargetMultiplierTextField.setText(value); final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected == null) return; final double currentRTMValue = (this.renderTargetMultiplierSlider.getValue() * 10); selected.setCurrentSettings( new SteamAppSettings((int) currentRTMValue, selected.getCurrentSettings().isAllowReprojection())); checkDirty(); this.updateTargetResolution(selected.getCurrentSettings().getRenderTargetMultiplier()); } private final void plusRTMImageViewMousePressed(final MouseEvent e) { final double currentWidth = this.plusRTMImageView.getFitWidth(); this.plusRTMImageView.setFitWidth(0.85d * currentWidth); this.plusRTMImageView.setOnMouseReleased(released -> { this.plusRTMImageView.setFitWidth(currentWidth); increaseRTM(); }); } private final void gamesListViewListChanged() { gamesLabel.setText("Applications (" + gamesListView.getItems().size() + ")"); } private final void searchApplicationsTextFieldKeyReleased(KeyEvent e) { this.updateShownApps(); } @SuppressWarnings("unchecked") private final void launchApplicationButtonMouseClicked(MouseEvent event) { final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected == null) return; // TODO finish this final ArrayList<File> folders = new ArrayList<>(); this.settingsTabController.getSteamFoldersListView().getItems().forEach(sf -> folders.add(sf.asFile())); final Optional<File> steamVRSettingsFile = SteamUtils.findSteamVRSettings(folders); if (!steamVRSettingsFile.isPresent()) { Alerts.showErrorAlert("Error", "Steam VR Settings not found", "Ensure that the folder containing this file is indexed (Maybe Steam is installed over multiple drives)."); return; } final String taskList = getTaskList(); final boolean vrMonitorRunning = isSteamVRMonitorRunning(taskList); try { final StringBuilder builder = new StringBuilder(); final Scanner scanner = new Scanner(steamVRSettingsFile.get()); while (scanner.hasNextLine()) builder.append(scanner.nextLine() + "\n"); scanner.close(); final JSONParser parser = new JSONParser(); final JSONObject settings = (JSONObject) parser.parse(builder.toString()); JSONObject steamVR = (JSONObject) settings.get("steamvr"); if (steamVR == null) { steamVR = new JSONObject(); steamVR.put("allowReprojection", selected.getCurrentSettings().isAllowReprojection()); steamVR.put("renderTargetMultiplier", ((double) (selected.getCurrentSettings().getRenderTargetMultiplier() / 10d))); settings.put("steamvr", steamVR); } else { steamVR.put("allowReprojection", selected.getCurrentSettings().isAllowReprojection()); steamVR.put("renderTargetMultiplier", ((double) (selected.getCurrentSettings().getRenderTargetMultiplier() / 10d))); } final Gson gson = new GsonBuilder().setPrettyPrinting().create(); final String jsonOutput = gson.toJson(settings); final FileWriter writer = new FileWriter(steamVRSettingsFile.get()); writer.write(jsonOutput); writer.close(); final String changeComment = "Changed settings before launching '" + selected.getName() + "'"; SteamVRLauncher.getConnection().insertFileModificationHistory(steamVRSettingsFile.get().getAbsolutePath(), changeComment, builder.toString(), jsonOutput); refreshFileModificationHistory(); // TODO organise the JSON when exporting if (vrMonitorRunning) { final Process killVRMonitor = Runtime.getRuntime() .exec("taskkill /F /IM " + SteamConstants.STEAM_VR_MONITOR_PROCESS_NAME); killVRMonitor.waitFor(); } // TODO maybe even find another way to deal with these SteamVR bugs // TODO extract this to a settings variable Thread.sleep(5000); URI uri = new URI(selected.getLaunchPath()); Desktop.getDesktop().browse(uri); } catch (Exception e) { e.printStackTrace(); } } private final void refreshFileModificationHistory() { // TODO make this have better peformance this.fileVersionHistoryListView.getItems().setAll(SteamVRLauncher.getConnection().selectAllFileModifications()); } public final String getTaskList() { final StringBuilder builder = new StringBuilder(); try { final Process taskList = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\tasklist.exe"); final BufferedReader input = new BufferedReader(new InputStreamReader(taskList.getInputStream())); String line; while ((line = input.readLine()) != null) builder.append(line + "\n"); input.close(); } catch (Exception e) { e.printStackTrace(); } return builder.toString().trim(); } public final boolean isSteamVRMonitorRunning(final String taskList) { return taskList.contains(SteamConstants.STEAM_VR_MONITOR_PROCESS_NAME); } public final boolean isSteamVRServerRunning(final String taskList) { return taskList.contains(SteamConstants.STEAM_VR_SERVER_PROCESS_NAME); } private final void upApplicationsButtonMouseClicked(MouseEvent e) { // TODO make this scroll down from the first visible index final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected != null) { final int selectedIndex = this.gamesListView.getItems().indexOf(selected); if (selectedIndex > -1 && selectedIndex != 0) { final int newIndex = selectedIndex - 1; this.gamesListView.getSelectionModel().select(newIndex); this.gamesListView.scrollTo(newIndex); } Platform.runLater(() -> gamesListView.requestFocus()); } } private final void downApplicationsButtonMouseClicked(MouseEvent e) { final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected != null) { final int maxIndexes = this.gamesListView.getItems().size(); final int selectedIndex = this.gamesListView.getItems().indexOf(selected); final int newIndex = selectedIndex + 1; if (selectedIndex > -1 && newIndex < maxIndexes) { this.gamesListView.getSelectionModel().select(newIndex); this.gamesListView.scrollTo(newIndex); } Platform.runLater(() -> gamesListView.requestFocus()); } } private final void saveApplicationButtonMouseClicked(final MouseEvent e) { final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected != null) { SteamVRLauncher.getConnection().updateSteamAppSettings(selected.getId(), selected.getCurrentSettings().getRenderTargetMultiplier(), selected.getCurrentSettings().isAllowReprojection()); selected.setSavedSettings(selected.getCurrentSettings().copy()); gamesListViewItemSelected(); Platform.runLater(() -> gamesListView.requestFocus()); checkDirty(); } } private final void updateCurrentSettings() { final SteamApp selected = this.gamesListView.getSelectionModel().getSelectedItem(); if (selected == null) return; final double currentRTMValue = (this.renderTargetMultiplierSlider.getValue() * 10); selected.setCurrentSettings( new SteamAppSettings((int) currentRTMValue, this.reprojectionCheckBox.isSelected())); checkDirty(); } private final void updateControls(boolean toggle) { this.currentGameLabel.setVisible(toggle); this.currentApplicationImageView.setVisible(toggle); this.renderTargetMultiplierSlider.setVisible(toggle); this.minusRTMImageView.setVisible(toggle); this.plusRTMImageView.setVisible(toggle); this.currentRenderTargetMultiplierTextField.setVisible(toggle); this.savedRenderTargetMultiplierTextField.setVisible(toggle); this.reprojectionCheckBox.setVisible(toggle); this.launchApplicationButton.setVisible(toggle); this.saveApplicationButton.setVisible(toggle); this.currentRenderTargetMultiplierLabel.setVisible(toggle); this.savedRenderTargetMultiplierLabel.setVisible(toggle); this.renderTargetMultiplierLabel.setVisible(toggle); this.outputResolutionLabel.setVisible(toggle); this.outputResolutionTextField.setVisible(toggle); } private final void gamesListViewItemSelected() { final SteamApp selected = gamesListView.getSelectionModel().getSelectedItem(); final boolean isAnySelected = selected != null; updateControls(isAnySelected); if (!isAnySelected) return; this.currentGameLabel.setText(selected.getName()); if (selected.getImage().isPresent()) { this.currentApplicationImageView.setImage(selected.getImage().get()); } else { // TODO maybe set as a custom image that says 'image not found' this.currentApplicationImageView.setImage(Resources.getImageNotFound()); } final double currentRTM = (selected.getCurrentSettings().getRenderTargetMultiplier() / 10d); final double savedRTM = (selected.getSavedSettings().getRenderTargetMultiplier() / 10d); this.currentRenderTargetMultiplierTextField.setText("" + currentRTM); this.savedRenderTargetMultiplierTextField.setText("" + savedRTM); this.renderTargetMultiplierSlider.setValue(currentRTM); this.reprojectionCheckBox.setSelected(selected.getCurrentSettings().isAllowReprojection()); checkDirty(); } private final void checkDirty() { final SteamApp selected = gamesListView.getSelectionModel().getSelectedItem(); if (selected != null) { final boolean dirty = selected.isDirty(); this.saveApplicationButton.setDisable(!dirty); } } private final void decreaseRTM() { int rtm = gamesListView.getSelectionModel().getSelectedItem().getCurrentSettings().getRenderTargetMultiplier(); rtm = (rtm - 1); if (rtm < 0) rtm = 0; final double currentValue = (rtm / 10d); this.renderTargetMultiplierSlider.setValue(currentValue); } private final void increaseRTM() { // TODO make it so the setting goes by a constant instead of just 30 int rtm = gamesListView.getSelectionModel().getSelectedItem().getCurrentSettings().getRenderTargetMultiplier(); rtm = (rtm + 1); if (rtm > 30) rtm = 30; final double currentValue = (rtm / 10d); this.renderTargetMultiplierSlider.setValue(currentValue); } private final void setImages() { try { plusRTMImageView.setImage(new Image(Resources.class.getResource("plus_icon.png").openStream())); minusRTMImageView.setImage(new Image(Resources.class.getResource("minus_icon.png").openStream())); } catch (Exception e) { e.printStackTrace(); } } private final void changeListView() { // TODO make this either an image or the name of the app JavaFXUtils.setListViewCellFactory(gamesListView, (cell, item, b) -> { final Optional<Image> image = item.getImage(); if (!image.isPresent()) { final Label label = new Label(item.getName()); label.setStyle("-fx-font-size: 20px;"); cell.setGraphic(label); return; } final ImageView view = new ImageView(image.get()); view.setPreserveRatio(true); this.gamesListView.widthProperty().addListener(l -> { view.setFitWidth(gamesListView.getWidth() * 0.92d); }); cell.setGraphic(view); view.setFitWidth(gamesListView.getWidth() * 0.92d); }); } public final void refreshApps() { // TODO check to see if there are any at all... Platform.runLater(() -> { final AnchorPane loadingScreen = LoadingOverlayController.getSingleton().getRoot(); rootPane.getChildren().add(loadingScreen); loadingScreen.toFront(); loadingScreen.prefWidthProperty().bind(rootPane.widthProperty()); loadingScreen.prefHeightProperty().bind(rootPane.heightProperty()); LoadingOverlayController.getSingleton().getCurrentTaskLabel().setText("Refreshing application list..."); this.loadedApps.clear(); this.loadedApps.addAll(SteamVRLauncher.getConnection().selectAllSteamApps()); updateShownApps(); rootPane.getChildren().remove(loadingScreen); }); } private final void updateShownApps() { final ArrayList<SteamApp> showing = new ArrayList<>(); final String searchQuery = this.searchApplicationsTextField.getText().trim(); final boolean queryNull = (searchQuery == null || searchQuery.length() < 1); this.gamesListView.getItems().clear(); for (SteamApp a : this.loadedApps) { if (queryNull) { showing.add(a); continue; } else { if (a.getName().toLowerCase().contains(searchQuery.toLowerCase())) showing.add(a); } } this.gamesListView.getItems().setAll(showing); } public AnchorPane getRootPane() { return rootPane; } public Stage getStage() { return stage; } public AboutTabController getAboutTabController() { return aboutTabController; } }
package project; /*깃허브 수정 보려고 그냥 입력함*/ import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import lotto.dao.MemberDAO; public class Login extends JFrame { private JPanel contentPane; private JLabel lbl_title; private JLabel lbl_id; private JLabel lbl_pwd; private JTextField txt_id; private JTextField txt_pwd; public JTextField getTxt_id() { return txt_id; } public void setTxt_id(JTextField txt_id) { this.txt_id = txt_id; } public JTextField getTxt_pwd() { return txt_pwd; } public void setTxt_pwd(JTextField txt_pwd) { this.txt_pwd = txt_pwd; } private JButton btn_login; private JButton btn_join; private JButton btn_close; private final Action action = new SwingAction(); MemberDAO dao = new MemberDAO(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Login frame = new Login(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Login() { try{ dao.dbConnect(); }catch(Exception e){ e.printStackTrace(); } initGUI(); } private void initGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 315, 256); //화면 중앙 출력을 위한 코드----- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = this.getSize(); int xpos = (int)(screenSize.getWidth() - frameSize.getWidth()) / 2; int ypos = (int)(screenSize.getHeight() - frameSize.getHeight()) / 2; this.setLocation(xpos, ypos); //-------------------------------- contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); lbl_title = new JLabel("IT_Lotto"); lbl_title.setFont(new Font("굴림", Font.BOLD, 30)); lbl_title.setBounds(76, 10, 165, 54); contentPane.add(lbl_title); lbl_id = new JLabel("ID"); lbl_id.setBounds(43, 80, 67, 15); contentPane.add(lbl_id); lbl_pwd = new JLabel("Password"); lbl_pwd.setBounds(43, 133, 78, 15); contentPane.add(lbl_pwd); txt_id = new JTextField(); txt_id.setBounds(133, 80, 116, 21); contentPane.add(txt_id); txt_id.setColumns(10); txt_pwd = new JPasswordField(); txt_pwd.setBounds(133, 130, 116, 21); contentPane.add(txt_pwd); txt_pwd.setColumns(10); btn_login = new JButton("로그인"); btn_login.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_btn_login_actionPerformed(e); } }); btn_login.setBounds(24, 172, 75, 23); contentPane.add(btn_login); btn_join = new JButton("가입"); btn_join.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_btn_join_actionPerformed(e); } }); btn_join.setBounds(111, 172, 75, 23); contentPane.add(btn_join); btn_close = new JButton("닫기"); btn_close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_btn_close_actionPerformed(e); } }); btn_close.setBounds(198, 172, 75, 23); contentPane.add(btn_close); } private class SwingAction extends AbstractAction { public SwingAction() { putValue(NAME, "SwingAction"); putValue(SHORT_DESCRIPTION, "Some short description"); } public void actionPerformed(ActionEvent e) { } } protected void do_btn_close_actionPerformed(ActionEvent e) { System.exit(0); } protected void do_btn_join_actionPerformed(ActionEvent e) { JoinGUI joinGUI = new JoinGUI(); } protected void do_btn_login_actionPerformed(ActionEvent e) { String login_id = txt_id.getText(); String pwd = txt_pwd.getText(); if(login_id.equals("")){ JOptionPane.showMessageDialog(null, "아이디를 입력하여 주세요"); }else if(pwd.equals("")){ JOptionPane.showMessageDialog(null, "비밀번호를 입력하여 주세요"); }else{ System.out.println("출력확인용"); String id = dao.login(login_id, pwd); if(id != null && id.equals("nopass")==false && id.equals("noid")==false){ System.out.println(id+"님 환영합니다"); int k = dao.div_admin(id); if(k ==1){ Admin_main am = new Admin_main(id); }else if(k==0){ User_main um = new User_main(id); }else{ System.out.println("로그인 오류입니다."); } } else if(id.equals("nopass")){ txt_pwd.setText(""); System.out.println("다시입력해주세요"); JOptionPane.showMessageDialog(null, "비밀번호가 틀렸습니다."); }else if(id.equals("noid")){ txt_id.setText(""); txt_pwd.setText(""); System.out.println("다시입력해주세요"); JOptionPane.showMessageDialog(null, "존재하지 않는 ID입니다."); } } } }
/* * CountData.java * * Created on 2006Äê10ÔÂ18ÈÕ, ÏÂÎç4:44 * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package tot.count; /** * * @author Administrator */ public class CountBean { private String countType; int countId; /** Creates a new instance of CountData */ public CountBean() { } public void setCountType(String countTypes){ this.countType=countTypes; } public void setCountId(int countIds){ this.countId=countIds; } public String getCountType(){ return countType; } public int getCountId(){ return countId; } }
package factoring.trial.variant; import java.util.Collection; /** * This implementation is generating a list of all primes up to a limit. * Beside of storing the prime itself, it also store the reciprocal value. * When checking a number if it is dividable by the prime, we will not divide * the number by the prime, we will multiply by the inverse, since this is faster. * Due to precision we have to check for a given range near an Integer. * And then do a Long division. * This implementation is around two times faster then a version based on long numbers. * Since Double only has 52 bis for the remainder, this can only work for numbers below 2^52. * We can only factorize numbers up to maxFactor^2 * When calling it with bigger numbers only prime factors below * maxFactor were added to the factors. {@link #findPrimeFactors(long, Collection, double, double)} then might return a * composite number. ** * Created by Thilo Harich on 02.03.2017. */ public class TrialRangeFact { // The number of values to be printed private static final int PRINT_NUM = 20000; // for printing we need a value a little bit above 1 public static final double PRINT_CONST = 1.0000001; private int maxFactor = 65535; double[] primesInv; int[] primes; int maxFactorIndex = 0; /** * finds the prime factors up to maxFactor by the sieve of eratosthenes. * Not optimized, since this is only called once when initializing. */ void initPrimesEratosthenes() { final double logMaxFactor = Math.log(maxFactor); final int maxPrimeIndex = (int) ((maxFactor) / (logMaxFactor - 1.1)) + 1; primesInv = new double [maxPrimeIndex]; //the 6542 primesInv up to 65536=2^16, then sentinel 65535 at end primes = new int [maxPrimeIndex]; //the 6542 primesInv up to 65536=2^16, then sentinel 65535 at end final boolean [] noPrimes = new boolean [maxFactor]; for (int i = 2; i <= Math.sqrt(maxFactor); i++) { if (!noPrimes[i]) { primes[maxFactorIndex] = i; primesInv[maxFactorIndex++] = 1.0 / i; } for (int j = i * i; j < maxFactor; j += i) { noPrimes[j] = true; } } for (int i = (int) (Math.sqrt(maxFactor)+1); i < maxFactor; i++) { if (!noPrimes[i]) { primes[maxFactorIndex] = i; primesInv[maxFactorIndex++] = 1.0 / i; } } for (int i = maxFactorIndex; i < primes.length; i++) { primes[i] = Integer.MAX_VALUE; } System.out.println("Prime table built max factor '" + maxFactor + "' bytes used : " + maxFactorIndex * 12); } public TrialRangeFact(int maxFactor) { // if (maxFactor > 65535) // throw new IllegalArgumentException("the maximal factor has to be lower then 65536"); this.maxFactor = maxFactor; // initPrimes(); initPrimesEratosthenes(); } /** * since * f(x) = x * ln (x) * f(x*b) = x*b * ln (x*b) = x*b * (ln (x) + ln(b)) = f(x)*b + x*b*ln(b) < = f(x)*b * (1 + b*ln(b)/ln(x)) * b = begin - begin * Math. * begin - 1 = * primes [(int)(maxFactorIndex*begin)] < primes [maxFactorIndex] * @param n * @param primeFactors * @param begin * @param end * @return */ public long findPrimeFactors(long n, Collection<Long> primeFactors, double begin, double end) { // adjust the begin and end value such that it begins/ends just below n^1/3 // this ensures we always have prime factors in the lehman phase as well // double b = end == 1 ? begin : end; // double correctFakt = b - b * Math.log(b) * 3 / Math.log(n); // begin = begin == 0 ? 0 : correctFakt; // end = end == 1 ? 1 : correctFakt; for (int primeIndex = (int)(maxFactorIndex*begin); primeIndex < maxFactorIndex*end; primeIndex++) { double nDivPrime = n*primesInv[primeIndex]; // TODO choose the precision factor with respect to the maxFactor!? // if (primes[primeIndex] == 0) // System.out.println(); while (Math.abs(Math.round(nDivPrime) - nDivPrime) < 0.01 && n > 1 && n % primes[primeIndex] == 0) { if (primeFactors == null) return (long) primes[primeIndex]; primeFactors.add((long) primes[primeIndex]); n = Math.round(nDivPrime); // // if the remainder is lower then the maximal prime we can exit early // if (n < maxFactor && primeFactors != null){ // primeFactors.add(n); // return 1; // } nDivPrime = n*primesInv[primeIndex]; } } return n; } public long findPrimeFactor(long n, Collection<Long> factors, int primeIndex) { double nDivPrime = n*primesInv[primeIndex]; // TODO choose the precision factor with respect to the maxFactor!? if (primes[primeIndex] == 0) System.out.println(); while (Math.abs(Math.round(nDivPrime) - nDivPrime) < 0.01 && n > 1 && n % primes[primeIndex] == 0) { factors.add((long) primes[primeIndex]); n = Math.round(nDivPrime); nDivPrime = n*primesInv[primeIndex]; } return n; } public void setMaxFactor(int maxTrialFactor) { maxFactor = maxTrialFactor; } }
package com.itheima.day_03.innerClass; public class InnerDemo { public static void main(String[] args) { Outer.Inner inner = new Outer("李四").new Inner(); inner.show(); } }
package mylistpackage; import java.util.Iterator; /** * Represents MyList interface. * * @author Letian Sun * @version Jan. 12, 2015 * @param <Type> is of any object type. */ public interface MyList<Type> { /** * Returns the current number of elements in the list. * @return the current number of elements in the list >= 0 */ public int getSize(); /** * Returns whether the list is empty. * @return true if list is empty, false otherwise. */ public boolean isEmpty(); /** * Returns whether value is in the list. * @param value assigned * @return true if value in the list, false otherwise. */ public boolean contains(Type value); /** * Inserts an element in the back of the list. * @param value assigned */ public void insert(Type value); /** * Insert an element into the front of the list. Previous front element is then moved to the back. * @param value - the element to insert into the front of the list */ public void insertFront(Type value); /** * Remove the element at a particular index * @param index - index of the element to remove */ public void removeAtIndex(int index); /** * Removes the first occurrence of the element from the list. * @param value assigned */ public void remove(Type value); /** * Clears the list. */ public void clear(); /** * Returns a string representation of list contents. * @return a string representation of list contents. * @see Object#toString() */ @Override public String toString(); /** * Returns the index of a given element in the list * @param value - value in list to retrieve the index of * @return the index of the given value, or -1 if given value does not exist */ public int getIndex(Type value); /** * Insert an element at a particular element in the list * @param index the index to insert the element at * @param value the value to insert at that index */ public void insertAtIndex(int index, Type value); /** * Set the element at a particular index in the list * @param index the index to set element at * @param value the element to set */ public void set(int index, Type value); /** * Retrieve the element at a particular index * @param index - index of element to retrieve * @return the element at that index */ public Type get(int index); /** * Returns an iterator for this list * @return an iterator for this list */ public Iterator<Type> iterator(); }
package custom; import javax.swing.JFrame; public class GenericFrame extends JFrame { public GenericFrame() { super(); setGenericProperties(); } public GenericFrame(String t) { super(t); setGenericProperties(); } public GenericFrame(int w, int h) { super(); setSize(w, h); setGenericProperties(); } private void setGenericProperties() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); } }
package com.example.jonathan.iadvisor; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.util.TypedValue; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class favorite extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private ListView listView; private String[] list = {"3008 大立光", "2330 台積電", "2412 中華電", "2498 宏達電", "2357 華碩", "2376 技嘉", "2379 瑞昱", "2454 聯發科"};//the list!! private ArrayAdapter<String> listAdapter; NotificationManager manager; Notification myNotication; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_favorite); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent intent = new Intent(favorite.this,stock.class); PendingIntent pendingIntent = PendingIntent.getActivity(favorite.this, 1, intent, 0); //intent.setClass(favorite.this, stock.class); Notification.Builder builder = new Notification.Builder(favorite.this); builder.setAutoCancel(true); //builder.setTicker("this is ticker text"); builder.setContentTitle("iAdvisor關心您"); builder.setContentText("2498 宏達電 泡沫指數已達危險值"); builder.setSmallIcon(R.drawable.ic_action_notice); builder.setContentIntent(pendingIntent); builder.setOngoing(true); //builder.setSubText("This is subtext..."); //API level 16 //builder.setNumber(100); builder.build(); myNotication = builder.getNotification(); manager.notify(11, myNotication); listView = (ListView) findViewById(R.id.listView); //listAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, list) {//android.R.layout.simple_list_item_1 @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent);/// Get the Item from ListView TextView tv = (TextView) view.findViewById(android.R.id.text1); tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);// Set the text size 25 dip for ListView each item if(list[position]=="2498 宏達電"){ tv.setBackgroundColor(getResources().getColor(R.color.pink)); } else if(list[position]=="2454 聯發科"){ tv.setBackgroundColor(getResources().getColor(R.color.yello)); } else{ tv.setBackgroundColor(getResources().getColor(R.color.blue)); } //tv.setTextColor(Color.RED); //tv.setTextSize(20); //tv.setBackgroundColor(Color.BLUE); // Return the view return view; } }; listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), list[position] + " 資料擷取中...", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); intent.setClass(favorite.this, stock.class); Bundle bundle = new Bundle(); bundle.putString("input", list[position]); intent.putExtras(bundle); startActivityForResult(intent, 2); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (id == R.id.action_find) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action Intent intent = new Intent(); intent.setClass(favorite.this, MainActivity.class); Bundle bundle = new Bundle(); bundle.putString("input", "hahahah"); intent.putExtras(bundle); startActivityForResult(intent, 2); } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
import java.io.Serializable; import java.util.ArrayList; import java.util.Date; public class UtenteList implements Serializable { String archive_id; String last_modification; private ArrayList<Utente> list; public UtenteList(){ list = new ArrayList<>(); } public synchronized void add(Utente p){ last_modification = new Date().toString(); list.add(p); } public synchronized String remove(String cf){ last_modification = new Date().toString(); String responso = null; for (Utente ut : list){ if ((ut.getCF().equals(cf))){ list.remove(ut); responso = "REMOVE_OK"; return responso; } } System.out.println("Utente non presente in lista"); responso = "REMOVE_ERROR"; return responso; } public ArrayList<Utente> getListCopy(){ ArrayList<Utente> a_list = new ArrayList<>(); a_list.addAll(list); return a_list; } @Override public String toString() { String s; s = "BEGIN_LIST"; s = s + "MOD_DATE:" + last_modification; for (Utente u : list){ s = s + "CF: " + u.getCF(); s = s + "Nome: " + u.getNome(); s = s + "Cognome: " + u.getCognome(); s = s + "Mansione: " + u.getMansione(); } s = s + "END_LIST"; return s; } }
package kr.co.magiclms.mapper; import java.util.List; import kr.co.magiclms.domain.Order; public interface OrderMapper { List<Order> selectOrder(); Order selectOrderByName(String memberId); Order selectOrderByNo(int no); void insertOrder(Order order); }
package com.lenovohit.hwe.treat.model; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.hwe.base.model.AuditableModel; @Entity @Table(name = "TREAT_CONSULT_REPLY") public class ConsultReply extends AuditableModel implements java.io.Serializable{ private static final long serialVersionUID = 2785667409688656841L; public static final String STATUS_NO_READ ="0"; //未读 public static final String STATUS_READ ="1"; //已读 private String businessId; private String sendId; private String sendName; private String sendContent; private String status; // 0未读 1已读 private String type; private String stopFlag; public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public String getSendId() { return sendId; } public void setSendId(String sendId) { this.sendId = sendId; } public String getSendName() { return sendName; } public void setSendName(String sendName) { this.sendName = sendName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStopFlag() { return stopFlag; } public void setStopFlag(String stopFlag) { this.stopFlag = stopFlag; } public String getSendContent() { return sendContent; } public void setSendContent(String sendContent) { this.sendContent = sendContent; } }
package com.lotus.util; import java.util.Comparator; public class PairComparator implements Comparator<Pair<String, Integer>> { @Override public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) { // if (o1.getFirst().equalsIgnoreCase(o2.getFirst())) { // return 0; // }else { return o2.getSecond() - o1.getSecond(); // } } }
import java.util.*; public class PlusOne { public static List<Integer> plusOneAdd(List<Integer> A) { int n = A.size() - 1; A.set(n, A.get(n) + 1); for(int i = n; i > 0 && A.get(i) == 10; --i) { A.set(i,0); A.set(i-1, A.get(i-1) + 1); } if(A.get(0) == 10) { A.set(0, 1); A.add(0); } return A; } public static void main(String args[]) { Scanner sc = new Scanner (System.in); System.out.println("Enter size of the list"); int size = sc.nextInt(); List<Integer> list = new ArrayList<Integer>(); for(int i=0; i<size; i++) { list.add(sc.nextInt()); } list = plusOneAdd(list); for(int i = 0; i < list.size(); i++) { System.out.print(list.get(i)); } sc.close(); } }
package com.github.davidmoten.geo; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class Base32Test { public static final long MAX_LONG_DECODE = 9223372036854775807L ; public static final long MIN_LONG_DECODE = -9223372036854775807L ; public static final String MAX_LONG_ENCODE = "7zzzzzzzzzzzz" ; public static final String MIN_LONG_ENCODE = "-7zzzzzzzzzzzz" ; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void encodeBase32() throws Exception { String encode_max = Base32.encodeBase32(MAX_LONG_DECODE); String encode_min = Base32.encodeBase32(MIN_LONG_DECODE); assertEquals(MAX_LONG_ENCODE, encode_max); assertEquals(MIN_LONG_ENCODE, encode_min); } @Test public void encodeBase32hasLength() throws Exception { String encode_max = Base32.encodeBase32(MAX_LONG_DECODE, 12); String encode_min = Base32.encodeBase32(MIN_LONG_DECODE, 13); String encode_neg = Base32.encodeBase32(-31, 13); assertEquals(MAX_LONG_ENCODE, encode_max); assertEquals(MIN_LONG_ENCODE, encode_min); assertEquals("-000000000000z", encode_neg); } @Test public void decodeBase32() throws Exception { long decode_max = Base32.decodeBase32(MAX_LONG_ENCODE); long decode_min = Base32.decodeBase32(MIN_LONG_ENCODE); long decode_null = Base32.decodeBase32(""); assertEquals(MAX_LONG_DECODE, decode_max); assertEquals(MIN_LONG_DECODE, decode_min); assertEquals(0,decode_null); } @Test public void getCharIndex() throws Exception { int index_max = Base32.getCharIndex('z'); int index_min = Base32.getCharIndex('0'); assertEquals(31, index_max); assertEquals(0, index_min); } @Test public void padLeftWithZerosToLength() throws Exception { String padWord = Base32.padLeftWithZerosToLength("a",2); String padMax = Base32.padLeftWithZerosToLength(MAX_LONG_ENCODE,3); String padMin = Base32.padLeftWithZerosToLength(MIN_LONG_ENCODE,3); assertEquals("0a", padWord); assertEquals("7zzzzzzzzzzzz", padMax); assertEquals("-7zzzzzzzzzzzz", padMin); } @Test (expected = IllegalArgumentException.class) public void decodeBase32Exception() throws Exception { long decodeException = Base32.decodeBase32(" "); } }
/** * /**************************************************************************** * Name: Luis Gustavo Grubert Valensuela Z#:23351882 lvalensuela2015@fau.edu * Course: JavaProgramming * Professor: Dr. Mehrdad Nojoumian * Due Date:02/22/2018 Due Time: 11:30PM * Assignment Number: lab 05 * Last Changed: 02/22/2018 * * Description: * Program to display a student information. * * In this assignment a class Student will be created with the following * * instance variables: * public String name; * public String ZNumber; * public String major; * public Double gpa; * public int birthYear; * public int credits; * * Methods: * public void initialize(args) * public void studentAge() * public void studentProfile() * public void studentYear() * /******************************************************************************* */ package lab5.q2; import java.util.Calendar; class Student{ public String name; public String ZNumber; public String major; public Double gpa; public int birthYear; public int credits; public void initialize(String studentName, String studentZNumber, String studentMajor, double studentGPA, int studentBirthYear, int studentCredits){ name = studentName; ZNumber = studentZNumber; major = studentMajor; gpa = studentGPA; birthYear = studentBirthYear; credits = studentCredits; } public void studentAge() { int year = Calendar.getInstance().get(Calendar.YEAR); int age = year - birthYear; System.out.println(name +" is "+age+"\n"); } public void studentProfile(){ System.out.println("Name - "+name); System.out.println("Z Number - "+ZNumber); System.out.println("Major - "+major); System.out.println("GPA - "+gpa+ "\n"); } public void studentYear(){ if(credits < 30) { System.out.println(name + " is a freshmen"); } else if(credits < 60) { System.out.println(name + " is a sophomore"); } else if(credits < 90) { System.out.println(name + " is a junior"); } else { System.out.println(name + " is a senior"); } System.out.println(""); } } public class Q2 { public static void main(String[] args) { Student student1 = new Student(); Student student2 = new Student(); student1.initialize("Gustavo", "z23351882", "Computer Engineer", 3.96, 1976, 200); student2.initialize("Rachel", "z1546431", "Computer Science", 3.05, 1999, 60); student1.studentAge(); student1.studentProfile(); student1.studentYear(); student2.studentAge(); student2.studentProfile(); student2.studentYear(); } }
package com.tmdaq.etltool.json.wapper; import com.alibaba.fastjson.JSON; import com.tmdaq.etltool.core.Configuration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author vttmlin */ public class FastJsonWapper extends Json { FastJsonWapper(Configuration config) { super(config); } @Override Map<String, Object> readValue(String json) { if (json == null || "".equals(json)) { return new HashMap<>(0); } return JSON.parseObject(json, Map.class); } @Override List readValueFromList(String json) { if (json == null || "".equals(json)) { return new ArrayList(); } return JSON.parseObject(json, List.class); } }
package com.explore.service.Impl; import com.explore.common.ServerResponse; import com.explore.dao.*; import com.explore.pojo.*; import com.explore.service.ICampusService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Transactional @Service public class CampusServiceImpl implements ICampusService { @Autowired StudentMapper studentMapper; @Autowired CoachMapper coachMapper; @Autowired VehicleMapper vehicleMapper; @Autowired SubjectStudentMapper subjectStudentMapper; @Autowired CampusMapper campusMapper; @Autowired SubjectMapper subjectMapper; @Override public ServerResponse searchStudents(Campus campus) { List<Student> students = studentMapper.searchStudentCampus(campus.getId()); return ServerResponse.createBySuccess(students); } @Override public ServerResponse searchCoaches(Campus campus) { List<Coach> coaches = coachMapper.searchCoachesCampus(campus.getId()); return ServerResponse.createBySuccess(coaches); } @Override public ServerResponse searchVehicles(Campus campus) { List<Vehicle> vehicles = vehicleMapper.searchVehiclesCampus(campus.getId()); return ServerResponse.createBySuccess(vehicles); } @Override public ServerResponse searchExam(Campus campus) { List<HashMap<String,Object>> allData=new ArrayList<>(); List<SubjectStudent> subjectStudents = subjectStudentMapper.searchExam(campus.getId()); for(int i =0;i<subjectStudents.size();i++){ Student student = studentMapper.selectByPrimaryKey(subjectStudents.get(i).getStudentId()); Subject subject = subjectMapper.selectByPrimaryKey(subjectStudents.get(i).getSubjectId()); HashMap<String,Object> data=new HashMap<>(); data.put("student",student); data.put("subjectStudent",subjectStudents.get(i)); data.put("subject",subject); allData.add(data); } return ServerResponse.createBySuccess(allData); } @Override public ServerResponse deleteCampus(Integer id) { int count = campusMapper.deleteByPrimaryKey(id); if(count==1) return ServerResponse.createBySuccessMessage("删除成功"); return ServerResponse.createByErrorMessage("删除失败"); } @Override public ServerResponse addCampus(Campus campus) { int count = campusMapper.insert(campus); if(count ==1){ return ServerResponse.createBySuccessMessage("增加成功"); } return ServerResponse.createByErrorMessage("增加失败"); } @Override public ServerResponse reviseCampus(Campus campus) { int count = campusMapper.updateByPrimaryKeySelective(campus); if(count==1) return ServerResponse.createBySuccessMessage("修改成功"); return ServerResponse.createByErrorMessage("修改失败"); } @Override public Integer allCount() { return campusMapper.selectAllCount(); } @Override public Campus findById(Integer campusId) { return campusMapper.selectByPrimaryKey(campusId); } }
package com.jinns.optimize.jvm.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; @RestController @Slf4j @RequestMapping("/jvm") public class JvmController { @GetMapping("/test") public String test(@RequestParam("id")String id ,@RequestParam("name")String name){ return "id是: "+id+" name是 "+name; } }
package com.test; import java.util.HashSet; import java.util.Set; import com.test.base.Solution; /** * 官方给定的answer, 比较人性化的一个方案,而且效率高 * 解题思路: * 1,将第一段"较长的段落",加入set,并计算出当前最大值 * 2,往下遍历,若有遇到相同的,则将之前的抛弃掉,并抛出set; * * 算法复杂度: * n*O(log(n)) * * @author YLine * * 2018年7月19日 下午3:05:55 */ public class SolutionB implements Solution { @Override public int lengthOfLongestSubstring(String s) { int length = s.length(); Set<Character> set = new HashSet<>(); int ans = 0, i = 0, j = 0; while (i < length && j < length) { // try to extend the range [i, j] if (!set.contains(s.charAt(j))) { set.add(s.charAt(j++)); ans = Math.max(ans, j - i); } else { set.remove(s.charAt(i++)); } } return ans; } }
/* * Merge HRIS API * The unified API for building rich integrations with multiple HR Information System platforms. * * The version of the OpenAPI document: 1.0 * Contact: hello@merge.dev * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package merge_hris_client.model; import com.google.gson.annotations.SerializedName; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for EmploymentTypeEnum */ public class EmploymentTypeEnumTest { /** * Model tests for EmploymentTypeEnum */ @Test public void testEmploymentTypeEnum() { // TODO: test EmploymentTypeEnum } }
package test.mytatis.zsl.com.dao; import test.mytatis.zsl.com.entity.User; public interface UserDao { User queryUserById(Integer id); User queryUserByName(String name); }
import com.offcn.pojo.TbItem; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.solr.core.SolrTemplate; import org.springframework.data.solr.core.query.Criteria; import org.springframework.data.solr.core.query.Query; import org.springframework.data.solr.core.query.SimpleQuery; import org.springframework.data.solr.core.query.result.ScoredPage; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * @Author CX * @Date 2020/2/12 20:51 * @Version 1.0 * @Description: * solr也相当于一个数据库,将数据存储solr数据库中,然后进行搜索, * 搜索时他会根据中文的常用关键词进行搜索 * 增删改要进行事务的提交(commit) * **/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring-solr.xml") public class TestTemplate { /*操作solr的对象*/ @Autowired private SolrTemplate solrTemplate; /* 测试向solr数据库中的添加 相当于数据库的添加 单个对象的添加 */ @Test public void testAdd(){ TbItem item=new TbItem(); item.setId(3L); item.setBrand("小米"); item.setCategory("手机pluse"); item.setGoodsId(1L); item.setSeller("小米1号专卖店"); item.setTitle("红米Mate9"); item.setPrice(new BigDecimal(2200)); solrTemplate.saveBean(item); //调用添加方法进行添加 solrTemplate.commit(); //事务的提交 } /* * 主键查询 * */ @Test public void testFindOne(){ //使用对象调用查询方法,参数1:查询条件,参数2:传入要查询的实体的字节码文件对象 TbItem item = solrTemplate.getById("3", TbItem.class); System.out.println(item.getTitle()); } /* * 主键删除 * */ @Test public void testDelete(){ solrTemplate.deleteById("3"); solrTemplate.commit(); } /* * 分页查询+批量添加(直接添加一个存啦多个对象的集合) * */ @Test public void testAddList(){ List<TbItem> itemList=new ArrayList<>(); for (int i=0;i<100;i++){ TbItem item=new TbItem(); item.setId(Long.valueOf(i)); item.setBrand("小米"); item.setCategory("手机pluse"); item.setGoodsId(1L); item.setSeller("小米1号专卖店"); item.setTitle("红米Mate9"); item.setPrice(new BigDecimal(2200)); itemList.add(item); } solrTemplate.saveBeans(itemList); solrTemplate.commit(); } @Test public void testPageQuery(){ //创建查询对象:*:* 是对所有的数据进行操作 Query query=new SimpleQuery("*:*"); query.setOffset(0); //分页开始的索引 query.setRows(10); //分页每页的数据量 //得到分页对象,这里面除啦数据外,还有分页所需的内容:传入的是分页的条件,和TbItem的字节码文件对象 ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); //从分页对象中取出数据,此数据是分页后的数据展示 List<TbItem> list = page.getContent(); for (TbItem item:list){ System.out.println(item.getTitle()); } } /* * 条件查询 * 将查询的条件封装进Criteria对象 * */ @Test public void testPageQueryMutil(){ //查询条件对象 Query query=new SimpleQuery("*:*"); //封装查询条件的条件对象 //条件为item_title字段值中含有9 Criteria criteria=new Criteria("item_title").contains("9"); //为查询对象中添加条件对象 query.addCriteria(criteria); //排序对象 Sort sort=new Sort(Sort.Direction.DESC,"item_price"); query.addSort(sort); //加啦查询条件,进行分页查询 query.setOffset(0); query.setRows(10); ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); List<TbItem> content = page.getContent(); for (TbItem item:content){ System.out.println(item.getTitle()); } } /* * 全部删除 * * */ @Test public void testDeleteAll(){ Query query =new SimpleQuery("*:*"); solrTemplate.delete(query); solrTemplate.commit(); } }
/* * Merge HRIS API * The unified API for building rich integrations with multiple HR Information System platforms. * * The version of the OpenAPI document: 1.0 * Contact: hello@merge.dev * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package merge_hris_client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import merge_hris_client.model.RemoteData; import merge_hris_client.model.RunStateEnum; import merge_hris_client.model.RunTypeEnum; import org.threeten.bp.OffsetDateTime; /** * # The PayrollRun Object ### Description The &#x60;PayrollRun&#x60; object is used to represent a payroll run. ### Usage Example Fetch from the &#x60;LIST PayrollRuns&#x60; endpoint and filter by &#x60;ID&#x60; to show all payroll runs. */ @ApiModel(description = "# The PayrollRun Object ### Description The `PayrollRun` object is used to represent a payroll run. ### Usage Example Fetch from the `LIST PayrollRuns` endpoint and filter by `ID` to show all payroll runs.") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-06-09T12:47:41.903246-07:00[America/Los_Angeles]") public class PayrollRun { public static final String SERIALIZED_NAME_ID = "id"; @SerializedName(SERIALIZED_NAME_ID) private UUID id; public static final String SERIALIZED_NAME_REMOTE_ID = "remote_id"; @SerializedName(SERIALIZED_NAME_REMOTE_ID) private String remoteId; public static final String SERIALIZED_NAME_RUN_STATE = "run_state"; @SerializedName(SERIALIZED_NAME_RUN_STATE) private RunStateEnum runState; public static final String SERIALIZED_NAME_RUN_TYPE = "run_type"; @SerializedName(SERIALIZED_NAME_RUN_TYPE) private RunTypeEnum runType; public static final String SERIALIZED_NAME_START_DATE = "start_date"; @SerializedName(SERIALIZED_NAME_START_DATE) private OffsetDateTime startDate; public static final String SERIALIZED_NAME_END_DATE = "end_date"; @SerializedName(SERIALIZED_NAME_END_DATE) private OffsetDateTime endDate; public static final String SERIALIZED_NAME_CHECK_DATE = "check_date"; @SerializedName(SERIALIZED_NAME_CHECK_DATE) private OffsetDateTime checkDate; public static final String SERIALIZED_NAME_REMOTE_DATA = "remote_data"; @SerializedName(SERIALIZED_NAME_REMOTE_DATA) private List<RemoteData> remoteData = null; /** * Get id * @return id **/ @javax.annotation.Nullable @ApiModelProperty(example = "37336947-b3d4-4a4c-a310-ab6ab510e079", value = "") public UUID getId() { return id; } public PayrollRun remoteId(String remoteId) { this.remoteId = remoteId; return this; } /** * The third-party API ID of the matching object. * @return remoteId **/ @javax.annotation.Nullable @ApiModelProperty(example = "19202938", value = "The third-party API ID of the matching object.") public String getRemoteId() { return remoteId; } public void setRemoteId(String remoteId) { this.remoteId = remoteId; } public PayrollRun runState(RunStateEnum runState) { this.runState = runState; return this; } /** * The state of the payroll run * @return runState **/ @javax.annotation.Nullable @ApiModelProperty(example = "PAID", value = "The state of the payroll run") public RunStateEnum getRunState() { return runState; } public void setRunState(RunStateEnum runState) { this.runState = runState; } public PayrollRun runType(RunTypeEnum runType) { this.runType = runType; return this; } /** * The type of the payroll run * @return runType **/ @javax.annotation.Nullable @ApiModelProperty(example = "REGULAR", value = "The type of the payroll run") public RunTypeEnum getRunType() { return runType; } public void setRunType(RunTypeEnum runType) { this.runType = runType; } public PayrollRun startDate(OffsetDateTime startDate) { this.startDate = startDate; return this; } /** * The day and time the payroll run started. * @return startDate **/ @javax.annotation.Nullable @ApiModelProperty(value = "The day and time the payroll run started.") public OffsetDateTime getStartDate() { return startDate; } public void setStartDate(OffsetDateTime startDate) { this.startDate = startDate; } public PayrollRun endDate(OffsetDateTime endDate) { this.endDate = endDate; return this; } /** * The day and time the payroll run ended. * @return endDate **/ @javax.annotation.Nullable @ApiModelProperty(value = "The day and time the payroll run ended.") public OffsetDateTime getEndDate() { return endDate; } public void setEndDate(OffsetDateTime endDate) { this.endDate = endDate; } public PayrollRun checkDate(OffsetDateTime checkDate) { this.checkDate = checkDate; return this; } /** * The day and time the payroll run was checked. * @return checkDate **/ @javax.annotation.Nullable @ApiModelProperty(value = "The day and time the payroll run was checked.") public OffsetDateTime getCheckDate() { return checkDate; } public void setCheckDate(OffsetDateTime checkDate) { this.checkDate = checkDate; } /** * Get remoteData * @return remoteData **/ @javax.annotation.Nullable @ApiModelProperty(example = "[{\"path\":\"/payroll\",\"data\":[\"Varies by platform\"]}]", value = "") public List<RemoteData> getRemoteData() { return remoteData; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PayrollRun payrollRun = (PayrollRun) o; return Objects.equals(this.id, payrollRun.id) && Objects.equals(this.remoteId, payrollRun.remoteId) && Objects.equals(this.runState, payrollRun.runState) && Objects.equals(this.runType, payrollRun.runType) && Objects.equals(this.startDate, payrollRun.startDate) && Objects.equals(this.endDate, payrollRun.endDate) && Objects.equals(this.checkDate, payrollRun.checkDate) && Objects.equals(this.remoteData, payrollRun.remoteData); } @Override public int hashCode() { return Objects.hash(id, remoteId, runState, runType, startDate, endDate, checkDate, remoteData); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PayrollRun {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" remoteId: ").append(toIndentedString(remoteId)).append("\n"); sb.append(" runState: ").append(toIndentedString(runState)).append("\n"); sb.append(" runType: ").append(toIndentedString(runType)).append("\n"); sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); sb.append(" checkDate: ").append(toIndentedString(checkDate)).append("\n"); sb.append(" remoteData: ").append(toIndentedString(remoteData)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.company; import java.text.DecimalFormat; public class HighSchool extends SchoolClass { @Override public Double chargeFees(Student student) { DecimalFormat decimalFormat = new DecimalFormat("#.##"); if (student.getGrade().toString().equals("GRADE9")) { fee = 100 * 2.00; } else if (student.getGrade().toString().equals("GRADE10")) { fee = (100 * 2.00) + (100 * 2.00) * 0.45; } else if (student.getGrade().toString().equals("GRADE11")) { fee = ((100 * 2.00) + (100 * 2.00) * 0.45) + (((100 * 2.00) + (100 * 2.00) * 0.45) * 0.45); } else if (student.getGrade().toString().equals("GRADE12")) { fee = (((100 * 2.00) + (100 * 2.00) * 0.45) + (((100 * 2.00) + (100 * 2.00) * 0.45) * 0.45)) + (((100 * 2.00) + (100 * 2.00) * 0.45) + (((100 * 2.00) + (100 * 2.00) * 0.45) * 0.45)) * 0.45; } return Double.valueOf(decimalFormat.format(fee)); } }
/* * @(#) DbsqlInfo.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.dbsqlinfo; import com.esum.wp.ims.dbsqlinfo.base.BaseDbsqlInfo; /** * * @author heowon@esumtech.com * @version $Revision: 1.2 $ $Date: 2009/01/15 09:23:12 $ */ public class DbsqlInfo extends BaseDbsqlInfo { private static final long serialVersionUID = 1L; // DataBase Flag private String dbType; // for paging private Integer currentPage; private Integer itemCountPerPage; private Integer totalCount; private Integer minIndex; private Integer maxIndex; public Integer getMinIndex() { return minIndex; } public void setMinIndex(Integer minIndex) { this.minIndex = minIndex; } public Integer getMaxIndex() { return maxIndex; } public void setMaxIndex(Integer maxIndex) { this.maxIndex = maxIndex; } private String mode; private Integer index; private String formName; private String fieldName; private java.util.List dbsqlInfoDetailList = null; public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getFormName() { return formName; } public void setFormName(String formName) { this.formName = formName; } public java.util.List getDbsqlInfoDetailList() { return dbsqlInfoDetailList; } public void setDbsqlInfoDetailList(java.util.List dbsqlInfoDetailList) { this.dbsqlInfoDetailList = dbsqlInfoDetailList; } public Integer getIndex() { return index; } public void setIndex(Integer index) { this.index = index; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } /*[CONSTRUCTOR MARKER BEGIN]*/ public DbsqlInfo () { super(); } /** * Constructor for primary key */ public DbsqlInfo (java.lang.String dbsqlId) { super(dbsqlId); } /*[CONSTRUCTOR MARKER END]*/ protected void initialize () { super.initialize(); } /** * @return Returns the currentPage. */ public Integer getCurrentPage() { return currentPage; } /** * @param currentPage The currentPage to set. */ public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } /** * @return Returns the itemCountPerPage. */ public Integer getItemCountPerPage() { return itemCountPerPage; } /** * @param itemCountPerPage The itemCountPerPage to set. */ public void setItemCountPerPage(Integer itemCountPerPage) { this.itemCountPerPage = itemCountPerPage; } /** * @return Returns the totalItemCount. */ public Integer getTotalCount() { return totalCount; } /** * @param totalItemCount The totalItemCount to set. */ public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public String getDbType() { return dbType; } public void setDbType(String dbType) { this.dbType = dbType; } }
package com.izasoft.jcart.security; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.izasoft.jcart.JCartException; import com.izasoft.jcart.domain.Permission; import com.izasoft.jcart.domain.Role; import com.izasoft.jcart.domain.User; import com.izasoft.jcart.repository.PermissionRepository; import com.izasoft.jcart.repository.RoleRepository; import com.izasoft.jcart.repository.UserRepository; import com.izasoft.jcart.repositoryService.PermissionService; @Service @Transactional public class SecurityService { @Autowired UserRepository userRepository; @Autowired PermissionRepository permissionRepository; @Autowired RoleRepository roleRepository; @Autowired PermissionService permissionService; public User findUserByEmail(String email) { return userRepository.findByEmail(email); } public String resetPassword(String email) { // TODO Auto-generated method stub return null; } public boolean verifyPasswordResetToken(String email, String token) { // TODO Auto-generated method stub return false; } public void updatePassword(String email, String token, String encodedPwd) { // TODO Auto-generated method stub } public List<Permission> getAllPermissions(){ return permissionRepository.findAll(); } public List<Role> getAllRoles(){ return roleRepository.findAll(); } public Role getRoleByName(String name) { return roleRepository.findByName(name); } public Role createRole(Role role) { Role roleByName = getRoleByName(role.getName()); System.out.println("Create Role Service"); if(roleByName != null) { throw new JCartException("Role "+role.getName()+" already exist"); } List<Permission> persistedPermission = new ArrayList<Permission>(); List<Permission> permissions = role.getPermissions(); if(permissions !=null) { for(Permission permission: permissions) { if(permission.getId() != null) { Permission p = permissionService.findPermission(permission.getId()); persistedPermission.add(p); } } } role.setPermissions(persistedPermission); return roleRepository.save(role); } public Role updateRole(Role role) { Role persistedRole = getRoleById(role.getId()); if(persistedRole == null) { throw new JCartException("Role "+role.getId()+" doesn't exist"); } persistedRole.setDescription(role.getDescription()); List<Permission> updatedPermissions = new ArrayList<Permission>(); List<Permission> permissions = role.getPermissions(); if(permissions != null) { for(Permission permission: permissions) { if(permission.getId()!=null) { updatedPermissions.add(permissionService.findPermission(permission.getId())); } } } persistedRole.setPermissions(updatedPermissions); return roleRepository.save(persistedRole); } public Role getRoleById(Integer id) { return this.roleRepository.findById(id).orElse(null); } }
package com.bayamp.arrays.programs; public class ReverseAnArray { public static void main(String[] args) { long[] arr1={-25896, -3560, -124, 1, 387, 4700, 56420 }; long[] arr3 = reverseArray(arr1); for(int a=0;a<arr3.length;a++){ System.out.print("\n"+arr3[a]); } } public static long[] reverseArray(long[] arr2){ for(int i=0;i<arr2.length/2;i++){ long temp=arr2[i]; arr2[i]=arr2[arr2.length-1-i]; arr2[arr2.length-1-i]=temp; } return arr2; } }
package dao; import models.Product; import org.sql2o.Connection; import org.sql2o.Sql2o; import org.sql2o.Sql2oException; import java.util.List; public class Sql2oProductDao implements ProductDao { private final Sql2o sql2o; public Sql2oProductDao(Sql2o sql2o) { this.sql2o = sql2o; } @Override public void add(Product product) { String sql = "INSERT INTO products (name) VALUES (:name);"; try (Connection conn = sql2o.open()) { int id = (int) conn.createQuery(sql, true) .bind(product) .executeUpdate() .getKey(); product.setId(id); } catch (Sql2oException ex) { System.out.println(ex); } } @Override public List<Product> getAll() { String sql = "SELECT * FROM products;"; try (Connection con = sql2o.open()) { return con.createQuery(sql) .executeAndFetch(Product.class); } } @Override public Product findById(int id) { String sql = "SELECT * FROM products WHERE id = :id ;"; try (Connection con = sql2o.open()) { return con.createQuery(sql) .addParameter("id", id) .executeAndFetchFirst(Product.class); } } @Override public void update(int id, String name) { String sql = "UPDATE products SET name = :name WHERE id = :id; "; try (Connection con = sql2o.open()) { con.createQuery(sql) .addParameter("name", name) .addParameter("id", id) .executeUpdate(); } } @Override public void deleteById(int id) { String sql = "DELETE FROM products WHERE id = :id ;"; try (Connection con = sql2o.open()) { con.createQuery(sql) .addParameter("id", id) .executeUpdate(); } } @Override public void clearAll() { String sql = "DELETE FROM products;"; try (Connection con = sql2o.open()) { con.createQuery(sql) .executeUpdate(); } } }
package ObjMarker; public class Marker { float length=10; float width=15; String color="red"; void write() { System.out.println("hello"); } public static void main (String args[]) { Marker m=new Marker(); float f=m.width; float k=m.length; String g=m.color; m.write(); System.out.println("f"); } }
package com.example.selfhelpcity.bean.db; import io.objectbox.annotation.Entity; import io.objectbox.annotation.Id; import lombok.Data; @Data @Entity public class CommuityBean { @Id private long id; /** * fy_id : 1 * user_id : 1 * title : 环境优美安静 * zujin : 1800.0 * address : 湖南长沙 * huxing : 一室一厅 * mianji : 48.0 * zhuangxiu : 精装修 * jianjie : 湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅湖南长沙一室一厅 * fbTime : 1574167250000 * picture : fang1.jpg */ private int fyId; private int userId; private String title; private double zujin; private String address; private String huxing; private double mianji; private String zhuangxiu; private String jianjie; private long fbTime; private String picture; private boolean isCollection; }
package com.yea.core.loadbalancer; import java.util.Collection; /** * This interface allows for filtering the configured or dynamically obtained * List of candidate servers with desirable characteristics. * * @author stonse * * @param <T> */ public interface INodeListFilter<T extends BalancingNode> { public Collection<T> getFilteredListOfNodes(Collection<T> nodes); }
package co.edu.poli.sistemasdistribuidos; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Optional; /** * Clase que recibe y procesa las peticiones del cliente */ public class Servidor { private static final String RUTA_ARCHIVO = "./datos.txt"; private static void crearCuenta(Mensaje mensaje) throws IOException { // Concatenar mensaje separado por comas (,) String linea = mensaje.cuenta + "," + mensaje.valor + "\n"; // Abrir el archivo para agregar línea try (Writer writer = new FileWriter(RUTA_ARCHIVO, true)) { // agregar línea writer.write(linea); } } private static double consultarCuenta(String cuenta) throws IOException { // Abrir el archivo para leerlo línea a línea try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(RUTA_ARCHIVO)))) { Optional<Double> valor = reader.lines() // separar cada línea por la coma .map(linea -> linea.split(",")) // verificar que haya 2 elementos y filtrar por la cuenta .filter(elementos -> elementos.length == 2 && elementos[0].equals(cuenta)) // tomar el valor (segunda posición) .map(elementos -> elementos[1]) // convertir el valor a Double .map(Double::parseDouble) // tomar la primera coincidencia .findFirst(); // si se encontró if (valor.isPresent()) { // retornar el valor return valor.get(); } } catch (FileNotFoundException fnfe) { System.err.println(fnfe.getMessage()); } throw new RuntimeException("cuenta no encontrada"); } public static void main(String[] args) throws IOException { // Escuchar peticiones en el puerto 1234 try (ServerSocket serverSocket = new ServerSocket(1234)) { System.out.println("Servidor escuchando en el puerto: " + serverSocket.getLocalPort()); // Recibir conexiones desde el cliente indefinidamente while (true) { // Esperar conexión del cliente try (Socket clientSocket = serverSocket.accept(); // Convertir el stream de datos de entrada a un BufferedReader para poder leer línea a línea BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Salida para escribir respuesta como string BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) { System.out.println("Conexión recibida desde: " + clientSocket.getInetAddress()); // Leer línea del mensaje de entrada String linea = reader.readLine(); System.out.println("Mensaje: " + linea); try { // Convertir línea a tipo Mensaje Mensaje mensaje = Mensaje.decode(linea); if (mensaje.tipo == Mensaje.Tipo.CrearCuenta) { // Guardar cuenta en el archivo crearCuenta(mensaje); writer.write("OK"); } else if (mensaje.tipo == Mensaje.Tipo.ConsultarCuenta) { double valor = consultarCuenta(mensaje.cuenta); writer.write(String.valueOf(valor)); } } catch (RuntimeException rte) { System.err.println(rte.getMessage()); writer.write("NO-OK"); } // Terminar respuesta escribiendo una nueva línea writer.newLine(); System.out.println("Respuesta enviada"); } } } } }
package com.lrms.bo.impl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.lrms.bo.PatientFecalysisBo; import com.lrms.dao.PatientFecalysisDao; import com.lrms.model.PatientFecalysis; /** * * @author dward * */ @Service public class PatientFecalysisBoImpl implements PatientFecalysisBo{ private final static Logger logger = Logger.getLogger(PatientFecalysisBoImpl.class); @Autowired PatientFecalysisDao patientFecalysisDao; public void setPatientFecalysisDao(PatientFecalysisDao patientFecalysisDao){ this.patientFecalysisDao = patientFecalysisDao; } @Override @Transactional public boolean saveOrUpdate(PatientFecalysis entity) { logger.info("Save: " + entity.toString()); return patientFecalysisDao.saveOrUpdate(entity); } @Override public PatientFecalysis findByPatientLabExamId(int id) { return patientFecalysisDao.findByPatientLabExamId(id); } }
package pkgb; public class MyRuntimeException extends RuntimeException { private static final long serialVersionUID = 1L; public MyRuntimeException() { super("MyRuntimeException's message"); } }
import javax.swing.table.DefaultTableModel; import java.util.Vector; public class SessionTableModel extends DefaultTableModel { public void addSessionRow(Session s) { Vector<Object> entity = new Vector<>(2); entity.addElement(s.getSessionName()); entity.addElement(s.getSessionId()); this.addRow(entity); } @Override public boolean isCellEditable(int i, int i1) { return false; } }
/* * Generated by the Jasper component of Apache Tomcat * Version: jetty/9.3.7.v20160115 * Generated at: 2020-03-23 09:50:49 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.view; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class list_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent, org.apache.jasper.runtime.JspSourceImports { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(4); _jspx_dependants.put("file:/E:/repository/org/apache/taglibs/taglibs-standard-impl/1.2.5/taglibs-standard-impl-1.2.5.jar", Long.valueOf(1582099104013L)); _jspx_dependants.put("jar:file:/E:/repository/jstl/jstl/1.2/jstl-1.2.jar!/META-INF/fmt.tld", Long.valueOf(1153356282000L)); _jspx_dependants.put("file:/E:/repository/jstl/jstl/1.2/jstl-1.2.jar", Long.valueOf(1582098661643L)); _jspx_dependants.put("jar:file:/E:/repository/org/apache/taglibs/taglibs-standard-impl/1.2.5/taglibs-standard-impl-1.2.5.jar!/META-INF/c.tld", Long.valueOf(1425949870000L)); } private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fif_0026_005ftest; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.release(); _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.release(); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.release(); } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final java.lang.String _jspx_method = request.getMethod(); if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD"); return; } final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta charset=\"UTF-8\">\r\n"); out.write("<title>Insert title here</title>\r\n"); out.write("</head>\r\n"); out.write("<link rel=\"stylesheet\" href=\"/css/bootstrap.css\">\r\n"); out.write("<script type=\"text/javascript\" src=\"/js/jquery-3.2.1.js\"></script>\r\n"); out.write("<body>\r\n"); out.write("\t<table class=\"table\">\r\n"); out.write("\t\t<tr>\r\n"); out.write("\t\t\t<td colspan=\"100\">\r\n"); out.write("\t\t\t\t<input type=\"button\" class=\"btn btn-info\" value=\"查询影片\" onclick=\"query()\">\r\n"); out.write("\t\t\t\t<input type=\"button\" class=\"btn btn-success\" value=\"添加影片\">\r\n"); out.write("\t\t\t\t<input type=\"button\" class=\"btn btn-danger\" value=\"删除影片\" onclick=\"del()\">\r\n"); out.write("\t\t\t\t<form id=\"queryForm\" action=\"/movie/list\" method=\"post\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"name\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.name}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"director\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.director}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"legend\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.legend}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"startTime\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.startTime}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"endTime\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.endTime}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"lowerPrice\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.lowerPrice}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"upperPrice\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.upperPrice}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"lowerLength\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.lowerLength}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"upperLength\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query.upperLength}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"pageNum\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageNum}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"pageSize\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageSize}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"condition\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${condition}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t\t<input type=\"hidden\" name=\"order\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${order}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t</form>\r\n"); out.write("\t\t\t</td>\r\n"); out.write("\t\t</tr>\r\n"); out.write("\t\t<tr>\r\n"); out.write("\t\t\t<th>\r\n"); out.write("\t\t\t\t<input type=\"checkbox\" id=\"selectAll\">\r\n"); out.write("\t\t\t</th>\r\n"); out.write("\t\t\t<th>影片名</th>\r\n"); out.write("\t\t\t<th>导演</th>\r\n"); out.write("\t\t\t<th>票价</th>\r\n"); out.write("\t\t\t<th>\r\n"); out.write("\t\t\t\t上映时间\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"^\" onclick=\"orderMovie('showDate')\">\r\n"); out.write("\t\t\t</th>\r\n"); out.write("\t\t\t<th>\r\n"); out.write("\t\t\t\t时长\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"^\" onclick=\"orderMovie('timeLength')\">\r\n"); out.write("\t\t\t</th>\r\n"); out.write("\t\t\t<th>类型</th>\r\n"); out.write("\t\t\t<th>\r\n"); out.write("\t\t\t\t年代\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"^\" onclick=\"orderMovie('legend')\">\r\n"); out.write("\t\t\t</th>\r\n"); out.write("\t\t\t<th>区域</th>\r\n"); out.write("\t\t\t<th>状态</th>\r\n"); out.write("\t\t\t<th>操作</th>\r\n"); out.write("\t\t</tr>\r\n"); out.write("\t\t"); if (_jspx_meth_c_005fforEach_005f0(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t<tr>\r\n"); out.write("\t\t\t<td colspan=\"100\">\r\n"); out.write("\t\t\t\t第"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.pageNum}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write('/'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.pages}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write('页'); out.write(','); out.write('共'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.total}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("条\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"首页\" class=\"btn btn-info\" onclick=\"page(1)\">\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"上一页\" class=\"btn btn-info\" onclick=\"page("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.prePage}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write(")\">\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"下一页\" class=\"btn btn-info\" onclick=\"page("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.nextPage}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write(")\">\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"尾页\" class=\"btn btn-info\" onclick=\"page("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page.pages}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write(")\">\r\n"); out.write("\t\t\t\t前往\r\n"); out.write("\t\t\t\t<input type=\"text\" id=\"pageNum\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageNum}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\">\r\n"); out.write("\t\t\t\t页\r\n"); out.write("\t\t\t\t<select id=\"pageSize\">\r\n"); out.write("\t\t\t\t\t<option value=\"3\" \r\n"); out.write("\t\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f4(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t\t\t\t>3条/页</option>\r\n"); out.write("\t\t\t\t\t<option value=\"5\"\r\n"); out.write("\t\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f5(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t\t\t\t>5条/页</option>\r\n"); out.write("\t\t\t\t\t<option value=\"8\"\r\n"); out.write("\t\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f6(_jspx_page_context)) return; out.write("\r\n"); out.write("\t\t\t\t\t>8条/页</option>\r\n"); out.write("\t\t\t\t</select>\r\n"); out.write("\t\t\t\t<input type=\"button\" value=\"前往\" class=\"btn btn-info\" onclick=\"page(0)\">\r\n"); out.write("\t\t\t</td>\r\n"); out.write("\t\t</tr>\r\n"); out.write("\t</table>\r\n"); out.write("</body>\r\n"); out.write("<script type=\"text/javascript\">\r\n"); out.write("\tfunction page(pageNum){\r\n"); out.write("\t\tif(pageNum){\r\n"); out.write("\t\t\t$(\":hidden[name='pageNum']\").val(pageNum);\r\n"); out.write("\t\t}else{\r\n"); out.write("\t\t\tvar num = $(\"#pageNum\").val();\r\n"); out.write("\t\t\tif(!isNaN(num)){\r\n"); out.write("\t\t\t\t$(\":hidden[name='pageNum']\").val(num);\r\n"); out.write("\t\t\t}else{\r\n"); out.write("\t\t\t\t$(\":hidden[name='pageNum']\").val(1);\r\n"); out.write("\t\t\t}\r\n"); out.write("\t\t}\r\n"); out.write("\t\t$(\":hidden[name='pageSize']\").val($(\"#pageSize\").val());\r\n"); out.write("\t\t$(\"#queryForm\").submit();\r\n"); out.write("\t}\r\n"); out.write("\tfunction convertState(id){\r\n"); out.write("\t\t$.ajax({\r\n"); out.write("\t\t\turl:\"/movie/convert\",\r\n"); out.write("\t\t\tdata:{\"id\":id},\r\n"); out.write("\t\t\tsuccess:function(success){\r\n"); out.write("\t\t\t\tif(success){\r\n"); out.write("\t\t\t\t\tlocation.reload();\r\n"); out.write("\t\t\t\t}else{\r\n"); out.write("\t\t\t\t\talert(\"设置失败!\");\r\n"); out.write("\t\t\t\t}\r\n"); out.write("\t\t\t}\r\n"); out.write("\t\t})\r\n"); out.write("\t}\r\n"); out.write("\t$(\"#selectAll\").click(function(){\r\n"); out.write("\t\t$(\":checkbox.movie\").prop(\"checked\",this.checked);\r\n"); out.write("\t})\r\n"); out.write("\tfunction del(){\r\n"); out.write("\t\tif($(\":checkbox.movie:checked\").length==0){\r\n"); out.write("\t\t\talert(\"请选择要删除的电影!\");\r\n"); out.write("\t\t\treturn;\r\n"); out.write("\t\t}\r\n"); out.write("\t\tif(confirm(\"确定要删除选中的电影吗?\")){\r\n"); out.write("\t\t\tvar ids = $(\":checkbox.movie:checked\").map(function(){\r\n"); out.write("\t\t\t\treturn $(this).val();\r\n"); out.write("\t\t\t}).get().join();\r\n"); out.write("\t\t\t$.ajax({\r\n"); out.write("\t\t\t\turl:\"/movie/delete\",\r\n"); out.write("\t\t\t\tdata:{\"ids\":ids},\r\n"); out.write("\t\t\t\tsuccess:function(success){\r\n"); out.write("\t\t\t\t\tif(success){\r\n"); out.write("\t\t\t\t\t\tlocation.reload();\r\n"); out.write("\t\t\t\t\t}else{\r\n"); out.write("\t\t\t\t\t\talert(\"删除失败!\");\r\n"); out.write("\t\t\t\t\t}\r\n"); out.write("\t\t\t\t}\r\n"); out.write("\t\t\t})\r\n"); out.write("\t\t}\r\n"); out.write("\t}\r\n"); out.write("\tfunction query(){\r\n"); out.write("\t\tvar data = $(\"#queryForm\").serialize();\r\n"); out.write("\t\tlocation.href='/movie/query?'+data;\r\n"); out.write("\t}\r\n"); out.write("\tfunction orderMovie(condition){\r\n"); out.write("\t\t$(\":hidden[name='condition']\").val(condition);\r\n"); out.write("\t\tif($(\":hidden[name='order']\").val()=='asc'){\r\n"); out.write("\t\t\t$(\":hidden[name='order']\").val(\"desc\");\r\n"); out.write("\t\t}else if($(\":hidden[name='order']\").val()=='desc'){\r\n"); out.write("\t\t\t$(\":hidden[name='order']\").val(\"asc\");\r\n"); out.write("\t\t} \r\n"); out.write("\t\tpage(1);\r\n"); out.write("\t}\r\n"); out.write("</script>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_c_005fforEach_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f0.setParent(null); // /WEB-INF/view/list.jsp(61,2) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true expectedTypeName = java.lang.Object deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f0.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/view/list.jsp(61,2) '${requestScope.movieList}'",_jsp_getExpressionFactory().createValueExpression(_jspx_page_context.getELContext(),"${requestScope.movieList}",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/view/list.jsp(61,2) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fforEach_005f0.setVar("movie"); int[] _jspx_push_body_count_c_005fforEach_005f0 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f0 = _jspx_th_c_005fforEach_005f0.doStartTag(); if (_jspx_eval_c_005fforEach_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t<tr>\r\n"); out.write("\t\t\t\t<td>\r\n"); out.write("\t\t\t\t\t<input type=\"checkbox\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("\" class=\"movie\">\r\n"); out.write("\t\t\t\t</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.name}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.director}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.price}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>\r\n"); out.write("\t\t\t\t\t"); if (_jspx_meth_fmt_005fformatDate_005f0(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0)) return true; out.write("\r\n"); out.write("\t\t\t\t</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.timeLength}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.typeName}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.legend}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.area}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write("</td>\r\n"); out.write("\t\t\t\t<td>\r\n"); out.write("\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f0(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0)) return true; out.write("\r\n"); out.write("\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f1(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0)) return true; out.write("\r\n"); out.write("\t\t\t\t</td>\r\n"); out.write("\t\t\t\t<td>\r\n"); out.write("\t\t\t\t\t<input type=\"button\" value=\"详情\">\r\n"); out.write("\t\t\t\t\t<input type=\"button\" value=\"编辑\">\r\n"); out.write("\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f2(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0)) return true; out.write("\r\n"); out.write("\t\t\t\t\t"); if (_jspx_meth_c_005fif_005f3(_jspx_th_c_005fforEach_005f0, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f0)) return true; out.write("\r\n"); out.write("\t\t\t\t</td>\r\n"); out.write("\t\t\t</tr>\r\n"); out.write("\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f0[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f0.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f0.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f0); } return false; } private boolean _jspx_meth_fmt_005fformatDate_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:formatDate org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_005fformatDate_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class); _jspx_th_fmt_005fformatDate_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fformatDate_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0); // /WEB-INF/view/list.jsp(70,5) name = value type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.showDate}", java.util.Date.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); // /WEB-INF/view/list.jsp(70,5) name = pattern type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setPattern("yyyy-MM-dd"); int _jspx_eval_fmt_005fformatDate_005f0 = _jspx_th_fmt_005fformatDate_005f0.doStartTag(); if (_jspx_th_fmt_005fformatDate_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return true; } _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return false; } private boolean _jspx_meth_c_005fif_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0); // /WEB-INF/view/list.jsp(77,5) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.state==1}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag(); if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("正在热映"); int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); return false; } private boolean _jspx_meth_c_005fif_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f1 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0); // /WEB-INF/view/list.jsp(78,5) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.state==0}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f1 = _jspx_th_c_005fif_005f1.doStartTag(); if (_jspx_eval_c_005fif_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("已经下架"); int evalDoAfterBody = _jspx_th_c_005fif_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f1); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f1); return false; } private boolean _jspx_meth_c_005fif_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f2 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f2.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0); // /WEB-INF/view/list.jsp(83,5) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.state==1}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f2 = _jspx_th_c_005fif_005f2.doStartTag(); if (_jspx_eval_c_005fif_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t<input type=\"button\" value=\"下架\" onclick=\"convertState("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write(")\">\r\n"); out.write("\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fif_005f2.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f2); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f2); return false; } private boolean _jspx_meth_c_005fif_005f3(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f0, javax.servlet.jsp.PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f0) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f3 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f3.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f3.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f0); // /WEB-INF/view/list.jsp(86,5) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f3.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.state==0}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f3 = _jspx_th_c_005fif_005f3.doStartTag(); if (_jspx_eval_c_005fif_005f3 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n"); out.write("\t\t\t\t\t\t<input type=\"button\" value=\"上架\" onclick=\"convertState("); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${movie.id}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)); out.write(")\">\r\n"); out.write("\t\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fif_005f3.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f3); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f3); return false; } private boolean _jspx_meth_c_005fif_005f4(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f4 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f4.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f4.setParent(null); // /WEB-INF/view/list.jsp(104,6) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f4.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageSize==3}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f4 = _jspx_th_c_005fif_005f4.doStartTag(); if (_jspx_eval_c_005fif_005f4 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("selected=\"selected\""); int evalDoAfterBody = _jspx_th_c_005fif_005f4.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f4); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f4); return false; } private boolean _jspx_meth_c_005fif_005f5(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f5 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f5.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f5.setParent(null); // /WEB-INF/view/list.jsp(107,6) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f5.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageSize==5}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f5 = _jspx_th_c_005fif_005f5.doStartTag(); if (_jspx_eval_c_005fif_005f5 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("selected=\"selected\""); int evalDoAfterBody = _jspx_th_c_005fif_005f5.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f5); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f5); return false; } private boolean _jspx_meth_c_005fif_005f6(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.PageContext pageContext = _jspx_page_context; javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f6 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f6.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f6.setParent(null); // /WEB-INF/view/list.jsp(110,6) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f6.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageSize==8}", boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null)).booleanValue()); int _jspx_eval_c_005fif_005f6 = _jspx_th_c_005fif_005f6.doStartTag(); if (_jspx_eval_c_005fif_005f6 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("selected=\"selected\""); int evalDoAfterBody = _jspx_th_c_005fif_005f6.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f6); return true; } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f6); return false; } }
package com.gxtc.huchuan.im.ui; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.FileUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.LogUtil; import com.gxtc.commlibrary.utils.SpUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.commlibrary.utils.WindowUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.R; import com.gxtc.huchuan.bean.CircleBean; import com.gxtc.huchuan.bean.MergeMessageBean; import com.gxtc.huchuan.bean.RedPacketBean; import com.gxtc.huchuan.bean.event.EventClickBean; import com.gxtc.huchuan.bean.event.EventGroupBean; import com.gxtc.huchuan.bean.event.EventLoadBean; import com.gxtc.huchuan.bean.event.EventSelectFriendBean; import com.gxtc.huchuan.bean.event.EventSelectFriendForPostCardBean; import com.gxtc.huchuan.bean.event.EventSendRPBean; import com.gxtc.huchuan.bean.event.EventShareMessage; import com.gxtc.huchuan.bean.event.EventUnReadBean; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.dialog.CustomDayDialog; import com.gxtc.huchuan.dialog.ListDialog; import com.gxtc.huchuan.dialog.RedPacketOpenDialog; import com.gxtc.huchuan.handler.CircleShareHandler; import com.gxtc.huchuan.handler.QrcodeHandler; import com.gxtc.huchuan.helper.RongImHelper; import com.gxtc.huchuan.helper.RxTaskHelper; import com.gxtc.huchuan.helper.ShareHelper; import com.gxtc.huchuan.im.utilities.OptionsPopupDialog; import com.gxtc.huchuan.ui.circle.groupmember.AllGroupMemberActivity; import com.gxtc.huchuan.ui.circle.groupmember.GroupChatMembersActivity; import com.gxtc.huchuan.ui.circle.homePage.CircleMainActivity; import com.gxtc.huchuan.ui.deal.deal.fastDeal.FastDealActivity; import com.gxtc.huchuan.ui.im.merge.MergeHistoryMessage; import com.gxtc.huchuan.ui.im.postcard.PTMessage; import com.gxtc.huchuan.ui.im.redPacket.RPMessage; import com.gxtc.huchuan.ui.im.redPacket.RedPacketDetailedActivity; import com.gxtc.huchuan.ui.im.share.ShareMessage; import com.gxtc.huchuan.ui.im.system.ArticleMessage; import com.gxtc.huchuan.ui.im.system.CircleMessage; import com.gxtc.huchuan.ui.im.system.ClassMessage; import com.gxtc.huchuan.ui.im.system.DealMessage; import com.gxtc.huchuan.ui.im.system.MallMessage; import com.gxtc.huchuan.ui.im.system.MessagePresenter; import com.gxtc.huchuan.ui.im.system.SystemMessage; import com.gxtc.huchuan.ui.im.system.TradeInfoMessage; import com.gxtc.huchuan.ui.im.video.VideoMessage; import com.gxtc.huchuan.ui.message.AllGroupInfoMemberActivity; import com.gxtc.huchuan.ui.message.GroupInfoActivity; import com.gxtc.huchuan.ui.mine.personalhomepage.personalinfo.PersonalInfoActivity; import com.gxtc.huchuan.utils.AndroidBug5497Workaround; import com.gxtc.huchuan.utils.ClickUtil; import com.gxtc.huchuan.utils.DialogUtil; import com.gxtc.huchuan.utils.ImMessageUtils; import com.gxtc.huchuan.utils.RIMErrorCodeUtil; import com.gxtc.huchuan.utils.StringUtil; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.ui.PictureEditActivity; import com.yalantis.ucrop.util.FileUtils; import org.greenrobot.eventbus.Subscribe; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import cn.jzvd.JZMediaManager; import cn.jzvd.JZVideoPlayer; import im.collect.CollectMessage; import io.rong.imkit.RongIM; import io.rong.imkit.RongMessageItemLongClickActionManager; import io.rong.imkit.mention.IMentionedInputListener; import io.rong.imkit.mention.RongMentionManager; import io.rong.imkit.model.UIMessage; import io.rong.imkit.widget.provider.MessageItemLongClickAction; import io.rong.imlib.IRongCallback; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Message; import io.rong.imlib.model.MessageContent; import io.rong.imlib.model.UserInfo; import io.rong.message.FileMessage; import io.rong.message.ImageMessage; import io.rong.message.RecallNotificationMessage; import io.rong.message.TextMessage; import io.rong.message.VoiceMessage; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; /** http://blog.csdn.net/qq_19986309/article/details/50402476 * 融云会话界面 */ public class ConversationActivity extends BaseTitleActivity implements ConversationContract.View, View.OnClickListener{ public final static int REQUEST_SHARE_CONTENT = 0; //分享内容给好友 public final static int REQUEST_SHARE_RELAY = 1; //转发内容给好友 public final static int REQUEST_SHARE_CARD = 2; //分享个人名片 public final static int REQUEST_SHARE_COLLECT = 3; //分享收藏 public final static int REQUEST_SHARE_INVITE = 4; //分享课堂邀请 public final static int REQUEST_SHARE_IMAGE = 6; //分享编辑的图片 public final static int REQUEST_SHARE_SRC_IMAGE = 7; //分享图片 public final static int REQUEST_SHARE_VIDEO = 8; //分享视频 public final static int REQUEST_SHARE_MORE_RELAY = 9; //多聊天消息逐条转发 public final static int REQUEST_SHARE_MORE_MERGE_RELAY = 10; //多聊天消息合并转发 public static final int STATUE_INVATE_CARD = 5 ; //邀请卡 public static final int REQUEST_VIDEO = 101 ; //邀请卡 private final static int GROUP_TYPE_CIRCLE = 1; //圈子群聊 private final static int GROUP_TYPE_CUSTOM = 2; //自建群聊 private final static String CONVERSATIONACTIVITY = "ConversationActivity"; //首次进去群聊key private LinearLayout mUnReadLayout; private TextView mTvUnreadCircle; private int groupType = 0; private int groupId = 0; private int groupCount = 0; private int unreadMsgCount = 0; //未读圈子动态数 private String tradeType = "0"; private String mTargetId; private String mTargetIds; private String title; private String goodsId; private String roleType; //角色。0:普通用户,1:管理员,2:圈主 private String clickUserCode; private String editPicturePath; //编辑图片后的地址 private MyConversationFragment fragment; private AlertDialog exitDialog; private List<Message> selectMessage; //选中的消息 private Conversation.ConversationType mConversationType; private Message currMessage; private CircleBean bean; private CircleShareHandler mShareHandler; private ConversationContract.Presenter mPresenter; private AlertDialog mAlertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.conversation); AndroidBug5497Workaround.assistActivity(this); EventBusUtil.register(this); } /** http://blog.csdn.net/acerhphp/article/details/62889468 * JZVideoPlayer 内部的AudioManager会对Activity持有一个强引用,而AudioManager的生命周期比较长,导致这个Activity始终无法被回收 */ @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(new ContextWrapper(newBase) { @Override public Object getSystemService(String name) { if (Context.AUDIO_SERVICE.equals(name)){ return getApplicationContext().getSystemService(name); } return super.getSystemService(name); } }); } @Override public void initView() { /*从 intent 携带的数据里获取 targetId 和会话类型*/ Intent intent = getIntent(); mTargetId = intent.getData().getQueryParameter("targetId"); tradeType = intent.getData().getQueryParameter("tradeType"); if(mTargetId == null) return; mTargetIds = intent.getData().getQueryParameter("targetIds"); title = intent.getData().getQueryParameter("title"); getBaseHeadView().showTitle(title); goodsId = getIntent().getData().getQueryParameter("goodsId"); mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault())); initFragment(); initHeadTitle(); initRongIm(); } @Override public void initData() { goodsId = getIntent().getData().getQueryParameter("goodsId"); String userCode = UserManager.getInstance().getUserCode(); if (!TextUtils.isEmpty(goodsId) && !TextUtils.isEmpty(userCode) && !userCode.equals(mTargetId) && !"1".equals(tradeType.trim())) { //0:出售,1:求购(必选) getBaseHeadView().showHeadRightButton("发起交易",this); } mShareHandler = new CircleShareHandler(this); new ConversationPresenter(this, mTargetId, mConversationType); //获取群的信息 if(mConversationType == Conversation.ConversationType.GROUP) { boolean isFirstComeIntoGrounp = SpUtil.getBoolean(this,CONVERSATIONACTIVITY); //首次进入群聊(包括圈子) if(isFirstComeIntoGrounp){ mAlertDialog = DialogUtil.showNoticeDialog(this, true, "温馨提示", "为了保证用户体验,不能在群聊内发布带有第三方账号和二维码以及收徒招代理等广告,违反规则直接踢出群聊和撤回广告并封号处理!", new View.OnClickListener() { @Override public void onClick(View v) { mAlertDialog.dismiss(); } }); } //自建的群聊 if (mTargetId.contains("user")) { groupType = GROUP_TYPE_CUSTOM; //圈子的群聊 } else { groupType = GROUP_TYPE_CIRCLE; initUnReadMsg(); } SpUtil.putBoolean(this,CONVERSATIONACTIVITY,false); mPresenter.getCircleInfo(mTargetId); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.headBackButton: WindowUtil.closeInputMethod(ConversationActivity.this); if(exitCheckVideoMessage()){ showExitDialog(); return; } if(fragment != null && fragment.onBackPressed()){ return; } finish(); break; case R.id.headRightButton: gotoFastDeal(goodsId); break; case R.id.HeadRightImageButton: if(mConversationType == Conversation.ConversationType.PRIVATE){ PersonalInfoActivity.startActivity(this,mTargetId); } else if(mConversationType != Conversation.ConversationType.CUSTOMER_SERVICE) { if(bean != null && groupType == GROUP_TYPE_CIRCLE){ //群成员列表 Intent intent = new Intent(ConversationActivity.this, GroupChatMembersActivity.class); intent.putExtra("groupId",groupId); intent.putExtra("isMy",String.valueOf(bean.getIsMy())); intent.putExtra("count",groupCount); intent.putExtra(Constant.INTENT_DATA,mTargetId); startActivityForResult(intent,555); } if(groupType == GROUP_TYPE_CUSTOM){ GroupInfoActivity.startActivity(this,mTargetId,groupCount); } } break; } } @Override public void showCircleInfo(CircleBean bean) { groupCount = bean.getCount(); getBaseHeadView().showTitle(title + "(" + groupCount + ")"); //获取在群里的身份 是否有权执行禁言删除操作 mPresenter.getMemberTypeByChat(mTargetId); } //点击红包 @Override public void showRedPackInfo(RedPacketBean data) { if(data != null){ //如果是私聊 并且是自己点击红包 String userCoder = UserManager.getInstance().getUserCode(); if(data.getConversationType() == Conversation.ConversationType.PRIVATE && data.getUserCode().equals(userCoder)){ Intent intent = new Intent(this, RedPacketDetailedActivity.class); intent.putExtra(Constant.INTENT_DATA,data); startActivity(intent); return; } //没领取这个红包,打开弹窗 if(data.getIsSnatch() == 0){ showOpenDialog(this,data); //领取了红包,打开红包详情页面 }else{ Intent intent = new Intent(this, RedPacketDetailedActivity.class); intent.putExtra(Constant.INTENT_DATA,data); startActivity(intent); } } } private void showOpenDialog(Context context, RedPacketBean data){ RedPacketOpenDialog mOpenDialog = new RedPacketOpenDialog(context,data); mOpenDialog.show(); } @Override public void showMemberType(CircleBean bean) { if(bean.getRoleType() == null) return; bean.setIsMy(Integer.valueOf(bean.getRoleType())); groupId = bean.getGroupId(); this.bean = bean; roleType = bean.getRoleType(); unreadMsgCount = bean.getUnReadInfo(); showUnReadMsg(); } @Override public void showShutupResult(boolean isSuccessed,String msg , String errorCode, String error) { if(isSuccessed){ ToastUtil.showShort(this,msg); }else{ ToastUtil.showShort(this,error); } } @Override public void showRemoveResult(boolean isSuccessed, String errorCode, String error) { if(isSuccessed){ ToastUtil.showShort(this, "移除成员成功"); }else{ ToastUtil.showShort(this,error); } } //显示合并消息结果 @Override public void showMergeResult(boolean isSuccessed, String msg) { if(isSuccessed){ ToastUtil.showShort(this, getString(R.string.message_relay_isuccess)); }else{ ToastUtil.showShort(this, msg); } } //code 10261 不在该群 10278群解散或圈子解散 @Override public void showOutClear(String code, String msg) { String content = ""; if(Constant.GROUPCODE_OUT.equals(code)){ content = "你已不在此群聊"; } if(Constant.GROUPCODE_CLEAR.equals(code)){ if(groupType == GROUP_TYPE_CIRCLE){ content = "此圈子已解散"; }else{ content = "此群聊已解散"; } } mAlertDialog = DialogUtil.showDeportDialog(this, false, null, content, new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.tv_dialog_confirm) { removeMessage(); } mAlertDialog.dismiss(); } private void removeMessage() { RongIM.getInstance().removeConversation(mConversationType, mTargetId, new RongIMClient.ResultCallback<Boolean>() { @Override public void onSuccess(Boolean aBoolean) { if(aBoolean){ mAlertDialog.dismiss(); finish(); } } @Override public void onError(RongIMClient.ErrorCode errorCode) { mAlertDialog.dismiss(); ToastUtil.showShort(MyApplication.getInstance(), RIMErrorCodeUtil.handleErrorCode(errorCode)); } }); } }); } //发送小视频 @Subscribe public void onEvent(EventClickBean bean){ mPresenter.sendVideoMessage(this, (LocalMedia) bean.bean); } @Subscribe public void onEvent(EventLoadBean bean){ getBaseLoadingView().show(bean.isLoading); } @Subscribe public void onEvent(EventSendRPBean bean){ if(fragment.getRongExtension() != null) fragment.getRongExtension().collapseExtension(); } //退出群聊结束会话 @Subscribe(priority = 1) public void onEvent(EventGroupBean bean){ if(bean.isDelete) { finish(); } } @Override public void onBackPressed() { if (JZVideoPlayer.backPress()) { return; } if(fragment != null && fragment.onBackPressed()){ return; } if(exitCheckVideoMessage()){ showExitDialog(); return; } super.onBackPressed(); } private boolean exitCheckVideoMessage() { return mPresenter.getUploadMessagQueen() != null && mPresenter.getUploadMessagQueen().size() > 0; } @Override protected void onPause() { super.onPause(); JZVideoPlayer.releaseAllVideos(); //onDestroy方法在软键盘弹起后 直接调用finish()方法 会出现延迟好几秒调用的情况,所以释放资源放到这里来 if(isFinishing()){ //这里只对软键盘做处理,释放资源还是放到onDestroy方法里 RongIM.setConversationBehaviorListener(null); RongMentionManager.getInstance().setMentionedInputListener(null); LogUtil.i("onPause "); } } @Override protected void onDestroy() { super.onDestroy(); EventBusUtil.unregister(this); RxTaskHelper.getInstance().cancelTask(this); mPresenter.destroy(); mShareHandler.destroy(); MessagePresenter.INSTANCE.destroy(); EventBusUtil.post(new EventUnReadBean()); //更新未读消息数 JZMediaManager.instance().releaseMediaPlayer(); //释放视频资源 } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1000){ initRongIm(); } if (requestCode == 1001 && resultCode == RESULT_OK){ groupCount = data.getIntExtra("count",0);//当群聊的人数改变,在这里会重新设置 getBaseHeadView().showTitle(title + "(" + groupCount + ")"); } //退出圈子结束会话界面 if (requestCode == 555 && resultCode == RESULT_OK){ finish(); } if(requestCode == REQUEST_SHARE_CONTENT && resultCode == RESULT_OK){ EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA); String targetId = bean.targetId; Conversation.ConversationType type = bean.mType; mPresenter.shareMessage(currMessage, targetId, type); } //发送收藏 if(requestCode == REQUEST_SHARE_COLLECT && resultCode == RESULT_OK){ EventShareMessage bean = (EventShareMessage) data.getSerializableExtra(Constant.INTENT_DATA); mPresenter.sendCollectionMessage(bean,mTargetId,mConversationType); } //转发消息 if(requestCode == REQUEST_SHARE_RELAY && resultCode == RESULT_OK){ EventShareMessage bean = (EventShareMessage) data.getSerializableExtra(Constant.INTENT_DATA); mPresenter.relayMessage(currMessage.getContent(), (String) bean.mObject,bean.mType,bean.Liuyan); } //发送名片 if(requestCode == REQUEST_SHARE_CARD && resultCode == RESULT_OK){ EventSelectFriendForPostCardBean bean = data.getParcelableExtra(Constant.INTENT_DATA); mPresenter.sendRongIm(bean); } //发送文件 if(requestCode == Constant.requestCode.UPLOAD_FILE && resultCode == RESULT_OK){ Uri uri = data.getData(); sentFile(uri); } //编辑图片 if(requestCode == PictureEditActivity.REQUEST_CODE && resultCode == RESULT_OK){ editPicturePath = data.getStringExtra("data"); showEditPictureDialog(); } //分享编辑的图片 if(requestCode == REQUEST_SHARE_IMAGE && resultCode == RESULT_OK){ EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA); String targetId = bean.targetId; Conversation.ConversationType type = bean.mType; mPresenter.sendImageMessage(this, editPicturePath, targetId, type); } //分享视频 if(requestCode == REQUEST_SHARE_VIDEO && resultCode == RESULT_OK){ EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA); ShareHelper.INSTANCE.getBuilder().targetId(bean.targetId).type(bean.mType).liuyan(bean.liuyan).action(ConversationActivity.REQUEST_SHARE_VIDEO).toShare(); } //多消息逐条转发 if(requestCode == REQUEST_SHARE_MORE_RELAY && resultCode == RESULT_OK){ fragment.resetMoreActionState(); EventShareMessage bean = (EventShareMessage) data.getSerializableExtra(Constant.INTENT_DATA); mPresenter.relayMessages(selectMessage, (String) bean.mObject, bean.mType, bean.Liuyan); } //多消息合并转发 if(requestCode == REQUEST_SHARE_MORE_MERGE_RELAY && resultCode == RESULT_OK){ fragment.resetMoreActionState(); EventShareMessage bean = (EventShareMessage) data.getSerializableExtra(Constant.INTENT_DATA); mPresenter.mergeRelayMessages(selectMessage, (String) bean.mObject, bean.mType, bean.Liuyan); } } private void showEditPictureDialog() { String [] items = {"发送好友", "保存图片"}; OptionsPopupDialog dialog = OptionsPopupDialog .newInstance(this, items) .setOptionsPopupDialogListener(new OptionsPopupDialog.OnOptionsItemClickedListener() { @Override public void onOptionsItemClicked(int which) { if(which == 0){ ConversationListActivity.startActivity(ConversationActivity.this, ConversationActivity.REQUEST_SHARE_IMAGE, Constant.SELECT_TYPE_SHARE); } if(which == 1){ ToastUtil.showLong(ConversationActivity.this, "图片已保存至: " + editPicturePath); } } }); dialog.show(); } private void initUnReadMsg() { Subscription sub = Observable.timer(200, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { mUnReadLayout = (LinearLayout) View.inflate(ConversationActivity.this, R.layout.layout_circle_unread_msg, null); mTvUnreadCircle = mUnReadLayout.findViewById(R.id.tv_unread); if(fragment != null && fragment.getView() != null){ LinearLayout floatLayout = fragment.getView().findViewById(R.id.float_layout); floatLayout.addView(mUnReadLayout,0); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mUnReadLayout.getLayoutParams(); params.gravity = Gravity.END; params.width = LinearLayout.LayoutParams.WRAP_CONTENT; params.height = WindowUtil.dip2px(ConversationActivity.this, 40); params.bottomMargin = (int) getResources().getDimension(R.dimen.margin_middle); showUnReadMsg(); mUnReadLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hideUnReadMsg(); CircleMainActivity.startActivity(ConversationActivity.this, groupId); } }); } } }); RxTaskHelper.getInstance().addTask(this, sub); } private void showUnReadMsg(){ if(mTvUnreadCircle.isSelected()) return; if(mUnReadLayout != null && mUnReadLayout.getAnimation() == null){ TranslateAnimation translateAnimation = new TranslateAnimation(300.0F, 0.0F, 0.0F, 0.0F); AlphaAnimation alphaAnimation = new AlphaAnimation(0.0F, 1.0F); translateAnimation.setDuration(1000L); alphaAnimation.setDuration(2000L); AnimationSet set = new AnimationSet(true); set.addAnimation(translateAnimation); set.addAnimation(alphaAnimation); mUnReadLayout.setVisibility(View.VISIBLE); mUnReadLayout.startAnimation(set); if(unreadMsgCount > 0){ String s = String.format(Locale.CHINA, "%s条新动态", unreadMsgCount > 99 ? "99+" : unreadMsgCount); mTvUnreadCircle.setText(s); }else{ String s = "进入圈子"; mTvUnreadCircle.setText(s); } mTvUnreadCircle.setSelected(true); LinearLayout floatLayout = fragment.getView().findViewById(R.id.float_layout); if(floatLayout != null ){ LinearLayout messageLayout = floatLayout.findViewById(R.id.rc_unread_message_layout); if(messageLayout != null){ int messageWidth = messageLayout.getWidth(); int padding = (int) (getResources().getDimension(R.dimen.margin_tiny) * 2 + WindowUtil.dip2px(this, 7)); int dynamicWidth = 48 + padding + StringUtil.getTextViewLength(mTvUnreadCircle, mTvUnreadCircle.getText().toString()); LinearLayout.LayoutParams params = null; if(messageWidth > dynamicWidth){ params = (LinearLayout.LayoutParams) mUnReadLayout.getLayoutParams(); params.width = messageWidth; }else if(dynamicWidth > messageWidth){ params = (LinearLayout.LayoutParams) messageLayout.getLayoutParams(); params.width = dynamicWidth; } } } } } private void hideUnReadMsg(){ if(mUnReadLayout != null){ mTvUnreadCircle.setText("进入圈子"); } } private void sentFile(Uri uri) { if(uri == null) return; String path = FileUtils.getPath(MyApplication.getInstance().getApplicationContext(), uri); if(TextUtils.isEmpty(path)){ ToastUtil.showShort(this, "文件地址无效,请重新选择"); return; } FileMessage fileMessage = FileMessage.obtain(Uri.fromFile(FileUtil.createFile(path))); if(fileMessage == null){ ToastUtil.showShort(this, "文件地址无效,请重新选择"); return; } Message message = ImMessageUtils.obtain(mTargetId,mConversationType,fileMessage); RongIM.getInstance().sendMediaMessage(message, "文件", "文件", new IRongCallback.ISendMediaMessageCallback() { @Override public void onProgress(Message message, int i) {} @Override public void onCanceled(Message message) {} @Override public void onAttached(Message message) {} @Override public void onSuccess(Message message) { ToastUtil.showShort(ConversationActivity.this, "发送文件成功"); } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { ToastUtil.showShort(ConversationActivity.this, "发送文件失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode)); } }); } private void initHeadTitle(){ getBaseHeadView().showBackButton(this); String userCode = UserManager.getInstance().getUserCode(); if (!TextUtils.isEmpty(goodsId) && !TextUtils.isEmpty(userCode) && !userCode.equals(mTargetId)) { getBaseHeadView().showHeadRightButton("发起交易",this); }else { if (mConversationType == Conversation.ConversationType.PRIVATE) { getBaseHeadView().showTitle(title); getBaseHeadView().showHeadRightImageButton(R.drawable.person_friend_icon_homepage, this); } else if(mConversationType == Conversation.ConversationType.GROUP) { getBaseHeadView().showHeadRightImageButton(R.drawable.person_friend_icon_hylb, this); } else if(mConversationType == Conversation.ConversationType.SYSTEM){ getBaseHeadView().showTitle(title); } } } private boolean isAdmin(){ return "1".equals(roleType) || "2".equals(roleType); } /** * 会话消息点击事件 * 自定义消息的点击操作已经移到自定义消息的provider里面处理 * 采用静态内部类和弱引用的写法避免内存泄漏 */ private static class ConversationListenerImp implements RongIM.ConversationBehaviorListener{ WeakReference<ConversationActivity> mWeakReference; ConversationActivity mConversationActivity; public ConversationListenerImp(ConversationActivity activity) { mWeakReference = new WeakReference<>(activity); RongIM.setConversationBehaviorListener(this); } @Override public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) { if(mWeakReference.get() == null) return true; mConversationActivity = mWeakReference.get(); String id = userInfo.getUserId(); //系统的小助手不然后用户点击头像 if(!TextUtils.isEmpty(id) && id.startsWith("1000") && id.length() == 6){ return true; } // PersonalInfoActivity.startActivity(mConversationActivity,userInfo.getUserId(),1000); PersonalInfoActivity.startActivity(mConversationActivity,userInfo.getUserId()); return true; } @Override public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) { return false; } @Override public boolean onMessageLinkClick(Context context, String s) { if(mWeakReference.get() != null){ QrcodeHandler handler = new QrcodeHandler(mWeakReference.get()); handler.resolvingCode(s, ""); return true; } return false; } @Override public boolean onMessageClick(Context context, View view, Message message) { if(mWeakReference.get() == null) return true; mConversationActivity = mWeakReference.get(); MessageContent messageContent = message.getContent(); //修改融云的图片长按点击事件 if(messageContent instanceof ImageMessage){ Intent intent = new Intent(context, PicturePagerActivity.class); intent.setPackage(view.getContext().getPackageName()); intent.putExtra("message", message); if(view.getContext() instanceof Activity){ ((Activity) view.getContext()).startActivityForResult(intent, PictureEditActivity.REQUEST_CODE); } return true; } //打开红包 if(messageContent instanceof RPMessage){ if(ClickUtil.isFastClick()) return false; mConversationActivity.mPresenter.getRedPackInfo(message); } //分享 if(messageContent instanceof ShareMessage){ ShareMessage shareMessage = (ShareMessage) message.getContent(); if(!TextUtils.isEmpty(shareMessage.getTypeId())){ try { int type = Integer.valueOf(shareMessage.getInfoType()); UIMessage uiMessage = UIMessage.obtain(message); mConversationActivity.mShareHandler.shareHandle(view.getContext(),shareMessage.getTypeId(),type,uiMessage); }catch (Exception e){ e.printStackTrace(); } } } //收藏 if(messageContent instanceof CollectMessage){ CollectMessage cMessage = (CollectMessage) message.getContent(); mConversationActivity.mShareHandler.collectHandle(cMessage.getId(),cMessage.getType(),cMessage.getUrl()); } //系统小助手 if(messageContent instanceof ClassMessage || messageContent instanceof DealMessage || messageContent instanceof CircleMessage || messageContent instanceof ArticleMessage || messageContent instanceof TradeInfoMessage || messageContent instanceof SystemMessage || (messageContent instanceof TextMessage && "100001".equals(message.getTargetId())) //通过文本消息和 TargetId = 100001 判断是不是系统消息 || messageContent instanceof MallMessage){ return MessagePresenter.INSTANCE.messageClick(mConversationActivity,view,message); } return false; } //这里为了给原来的长按弹窗加 收藏功能 todo @Override public boolean onMessageLongClick(final Context context, final View view, final Message message) { if(mWeakReference.get() == null) return true; mConversationActivity = mWeakReference.get(); mConversationActivity.currMessage = message; mConversationActivity.clickUserCode = message.getSenderUserId(); String userCode = UserManager.getInstance().getUserCode(); //红包消息不给撤回 if(message.getContent() instanceof RPMessage) return true; final UIMessage uiMessage = UIMessage.obtain(message); final List messageItemLongClickActions = RongMessageItemLongClickActionManager.getInstance().getMessageItemLongClickActions(uiMessage); Collections.sort(messageItemLongClickActions, new Comparator<MessageItemLongClickAction>() { public int compare(MessageItemLongClickAction lhs, MessageItemLongClickAction rhs) { return rhs.priority - lhs.priority; } }); final ArrayList<String> titles = new ArrayList<>(); Iterator var7 = messageItemLongClickActions.iterator(); while(var7.hasNext()) { MessageItemLongClickAction action = (MessageItemLongClickAction)var7.next(); titles.add(action.getTitle(context)); } //只能收藏这几种消息 if(message.getContent() instanceof TextMessage || message.getContent() instanceof ImageMessage || message.getContent() instanceof ShareMessage || message.getContent() instanceof VideoMessage){ titles.add("收藏"); } //只能转发这几种消息 if(message.getContent() instanceof TextMessage || message.getContent() instanceof FileMessage || message.getContent() instanceof ImageMessage || message.getContent() instanceof PTMessage || message.getContent() instanceof MergeHistoryMessage || message.getContent() instanceof VoiceMessage || message.getContent() instanceof VideoMessage){ titles.add("转发"); } //只有群主或者管理员才有权限管理成员 if(mConversationActivity.isAdmin() && !userCode.equals(mConversationActivity.clickUserCode) && mConversationActivity.groupType == GROUP_TYPE_CIRCLE){ titles.add("禁言"); titles.add("拉黑"); } //给管理员添加个 if(mConversationActivity.isAdmin() && !userCode.equals(mConversationActivity.clickUserCode) && !(message.getContent() instanceof RPMessage)){ titles.add("撤回消息"); } OptionsPopupDialog.newInstance(context, titles.toArray(new String[titles.size()])).setOptionsPopupDialogListener( new OptionsPopupDialog.OnOptionsItemClickedListener() { @Override public void onOptionsItemClicked(int flag) { if(flag < messageItemLongClickActions.size()){ ((MessageItemLongClickAction)messageItemLongClickActions.get(flag)).listener.onMessageItemLongClick(context, uiMessage); }else{ String title = titles.get(flag); //收藏消息 if(title.equals("收藏")){ mConversationActivity.mPresenter.collectMessage(message); } //转发 if(title.equals("转发")){ ConversationListActivity.startActivity(mConversationActivity,REQUEST_SHARE_RELAY ,Constant.SELECT_TYPE_RELAY); } //禁言 if(title.equals("禁言")){ mConversationActivity.showSelectDialog(); } //拉黑 if(title.equals("拉黑")){ mConversationActivity.removeMemberDialog(); } //撤回消息 if(title.equals("撤回消息")){ mConversationActivity.recallMessage(message); } } } }).show(); return true; } } //撤回消息 private void recallMessage(final Message message){ RongIMClient.getInstance().recallMessage(message, "", new RongIMClient.ResultCallback<RecallNotificationMessage>() { @Override public void onSuccess(RecallNotificationMessage recallNotificationMessage) { RongIM.getInstance().deleteMessages(new int[]{message.getMessageId()}, new RongIMClient.ResultCallback<Boolean>() { @Override public void onSuccess(Boolean aBoolean) { } @Override public void onError(RongIMClient.ErrorCode errorCode) { } }); } @Override public void onError(RongIMClient.ErrorCode errorCode) { LogUtil.i("撤回消息失败 : " + errorCode); ToastUtil.showShort(ConversationActivity.this, "撤回消息失败"); } }); } //选择禁言时间 private ListDialog mListDialog; String [] datas = new String[]{"1天", "2天", "3天", "4天", "30天", "永久"}; public void showSelectDialog() { if (mListDialog == null) { mListDialog = new ListDialog(this, datas, true, R.style.cusDialog); mListDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position != 5) { int days = Integer.parseInt(datas[position] .replace("天","").trim()); forbidentSay(days * 24 * 60); //后台接口按分计算 } else { int days = -1; forbidentSay(days); } } }); } mListDialog.show(); } //time 按分钟算 0代表取消禁言 private void forbidentSay(int time) { mPresenter.shutup(groupId,clickUserCode,time); } private AlertDialog dialog; //删除成员 private void removeMemberDialog() { dialog = DialogUtil.showInputDialog(this, false, "", "确认将此成员移出圈子?", new View.OnClickListener() { @Override public void onClick(View v) { if (UserManager.getInstance().isLogin()) { mPresenter.removeMember(groupId,clickUserCode); } else { Toast.makeText(ConversationActivity.this, "登录后才能操作", Toast.LENGTH_SHORT).show(); } dialog.dismiss(); } }); } private void initFragment() { /* 新建 ConversationFragment 实例,通过 setUri() 设置相关属性*/ fragment = new MyConversationFragment(); WeakReference<MyConversationFragment> weakReference = new WeakReference<>(fragment); if(weakReference.get() != null){ fragment = weakReference.get(); Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon() .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase()) .appendQueryParameter("targetId", mTargetId) .appendQueryParameter("targetIds", mTargetIds).build(); fragment.setUri(uri); /* 加载 ConversationFragment */ FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.add(R.id.rong_content, fragment); transaction.commitAllowingStateLoss(); } } //去快速交易 private void gotoFastDeal(String id) { String isFinish = getIntent().getData().getQueryParameter("isFinish"); if ("1".equals(isFinish)) { ToastUtil.showShort(this, "当前商品正在交易中"); return; } if ("2".equals(isFinish)) { ToastUtil.showShort(this, "当前商品已交易完成"); return; } if (UserManager.getInstance().isLogin(this)) { GotoUtil.goToActivity(this, FastDealActivity.class, 0, Integer.valueOf(id)); } } private void initRongIm() { connectRongIm(); new ConversationListenerImp(this); new IMentionedInputListenerImp(this); } //设置@成员数据 private static class IMentionedInputListenerImp implements IMentionedInputListener{ private WeakReference<ConversationActivity> mWeakReference; private ConversationActivity mActivity; private IMentionedInputListenerImp(ConversationActivity conversationActivity){ mWeakReference = new WeakReference<>(conversationActivity); RongMentionManager.getInstance().setMentionedInputListener(this); } @Override public boolean onMentionedInput(Conversation.ConversationType conversationType, String targetId) { if(mWeakReference.get() == null) return true; mActivity = mWeakReference.get(); Class targetClass = null; switch (mActivity.groupType){ case GROUP_TYPE_CIRCLE: targetClass = AllGroupMemberActivity.class; break; case GROUP_TYPE_CUSTOM: targetClass = AllGroupInfoMemberActivity.class; break; } Intent intent = new Intent(MyApplication.getInstance(), targetClass); intent.putExtra("count", mActivity.groupCount); intent.putExtra("targetId", targetId); intent.putExtra("isAiter", true); intent.putExtra("groupId", mActivity.groupId); mActivity.startActivity(intent); return true; } } //连接融云操作 private void connectRongIm() { String token = UserManager.getInstance().getImToken(); RongImHelper.connect(MyApplication.getInstance(), token, new RongIMClient.ConnectCallback() { @Override public void onTokenIncorrect() {} @Override public void onSuccess(String s) { RongImHelper.initDefaultConfig(); } @Override public void onError(RongIMClient.ErrorCode errorCode) {} }); } private void showExitDialog() { exitDialog = DialogUtil.showInputDialog(this, false, "", "尚未上传完成视频,确认退出?", new View.OnClickListener() { @Override public void onClick(View v) { exitDialog.dismiss(); finish(); } }); } public void setSelectMessage(List<Message> selectMessage) { if(this.selectMessage == null){ this.selectMessage = new ArrayList<>(); } this.selectMessage.clear(); this.selectMessage.addAll(selectMessage); } @Override public void setPresenter(ConversationContract.Presenter presenter) { mPresenter = presenter; } @Override public void showLoad() { getBaseLoadingView().showLoading(); } @Override public void showLoadFinish() { getBaseLoadingView().hideLoading(); } @Override public void showEmpty() {} @Override public void showReLoad() {} @Override public void showError(String info) { ToastUtil.showShort(this,info); } @Override public void showNetError() {} }
package com.project.universitystudentassistant.utils; public class AppStringFormatter { public static String replaceSymbols(String value){ return value.replace("|", ",") .replace("�", "'") .replace("\"", ""); } public static String replaceZeros(int number){ return String.valueOf(number).replace("000", "k"); } }
package info.javierferia.app.misSitios; import info.javierferia.app.misSitios.db.BaseDatos; import info.javierferia.app.misSitios.db.SitiosDB; import info.javierferia.app.misSitios.utils.SUtil; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class SitiosProvider extends ContentProvider { public static final String CONTENT_PROFIJO = "content://"; public static final String CONTENT_AUTHORITY = "info.javierferia.app.misSitios"; private static final String TYPE_DIR = "vnd.android.cursor.dir/vnd.sitios"; private static final String TYPE_ITEM = "vnd.android.cursor.item/vnd.sitios"; public static final Uri CONTENT_URI = Uri.parse(CONTENT_PROFIJO+CONTENT_AUTHORITY+"/sitios"); public static final String CONTENT_URI_STRING = CONTENT_PROFIJO+CONTENT_AUTHORITY+"/sitios"; private static final int SITIOS = 1; private static final int SITIOS_ID = 2; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(CONTENT_AUTHORITY, "sitios", SITIOS); uriMatcher.addURI(CONTENT_AUTHORITY, "sitios/#", SITIOS_ID); }; private SQLiteDatabase sitiosDB; @Override public boolean onCreate () { Context context = getContext(); BaseDatos dbHelper = new BaseDatos(context, SitiosDB.DB_VERSION); sitiosDB = dbHelper.getWritableDatabase(); return (sitiosDB == null) ? false : true; } // public boolean onCreate @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder(); sqlBuilder.setTables(SitiosDB.TSitios.NOMBRE_TABLA); if (uriMatcher.match(uri) == SITIOS_ID) { sqlBuilder.appendWhere(SitiosDB.TSitios._ID+"="+uri.getPathSegments().get(1)); } if (sortOrder == null || sortOrder == "") { sortOrder = SitiosDB.TSitios.DEFAULT_SORT_ORDER; } Cursor c = sqlBuilder.query(sitiosDB, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } // @Override public int delete (Uri uri, String where, String[] whereargs) { int count = 0; switch ( uriMatcher.match(uri) ) { case SITIOS: count = sitiosDB.delete(SitiosDB.TSitios.NOMBRE_TABLA, where, whereargs); break; case SITIOS_ID: String id = uri.getPathSegments().get(1); count = sitiosDB.delete(SitiosDB.TSitios.NOMBRE_TABLA, SitiosDB.TSitios._ID+" = "+id, whereargs); break; default: throw new IllegalArgumentException(Resources.getSystem().getResourceName(R.string.UnknowURI)+uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // public int delete @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case SITIOS: return TYPE_DIR; case SITIOS_ID: return TYPE_ITEM; default: throw new IllegalArgumentException(Resources.getSystem().getResourceName(R.string.UnsoportURI) + uri); } } @Override public Uri insert (Uri uri, ContentValues values) { long rowID = sitiosDB.replace(SitiosDB.TSitios.NOMBRE_TABLA, "", values); /* Si todo ha ido bien devolvemos su URI */ if (rowID > 0) { Uri baseUri = Uri.parse(CONTENT_PROFIJO+CONTENT_AUTHORITY+"/post"); Uri _uri = ContentUris.withAppendedId(baseUri, rowID); getContext().getContentResolver().notifyChange(_uri, null); getContext().getContentResolver().notifyChange(baseUri, null); return _uri; } // throw new IllegalArgumentException(Resources.getSystem().getResourceName(R.string.FailRowInto)+ uri); } // public Uri insert @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SUtil.t(String.valueOf(uriMatcher.match(uri)),"Entre y Path 1"); int count = 0; switch (uriMatcher.match(uri)) { case SITIOS: SUtil.t("SITIOS"); count = sitiosDB.update(SitiosDB.TSitios.NOMBRE_TABLA, values, selection, selectionArgs); break; case SITIOS_ID: SUtil.t("SITIOS_ID"); count = sitiosDB.update(SitiosDB.TSitios.NOMBRE_TABLA, values, SitiosDB.TSitios._ID+"="+uri.getPathSegments().get(1),selectionArgs); break; default: throw new IllegalArgumentException(Resources.getSystem().getResourceName(R.string.UnknowURI)+uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } }
package com.igs.exception; import com.hl.util.LogUtils; /** * 类描述:构建请求参数时错误 * 创建人:heliang * 创建时间:2015/10/21 17:04 * 修改人:8153 * 修改时间:2015/10/21 17:04 * 修改备注: */ public class ErrorReq implements ErrorBundle { private String backMsg = "请求参数异常!"; private Exception e; private String method; String params; public ErrorReq(Exception e,String method, String params) { this.e = e; this.method = method; this.params = params; logReqMsg(); } @Override public Exception getException() { return e; } @Override public String getErrorMessage() { return backMsg; } @Override public String getErrorCode() { return ErrCode.ERROR_REQ; } /** * 处理请求参数异常 */ public void logReqMsg(){ if(LogUtils.isDebug){ LogUtils.d("构建"+backMsg+"-method:"+method +"-params:"+params); if(e!= null){ LogUtils.d("-errorMsg:"+e.getCause()+e.getMessage()); } } } }
/* * Copyright 2002-2022 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.test.web.reactive.server; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import org.springframework.http.HttpHeaders; import org.springframework.http.client.reactive.ClientHttpConnector; import org.springframework.http.client.reactive.HttpComponentsClientHttpConnector; import org.springframework.http.client.reactive.JdkClientHttpConnector; import org.springframework.http.client.reactive.JettyClientHttpConnector; import org.springframework.http.client.reactive.ReactorClientHttpConnector; import org.springframework.http.client.reactive.ReactorNetty2ClientHttpConnector; import org.springframework.http.codec.ClientCodecConfigurer; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.ExchangeFunction; import org.springframework.web.reactive.function.client.ExchangeFunctions; import org.springframework.web.reactive.function.client.ExchangeStrategies; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import org.springframework.web.util.DefaultUriBuilderFactory; import org.springframework.web.util.UriBuilderFactory; /** * Default implementation of {@link WebTestClient.Builder}. * * @author Rossen Stoyanchev * @since 5.0 */ class DefaultWebTestClientBuilder implements WebTestClient.Builder { private static final boolean reactorNettyClientPresent; private static final boolean reactorNetty2ClientPresent; private static final boolean jettyClientPresent; private static final boolean httpComponentsClientPresent; private static final boolean webFluxPresent; static { ClassLoader loader = DefaultWebTestClientBuilder.class.getClassLoader(); reactorNettyClientPresent = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", loader); reactorNetty2ClientPresent = ClassUtils.isPresent("reactor.netty5.http.client.HttpClient", loader); jettyClientPresent = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", loader); httpComponentsClientPresent = ClassUtils.isPresent("org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient", loader) && ClassUtils.isPresent("org.apache.hc.core5.reactive.ReactiveDataConsumer", loader); webFluxPresent = ClassUtils.isPresent( "org.springframework.web.reactive.function.client.ExchangeFunction", loader); } @Nullable private final WebHttpHandlerBuilder httpHandlerBuilder; @Nullable private final ClientHttpConnector connector; @Nullable private String baseUrl; @Nullable private UriBuilderFactory uriBuilderFactory; @Nullable private HttpHeaders defaultHeaders; @Nullable private MultiValueMap<String, String> defaultCookies; @Nullable private List<ExchangeFilterFunction> filters; private Consumer<EntityExchangeResult<?>> entityResultConsumer = result -> {}; @Nullable private ExchangeStrategies strategies; @Nullable private List<Consumer<ExchangeStrategies.Builder>> strategiesConfigurers; @Nullable private Duration responseTimeout; /** Determine connector via classpath detection. */ DefaultWebTestClientBuilder() { this(null, null); } /** Use HttpHandlerConnector with mock server. */ DefaultWebTestClientBuilder(WebHttpHandlerBuilder httpHandlerBuilder) { this(httpHandlerBuilder, null); } /** Use given connector. */ DefaultWebTestClientBuilder(ClientHttpConnector connector) { this(null, connector); } DefaultWebTestClientBuilder( @Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) { Assert.isTrue(httpHandlerBuilder == null || connector == null, "Expected WebHttpHandlerBuilder or ClientHttpConnector but not both."); // Helpful message especially for MockMvcWebTestClient users Assert.state(webFluxPresent, "To use WebTestClient, please add spring-webflux to the test classpath."); this.connector = connector; this.httpHandlerBuilder = (httpHandlerBuilder != null ? httpHandlerBuilder.clone() : null); } /** Copy constructor. */ DefaultWebTestClientBuilder(DefaultWebTestClientBuilder other) { this.httpHandlerBuilder = (other.httpHandlerBuilder != null ? other.httpHandlerBuilder.clone() : null); this.connector = other.connector; this.responseTimeout = other.responseTimeout; this.baseUrl = other.baseUrl; this.uriBuilderFactory = other.uriBuilderFactory; if (other.defaultHeaders != null) { this.defaultHeaders = new HttpHeaders(); this.defaultHeaders.putAll(other.defaultHeaders); } else { this.defaultHeaders = null; } this.defaultCookies = (other.defaultCookies != null ? new LinkedMultiValueMap<>(other.defaultCookies) : null); this.filters = (other.filters != null ? new ArrayList<>(other.filters) : null); this.entityResultConsumer = other.entityResultConsumer; this.strategies = other.strategies; this.strategiesConfigurers = (other.strategiesConfigurers != null ? new ArrayList<>(other.strategiesConfigurers) : null); } @Override public WebTestClient.Builder baseUrl(String baseUrl) { this.baseUrl = baseUrl; return this; } @Override public WebTestClient.Builder uriBuilderFactory(UriBuilderFactory uriBuilderFactory) { this.uriBuilderFactory = uriBuilderFactory; return this; } @Override public WebTestClient.Builder defaultHeader(String header, String... values) { initHeaders().put(header, Arrays.asList(values)); return this; } @Override public WebTestClient.Builder defaultHeaders(Consumer<HttpHeaders> headersConsumer) { headersConsumer.accept(initHeaders()); return this; } private HttpHeaders initHeaders() { if (this.defaultHeaders == null) { this.defaultHeaders = new HttpHeaders(); } return this.defaultHeaders; } @Override public WebTestClient.Builder defaultCookie(String cookie, String... values) { initCookies().addAll(cookie, Arrays.asList(values)); return this; } @Override public WebTestClient.Builder defaultCookies(Consumer<MultiValueMap<String, String>> cookiesConsumer) { cookiesConsumer.accept(initCookies()); return this; } private MultiValueMap<String, String> initCookies() { if (this.defaultCookies == null) { this.defaultCookies = new LinkedMultiValueMap<>(3); } return this.defaultCookies; } @Override public WebTestClient.Builder filter(ExchangeFilterFunction filter) { Assert.notNull(filter, "ExchangeFilterFunction is required"); initFilters().add(filter); return this; } @Override public WebTestClient.Builder filters(Consumer<List<ExchangeFilterFunction>> filtersConsumer) { filtersConsumer.accept(initFilters()); return this; } private List<ExchangeFilterFunction> initFilters() { if (this.filters == null) { this.filters = new ArrayList<>(); } return this.filters; } @Override public WebTestClient.Builder entityExchangeResultConsumer(Consumer<EntityExchangeResult<?>> entityResultConsumer) { Assert.notNull(entityResultConsumer, "'entityResultConsumer' is required"); this.entityResultConsumer = this.entityResultConsumer.andThen(entityResultConsumer); return this; } @Override public WebTestClient.Builder codecs(Consumer<ClientCodecConfigurer> configurer) { if (this.strategiesConfigurers == null) { this.strategiesConfigurers = new ArrayList<>(4); } this.strategiesConfigurers.add(builder -> builder.codecs(configurer)); return this; } @Override public WebTestClient.Builder exchangeStrategies(ExchangeStrategies strategies) { this.strategies = strategies; return this; } @Override @SuppressWarnings("deprecation") public WebTestClient.Builder exchangeStrategies(Consumer<ExchangeStrategies.Builder> configurer) { if (this.strategiesConfigurers == null) { this.strategiesConfigurers = new ArrayList<>(4); } this.strategiesConfigurers.add(configurer); return this; } @Override public WebTestClient.Builder apply(WebTestClientConfigurer configurer) { configurer.afterConfigurerAdded(this, this.httpHandlerBuilder, this.connector); return this; } @Override public WebTestClient.Builder responseTimeout(Duration timeout) { this.responseTimeout = timeout; return this; } @Override public WebTestClient build() { ClientHttpConnector connectorToUse = this.connector; if (connectorToUse == null) { if (this.httpHandlerBuilder != null) { connectorToUse = new HttpHandlerConnector(this.httpHandlerBuilder.build()); } } if (connectorToUse == null) { connectorToUse = initConnector(); } Function<ClientHttpConnector, ExchangeFunction> exchangeFactory = connector -> { ExchangeFunction exchange = ExchangeFunctions.create(connector, initExchangeStrategies()); if (CollectionUtils.isEmpty(this.filters)) { return exchange; } return this.filters.stream() .reduce(ExchangeFilterFunction::andThen) .map(filter -> filter.apply(exchange)) .orElse(exchange); }; return new DefaultWebTestClient(connectorToUse, exchangeFactory, initUriBuilderFactory(), this.defaultHeaders != null ? HttpHeaders.readOnlyHttpHeaders(this.defaultHeaders) : null, this.defaultCookies != null ? CollectionUtils.unmodifiableMultiValueMap(this.defaultCookies) : null, this.entityResultConsumer, this.responseTimeout, new DefaultWebTestClientBuilder(this)); } private static ClientHttpConnector initConnector() { if (reactorNettyClientPresent) { return new ReactorClientHttpConnector(); } else if (reactorNetty2ClientPresent) { return new ReactorNetty2ClientHttpConnector(); } else if (jettyClientPresent) { return new JettyClientHttpConnector(); } else if (httpComponentsClientPresent) { return new HttpComponentsClientHttpConnector(); } else { return new JdkClientHttpConnector(); } } private ExchangeStrategies initExchangeStrategies() { if (CollectionUtils.isEmpty(this.strategiesConfigurers)) { return (this.strategies != null ? this.strategies : ExchangeStrategies.withDefaults()); } ExchangeStrategies.Builder builder = (this.strategies != null ? this.strategies.mutate() : ExchangeStrategies.builder()); this.strategiesConfigurers.forEach(configurer -> configurer.accept(builder)); return builder.build(); } private UriBuilderFactory initUriBuilderFactory() { if (this.uriBuilderFactory != null) { return this.uriBuilderFactory; } return (this.baseUrl != null ? new DefaultUriBuilderFactory(this.baseUrl) : new DefaultUriBuilderFactory()); } }
package com.online.spring.web.model; public class Suppliers { int supplierID; String companyName; String contactName; String contactJobTitle; String username; String password; public Suppliers() { } public Suppliers(int supplierID, String companyName, String contactName, String contactJobTitle, String username, String password) { this.supplierID = supplierID; this.companyName = companyName; this.contactName = contactName; this.contactJobTitle = contactJobTitle; this.username = username; this.password = password; } public int getSupplierID() { return supplierID; } public void setSupplierID(int supplierID) { this.supplierID = supplierID; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getContactJobTitle() { return contactJobTitle; } public void setContactJobTitle(String contactJobTitle) { this.contactJobTitle = contactJobTitle; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Suppliers [supplierID=" + supplierID + ", companyName=" + companyName + ", contactName=" + contactName + ", contactJobTitle=" + contactJobTitle + ", username=" + username + ", password=" + password + "]"; } }
package com.uchain.cryptohash; public class PointProxy { private BinaryData data; public BinaryData getData() { return data; } public void setData(BinaryData data) { this.data = data; } public static Object readResolve(BinaryData data) { return Point.apply(data); } }
package com.metoo.module.app.test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.metoo.foundation.domain.User; import com.metoo.foundation.service.IUserService; @Controller @RequestMapping(value="/users") public class PathVariableTest { @Autowired private IUserService userServiec; // 创建线程安全的Map static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); @RequestMapping(value="/", method=RequestMethod.GET) @ResponseBody public void getUserList() { // 处理"/users/"的GET请求,用来获取用户列表 // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 // System.out.println(0); } @RequestMapping(value="/", method=RequestMethod.POST) public String postUser(@ModelAttribute User user) { // 处理"/users/"的POST请求,用来创建User // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数 users.put(user.getId(), user); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 // url中的id可通过@PathVariable绑定到函数的参数中 return users.get(id); } /* @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { // 处理"/users/{id}"的PUT请求,用来更新User信息 User u = users.get(id); u.setName(user.getUserName()); u.setAge(user.getYears()); users.put(id, u); return "success"; } */ @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // 处理"/users/{id}"的DELETE请求,用来删除User users.remove(id); return "success"; } }
package es.neifi.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class PostgreSQLConnection { private final static String URL ="jdbc:postgresql://localhost:5433/gestiongym"; private final static String USER ="postgres"; private final static String PASSWORD ="admin"; private static Connection connection; public static Connection getConnection() { try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection(URL,USER,PASSWORD); System.out.println("Exito al conectar"); return connection; } catch (ClassNotFoundException | SQLException e) { System.out.println("[INFO] No se pudo conectar"); e.printStackTrace(); } return connection; } /** * Cierra una conexión especifica * @param conn conexion a cerrar */ public static void closeConnection(Connection conn) { try { conn.close(); System.out.println("Conexion cerrada correctamente"); } catch (SQLException e) { System.out.println("No se pudo cerrar la conexión"); e.printStackTrace(); } } public static void closeConnection() { try { connection.close(); System.out.println("Conexion cerrada correctamente"); } catch (SQLException e) { System.out.println("No se pudo cerrar la conexión"); e.printStackTrace(); } } public static void closeStmt(PreparedStatement stmt) { try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** * */ package com.jspmyadmin.app.common.controllers; import java.io.IOException; import java.sql.SQLException; import com.jspmyadmin.app.common.beans.InstallBean; import com.jspmyadmin.app.common.logic.InstallLogic; import com.jspmyadmin.framework.connection.ConnectionFactory; import com.jspmyadmin.framework.constants.AppConstants; import com.jspmyadmin.framework.constants.Constants; import com.jspmyadmin.framework.exception.EncodingException; import com.jspmyadmin.framework.web.annotations.Detect; import com.jspmyadmin.framework.web.annotations.HandleGet; import com.jspmyadmin.framework.web.annotations.HandlePost; import com.jspmyadmin.framework.web.annotations.Model; import com.jspmyadmin.framework.web.annotations.ValidateToken; import com.jspmyadmin.framework.web.annotations.WebController; import com.jspmyadmin.framework.web.logic.EncodeHelper; import com.jspmyadmin.framework.web.utils.RedirectParams; import com.jspmyadmin.framework.web.utils.RequestAdaptor; import com.jspmyadmin.framework.web.utils.RequestLevel; import com.jspmyadmin.framework.web.utils.View; import com.jspmyadmin.framework.web.utils.ViewType; /** * @author Yugandhar Gangu * @created_at 2016/02/03 * */ @WebController(authentication = false, path = "/install.html", requestLevel = RequestLevel.DEFAULT) public class InstallController { @Detect private RequestAdaptor requestAdaptor; @Detect private RedirectParams redirectParams; @Detect private EncodeHelper encodeObj; @Detect private View view; @Model private InstallBean bean; @HandleGet private void load() throws EncodingException, SQLException { bean.setToken(requestAdaptor.generateToken()); view.setType(ViewType.FORWARD); view.setPath(AppConstants.JSP_COMMON_INSTALL); } @HandlePost @ValidateToken private void save() { InstallLogic installLogic = new InstallLogic(encodeObj); try { installLogic.installConfig(bean); ConnectionFactory.init(); view.setType(ViewType.REDIRECT); view.setPath(AppConstants.PATH_HOME); } catch (IOException e) { e.printStackTrace(); redirectParams.put(Constants.ERR_KEY, AppConstants.ERR_UNABLE_TO_CONNECT_WITH_SERVER); view.setType(ViewType.REDIRECT); view.setPath(AppConstants.PATH_INSTALL); } } }