text
stringlengths
10
2.72M
import java.util.Stack; public class Invalidparen { public static void main(String[] args) { System.out.println(new Invalidparen().isValid(")")); } public boolean isValid(String s) { Stack<Character> stack = new Stack<Character> (); for (char ch :s.toCharArray()){ if(ch == '('){ stack.push(ch); } if(ch == '['){ stack.push(ch); } if(ch == '{'){ stack.push(ch); } if(ch == ')'){ if(stack.empty()){ return false; } char top= stack.pop(); if(top != '('){ return false; } } if(ch == ']'){ if(stack.empty()){ return false; } char top= stack.pop(); if(top != '['){ return false; } } if(ch == '}'){ if(stack.empty()){ return false; } char top= stack.pop(); if(top != '{'){ return false; } } } if(!stack.empty()){ return false; } return true; } }
package jogadoresTreinamento; public class JogadorDeFutebol { private String nome; private int energia,alegria,gols, experiencia; public JogadorDeFutebol(String nome,int energia, int alegria, int gols, int experiencia){ this.nome = nome; this.energia = energia; this.alegria = alegria; this.gols = gols; this.experiencia = experiencia; } public String getNome() { return nome; } public int getEnergia() { return energia; } public int getAlegria() { return alegria; } public int getGols() { return gols; } public int getExperiencia() { return experiencia; } public int setExperiencia(int experiencia) { this.experiencia += experiencia; return experiencia; } public void fazerGol(){ this.energia = energia-5; this.alegria = alegria+10; this.gols = gols+1; System.out.println("GOOOL"); } public void Correr(){ this.energia = energia-10; System.out.println("cansei!!!"); } public void mostraEstatistica(){ System.out.println("Nome: "+ this.getNome()); System.out.println("Energia: "+ this.getEnergia()); System.out.println("Alegria: "+ this.getAlegria()); System.out.println("Gols: "+ this.getGols()); System.out.println("Experiência: "+ this.getExperiencia()); } }
package valatava.lab.warehouse.exeption; /** * @author Yuriy Govorushkin */ public class InvalidPasswordException extends RuntimeException { public InvalidPasswordException() { super("Incorrect password"); } }
package ua.com.goit.kyrychok.dao; import ua.com.goit.kyrychok.domain.ProjectEvent; import java.util.List; public interface ProjectEventDao { List<ProjectEvent> fetch(int projectId); }
package net.drs.myapp.dao; import java.util.List; import net.drs.myapp.dto.WedDTO; import net.drs.myapp.exceptions.MatrimonialException; import net.drs.myapp.model.Wed; public interface IMatrimonialServiceDAO { List viewActiveProfiles() throws MatrimonialException; List<Wed>getAllWedProfiles() throws MatrimonialException; Wed activatedeactivateWed(WedDTO wedDTO) throws MatrimonialException; }
package com.fleet.seg.util; import com.huaban.analysis.jieba.JiebaSegmenter; import com.huaban.analysis.jieba.SegToken; import java.util.ArrayList; import java.util.List; /** * Jieba 分词器 * * @author April Han */ public class JiebaUtil { public static List<String> indexSeg(String text) { List<String> list = new ArrayList<>(); JiebaSegmenter jiebaSegmenter = new JiebaSegmenter(); for (SegToken segToken : jiebaSegmenter.process(text, JiebaSegmenter.SegMode.INDEX)) { list.add(segToken.word); } return list; } public static List<String> searchSeg(String text) { List<String> list = new ArrayList<>(); JiebaSegmenter jiebaSegmenter = new JiebaSegmenter(); for (SegToken segToken : jiebaSegmenter.process(text, JiebaSegmenter.SegMode.SEARCH)) { list.add(segToken.word); } return list; } }
package pers.pbyang.entity; import java.sql.Date; public class PicNews { private int id; private String title; private Date upTime; private String from1; private String content; private String author; private int traffic; private String picplace; public String getPicplace() { return picplace; } public void setPicplace(String picplace) { this.picplace = picplace; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getUpTime() { return upTime; } public void setUpTime(Date upTime) { this.upTime = upTime; } public String getFrom1() { return from1; } public void setFrom1(String from1) { this.from1 = from1; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getTraffic() { return traffic; } public void setTraffic(int traffic) { this.traffic = traffic; } }
package org.nmrg.entity.common; import java.util.HashMap; import org.nmrg.entity.BaseEntity; /** * 邮件 * Created by admin on 2017/9/27. */ public class EmailEntity extends BaseEntity { // --- 邮件接收方 private String toAddress; // --- 邮件主题 private String subject; // --- 邮件内容 private String content; // --- 模板 private String template; // --- 自定义参数 private HashMap<String, String> kvMap; public EmailEntity() { } public EmailEntity(String toAddress, String subject, String content, String template, HashMap<String, String> kvMap) { this.toAddress = toAddress; this.subject = subject; this.content = content; this.template = template; this.kvMap = kvMap; } public String getToAddress() { return toAddress; } public void setToAddress(String toAddress) { this.toAddress = toAddress; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public HashMap<String, String> getKvMap() { return kvMap; } public void setKvMap(HashMap<String, String> kvMap) { this.kvMap = kvMap; } }
package com.estrelladelsur.miequipo; import java.util.ArrayList; import com.estrelladelsur.R; import com.estrelladelsur.abstractclases.Anio; import com.estrelladelsur.abstractclases.Mes; import com.estrelladelsur.abstractclases.Torneo; import com.estrelladelsur.adaptadores.AdaptadorRecyclerTorneo; import com.estrelladelsur.adaptadores.AdapterSpinnerAnio; import com.estrelladelsur.adaptadores.AdapterSpinnerCancha; import com.estrelladelsur.adaptadores.AdapterSpinnerMes; import com.estrelladelsur.alert.AlertsMenu; import com.estrelladelsur.connectionmanager.BL; import com.estrelladelsur.databases.ControladorAdeful; import com.estrelladelsur.liga.DividerItemDecoration; import com.estrelladelsur.liga.FragmentTorneo.ClickListener; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; /** * A simple {@link Fragment} subclass. Use the * {@link FragmentGenerarNoticia.sgoliver.android.toolbartabs.Fragment1#newInstance} * factory method to create an instance of this fragment. */ public class FragmentEditarEntrenamiento extends Fragment { private Spinner entrenamientoAnioSpinner; private Spinner entrenamientoMesSpinner; private ControladorAdeful controladorAdeful; private RecyclerView recycleViewGeneral; private int CheckedPositionFragment; private FloatingActionButton botonFloating; private ArrayList<Anio> anioArray; private ArrayList<Mes> mesArray; private AdapterSpinnerAnio adapterSpinnerAnio; private AdapterSpinnerMes adapterSpinnerMes; public static FragmentEditarEntrenamiento newInstance() { FragmentEditarEntrenamiento fragment = new FragmentEditarEntrenamiento(); return fragment; } public FragmentEditarEntrenamiento() { // Required empty public constructor } @Override public void onActivityCreated(Bundle state) { super.onActivityCreated(state); controladorAdeful = new ControladorAdeful(getActivity()); if (state != null) { CheckedPositionFragment = state.getInt("curChoice", 0); } else { init(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_consultar_entrenamiento, container, false); // RECYCLER recycleViewGeneral = (RecyclerView) v .findViewById(R.id.recycleViewGeneral); // CANCHA entrenamientoAnioSpinner = (Spinner) v .findViewById(R.id.entrenamientoAnioSpinner); // DIA entrenamientoMesSpinner = (Spinner) v .findViewById(R.id.entrenamientoMesSpinner); botonFloating = (FloatingActionButton) v .findViewById(R.id.botonFloating); return v; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("curChoice", CheckedPositionFragment); } private void init() { // ANIO SPINNER controladorAdeful.abrirBaseDeDatos(); anioArray = controladorAdeful.selectListaAnio(); controladorAdeful.cerrarBaseDeDatos(); // ANIO ADAPTER adapterSpinnerAnio = new AdapterSpinnerAnio(getActivity(), R.layout.simple_spinner_dropdown_item, anioArray); entrenamientoAnioSpinner.setAdapter(adapterSpinnerAnio); // MES SPINNER controladorAdeful.abrirBaseDeDatos(); mesArray = controladorAdeful.selectListaMes(); controladorAdeful.cerrarBaseDeDatos(); // MES ADAPTER adapterSpinnerMes = new AdapterSpinnerMes(getActivity(), R.layout.simple_spinner_dropdown_item, mesArray); entrenamientoMesSpinner.setAdapter(adapterSpinnerMes); //recyclerViewLoadEntrenamiento(); recycleViewGeneral.addOnItemTouchListener(new RecyclerTouchListener( getActivity(), recycleViewGeneral, new ClickListener() { @Override public void onLongClick(View view, final int position) { // alertMenu = new AlertsMenu(getActivity(), "ALERTA", // "Desea eliminar el torneo?", null, null); // alertMenu.btnAceptar.setText("Aceptar"); // alertMenu.btnCancelar.setText("Cancelar"); // // alertMenu.btnAceptar // .setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // BL.getBl().eliminarTorneoAdeful( // torneoArray.get(position) // .getID_TORNEO()); // recyclerViewLoadTorneo(); // // Toast.makeText( // getActivity(), // "Torneo Eliminado Correctamente", // Toast.LENGTH_SHORT).show(); // // alertMenu.alertDialog.dismiss(); // // } // }); // alertMenu.btnCancelar // .setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View v) { // // TODO Auto-generated method stub // alertMenu.alertDialog.dismiss(); // } // }); } // @Override public void onClick(View view, int position) { // TODO Auto-generated method stub // // insertar = false; // editTextTorneo.setText(torneoArray.get(position) // .getDESCRIPCION()); // // posicion = position; // } })); // // botonFloating.setOnClickListener(new View.OnClickListener() { // // @SuppressLint("NewApi") // public void onClick(View view) { // // if (editTextTorneo.getText().toString().equals("")) { // Toast.makeText(getActivity(), // "Ingrese el nombre del torneo.", Toast.LENGTH_SHORT) // .show(); // // } else { // // if (insertar) { // String usuario = "Administrador"; // String fechaCreacion = BL.getBl().getFechaOficial(); // String fechaActualizacion = fechaCreacion; // String estado = "P"; // String tabla = "TORNEO_ADEFUL"; // // torneo = new Torneo(0, editTextTorneo.getText() // .toString(), usuario, fechaCreacion, // fechaActualizacion, estado, tabla); // // controladorAdeful.abrirBaseDeDatos(); // controladorAdeful.insertTorneoAdeful(torneo); // controladorAdeful.cerrarBaseDeDatos(); // // BL.getBl().insertarTorneoAdeful(torneo); // // recyclerViewLoadTorneo(); // // editTextTorneo.setText(""); // } else { // // String usuario = "Administrador"; // String fechaActualizacion = BL.getBl() // .getFechaOficial(); // String estado = "P"; // // String tabla = "DIVISION_ADEFUL"; // // torneo = new Torneo(torneoArray.get(posicion) // .getID_TORNEO(), editTextTorneo.getText() // .toString(), usuario, null, fechaActualizacion, // estado, null); // // controladorAdeful.abrirBaseDeDatos(); // controladorAdeful.actualizarTorneoAdeful(torneo); // controladorAdeful.cerrarBaseDeDatos(); // // //BL.getBl().actualizarTorneoAdeful(torneo); // // recyclerViewLoadTorneo(); // // editTextTorneo.setText(""); // // insertar = true; // // Toast.makeText(getActivity(), // "Torneo actualizado correctamente.", // Toast.LENGTH_SHORT).show(); // // } // } // } // }); } public void recyclerViewLoadEntrenamiento(String fecha) { recycleViewGeneral.setLayoutManager(new LinearLayoutManager( getActivity(), LinearLayoutManager.VERTICAL, false)); recycleViewGeneral.addItemDecoration(new DividerItemDecoration( getActivity(), DividerItemDecoration.VERTICAL_LIST)); recycleViewGeneral.setItemAnimator(new DefaultItemAnimator()); // controladorAdeful.abrirBaseDeDatos(); // torneoArray=controladorAdeful.selectListaTorneoAdeful(); // controladorAdeful.cerrarBaseDeDatos(); // // //torneoArray = BL.getBl().selectListaTorneoAdeful(); // adaptadorTorneo = new AdaptadorRecyclerTorneo(torneoArray); // adaptadorTorneo.notifyDataSetChanged(); // recycleViewTorneo.setAdapter(adaptadorTorneo); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } /** * Metodo click item recycler * * @author LEO * */ public static interface ClickListener { public void onClick(View view, int position); public void onLongClick(View view, int position); } static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { private GestureDetector detector; private ClickListener clickListener; public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) { this.clickListener = clickListener; detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder( e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { // TODO Auto-generated method stub View child = rv.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null && detector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)); } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean arg0) { // TODO Auto-generated method stub } } }
import java.awt.Color; import javax.swing.JPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; public class VoltageGraphPanel extends JPanel { private TimeSeries series; private ChartPanel chartPanel; private JFreeChart chart; public VoltageGraphPanel() { this.series = new TimeSeries("Voltage"); final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series); this.chart = ChartFactory.createTimeSeriesChart("Voltage", "Time", "Voltage", dataset, false, false, false); chart.setBackgroundPaint(Color.white); final XYPlot plot = (XYPlot) chart.getPlot(); ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(60000.0); axis = plot.getRangeAxis(); axis.setRange(0.0, 10.0); this.chartPanel = new ChartPanel(chart); this.add(chartPanel); chartPanel.setPreferredSize(new java.awt.Dimension(300, 300)); } public void addPoint(double voltage) { voltage = (voltage/4096) * 1.5; series.add(new Millisecond(), voltage); } }
package cn.canlnac.onlinecourse.domain.interactor; import java.util.Map; import javax.inject.Inject; import cn.canlnac.onlinecourse.domain.executor.PostExecutionThread; import cn.canlnac.onlinecourse.domain.executor.ThreadExecutor; import cn.canlnac.onlinecourse.domain.repository.ChatRepository; import rx.Observable; /** * 创建话题使用用例. */ public class CreateChatUseCase extends UseCase { private final Map<String, Object> chat; private final ChatRepository chatRepository; @Inject public CreateChatUseCase( Map<String, Object> chat, ChatRepository chatRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread ) { super(threadExecutor, postExecutionThread); this.chat = chat; this.chatRepository = chatRepository; } @Override protected Observable buildUseCaseObservable() { return this.chatRepository.createChat(chat); } }
/** * */ package work.waynelee.captcha; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import work.waynelee.captcha.properties.CaptchaProperties; import work.waynelee.captcha.service.CaptchaService; import work.waynelee.captcha.service.CaptchaServiceImpl; /** * * @author 李文庆 * 2019年3月19日 下午1:41:52 */ @Configuration @EnableConfigurationProperties({CaptchaProperties.class}) public class CaptchaAutoConfiguration { @Bean @ConditionalOnMissingBean(CaptchaService.class) public CaptchaService captchaService(){ return new CaptchaServiceImpl(); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; public final class bon extends a { public int hcE; public String jSA; public int lOH; public String rTW; public int rXs; public String rdS; public int rdq; public String smB; public int smg; public int smh; public int smi; public long smj; public long smk; public int smm; protected final int a(int i, Object... objArr) { int h; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.rdS != null) { aVar.g(1, this.rdS); } if (this.rTW != null) { aVar.g(2, this.rTW); } aVar.fT(3, this.rdq); aVar.fT(4, this.hcE); if (this.jSA != null) { aVar.g(5, this.jSA); } aVar.fT(6, this.lOH); aVar.fT(7, this.smh); aVar.fT(8, this.smg); if (this.smB != null) { aVar.g(9, this.smB); } aVar.fT(10, this.smi); aVar.T(11, this.smj); aVar.T(12, this.smk); aVar.fT(13, this.rXs); aVar.fT(14, this.smm); return 0; } else if (i == 1) { if (this.rdS != null) { h = f.a.a.b.b.a.h(1, this.rdS) + 0; } else { h = 0; } if (this.rTW != null) { h += f.a.a.b.b.a.h(2, this.rTW); } h = (h + f.a.a.a.fQ(3, this.rdq)) + f.a.a.a.fQ(4, this.hcE); if (this.jSA != null) { h += f.a.a.b.b.a.h(5, this.jSA); } h = ((h + f.a.a.a.fQ(6, this.lOH)) + f.a.a.a.fQ(7, this.smh)) + f.a.a.a.fQ(8, this.smg); if (this.smB != null) { h += f.a.a.b.b.a.h(9, this.smB); } return ((((h + f.a.a.a.fQ(10, this.smi)) + f.a.a.a.S(11, this.smj)) + f.a.a.a.S(12, this.smk)) + f.a.a.a.fQ(13, this.rXs)) + f.a.a.a.fQ(14, this.smm); } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) { if (!super.a(aVar2, this, h)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; bon bon = (bon) objArr[1]; switch (((Integer) objArr[2]).intValue()) { case 1: bon.rdS = aVar3.vHC.readString(); return 0; case 2: bon.rTW = aVar3.vHC.readString(); return 0; case 3: bon.rdq = aVar3.vHC.rY(); return 0; case 4: bon.hcE = aVar3.vHC.rY(); return 0; case 5: bon.jSA = aVar3.vHC.readString(); return 0; case 6: bon.lOH = aVar3.vHC.rY(); return 0; case 7: bon.smh = aVar3.vHC.rY(); return 0; case 8: bon.smg = aVar3.vHC.rY(); return 0; case 9: bon.smB = aVar3.vHC.readString(); return 0; case 10: bon.smi = aVar3.vHC.rY(); return 0; case 11: bon.smj = aVar3.vHC.rZ(); return 0; case 12: bon.smk = aVar3.vHC.rZ(); return 0; case 13: bon.rXs = aVar3.vHC.rY(); return 0; case 14: bon.smm = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package com.flurry.proguard; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.Properties; import java.util.UUID; /** * Test uploads */ public class UploadMappingTest { private static final String FLURRY_TOKEN = "FLURRY_TOKEN"; private static final String API_KEY = "API_KEY"; @Test public void testParseConfigFile() { String path = getResourcePath("flurry.config"); Properties vals = UploadMapping.parseConfigFile(path); Assert.assertEquals(vals.get("api-key"), "FOO_API_KEY"); Assert.assertEquals(vals.get("token"), "FOO_TOKEN"); Assert.assertEquals(vals.get("timeout"), "60000"); } @Test public void testUploadFile() throws IOException { String apiKey = System.getenv(API_KEY); String uuid = UUID.randomUUID().toString(); String path = getResourcePath("mapping.txt"); String token = System.getenv(FLURRY_TOKEN); UploadMapping.uploadFiles(apiKey, uuid, Collections.singletonList(path), token, UploadMapping.ONE_MINUTE_IN_MS, AndroidUploadType.ANDROID_JAVA); } private String getResourcePath(String resource) { return UploadMappingTest.class.getClassLoader().getResource(resource).getPath(); } }
/** * 17.10. Find Majority Element LCCI * "Easy" * 摩尔投票,非主要数就减,主要数就加 */ public class Solution { public int majorityElement(int[] nums) { int candidate = -1, count = 0, n = nums.length; for (int i : nums) { if (count == 0) { candidate = i; } if (i == candidate) { count++; } else { count--; } } count = 0; for (int i : nums) { if (i == candidate) { count++; } } return count * 2 > n ? candidate : -1; } public static void main(String[] args) { int[][] nums = { { 1, 2, 5, 9, 5, 9, 5, 5, 5 }, { 3, 2 }, { 2, 2, 1, 1, 1, 2, 2 } }; Solution s = new Solution(); for (int[] ns : nums) { System.out.println(s.majorityElement(ns)); } } }
package com.dev.jdbc; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class JDBCInsertion { public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; try { //step 1: Loading and registring driver Driver div = new com.mysql.jdbc.Driver(); DriverManager.registerDriver(div); System.out.println("Driver Loaded..."); //step 2: get connection via driver String url = "jdbc:mysql://localhost:3306/caps_buggers?user=root&password=root"; conn = DriverManager.getConnection(url); System.out.println("Connection Estd..."); //step 3: issue SQL query via connection String query = "insert into users_info values(?,?,?,?)"; pstmt = conn.prepareStatement(query); Scanner sc = new Scanner(System.in); System.out.println("Enter userid..."); int userid = Integer.parseInt(sc.nextLine()); System.out.println("Enter user name..."); String username = sc.nextLine(); System.out.println("Enter email id..."); String email = sc.nextLine(); System.out.println("enter password..."); String password = sc.nextLine(); pstmt.setInt(1, userid); pstmt.setString(2, username); pstmt.setString(3, email); pstmt.setString(4, password); int count = pstmt.executeUpdate(); //step 4: process the result if(count>0) { System.out.println("data inserted..."); }else { System.out.println("error!!!"); } } catch (SQLException e) { e.printStackTrace(); } //step 5:Close all JDBC objects finally { if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pstmt!=null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
package com.diozero.internal.provider.firmata; /*- * #%L * Organisation: diozero * Project: diozero - Firmata * Filename: FirmataServoDevice.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import org.tinylog.Logger; import com.diozero.api.RuntimeIOException; import com.diozero.internal.provider.firmata.adapter.FirmataAdapter; import com.diozero.internal.provider.firmata.adapter.FirmataProtocol.PinMode; import com.diozero.internal.spi.AbstractDevice; import com.diozero.internal.spi.InternalServoDeviceInterface; public class FirmataServoDevice extends AbstractDevice implements InternalServoDeviceInterface { // Values < 544 will be treated as angles in degrees, values >= 544 are treated // as pulse width in microseconds // Ref: // https://github.com/firmata/firmata.js/blob/54dda2d2112e9fc3f997324df22d59f6e3d05298/packages/firmata-io/lib/firmata.js#L923 private static final int MIN_PULSE_WIDTH_US = 544; private static final int ARDUINO_SERVO_FREQUENCY = 50; private FirmataAdapter adapter; private int gpio; private int max; public FirmataServoDevice(FirmataDeviceFactory deviceFactory, String key, int gpio, int minPulseWidthUs, int maxPulseWidthUs, int initialPulseWidthUs) { super(key, deviceFactory); this.gpio = gpio; adapter = deviceFactory.getFirmataAdapter(); max = adapter.getMax(gpio, PinMode.SERVO); // minPulse and maxPulse are both 14-bit unsigned integers /*- // This will map 0-180 to 1000-1500 board.servoConfig(9, 1000, 1500); */ adapter.servoConfig(gpio, Math.max(MIN_PULSE_WIDTH_US, minPulseWidthUs), Math.min(max, maxPulseWidthUs)); adapter.setPinMode(gpio, PinMode.SERVO); setPulseWidthUs(initialPulseWidthUs); } @Override public int getGpio() { return gpio; } @Override public int getServoNum() { return gpio; } @Override public int getPulseWidthUs() throws RuntimeIOException { return adapter.getValue(gpio); } @Override public void setPulseWidthUs(int pulseWidthUs) throws RuntimeIOException { // Values < 544 will be treated as angles in degrees, values >= 544 are treated // as pulse width in microseconds // Ref: // https://github.com/firmata/firmata.js/blob/54dda2d2112e9fc3f997324df22d59f6e3d05298/packages/firmata-io/lib/firmata.js#L923 // Should really be in the range 544..2,500 microseconds adapter.setValue(gpio, Math.max(MIN_PULSE_WIDTH_US, Math.min(max, pulseWidthUs))); } @Override public int getServoFrequency() { return ARDUINO_SERVO_FREQUENCY; } @Override public void setServoFrequency(int frequencyHz) throws RuntimeIOException { throw new UnsupportedOperationException("Cannot change servo frequency via Firmata"); } @Override protected void closeDevice() throws RuntimeIOException { Logger.trace("closeDevice() {}", getKey()); // Cannot do setPulseWidth(0) as that is interpreted as 0 degrees // So... revert to the default (digital output, value off) adapter.setPinMode(gpio, PinMode.DIGITAL_OUTPUT); adapter.setDigitalValue(gpio, false); } }
package com.wrapp.floatlabelededittext; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.animation.ObjectAnimator; public class FloatLabeledEditText extends LinearLayout { private String hint; private TextView hintTextView; private EditText editText; public FloatLabeledEditText(Context context) { super(context); initialize(); } public FloatLabeledEditText(Context context, AttributeSet attrs) { super(context, attrs); setAttributes(attrs); initialize(); } public FloatLabeledEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setAttributes(attrs); initialize(); } private void setAttributes(AttributeSet attrs) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FloatLabeledEditText); try { hint = a.getString(R.styleable.FloatLabeledEditText_floatingHint); } finally { a.recycle(); } } private void initialize() { setOrientation(VERTICAL); View view = LayoutInflater.from(getContext()).inflate(R.layout.float_labeled_edit_text, this); hintTextView = (TextView) view.findViewById(R.id.FloatLabeledEditTextHint); editText = (EditText) view.findViewById(R.id.FloatLabeledEditTextEditText); if (hint != null) { setHint(hint); } hintTextView.setVisibility(View.INVISIBLE); editText.addTextChangedListener(onTextChanged); editText.setOnFocusChangeListener(onFocusChanged); } private TextWatcher onTextChanged = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { setShowHint(editable.length() != 0); } }; private OnFocusChangeListener onFocusChanged = new OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean gotFocus) { if (gotFocus) { ObjectAnimator.ofFloat(hintTextView, "alpha", 0.33f, 1f).start(); } else { ObjectAnimator.ofFloat(hintTextView, "alpha", 1f, 0.33f).start(); } } }; private void setShowHint(final boolean show) { AnimatorSet animation = null; if ((hintTextView.getVisibility() == VISIBLE) && !show) { animation = new AnimatorSet(); ObjectAnimator move = ObjectAnimator.ofFloat(hintTextView, "translationY", 0, hintTextView.getHeight() / 8); ObjectAnimator fade = ObjectAnimator.ofFloat(hintTextView, "alpha", 1, 0); animation.playTogether(move, fade); } else if ((hintTextView.getVisibility() != VISIBLE) && show) { animation = new AnimatorSet(); ObjectAnimator move = ObjectAnimator.ofFloat(hintTextView, "translationY", hintTextView.getHeight() / 8, 0); ObjectAnimator fade = ObjectAnimator.ofFloat(hintTextView, "alpha", 0, 1); animation.playTogether(move, fade); } if (animation != null) { animation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { super.onAnimationStart(animation); hintTextView.setVisibility(VISIBLE); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); hintTextView.setVisibility(show ? VISIBLE : INVISIBLE); } }); animation.start(); } } private void setHint(String hint) { this.hint = hint; editText.setHint(hint); hintTextView.setText(hint); } public Editable getText() { return editText.getText(); } public void setText(CharSequence text) { editText.setText(text); } }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * SalesVan inherits from WareHouse and creates a van object that will * store inventory from the WareHouse. * * @author ZZywusko * @version Project 2 */ public class SalesVan extends WareHouse { // instance variables - replace the example below with your own private String vanName; private ArrayList<String> finalVan= new ArrayList<String>(); private ArrayList<String> transferVan = new ArrayList<String>(); /** * Constructor for objects of class SalesVan */ public SalesVan(String n) { vanName = n; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public ArrayList<String> updateVan(ArrayList<String> warehouseArray, ArrayList<String> vanArray) { for(int i = 0; i<vanArray.size(); i++){ String vanCompare = vanArray.get(i); String str[] = vanCompare.split(","); String vanItemName= str[0]; int VANinvNum= Integer.valueOf(str[1]); for (int y = 0; y<warehouseArray.size(); i++){ String warehouseCompare = warehouseArray.get(y); String strWH[] = warehouseCompare.split(","); String whItemName= str[0]; //int wareInv = warehouseCompare.getQuantity(); int WHinvNum= Integer.valueOf(str[1]); if (vanItemName == whItemName && VANinvNum<WHinvNum){ warehouseArray.remove(warehouseCompare); int updatedValue= VANinvNum - WHinvNum; finalVan.add(vanItemName+","+ updatedValue); }else if(vanItemName == whItemName && VANinvNum>WHinvNum) { warehouseArray.remove(warehouseCompare); int updatedValue= WHinvNum; finalVan.add(vanItemName+","+ updatedValue); } } } return finalVan; } public ArrayList<String> transferVan(ArrayList<String> toVan, ArrayList<String> awayVan){ for(int i = 0; i<toVan.size(); i++){ String vanCompare = toVan.get(i); String str[] = vanCompare.split(","); String vanItemName= str[0]; int VANinvNum= Integer.valueOf(str[1]); for(int y = 0; y<awayVan.size(); y++){ String newVanCompare = awayVan.get(i); String newStr[] = newVanCompare.split(","); String newVanItemName= str[0]; int newVANinvNum= Integer.valueOf(str[1]); if (vanItemName == newVanItemName){ awayVan.remove(y); transferVan.remove(y); transferVan.add(vanItemName +","+ (VANinvNum+newVANinvNum)); } } } while (awayVan.size()>(-1)){ for(int i = 0; i<awayVan.size(); i++){ transferVan.add(awayVan.get(i)); } } return transferVan; } }
package com.ftd.schaepher.coursemanagement.activities; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.ftd.schaepher.coursemanagement.R; import com.ftd.schaepher.coursemanagement.db.CourseDBHelper; import com.ftd.schaepher.coursemanagement.pojo.TableCourseMultiline; import com.ftd.schaepher.coursemanagement.pojo.TableTaskInfo; import com.ftd.schaepher.coursemanagement.tools.Loger; import com.rey.material.app.SimpleDialog; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import jxl.Sheet; import jxl.Workbook; import jxl.format.Alignment; import jxl.format.CellFormat; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; /** * Created by sxq on 2015/10/31. * 任务详情页面 */ public class TaskDetailActivity extends AppCompatActivity implements View.OnClickListener { private CardView cardvTaskDetail; private TextView tvDepartmentDeadline; private TextView tvTeacherDeadline; private TextView tvTaskState; private TextView tvTaskName; private TextView tvTaskTerm; private ProgressDialog progress; private String relativeTable; private TableTaskInfo task; private CourseDBHelper dbHelper; private String tableName; private String filePath; private String excelTitle; private String taskTerm; private String taskName; // private String workNumber; private String toTableName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_detail); Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar_task_detail); setSupportActionBar(mToolbar); ActionBar mActionBar = getSupportActionBar(); mActionBar.setTitle("报课任务详情"); mActionBar.setDisplayHomeAsUpEnabled(true); toTableName = TableCourseMultiline.class.getSimpleName(); // workNumber = getSharedPreferences(ConstantStr.USER_INFORMATION, MODE_PRIVATE).getString(ConstantStr.USER_WORK_NUMBER, ""); relativeTable = getIntent().getStringExtra("relativeTable"); Loger.i("TAG", "relativeTable" + relativeTable); dbHelper = new CourseDBHelper(this); initWidgetValue(); } // 初始化控件数据 private void initWidgetValue() { tvTaskTerm = (TextView) findViewById(R.id.tv_task_detail_term); tvTeacherDeadline = (TextView) findViewById(R.id.tv_task_detail_teacher_deadline); tvDepartmentDeadline = (TextView) findViewById(R.id.tv_task_detail_department_deadline); // tvTaskRemark = (TextView) findViewById(R.id.tv_task_detail_remark); tvTaskState = (TextView) findViewById(R.id.tv_task_detail_state); tvTaskName = (TextView) findViewById(R.id.tv_task_detail_name); cardvTaskDetail = (CardView) findViewById(R.id.cardv_task_detail); cardvTaskDetail.setOnClickListener(this); Loger.d("relativeTable", relativeTable); task = dbHelper.findById(relativeTable, TableTaskInfo.class); Loger.d("TAG", task.toString()); taskTerm = task.getYear() + task.getSemester(); tvTaskTerm.setText(taskTerm); tvDepartmentDeadline.setText(task.getDepartmentDeadline()); tvTeacherDeadline.setText(task.getTeacherDeadline()); tvTaskState.setText(TaskListActivity.taskStateMap(task.getTaskState())); taskName = TaskListActivity.transferTableNameToChinese(task.getRelativeTable()); tvTaskName.setText(taskName); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.task_detail_activity_actions, menu); return true; } // 标题栏图标点击事件 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_export_file: final SimpleDialog notificationDialog = new SimpleDialog(TaskDetailActivity.this); notificationDialog.title("是否导出文件") .positiveAction("确定") .positiveActionClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notificationDialog.cancel(); progress = new ProgressDialog(TaskDetailActivity.this); progress.setMessage("导出中..."); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); progress.setCancelable(false); progress.show(); new Thread() { @Override public void run() { try { exportFile(); sendToast("导出成功"); } catch (Exception e) { e.printStackTrace(); sendToast("导出失败"); } finally { closeProgress(); } } }.start(); } }).negativeAction("取消") .negativeActionClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notificationDialog.cancel(); } }).show(); return true; default: return super.onOptionsItemSelected(item); } } private void closeProgress() { runOnUiThread(new Runnable() { @Override public void run() { progress.cancel(); } }); } public void sendToast(final String message) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(TaskDetailActivity.this, message, Toast.LENGTH_SHORT).show(); } }); } //导出文件 private void exportFile() throws Exception { filePath = Environment.getExternalStorageDirectory().getAbsoluteFile().toString() + "/" + tvTaskName.getText().toString(); tableName = task.getRelativeTable(); dbHelper.dropTable(toTableName); dbHelper.changeTableName(tableName, toTableName); copyExcel(dbHelper.findAll(TableCourseMultiline.class)); dbHelper.changeTableName(toTableName, tableName); } public void copyExcel(List<TableCourseMultiline> list) throws IOException, BiffException, WriteException { //删除空表的前三行会出问题,暂时解决办法是删除表格的前三行 list.remove(0); list.remove(0); list.remove(0); File file = new File(filePath + ".xls"); InputStream ins = getResources().openRawResource(R.raw.blank_table); OutputStream os = new FileOutputStream(file); int bytesRead; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); Workbook book = Workbook.getWorkbook(file); Sheet sheet = book.getSheet(0); // 获取行 int row = sheet.getRows(); System.out.println(row); int column; WritableWorkbook wbook = Workbook.createWorkbook(file, book); // 根据book创建一个操作对象 WritableSheet sh = wbook.getSheet(0);// 得到一个工作对象 CellFormat cellFormat; if (!sh.getCell(0, 1).getContents().equals("")) { cellFormat = sh.getCell(0, 1).getCellFormat(); } else { cellFormat = sh.getCell(0, 2).getCellFormat(); } WritableCellFormat cellFormatLeft = new WritableCellFormat(cellFormat);//相同格式,左对齐 cellFormatLeft.setAlignment(Alignment.LEFT); WritableCellFormat cellFormatCenter = new WritableCellFormat(cellFormat);//相同格式,居中 cellFormatCenter.setAlignment(Alignment.CENTRE); //设置excel表格标题 String term = taskTerm.substring(4, 6); if (term.equals("01")) { term = "上学期"; } else if (term.equals("02")) { term = "下学期"; } excelTitle = taskTerm.substring(0, 4) + "学年" + term + taskName + "开课计划书"; Label label = new Label(0, 0, excelTitle, sh.getCell(0, 0).getCellFormat()); sh.addCell(label); // 从最后一行开始加 for (int i = 0; i < list.size(); i++, row++) { column = 0; label = new Label(column++, row, list.get(i).getGrade(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getMajor(), cellFormatLeft); sh.addCell(label); label = new Label(column++, row, list.get(i).getPeople(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getCourseName(), cellFormatLeft); sh.addCell(label); label = new Label(column++, row, list.get(i).getCourseType(), cellFormatLeft); sh.addCell(label); label = new Label(column++, row, list.get(i).getCourseCredit(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getCourseHour(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getPracticeHour(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getOnMachineHour(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getTimePeriod(), cellFormatCenter); sh.addCell(label); label = new Label(column++, row, list.get(i).getTeacherName(), cellFormatLeft); sh.addCell(label); label = new Label(column++, row, list.get(i).getRemark(), cellFormatLeft); sh.addCell(label); } wbook.write(); wbook.close(); } // 点击查看文件跳转逻辑 @Override public void onClick(View v) { Intent intent = new Intent(TaskDetailActivity.this, ExcelDisplayActivity.class); intent.putExtra("tableName", task.getRelativeTable()); startActivity(intent); } }
package unlinked; import java.util.ArrayList; public class Vehicle { private String VSAMP; private String SAMPN; private String VEHNO; private String YEAR; private String BODY; private String O_BODY; private String FUEL; private String O_FUEL; private String EZPAS; private String CNTV; private String O_CNTV; private String HH1; private String HH_WHT2; public Vehicle(ArrayList<String>attributes) { setVSAMP(attributes.get(0)); setSAMPN(attributes.get(1)); setVEHNO(attributes.get(2)); setYEAR(attributes.get(3)); setBODY(attributes.get(4)); setO_BODY(attributes.get(5)); setFUEL(attributes.get(6)); setO_FUEL(attributes.get(7)); setEZPAS(attributes.get(8)); setCNTV(attributes.get(9)); setO_CNTV(attributes.get(10)); setHH1(attributes.get(11)); setHH_WHT2(attributes.get(12)); } public String getVSAMP() { return VSAMP; } public void setVSAMP(String vSAMP) { VSAMP = vSAMP; } public String getSAMPN() { return SAMPN; } public void setSAMPN(String sAMPN) { SAMPN = sAMPN; } public String getVEHNO() { return VEHNO; } public void setVEHNO(String vEHNO) { VEHNO = vEHNO; } public String getYEAR() { return YEAR; } public void setYEAR(String yEAR) { YEAR = yEAR; } public String getBODY() { return BODY; } public void setBODY(String bODY) { BODY = bODY; } public String getO_BODY() { return O_BODY; } public void setO_BODY(String o_BODY) { O_BODY = o_BODY; } public String getFUEL() { return FUEL; } public void setFUEL(String fUEL) { FUEL = fUEL; } public String getO_FUEL() { return O_FUEL; } public void setO_FUEL(String o_FUEL) { O_FUEL = o_FUEL; } public String getEZPAS() { return EZPAS; } public void setEZPAS(String eZPAS) { EZPAS = eZPAS; } public String getCNTV() { return CNTV; } public void setCNTV(String cNTV) { CNTV = cNTV; } public String getO_CNTV() { return O_CNTV; } public void setO_CNTV(String o_CNTV) { O_CNTV = o_CNTV; } public String getHH1() { return HH1; } public void setHH1(String hH1) { HH1 = hH1; } public String getHH_WHT2() { return HH_WHT2; } public void setHH_WHT2(String hH_WHT2) { HH_WHT2 = hH_WHT2; } }
/* * Copyright by Deppon and the original author or authors. * * This document only allow internal use ,Any of your behaviors using the file * not internal will pay legal responsibility. * * You may learn more information about Deppon from * * * http://www.deppon.com * */ package com.goodhealth.framework.session; import com.alibaba.fastjson.JSONObject; import com.goodhealth.comm.util.StringUtil; import com.goodhealth.comm.util.restful.HttpUtil; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; /** * @描述:session 信息 */ public class SessionInfo implements Serializable { private static final long serialVersionUID = 6029657754584291179L; /** * 创建时间 */ private long createtime; /** * 最后使用时间 */ private long lastusetime; /** * session过期时间 */ private int timeout; /** * 客户端ip */ private String clientIp; /** * SessionInfo */ private SessionInfo(){ } /** * 创建sessionInfo * @param request * @return */ static SessionInfo create(HttpServletRequest request) { SessionInfo sessionInfo = null; try{ sessionInfo = new SessionInfo(); // 客户端IP sessionInfo.setClientIp(HttpUtil.getUserClientIp(request)); // session创建时间 sessionInfo.setCreatetime(System.currentTimeMillis()); // 最后更新时间 sessionInfo.setLastusetime(System.currentTimeMillis()); // session过期时间 int timeout = 1000; String timeoutOfConfig = "framework.session.timeout"; if(StringUtil.isNotEmpty(timeoutOfConfig)){ timeout = Integer.valueOf(timeoutOfConfig); } sessionInfo.setTimeout(timeout); }catch (Exception e) { e.printStackTrace(); } return sessionInfo; } /** * json数据转换为SessionInfo * @param * @param json */ static SessionInfo conversionFromJson(String json){ SessionInfo sessionInfo = null; try{ sessionInfo = JSONObject.parseObject(json, SessionInfo.class); }catch (Exception e) { e.printStackTrace(); } return sessionInfo; } /** * 是否过期 * @return */ boolean isTimeout(){ long t1 = System.currentTimeMillis()-this.lastusetime; long t2 = ((long)this.timeout) * 1000; if(t1>t2){ return true; }else{ return false; } } public long getCreatetime() { return createtime; } public void setCreatetime(long createtime) { this.createtime = createtime; } public long getLastusetime() { return lastusetime; } public void setLastusetime(long lastusetime) { this.lastusetime = lastusetime; } public void updateLastUseTime() { this.lastusetime = System.currentTimeMillis(); } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getClientIp() { return clientIp; } public void setClientIp(String clientIp) { this.clientIp = clientIp; } }
package com.it.userportrait.analy; import java.util.Date; import java.util.List; public class UserGroupEntity { private long userid; private Date ordertime; private String productTypeId; private double amount; private String groupField; private List<UserGroupEntity> list; private double avgAmount;// private double maxAmount; private int avgdays;// private long dianZiNums; private long shenghuoNums; private long huwaiNums; private long time1;//7-12 1 private long time2;//13-19 2 private long time3;//20-24 3 private long time4;//0-6 4 private Point centerPoint; private long numbers; private long timeinfo; public long getTimeinfo() { return timeinfo; } public void setTimeinfo(long timeinfo) { this.timeinfo = timeinfo; } public Point getCenterPoint() { return centerPoint; } public void setCenterPoint(Point centerPoint) { this.centerPoint = centerPoint; } public long getNumbers() { return numbers; } public void setNumbers(long numbers) { this.numbers = numbers; } public long getTime1() { return time1; } public void setTime1(long time1) { this.time1 = time1; } public long getTime2() { return time2; } public void setTime2(long time2) { this.time2 = time2; } public long getTime3() { return time3; } public void setTime3(long time3) { this.time3 = time3; } public long getTime4() { return time4; } public void setTime4(long time4) { this.time4 = time4; } public long getDianZiNums() { return dianZiNums; } public void setDianZiNums(long dianZiNums) { this.dianZiNums = dianZiNums; } public long getShenghuoNums() { return shenghuoNums; } public void setShenghuoNums(long shenghuoNums) { this.shenghuoNums = shenghuoNums; } public long getHuwaiNums() { return huwaiNums; } public void setHuwaiNums(long huwaiNums) { this.huwaiNums = huwaiNums; } public double getAvgAmount() { return avgAmount; } public void setAvgAmount(double avgAmount) { this.avgAmount = avgAmount; } public double getMaxAmount() { return maxAmount; } public void setMaxAmount(double maxAmount) { this.maxAmount = maxAmount; } public int getAvgdays() { return avgdays; } public void setAvgdays(int avgdays) { this.avgdays = avgdays; } public List<UserGroupEntity> getList() { return list; } public void setList(List<UserGroupEntity> list) { this.list = list; } public long getUserid() { return userid; } public void setUserid(long userid) { this.userid = userid; } public Date getOrdertime() { return ordertime; } public void setOrdertime(Date ordertime) { this.ordertime = ordertime; } public String getProductTypeId() { return productTypeId; } public void setProductTypeId(String productTypeId) { this.productTypeId = productTypeId; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getGroupField() { return groupField; } public void setGroupField(String groupField) { this.groupField = groupField; } }
package com.tt.miniapp.impl; import android.app.Application; import android.content.Context; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.host.HostDependManager; import com.tt.option.g.b; import com.tt.option.g.c; public class HostOptionFavoriteDependImpl implements c { public void firstFavoriteAction() { String str; Application application = AppbrandContext.getInst().getApplicationContext(); if (AppbrandContext.getInst().isGame()) { str = (HostDependManager.getInst().getHostCustomFavoriteEntity((Context)application)).h; } else { str = (HostDependManager.getInst().getHostCustomFavoriteEntity((Context)application)).g; } HostDependManager.getInst().showToast((Context)application, null, str, 0L, "success"); } public b getHostCustomFavoriteEntity(Context paramContext) { return (new b.a(paramContext)).a(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\impl\HostOptionFavoriteDependImpl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example; /** * Created by shivam on 27/02/16. */ public interface IAfterLoginActions { public void showNextScreen(String message); public void showFailedScreen(String reason); }
package com.tencent.mm.plugin.chatroom.ui; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import com.tencent.mm.storage.bd; class SelectMemberChattingRecordUI$1 implements OnItemClickListener { final /* synthetic */ SelectMemberChattingRecordUI hPm; SelectMemberChattingRecordUI$1(SelectMemberChattingRecordUI selectMemberChattingRecordUI) { this.hPm = selectMemberChattingRecordUI; } public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { bd bdVar = (bd) SelectMemberChattingRecordUI.a(this.hPm).getItem(i); if (bdVar != null) { SelectMemberChattingRecordUI.a(this.hPm, bdVar.field_msgId); } } }
package com.tencent.mm.plugin.brandservice.b; import com.tencent.mm.ab.b; import com.tencent.mm.ab.b.a; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.q; import com.tencent.mm.protocal.c.ai; import com.tencent.mm.protocal.c.blm; import com.tencent.mm.protocal.c.bln; import com.tencent.mm.protocal.c.ix; import com.tencent.mm.sdk.platformtools.x; import java.util.LinkedList; import java.util.List; public final class k extends l implements com.tencent.mm.network.k { private final b diG; private e diJ; public k(List<ix> list) { a aVar = new a(); aVar.dIG = new blm(); aVar.dIH = new bln(); aVar.uri = "/cgi-bin/micromsg-bin/setapplist"; aVar.dIF = 386; aVar.dII = 0; aVar.dIJ = 0; this.diG = aVar.KT(); blm blm = (blm) this.diG.dID.dIL; LinkedList linkedList = new LinkedList(); for (ix ixVar : list) { ai aiVar = new ai(); aiVar.hbL = ixVar.userName; linkedList.add(aiVar); } blm.hbF = linkedList.size(); blm.hbG = linkedList; x.i("MicroMsg.BrandService.NetSceneSetAppList", "info: upload size %d, toString %s", new Object[]{Integer.valueOf(linkedList.size()), linkedList.toString()}); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { x.i("MicroMsg.BrandService.NetSceneSetAppList", "on scene end code(%d, %d)", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3)}); if (i2 == 0 && i3 == 0) { x.i("MicroMsg.BrandService.NetSceneSetAppList", "ok, hash code is %d", new Object[]{Integer.valueOf(((bln) this.diG.dIE.dIL).rEY)}); com.tencent.mm.plugin.brandservice.a.g(196610, Integer.valueOf(r0.rEY)); com.tencent.mm.plugin.brandservice.a.g(196611, Boolean.valueOf(false)); } else { com.tencent.mm.plugin.brandservice.a.g(196611, Boolean.valueOf(true)); } this.diJ.a(i2, i3, str, this); } public final int getType() { return 386; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; x.i("MicroMsg.BrandService.NetSceneSetAppList", "do scene"); return a(eVar, this.diG, this); } }
package com.rc.tasks; /** * Created by song on 14/06/2017. */ public class MessageResendTask { ResendTaskCallback listener; public void setListener(ResendTaskCallback listener) { this.listener = listener; } public void execute(String messageId) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(listener.getTime()); listener.onNeedResend(messageId); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }
package scripts; import java.awt.*; import org.tribot.api2007.Inventory; import org.tribot.api2007.types.RSItem; import javax.swing.*; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.URI; /** * Created by Apothum (https://tribot.org/forums/user/220199-apothum/) on 4/19/2015. */ public class AWGui extends JFrame { private AWGui myFrame; public AWGui() { myFrame = this; Variables.isOpen = true; myFrame.$$$setupUI$$$(); comboBox1.addItem("Rune"); comboBox1.addItem("Adamant"); comboBox1.addItem("Steel"); comboBox1.addItem("Iron"); comboBox1.addItem("Bronze"); comboBox1.addItem("Mithril"); comboBox2.addItem("Both"); comboBox2.addItem("Low Level"); comboBox2.addItem("High Level"); spinner1.setValue(350); getFoodIDButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RSItem[] food = Inventory.getAll(); if (food.length < 1) { return; } foodnameid.setText(food[0].getDefinition().getName()); Variables.foodID = food[0].getID(); } }); supportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(URI.create("https://tribot.org/forums/index.php?app=members&module=messaging&section=send&do=form&fromMemberID=220199")); } catch (IOException e1) { e1.printStackTrace(); } } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Variables.tokenToStart = (int) spinner1.getValue(); switch (comboBox2.getSelectedItem().toString()) { case "Both": Variables.cylclopsID = Variables.cyclopsBoth; break; case "Low Level": Variables.cylclopsID = Variables.cyclopsLowID; break; case "High Level": Variables.cylclopsID = Variables.cyclopsHighID; break; } switch (comboBox1.getSelectedItem().toString()) { case "Rune": Variables.armourID = Variables.runeArmourID; Variables.animatedID = Variables.rune; break; case "Adamant": Variables.armourID = Variables.addyArmourID; Variables.animatedID = Variables.addy; break; case "Steel": Variables.armourID = Variables.steelArmourID; Variables.animatedID = Variables.steel; break; case "Iron": Variables.armourID = Variables.ironArmourID; Variables.animatedID = Variables.iron; break; case "Bronze": Variables.armourID = Variables.bronzeArmourID; Variables.animatedID = Variables.bronze; break; case "Mithril": Variables.armourID = Variables.mithArmourID; Variables.animatedID = Variables.mith; break; } Variables.isOpen = false; } }); } public static void main(String[] args) { } public void InstantiateGUI() { this.setContentPane(new AWGui().panel); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.pack(); this.setVisible(true); } public JPanel panel; private JComboBox comboBox1; private JButton startButton; private JButton getFoodIDButton; private JLabel foodnameid; private JButton supportButton; private JSpinner spinner1; private JComboBox comboBox2; { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { panel = new JPanel(); panel.setLayout(new GridBagLayout()); final JLabel label1 = new JLabel(); label1.setText("Select Armour Type"); GridBagConstraints gbc; gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; panel.add(label1, gbc); comboBox1 = new JComboBox(); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 0; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(comboBox1, gbc); final JLabel label2 = new JLabel(); label2.setText("Food to eat (Place in first inventory slot): "); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 1; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; panel.add(label2, gbc); startButton = new JButton(); startButton.setText("Start"); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 4; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(startButton, gbc); getFoodIDButton = new JButton(); getFoodIDButton.setText("GetFood"); gbc = new GridBagConstraints(); gbc.gridx = 2; gbc.gridy = 1; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(getFoodIDButton, gbc); foodnameid = new JLabel(); foodnameid.setText("null"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 1; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; panel.add(foodnameid, gbc); supportButton = new JButton(); supportButton.setText("Message Author"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 4; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(supportButton, gbc); final JLabel label3 = new JLabel(); label3.setText("Tokens to Start"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; panel.add(label3, gbc); spinner1 = new JSpinner(); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 2; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(spinner1, gbc); final JLabel label4 = new JLabel(); label4.setText("Cyclops attack preference"); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 3; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; panel.add(label4, gbc); comboBox2 = new JComboBox(); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.gridy = 3; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(comboBox2, gbc); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return panel; } }
package com.accp.domain; public class Trademark { private String trkid; private String trkname; private String trkzimu; public String getTrkid() { return trkid; } public void setTrkid(String trkid) { this.trkid = trkid; } public String getTrkname() { return trkname; } public void setTrkname(String trkname) { this.trkname = trkname; } public String getTrkzimu() { return trkzimu; } public void setTrkzimu(String trkzimu) { this.trkzimu = trkzimu; } }
package com.jim.multipos.ui.customers; import com.jim.multipos.core.Presenter; public interface CustomersActivityPresenter extends Presenter { }
package com.xuecheng.framework.advice; import com.google.common.collect.ImmutableMap; import com.xuecheng.framework.exception.CustomerException; import com.xuecheng.framework.model.response.CommonCode; import com.xuecheng.framework.model.response.ResponseResult; import com.xuecheng.framework.model.response.ResultCode; import lombok.extern.slf4j.Slf4j; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @Slf4j @ControllerAdvice//增强启动器 public class ExceptionCatch { private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTION; protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder(); //捕获 CustomException异常 @ExceptionHandler(CustomerException.class) @ResponseBody//返回json串 public ResponseResult handlerRunTimeException(CustomerException e) { log.error("catch exception:{}", e.getResultCode().message()); return new ResponseResult(e.getResultCode()); } @ExceptionHandler(Exception.class) @ResponseBody public ResponseResult handlerException(Exception e) { log.error("catch exception:{}", e.getMessage()); if (EXCEPTION == null) { EXCEPTION = builder.build(); } ResultCode resultCode = EXCEPTION.get(e.getClass()); final ResponseResult responseResult; if (resultCode != null) { responseResult = new ResponseResult(resultCode); } else { responseResult = new ResponseResult(CommonCode.SERVER_ERROR); } return responseResult; } static { //在这里添加一些基础的异常类型判断 builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM); } }
package com.smxknife.java2.thread.executorservice.demo03; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/3/6 */ public class _Run2_ThreadPoolMonitor { public static void main(String[] args) throws InterruptedException { _Run2_ThreadPoolMonitor run = new _Run2_ThreadPoolMonitor(); TimeUnit.SECONDS.sleep(15); // 为了打开jvisualvm run.test(); } private void test() { ExecutorService service = ThreadPoolMonitor.newFixedThreadPool(5, "test"); for (int i = 0; i < 100; i++) { service.execute(this::cycle); } } private void cycle() { System.out.println("---- " + Thread.currentThread().getName()); new Thread(() -> { System.out.println("**** " + Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } }, "inner-thread").run(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }
package service; import dto.BookDetailsDto; import exceptions.BookNotFoundException; public interface BookService { public BookDetailsDto getBookById(long id); public long getBooksByAuthor(String author); public BookDetailsDto createNewBook(String title, String author); public BookDetailsDto updateBook(long id, String updatedTitle, String updatedAuthor); public void deleteBook(long id); }
package com.designPattern.SOLID.srp.solution; public class NotificationService { public void sendOTP(String medium) { if(medium.equals("email")) { // SEND OTP ON EMAIL } else if(medium.equals("mobile")) { // SEND OTP ON MOBILE } } }
package com.cg.ibs.spmgmt.bean; import java.time.LocalDate; import java.util.Arrays; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; @Entity public class SPCustomerData { private Double billAmount; private LocalDate billDate; private LocalDate dueDate; private String status="Pending"; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Id @GeneratedValue(strategy = GenerationType.AUTO) Integer id; @ManyToOne(targetEntity = ServiceProvider.class) private ServiceProvider serviceProvider; private String spcId; public Double getBillAmount() { return billAmount; } public LocalDate getBillDate() { return billDate; } public LocalDate getDueDate() { return dueDate; } public Integer getId() { return id; } public ServiceProvider getServiceProvider() { return serviceProvider; } public String getSpcId() { return spcId; } public void setBillAmount(Double billAmount) { this.billAmount = billAmount; } public void setBillDate(LocalDate billDate) { this.billDate = billDate; } public void setDueDate(LocalDate dueDate) { this.dueDate = dueDate; } public void setId(Integer id) { this.id = id; } public void setServiceProvider(ServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; } public void setSpcId(String spcId) { this.spcId = spcId; } @Override public String toString() { return "SPCustomerData [id=" + id + ", serviceProvider=" + serviceProvider + ", dueDate=" + dueDate + ", billDate=" + billDate + ", billAmount=" + billAmount + ", spcId=" + spcId + "]"; } }
import java.util.Scanner; class mes_case { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int mes; System.out.println("Digite o mes de 1 a 12 "); mes = sc.nextInt(); switch (mes) { case 1: System.out.println("O mes = Janeiro"); break; case 2: System.out.println("O mes = Fevereiro"); break; case 3: System.out.println("O mes = Marco"); break; case 4: System.out.println("O mes = Abril"); break; case 5: System.out.println("O mes = Maio"); break; case 6: System.out.println("O mes = Junho"); break; case 7: System.out.println("O mes = Julho"); break; case 8: System.out.println("O mes = Agosto"); break; case 9: System.out.println("O mes = Setembro"); break; case 10: System.out.println("O mes = Outubro"); break; case 11: System.out.println("O mes = Novembro"); break; case 12: System.out.println("O mes = Dezembro"); break; default: System.out.println("O mes nao EXISTE"); } sc.close(); } }
package com.example.lnctmeet.view; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.lnctmeet.R; import com.example.lnctmeet.adapters.CategoryFragmentPagerAdapter; import com.example.lnctmeet.model.Post; import com.example.lnctmeet.preferences.UserSessionManager; import com.example.lnctmeet.utils.Constants; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.android.material.tabs.TabLayout; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity { //RetrofitService service; UserSessionManager userSessionManager; HashMap<String,String>details; String name; RecyclerView recyclerView; Query q1; ViewPager viewPager; TabLayout tablayout; Toolbar toolbar; private static final String TAG_NAME = MainActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //service= ApiClient.getClient().create(RetrofitService.class); setUpUIViews(); if (userSessionManager.checkLogin()) finish(); //setting toolbar in place of actionbar setSupportActionBar(toolbar); details = userSessionManager.getUserDetails(); name = details.get(UserSessionManager.KEY_NAME); toolbar.setTitle(name); tablayout.setupWithViewPager(viewPager); // Set gravity for tab bar tablayout.setTabGravity(TabLayout.GRAVITY_FILL); // Set category fragment pager adapter CategoryFragmentPagerAdapter pagerAdapter = new CategoryFragmentPagerAdapter(this, getSupportFragmentManager()); // Set the pager adapter onto the view pager viewPager.setAdapter(pagerAdapter); } public String sendData(){ return userSessionManager.getUserDetails().get(UserSessionManager.KEY_LOGIN); } void setUpUIViews() { // recyclerView = findViewById(R.id.recycler); userSessionManager=new UserSessionManager(this); recyclerView = findViewById(R.id.recycler_view); viewPager = findViewById(R.id.view_pager); // Give the TabLayout the ViewPager tablayout = findViewById(R.id.tabs); toolbar=(Toolbar) findViewById(R.id.toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main,menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.action_logout: userSessionManager.logoutUser(); break; case R.id.action_bookmark: startActivity(new Intent(MainActivity.this,SavedActivity.class)); break; } return super.onOptionsItemSelected(item); } }
package rontikeky.beraspakone.konfirmasi; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import java.util.List; import rontikeky.beraspakone.R; import rontikeky.beraspakone.kurir.KurirAdapter; import rontikeky.beraspakone.pembayaran.AtmAdapter; import rontikeky.beraspakone.pembayaran.responseAtm; /** * A simple {@link Fragment} subclass. */ public class stepThree extends Fragment { private RecyclerView rvAtm; private RecyclerView.LayoutManager mAtmLayoutManager; private RecyclerView.Adapter mAtmAdapter; protected Context mCtx; List<responseAtm> mAtm; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_step_three, container, false); rvAtm = view.findViewById(R.id.rvAtm); rvAtm.setHasFixedSize(true); mAtmLayoutManager = new GridLayoutManager(mCtx, 2); rvAtm.setLayoutManager(mAtmLayoutManager); mAtmAdapter = new AtmAdapter(); Log.d("Adapter", String.valueOf(mAtmAdapter)); rvAtm.setAdapter(mAtmAdapter); rvAtm.setVisibility(View.VISIBLE); return view; } @Override public void onAttach(Context mCtx) { super.onAttach(mCtx); this.mCtx = mCtx; } }
package info.blockchain.wallet.payload; import com.blockchain.api.services.NonCustodialBitcoinService; import com.blockchain.api.bitcoin.data.BalanceDto; import com.blockchain.api.bitcoin.data.MultiAddress; import info.blockchain.wallet.ImportedAddressHelper; import info.blockchain.wallet.WalletApiMockedResponseTest; import info.blockchain.wallet.exceptions.HDWalletException; import info.blockchain.wallet.exceptions.InvalidCredentialsException; import info.blockchain.wallet.exceptions.ServerConnectionException; import info.blockchain.wallet.exceptions.UnsupportedVersionException; import info.blockchain.wallet.keys.SigningKey; import info.blockchain.wallet.keys.SigningKeyImpl; import info.blockchain.wallet.multiaddress.MultiAddressFactoryBtc; import info.blockchain.wallet.multiaddress.TransactionSummary; import info.blockchain.wallet.multiaddress.TransactionSummary.TransactionType; import info.blockchain.wallet.payload.data.Account; import info.blockchain.wallet.payload.data.ImportedAddress; import info.blockchain.wallet.payload.data.Wallet; import info.blockchain.wallet.payload.data.XPub; import info.blockchain.wallet.payload.data.XPubs; import retrofit2.Call; import org.bitcoinj.core.Base58; import org.bitcoinj.core.ECKey; import org.bitcoinj.crypto.DeterministicKey; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.MockitoAnnotations; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class PayloadManagerTest extends WalletApiMockedResponseTest { private final NonCustodialBitcoinService bitcoinApi = mock(NonCustodialBitcoinService.class); private PayloadManager payloadManager; @Before public void setup() { MockitoAnnotations.initMocks(this); payloadManager = new PayloadManager( walletApi, bitcoinApi, new MultiAddressFactoryBtc(bitcoinApi), new BalanceManagerBtc(bitcoinApi), new BalanceManagerBch(bitcoinApi) ); } @Test public void getInstance() { assertNotNull(payloadManager); } @Test public void create_v3() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockInterceptor.setResponseStringList(responseList); mockEmptyBalance(bitcoinApi); payloadManager.create( "My HDWallet", "name@email.com", "SomePassword", false ); Wallet walletBody = payloadManager .getPayload(); assertEquals(36, walletBody.getGuid().length());//GUIDs are 36 in length assertEquals("My HDWallet", walletBody.getWalletBody().getAccounts().get(0).getLabel()); assertEquals(1, walletBody.getWalletBody().getAccounts().size()); assertEquals(5000, walletBody.getOptions().getPbkdf2Iterations()); assertEquals(600000, walletBody.getOptions().getLogoutTime()); assertEquals(10000, walletBody.getOptions().getFeePerKb()); } @Test(expected = ServerConnectionException.class) public void create_ServerConnectionException() throws Exception { mockInterceptor.setResponseString("Save failed."); mockInterceptor.setResponseCode(500); payloadManager.create( "My HDWallet", "name@email.com", "SomePassword", true ); } @Test public void recoverFromMnemonic_v3() throws Exception { String mnemonic = "all all all all all all all all all all all all"; LinkedList<String> responseList = new LinkedList<>(); responseList.add("HDWallet successfully synced with server"); mockInterceptor.setResponseStringList(responseList); //Responses for checking how many accounts to recover String balance1 = loadResourceContent("balance/wallet_all_balance_1.txt"); Call<Map<String, BalanceDto>> balanceResponse1 = makeBalanceResponse(balance1); String balance2 = loadResourceContent("balance/wallet_all_balance_2.txt"); Call<Map<String, BalanceDto>> balanceResponse2 = makeBalanceResponse(balance2); String balance3 = loadResourceContent("balance/wallet_all_balance_3.txt"); Call<Map<String, BalanceDto>> balanceResponse3 = makeBalanceResponse(balance3); when(bitcoinApi.getBalance(any(String.class), any(), any(), any())) .thenReturn(balanceResponse1) .thenReturn(balanceResponse2) .thenReturn(balanceResponse3); payloadManager.recoverFromMnemonic( mnemonic, "My HDWallet", "name@email.com", "SomePassword", false ); Wallet walletBody = payloadManager .getPayload(); assertEquals(36, walletBody.getGuid().length());//GUIDs are 36 in length assertEquals("My HDWallet", walletBody.getWalletBody().getAccounts().get(0).getLabel()); assertEquals("0660cc198330660cc198330660cc1983", walletBody.getWalletBody().getSeedHex()); assertEquals(10, walletBody.getWalletBody().getAccounts().size()); assertEquals(5000, walletBody.getOptions().getPbkdf2Iterations()); assertEquals(600000, walletBody.getOptions().getLogoutTime()); assertEquals(10000, walletBody.getOptions().getFeePerKb()); } @Test(expected = ServerConnectionException.class) public void recoverFromMnemonic_ServerConnectionException_v3() throws Exception { String mnemonic = "all all all all all all all all all all all all"; LinkedList<String> responseList = new LinkedList<>(); responseList.add("Save failed"); mockInterceptor.setResponseStringList(responseList); //checking if xpubs has txs succeeds but then savinf fails LinkedList<Integer> codes = new LinkedList<>(); codes.add(500); mockInterceptor.setResponseCodeList(codes); //Responses for checking how many accounts to recover String balance1 = loadResourceContent("balance/wallet_all_balance_1.txt"); Call<Map<String, BalanceDto>> balanceResponse1 = makeBalanceResponse(balance1); String balance2 = loadResourceContent("balance/wallet_all_balance_2.txt"); Call<Map<String, BalanceDto>> balanceResponse2 = makeBalanceResponse(balance2); String balance3 = loadResourceContent("balance/wallet_all_balance_3.txt"); Call<Map<String, BalanceDto>> balanceResponse3 = makeBalanceResponse(balance3); when(bitcoinApi.getBalance(any(String.class), any(), any(), any())) .thenReturn(balanceResponse1) .thenReturn(balanceResponse2) .thenReturn(balanceResponse3); payloadManager.recoverFromMnemonic( mnemonic, "My HDWallet", "name@email.com", "SomePassword", false ); Wallet walletBody = payloadManager .getPayload(); assertEquals(36, walletBody.getGuid().length());//GUIDs are 36 in length assertEquals("My HDWallet", walletBody.getWalletBody().getAccounts().get(0).getLabel()); assertEquals("0660cc198330660cc198330660cc1983", walletBody.getWalletBody().getSeedHex()); assertEquals(10, walletBody.getWalletBody().getAccounts().size()); assertEquals(5000, walletBody.getOptions().getPbkdf2Iterations()); assertEquals(600000, walletBody.getOptions().getLogoutTime()); assertEquals(10000, walletBody.getOptions().getFeePerKb()); } @Test(expected = UnsupportedVersionException.class) public void initializeAndDecrypt_unsupported_version_v4() throws Exception { String walletBase = loadResourceContent("wallet_v5_unsupported.txt"); mockInterceptor.setResponseString(walletBase); payloadManager.initializeAndDecrypt( "any_shared_key", "any_guid", "SomeTestPassword", true ); } @Test public void initializeAndDecrypt_v3() throws Exception { String walletBase = loadResourceContent("wallet_v3_3.txt"); LinkedList<String> responseList = new LinkedList<>(); responseList.add(walletBase); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.initializeAndDecrypt( "any", "any", "SomeTestPassword", false ); } @Test public void initializeAndDecrypt_v4() throws Exception { String walletBase = loadResourceContent("wallet_v4_encrypted.txt"); LinkedList<String> responseList = new LinkedList<>(); responseList.add(walletBase); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.initializeAndDecrypt( "any", "any", "blockchain", true ); } @Test(expected = InvalidCredentialsException.class) public void initializeAndDecrypt_invalidGuid() throws Exception { String walletBase = loadResourceContent("invalid_guid.txt"); mockInterceptor.setResponseString(walletBase); mockInterceptor.setResponseCode(500); payloadManager.initializeAndDecrypt( "any", "any", "SomeTestPassword", false ); } @Test(expected = HDWalletException.class) public void save_HDWalletException() throws Exception { //Nothing to save payloadManager.save(); } @Test public void save_v3() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "SomePassword", false ); mockInterceptor.setResponseString("MyWallet save successful."); payloadManager.save(); } @Test public void save_v4() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "SomePassword", true ); mockInterceptor.setResponseString("MyWallet save successful."); payloadManager.save(); } @Test public void upgradeV2PayloadToV3() { // Tested in integration tests } @Test public void addAccount_v3() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "MyTestWallet", false ); assertEquals(1, payloadManager.getPayload().getWalletBody().getAccounts().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.addAccount("Some Label", null); assertEquals(2, payloadManager.getPayload().getWalletBody().getAccounts().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); payloadManager.addAccount("Some Label", null); assertEquals(3, payloadManager.getPayload().getWalletBody().getAccounts().size()); } @Test public void addLegacyAddress_v3() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "MyTestWallet", false ); assertEquals(0, payloadManager.getPayload().getImportedAddressList().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); payloadManager.addImportedAddress(ImportedAddressHelper.getImportedAddress()); assertEquals(1, payloadManager.getPayload().getImportedAddressList().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); payloadManager.addImportedAddress(ImportedAddressHelper.getImportedAddress()); assertEquals(2, payloadManager.getPayload().getImportedAddressList().size()); } @Test public void setKeyForLegacyAddress_v3() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "MyTestWallet", false ); assertEquals(0, payloadManager.getPayload().getImportedAddressList().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); payloadManager.addImportedAddress(ImportedAddressHelper.getImportedAddress()); assertEquals(1, payloadManager.getPayload().getImportedAddressList().size()); ImportedAddress importedAddressBody = payloadManager.getPayload() .getImportedAddressList().get(0); SigningKey key = new SigningKeyImpl( DeterministicKey.fromPrivate(Base58.decode(importedAddressBody.getPrivateKey())) ); importedAddressBody.setPrivateKey(null); mockInterceptor.setResponseString("MyWallet save successful."); payloadManager.setKeyForImportedAddress(key, null); } @Test public void setKeyForLegacyAddress_NoSuchAddressException() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "MyTestWallet", false ); assertEquals(0, payloadManager.getPayload().getImportedAddressList().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); payloadManager.addImportedAddress(ImportedAddressHelper.getImportedAddress()); assertEquals(1, payloadManager.getPayload().getImportedAddressList().size()); ImportedAddress existingImportedAddressBody = payloadManager.getPayload() .getImportedAddressList().get(0); //Try non matching ECKey SigningKey key = new SigningKeyImpl(new ECKey()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); ImportedAddress newlyAdded = payloadManager .setKeyForImportedAddress(key, null); //Ensure new address is created if no match found assertNotNull(newlyAdded); assertNotNull(newlyAdded.getPrivateKey()); assertNotNull(newlyAdded.getAddress()); assertNotEquals(existingImportedAddressBody.getPrivateKey(), newlyAdded.getPrivateKey()); assertNotEquals(existingImportedAddressBody.getAddress(), newlyAdded.getAddress()); } @Test public void setKeyForLegacyAddress_saveFail_revert() throws Exception { LinkedList<String> responseList = new LinkedList<>(); responseList.add("MyWallet save successful."); mockEmptyBalance(bitcoinApi); mockInterceptor.setResponseStringList(responseList); payloadManager.create( "My HDWallet", "name@email.com", "MyTestWallet", false ); assertEquals(0, payloadManager.getPayload().getImportedAddressList().size()); responseList = new LinkedList<>(); responseList.add("MyWallet save successful"); mockInterceptor.setResponseStringList(responseList); payloadManager.addImportedAddress(ImportedAddressHelper.getImportedAddress()); assertEquals(1, payloadManager.getPayload().getImportedAddressList().size()); ImportedAddress importedAddressBody = payloadManager.getPayload() .getImportedAddressList().get(0); SigningKey key = new SigningKeyImpl( DeterministicKey.fromPrivate(Base58.decode(importedAddressBody.getPrivateKey())) ); importedAddressBody.setPrivateKey(null); mockInterceptor.setResponseCode(500); mockInterceptor.setResponseString("Oops something went wrong"); payloadManager.setKeyForImportedAddress(key, null); // Ensure private key reverted on save fail assertNull(importedAddressBody.getPrivateKey()); } @Test public void getNextAddress_v3() throws Exception { String walletBase = loadResourceContent("wallet_v3_5.txt"); LinkedList<String> responseList = new LinkedList<>(); responseList.add(walletBase); mockInterceptor.setResponseStringList(responseList); mockEmptyBalance(bitcoinApi); String multi1 = loadResourceContent("multiaddress/wallet_v3_5_m1.txt"); Call<MultiAddress> multiResponse1 = makeMultiAddressResponse(multi1); String multi2 = loadResourceContent("multiaddress/wallet_v3_5_m2.txt"); Call<MultiAddress> multiResponse2 = makeMultiAddressResponse(multi2); String multi3 = loadResourceContent("multiaddress/wallet_v3_5_m3.txt"); Call<MultiAddress> multiResponse3 = makeMultiAddressResponse(multi3); String multi4 = loadResourceContent("multiaddress/wallet_v3_5_m4.txt"); Call<MultiAddress> multiResponse4 = makeMultiAddressResponse(multi4); when(bitcoinApi.getMultiAddress( any(String.class), any(), any(), eq(null), any(), any(Integer.class), any(Integer.class) )).thenReturn(multiResponse1) .thenReturn(multiResponse2) .thenReturn(multiResponse3) .thenReturn(multiResponse4); payloadManager.initializeAndDecrypt( "06f6fa9c-d0fe-403d-815a-111ee26888e2", "4750d125-5344-4b79-9cf9-6e3c97bc9523", "MyTestWallet", false ); Wallet wallet = payloadManager.getPayload(); // Reserve an address to ensure it gets skipped Account account = wallet.getWalletBody().getAccounts().get(0); account.addAddressLabel(1, "Reserved"); // set up indexes first payloadManager.getAccountTransactions( account.getXpubs(), 50, 0 ); // Next Receive String nextReceiveAddress = payloadManager.getNextReceiveAddress(account); assertEquals("1H9FdkaryqzB9xacDbJrcjXsJ9By4UVbQw", nextReceiveAddress); // Increment receive and check payloadManager.incrementNextReceiveAddress(account); nextReceiveAddress = payloadManager.getNextReceiveAddress(account); assertEquals("18DU2RjyadUmRK7sHTBHtbJx5VcwthHyF7", nextReceiveAddress); // Next Change String nextChangeAddress = payloadManager.getNextChangeAddress(account); assertEquals("1GEXfMa4SMh3iUZxP8HHQy7Wo3aqce72Nm", nextChangeAddress); // Increment Change and check payloadManager.incrementNextChangeAddress(account); nextChangeAddress = payloadManager.getNextChangeAddress(account); assertEquals("1NzpLHV6LLVFCYdYA5woYL9pHJ48KQJc9K", nextChangeAddress); } @Test public void balance() throws Exception { String walletBase = loadResourceContent("wallet_v3_6.txt"); LinkedList<String> responseList = new LinkedList<>(); responseList.add(walletBase); mockInterceptor.setResponseStringList(responseList); // Bitcoin String btcBalance = loadResourceContent("balance/wallet_v3_6_balance.txt"); Call<Map<String, BalanceDto>> btcResponse = makeBalanceResponse(btcBalance); when(bitcoinApi.getBalance( eq("btc"), any(), any(), any()) ).thenReturn(btcResponse); // Bitcoin Cash String bchBalance = loadResourceContent("balance/wallet_v3_6_balance.txt"); Call<Map<String, BalanceDto>> bchResponse = makeBalanceResponse(bchBalance); when(bitcoinApi.getBalance( eq("bch"), any(), any(), any()) ).thenReturn(bchResponse); payloadManager.initializeAndDecrypt( "any", "any", "MyTestWallet", false ); // 'All' wallet balance and transactions assertEquals(743071, payloadManager.getWalletBalance().longValue()); BigInteger balance = payloadManager.getImportedAddressesBalance(); // Imported addresses consolidated assertEquals(137505, balance.longValue()); // Account and address balances XPubs first = new XPubs( new XPub( "xpub6CdH6yzYXhTtR7UHJHtoTeWm3nbuyg9msj3rJvFnfMew9CBff6Rp62zdTrC57Spz4TpeRPL8m9xLiVaddpjEx4Dzidtk44rd4N2xu9XTrSV", XPub.Format.LEGACY ) ); assertEquals( BigInteger.valueOf(566349), payloadManager.getAddressBalance(first).toBigInteger() ); XPubs second = new XPubs( new XPub( "xpub6CdH6yzYXhTtTGPPL4Djjp1HqFmAPx4uyqoG6Ffz9nPysv8vR8t8PEJ3RGaSRwMm7kRZ3MAcKgB6u4g1znFo82j4q2hdShmDyw3zuMxhDSL", XPub.Format.LEGACY ) ); assertEquals( BigInteger.valueOf(39217), payloadManager.getAddressBalance(second).toBigInteger() ); XPubs third = new XPubs( new XPub( "189iKJLruPtUorasDuxmc6fMRVxz6zxpPS", XPub.Format.LEGACY ) ); assertEquals( BigInteger.valueOf(137505), payloadManager.getAddressBalance(third).toBigInteger() ); } @Test public void getAccountTransactions() throws Exception { //guid 5350e5d5-bd65-456f-b150-e6cc089f0b26 String walletBase = loadResourceContent("wallet_v3_6.txt"); LinkedList<String> responseList = new LinkedList<>(); responseList.add(walletBase); mockInterceptor.setResponseStringList(responseList); // Bitcoin String btcBalance = loadResourceContent("balance/wallet_v3_6_balance.txt"); Call<Map<String, BalanceDto>> btcBalanceResponse = makeBalanceResponse(btcBalance); when(bitcoinApi.getBalance(eq("btc"), any(), any(), any())) .thenReturn(btcBalanceResponse); // Bitcoin Cash String bchBalance = loadResourceContent("balance/wallet_v3_6_balance.txt"); Call<Map<String, BalanceDto>> bchBalanceResponse = makeBalanceResponse(bchBalance); when(bitcoinApi.getBalance(eq("bch"), any(), any(), any())) .thenReturn(bchBalanceResponse); // Bitcoin mockMultiAddress(bitcoinApi, "btc", "multiaddress/wallet_v3_6_m1.txt"); // Bitcoin cash mockMultiAddress(bitcoinApi, "bch", "multiaddress/wallet_v3_6_m1.txt"); payloadManager.initializeAndDecrypt( "0f28735d-0b89-405d-a40f-ee3e85c3c78c", "5350e5d5-bd65-456f-b150-e6cc089f0b26", "MyTestWallet", false ); //Account 1 XPubs first = new XPubs( new XPub( "xpub6CdH6yzYXhTtR7UHJHtoTeWm3nbuyg9msj3rJvFnfMew9CBff6Rp62zdTrC57Spz4TpeRPL8m9xLiVaddpjEx4Dzidtk44rd4N2xu9XTrSV", XPub.Format.LEGACY ) ); mockMultiAddress(bitcoinApi, "multiaddress/wallet_v3_6_m2.txt"); List<TransactionSummary> transactionSummaries = payloadManager .getAccountTransactions(first, 50, 0); Assert.assertEquals(8, transactionSummaries.size()); TransactionSummary summary = transactionSummaries.get(0); Assert.assertEquals(68563, summary.getTotal().longValue()); Assert.assertEquals(TransactionType.TRANSFERRED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("125QEfWq3eKzAQQHeqcMcDMeZGm13hVRvU"));//My Bitcoin Account Assert.assertEquals(2, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1Nm1yxXCTodAkQ9RAEquVdSneJGeubqeTw"));//Savings account Assert.assertTrue(summary.getOutputsMap().containsKey("189iKJLruPtUorasDuxmc6fMRVxz6zxpPS")); summary = transactionSummaries.get(1); Assert.assertEquals(138068, summary.getTotal().longValue()); Assert.assertEquals(TransactionType.SENT, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("1CQpuTQrJQLW6PEar17zsd9EV14cZknqWJ"));//My Bitcoin Wallet Assert.assertEquals(2, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1LQwNvEMnYjNCNxeUJzDfD8mcSqhm2ouPp")); Assert.assertTrue(summary.getOutputsMap().containsKey("1AdTcerDBY735kDhQWit5Scroae6piQ2yw")); summary = transactionSummaries.get(2); Assert.assertEquals(800100, summary.getTotal().longValue()); Assert.assertEquals(TransactionSummary.TransactionType.RECEIVED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("19CMnkUgBnTBNiTWXwoZr6Gb3aeXKHvuGG")); Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1CQpuTQrJQLW6PEar17zsd9EV14cZknqWJ"));//My Bitcoin Wallet summary = transactionSummaries.get(3); Assert.assertEquals(35194, summary.getTotal().longValue()); Assert.assertEquals(TransactionSummary.TransactionType.SENT, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("15HjFY96ZANBkN5kvPRgrXH93jnntqs32n"));//My Bitcoin Wallet Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1PQ9ZYhv9PwbWQQN74XRqUCjC32JrkyzB9")); summary = transactionSummaries.get(4); Assert.assertEquals(98326, summary.getTotal().longValue()); Assert.assertEquals(TransactionType.TRANSFERRED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("1Peysd3qYDe35yNp6KB1ZkbVYHr42JT9zZ"));//My Bitcoin Wallet Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("189iKJLruPtUorasDuxmc6fMRVxz6zxpPS")); summary = transactionSummaries.get(5); Assert.assertEquals(160640, summary.getTotal().longValue()); Assert.assertEquals(TransactionType.RECEIVED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("1BZe6YLaf2HiwJdnBbLyKWAqNia7foVe1w")); Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1Peysd3qYDe35yNp6KB1ZkbVYHr42JT9zZ"));//My Bitcoin Wallet summary = transactionSummaries.get(6); Assert.assertEquals(9833, summary.getTotal().longValue()); Assert.assertEquals(TransactionSummary.TransactionType.TRANSFERRED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("17ijgwpGsVQRzMjsdAfdmeP53kpw9yvXur"));//My Bitcoin Wallet Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1AtunWT3F6WvQc3aaPuPbNGeBpVF3ZPM5r"));//Savings account summary = transactionSummaries.get(7); Assert.assertEquals(40160, summary.getTotal().longValue()); Assert.assertEquals(TransactionType.RECEIVED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("1Baa1cjB1CyBVSjw8SkFZ2YBuiwKnKLXhe")); Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("17ijgwpGsVQRzMjsdAfdmeP53kpw9yvXur"));//My Bitcoin Wallet //Account 2 XPubs second = new XPubs( new XPub( "xpub6CdH6yzYXhTtTGPPL4Djjp1HqFmAPx4uyqoG6Ffz9nPysv8vR8t8PEJ3RGaSRwMm7kRZ3MAcKgB6u4g1znFo82j4q2hdShmDyw3zuMxhDSL", XPub.Format.LEGACY ) ); mockMultiAddress(bitcoinApi, "multiaddress/wallet_v3_6_m3.txt"); transactionSummaries = payloadManager.getAccountTransactions(second, 50, 0); Assert.assertEquals(2, transactionSummaries.size()); summary = transactionSummaries.get(0); Assert.assertEquals(68563, summary.getTotal().longValue()); Assert.assertEquals(TransactionType.TRANSFERRED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("125QEfWq3eKzAQQHeqcMcDMeZGm13hVRvU"));//My Bitcoin Wallet Assert.assertEquals(2, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1Nm1yxXCTodAkQ9RAEquVdSneJGeubqeTw"));//Savings account Assert.assertTrue(summary.getOutputsMap().containsKey("189iKJLruPtUorasDuxmc6fMRVxz6zxpPS")); summary = transactionSummaries.get(1); Assert.assertEquals(9833, summary.getTotal().longValue()); Assert.assertEquals(TransactionSummary.TransactionType.TRANSFERRED, summary.getTransactionType()); Assert.assertEquals(1, summary.getInputsMap().size()); Assert.assertTrue(summary.getInputsMap().containsKey("17ijgwpGsVQRzMjsdAfdmeP53kpw9yvXur"));//My Bitcoin Wallet Assert.assertEquals(1, summary.getOutputsMap().size()); Assert.assertTrue(summary.getOutputsMap().containsKey("1AtunWT3F6WvQc3aaPuPbNGeBpVF3ZPM5r"));//Savings account } }
package com.qcwp.carmanager.ui; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.blankj.utilcode.constant.TimeConstants; import com.blankj.utilcode.util.TimeUtils; import com.qcwp.carmanager.R; import com.qcwp.carmanager.broadcast.MessageEvent; import com.qcwp.carmanager.control.NavBarView; import com.qcwp.carmanager.control.TitleContentView; import com.qcwp.carmanager.enumeration.KeyEnum; import com.qcwp.carmanager.enumeration.ProfessionalTestEnum; import com.qcwp.carmanager.enumeration.UploadStatusEnum; import com.qcwp.carmanager.implement.TextToSpeechClass; import com.qcwp.carmanager.model.UserData; import com.qcwp.carmanager.model.sqLiteModel.CarInfoModel; import com.qcwp.carmanager.model.sqLiteModel.TestSummaryModel; import com.qcwp.carmanager.obd.OBDClient; import com.qcwp.carmanager.utils.CommonUtils; import com.qcwp.carmanager.utils.Print; import java.util.ArrayList; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; import lecho.lib.hellocharts.gesture.ZoomType; import lecho.lib.hellocharts.model.Axis; import lecho.lib.hellocharts.model.AxisValue; import lecho.lib.hellocharts.model.Line; import lecho.lib.hellocharts.model.LineChartData; import lecho.lib.hellocharts.model.PointValue; import lecho.lib.hellocharts.model.ValueShape; import lecho.lib.hellocharts.model.Viewport; import lecho.lib.hellocharts.view.LineChartView; public class ProfessionalTestDetailActivity extends BaseActivity { @BindView(R.id.chartView) LineChartView chartView; @BindView(R.id.testState) TextView testState; @BindView(R.id.accelerateTime) TextView accelerateTime; @BindView(R.id.testItemValue) TextView testItemValue; @BindView(R.id.testDataBackground) LinearLayout testDataBackground; @BindView(R.id.carSeries) TitleContentView carSeries; @BindView(R.id.carType) TitleContentView carType; @BindView(R.id.productYear) TitleContentView productYear; @BindView(R.id.carTotalMileage) TitleContentView carTotalMileage; @BindView(R.id.testItemName) TextView testItemName; @BindView(R.id.NavbarView) NavBarView navBarView; @BindView(R.id.testTimeName) TextView testTimeName; private OBDClient obdClient; private Boolean isReady=false,isEnd=false; private Boolean isBrake=false; private long testStartTime; private long driveTime; private List<PointValue>pointValueList; private LineChartData data; private Line line; private float totalVehicleSpeed; private int count; private float lastVehicleSpeed; private ProfessionalTestEnum professionalTestType; private CarInfoModel carInfoModel; private float maxSpeed,testTime,testDist; @Override protected int getContentViewLayoutID() { return R.layout.activity_professional_test_detail; } @Override protected void initViewsAndEvents(Bundle savedInstanceState) { obdClient=OBDClient.getDefaultClien(); Intent intent=getIntent(); professionalTestType=(ProfessionalTestEnum)intent.getSerializableExtra(KeyEnum.professionalTestType); String axisYName=""; switch (professionalTestType){ case HectometerAccelerate: navBarView.setTitle(this.getString(R.string.hectometerAccelerateName)); axisYName="距离(m)"; testItemName.setText("最高时速"); break; case KilometersAccelerate: navBarView.setTitle(this.getString(R.string.kilometersAccelerateName)); axisYName="速度(km/h)"; testItemName.setText("行车距离"); break; case KilometersBrake: navBarView.setTitle(this.getString(R.string.kilometersBrakeName)); axisYName="速度(km/h)"; testItemName.setText("刹车距离"); testState.setText("请将速度提至100km/h以上"); testTimeName.setText("刹车距离"); break; } this.initChartView(axisYName); carInfoModel=CarInfoModel.getCarInfoByVinCode(UserData.getInstance().getVinCode()); if (carInfoModel!=null){ carType.setContentTextViewText(carInfoModel.getCarType().getCarTypeName()); carSeries.setContentTextViewText(carInfoModel.getCarSeries()); productYear.setContentTextViewText(carInfoModel.getProductiveYear()); carTotalMileage.setContentTextViewText(String.format(Locale.getDefault(),"%.1f",carInfoModel.getTotalMileage())); } } @Override protected void onReceiveMessageEvent(MessageEvent messageEvent) { float vehicleSpeed=(float)obdClient.getVehicleSpeed(); switch (messageEvent.getType()){ case Driving: switch (professionalTestType){ case HectometerAccelerate: case KilometersAccelerate: if (vehicleSpeed==0){ obdClient.startTest(); //开始测试状态 } break; case KilometersBrake: if (vehicleSpeed>100){ obdClient.startTest(); //开始测试状态 } testState.setText(String.format(Locale.getDefault(),"预测试阶段速度:%.1f km/h",vehicleSpeed)); break; } break; case CarTest: switch (professionalTestType){ case HectometerAccelerate: case KilometersAccelerate: if (vehicleSpeed==0&&!isReady) {//测试初始化 this.readyTest(); }else if (vehicleSpeed>0){ if (isReady){ this.testStart();//测试开始 } this.updateChartViewData(vehicleSpeed); } break; case KilometersBrake: if (!isReady&&!isBrake) {//测试初始化 this.readyTest(); Print.d(TAG,"readyTest"); }else{ if (vehicleSpeed<lastVehicleSpeed-2&&!isBrake){ this.testStart();//测试开始 Print.d(TAG,"testStart"); } if (isBrake) { this.updateChartViewData(vehicleSpeed); }else { maxSpeed=vehicleSpeed; testState.setText(String.format(Locale.getDefault(),"预测试速度:%.1f km/h",vehicleSpeed)); } } break; } lastVehicleSpeed=vehicleSpeed; break; } } /*** 设置X 轴的显示 */ private List<AxisValue> getAxisX() { List<AxisValue> axisValueList=new ArrayList<>(); for (int i = 0; i < 10; i++) { axisValueList.add(new AxisValue(i*1000).setLabel(String.valueOf(i))); } return axisValueList; } /*** 设置Y 轴的显示 */ private List<AxisValue> getAxisY() { List<AxisValue> axisValueList=new ArrayList<>(); for (int i = 0; i < 7; i++) { axisValueList.add(new AxisValue(i*20).setLabel(String.valueOf(i*20))); } return axisValueList; } @Override public void onClick(View v) { super.onClick(v); switch (v.getId()){ case R.id.startTest: break; } } private void readyTest(){ Print.d(TAG,"readyTest"); isReady=true; testState.setText(this.getString(R.string.professionalTest_testReady)); pointValueList=new ArrayList<>(); totalVehicleSpeed=0; count=0; lastVehicleSpeed=0; } private void testStart(){ if (professionalTestType!=ProfessionalTestEnum.KilometersBrake) { testState.setText(this.getString(R.string.professionalTest_testStart)); } testStartTime= TimeUtils.getNowMills(); isReady=false; isBrake=true; } private void testEnd(String message){ obdClient.stopTest(); testState.setText(message); isBrake=false; isEnd=true; String createDate=TimeUtils.getNowString(); TestSummaryModel testSummaryModel=new TestSummaryModel(); testSummaryModel.setVinCode(carInfoModel.getVinCode()); testSummaryModel.setCarNumber(carInfoModel.getCarNumber()); testSummaryModel.setCreateDate(createDate); testSummaryModel.setMaxSpeed(maxSpeed); testSummaryModel.setTestDist(testDist); testSummaryModel.setTestTime(testTime); testSummaryModel.setTestType(professionalTestType); testSummaryModel.setUploadFlag(UploadStatusEnum.NotUpload); testSummaryModel.setUserName(UserData.getInstance().getUserName()); mDaoSession.insert(testSummaryModel); CommonUtils.saveCurrentImage(this,createDate); } private void updateChartViewData(float vehicleSpeed){ long testEndTime=TimeUtils.getNowMills(); driveTime=TimeUtils.getTimeSpan(testStartTime,testEndTime, TimeConstants.MSEC); accelerateTime.setText(String.format(Locale.getDefault(),"%.1f s",driveTime*1f/1000)); //0.001s 的路程= (speed值*1000m/3600s)*0.001s=speed值/3600 (m) totalVehicleSpeed+=vehicleSpeed; count++; float currentMileage=(totalVehicleSpeed/count)/3600*driveTime; PointValue value=null; switch (professionalTestType){ case HectometerAccelerate: testItemValue.setText(String.format(Locale.getDefault(),"%.1f km/h",vehicleSpeed)); value = new PointValue(driveTime, currentMileage); if (currentMileage>100&&!isEnd){ maxSpeed=vehicleSpeed; testDist=currentMileage; testTime=driveTime*1f/1000; this.testEnd(this.getString(R.string.professionalTest_testEnd)); return; } if (vehicleSpeed<lastVehicleSpeed-2){ this.testEnd(this.getString(R.string.professionalTest_testFailure)); return; } break; case KilometersAccelerate: testItemValue.setText(String.format(Locale.getDefault(),"%.1f m",currentMileage)); value = new PointValue(driveTime, vehicleSpeed); if (vehicleSpeed>100&&!isEnd){ maxSpeed=vehicleSpeed; testDist=currentMileage; testTime=driveTime*1f/1000; this.testEnd(this.getString(R.string.professionalTest_testEnd)); return; } if (vehicleSpeed<lastVehicleSpeed-2){ this.testEnd(this.getString(R.string.professionalTest_testFailure)); return; } break; case KilometersBrake: testItemValue.setText(String.format(Locale.getDefault(),"%.1f m",currentMileage)); value = new PointValue(driveTime, vehicleSpeed); if (vehicleSpeed==0&&!isEnd){ testDist=currentMileage; testTime=driveTime*1f/1000; this.testEnd(this.getString(R.string.professionalTest_testEnd)); return; } if (vehicleSpeed>lastVehicleSpeed+2){ this.testEnd(this.getString(R.string.professionalTest_testFailure)); return; } break; } //实时添加新的点 pointValueList.add(value); float x = value.getX(); //根据新的点的集合画出新的线 line.setValues(pointValueList); List<Line> linesList = new ArrayList<>(); linesList.add(line); data.setLines(linesList); chartView.setLineChartData(data); float right=10*1000; if (x>right){ right=((int)((x-right)/1000)+1)*1000+right; } Viewport port = new Viewport(0,120,right,0); chartView.setMaximumViewport(port);//最大窗口 chartView.setCurrentViewport(port);//当前窗口 } @Override protected void onDestroy() { super.onDestroy(); obdClient.stopTest(); } private void initChartView(String axisYName){ chartView.setInteractive(false);//设置图表是可以交互的(拖拽,缩放等效果的前提) chartView.setZoomType(ZoomType.HORIZONTAL_AND_VERTICAL);//设置缩放方向 data = new LineChartData(); Axis axisX = new Axis();//x轴 axisX.setName("时间(s)"); axisX.setHasLines(true); axisX.setValues(getAxisX()); axisX.setHasLines(true); data.setAxisXBottom(axisX); Axis axisY = new Axis();//y轴 axisY.setName(axisYName); axisY.setValues(getAxisY()); axisY.setHasLines(true); axisY.setHasLines(true); data.setAxisYLeft(axisY); line = new Line().setColor(Color.RED); //折线的颜色(橙色) line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状 这里是圆形 (有三种 :ValueShape.SQUARE ValueShape.CIRCLE ValueShape.DIAMOND) line.setCubic(false);//曲线是否平滑,即是曲线还是折线 line.setFilled(false);//是否填充曲线的面积 line.setHasLabels(false);//曲线的数据坐标是否加上备注 // line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据(设置了这个line.setHasLabels(true);就无效) line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示 line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示(每个数据点都是个大的圆点) chartView.setLineChartData(data);//给图表设置数据 Viewport v = new Viewport(0,120,10*1000,0); chartView.setMaximumViewport(v); chartView.setCurrentViewport(chartView.getMaximumViewport()); } }
// Virginia Tech Honor Code Pledge: // // As a Hokie, I will conduct myself with honor and integrity at all times. // I will not lie, cheat, or steal, nor will I accept the actions of those // who do. // -- Musaab Elsheikh (melsheikh) import sofia.micro.*; import sofia.graphics.Color; // ------------------------------------------------------------------------- /** * Tests all methods in the Water class. * * @author Musaab Elsheikh (melsheikh) * @version (2019.11.05) */ public class WaterTest extends TestCase { //~ Fields ................................................................ private ParticleWorld world; private Water water; //~ Constructor ........................................................... // ---------------------------------------------------------- /** * Creates a new WaterTest test object. */ public WaterTest() { // The constructor is usually empty in unit tests, since it runs // once for the whole class, not once for each test method. // Per-test initialization should be placed in setUp() instead. } //~ Methods ............................................................... // ---------------------------------------------------------- /** * Sets up the test fixture. * Called before every test case method. */ public void setUp() { world = new ParticleWorld(0); water = new Water(); } // ---------------------------------------------------------- /** * Tests Water constructor */ public void testWaterConstructor() { world.add(water, 100, 100); assertEquals(Color.cadetBlue, water.getColor()); assertFalse(water.willDissolve()); assertEquals(1, water.getDensity(), 0.001); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import java.util.LinkedList; public final class amo extends a { public int create_time; public int huK; public String hwg; public int peW; public String rIw; public String rPn; public bao rPo; public int rPp; public int rPq; public String rPr; public String rrW; public long ruW; public int state; protected final int a(int i, Object... objArr) { int h; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.rIw != null) { aVar.g(1, this.rIw); } if (this.rrW != null) { aVar.g(2, this.rrW); } aVar.T(3, this.ruW); aVar.fT(4, this.state); if (this.rPn != null) { aVar.g(5, this.rPn); } aVar.fT(6, this.peW); if (this.rPo != null) { aVar.fV(7, this.rPo.boi()); this.rPo.a(aVar); } aVar.fT(8, this.create_time); aVar.fT(9, this.huK); aVar.fT(10, this.rPp); aVar.fT(11, this.rPq); if (this.rPr != null) { aVar.g(12, this.rPr); } if (this.hwg == null) { return 0; } aVar.g(13, this.hwg); return 0; } else if (i == 1) { if (this.rIw != null) { h = f.a.a.b.b.a.h(1, this.rIw) + 0; } else { h = 0; } if (this.rrW != null) { h += f.a.a.b.b.a.h(2, this.rrW); } h = (h + f.a.a.a.S(3, this.ruW)) + f.a.a.a.fQ(4, this.state); if (this.rPn != null) { h += f.a.a.b.b.a.h(5, this.rPn); } h += f.a.a.a.fQ(6, this.peW); if (this.rPo != null) { h += f.a.a.a.fS(7, this.rPo.boi()); } h = (((h + f.a.a.a.fQ(8, this.create_time)) + f.a.a.a.fQ(9, this.huK)) + f.a.a.a.fQ(10, this.rPp)) + f.a.a.a.fQ(11, this.rPq); if (this.rPr != null) { h += f.a.a.b.b.a.h(12, this.rPr); } if (this.hwg != null) { h += f.a.a.b.b.a.h(13, this.hwg); } return h; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) { if (!super.a(aVar2, this, h)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; amo amo = (amo) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); switch (intValue) { case 1: amo.rIw = aVar3.vHC.readString(); return 0; case 2: amo.rrW = aVar3.vHC.readString(); return 0; case 3: amo.ruW = aVar3.vHC.rZ(); return 0; case 4: amo.state = aVar3.vHC.rY(); return 0; case 5: amo.rPn = aVar3.vHC.readString(); return 0; case 6: amo.peW = aVar3.vHC.rY(); return 0; case 7: LinkedList IC = aVar3.IC(intValue); int size = IC.size(); for (intValue = 0; intValue < size; intValue++) { byte[] bArr = (byte[]) IC.get(intValue); bao bao = new bao(); f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (boolean z = true; z; z = bao.a(aVar4, bao, a.a(aVar4))) { } amo.rPo = bao; } return 0; case 8: amo.create_time = aVar3.vHC.rY(); return 0; case 9: amo.huK = aVar3.vHC.rY(); return 0; case 10: amo.rPp = aVar3.vHC.rY(); return 0; case 11: amo.rPq = aVar3.vHC.rY(); return 0; case 12: amo.rPr = aVar3.vHC.readString(); return 0; case 13: amo.hwg = aVar3.vHC.readString(); return 0; default: return -1; } } } }
/* * $Id: $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.struts.annotations.taglib.apt; /** * Used to hold tag attribute information for TLD generation * */ public class TagAttribute { private String name; private boolean required; private boolean rtexprvalue; private String description; private String defaultValue; private String type; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public boolean isRtexprvalue() { return rtexprvalue; } public void setRtexprvalue(boolean rtexprvalue) { this.rtexprvalue = rtexprvalue; } public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
package com.microsilver.mrcard.basicservice.controller; import com.microsilver.mrcard.basicservice.service.OrderService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component @Transactional public class TestTask1 { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private OrderService orderService; private int count=0; //每隔60分钟 //@Scheduled(cron="0 */60 * * * ?") @Scheduled(cron="* */60 * * * ?") private void process() { System.out.println("[" + Thread.currentThread().getName() + "]" + "this is scheduler task runing " + (count++)); // List<FxSdCarriageOrder> list = orderService.selectAllOrder(); // if (list != null) { // for (FxSdCarriageOrder order : list) { // Byte payType = order.getPayType(); // if (payType!=null && payType == 22) { // order.setStatus((byte)9); // orderService.updateOrder(order); // //返回金额到用户账户中(目前仅支持支付宝) // String s = AlipayRefundUtil.alipayRefundRequest(order.getOrdersn(), order.getTransId(), order.getDispatchPrice().doubleValue()); // logger.info("用户id为:" + order.getMemberId() + ",订单已取消,取消金额为:" + order.getDispatchPrice().doubleValue() // + ",订单号:" + order.getOrdersn() + ",支付宝支付流水号:" + order.getTransId() + ",支付状态:" + order.getStatus() + ",支付宝退款成功,"); // logger.info("支付宝回调信息:"+s); // } // } // } } }
package arrayJava; // print a grid with the help of array public class ArrayGrid { public static void main(String[] args) { int a[][] = new int [10][10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { System.out.printf("%2d",a[i][j]); } System.out.println(); } } }
/* * Copyright (C), 2013-2015, 上海汽车集团股份有限公司 * FileName: MailVo.java * Author: baowenzhou * Date: 2015年01月05日 下午1:34:06 * Description: //模块目的、功能描述 * History: //修改记录 * <author> <time> <version> <desc> * 修改人姓名 修改时间 版本号 描述 */ package com.xjf.wemall.api.entity.mail; import java.util.Date; /** * 微信菜单实体 <br> * 〈功能详细描述〉 * * @author baowenzhou * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ public class MailVo { // 收件人 private String to; // 主题 private String subject; // 内容 private String text; // 内容 private Date sendDate; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String[] getToArray() { String[] toArray = {}; if (to != null && to.length() > 0) { toArray = to.split(";"); } return toArray; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getSendDate() { return sendDate; } public void setSendDate(Date sendDate) { this.sendDate = sendDate; } }
/* * Copyright 2011-2014 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.splunk.config.xml; import org.w3c.dom.Element; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.xml.IntegrationNamespaceUtils; import org.springframework.integration.splunk.support.SplunkServer; /** * Splunk server element parser. * * The XML element is like this: * <pre class="code"> * {@code * <splunk:server id="splunkServer" host="host" port="8089" username="admin" password="password" * scheme="https" owner="admin" app="search"/> * } * </pre> * * @author Jarred Li * @author Olivier Lamy * @since 1.0 * */ public class SplunkServerParser extends AbstractSimpleBeanDefinitionParser { @Override public Class<?> getBeanClass(Element element) { return SplunkServer.class; } @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doParse(element, parserContext, builder); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, BeanDefinitionParserDelegate.SCOPE_ATTRIBUTE); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "host"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "port"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "scheme"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "app"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "owner"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "username"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "password"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "checkServiceOnBorrow"); } }
package org.javamisc.jee.entitycrud; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import java.lang.reflect.TypeVariable; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import javax.persistence.Id; import javax.persistence.Entity; import javax.persistence.Column; import javax.persistence.OneToOne; import javax.persistence.OneToMany; import javax.persistence.ManyToOne; import javax.persistence.ManyToMany; import static org.javamisc.Util.genericTypecast; /** * Bean utilities to support the entitycrud package, mostly reflection * stuff. */ public class BeanUtil { /** * BeanUtil is not to be instantiated, just provides static methods. */ private BeanUtil() { } /** * Construct an instance of a class. * * @param c the class to be instantiated * @return an instance of the class, obtained by invoking the parameterless constructor of the class * * @throws NoSuchMethodException if there is no default constructor * @throws InstantiationException if instantiation fails * @throws IllegalAccessException if access violation occurs * @throws InvocationTargetException if constructor invocation fails */ public static Object constructDefaultInstance(Class<?> c) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Constructor defaultConstructor = c.getConstructor(); Object o = defaultConstructor.newInstance(); return (o); } /** * Construct an instance of a class specified by a name. * * @param className the canonical name of the class to be instantiated * @return an instance of the class, obtained by invoking the parameterless constructor of the class * * @throws ClassNotFoundException if class with specified name cannot be found * @throws NoSuchMethodException {@link #constructDefaultInstance(Class)} * @throws InstantiationException {@link #constructDefaultInstance(Class)} * @throws IllegalAccessException {@link #constructDefaultInstance(Class)} * @throws InvocationTargetException {@link #constructDefaultInstance(Class)} */ public static Object constructDefaultInstance(String className) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { return (constructDefaultInstance(Class.forName(className))); } /** * Extract the name of a property from the name of an accessor or mutator method. * * @param methodName the name of the accessor or mutator method * @return the name of the property */ public static String extractPropertyName(String methodName) { int i = 0; if (methodName.startsWith("get") || methodName.startsWith("set")) { i = 3; } else if (methodName.startsWith("is")) { i = 2; } else { throw new IllegalArgumentException(String.format("not an accessor or mutator name: %s", methodName)); } String propertyName = methodName.substring(i, i + 1).toLowerCase() + methodName.substring(i + 1); return (propertyName); } /** * Extract the name of a property from an accessor or mutator method. * * @param method the accessor or mutator method * @return the name of the property */ public static String extractPropertyName(Method method) { return (extractPropertyName(method.getName())); } /** * Compute the accessor name corresponding to a property. * * <p>This method prefixes the property name with {@code get} and * converts the first character of the property to upper case. There * is no provision for boolean accessors prefixed with {@code is}.</p> * * @param propertyName the name of the property * @return the corresponding accessor name */ public static String makeAccessorName(String propertyName) { // FIXME: cannot generate isSomething style boolean accessors return ("get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1)); } /** * Compute the mutator name corresponding to a property. * * <p>This method prefixes the property name with {@code set} and * converts the first character of the property to upper case.</p> * * @param propertyName the name of the property * @return the corresponding mutator name */ public static String makeMutatorName(String propertyName) { return ("set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1)); } /** * Determine whether a method is an accessor method. * * <p>Currently checks are (1) whether the method's name starts with * {@code get} or {@code is} and (2) whether the method takes no * parameters.</p> * * @param method the method to be checked * @return {@code true} if the method is considered to be an accessor method. */ public static boolean isAccessor(Method method) { String methodName = method.getName(); if (!methodName.startsWith("get") && !methodName.startsWith("is")) { return (false); } Class parameterTypes[] = method.getParameterTypes(); if (parameterTypes.length != 0) { return (false); } else { return (true); } } /** * Determine whether a method is a mutator method. * * <p>Currently checks are (1) whether the method's name starts with * {@code set} and (2) whether the method takes exactly one parameter.</p> * * @param method the method to be checked * @return {@code true} if the method is considered to be an mutator method. */ public static boolean isMutator(Method method) { String methodName = method.getName(); if (!methodName.startsWith("set")) { return (false); } Class parameterTypes[] = method.getParameterTypes(); if (parameterTypes.length != 1) { return (false); } else { return (true); } } /** * Find the accessor method for a given property. * * <p>Accessors found by this method take no parameter. The method * returns the first accessor it finds.</p> * * @param entityClass the entity class within which the accessor is searched * @param propertyName the name of the property * @return the accessor method, or {@code null} if no mutator was found */ public static Method findAccessor(Class<?> entityClass, String propertyName) { for (Method method : entityClass.getMethods()) { if (isAccessor(method)) { if (propertyName.equals(extractPropertyName(method))) { return (method); } } } return (null); } /** * Find the mutator method for a given property. * * <p>Mutators found by this method take exactly one parameter. The * method returns the first mutator it finds.</p> * * @param entityClass the entity class within which the mutator is searched * @param propertyName the name of the property * @return the mutator method, or {@code null} if no mutator was found */ // FIXME: really ought to check for property type as well public static Method findMutator(Class<?> entityClass, String propertyName) { for (Method method : entityClass.getMethods()) { if (isMutator(method)) { if (propertyName.equals(extractPropertyName(method))) { return (method); } } } return (null); } /** * Determine the type of a property. * * <p>This method operates by trying to find an accessor method for * the property and returns that accessor's return type.</p> * * @param entityClass the entity class for which to determine the property type * @param propertyName the property's name * @return the type of the property, or {@code null} if the entity class has no accessor for the specified property */ public static Class<?> findPropertyType(Class<?> entityClass, String propertyName) { Method accessor = findAccessor(entityClass, propertyName); if (accessor == null) { return (null); } return (accessor.getReturnType()); } /** * Determine the type of a property. * * <p>This method operates by trying to find an accessor method for * the property and returns that accessor's return type.</p> * * @param entity the entity for which to determine the property type * @param propertyName the property's name * @return the type of the property, or {@code null} if the entity class has no accessor for the specified property */ public static Class<?> findPropertyType(Object entity, String propertyName) { return (findPropertyType(entity.getClass(), propertyName)); } /** * Find the names of all properties of an entity class. * * <p>Properties found by this method are both accessible and * mutatable.</p> * * @param entityClass the entity class * @return a set containing the names of the properties */ public static Set<String> findPropertyNameSet(Class<?> entityClass) { HashSet<String> propertyNameSet = new HashSet<String>(); for (Method method : entityClass.getMethods()) { if (isAccessor(method)) { String propertyName = extractPropertyName(method.getName()); if (findMutator(entityClass, propertyName) != null) { propertyNameSet.add(propertyName); } } } return (propertyNameSet); } /** * Find the names of all properties of an entity. * * <p>Properties found by this method are both accessible and * mutatable.</p> * * @param entity the entity * @return a set containing the names of the properties */ public static Set<String> findPropertyNameSet(Object entity) { return (findPropertyNameSet(entity.getClass())); } /** * Find properties of an entity class that are constrained to be * unique by a {@code @Column} annotation or that have an {@code @Id} * annotation. * * @param entityClass the entity class * @return a list of names of the entity class' unique properties */ public static Set<String> findUniquePropertyNameSet(Class<?> entityClass) { HashSet<String> uniquePropertyNameSet = new HashSet<String>(); for (String propertyName : findPropertyNameSet(entityClass)) { Method accessor = findAccessor(entityClass, propertyName); Method mutator = findMutator(entityClass, propertyName); if ((accessor.getAnnotation(Id.class) != null) || (mutator.getAnnotation(Id.class) != null)) { uniquePropertyNameSet.add(propertyName); } else { Column columnAnnotation = accessor.getAnnotation(Column.class); if (columnAnnotation == null) { columnAnnotation = mutator.getAnnotation(Column.class); } if (columnAnnotation != null && columnAnnotation.unique()) { uniquePropertyNameSet.add(propertyName); } } } return (uniquePropertyNameSet); } /** * Determine whether an class represents a collection of entities. * * <p>A collection of entities is defined as an instance of {@code * java.util.Collection} with an element type that is annotated * {@code @javax.persistence.Entity}.</p> * * <p>Seems to be impossible due to restrictions caused by type erasure :-(((</p> * * @param objClass the class to be checked * @return {@code} true if the object is a collection of entities */ public static boolean isEntityCollectionClass(Class<?> objClass) { throw new RuntimeException("not implemented due to erasure problems"); /* if (!(objClass instanceof ParameterizedType)) { return (false); } return (true); */ } /** * Determine whether an object is a collection of entities. * * <p>A collection of entities is defined as an instance of {@code * java.util.Collection} with an element type that is annotated * {@code @javax.persistence.Entity}.</p> * * @param obj the object to be checked * @return {@code} true if the object is a collection of entities */ public static boolean isEntityCollection(Object obj) { return (isEntityCollectionClass(obj.getClass())); } /** * Compute a map of property names to classes that the entity has * associations with. * * @param entityClass the entity for which associations are to be found. * @return a map with property names as keys and classes as values. */ public static Map<String, Class<?>> findAssociationPropertyMap(Class<?> entityClass) { HashMap<String, Class<?>> associationPropertyMap = new HashMap<String, Class<?>>(); for (String propertyName : findPropertyNameSet(entityClass)) { Method accessor = findAccessor(entityClass, propertyName); Method mutator = findMutator(entityClass, propertyName); if ((accessor.getAnnotation(OneToOne.class) != null) || (accessor.getAnnotation(ManyToOne.class) != null) || (mutator.getAnnotation(OneToOne.class) != null) || (mutator.getAnnotation(ManyToOne.class) != null)) { // System.err.println(String.format("Util.findAssociationPropertyMap: %s: using simple returnType for to-one association", propertyName)); associationPropertyMap.put(propertyName, accessor.getReturnType()); } else if ((accessor.getAnnotation(OneToMany.class) != null) || (accessor.getAnnotation(ManyToMany.class) != null) || (mutator.getAnnotation(OneToMany.class) != null) || (mutator.getAnnotation(ManyToMany.class) != null)) { // System.err.println(String.format("Util.findAssociationPropertyMap: %s: analysing generic returnType for to-many association", propertyName)); Type rawToManyType = accessor.getGenericReturnType(); if (!(rawToManyType instanceof ParameterizedType)) { throw new IllegalArgumentException(String.format("illegal type for to-many association: %s", rawToManyType.toString())); } ParameterizedType toManyType = (ParameterizedType) rawToManyType; Type[] actualTypeList = toManyType.getActualTypeArguments(); if (actualTypeList.length != 1) { throw new IllegalArgumentException("cannot deal with collections that do not have exactly one type parameter"); } Type associatedType = actualTypeList[0]; if (associatedType instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) associatedType; System.err.println(String.format("class %s, property %s: parameterized: %s, raw: %s", entityClass.getName(), propertyName, ptype.toString(), ptype.getRawType().toString())); } if (associatedType instanceof TypeVariable) { TypeVariable tvar = (TypeVariable) associatedType; System.err.println(String.format("class %s, property %s: typevar: %s", entityClass.getName(), propertyName, tvar.toString())); Type[] bounds = tvar.getBounds(); for (Type t : bounds) { System.err.println(String.format(" bound: %s, is %sa class", t.toString(), t instanceof Class<?> ? "" : "not ")); } // FIXME: falling back to type bound as minimal solution. It should be possible to find out the actual type, at least if the entity class considered is defined "... extends EntityBase<ActualClass>", i.e. if the entity class is not parameterized itself. if (bounds.length == 1) { associatedType = bounds[0]; } } if (!(associatedType instanceof Class<?>)) { throw new IllegalArgumentException(String.format("cannot deal with association types that are not classes (type: %s)", associatedType.toString())); } Class<?> associatedClass = genericTypecast(associatedType); associationPropertyMap.put(propertyName, associatedClass); } } return (associationPropertyMap); } /** * Compute a map of property names to classes that the entity has * associations with. * * @param entity the entity for which associations are to be found. * @return a map with property names as keys and classes as values. */ public static Map<String, Class<?>> findAssociationPropertyMap(Object entity) { Class<?> entityClass = entity.getClass(); return findAssociationPropertyMap(entityClass); } /** * Find properties of an entity that are constrained to be * unique by a {@code @Column} annotation or that have an {@code @Id} * annotation. * * @param entity the entity * @return a list of names of the entity's unique properties */ public static Set<String> findUniquePropertyNameSet(Object entity) { return (findUniquePropertyNameSet(entity.getClass())); } /** * Get a property from an entity (or generally a bean like object). * * @param entity the entity (or general object) to get the property from * @param propertyName the name of the property to get * @return the property's value * * @throws IllegalAccessException if access control violation occurs * @throws InvocationTargetException if invocation fails * @throws NoSuchMethodException if accessor does not exist */ public static Object getProperty(Object entity, String propertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String accessorName = makeAccessorName(propertyName); Class<?> entityClass = entity.getClass(); Method accessorMethod = entityClass.getMethod(accessorName); Object property = accessorMethod.invoke(entity); return (property); } /** * Set a property on an entity (or generally a bean like object). * * @param entity the entity (or general object) to get the property from * @param propertyName the name of the property to get * @param propertyValue the value to set * * @throws IllegalAccessException if access control violation occurs * @throws InvocationTargetException if invocation fails * @throws NoSuchMethodException if mutator does not exist */ public static void setProperty(Object entity, String propertyName, Object propertyValue) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String mutatorName = makeMutatorName(propertyName); Class<?> entityClass = entity.getClass(); Method mutatorMethod = null; if (propertyValue != null) { Class<?> valueClass = propertyValue.getClass(); mutatorMethod = entityClass.getMethod(mutatorName, valueClass); } else { // FIXME: just find any method taking one parameter -- cannot use parameter type now for (Method method : entityClass.getMethods()) { if (mutatorName.equals(method.getName()) && (method.getParameterTypes().length == 1)) { mutatorMethod = method; break; } } } // FIXME: ignoring the return value, assuming method returns void mutatorMethod.invoke(entity, propertyValue); } /** * Set a property based on a {@code String} value on an entity (or * generally a bean like object). * * <p>This method checks the type of the property and converts the * {@code String} accordingly. Currently supported types are:</p> * <table><caption>currently supported types</caption> * <tr><td>{@code String}</td><td>no conversion</td></tr> * <tr><td>{@code Integer}</td><td>conversion by {@code Integer.parseInt}</td></tr> * <tr><td>{@code Double}</td><td>conversion by {@code Double.parseDouble}</td></tr> * </table> * * @param entity the object to get the property from * @param propertyName the name of the property to get * @param propertyValueString the value to set, as a string * * @throws IllegalAccessException if access control violation occurs * @throws InvocationTargetException if invocation fails * @throws NoSuchMethodException if mutator does not exist */ public static void setPropertyFromString(Object entity, String propertyName, String propertyValueString) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Class<?> valueClass = findPropertyType(entity.getClass(), propertyName); Object propertyValue = null; if (String.class.isAssignableFrom(valueClass)) { valueClass = String.class; propertyValue = propertyValueString; } else if (Integer.class.isAssignableFrom(valueClass)) { valueClass = Integer.class; propertyValue = new Integer(Integer.parseInt(propertyValueString)); } else if (Double.class.isAssignableFrom(valueClass)) { valueClass = Double.class; propertyValue = new Double(Double.parseDouble(propertyValueString)); } else { throw new IllegalArgumentException("property type not (yet) supported"); } setProperty(entity, propertyName, propertyValue); } }
package com.example.nihar.delta; public class User { public String username; public Boolean boolSpeakPeriodic=true; public Boolean boolSpeechInput=true; public Boolean boolDetectLabels=true; public Boolean boolDetectExpressions=true; public String Name; public Boolean LocationAccess = true; public String Address=""; public String BloodGroup=""; public String GName=""; public String GNumber=""; public String age = ""; public String msgnumber1="",msgnumber2=""; }
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class IteratorIterableTest { private GenericStack<Integer> s; private GLIterator<Integer> sIterator; @BeforeEach void init() { s = new GenericStack<Integer>(200); } @Test void testNextAfterPush() { s.push(100); sIterator = s.createIterator(); assertEquals(100, sIterator.next(), "next() doesn't work"); } @Test void testHasNextAfterPush() { s.push(100); sIterator = s.createIterator(); assertTrue(sIterator.hasNext()); } @Test void testHasNextAfterPop() { s.pop(); sIterator = s.createIterator(); assertFalse(sIterator.hasNext()); } @Test void testNextMiddle() { s.push(50); sIterator = s.createIterator(); sIterator.next(); assertEquals(200, sIterator.next(), "testNextMiddle isn't correct"); } @Test void testIfStackIsNull() { sIterator = s.createIterator(); s.pop(); s.forEach(e->assertNull(e)); } @Test void testIfStackIsntNull() { sIterator = s.createIterator(); s.forEach(e->assertEquals(200, e, "testIfStackIsntNull is incorrect")); } @Test void testIfStackHasAVal(){ sIterator = s.createIterator(); assertTrue(sIterator.hasNext(),"testIfStackHasAVal is incorrect"); } }
/** * */ package alg.sort; import java.util.Arrays; /** * 归并排序. * 改进点:当元素数在一定范围内时,避免递归,直接插入排序 * 稳定 * @title MergeSort */ public class MergeSort { public static void main(String[] args) { // int[] a = {1}; // int[] a = {-1, 7}; // int[] a = {8, 2}; int[] a = {4, 1, 1, 6, 9, 2, 1, 0, 3, 5, -19, -1, 0, 5}; MergeSort ms = new MergeSort(); ms.bottomUpSort(a); System.out.println(Arrays.toString(a)); } public void sort(int[] a, int left, int right) { if(left >= right) return; int mid = (left + right) / 2; sort(a, left, mid); sort(a, mid + 1, right); merge(a, left, mid, right); } // 自顶而下 private void merge(int[] a, int left, int mid, int right) { int[] tmp = new int[right - left + 1]; int p = left, q = mid + 1; int k = 0; while(p <= mid && q <= right) { tmp[k++] = (a[p] <= a[q]) ? a[p++] : a[q++]; } while(p <= mid) { tmp[k++] = a[p++]; } while(q <= right) { tmp[k++] = a[q++]; } System.arraycopy(tmp, 0, a, left, right - left + 1); } // 自底而上,不使用递归 private void bottomUpSort(int[] a) { int n = a.length; for(int size = 1; size < n; size *= 2) { for(int i = 0; i + size < n; i += size + size) { merge(a, i, i + size - 1, Math.min(i + size + size - 1, n - 1)); } } } }
import org.apache.commons.math3.distribution.NormalDistribution; public class TestGaussian { public static void main(String [] args) { double mean = 1337215609117.184800; double variance = 82079460604218752.000000; NormalDistribution nd = new NormalDistribution(mean, Math.sqrt(variance)); double t1 = nd.inverseCumulativeProbability(0.25); double diff = mean - t1; double t2 = mean + diff; System.out.println(String.format("%f, %f", t1, t2)); double p = nd.cumulativeProbability(t1, t2); System.out.println(p); } }
package designPattern2; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class FireFoxBrowser extends Browser{ @Test public void getBrowser() { System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"/Driver/geckodriver.exe"); WebDriver driver = new FirefoxDriver(); } }
package controllers; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import models.User; import models.Address; import models.City; public class ShowAllAddressServlet extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); if(user!=null){ ArrayList<Address> addresses = Address.getAllAddresses(user.getUserId()); request.setAttribute("addresses_",addresses); request.getRequestDispatcher("show_all_addresses.jsp").forward(request,response); }else{ request.getRequestDispatcher("login.jsp").forward(request,response); } } }
package com.tt.miniapp.component.nativeview.game; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import com.tt.miniapp.thread.ThreadUtil; public class GameBtnImage extends GameButton { private RoundedImageView mImageView; GameBtnImage(RoundedImageView paramRoundedImageView, GameButtonStyle paramGameButtonStyle) { super((View)paramRoundedImageView, paramGameButtonStyle); this.mImageView = paramRoundedImageView; } public void applyImageUpdate(byte paramByte, GameButtonStyle paramGameButtonStyle, Drawable paramDrawable) { if (paramDrawable != null) this.mImageView.setImageDrawable(paramDrawable); if ((paramByte & 0x4) != 0) GameButtonHelper.applyImageStyle(this.mImageView, paramGameButtonStyle); if ((paramByte & 0x2) != 0) { GameAbsoluteLayout.LayoutParams layoutParams = (GameAbsoluteLayout.LayoutParams)this.mRealView.getLayoutParams(); layoutParams.width = paramGameButtonStyle.width; layoutParams.height = paramGameButtonStyle.height; layoutParams.setXY(paramGameButtonStyle.left, paramGameButtonStyle.top); this.mRealView.setLayoutParams((ViewGroup.LayoutParams)layoutParams); } this.mStyle = paramGameButtonStyle; } public int getBtnType() { return 1; } public void loadImageIfNeed(final byte cmp, final GameButtonStyle style, final GameBtnUpdateAnim anim) { if ((cmp & 0x1) != 0) { GameButtonHelper.applyImage(this.mImageView, style.content, style.width, style.height, new GameButtonHelper.ApplyImageCallback() { public void onLoaded(boolean param1Boolean, Drawable param1Drawable) { GameBtnImage.this.updateImageBtn(cmp, style, anim, param1Drawable); } }); return; } updateImageBtn(cmp, style, anim, (Drawable)null); } public void update(final GameButtonStyle style, final GameBtnUpdateAnim anim) { if (style == null) return; final byte cmp = this.mStyle.compare(style); if (b == 0) return; ThreadUtil.runOnUIThread(new Runnable() { public void run() { GameBtnImage.this.loadImageIfNeed(cmp, style, anim); } }); } public void updateImageBtn(final byte cmp, final GameButtonStyle style, GameBtnUpdateAnim paramGameBtnUpdateAnim, final Drawable drawable) { if (paramGameBtnUpdateAnim == null || this.mRealView.getVisibility() != 0) { applyImageUpdate(cmp, style, drawable); return; } this.mRealView.startAnimation(paramGameBtnUpdateAnim.getAnim()); ThreadUtil.runOnUIThread(new Runnable() { public void run() { GameBtnImage.this.applyImageUpdate(cmp, style, drawable); } }paramGameBtnUpdateAnim.getApplyDelayMs()); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\component\nativeview\game\GameBtnImage.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package lesson04; public class Season04 { //CŨNG LÀ VÍ DỤ 2(season): TẠO ENUM BÊN NGOÀI LỚP(CLASS) VÀ KẾT HỢP VỚI MỘT CLASS KHÁC ĐỂ HIỂN THỊ NỘI DUNG public static void main(String[] args) { SeasonSP04 winter = SeasonSP04.WINTER; SeasonSP04 summer = SeasonSP04.SUMMER; System.out.println(winter.getValue()); //hiển thị ra tên tiếng việt của giá trị System.out.println(winter); //hiển thị ra chính giá trị đó System.out.println(winter == summer); //so sánh xem giá trị của 2 thằng có bằng (trùng) nhau hay không System.out.println(winter == winter); } }
package com.fhzz.psop.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.fhzz.psop.entity.UserInfo; @FeignClient(value = "psop-admin") public interface UserInfoService { @RequestMapping(value = "/user/findByUsername", method = RequestMethod.GET) UserInfo findByUsername(@RequestParam(value = "username") String username); }
package schr0.tanpopo.item; import net.minecraft.item.Item; import schr0.tanpopo.init.TanpopoItems; public class ItemAttachmentMattock extends ItemModeToolAttachment { public ItemAttachmentMattock() { super(); } @Override public Item getDefaultModeTool() { return TanpopoItems.TOOL_MATTOCK; } }
package net.sssanma.mc.usefulcmd; import net.minecraft.server.v1_7_R4.Item; import net.minecraft.server.v1_7_R4.ItemStack; import net.minecraft.server.v1_7_R4.RecipesFurnace; import net.minecraft.server.v1_7_R4.TileEntityFurnace; import net.sssanma.mc.ECore; import net.sssanma.mc.utility.NMSUtil; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.v1_7_R4.entity.CraftHumanEntity; import org.bukkit.craftbukkit.v1_7_R4.inventory.CraftInventoryFurnace; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.List; public class UsefulInstant extends UsefulCommandAndTabCompleter { public UsefulInstant() { super("instant", false, null); } @Override public Return execute(CommandSender sender, String[] cmd, int length, boolean fromConsole) { if (length == 1) { Player player = (Player) sender; if (cmd[0].equalsIgnoreCase("crafting")) { player.openWorkbench(null, true); } else if (cmd[0].equalsIgnoreCase("smelting")) { player.openInventory(new CraftInventoryFurnace(new TileEntityInstantFurnace())); } else if (cmd[0].equalsIgnoreCase("enchanting")) { player.openEnchanting(player.getLocation(), true); } } sender.sendMessage(ChatColor.RED + "/instant <crafting|smelting|enchanting>"); return Return.HELP_DISPLAYED; } @Override public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args, int length) { if (length == 1) return tabCompleteReturn(args[0], "crafting", "smelting", "enchanting"); return null; } public static class TileEntityInstantFurnace extends TileEntityFurnace { private InstanceFurnaceUpdater updater; public TileEntityInstantFurnace() { this.updater = new InstanceFurnaceUpdater(); } @Override public void h() { boolean flag = this.burnTime > 0; boolean flag1 = false; if (this.burnTime > 0) { --this.burnTime; } if (this.burnTime != 0 || getItem(1) != null && getItem(0) != null) { if (this.burnTime == 0 && this.canBurn()) { this.ticksForCurrentFuel = this.burnTime = fuelTime(getItem(1)); if (this.burnTime > 0) { flag1 = true; if (getItem(1) != null) { --getItem(1).count; if (getItem(1).count == 0) { Item item = getItem(1).getItem().t(); setItem(1, item != null ? new ItemStack(item) : null); } } } } if (this.isBurning() && this.canBurn()) { ++this.cookTime; if (this.cookTime == 200) { this.cookTime = 0; this.burn(); flag1 = true; } } else { this.cookTime = 0; } } if (flag != this.burnTime > 0) { flag1 = true; } if (flag1) { this.update(); } } public boolean canBurn() { if (getItem(0) == null) { return false; } else { ItemStack itemstack = RecipesFurnace.getInstance().getResult(getItem(0)); return itemstack == null ? false : (getItem(2) == null ? true : (!getItem(2).doMaterialsMatch(itemstack) ? false : (getItem(2).count < this.getMaxStackSize() && getItem(2).count < getItem(2).getMaxStackSize() ? true : getItem(2).count < itemstack.getMaxStackSize()))); } } @Override public void burn() { if (this.canBurn()) { ItemStack itemstack = RecipesFurnace.getInstance().getResult(getItem(0)); if (getItem(2) == null) { setItem(2, itemstack.cloneItemStack()); } else if (getItem(2).getItem() == itemstack.getItem()) { ++getItem(2).count; } --getItem(0).count; if (getItem(0).count <= 0) { setItem(0, null); } } } @Override public void onOpen(CraftHumanEntity who) { this.updater.runTaskTimer(ECore.getPlugin(), 0, 1); } @Override public void onClose(CraftHumanEntity who) { for (int i = 0; i < 3; i++) { if (getItem(i) != null) NMSUtil.dropItemFromPlayer(who, getItem(i)); setItem(i, null); } this.updater.cancel(); } private class InstanceFurnaceUpdater extends BukkitRunnable { @Override public void run() { if (transaction.size() > 0) h(); else cancel(); } } } }
package com.example.supplico_login; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class pdt_card extends AppCompatActivity { TextView hometext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pdt_card); hometext=findViewById(R.id.back_home); hometext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(pdt_card.this,home.class)); } }); } }
package model.impl; import java.util.Vector; import model.AccessPoint; import model.GridPoint; import model.PathLossModel; import model.ReceiverCardImpl; import model.Room; import model.Trajectory; import model.TxRadioImpl; import model.Wall; public class FreeSpaceLossModelImpl implements PathLossModel { private double freq_MHz; private double shad_margin; private double fade_margin; private double interf_margin; public double calculateMaxDist(double min_P_req,TxRadioImpl rad,int txheight,int RxHeight,ReceiverCardImpl rectype) { double total_margin=this.getTotalMargin(0); double maxPL=rad.getPt()+rad.getGain()+rectype.getRec_gain()-total_margin-min_P_req; return 100000*Math.pow(10, (maxPL-32.4-20*(Math.log10(freq_MHz)))/(20)); } public FreeSpaceLossModelImpl(double freq_MHz) { this.freq_MHz=freq_MHz; } public double getMaxPL(double TxP,double TxGain,double RxGain,double RxReq,double total_margin){ return TxP-RxReq+RxGain+TxGain-total_margin; } public double getFreq() { return freq_MHz; } public void setFreq_MHz(double freq_MHz) { this.freq_MHz = freq_MHz; } public Trajectory getLastbestTraj() { return null; } public double calculate_Pathloss(Room r, TransTxRadioImpl rad, GridPoint Rx,Vector<Wall> w, Trajectory posbestpath, double max_PL,Trajectory t) { return 32.4+20*(Math.log10(Rx.distance(rad.getParentAP().getCoordinates())/100000))+20*(Math.log10(this.freq_MHz)); } public double getDistanceloss(double dist, AccessPoint ap, GridPoint g) { return 32.4+20*(Math.log10(dist)/100000)+20*(Math.log10(this.freq_MHz)); } public double calculate_losPowerDensity(double trans_power, AccessPoint ap,GridPoint Rx, Vector<Wall> w) { double separation_Ap_Rx = Rx.distance(ap.getCoordinates()) / 100; // Tx separation from the AP double losPowerDensity = trans_power/ (4 * Math.PI * Math.pow(separation_Ap_Rx, 2)); // LOS power density Vector<Wall> tussenmuren = ap.determineWallsTxRx(Rx, w,true); // double cumulWallLoss = 0; double total_Transm_Factor_Linear = 1; for (int i = 0; i < tussenmuren.size(); i++) { double cumulWallLoss = ModelWall.getPenL(tussenmuren.elementAt(i).getMaterial(), tussenmuren.elementAt(i).getThickness()); total_Transm_Factor_Linear = total_Transm_Factor_Linear* (Math.pow(10,-cumulWallLoss/10)); } // double cumulWallLoss_Linear = Math.pow(10, -cumulWallLoss/10); // double total_Trans_Factor_Linear = 1-cumulWallLoss_Linear; // System.out.println("LOOOOS = "+total_Transm_Factor_Linear); losPowerDensity = losPowerDensity * total_Transm_Factor_Linear; /*if(Rx.getX()<120) System.out.println("RX location: "+Rx);*/ /*if(Rx.distance(110, 490)<0.1){ System.out.println("EUREKA $$$$$$$$$$$$$$$$$$$$$$$$"); System.out.println(); System.out.println("separation_Ap_Rx: "+separation_Ap_Rx); System.out.println("losPowerDensity: "+ losPowerDensity); System.out.println("losPowerDensity: "+losPowerDensity); for (int i = 0; i < tussenmuren.size(); i++) { double cumulWallLoss = ModelWall.getPenL(tussenmuren.elementAt(i).getMaterial(), tussenmuren.elementAt(i).getThickness()); System.out.println("cumulWallLoss "+i+" "+cumulWallLoss); System.out.println("total_Transm_Factor_Linear "+i+" "+total_Transm_Factor_Linear); total_Transm_Factor_Linear = total_Transm_Factor_Linear* (1 - Math.pow(10,-cumulWallLoss/10)); } System.out.println(); System.out.println(); }*/ return losPowerDensity; } public void setShadowingMargin(double shad_margin) { this.shad_margin=shad_margin; } public void setFadingMargin(double fade_margin) { this.fade_margin=fade_margin; } public void setInterferenceMargin(double interference_margin) { this.interf_margin=interference_margin; } public double getTotalMargin(double distance) { return this.fade_margin+this.interf_margin+this.shad_margin; } }
package gr.athena.innovation.fagi.core.function.geo; import gr.athena.innovation.fagi.specification.Namespace; import gr.athena.innovation.fagi.specification.SpecificationConstants; import org.apache.jena.datatypes.RDFDatatype; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.logging.log4j.LogManager; import org.junit.Test; import static org.junit.Assert.*; /** * * @author nkarag */ public class GeometriesCloserThanTest { private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger(GeometriesCloserThanTest.class); /** * Test of evaluate method, of class GeometriesCloserThan. */ @Test public void testEvaluate() { LOG.info("evaluate"); RDFDatatype geometryDatatype = Namespace.WKT_RDF_DATATYPE; GeometriesCloserThan instance = new GeometriesCloserThan(); String wktA = "POINT(38.03667880446578 23.80251648397791)"; Literal wktALiteral = ResourceFactory.createTypedLiteral(wktA, geometryDatatype); String wktB = "POINT (38.043919 23.804989)"; Literal wktBLiteral = ResourceFactory.createTypedLiteral(wktB, geometryDatatype); String tolerance1 = "850"; boolean expResult1 = true; boolean result = instance.evaluate(wktALiteral, wktBLiteral, tolerance1); assertEquals(expResult1, result); String tolerance2 = "800"; boolean expResult2 = false; boolean result2 = instance.evaluate(wktALiteral, wktBLiteral, tolerance2); assertEquals(expResult2, result2); String wktA3 = "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(38.03667880446578 23.80251648397791)^^http://www.opengis.net/ont/geosparql#wktLiteral"; Literal wktALiteral3 = ResourceFactory.createTypedLiteral(wktA3); String wktB3 = "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT (38.043919 23.804989)^^http://www.opengis.net/ont/geosparql#wktLiteral"; Literal wktBLiteral3 = ResourceFactory.createTypedLiteral(wktB3); String tolerance3 = "850"; boolean expResult3 = true; boolean result3 = instance.evaluate(wktALiteral3, wktBLiteral3, tolerance3); assertEquals(expResult3, result3); } /** * Test of getName method, of class GeometriesCloserThan. */ @Test public void testGetName() { LOG.info("getName"); GeometriesCloserThan instance = new GeometriesCloserThan(); String expResult = SpecificationConstants.Functions.GEOMETRIES_CLOSER_THAN; String result = instance.getName(); assertEquals(expResult, result); } }
package es.crud.spring.boot.thymeleaf.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import es.crud.spring.boot.thymeleaf.entity.Employee; public interface EmployeeRespository extends JpaRepository<Employee, Integer> { public List<Employee> findAllByOrderByLastNameAsc(); //it's all part of Spring Data JPA }
package com.guli.acl.service.impl; import com.guli.acl.entity.User; import com.guli.acl.mapper.UserMapper; import com.guli.acl.service.UserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 用户表 服务实现类 * </p> * * @author dtt * @since 2021-04-06 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { }
package com.biblio.theque.groupe8.domain; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; /** * A Theme. */ @Entity @Table(name = "theme") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Theme implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @NotNull @Size(max = 45) @Column(name = "theme", length = 45, nullable = false) private String theme; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTheme() { return theme; } public Theme theme(String theme) { this.theme = theme; return this; } public void setTheme(String theme) { this.theme = theme; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Theme)) { return false; } return id != null && id.equals(((Theme) o).id); } @Override public int hashCode() { return 31; } // prettier-ignore @Override public String toString() { return "Theme{" + "id=" + getId() + ", theme='" + getTheme() + "'" + "}"; } }
package jankenpon; /** * Possiveis Resultados de uma Partida de JanKenPon. * * @author Ana Luiza Cunha * */ public enum Resultado { VITORIA, DERROTA, EMPATE; }
package jp.astra.cameramap; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import jp.astra.cameramap.helper.ActivityUtil; import jp.astra.cameramap.helper.ArrayUtil; import jp.astra.cameramap.helper.Dictionary; import jp.astra.cameramap.helper.Logger; import jp.astra.cameramap.helper.Notify; import jp.astra.cameramap.helper.StringUtil; import jp.astra.cameramap.helper.Util; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.maps.GeoPoint; /** * @author Lau */ public class GalleryView extends MapActivity implements OnInfoWindowClickListener{ private ImageAdapter imageAdapter; private GridView gridview; private String[] files; private String fileSelected; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.gallery_view); this.inflateControls(this); Button buttonTakePicture = (Button)this.findViewById(R.id.takepicture); buttonTakePicture.setOnClickListener(this.captureButtonListener); Button buttonList = (Button)this.findViewById(R.id.gallerylist); buttonList.setOnClickListener(this.galleryListButtonListener); this.findViewById(R.id.photomap).setVisibility(View.INVISIBLE); Button buttonScreenshots = (Button)this.findViewById(R.id.screenshots); buttonScreenshots.setOnClickListener(this.reportButtonListener); Log.e("LAURICE", "GalleryView"); Button buttonPreview = (Button)this.findViewById(R.id.previewbtn); buttonPreview.setVisibility(View.VISIBLE); buttonPreview.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { Intent intent = new Intent(GalleryView.this, GalleryPreviewView.class); intent.putExtra("latitude", ""+GalleryView.this.latitude); intent.putExtra("longitude", ""+GalleryView.this.longitude); intent.putExtra("zoomLevel", ""+GalleryView.this.zoomLevel); intent.putExtra("width", ""+GalleryView.this.width); intent.putExtra("height", ""+GalleryView.this.height); intent.putExtra("markers", GalleryView.this.markerStr); intent.putExtra("filePath", GalleryView.this.files); intent.putExtra("imageFolder", GalleryView.this.imageFolder.getAbsolutePath()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); GalleryView.this.startActivity(intent); Logger.debug(GalleryView.this, "extras latitude :" + GalleryView.this.latitude); Logger.debug(GalleryView.this, "extras longitude :" + GalleryView.this.longitude); Logger.debug(GalleryView.this, "extras zoomLevel :" + GalleryView.this.zoomLevel); Logger.debug(GalleryView.this, "extras markerStr :" + GalleryView.this.markerStr); Logger.debug(GalleryView.this, "extras imageFolder :" + GalleryView.this.imageFolder.getAbsolutePath()); }}); this.progress.show(); if(Util.isReachable(this)){ new GalleryBackgroundTask().execute(); }else{ Notify.toast(this, "No network connection"); } } @Override public void onResume() { super.onResume(); Notify.toast(GalleryView.this, "scanning..."); MediaScannerConnection.scanFile(GalleryView.this, new String[] {GalleryView.this.imageFolder.getAbsolutePath()}, null, GalleryView.this.scanMediaListener); } @Override public void setContentView(int layoutId) { super.setContentView(layoutId); Bundle extras = this.getIntent().getExtras(); this.files = extras.getStringArray("filePath"); Log.e("LAURICE", "filePath: " + this.files.toString()); this.imageFolder = new File(Util.getExternalStoragePath(this)); this.imageAdapter = new ImageAdapter(); this.gridview = (GridView) this.findViewById(R.id.gallery_grid_view); this.gridview.setAdapter(this.imageAdapter); this.gridview.setOnItemClickListener(this.imageListener); this.gridview.setOnItemLongClickListener(this.imageLongClickListener); if (this.imageAdapter.isEmpty()) { TextView emptyListText = (TextView) this.findViewById(R.id.gallery_no_images_text); emptyListText.setVisibility(View.VISIBLE); } if(this.map == null){ GalleryView.this.map = ((MapFragment) GalleryView.this.getFragmentManager().findFragmentById(R.id.map)).getMap(); } this.map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition cameraPosition) { if (cameraPosition.zoom != GalleryView.this.oldZoom) { GalleryView.this.checkMarkers(GalleryView.this.map); } GalleryView.this.oldZoom = cameraPosition.zoom; GalleryView.this.latitude = Util.roundDecimals(cameraPosition.target.latitude); GalleryView.this.longitude = Util.roundDecimals(cameraPosition.target.longitude); GalleryView.this.zoomLevel = (int) cameraPosition.zoom; Logger.debug(GalleryView.this, "new latitude :" + GalleryView.this.latitude); Logger.debug(GalleryView.this, "new longitude :" + GalleryView.this.longitude); Logger.debug(GalleryView.this, "new zoom level :" + GalleryView.this.zoomLevel); // latLng = cameraPosition.target; } }); this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(this.latLng, 5)); this.zoomLevel = 5; } private MediaScannerConnection.OnScanCompletedListener scanMediaListener = new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { GalleryView.this.refreshGalleryHandler.sendEmptyMessage(0); } }; private OnItemClickListener imageListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long extra) { Dictionary bundle = new Dictionary(); bundle.setData("filepath", GalleryView.this.imageAdapter.getItem(position)); ActivityUtil.openActivityOnTop(GalleryView.this, PreviewView.class, bundle); } }; private OnItemLongClickListener imageLongClickListener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long extra) { GalleryView.this.fileSelected = (String) GalleryView.this.imageAdapter.getItem(position); Notify.prompt(GalleryView.this, "Delete " + StringUtil.fileBaseName(GalleryView.this.fileSelected) + "?", "Delete", "Cancel", GalleryView.this.deleteListener, null); return false; } }; private final DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { File file = new File(GalleryView.this.fileSelected); if(file.delete()){ GalleryView.this.progress.show(); GalleryView.this.files = ArrayUtil.removeString(GalleryView.this.files, GalleryView.this.fileSelected); if(Util.isReachable(GalleryView.this)){ GalleryView.this.map.clear(); GalleryView.this.markers = new ArrayList<Marker>(); GalleryView.this.fileNames = new HashMap<Marker, String>(); new GalleryBackgroundTask().execute(); }else{ Notify.toast(GalleryView.this, "No network connection"); } GalleryView.this.onResume(); } } }; public final Handler refreshGalleryHandler = new Handler() { @Override public void handleMessage(Message msg) { Notify.toast(GalleryView.this, "scanning complete!"); GalleryView.this.imageAdapter.notifyDataSetChanged(); GalleryView.this.gridview.invalidateViews(); GalleryView.this.hideProgressHandler.sendEmptyMessage(0); super.handleMessage(msg); } }; private class GalleryBackgroundTask extends BackgroundTask{ @Override protected Void doInBackground(Void... params) { for (String file : GalleryView.this.files) { LatLng location = GalleryView.this.setPhotoLocation(file); Log.e("LAURICE", "latlng: " + location); if(location != null){ GeoPoint point = new GeoPoint( (int) (location.latitude * 1E6), (int) (location.longitude * 1E6)); String locationName = StringUtil.ConvertPointToLocation(GalleryView.this, point); Details details = new Details(); details.locationName = locationName; details.location = location; details.filePath = file; this.publishProgress(details); } } return null; } } private class ImageAdapter extends BaseAdapter { private String[] filePaths; public ImageAdapter() { this.getImageFiles(); } @Override public boolean isEmpty() { return this.getCount() < 1; } @Override public int getCount() { return this.filePaths.length; } @Override public Object getItem(int position) { return this.filePaths[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater inflater = GalleryView.this.getLayoutInflater(); v = inflater.inflate(R.layout.gallery_row_view, null); } ImageView imageView = (ImageView)v.findViewById(R.id.imageGrid); TextView textView = (TextView)v.findViewById(R.id.filename); String imageFile = this.filePaths[position]; BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = 4; Bitmap imageBitmap = BitmapFactory.decodeFile(imageFile, o2); imageView.setImageBitmap(imageBitmap); textView.setText(StringUtil.fileBaseName(imageFile)); return v; } public void getImageFiles() { int count = 0; this.filePaths = new String[0]; for (String file : GalleryView.this.files) { this.filePaths = ArrayUtil.insertToStringArray(this.filePaths, file, count); count++; } if (count > 0) { GalleryView.this.findViewById(R.id.gallery_no_images_text).setVisibility(View.INVISIBLE); } else { GalleryView.this.findViewById(R.id.gallery_no_images_text).setVisibility(View.VISIBLE); } } @Override public void notifyDataSetChanged() { this.getImageFiles(); super.notifyDataSetChanged(); } } @Override protected void mapUpdate() { super.mapUpdate(); } }
package com.hesoyam.pharmacy.medicine.service.impl; import com.hesoyam.pharmacy.medicine.dto.MedicineDiscountInfoDTO; import com.hesoyam.pharmacy.medicine.dto.MedicineSearchDTO; import com.hesoyam.pharmacy.medicine.dto.MedicineSearchResultDTO; import com.hesoyam.pharmacy.medicine.exceptions.InvalidDeleteMedicineRequestException; import com.hesoyam.pharmacy.medicine.exceptions.MedicineNotFoundException; import com.hesoyam.pharmacy.medicine.mapper.MedicineMapper; import com.hesoyam.pharmacy.medicine.model.Medicine; import com.hesoyam.pharmacy.medicine.model.MedicineType; import com.hesoyam.pharmacy.medicine.repository.MedicineRepository; import com.hesoyam.pharmacy.medicine.service.IMedicineService; import com.hesoyam.pharmacy.pharmacy.model.InventoryItem; import com.hesoyam.pharmacy.pharmacy.service.IInventoryItemService; import com.hesoyam.pharmacy.user.model.LoyaltyAccount; import com.hesoyam.pharmacy.user.model.Patient; import com.hesoyam.pharmacy.user.service.ILoyaltyAccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityNotFoundException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Service public class MedicineService implements IMedicineService { @Autowired ILoyaltyAccountService loyaltyAccountService; @Autowired MedicineRepository medicineRepository; @Autowired IInventoryItemService inventoryItemService; @Override public Medicine get(Long id) { return medicineRepository.getOne(id); } @Override public List<Medicine> getAll() { return medicineRepository.findAll(); } @Override public Medicine create(Medicine medicine) { medicine.setId(null); //Since we don't use DTO, we want to make sure we are not updating a random medicine. return medicineRepository.save(medicine); } @Override public List<MedicineType> getAllMedicineTypes() { return Arrays.asList(MedicineType.values()); } @Override public List<Medicine> findByMedicineName(String name) { List<Medicine> medicines = medicineRepository.findAllByNameLike(name); if(medicines.isEmpty()) throw new EntityNotFoundException(); return medicines; } @Override public List<MedicineSearchResultDTO> search(MedicineSearchDTO medicineSearchDTO) { List<Medicine> medicines = medicineRepository.search(medicineSearchDTO, PageRequest.of(medicineSearchDTO.getPage()-1, 10)); return medicines.stream().map(medicine -> MedicineMapper.mapMedicineToMedicineResultDTO(medicine)).collect(Collectors.toList()); } @Override public Medicine findById(Long id) throws MedicineNotFoundException { return medicineRepository.findById(id).orElseThrow(() -> new MedicineNotFoundException(id)); } @Override public MedicineDiscountInfoDTO getMedicinePriceByPharmacy(Long pharmacyId, Long medicineId, Patient patient) { InventoryItem inventoryItem = inventoryItemService.getInventoryItemByPharmacyIdAndMedicineId(pharmacyId, medicineId); if(inventoryItem == null) throw new EntityNotFoundException(); double currentPrice = inventoryItem.getTodayPrice(); double discountedPrice = currentPrice; MedicineDiscountInfoDTO medicineDiscountInfoDTO = new MedicineDiscountInfoDTO(currentPrice, discountedPrice); if(patient != null){ LoyaltyAccount loyaltyAccount = loyaltyAccountService.getPatientLoyaltyAccount(patient); medicineDiscountInfoDTO.setHasDiscount(true); medicineDiscountInfoDTO.setDiscountedPrice(loyaltyAccount.getDiscountedPrice(currentPrice)); } return medicineDiscountInfoDTO; } @Override public void delete(Long medicineId) { try{ Medicine medicine = medicineRepository.getOne(medicineId); medicineRepository.delete(medicine); }catch (DataIntegrityViolationException e){ throw new InvalidDeleteMedicineRequestException("Medicine is used, so you can't delete it."); } } @Override public void updateRating(Long id, double rating) throws MedicineNotFoundException { Medicine medicine = medicineRepository.findById(id).orElseThrow(() -> new MedicineNotFoundException(id)); medicine.setRating(rating); medicineRepository.save(medicine); } @Transactional(propagation = Propagation.REQUIRED) public boolean checkAvailability(String medicineName, int quantity, long pharmacyId) { Medicine medicine = medicineRepository.findByName(medicineName); int stock = inventoryItemService.getInventoryItemByPharmacyIdAndMedicineId(pharmacyId, medicine.getId()).getAvailable(); if(stock > quantity) return true; else return false; } }
package LeetCode; import java.util.ArrayList; import java.util.List; public class Sample_2 { static List<Integer> oddNumbers(int l, int r) { List<Integer> li = new ArrayList<>() ; while(l<=r){ if(l%2!=0){ li.add(l); } l++; } return li; } }
/** * ファイル名 : PaginationController.java * 作成者 : minh.nt * 作成日時 : 2018/5/31 * Copyright © 2017-2018 TAU Corporation. All Rights Reserved. */ package jp.co.tau.web7.admin.supplier.controllers; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.RollbackException; import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindingResult; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import jp.co.tau.web7.admin.supplier.common.CommonConstants; import jp.co.tau.web7.admin.supplier.common.CommonConstants.MessageType; import jp.co.tau.web7.admin.supplier.common.MessageConstants; import jp.co.tau.web7.admin.supplier.dto.CSVDTO; import jp.co.tau.web7.admin.supplier.dto.MasterBaseDTO; import jp.co.tau.web7.admin.supplier.dto.OtherUploadImageDTO; import jp.co.tau.web7.admin.supplier.dto.UploadCSVDTO; import jp.co.tau.web7.admin.supplier.dto.search.BaseSearchDTO; import jp.co.tau.web7.admin.supplier.forms.AppForm; import jp.co.tau.web7.admin.supplier.forms.OtherUploadImageForm; import jp.co.tau.web7.admin.supplier.forms.UploadCSVForm; import jp.co.tau.web7.admin.supplier.forms.UploadFileCSVForm; import jp.co.tau.web7.admin.supplier.output.BaseOutput; import jp.co.tau.web7.admin.supplier.services.master.MasterBaseService; import jp.co.tau.web7.admin.supplier.utils.Utilities; import jp.co.tau.web7.admin.supplier.vo.MasterBaseVO; import jp.co.tau.web7.admin.supplier.vo.MessageVO; /** * <p>クラス名 : Pagination controller</p> * <p>説明 : FIXME TableController</p> * @author : minh.nt * @since 2018/5/31 */ public abstract class PaginationController extends AppController { /** PAGE_NUM_ON_SCREEN = 5 */ private static final int PAGE_NUM_ON_SCREEN = 10; /** PAGE = "page" */ private static final String PAGE = "page"; /** CURENT_PAGE = "currentPage" */ private static final String TABLE_CURENT_PAGE = "currentPage"; /** TOTAL_ROW_COUNT = "totalRowCount" */ private static final String TOTAL_RECORD = "totalRecord"; /** DISPLAY_DATA = "displayData" */ private static final String DISPLAY_DATA = "displayData"; /** START_ROW = "startRow"*/ private static final String START_ROW = "startRow"; /** TOTAL_PAGE = "totalPage" */ protected static final String TOTAL_PAGE = "totalPage"; /** * FIXME Confirm lại xem có cần thiết tạo ra method này không? * <p>説明 : getFirstElement</p> * @author : minh.nt * @since : 2017/12/27 * @param page FIXME page id * @return FIXME start row */ protected int getFirstElement(int page) { int currentRow = page; if (page < 1) { currentRow = 1; } int startRow = (currentRow - 1) * CommonConstants.GRID_ROW_COUNT; return startRow; } /** * * <p>説明 : setDisplayDataOnPage</p> * @author : minh.nt * @since : 2017/12/27 * @param page int * @param totalPage int * @return displayData List<Integer> */ protected List<Integer> setDisplayDataOnPage(int page, int totalPage) { int last = 0; int isOdd = PAGE_NUM_ON_SCREEN % 2; if (page > (PAGE_NUM_ON_SCREEN / 2 + isOdd)) { last = Math.min(page + (PAGE_NUM_ON_SCREEN / 2), totalPage); } else { last = Math.min(PAGE_NUM_ON_SCREEN, totalPage); } int first = Math.max(1, last - (PAGE_NUM_ON_SCREEN - 1)); List<Integer> displayData = new ArrayList<Integer>(); for (int i = first; i <= last; i++) { displayData.add(i); } return displayData; } /** * * <p>説明 : getPrevElement</p> * @author : minh.nt * @since : 2017/12/27 * @param mdCd Integer * @param list List<Integer> * @return Integer */ protected int getPrevElement(int mdCd, List<Integer> list) { int idPrev = -1; if (list != null) { for (int i = 0; i < list.size(); i++) { if (list.get(i) == mdCd) { idPrev = (i == 0) ? -1 : list.get(i - 1); break; } } } return idPrev; } /** * * <p>説明 : getPrevElement</p> * @author : hung.nq * @since 2018/02/23 * @param mdCd mdCd * @param list list * @return String */ protected String getPrevElement(String mdCd, List<String> list) { String idPrev = ""; if (list != null) { for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(mdCd)) { idPrev = (i == 0) ? "" : list.get(i - 1); break; } } } return idPrev; } /** * <p>説明 : get prev obj detail</p> * @author : truong.dx * @since : 2018/02/08 * @param item HashMap<String, Object> * @param itmList List<HashMap<String, Object>> * @return HashMap<String, Object> */ protected HashMap<String, Object> getPrevElementByHashMap(HashMap<String, Object> item, List<HashMap<String, Object>> itmList) { int pos = itmList.indexOf(item); if (pos > 0) { return itmList.get(pos - 1); } return null; } /** * <p>説明 : get next obj detail</p> * @author : truong.dx * @since : 2018/02/08 * @param item HashMap<String, Object> * @param itmList List<HashMap<String, Object>> * @return HashMap<String, Object> */ protected HashMap<String, Object> getNextElementByHashMap(HashMap<String, Object> item, List<HashMap<String, Object>> itmList) { int pos = itmList.indexOf(item); if (pos < itmList.size() - 1 && pos != -1) { return itmList.get(pos + 1); } return null; } /** * * <p>説明 : getNextElement</p> * @author : thien.nv * @since 2017/12/25 * @param mdCd Integer * @param list List<Integer> * @return Integer */ protected int getNextElement(int mdCd, List<Integer> list) { int idNext = -1; if (list != null) { for (int i = 0; i < list.size(); i++) { if (list.get(i) == mdCd) { idNext = (i == (list.size() - 1)) ? -1 : list.get(i + 1); break; } } } return idNext; } /** * * <p>説明 : getNextElement</p> * @author : hung.nq * @since 2018/02/23 * @param cd code * @param list list * @return String */ protected String getNextElement(String cd, List<String> list) { String idNext = ""; if (list != null) { for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(cd)) { idNext = (i == (list.size() - 1)) ? "" : list.get(i + 1); break; } } } return idNext; } /** * * <p>説明 : Binding data pagination</p> * @author : minh.nt * @since 2018/05/31 * @param modelAndView ModelAndView * @param page int * @param totalRecord int */ protected void setPaginationData(ModelAndView modelAndView, int page, int totalRecord) { int offset = getOffsetByPage(page); int totalPage = getTotalPage(totalRecord); modelAndView.addObject(TOTAL_RECORD, totalRecord); modelAndView.addObject(DISPLAY_DATA, setDisplayDataOnPage(page, totalPage)); modelAndView.addObject(START_ROW, offset); modelAndView.addObject(PAGE, 1); modelAndView.addObject(TABLE_CURENT_PAGE, page == 0 ? 1 : page); modelAndView.addObject(TOTAL_PAGE, totalPage); } /** * * <p>説明 : Binding data pagination with one page only</p> * @author : hung.nq * @since 2018/05/31 * @param modelAndView ModelAndView * @param page int * @param totalRecord int */ protected void setPaginationData(ModelAndView modelAndView, int totalRecord) { int offset = getOffsetByPage(1); modelAndView.addObject(TOTAL_RECORD, totalRecord); modelAndView.addObject(START_ROW, offset); modelAndView.addObject(PAGE, 1); modelAndView.addObject(TABLE_CURENT_PAGE, 1); modelAndView.addObject(TOTAL_PAGE, 1); } /** * <p>説明 : FIXME get curent record by page index</p> * @author : minh.ls * @since 2018/02/12 * @param page page number * @return curent record */ protected int getOffsetByPage(Integer page) { if (page == null || page <= 1) { return 0; } else { return (page - 1) * CommonConstants.GRID_ROW_COUNT; } } /** * <p>説明 : FIXME get total page by total record</p> * @author : minh.ls * @since 2018/02/10 * @param totalRecord total of record * @return total page */ private int getTotalPage(int totalRecord) { return (int) Math.ceil((double) totalRecord / CommonConstants.GRID_ROW_COUNT); } /** * <p>説明 : FIXME copy data when paging</p> * @author : minh.ls * @since 2018/02/23 * @param formSource : AppForm Source * @param formDestination : AppForm Destination */ protected void copyPaginationSortData(AppForm formSource, AppForm formDestination) { int page = formSource.getPage(); String sortType = formSource.getSortType(); int sortIndex = formSource.getSortIndex(); Utilities.map(formDestination, formSource); formSource.setPage(page); formSource.setSortType(sortType); formSource.setSortIndex(sortIndex); } /** * mng3104Service */ protected ModelAndView initSearch(boolean isSearch, MasterBaseService service, Map<String, Object> configData) { String viewName = (String) configData.get(CommonConstants.SEARCH_SCREEN); ModelAndView modelAndView = createView(configData, viewName); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); // get form name String formName = (String) configData.get(CommonConstants.SEARCH_FORM); // 検索条件取得 AppForm appForm = (AppForm) getObjectFromSession(session, formName); // VO 名称 String voName = (String) configData.get(CommonConstants.VO); // Object voOBJ Object voObj; // 検索VO MasterBaseVO searchVO = null; // セッションに保存する addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.ONE_NUMBER); try { // 検索の実施チェック if (appForm != null && isSearch) { // 検索を実施 return doSearch(appForm, null, service, configData); } else { voObj = voClazz.newInstance(); searchVO = (MasterBaseVO) voObj; // get form class Class<?> formClazz = (Class<?>) configData.get(CommonConstants.SEARCH_CLAZZ); // フォーム初期 if (appForm == null) { Object object = formClazz.newInstance(); appForm = (AppForm) object; } // 初期データ取得 BaseOutput output = service.initSearch(null); // 検索VOを変換する if (output != null) { searchVO = (MasterBaseVO) modelMapper.map(output, voClazz); } } } catch (Exception ex) { ex.printStackTrace(); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); } setDataInitSearch(modelAndView, appForm, searchVO, formName, voName); return modelAndView; } /** * * <p>説明 : 検索処理</p> * @author : duc.bv * @since : 2018/03/13 * @param searchForm * @param result BindingResult * @param mng31040XService 該当サビース * @param configData 該当Controllerの設定 * @return ModelAndView */ protected ModelAndView doSearch(AppForm searchForm, BindingResult result, MasterBaseService mng31040XService, Map<String, Object> configData) { return doSearch(searchForm, result, mng31040XService, configData, false); } /** * * <p>説明 : 検索処理</p> * @author : duc.bv * @since : 2018/03/13 * @param searchForm * @param result BindingResult * @param service 該当サビース * @param configData 該当Controllerの設定 * @param withValidate チェックフラグ * @return ModelAndView */ protected ModelAndView doSearch(AppForm searchForm, BindingResult result, MasterBaseService service, Map<String, Object> configData, boolean withValidate) { String viewName = (String) configData.get(CommonConstants.SEARCH_SCREEN); ModelAndView modelAndView = createView(configData, viewName); try { searchForm = (AppForm) Utilities.trim(searchForm); searchForm.setScreenName(viewName); if (withValidate) { validate(searchForm, result); if (result.hasErrors()) { reloadSearchErrorData(modelAndView, service, configData, searchForm); return modelAndView; } } // get form name String formName = (String) configData.get(CommonConstants.SEARCH_FORM); // ページ・ソートのクリックチェック if (searchForm.isPaging()) { // セッションの検索条件取得 AppForm gradeSearch = (AppForm) getObjectFromSession(session, formName); copyPaginationSortData(searchForm, gradeSearch); } Class<?> searchDTO = (Class<?>) configData.get(CommonConstants.DTO_SEARCH_CLAZZ); BaseSearchDTO searchConditionDTO = (BaseSearchDTO) searchDTO.newInstance(); // フォームから、DTOに変換 modelMapper.map(searchForm, searchConditionDTO); // 検索実施 BaseOutput baseOuput = service.doSearch(searchConditionDTO); searchConditionDTO.setPage(baseOuput.getPage()); // ページ設定 if (searchConditionDTO.getLimit() > 0) { setPaginationData(modelAndView, baseOuput.getPage(), baseOuput.getTotalRowCount()); } else { setPaginationData(modelAndView, baseOuput.getTotalRowCount()); } // 検索条件をセッションに保存する addObjectToSession(formName, searchForm); String voName = (String) configData.get(CommonConstants.VO); Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO baseVO = (MasterBaseVO) modelMapper.map(baseOuput, voClazz); baseVO.initHeader(); baseVO.setHeaderSize(Utilities.getHeaderSize(baseVO.getHeaders())); // フォームにデータをinjectする setDataInitSearch(modelAndView, searchForm, baseVO, formName, voName); } catch (Exception e) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); reloadSearchErrorData(modelAndView, service, configData, searchForm); } // 3.レスポンスデータ設定 return modelAndView; } private void setDataInitSearch(ModelAndView modelAndView, AppForm appForm, MasterBaseVO masterBaseVO, String formName, String voName) { // 3.レスポンスデータ設定 modelAndView.addObject(formName, appForm); modelAndView.addObject(voName, masterBaseVO); } protected ModelAndView intDetail(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData) { return intDetail(initInfo, service, configData, false); } /** * * <p>説明 :紹介画面</p> * @author : duc.bv * @since : 2018/03/12 * @param initInfo 紹介データ * @param service 該当サビース * @param configData 該当Controllerの設定 * @return modelAndView 画面表示 */ protected ModelAndView intDetail(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData, boolean ignoreSearchData) { // init detail screen String viewName = (String) configData.get(CommonConstants.DETAIL_SCREEN); removeObjectFromSession(CommonConstants.CURRENT_TAB); // ModelAndViewを作成 ModelAndView modelAndView = createView(configData, viewName); try { String searchResultCdKey = (String) configData.get(CommonConstants.RESULT_CD); Object resultResult = getObjectFromSession(searchResultCdKey); initInfo.put(CommonConstants.RESULT_CD, resultResult); // get form class Class<?> formClazz = (Class<?>) configData.get(CommonConstants.SEARCH_CLAZZ); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); // get form name String formName = (String) configData.get(CommonConstants.SEARCH_FORM); // 検索条件取得 AppForm appForm = resultResult == null ? (AppForm) getObjectFromSession(session, formName) : null; // 検索条件チェック appForm = appForm == null ? (AppForm) formClazz.newInstance() : appForm; Class<?> dtoClazz = (Class<?>) configData.get(CommonConstants.DTO_SEARCH_CLAZZ); // DTOに変換する if (!ignoreSearchData) { BaseSearchDTO searchData = (BaseSearchDTO) modelMapper.map(appForm, dtoClazz); initInfo.put(CommonConstants.SEARCH_DTO_NAME, searchData); } String resultCd = (String) configData.get(CommonConstants.RESULT_CD); initInfo.put(CommonConstants.RESULT_CD, getObjectFromSession(resultCd)); BaseOutput baseOuput = service.initDetail(initInfo); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.DETAIL_ACTION); if (baseOuput == null || baseOuput.getDetailDTO() == null) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_468)); return modelAndView; } // グレード情報取得 addObjectToSession(resultCd, baseOuput.getResultCdList()); MasterBaseVO outPutVO = (MasterBaseVO) modelMapper.map(baseOuput, voClazz); // レスポンスデータ設定 modelAndView.addObject((String) configData.get(CommonConstants.VO), outPutVO); } catch (Exception e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); } return modelAndView; } /** * * <p>説明 : FIXME Mô tả ý nghia method</p> * @author : duc.bv * @since : 2018/03/12 * @param initInfo * @param service * @param configData * @return FIXME Mô nghĩa param/return */ protected ModelAndView initUpdate(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData) { return initUpdate(initInfo, service, configData, null); } protected ModelAndView initUpdate(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData, AppForm appForm) { // init detail screen String viewName = (String) configData.get(CommonConstants.UPDATE_SCREEN); // ModelAndViewを作成 ModelAndView modelAndView = createView(configData, viewName); modelAndView.addObject(CommonConstants.SCREEN_ACTION, CommonConstants.REGISTER_ACTION); try { // グレード情報取得 BaseOutput output = service.initUpdate(initInfo); if (output == null) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_468)); return modelAndView; } // 初期データの表示データ設定 loadUpdateInfo(modelAndView, output, configData, appForm); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.UPDATE_ACTION); removeObjectFromSession(CommonConstants.CURRENT_TAB); } catch (Exception e) { logger.info(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); return modelAndView; } return modelAndView; } /** * * <p>説明 : 更新・登録画面の初期表表示データ取得</p> * @author : duc.bv * @since : 2018/02/26 * @param modelAndView ModelAndView * @param gradeOutput GradeOutput */ private void loadUpdateInfo(ModelAndView modelAndView, BaseOutput output, Map<String, Object> configData, AppForm appForm) { // グレードフォーム作成 if (appForm == null) { Class<?> form = (Class<?>) configData.get(CommonConstants.UPDATE_FOM_CLAZZ); appForm = (AppForm) modelMapper.map(output.getDetailDTO(), form); } // グレードフォーム作成 Class<?> vo = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO resultVO = (MasterBaseVO) modelMapper.map(output, vo); String VO = (String) configData.get(CommonConstants.VO); modelAndView.addObject(VO, resultVO); modelAndView.addObject((String) configData.get(CommonConstants.UPDATE_FORM), appForm); } /** * <?> * <p>説明 : FIXME Mô tả ý nghia method</p> * @author : duc.bv * @since : 2018/03/12 * @param appForm * @param result * @param service * @param configData * @return FIXME Mô nghĩa param/return */ protected ModelAndView doUpdate(AppForm appForm, BindingResult result, MasterBaseService service, Map<String, Object> configData) { // init detail screen String viewName = (String) configData.get(CommonConstants.UPDATE_SCREEN); ModelAndView modelAndView = createView(configData, viewName); modelAndView.addObject(CommonConstants.SCREEN_ACTION, CommonConstants.UPDATE_ACTION); // データをマッピング Class<?> dtoClazz = (Class<?>) configData.get(CommonConstants.DTO_CLAZZ); MasterBaseDTO dto = (MasterBaseDTO) modelMapper.map(appForm, dtoClazz); copyCreateInfo(dto); try { appForm.setScreenName(viewName); // 入力チェック validate(appForm, result); if (result.hasErrors()) { reloadUpdateErrorData(modelAndView, service, configData, appForm, dto); return modelAndView; } String searchResultCdKey = (String) configData.get(CommonConstants.RESULT_CD); Map<String, Object> updateInfo = new HashMap<String, Object>(); Object resultCd = getObjectFromSession(searchResultCdKey); if (resultCd == null) { resultCd = new ArrayList<Object>(); } updateInfo.put(CommonConstants.RESULT_CD, resultCd); updateInfo.put(CommonConstants.DTO_NAME, dto); // グレードを更新 BaseOutput output = service.doUpdate(updateInfo); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定 modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.UPDATE_ACTION); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.INFO.toString(), MessageConstants.MSG_304)); // ビューア名設定 // TODO // 画面移動・紹介画面を表示チェックフラグ setViewName(modelAndView, (String) configData.get(CommonConstants.DETAIL_SCREEN)); } catch (RollbackException e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); addErrorMsg(modelAndView, e.getMessage()); // reloadUpdateErrorData(modelAndView, service, configData, appForm, dto); } catch (Exception e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); addErrorMsg(modelAndView, MessageConstants.MSG_1296); // reloadUpdateErrorData(modelAndView, service, configData, appForm, dto); } return modelAndView; } /** * * <p>説明 : FIXME Mô tả ý nghia method</p> * @author : duc.bv * @since : 2018/03/12 * @param initInfo * @param service * @param configData * @param appForm * @return FIXME Mô nghĩa param/return */ protected ModelAndView initAdd(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData) { return initAdd(initInfo, service, configData, null); } protected ModelAndView initAdd(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData, AppForm appForm) { // init detail screen String viewName = (String) configData.get(CommonConstants.INSERT_SCREEN); ModelAndView modelAndView = createView(configData, viewName); modelAndView.addObject(CommonConstants.SCREEN_ACTION, CommonConstants.REGISTER_ACTION); addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.TWO_NUMBER); try { BaseOutput output = service.initInsert(initInfo); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定+ modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); // グレードフォーム作成 if (appForm == null) { Class<?> form = (Class<?>) configData.get(CommonConstants.UPDATE_FOM_CLAZZ); appForm = (AppForm) form.newInstance(); } String VO = (String) configData.get(CommonConstants.VO); modelAndView.addObject(VO, outputVO); modelAndView.addObject((String) configData.get(CommonConstants.UPDATE_FORM), appForm); } catch (Exception e) { logger.info(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); return modelAndView; } return modelAndView; } /** * * <p>説明 : FIXME Mô tả ý nghia method</p> * @author : duc.bv * @since : 2018/03/12 * @param appForm * @param result * @param service * @param configData * @return FIXME Mô nghĩa param/return */ protected ModelAndView doAdd(AppForm appForm, BindingResult result, MasterBaseService service, Map<String, Object> configData) { // init detail screen String viewName = (String) configData.get(CommonConstants.INSERT_SCREEN); ModelAndView modelAndView = createView(configData, viewName); appForm.setScreenName(viewName); // フォームチェック validate(appForm, result); modelAndView.addObject(CommonConstants.SCREEN_ACTION, CommonConstants.REGISTER_ACTION); // データをマッピング Class<?> dtoClazz = (Class<?>) configData.get(CommonConstants.DTO_CLAZZ); MasterBaseDTO dto = (MasterBaseDTO) modelMapper.map(appForm, dtoClazz); copyCreateInfo(dto); if (result.hasErrors()) { // エラーデータ取得 reloadInsertErrorData(modelAndView, service, configData, appForm, dto); // 画面レイアウト戻る return modelAndView; } try { Map<String, Object> updateInfo = new HashMap<String, Object>(); updateInfo.put(CommonConstants.DTO_NAME, dto); // グレードを更新 BaseOutput output = service.doInsert(updateInfo); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定 modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.REGISTER_ACTION); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.INFO.toString(), MessageConstants.MSG_304)); // ビューア名設定 setViewName(modelAndView, (String) configData.get(CommonConstants.DETAIL_SCREEN)); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.INFO.toString(), MessageConstants.MSG_303)); } catch (RollbackException ex) { logger.error(ex.getMessage()); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); // エラーデータ取得 addErrorMsg(modelAndView, ex.getMessage()); // メッセージ追加 reloadInsertErrorData(modelAndView, service, configData, appForm, dto); return modelAndView; } catch (Exception e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); addErrorMsg(modelAndView, MessageConstants.MSG_1296); // エラーデータ取得 reloadInsertErrorData(modelAndView, service, configData, appForm, dto); return modelAndView; } return modelAndView; } /** * * <p>説明 : 更新・登録画面の初期表表示データ取得</p> * @author : duc.bv * @since : 2018/02/26 * @param modelAndView ModelAndView */ private void reloadInsertErrorData(ModelAndView modelAndView, MasterBaseService service, Map<String, Object> configData, AppForm appForm, MasterBaseDTO dto) { configData.put(CommonConstants.APP_TRANSFER_DTO, dto); // グレード情報取得*/ modelAndView.addObject((String) configData.get(CommonConstants.UPDATE_FORM), appForm); BaseOutput output = service.doInsertError(configData); if (output != null) { // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定+ modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); String vo = (String) configData.get(CommonConstants.VO); modelAndView.addObject(vo, outputVO); } } /** * * <p>説明 : reloadUpdateErrorData</p> * @author : duc.bv * @since : 2018/02/26 * @param modelAndView ModelAndView */ private void reloadUpdateErrorData(ModelAndView modelAndView, MasterBaseService service, Map<String, Object> configData, AppForm appForm, MasterBaseDTO dto) { configData.put(CommonConstants.APP_TRANSFER_DTO, dto); modelAndView.addObject((String) configData.get(CommonConstants.UPDATE_FORM), appForm); // グレード情報取得*/ BaseOutput output = service.doUpdateError(configData); if (output != null) { // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定+ modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); String vo = (String) configData.get(CommonConstants.VO); modelAndView.addObject(vo, outputVO); } } /** * * <p>説明 : reloadSearchErrorData</p> * @author : duc.bv * @since : 2018/02/26 * @param modelAndView ModelAndView */ private void reloadSearchErrorData(ModelAndView modelAndView, MasterBaseService service, Map<String, Object> configData, AppForm appForm) { // グレード情報取得*/ BaseOutput output = service.initSearch(configData); if (output != null) { // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定+ String voName = (String) configData.get(CommonConstants.VO); // get form name String formName = (String) configData.get(CommonConstants.SEARCH_FORM); setDataInitSearch(modelAndView, appForm, outputVO, formName, voName); } } /** * * <p>説明 : 削除画面の初期表示</p> * @author : duc.bv * @since : 2018/03/13 * @param initInfo 削除情報 * @param service 該当サービス * @param configData 該当Controllerの設定 * @return modelAndView ModelAndView */ protected ModelAndView initDelete(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData) { // init detail screen String viewName = (String) configData.get(CommonConstants.DELETE_SCREEN); // ModelAndViewを作成 ModelAndView modelAndView = createView(configData, viewName); try { // get VO class BaseOutput baseOuput = service.initDelete(initInfo); // get form class name Class<?> deleteFormClassName = (Class<?>) configData.get(CommonConstants.DELETE_FORM_CLASS); if (baseOuput.getDetailDTO() == null) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_14)); return modelAndView; } // create app form AppForm appForm = (AppForm) modelMapper.map(baseOuput.getDetailDTO(), deleteFormClassName); if (initInfo.containsKey("isLoadDetail")) { boolean isLoadDetail = (boolean) initInfo.get("isLoadDetail"); if (isLoadDetail) { // 初期データの表示データ設定 loadDeleteInfo(modelAndView, baseOuput, configData); } } // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(baseOuput, voClazz); // レスポンスデータ設定 modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); modelAndView.addObject((String) configData.get(CommonConstants.DELETE_FORM), appForm); removeObjectFromSession(CommonConstants.CURRENT_TAB); } catch (Exception e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); } return modelAndView; } /** * * <p>説明 : 削除情報画面のデータ取得</p> * @author : duc.bv * @since : 2018/03/13 * @param modelAndView ModelAndView * @param output BaseOutput * @param configData 該当Controllerの設定 */ private void loadDeleteInfo(ModelAndView modelAndView, BaseOutput output, Map<String, Object> configData) { Class<?> vo = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO resultVO = (MasterBaseVO) modelMapper.map(output, vo); String VO = (String) configData.get(CommonConstants.VO); modelAndView.addObject(VO, resultVO); } /** * * <p>説明 : データを削除</p> * @author : duc.bv * @since : 2018/03/13 * @param appForm 削除フォーム * @param result BindingResult * @param service 該当サビース * @param configData 該当Controllerの設定 * @return ModelAndView */ protected ModelAndView doDelete(AppForm appForm, BindingResult result, MasterBaseService service, Map<String, Object> configData) { // init delete String viewName = (String) configData.get(CommonConstants.DELETE_SCREEN); ModelAndView modelAndView = createView(configData, viewName); try { appForm.setScreenName(viewName); // 入力チェック validate(appForm, result); if (result.hasErrors()) { // TODO can phai add them logic xu ly khi get lai thong tin VO vao day modelAndView.addObject((String) configData.get(CommonConstants.DELETE_FORM), appForm); return modelAndView; } // データをマッピング Class<?> dtoClazz = (Class<?>) configData.get(CommonConstants.DTO_CLAZZ); MasterBaseDTO dto = (MasterBaseDTO) modelMapper.map(appForm, dtoClazz); copyDeleteInfo(dto); Map<String, Object> updateInfo = new HashMap<String, Object>(); updateInfo.put(CommonConstants.DTO_NAME, dto); BaseOutput output = service.doDelete(updateInfo); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.DELETE_ACTION); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.INFO.toString(), MessageConstants.MSG_305)); // ビューア名設定 setViewName(modelAndView, (String) configData.get(CommonConstants.DETAIL_SCREEN)); } catch (Exception ex) { addErrorMsg(modelAndView, MessageConstants.MSG_1296); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); } return modelAndView; } /** * * <p>説明 : initial screen import csv</p> * @author : duc.bv * @param screenName Screen ID * @return page import csv */ protected ModelAndView initImportCSV(String screenName) { ModelAndView modelAndView = createViewNameMaster(screenName); addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.THREE_NUMBER); modelAndView.addObject(CommonConstants.UPLOAD_FILE_CSV_FORM, new UploadFileCSVForm()); return modelAndView; } protected ModelAndView initImportCSV(String screenName, Map<String, Object> extraParams) { ModelAndView modelAndView = createViewNameMaster(screenName); addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.THREE_NUMBER); UploadFileCSVForm uploadForm = new UploadFileCSVForm(); uploadForm.setExtraParams(extraParams); modelAndView.addObject(CommonConstants.UPLOAD_FILE_CSV_FORM, uploadForm); return modelAndView; } /** * * <p>説明 : initial screen import csv with view type</p> * @author : minh.ls * @param screenName Screen ID * @param configData map config data * @return page import csv */ protected ModelAndView initImportCSVCusView(String screenName, Map<String, Object> configData) { ModelAndView modelAndView = createView(configData, screenName); addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.THREE_NUMBER); modelAndView.addObject(CommonConstants.UPLOAD_FILE_CSV_FORM, new UploadFileCSVForm()); return modelAndView; } /** * <p>説明 : doUploadCSV</p> * @author duc.bv * @param uploadFileCSVForm Data form upload csv file * @param result Binding result message error * @param service Clazz service implement * @param configData Configuration controller * @return Page read csv */ protected <T extends UploadFileCSVForm> ModelAndView doUploadCSV(T uploadFileCSVForm, BindingResult result, MasterBaseService service, Map<String, Object> configData) { String viewName = (String) configData.get(CommonConstants.CSV_SCREEN); ModelAndView modelAndView = createView(configData, viewName); Map<String, Object> info = null; Class<?> dtoClazz = (Class<?>) configData.get(CommonConstants.DTO_CLAZZ); if (dtoClazz != null) { MasterBaseDTO dto = (MasterBaseDTO) modelMapper.map(uploadFileCSVForm, dtoClazz); info = new HashMap<String, Object>(); info.put(CommonConstants.DTO_NAME, dto); } try { // ファイル必須チェック if (result.hasErrors() || uploadFileCSVForm.getCsvFile().isEmpty()) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_SC101)); return modelAndView; } BaseOutput output = service.initImportCSV(info); if (output != null) { // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定+ String vo = (String) configData.get(CommonConstants.VO); modelAndView.addObject(vo, outputVO); logger.debug("VO class {}", voClazz.getName()); logger.debug("Attribute VO {}", vo); } // フォームチェック validate(uploadFileCSVForm, result); if (result.hasErrors()) { return responseErrorCSV(uploadFileCSVForm, modelAndView); } // CSVファイルチェック MultipartFile multipartFile = uploadFileCSVForm.getCsvFile(); String fileName = multipartFile.getOriginalFilename().toLowerCase(); if (!fileName.endsWith(CommonConstants.CSV_EXTENTION)) { result.rejectValue(CommonConstants.FIELD_CSV_FILE, MessageConstants.MSG_1413); return responseErrorCSV(uploadFileCSVForm, modelAndView); } // CSVファイル読込む CSVDTO csvDTO = null; if (uploadFileCSVForm instanceof UploadFileCSVForm) { UploadFileCSVForm form = (UploadFileCSVForm) uploadFileCSVForm; if (form.getExtraParams() != null) { csvDTO = (CSVDTO) service.readCSV(multipartFile.getInputStream(), form.getExtraParams()); } else { if (uploadFileCSVForm.getClass().equals(UploadCSVForm.class)) { UploadCSVDTO csvInputDTO = modelMapper.map(uploadFileCSVForm, UploadCSVDTO.class); csvDTO = (CSVDTO) service.readCSV(csvInputDTO); } else { csvDTO = (CSVDTO) service.readCSV(multipartFile.getInputStream()); } } } // アクティブメニュー設定 addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.THREE_NUMBER); if (csvDTO == null) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); return modelAndView; } modelAndView.addObject("csv", csvDTO); // セッションにCSV内容を保存する addObjectToSession(CommonConstants.CSV_SESSION_NAME, csvDTO); } catch (IOException e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1413)); } catch (Exception e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); } return modelAndView; } /** * * <p>説明 : insert data csv into db</p> * @author duc.bv * @param service Service implement * @param configData Configration controller * @return show page after insert data */ protected ModelAndView doInsertCSV(MasterBaseService service, Map<String, Object> configData) { String viewName = (String) configData.get(CommonConstants.CSV_SCREEN); ModelAndView modelAndView = createView(configData, viewName); CSVDTO output = (CSVDTO) getObjectFromSession(CommonConstants.CSV_SESSION_NAME); try { // CSVファイル登録 Boolean result = service.insertCSV(output, getUser()); // 登録成功 if (result) { removeObjectFromSession(CommonConstants.CSV_SESSION_NAME); } // メッセジ設定 modelAndView.addObject(CommonConstants.SUBMIT_SUCCESS, true); } catch (RollbackException ex) { logger.error(ex.getMessage()); // TODO 顧客様とメッセジIDを確認中。他は画面レイアウトの確認も必要 modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); } catch (Exception ex) { logger.error(ex.getMessage()); // TODO 顧客様とメッセジIDを確認中。他は画面レイアウトの確認も必要 modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); } modelAndView.addObject("csv", output); return modelAndView; } /** * * <p>説明 : dowload csv data</p> * @author hung.pd * @param response Http Servlet Response * @param service Master Base Service * @param configData Map configuration */ protected void doDownloadCSV(HttpServletResponse response, MasterBaseService service, Map<String, Object> configData) { try { // get form name String formName = (String) configData.get(CommonConstants.SEARCH_FORM); logger.debug("Form name {}", formName); // 検索条件取得 AppForm appForm = (AppForm) getObjectFromSession(session, formName); logger.debug("Form value {}", appForm.toString()); // FIXME get search form from session Class<?> searchDTO = (Class<?>) configData.get(CommonConstants.DTO_SEARCH_CLAZZ); logger.debug("Class dto search name {}", searchDTO.getClass().getName()); BaseSearchDTO searchData = (BaseSearchDTO) searchDTO.newInstance(); // フォームから、DTOに変換 modelMapper.map(appForm, searchData); searchData.setLimit(-1); searchData.setOffset(-1); logger.debug("Convert Form to DTO {}", searchData.toString()); // Set to map parameter Map<String, Object> conditionSearchDataDownload = new HashMap<String, Object>(); conditionSearchDataDownload.put(CommonConstants.DTO_NAME, searchData); // FIXME download csv service.doDownloadCSV(response, conditionSearchDataDownload); } catch (Exception e) { logger.error(e.getMessage()); } } /** * * <p>説明 : CSV登録エラー画面設定</p> * @author : duc.bv * @since : 2018/03/04z * @param uploadFileCSVForm アップロードしたCSVファイル * @param modelAndView ModelAndView * @return modelAndView 画面レイアウト */ private ModelAndView responseErrorCSV(UploadFileCSVForm uploadFileCSVForm, ModelAndView modelAndView) { modelAndView.addObject(CommonConstants.UPLOAD_FILE_CSV_FORM, uploadFileCSVForm); addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.THREE_NUMBER); return modelAndView; } private ModelAndView createView(Map<String, Object> configData, String viewName) { String viewType = (String) configData.get(CommonConstants.VIEW_TYPE_KEY); if (viewType == null) { return createViewNameMaster(viewName); } if (CommonConstants.MASTER_VIEW_TYPE.equals(viewType)) { return createViewNameMaster(viewName); } if (CommonConstants.PRODUCT_VIEW_TYPE.equals(viewType)) { return createViewNameProduct(viewName); } if (CommonConstants.HANBAI_VIEW_TYPE.equals(viewType)) { return createViewNameHanbai(viewName); } if (CommonConstants.CHUMON_VIEW_TYPE.equals(viewType)) { return createViewNameChumon(viewName); } if (CommonConstants.SHOHIN_VIEW_TYPE.equals(viewType)) { return createViewName(CommonConstants.ROOT_DIRECTORY_SHOHIN, viewName); } return createViewNameMaster(viewName); } /** * <p>説明 : initial screen import csv</p> * @author : duc.bv * @param screenName Screen ID * @param service Class service implement * @param configData configuration * @return page import csv */ protected ModelAndView initImportCSV(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData) { return initImportCSV(initInfo, service, configData, null); } protected ModelAndView initImportCSV(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData, Map<String, Object> extraParams) { String viewName = (String) configData.get(CommonConstants.CSV_SCREEN); logger.debug("View name {}", viewName); ModelAndView modelAndView = createView(configData, viewName); addObjectToSession(CommonConstants.CURRENT_TAB, CommonConstants.ONE_NUMBER); try { BaseOutput output = service.initImportCSV(initInfo); // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(output, voClazz); // レスポンスデータ設定+ String vo = (String) configData.get(CommonConstants.VO); modelAndView.addObject(vo, outputVO); logger.debug("VO class {}", voClazz.getName()); logger.debug("Attribute VO {}", vo); // グレードフォーム作成 Class<?> form = (Class<?>) configData.get(CommonConstants.UPLOAD_CSV_FORM_CLAZZ); AppForm appForm = (AppForm) form.newInstance(); if (output.getDetailDTO() != null) { modelMapper.map(output.getDetailDTO(), form); } if (appForm instanceof UploadFileCSVForm) { ((UploadFileCSVForm) appForm).setExtraParams(extraParams); } String formName = (String) configData.get(CommonConstants.UPLOAD_FILE_CSV_FORM); logger.debug("Form class {}", CommonConstants.UPLOAD_FILE_CSV_FORM); logger.debug("Attribute form {}", formName); modelAndView.addObject(formName, appForm); } catch (Exception e) { logger.info(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); } return modelAndView; } /** * <p>説明 : init Copy screen</p> * @author hung.pd * @param initInfo * @param service * @param configData * @param appForm * @return show page copy */ protected ModelAndView initCopy(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData, AppForm appForm) { // init copy screen String viewName = (String) configData.get(CommonConstants.COPY_SCREEN); // ModelAndViewを作成 ModelAndView modelAndView = createView(configData, viewName); try { // グレード情報取得 BaseOutput output = service.initCopy(initInfo); if (output == null) { modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_6)); return modelAndView; } // 初期データの表示データ設定 loadUpdateInfo(modelAndView, output, configData, appForm); removeObjectFromSession(CommonConstants.CURRENT_TAB); } catch (Exception e) { logger.info(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); return modelAndView; } return modelAndView; } /** * * <p>説明 : Show page upload image</p> * @author :hung.pd * @since : 2018/03/13 * @param initInfo 削除情報 * @param service 該当サービス * @param configData 該当Controllerの設定 * @return modelAndView ModelAndView */ protected ModelAndView initUploadImage(Map<String, Object> initInfo, MasterBaseService service, Map<String, Object> configData) { // init detail screen String viewName = (String) configData.get(CommonConstants.UPLOAD_IMAGE_SCREEN); // ModelAndViewを作成 ModelAndView modelAndView = createView(configData, viewName); try { // // get VO class BaseOutput baseOuput = service.initUploadImage(initInfo); // // get form class name // Class<?> deleteFormClassName = (Class<?>) configData.get(CommonConstants.DELETE_FORM_CLASS); // if (baseOuput.getDetailDTO() == null) { // modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), // MessageConstants.MSG_14)); // return modelAndView; // } // // create app form // AppForm appForm = (AppForm) modelMapper.map(baseOuput.getDetailDTO(), deleteFormClassName); // // if (initInfo.containsKey("isLoadDetail")) { // boolean isLoadDetail = (boolean) initInfo.get("isLoadDetail"); // if (isLoadDetail) { // // 初期データの表示データ設定 // loadDeleteInfo(modelAndView, baseOuput, configData); // } // } // // // get VO class Class<?> voClazz = (Class<?>) configData.get(CommonConstants.VO_CLAZZ); MasterBaseVO outputVO = (MasterBaseVO) modelMapper.map(baseOuput, voClazz); // // // レスポンスデータ設定 modelAndView.addObject((String) configData.get(CommonConstants.VO), outputVO); // modelAndView.addObject((String) configData.get(CommonConstants.DELETE_FORM), appForm); // removeObjectFromSession(CommonConstants.CURRENT_TAB); } catch (Exception e) { logger.error(e.getMessage()); modelAndView.addObject(CommonConstants.MESSAGE, new MessageVO(MessageType.ERROR.toString(), MessageConstants.MSG_1296)); modelAndView.addObject(CommonConstants.ACTION, CommonConstants.ERROR_ACTION); } return modelAndView; } /** * * <p>説明 : doUploadImage</p> * @author hung.pd * @param initInfo * @param service * @param configData * @return ModelAndView */ protected ModelAndView doUploadImage(OtherUploadImageForm initInfo, MasterBaseService service, Map<String, Object> configData) { String viewName = (String) configData.get(CommonConstants.UPLOAD_IMAGE_SCREEN); // ModelAndViewを作成 ModelAndView modelAndView = createView(configData, viewName); // Cast DTO OtherUploadImageDTO dto = modelMapper.map(initInfo, OtherUploadImageDTO.class); BaseOutput baseOuput = service.doUploadImage(dto); return modelAndView; } }
package com.yuan.model; import com.yuan.prefence.FileConstants; import com.yuan.prefence.UrlConstants; import com.yuan.unit.FileUtils; import com.yuan.unit.HttpUtils; import com.yuan.unit.JsonUtils; import android.content.Context; import java.io.IOException; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.Map; /** * 系统通知表 entity. @author MyEclipse Persistence Tools */ @SuppressWarnings("serial") public class M系统通知表 implements java.io.Serializable { // Fields /** * */ private Integer id; private Integer 序号 = -1; private String content; private String receiver; private String 时间; private static M系统通知表 sInstance; private String received; private String sender; // Constructors /** default constructor */ private M系统通知表() { } public static M系统通知表 getInstance() { if (sInstance == null) { synchronized (M上班考勤表.class) { if (sInstance == null) { sInstance = new M系统通知表(); } } } return sInstance; } /** minimal constructor */ public M系统通知表(Integer id, Integer 序号) { this.id = id; this.序号 = 序号; } public void setFromMap(Map<?, ?> map) { try { this.id = Integer.parseInt(map.get("id").toString()); this.序号 = Integer.parseInt(map.get("序号").toString()); this.content = map.get("content").toString(); this.receiver = map.get("receiver").toString(); this.时间 = map.get("时间").toString(); this.received = map.get("received").toString(); this.sender = map.get("sender").toString(); } catch (Exception e) { e.printStackTrace(); } } /** * full constructor * * @param sender */ public M系统通知表(Integer id, Integer 序号, String content, String receiver, String 时间, String received, String sender) { this.id = id; this.序号 = 序号; this.content = content; this.receiver = receiver; this.时间 = 时间; this.received = received; this.sender = sender; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Integer get序号() { return this.序号; } public void set序号(Integer 序号) { this.序号 = 序号; } public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } public String getReceiver() { return this.receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String get时间() { return this.时间; } public void set时间(String 时间) { this.时间 = 时间; } public String getReceived() { return this.received; } public void setReceived(String received) { this.received = received; } public String getSender() { return this.sender; } public void setSender(String sender) { this.sender = sender; } public boolean sendNotice(Context mContext) { // TODO Auto-generated method stub if (序号 == -1) { try { M员工信息表.getInstance().setFromObject( FileUtils.File2erializable(FileConstants.SERIALIZABLE_员工信息表)); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } 序号 = M员工信息表.getInstance().get序号(); } String url = String.format(UrlConstants.SENDNOTICE, 序号 + "", content); String str = ""; try { str = HttpUtils.getUrlContent(mContext, url, "UTF-8"); if (str.equals("发送成功")) { return true; } else { return false; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } public boolean getAllNotice(Context mContext) { String str = null; if (序号 == -1) { try { M员工信息表.getInstance().setFromObject( FileUtils.File2erializable(FileConstants.SERIALIZABLE_员工信息表)); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } 序号 = M员工信息表.getInstance().get序号(); } String url = String.format(UrlConstants.GETALLNOTICE, 序号); try { str = HttpUtils.getUrlContent(mContext, url, "UTF-8"); ArrayList<?> mArrayList = JsonUtils.getList(str); FileUtils.Serializable2File(mArrayList, FileConstants.SERIALIZABLE_系统通知表); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public boolean readNotice(Context mContext, String string) { // TODO Auto-generated method stub String str = null; if (序号 == -1) { try { M员工信息表.getInstance().setFromObject( FileUtils.File2erializable(FileConstants.SERIALIZABLE_员工信息表)); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } 序号 = M员工信息表.getInstance().get序号(); } String url = String.format(UrlConstants.READNOTICEURL, 序号, string); try { str = HttpUtils.getUrlContent(mContext, url, "UTF-8"); if (!"确认阅读".equals(str)) { return false; } return getAllNotice(mContext); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }
package mx.edu.ittepic.practica3_u4_denisseespinosa; /** * Created by denisseyea on 20/11/18. */ public class Tortuga { int s,c = 1,p; public void jTortuga(){ p = (int) (Math.random() * 100) + 1; if (p <= 50){ s = 1; }else if (p <= 80){ s = 3; }else { s = 2; } if (s == 2){ if (c <= 6){ c = 1; }else { c-=6; } }else if (s == 1){ if (c > 67){ c = 70; }else { c+=3; } }else { c+=1; } } }
package com.adelean.elasticsearch.word2vec.upload; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestBuilder; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.ActionResponse; import org.elasticsearch.client.ElasticsearchClient; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import java.util.UUID; import static org.elasticsearch.action.ValidateActions.addValidationError; public final class StartUploadAction extends Action< StartUploadAction.StartUploadActionRequest, StartUploadAction.StartUploadActionResponse, StartUploadAction.StartUploadActionRequest.Builder> { public static final String NAME = "cluster:admin/word2vec/upload/start"; public static final StartUploadAction INSTANCE = new StartUploadAction(); protected StartUploadAction() { super(NAME); } @Override public StartUploadActionRequest.Builder newRequestBuilder(ElasticsearchClient client) { return new StartUploadActionRequest.Builder(client); } @Override public StartUploadActionResponse newResponse() { return new StartUploadActionResponse(); } public static final class StartUploadActionRequest extends ActionRequest { private String model; public StartUploadActionRequest() { } public StartUploadActionRequest(String model) { this.model = model; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException arve = null; if (model == null) { arve = addValidationError("'model' must be set", null); } return arve; } static final class Builder extends ActionRequestBuilder<StartUploadActionRequest, StartUploadActionResponse, Builder> { Builder(ElasticsearchClient client) { super(client, INSTANCE, new StartUploadActionRequest()); } } } public static final class StartUploadActionResponse extends ActionResponse implements ToXContentObject { private UUID uploadId; public StartUploadActionResponse() { } public StartUploadActionResponse(UUID uploadId) { this.uploadId = uploadId; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder .startObject() .field("uploadId", uploadId.toString()) .endObject(); } } }
package com.base.ifocus.myapplication.Fragment; /** * Created by iFocus on 10-09-2015. */ import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.base.ifocus.myapplication.Adapter.BaseFragAdapter; import com.base.ifocus.myapplication.Adapter.TodaysSpecialAdapter; import com.base.ifocus.myapplication.Network.Helper; import com.base.ifocus.myapplication.R; /** * A placeholder fragment containing a simple view. */ public class PlaceHolderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; private RecyclerView mRecyclerView; private RecyclerView.Adapter mRecentAdapter; private BaseFragAdapter mAdapter; private ViewPager mPager; /** * Returns a new instance of this fragment for the given section * number. */ public PlaceHolderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_base, container, false); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler); mAdapter = new BaseFragAdapter(getActivity().getSupportFragmentManager()); mPager = (ViewPager) rootView.findViewById(R.id.pager); mPager.setAdapter(mAdapter); createAdapter(mRecyclerView); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @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); } private void createAdapter(RecyclerView recyclerView) { recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mRecentAdapter = new TodaysSpecialAdapter(Helper.data, Helper.icons); recyclerView.setAdapter(mRecentAdapter); } }
import java.util.Random; public class Addressing{ public String AlphanumericStringGenerator(int length) { private int leftLimit = 48; private int rightLimit = 122; private int stringLength = length; Random random = new Random(); Addressing(){ } String alphanumericString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(stringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); return alphanumericString; } }
package net.xycq.campus.legend.base.util; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.mapper.MapperWrapper; /** * <br> * 标题: <br> * 描述: javaBean转xml工具类<br> * 公司: www.tydic.com<br> * * @autho QIJIANFEI * @time 2017年6月6日 下午4:22:48 */ public class XStreamUtil { /** * <br> * 适用场景: 初始化XStream<br> * 调用方式: <br> * 业务逻辑说明<br> * * @return * @autho QIJIANFEI * @time 2017年6月6日 下午4:35:13 */ private static XStream getXstream() { return new XStream(new DomDriver("utf-8")) { @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { if (definedIn == Object.class) { try { return this.realClass(fieldName) != null; } catch (Exception e) { return false; } } else return super.shouldSerializeMember(definedIn, fieldName); } }; } }; } /** * <br> * 适用场景: javaBean转换成xml<br> * 调用方式: <br> * 业务逻辑说明<br> * * @param obj * @return * @autho QIJIANFEI * @time 2017年6月6日 下午4:35:37 */ public static String obj2xmlByXStream(Object obj) throws Exception { try { XStream xst = getXstream(); // xst.alias("rootreq", PayReqMsgBo.class); return toUpper(xst.toXML(obj)); } catch (Exception e) { throw new RuntimeException("javaBean转xml出错:" + e); } } /** * <br> * 适用场景: javaBean转换成xml<br> * 调用方式: <br> * 业务逻辑说明<br> * * @param obj * @return * @autho QIJIANFEI * @time 2017年6月6日 下午4:35:37 */ public static String obj2xml(Object obj) throws Exception { try { XStream xst = getXstream(); // xst.alias("rootreq", PayReqMsgBo.class); return toUpper(xst.toXML(obj)); } catch (Exception e) { throw new RuntimeException("javaBean转xml出错:" + e); } } /** * <br> * 适用场景: xml转成成javaBean<br> * 调用方式: <br> * 业务逻辑说明<br> * * @param xml * @param tClass * @return * @autho QIJIANFEI * @time 2017年6月6日 下午4:36:48 */ public static <T> T xml2objByXStream(String xml, Class<T> tClass) { try { XStream xst = getXstream(); xst.processAnnotations(tClass); return (T) xst.fromXML(xml); } catch (Exception e) { throw new RuntimeException("xml转javaBean转xml出错:" + e); } } /** * <br> * 适用场景: 节点字母大写<br> * 调用方式: <br> * 业务逻辑说明<br> * * @param xml * @return * @autho QIJIANFEI * @time 2017年6月6日 下午7:37:15 */ private static String toUpper(String xml) { Pattern pattern = Pattern.compile("<.+?>"); StringBuilder res = new StringBuilder(); int lastIdx = 0; Matcher matchr = pattern.matcher(xml); Pattern patternBody = Pattern.compile("<body.+?>"); while (matchr.find()) { String str = UnderlineCamelUtil.camel2Underline(matchr.group()); Matcher matchrBody = patternBody.matcher(str); if (matchrBody.find()) { str = "<BODY>"; } res.append(xml.substring(lastIdx, matchr.start())); res.append(str.toUpperCase()); lastIdx = matchr.end(); } res.append(xml.substring(lastIdx)); return res.toString(); } /** * <br> * 适用场景: XStream的javaBeam转xml时候对于节点的重命名<br> * 调用方式: <br> * 业务逻辑说明<br> * * @param str * @return * @autho QIJIANFEI * @time 2017年6月6日 下午7:38:03 */ private static String updateBodyEle(String str) { Pattern pattern = Pattern.compile("<BODY.+?>"); Matcher matchr = pattern.matcher(str); while (matchr.find()) { str = "<BODY>"; } return str; } public static void main(String[] args) throws Exception { StringBuffer buffer = new StringBuffer(); InputStream is = new FileInputStream("D:/respon.xml"); String line; // 用来保存每行读取的内容 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); line = reader.readLine(); // 读取第一行 while (line != null) { // 如果 line 为空说明读完了 buffer.append(line); // 将读到的内容添加到 buffer 中 buffer.append("\n"); // 添加换行符 line = reader.readLine(); // 读取下一行 } reader.close(); is.close(); String str = buffer.toString(); String json = JsonUtils.toJson(XmlMapUtil.xml2Map(str, false)); } public static <T> T doPostUrlWithXml(String json, Class<T> valueType) { return JsonUtils.jsonStringToObject(json, valueType); } }
package br.com.scd.demo.session; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import br.com.scd.demo.api.session.dto.SessionRequest; import br.com.scd.demo.session.SessionForInsert; import br.com.scd.demo.session.SessionForInsertFactory; public class SessionForInsertFactoryTest { @Test public void shouldCreateInstance() { SessionRequest sessionRequest = new SessionRequest(); ReflectionTestUtils.setField(sessionRequest, "topicId", 20l); ReflectionTestUtils.setField(sessionRequest, "durationInMinutes", 40); SessionForInsert sessionForInsert = SessionForInsertFactory.getInstance(sessionRequest); assertEquals("40", sessionForInsert.getDurationInMinutes().toString()); assertEquals("20", sessionForInsert.getTopicId().toString()); } }
package birkann.com.kanaltakip.DbObject; /** * Created by birkan on 23.10.2016. */ public class ChannelDetails { private String id; private String desc; private String cName; private String profileImg; private String channelImg; public ChannelDetails(String id, String desc, String name, String profileImg, String channelImg) { this.id = id; this.desc = desc; this.cName = name; this.profileImg = profileImg; this.channelImg = channelImg; } public ChannelDetails(String id) { this.id = id; } public String getId() { return id; } public String getDesc() { return desc; } public String getcName() { return cName; } public String getProfileImg() { return profileImg; } public String getChannelImg() { return channelImg; } public void setId(String id) { this.id = id; } public void setDesc(String desc) { this.desc = desc; } public void setcName(String cName) { this.cName = cName; } public void setProfileImg(String profileImg) { this.profileImg = profileImg; } public void setChannelImg(String channelImg) { this.channelImg = channelImg; } }
package utilities; public class Holder<T> { private T item; private int hashcode; public Holder(T item) { this.item = item; this.hashcode = item.hashCode(); } public void setItem(T item) { this.item = item; } public T getItem() { return this.item; } /* * Object Overrides */ @Override public int hashCode() { return this.hashcode; } @Override public boolean equals(Object obj) { if (obj instanceof Holder) { return super.equals(obj); } Holder<?> cast = (Holder<?>)obj; return this.item.equals(cast.item); } }
package com.snewworld.listsample; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.snewworld.listsample.adapter.MainPagerAdapter; /** * Created by sNewWorld on 2017-04-27. */ public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private final String TITLE_1 = "Default List"; private final String TITLE_2 = "ViewPager List"; private final String TITLE_3 = "Grid"; private final String TITLE_4 = "Staggered Grid"; private final String TITLE_5 = "Flexible Layout"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Adding Toolbar to the activity Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Initializing the TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout); tabLayout.addTab(tabLayout.newTab().setText("List 1")); tabLayout.addTab(tabLayout.newTab().setText("List 2")); tabLayout.addTab(tabLayout.newTab().setText("List 3")); tabLayout.addTab(tabLayout.newTab().setText("List 4")); tabLayout.addTab(tabLayout.newTab().setText("List 5")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); // Initializing ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager); // Creating TabPagerAdapter adapter MainPagerAdapter mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(mainPagerAdapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); // Set TabSelectedListener tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); switch (tab.getPosition()) { case 0:((Toolbar) findViewById(R.id.toolbar)).setTitle(TITLE_1);break; case 1:((Toolbar) findViewById(R.id.toolbar)).setTitle(TITLE_2);break; case 2:((Toolbar) findViewById(R.id.toolbar)).setTitle(TITLE_3);break; case 3:((Toolbar) findViewById(R.id.toolbar)).setTitle(TITLE_4);break; case 4:((Toolbar) findViewById(R.id.toolbar)).setTitle(TITLE_5);break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); ((Toolbar) findViewById(R.id.toolbar)).setTitle(TITLE_1); } }
package co.edu.poli.sistemasdistribuidos.votaciones.controller; import co.edu.poli.sistemasdistribuidos.votaciones.entities.VotoEntity; import co.edu.poli.sistemasdistribuidos.votaciones.service.VotoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/voto") public class VotoController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(VotoController.class); @Autowired private VotoService votoService; @PostMapping("/votar") public VotoEntity votar(@RequestParam("idEleccion") long idEleccion, @RequestParam("idCandidato") long idCandidato) { VotoEntity voto = null; try { voto = votoService.votar(idEleccion, idCandidato); } catch (Exception e) { LOGGER.error("Ha ocurrido un error realizando el voto", e); } return voto; } }
package net.suntrans.haipopeiwang.mdns.api; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Handler; import android.os.Message; import net.suntrans.haipopeiwang.mdns.helper.CommonFunc; import net.suntrans.haipopeiwang.mdns.helper.MDNSErrCode; import net.suntrans.haipopeiwang.mdns.helper.SearchDeviceCallBack; import net.suntrans.haipopeiwang.utils.LogUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.Inet4Address; import java.net.InetAddress; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; //import android.util.Log; public class MDNS { private String TAG = "---MiCOmDNS---"; /** * 控制的参数 */ private CommonFunc comfunc = new CommonFunc(); // 线程是否已经启动 private boolean isWorking = false; private WifiManager wifiManager = null; private Map<String, JSONObject> jsonmap = null; // 发现设备的message.what private final int _ADDDEVICE = 1002; private final int _REMOVEDEVICE = 1003; /** * 接收的信息 */ private Context mContext; private SearchDeviceCallBack msearchdevcb; /** * callback相关 */ private JSONArray array;// callback的数组 private String mserviceName; private JmDNS jmdns; private SampleListener slistener; private WifiManager.MulticastLock lock; public MDNS(Context context) { this.mContext = context; } /** * Start mDNS to search my devices. * * @param serviceName serviceName * @param searchdevcb searchdevcb */ public void startSearchDevices(String serviceName, SearchDeviceCallBack searchdevcb) { if (comfunc.checkPara(serviceName)) { if (null != mContext) startMdnsService(serviceName, searchdevcb); else { comfunc.failureCBmDNS(MDNSErrCode.CONTEXT_CODE, MDNSErrCode.CONTEXT, searchdevcb); } } else { comfunc.failureCBmDNS(MDNSErrCode.EMPTY_CODE, MDNSErrCode.EMPTY, searchdevcb); } } /** * Stop search devices. * * @param searchdevcb searchdevcb */ public void stopSearchDevices(SearchDeviceCallBack searchdevcb) { stopMdnsService(searchdevcb); stopMDNS(); } private void startMdnsService(String serviceName, final SearchDeviceCallBack searchdevcb) { mserviceName = serviceName; msearchdevcb = searchdevcb; // 如果还没有启动,则启动,否则callback if (!isWorking) { isWorking = true; if (wifiManager == null) wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); startMDNS(); // // 开始线程,每3秒关掉再打开,并发送信息给前端 // new Thread() { // @Override // public void run() { // while (isWorking) { // try { // sendCallBack(); // Thread.sleep(1000 *2); //// Thread.sleep(100); //// Thread.sleep(1000 * 1); // } catch (InterruptedException e) { // comfunc.successCBmDNS(MDNSErrCode.EXCEPTION_CODE, e.getMessage(), searchdevcb); // e.printStackTrace(); // } // } // } // }.start(); } else { comfunc.failureCBmDNS(MDNSErrCode.BUSY_CODE, MDNSErrCode.BUSY, searchdevcb); } } private void stopMdnsService(SearchDeviceCallBack searchdevcb) { if (isWorking) { isWorking = false; comfunc.successCBmDNS(MDNSErrCode.SUCCESS_CODE, MDNSErrCode.SUCCESS, searchdevcb); } else { comfunc.failureCBmDNS(MDNSErrCode.CLOSED_CODE, MDNSErrCode.CLOSED, searchdevcb); } } private void startMDNS() { new Thread() { @Override public void run() { jmdns = null; slistener = null; InetAddress intf = null; array = new JSONArray(); if (jsonmap == null) jsonmap = new ConcurrentHashMap<String, JSONObject>(); jsonmap.clear(); try { boolean jmdnsTag = true; while (jmdnsTag) { if (intf != null && jmdns != null) { jmdnsTag = false; lock = wifiManager.createMulticastLock("mylock"); lock.setReferenceCounted(true); lock.acquire(); slistener = new SampleListener(); jmdns.addServiceListener(mserviceName, slistener); } else { if (intf == null) { intf = getLocalIpAddress(mContext); LogUtil.i("MDNS", intf.toString()); } if (jmdns == null) { String hostname = InetAddress.getByName(intf.getHostName()).toString(); jmdns = JmDNS.create(intf, hostname); } } } } catch (Exception e) { e.printStackTrace(); } } }.start(); } private void stopMDNS() { new Thread(){ @Override public void run() { if (null != jmdns) { try { jmdns.removeServiceListener(mserviceName, slistener); jmdns.unregisterAllServices(); jmdns.close(); jmdns=null; if (null != lock) lock.release(); lock=null; slistener=null; } catch (IOException e) { e.printStackTrace(); } } } }.start(); } public void updateMessage() { JSONArray tmpArray = new JSONArray(); Iterator it = jsonmap.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); tmpArray.put(entry.getValue()); } this.array = tmpArray; if (comfunc != null) comfunc.onDevsFindmDNS(array, msearchdevcb); } private void sendCallBack() { comfunc.onDevsFindmDNS(array, msearchdevcb); } class SampleListener implements ServiceListener { ServiceInfo sName; @Override public void serviceAdded(ServiceEvent event) { LogUtil.i("serviceAdded:" + event.getName()); jmdns.requestServiceInfo(event.getType(), event.getName(), 1); } @Override public void serviceRemoved(ServiceEvent event) { // Log.d("---HomeFragment---", event.getName()); jsonmap.remove(event.getName()); // 通知handler有数据更新 Message msg = new Message(); msg.what = _REMOVEDEVICE; mdnsHandler.sendMessage(msg); } @Override public void serviceResolved(ServiceEvent event) { if (!jsonmap.containsKey(event.getName())) { sName = event.getInfo(); LogUtil.i("serviceResolved:" + event.getName()); if (null != sName) { // 截取byte数组 ArrayList<String> mDNSList = new ArrayList(); byte[] allinfobyte = sName.getTextBytes(); int allLen = allinfobyte.length; for (int index = 0; index < allLen; ) { int infoLength = allinfobyte[index++]; byte[] temp = new byte[infoLength]; System.arraycopy(allinfobyte, index, temp, 0, infoLength); try { String isoString = new String(temp, "UTF-8"); mDNSList.add(isoString); // Log.d(TAG + "arraycopy", isoString); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } index += infoLength; } try { JSONObject jsonObject = new JSONObject(); String dev_ip = ""; // sName.getHostAddresses() String hostAddress = sName.getAddress().getHostAddress(); Inet4Address[] ipv4 = sName.getInet4Addresses(); if (ipv4.length > 0) { dev_ip = ipv4[0].toString(); int isOtherStr = dev_ip.indexOf("/"); if (isOtherStr > -1) { dev_ip = dev_ip.substring(isOtherStr + 1); } } jsonObject.put("Name", sName.getName()); jsonObject.put("IP", dev_ip); jsonObject.put("Port", sName.getPort()); for (String orlValue : mDNSList) { if (!"".equals(orlValue)) { String[] temp = orlValue.split("="); jsonObject.put(temp[0], temp[1]); } } //Log.d("---HomeFragment---", event.getName()); jsonmap.put(event.getName(), jsonObject); } catch (JSONException e) { e.printStackTrace(); } // 通知handler有数据更新 Message msg = new Message(); msg.what = _ADDDEVICE; mdnsHandler.sendMessage(msg); } else { LogUtil.e("serviceAdded:serviceInfo==null"); } } } } private Handler mdnsHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { // 通知线程有数据更新 case _ADDDEVICE: updateMessage(); break; // 如果有设备离线,就重新监听 case _REMOVEDEVICE: updateMessage(); break; } } }; public InetAddress getLocalIpAddress(Context context) throws Exception { if (wifiManager == null) wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo wifiinfo = wifiManager.getConnectionInfo(); int intaddr = wifiinfo.getIpAddress(); byte[] byteaddr = new byte[]{(byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff), (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff)}; InetAddress addr = InetAddress.getByAddress(byteaddr); return addr; } }
package com.fulvio.persistencia.entities; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; @SuppressWarnings("serial") @Entity public class Direccion implements Serializable{ @Id private int id; private int noCasa; private String calle; @OneToOne(cascade = CascadeType.PERSIST) private Sector sector; @OneToOne(cascade = CascadeType.PERSIST) private Ciudad ciudad; @OneToOne(cascade = CascadeType.PERSIST) private Pais pais; public int getNoCasa() { return noCasa; } public void setNoCasa(int noCasa) { this.noCasa = noCasa; } public String getCalle() { return calle; } public void setCalle(String calle) { this.calle = calle; } public Sector getSector() { return sector; } public void setSector(Sector sector) { this.sector = sector; } public Ciudad getCiudad() { return ciudad; } public void setCiudad(Ciudad ciudad) { this.ciudad = ciudad; } public Pais getPais() { return pais; } public void setPais(Pais pais) { this.pais = pais; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
package interfce; import pannels.PanelInicio; import pannels.PanelNovoJogo; public class TelaInicial { public static Janela janela1; public static PanelInicio panelLogin; /*public static void esconderTela(){ janela.setVisible(false); }*/ public TelaInicial(){ setJanela(); setPanelLogin(); janela1.add(panelLogin); janela1.repaint(); //janela1.remove(paneLogin); } public void setJanela(){ this.janela1 = new Janela(); }; public void setPanelLogin(){ this.panelLogin = new PanelInicio(); }; }
import java.util.regex.Pattern; import java.util.regex.Matcher; public class Validator { public static String validatePhoneNumber (String s) { s=s.trim(); if(s.length()==11) { if(s.startsWith("01")) { if(Character.getNumericValue(s.charAt(2))==2 || Character.getNumericValue(s.charAt(2))==0 ) {/*(Character.getNumericValue(s.charAt(1))!=1 || Character.getNumericValue(s.charAt(1))!=3 ||Character.getNumericValue(s.charAt(1))!=4 ||Character.getNumericValue(s.charAt(1))!=6) && */ return null; } for (int i =3 ; i < s.length(); i++) { if(Character.getNumericValue(s.charAt(2))< 0 || Character.getNumericValue(s.charAt(2))>9) { return null; } } return s; } }else if(s.length()==13) { if(s.startsWith("+8801")) { if(Character.getNumericValue(s.charAt(5))==2 || Character.getNumericValue(s.charAt(5))==0 ) {/*(Character.getNumericValue(s.charAt(1))!=1 || Character.getNumericValue(s.charAt(1))!=3 ||Character.getNumericValue(s.charAt(1))!=4 ||Character.getNumericValue(s.charAt(1))!=6) && */ return null; } for (int i =6 ; i < s.length(); i++) { if(Character.getNumericValue(s.charAt(i))<0 || Character.getNumericValue(s.charAt(i))>9) { return null; } } return s; } } return null; } public static String validateEmail(String s) { s=s.trim(); s=s.toLowerCase(); String regex="^(.+)@(.+)$"; Pattern pattern = Pattern.compile(regex); Matcher matcher=pattern.matcher(s); return matcher.matches()?s:null; } }
package pl.finapi.paypal.model; import org.apache.commons.lang3.builder.ToStringBuilder; public class BuyerInfo { public static final BuyerInfo EMPTY_BUYER = new BuyerInfo("", "", "", ""); private final String companyName; private final String addressLines1; private final String addressLines2; private final String nip; public BuyerInfo(String companyName, String addressLines1, String addressLines2, String nip) { this.companyName = companyName; this.addressLines1 = addressLines1; this.addressLines2 = addressLines2; this.nip = nip; } public String getCompanyName() { return companyName; } public String getAddressLine1() { return addressLines1; } public String getAddressLine2() { return addressLines2; } public String getNIP() { return nip; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
package level_1; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class AchivementInPercentageTest { // { // "objectives": [ // { "id": 1, "start": 0, "target": 50 }, // { "id": 2, "start": 10, "target": 42 }, // { "id": 3, "start": 20, "target": 0 } // ], // "progress_records": [ // { "id": 1, "objective_id": 1, "value": 15 }, // { "id": 2, "objective_id": 3, "value": 15 }, // { "id": 3, "objective_id": 2, "value": 14 } // ] // } @Test public void should_record_30_of_progress_for_15_from_start_0_to_target_50() { JsonObject input = new JsonParser().parse("{\n" + "\"objectives\": [\n" + " { \"id\": 1, \"start\": 0, \"target\": 50 }\n" + "],\n" + "\"progress_records\": [\n" + " { \"id\": 1, \"objective_id\": 1, \"value\": 15 },\n" + " ]\n" + "}").getAsJsonObject(); JsonElement result = new AchivementInPercentage().record(input); JsonObject expectedOutput = new JsonParser() .parse("{ \"progress_records\": [{\"id\":1,\"progress\":30}] }") .getAsJsonObject(); assertThat(result).isEqualTo(expectedOutput); } }
package stringutility; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import static stringutility.StringUtility.*; class StringUtilityTest { @Test void isVowel_Vowel_ReturnTrue() { Assertions.assertAll( () -> assertTrue(isVowel('a')), () -> assertTrue(isVowel('A')) ); } @Test void isVowel_Consonant_ReturnFalse() { Assertions.assertAll( () -> assertFalse(isVowel('b')), () -> assertFalse(isVowel('B')) ); } @Test void isVowel_NonLetter_ThrowIllegalArgumentException() { Assertions.assertThrows(IllegalArgumentException.class, () -> isVowel('&')); } @Test void isConsonant_Consonant_ReturnTrue() { Assertions.assertAll( () -> assertTrue(isConsonant('b')), () -> assertTrue(isConsonant('B')) ); } @Test void isConsonant_Vowel_ReturnFalse() { Assertions.assertAll( () -> assertFalse(isConsonant('a')), () -> assertFalse(isConsonant('A')) ); } @Test void isConsonant_NonLetter_ThrowIllegalArgumentException() { Assertions.assertThrows(IllegalArgumentException.class, () -> isConsonant('&')); } }
package fishy.sample.lanchatsample; import android.app.Dialog; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends AppCompatActivity { TextView tvIp; TextView tvState; ImageView iconSetting; TextView tvContent; EditText editContent; Button btnSend; AlertDialog dialogIp; EditText editIp; ClientThread clientThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); ConnectConfig.tempIp = TempIpInfo.readRecentIp(); EventBus.getDefault().register(this); new ServerThread().start(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void updateText(MsgEvent msgEvent) { tvContent.append(msgEvent.getMsg() + "\n"); } void init() { tvIp = (TextView) findViewById(R.id.tvIp); tvState = (TextView) findViewById(R.id.tvState); tvContent = (TextView) findViewById(R.id.tvContent); iconSetting = (ImageView) findViewById(R.id.iconSetting); editContent = (EditText) findViewById(R.id.editContent); btnSend = (Button) findViewById(R.id.btnSend); tvIp.setText(ConnectConfig.getLocalIp()); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(ConnectConfig.tempIp)) { toast("ip为null"); } else { // new ClientThread().start(); if(clientThread==null){ clientThread=new ClientThread(); clientThread.start(); }else{ clientThread.sendMsg(); } } } }); iconSetting.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createIpDialog(); } }); } void toast(String msg) { Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } void createIpDialog() { if (dialogIp == null) { editIp = new EditText(MainActivity.this); editIp.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); dialogIp=new AlertDialog.Builder(this) .setTitle("setIp") .setView(editIp) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { TempIpInfo.recordRecentIp(editIp.getText().toString()); } }) .create(); } editIp.setText(ConnectConfig.tempIp); dialogIp.show(); } }
package LC0_200.LC150_200; public class LC182_Duplicate_Emails { // mysql }
package com.project.utilImpl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.project.util.util; public class utilImpl implements util { private Connection con = null; public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","root"); } catch (ClassNotFoundException e) { System.out.println(e); System.out.println("driver class nai malto !!"); } catch (SQLException e) { System.out.println(e); System.out.println("connection ma kharabi 6!!"); } return con; } }
package com.pangpang6.books.leecode.ndatasum; import com.alibaba.fastjson.JSON; import java.util.Arrays; public class TwoSum { public static void main(String[] args) { int[] d1 = {1, 2, 3, 4, 5, 6}; System.out.println(JSON.toJSONString(twoSum(d1, 5))); } public static int[] twoSum(int[] nums, int target) { // 先对数组排序 Arrays.sort(nums); // 左右指针 int lp = 0, rp = nums.length - 1; while (lp < rp) { int sum = nums[lp] + nums[rp]; // 根据 sum 和 target 的比较,移动左右指针 if (sum < target) { while (lp < rp && nums[++lp] == nums[lp - 1]) { } } else if (sum > target) { while (lp < rp && nums[--rp] == nums[lp + 1]) { } } else if (sum == target) { return new int[]{nums[lp], nums[rp]}; } } return new int[]{}; } }
package devas.com.whatchaap; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import org.jxmpp.stringprep.XmppStringprepException; import java.util.ArrayList; import java.util.Random; public class Chats extends AppCompatActivity implements View.OnClickListener { private EditText msg_edittext; private static String user1 = "", user2 = "";// chating with self private Random random; public static ArrayList<ChatMessage> chatlist; public static ChatAdapter chatAdapter; ListView msgListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); UserDetails ud = new UserDetails(this); user1 = ud.getUsername(); Bundle b = getIntent().getExtras(); user2 = b.getString("user2"); random = new Random(); msg_edittext = (EditText) findViewById(R.id.messageEditText); msgListView = (ListView) findViewById(R.id.msgListView); ImageButton sendButton = (ImageButton)findViewById(R.id.sendMessageButton); sendButton.setOnClickListener(this); // ----Set autoscroll of listview when a new message arrives----// msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL); msgListView.setStackFromBottom(true); chatlist = new ArrayList<ChatMessage>(); chatAdapter = new ChatAdapter(this, chatlist); msgListView.setAdapter(chatAdapter); } public void sendTextMessage(View v) throws XmppStringprepException { String message = msg_edittext.getEditableText().toString(); if (!message.equalsIgnoreCase("")) { final ChatMessage chatMessage = new ChatMessage(user1, user2, message, "" + random.nextInt(1000), true); chatMessage.setMsgID(); chatMessage.body = message; chatMessage.Date = CommonMethods.getCurrentDate(); chatMessage.Time = CommonMethods.getCurrentTime(); chatMessage.ack = 0; msg_edittext.setText(""); chatAdapter.add(chatMessage); chatAdapter.notifyDataSetChanged(); MainActivity activity = new MainActivity(); activity.getmService().xmpp.sendMessage(chatMessage); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sendMessageButton: try { sendTextMessage(v); } catch (XmppStringprepException e) { e.printStackTrace(); } } } }
package mg.egg.eggc.compiler.egg.java; import mg.egg.eggc.runtime.libjava.*; import mg.egg.eggc.compiler.libegg.base.*; import mg.egg.eggc.compiler.libegg.java.*; import mg.egg.eggc.compiler.libegg.egg.*; import mg.egg.eggc.compiler.libegg.mig.*; import mg.egg.eggc.compiler.libegg.latex.*; import mg.egg.eggc.compiler.libegg.type.*; import mg.egg.eggc.runtime.libjava.lex.*; import java.util.*; import mg.egg.eggc.runtime.libjava.lex.*; import mg.egg.eggc.runtime.libjava.*; import mg.egg.eggc.runtime.libjava.messages.*; import mg.egg.eggc.runtime.libjava.problem.IProblem; import java.util.Vector; import java.util.List; import java.util.ArrayList; public class S_TYPE_EGG implements IDstNode { LEX_EGG scanner; S_TYPE_EGG() { } S_TYPE_EGG(LEX_EGG scanner, boolean eval) { this.scanner = scanner; this.att_eval = eval; offset = 0; length = 0; this.att_scanner = scanner; } int [] sync= new int[0]; Resolveur att_res; boolean att_eval; IType att_type; LEX_EGG att_scanner; IVisiteurEgg att_vis; private void regle9() throws Exception { //declaration T_EGG x_2 = new T_EGG(scanner ) ; S_TGEN_EGG x_3 = new S_TGEN_EGG(scanner,att_eval) ; //appel if (att_eval) action_auto_inh_9(x_2, x_3); x_2.analyser(LEX_EGG.token_t_ident); addChild(x_2); x_3.analyser() ; addChild(x_3); if (att_eval) action_gen_9(x_2, x_3); offset =x_2.getOffset(); length =x_3.getOffset() + x_3.getLength() - offset; } private void regle17() throws Exception { //declaration T_EGG x_2 = new T_EGG(scanner ) ; //appel x_2.analyser(LEX_EGG.token_t_char); addChild(x_2); if (att_eval) action_gen_17(); offset =x_2.getOffset(); length =x_2.getOffset() + x_2.getLength() - offset; } private void regle14() throws Exception { //declaration T_EGG x_2 = new T_EGG(scanner ) ; //appel x_2.analyser(LEX_EGG.token_t_integer); addChild(x_2); if (att_eval) action_gen_14(); offset =x_2.getOffset(); length =x_2.getOffset() + x_2.getLength() - offset; } private void regle15() throws Exception { //declaration T_EGG x_2 = new T_EGG(scanner ) ; //appel x_2.analyser(LEX_EGG.token_t_double); addChild(x_2); if (att_eval) action_gen_15(); offset =x_2.getOffset(); length =x_2.getOffset() + x_2.getLength() - offset; } private void regle16() throws Exception { //declaration T_EGG x_2 = new T_EGG(scanner ) ; //appel x_2.analyser(LEX_EGG.token_t_string); addChild(x_2); if (att_eval) action_gen_16(); offset =x_2.getOffset(); length =x_2.getOffset() + x_2.getLength() - offset; } private void action_gen_16() throws Exception { try { // instructions this.att_type=(this.att_res).getType("STRING"); }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#gen","TYPE -> t_string #gen ;"}); } } private void action_gen_17() throws Exception { try { // instructions this.att_type=(this.att_res).getType("CHARACTER"); }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#gen","TYPE -> t_char #gen ;"}); } } private void action_gen_14() throws Exception { try { // instructions this.att_type=(this.att_res).getType("INTEGER"); }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#gen","TYPE -> t_integer #gen ;"}); } } private void action_gen_15() throws Exception { try { // instructions this.att_type=(this.att_res).getType("DOUBLE"); }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#gen","TYPE -> t_double #gen ;"}); } } private void action_auto_inh_9(T_EGG x_2, S_TGEN_EGG x_3) throws Exception { try { // instructions x_3.att_res=this.att_res; x_3.att_vis=this.att_vis; }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#auto_inh","TYPE -> t_ident TGEN #gen ;"}); } } private void action_gen_9(T_EGG x_2, S_TGEN_EGG x_3) throws Exception { try { // instructions this.att_type=(this.att_res).getType(x_2.att_txt, x_3.att_pars); }catch(RuntimeException e) { att_scanner._interrompre(IProblem.Internal,att_scanner.getBeginLine(),ICoreMessages.id_EGG_runtime_error, CoreMessages.EGG_runtime_error,new Object[] { "EGG", "#gen","TYPE -> t_ident TGEN #gen ;"}); } } public void analyser () throws Exception { scanner.lit ( 1 ) ; switch ( scanner.fenetre[0].code ) { case LEX_EGG.token_t_ident : // 61 regle9 () ; break ; case LEX_EGG.token_t_integer : // 56 regle14 () ; break ; case LEX_EGG.token_t_double : // 57 regle15 () ; break ; case LEX_EGG.token_t_string : // 55 regle16 () ; break ; case LEX_EGG.token_t_char : // 58 regle17 () ; break ; default : scanner._interrompre(IProblem.Syntax, scanner.getBeginLine(), IEGGMessages.id_EGG_unexpected_token,EGGMessages.EGG_unexpected_token,new String[]{scanner.fenetre[0].getNom()}); } } private IDstNode parent; public void setParent( IDstNode p){parent = p;} public IDstNode getParent(){return parent;} private List<IDstNode> children = null ; public void addChild(IDstNode node){ if (children == null) { children = new ArrayList<IDstNode>() ;} children.add(node); node.setParent(this); } public List<IDstNode> getChildren(){return children;} public boolean isLeaf(){return children == null;} public void accept(IDstVisitor visitor) { boolean visitChildren = visitor.visit(this); if (visitChildren && children != null){ for(IDstNode node : children){ node.accept(visitor); } } visitor.endVisit(this); } private int offset; private int length; public int getOffset(){return offset;} public void setOffset(int o){offset = o;} public int getLength(){return length;} public void setLength(int l){length = l;} private boolean malformed = false; public void setMalformed(){malformed = true;} public boolean isMalformed(){return malformed;} }
package org.maven.ide.eclipse.ui.common.authentication; import java.beans.Beans; import java.io.File; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.maven.ide.eclipse.authentication.AnonymousAccessType; import org.maven.ide.eclipse.authentication.AuthFacade; import org.maven.ide.eclipse.authentication.IAuthData; import org.maven.ide.eclipse.authentication.internal.AuthData; import org.maven.ide.eclipse.swtvalidation.SwtValidationGroup; import org.maven.ide.eclipse.ui.common.InputHistory; import org.maven.ide.eclipse.ui.common.Messages; import org.maven.ide.eclipse.ui.common.composites.ValidatingComposite; import org.maven.ide.eclipse.ui.common.layout.WidthGroup; import org.maven.ide.eclipse.ui.common.validation.SonatypeValidators; import org.netbeans.validation.api.Problem; import org.netbeans.validation.api.Problems; import org.netbeans.validation.api.Validator; import org.netbeans.validation.api.builtin.stringvalidation.StringValidators; /** * Reusable widget to enter a URL and/or supply the associated credentials. * <P/> * When the widget is initially displayed, it checks if the auth registry already contains credentials for the given * URL, and populates the username/password and certificate fields. The URL can be rendered read-only or editable, a * drop-down input history is provided. * <P/> * The component is ready to be used in dialogs and wizard pages. * <P/> * Once the wizard flow is complete, call the getUrl() method to retrieve the URL. The credentials will be automatically * saved in the auth registry. */ public class UrlInputComposite extends ValidatingComposite { public static final String URL_CONTROL_NAME = "urlControl"; public static final String ANONYMOUS_LABEL_NAME = "anonymousLabel"; public static final String USERNAME_TEXT_NAME = "usernameText"; public static final String PASSWORD_TEXT_NAME = "passwordText"; public static final String CERTIFICATE_TEXT_NAME = "certificateText"; public static final String PASSPHRASE_TEXT_NAME = "passphraseText"; public static final String BROWSE_CERTIFICATE_BUTTON_NAME = "browseCertificateButton"; public static final String USE_CERTIFICATE_BUTTON_NAME = "useCertificateButton"; public static final int READ_ONLY_URL = 1; public static final int ALLOW_ANONYMOUS = 2; public static final int CERTIFICATE_CONTROLS = 4; private static final int INPUT_WIDTH = 200; private static final int INPUT_INDENT = 10; private static final String SETTINGS = "urls"; private UrlFieldFacade urlComponent; private Label urlLabel; private Text usernameText; private Text passwordText; protected boolean updating = false; private boolean readonlyUrl = true; private InputHistory inputHistory; private String urlLabelText; private Label usernameLabel; private Label passwordLabel; private Label certificateLabel; private Label anonymousLabel; private Text certificateText; private Button browseCertificateButton; private Label passphraseLabel; private Text passphraseText; private IAuthData authData; private IAuthData defaultAuthData; private boolean initialized; private String url; private String username; private String password; private String passphrase; private String certificate; private boolean dirty; public UrlInputComposite( Composite parent, WidthGroup widthGroup, SwtValidationGroup validationGroup, int style ) { super( parent, widthGroup, validationGroup ); this.readonlyUrl = ( style & READ_ONLY_URL ) != 0; boolean allowAnonymous = ( style & ALLOW_ANONYMOUS ) != 0; this.urlLabelText = Messages.urlInput_url_label; AnonymousAccessType anonymousAccessType = allowAnonymous ? AnonymousAccessType.ALLOWED : AnonymousAccessType.NOT_ALLOWED; if ( ( style & CERTIFICATE_CONTROLS ) != 0 ) { defaultAuthData = new AuthData( "", "", null, null, anonymousAccessType ); } else { defaultAuthData = new AuthData( "", "", anonymousAccessType ); } authData = defaultAuthData; setInputHistory( new InputHistory( SETTINGS ) ); setLayout( new GridLayout( 4, false ) ); createControls(); urlComponent.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { url = urlComponent.getText(); setDirty(); updateCredentials(); } } ); urlComponent.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { url = urlComponent.getText(); setDirty(); updateCredentials(); } } ); SwtValidationGroup.setComponentName( urlComponent.getWrappedControl(), Messages.urlInput_url_name ); addToValidationGroup( urlComponent.getWrappedControl(), new Validator<String>() { public Class<String> modelType() { return String.class; } public void validate( Problems problems, String compName, String model ) { SonatypeValidators.URL_MUST_BE_VALID.validate( problems, compName, model ); } } ); updateCredentials(); initialized = true; } public class CredentialsValidator implements Validator<String> { public Class<String> modelType() { return String.class; } public void validate( Problems problems, String compName, String model ) { if ( AnonymousAccessType.NOT_ALLOWED.equals( authData.getAnonymousAccessType() ) ) { StringValidators.REQUIRE_NON_EMPTY_STRING.validate( problems, compName, model ); } } }; public void setInputHistory( InputHistory hist ) { assert hist != null; inputHistory = hist; if ( urlComponent != null ) { // setting different input history after the ui component hierarchy was constructed Control c = urlComponent.getWrappedControl(); if ( c instanceof Combo ) { inputHistory.add( urlLabelText, (Combo) c ); inputHistory.load(); } } } public void setUrlLabelText( String text ) { urlLabelText = text; if ( urlLabel != null && !urlLabel.isDisposed() ) { urlLabel.setText( text ); } setInputHistory( new InputHistory( SETTINGS ) ); } protected void createControls() { urlLabel = new Label( this, SWT.NONE ); urlLabel.setText( urlLabelText ); urlLabel.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false ) ); addToWidthGroup( urlLabel ); createUrlControl(); } protected void createUrlControl() { UrlFieldFacade facade; if ( readonlyUrl ) { final Text urlText = new Text( this, SWT.READ_ONLY ); urlText.setData( "name", URL_CONTROL_NAME ); GridData gd = new GridData( SWT.FILL, SWT.CENTER, true, false, 3, 1 ); gd.widthHint = 100; gd.horizontalIndent = INPUT_INDENT; urlText.setLayoutData( gd ); urlText.setBackground( urlText.getDisplay().getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ) ); facade = new UrlFieldFacade() { public void setText( String text ) { urlText.setText( text ); } public void setEnabled( boolean enabled ) { } public String getText() { return urlText.getText(); } public void addModifyListener( ModifyListener listener ) { } public void addSelectionListener( SelectionListener listener ) { } public Control getWrappedControl() { return urlText; } }; } else { final Combo combo = new Combo( this, SWT.NONE ); combo.setData( "name", URL_CONTROL_NAME ); GridData gd = new GridData( SWT.FILL, SWT.CENTER, true, false, 3, 1 ); gd.widthHint = 100; gd.horizontalIndent = INPUT_INDENT; combo.setLayoutData( gd ); inputHistory.add( urlLabelText, combo ); inputHistory.load(); facade = new UrlFieldFacade() { public void setText( String text ) { combo.setText( text ); } public void setEnabled( boolean enabled ) { combo.setEnabled( enabled ); } public String getText() { return combo.getText(); } public void addModifyListener( ModifyListener listener ) { combo.addModifyListener( listener ); } public void addSelectionListener( SelectionListener listener ) { combo.addSelectionListener( listener ); } public Control getWrappedControl() { return combo; } }; } // use variable to be sure the field is set. assert facade != null; urlComponent = facade; } boolean hasUsernamePasswordControls = false; /** * Creates the controls for username and password authentication. * * @return true if the layout has changed */ private boolean createUsernamePasswordControls() { if ( hasUsernamePasswordControls ) { return false; } hasUsernamePasswordControls = true; usernameLabel = new Label( this, SWT.NONE ); usernameLabel.setText( Messages.urlInput_username_label ); GridData usernameLabelData = new GridData( SWT.LEFT, SWT.CENTER, false, false ); usernameLabelData.horizontalIndent = INPUT_INDENT; usernameLabel.setLayoutData( usernameLabelData ); addToWidthGroup( usernameLabel ); usernameText = new Text( this, SWT.BORDER ); usernameText.setData( "name", USERNAME_TEXT_NAME ); GridData usernameGridData = new GridData( SWT.LEFT, SWT.CENTER, false, false ); usernameGridData.widthHint = INPUT_WIDTH; usernameGridData.horizontalIndent = INPUT_INDENT; usernameText.setLayoutData( usernameGridData ); usernameText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { username = usernameText.getText(); setDirty(); } } ); // Set focus to username if the URL is read-only if ( readonlyUrl ) usernameText.setFocus(); anonymousLabel = new Label( this, SWT.NONE ); anonymousLabel.setText( Messages.urlInput_anonymousIfEmpty ); anonymousLabel.setData( "name", ANONYMOUS_LABEL_NAME ); anonymousLabel.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, true, false, 2, 1 ) ); passwordLabel = new Label( this, SWT.NONE ); passwordLabel.setText( Messages.urlInput_password_label ); GridData passwordLabelData = new GridData( SWT.LEFT, SWT.CENTER, false, false ); passwordLabelData.horizontalIndent = INPUT_INDENT; passwordLabel.setLayoutData( passwordLabelData ); addToWidthGroup( passwordLabel ); passwordText = new Text( this, SWT.BORDER | SWT.PASSWORD ); passwordText.setData( "name", PASSWORD_TEXT_NAME ); GridData passwordGridData = new GridData( SWT.LEFT, SWT.CENTER, false, false, 3, 1 ); passwordGridData.widthHint = INPUT_WIDTH; passwordGridData.horizontalIndent = INPUT_INDENT; passwordText.setLayoutData( passwordGridData ); passwordText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { password = passwordText.getText(); setDirty(); } } ); SwtValidationGroup.setComponentName( usernameText, Messages.urlInput_username_name ); SwtValidationGroup.setComponentName( passwordText, Messages.urlInput_password_name ); addToValidationGroup( usernameText, new CredentialsValidator() ); // addToValidationGroup( passwordText, new CredentialsValidator() ); return true; } /** * Removes the controls for username and password authentication. * * @return true if the layout has changed */ private boolean removeUsernamePasswordControls() { if ( !hasUsernamePasswordControls ) { return false; } hasUsernamePasswordControls = false; usernameLabel.dispose(); usernameText.dispose(); anonymousLabel.dispose(); passwordLabel.dispose(); passwordText.dispose(); return true; } boolean hasCertificateControls = false; /** * Removes the controls for SSL certificate authentication. * * @return true if the layout has changed */ private boolean removeCertificateControls() { if ( !hasCertificateControls ) { return false; } hasCertificateControls = false; certificateLabel.dispose(); certificateText.dispose(); browseCertificateButton.dispose(); passphraseLabel.dispose(); passphraseText.dispose(); return true; } /** * Creates the controls for SSL certificate authentication. * * @return true if the layout has changed */ private boolean createCertificateControls() { if ( hasCertificateControls ) { return false; } hasCertificateControls = true; certificateLabel = new Label( this, SWT.NONE ); GridData certificateLabelData = new GridData( SWT.LEFT, SWT.CENTER, false, false ); certificateLabelData.horizontalIndent = INPUT_INDENT; certificateLabel.setLayoutData( certificateLabelData ); certificateLabel.setText( Messages.urlInput_certificateFile_label ); addToWidthGroup( certificateLabel ); certificateText = new Text( this, SWT.BORDER ); certificateText.setData( "name", CERTIFICATE_TEXT_NAME ); GridData certificateData = new GridData( SWT.FILL, SWT.CENTER, true, false, 2, 1 ); certificateData.widthHint = 100; certificateData.horizontalIndent = INPUT_INDENT; certificateText.setLayoutData( certificateData ); SwtValidationGroup.setComponentName( certificateText, Messages.urlInput_certificateFile_name ); addToValidationGroup( certificateText, StringValidators.REQUIRE_NON_EMPTY_STRING ); certificateText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { certificate = certificateText.getText(); setDirty(); } } ); browseCertificateButton = new Button( this, SWT.PUSH ); browseCertificateButton.setData( "name", BROWSE_CERTIFICATE_BUTTON_NAME ); browseCertificateButton.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false ) ); browseCertificateButton.setText( Messages.urlInput_browse ); browseCertificateButton.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { FileDialog fd = new FileDialog( getShell(), SWT.OPEN ); fd.setText( Messages.urlInput_fileSelect_title ); String current = certificateText.getText().trim(); fd.setFilterExtensions( new String[] { "*.p12;*.crt", "*.*" //$NON-NLS-1$ $NON-NLS-2$ } ); fd.setFilterNames( new String[] { Messages.urlInput_fileSelect_filter1, Messages.urlInput_fileSelect_filter2 } ); if ( current.length() > 0 ) { fd.setFileName( current ); } String filename = fd.open(); if ( filename != null ) { certificateText.setText( filename ); } } } ); passphraseLabel = new Label( this, SWT.NONE ); GridData passphraseLabelData = new GridData( SWT.LEFT, SWT.CENTER, false, false ); passphraseLabelData.horizontalIndent = INPUT_INDENT; passphraseLabel.setLayoutData( passphraseLabelData ); passphraseLabel.setText( Messages.urlInput_passphrase_label ); addToWidthGroup( passphraseLabel ); passphraseText = new Text( this, SWT.BORDER | SWT.PASSWORD ); passphraseText.setData( "name", PASSPHRASE_TEXT_NAME ); GridData passphraseData = new GridData( SWT.LEFT, SWT.CENTER, false, false ); passphraseData.widthHint = INPUT_WIDTH; passphraseData.horizontalIndent = INPUT_INDENT; passphraseText.setLayoutData( passphraseData ); SwtValidationGroup.setComponentName( passphraseText, Messages.urlInput_passphrase_name ); // addToValidationGroup( passphraseText, StringValidators.REQUIRE_NON_EMPTY_STRING ); passphraseText.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { passphrase = passphraseText.getText(); setDirty(); } } ); return true; } public String getUrlText() { return url == null ? "" : url; } public void updateCredentials() { if ( Beans.isDesignTime() ) { return; } updating = true; IAuthData newAuthData = AuthFacade.getAuthService().select( getUrlText() ); if ( newAuthData == null ) { authData = defaultAuthData; } else { authData = newAuthData; } boolean usernamePasswordLayoutHasChanged = false; if ( authData.allowsUsernameAndPassword() ) { usernamePasswordLayoutHasChanged = createUsernamePasswordControls(); if ( AnonymousAccessType.REQUIRED.equals( authData.getAnonymousAccessType() ) ) { authData.setUsernameAndPassword( "", "" ); usernameText.setEnabled( false ); passwordText.setEnabled( false ); } else { usernameText.setEnabled( true ); passwordText.setEnabled( true ); } usernameText.setText( authData.getUsername() ); passwordText.setText( authData.getPassword() ); anonymousLabel.setVisible( authData.allowsAnonymousAccess() ); } else { usernamePasswordLayoutHasChanged = removeUsernamePasswordControls(); } boolean certificateLayoutHasChanged = false; if ( authData.allowsCertificate() ) { certificate = null; passphrase = null; File file = authData.getCertificatePath(); if ( file != null ) { certificate = file.getAbsolutePath(); } passphrase = authData.getCertificatePassphrase(); certificateLayoutHasChanged = createCertificateControls(); certificateText.setText( certificate == null ? "" : certificate ); passphraseText.setText( passphrase == null ? "" : passphrase ); } else { certificateLayoutHasChanged = removeCertificateControls(); } updating = false; if ( initialized && ( usernamePasswordLayoutHasChanged || certificateLayoutHasChanged ) ) { getShell().pack(); } if ( getValidationGroup() != null ) { getValidationGroup().performValidation(); } } public String getUrl() { if ( dirty ) { inputHistory.save(); saveCredentials(); dirty = false; } return getUrlText(); } public void setUrl( String text ) { if ( text != null ) { urlComponent.setText( text ); url = text; updateCredentials(); } } public void enableControls( boolean b ) { urlComponent.setEnabled( b ); } private void setDirty() { if ( !updating ) { dirty = true; } } private void saveCredentials() { if ( Beans.isDesignTime() ) { return; } Problem validationProblem = getValidationGroup().performValidation(); if (validationProblem != null && validationProblem.isFatal()) { return; } if ( authData.allowsUsernameAndPassword() ) { authData.setUsernameAndPassword( username, password ); } if ( authData.allowsCertificate() ) { File certificatePath = null; String filename = certificate; if ( filename.length() > 0 ) { certificatePath = new File( filename ); } authData.setSSLCertificate( certificatePath, passphrase ); } AuthFacade.getAuthService().save( getUrlText(), authData ); } /** * @return the combo box component showing the url. can return null if the url is not represented by the combobox. */ protected Combo getComboBoxComponent() { Control c = urlComponent.getWrappedControl(); return c instanceof Combo ? (Combo) c : null; } private interface UrlFieldFacade { String getText(); void setText( String text ); void addModifyListener( ModifyListener listener ); void addSelectionListener( SelectionListener listener ); void setEnabled( boolean enabled ); Control getWrappedControl(); } public void addModifyListener( ModifyListener modifyListener ) { urlComponent.addModifyListener( modifyListener ); } }
package com.leetcode.array; public class ArrayUtil { public static void printArray(int[] array) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < array.length; i++) { if (stringBuilder.length() > 0) { stringBuilder.append(","); } stringBuilder.append(array[i]); } System.out.println("数组:" + stringBuilder.toString()); } }
package com.collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static com.sun.xml.internal.fastinfoset.util.ValueArray.MAXIMUM_CAPACITY; /** * map test */ public class MapDemo { private static int RESIZE_STAMP_BITS = 16; public static void main(String[] args) { ConcurrentHashMap<Object, Object> concurrentHashMap = new ConcurrentHashMap<>(); concurrentHashMap.put(null,null); concurrentHashMap.get(null); Map<Object, Object> dataMap = new HashMap<>(8); dataMap.put(null, null); dataMap.get(null); int i = tableSizeFor(333); System.out.println("master 23:03"); } static final int resizeStamp(int n) { //hash = (h ^ (h >>> 16)) & HASH_BITS; // n为16(10000)时候,Integer.numberOfLeadingZeros(n) = 27 ,(1 << (RESIZE_STAMP_BITS - 1) =0000 0000 0000 0000 1000 0000 0000 0000 // 0000 0000 0000 0000 0000 0000 0001 1011 (27) // 0000 0000 0000 0000 1000 0000 0000 0000 ((1 << (RESIZE_STAMP_BITS - 1)) // 0000 0000 0000 0000 1000 0000 0001 1011 结果 // 1000 0000 0001 1011 0000 0000 0000 0010(rs << RESIZE_STAMP_SHIFT) + 2) return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1)); } static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } }
package com.koreait.captcha; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class CheckCaptcha */ @WebServlet("/check.do") public class CheckCaptcha extends HttpServlet { private static final long serialVersionUID = 1L; public CheckCaptcha() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /******* 사용자 입력값 검증 요청 *********/ String clientId = "1S0MXEyYjbRIgfkpKQLn";//애플리케이션 클라이언트 아이디값"; String clientSecret = "OLQ2Wgsoua";//애플리케이션 클라이언트 시크릿값"; // 발급 받은 캡차 키는 session 에 저장되어 있다. HttpSession session = request.getSession(); String key = session.getAttribute("key").toString(); // 캡차 키 발급시 받은 키값 // 사용자는 캡차 이미지 글자를 name="input"으로 전달한다. request.setCharacterEncoding("utf-8"); // 사실 불필요 String value = request.getParameter("input"); // 사용자가 입력한 캡차 이미지 글자값 try { String code = "1"; // 키 발급시 0, 캡차 이미지 비교시 1로 세팅 String apiURL = "https://openapi.naver.com/v1/captcha/nkey?code=" + code +"&key="+ key + "&value="+ value; URL url = new URL(apiURL); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("X-Naver-Client-Id", clientId); con.setRequestProperty("X-Naver-Client-Secret", clientSecret); int responseCode = con.getResponseCode(); BufferedReader br; if(responseCode==200) { // 정상 호출 br = new BufferedReader(new InputStreamReader(con.getInputStream())); } else { // 에러 발생 br = new BufferedReader(new InputStreamReader(con.getErrorStream())); } String inputLine; StringBuffer sb = new StringBuffer(); while ((inputLine = br.readLine()) != null) { sb.append(inputLine); } br.close(); System.out.println(sb.toString()); // sb.toString() // 검증 실패 {"result":false,"errorMessage":"Invalid key.","errorCode":"CT001"} // 검증 성공 {"result":true,"responseTime":18.0} // String -> JSONObject 객체 JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject)parser.parse(sb.toString()); // 다음 view 에게 result, responseTime 전달하기 위해 request 에 저장 request.setAttribute("result", (boolean)obj.get("result")); request.setAttribute("responseTime", (double)obj.get("responseTime")); } catch (Exception e) { System.out.println(e); } // 이동 request.getRequestDispatcher("result.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package pl.wiktor.generator; import java.util.Random; public class ArrayGenerator { public void sprawdzCzyPosortowany(int[] ciag) { boolean posortowany = false; for (int i = 1; i < ciag.length; i++) { if (ciag[i - 1] > ciag[i]) { posortowany = false; break; } else { posortowany = true; } } if (posortowany) { System.out.println("POSORTOWANY!"); } else if (!posortowany) { System.out.println("JAKIS BLAD!!!!!!!!!!!"); } } public void sprawdzCzyPosortowanyODWROTNIE(int[] ciag) { boolean posortowany = false; for (int i = 1; i < ciag.length; i++) { if (ciag[i - 1] < ciag[i]) { posortowany = false; break; } else { posortowany = true; } } if (posortowany) { System.out.println("POSORTOWANY!"); } else if (!posortowany) { System.out.println("JAKIS BLAD!!!!!!!!!!!"); } } public int[] generujCiag(Random rnd, int size) { int[] tmp = new int[size]; for (int i = 0; i < size; i++) { int tmp_int = rnd.nextInt(4532) + 1; tmp[i] = tmp_int; } return tmp; } public int[] generujCiagSpecjalny(Random rnd, int first_element, int size, boolean direction) { int[] tmp = new int[size]; tmp[0] = first_element; int tmp_int = 0; for (int i = 1; i < size + 1; i++) { if (direction) { tmp_int = tmp[i - 1] + rnd.nextInt(15) + i % 2; } else if (!direction) { tmp_int = tmp[i - 1] - rnd.nextInt(15) + i % 2; } tmp[i] = tmp_int; } return tmp; } }