text
stringlengths
10
2.72M
package ciphers; public class SubstitutionCipher { private final char[] PLAINTEXT = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private final char[] CIPHERTEXT = { 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K', 'J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A' }; public String substitutionEncrypt(String plaintext) { return substitution(plaintext, 0); } public String substitutionDecrypt(String plaintext) { return substitution(plaintext, 1); } public String substitution(String plaintext, int typeScrypt) { if (plaintext == null || plaintext.trim().isEmpty()) throw new NullPointerException("Plaintext is null or empty"); char[] letters = plaintext.toCharArray(); char[] result = new char[letters.length]; for (int i = 0; i < letters.length; i++) { int plaintextNum = getIndexOfText(letters[i], typeScrypt == 0 ? PLAINTEXT : CIPHERTEXT); result[i] = plaintextNum != -1 ? typeScrypt == 0 ? CIPHERTEXT[plaintextNum] : PLAINTEXT[plaintextNum] : letters[i]; } return new String(result); } private int getIndexOfText(char letter, char[] arr) { for (int i = 0; i < arr.length; i++) if (arr[i] == letter) return i; return -1; } public static void main(String[] args) { SubstitutionCipher sc = new SubstitutionCipher(); String letters = "ABC 18130305 GHJ XYZ"; String newLetter = sc.substitutionEncrypt(letters); System.out.println("Encrypt: " + letters + " -> " + newLetter); String oldLetter = sc.substitutionDecrypt(newLetter); System.out.println("Decrypt: " + newLetter + " -> " + oldLetter); } }
package global.model; /** * ¿Î³ÌÊÓͼÀà * * @author ggc * */ public class View_course { private String tp_id; private String tp_name; private String tp_mark; private String m_id; private String cou_id; private String cou_category; private String cou_name; private float cou_credit; private int cou_theoryhour; private int cou_experimentalhours; private int cou_practicehour; private int cou_semester; private int cou_type; private String d_id; private String d_name; public View_course(String tp_id, String tp_name, String tp_mark, String m_id,String cou_id, String cou_category, String cou_name, float cou_credit, int cou_theoryhour, int cou_experimentalhours, int cou_practicehour, int cou_semester, int cou_type, String d_id, String d_name) { super(); this.tp_id = tp_id; this.tp_name = tp_name; this.tp_mark = tp_mark; this.cou_id = cou_id; this.m_id = m_id; this.cou_category = cou_category; this.cou_name = cou_name; this.cou_credit = cou_credit; this.cou_theoryhour = cou_theoryhour; this.cou_experimentalhours = cou_experimentalhours; this.cou_practicehour = cou_practicehour; this.cou_semester = cou_semester; this.cou_type = cou_type; this.d_id = d_id; this.d_name = d_name; } public String getTp_id() { return tp_id; } public void setTp_id(String tp_id) { this.tp_id = tp_id; } public void setM_id(String m_id){ this.m_id = m_id; } public String getTp_name() { return tp_name; } public void setTp_name(String tp_name) { this.tp_name = tp_name; } public String getTp_mark() { return tp_mark; } public String getM_id() { return m_id; } public void setTp_mark(String tp_mark) { this.tp_mark = tp_mark; } public String getCou_id() { return cou_id; } public void setCou_id(String cou_id) { this.cou_id = cou_id; } public String getCou_category() { return cou_category; } public void setCou_category(String cou_category) { this.cou_category = cou_category; } public String getCou_name() { return cou_name; } public void setCou_name(String cou_name) { this.cou_name = cou_name; } public float getCou_credit() { return cou_credit; } public void setCou_credit(float cou_credit) { this.cou_credit = cou_credit; } public int getCou_theoryhour() { return cou_theoryhour; } public void setCou_theoryhour(int cou_theoryhour) { this.cou_theoryhour = cou_theoryhour; } public int getCou_experimentalhours() { return cou_experimentalhours; } public void setCou_experimentalhours(int cou_experimentalhours) { this.cou_experimentalhours = cou_experimentalhours; } public int getCou_practicehour() { return cou_practicehour; } public void setCou_practicehour(int cou_practicehour) { this.cou_practicehour = cou_practicehour; } public int getCou_semester() { return cou_semester; } public void setCou_semester(int cou_semester) { this.cou_semester = cou_semester; } public int getCou_type() { return cou_type; } public void setCou_type(int cou_type) { this.cou_type = cou_type; } public String getD_id() { return d_id; } public void setD_id(String d_id) { this.d_id = d_id; } public String getD_name() { return d_name; } public void setD_name(String d_name) { this.d_name = d_name; } }
package com.cts.product.profile.domain; import java.util.HashMap; import java.util.Map; public class UserProfile { private final String fullName; private final String userId; private final String mobileNo; private final String emailId; private final Map<String, String> preferences; private UserProfile( final String fullName, final String userId, final String mobileNo, final String emailId, final Map<String, String> preferences) { this.fullName = fullName; this.userId = userId; this.mobileNo = mobileNo; this.emailId = emailId; this.preferences = preferences; } public String getFullName() { return fullName; } public String getUserId() { return userId; } public String getMobileNo() { return mobileNo; } public String getEmailId() { return emailId; } public Map<String, String> getPreferences() { return preferences; } public static class ProfileBuilder { private String fullName; private String userId; private String mobileNo; private String emailId; private Map<String, String> preferences; public ProfileBuilder(final String userId) { this.userId = userId; } public ProfileBuilder fullName(String fullName) { this.fullName = fullName; return this; } public ProfileBuilder userId(String userId) { this.userId = userId; return this; } public ProfileBuilder mobileNo(String mobileNo) { this.mobileNo = mobileNo; return this; } public ProfileBuilder emailId(String emailId) { this.emailId = emailId; return this; } public ProfileBuilder preferences(Map<String, String> preferences) { this.preferences = preferences; return this; } public ProfileBuilder addPreference(String type, String value) { if (this.preferences == null) this.preferences = new HashMap<String, String>(); this.preferences.put(type, value); return this; } public UserProfile build() { return new UserProfile(fullName, userId, mobileNo, emailId, preferences); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package livraria.bo; import java.util.Date; import java.util.List; import livraria.persistence.Dao; import livraria.persistence.FuncionarioDao; import livraria.vo.Funcionario; /** * * @author Nilliam Ometto */ public class FuncionarioBO { private Dao dao; private Funcionario funcionario; private List<Funcionario> funcionarioList; private boolean isUpdate; public FuncionarioBO() { this.dao = new FuncionarioDao(); } public List<Funcionario> getAll() { return funcionarioList = dao.getAll(); } public void setSelected(int index) { funcionario = funcionarioList.get(index); } public Funcionario getFuncionario() { return funcionario; } public boolean removeSelected(int index) { return dao.remove(funcionarioList.get(index)); } public void setUpdate(boolean isUpdate) { this.isUpdate = isUpdate; } public boolean isUpdate() { return isUpdate; } public boolean persistir(String bairro, String celular, String cep, String cidade, String codigo, String complemento, String contato, String cpf, String email, String endereco, String nome, String num, String rg, String tel, String uf, String usuario, String senha, boolean isSupervisor) { Funcionario c = isUpdate ? funcionario : new Funcionario(); c.setBairro(bairro); c.setCelular(celular); c.setCep(cep); c.setCidade(cidade); c.setCodigo(codigo); c.setComplemento(complemento); c.setContato(contato); c.setCpf(cpf); c.setDataAtualizacao(new Date()); c.setDataCadastro(new Date()); c.setEmail(email); c.setEndereco(endereco); c.setNome(nome); c.setNumero(num); c.setRg(rg); c.setTelefone(tel); c.setUf(uf); c.setUsuario(usuario); c.setSenha(senha); c.setSupervisor(isSupervisor); return dao.persistir(c); } public String getCodigo() { return funcionario.getCodigo(); } public String getNome() { return funcionario.getNome(); } public String getCpf() { return funcionario.getCpf(); } public String getRg() { return funcionario.getRg(); } public String getEndereco() { return funcionario.getEndereco(); } public String getNumero() { return funcionario.getNumero(); } public String getComplemento() { return funcionario.getComplemento(); } public String getBairro() { return funcionario.getBairro(); } public String getCidade() { return funcionario.getCidade(); } public String getUf() { return funcionario.getUf(); } public String getCep() { return funcionario.getCep(); } public String getTelefone() { return funcionario.getTelefone(); } public String getContato() { return funcionario.getContato(); } public String getCelular() { return funcionario.getCelular(); } public String getEmail() { return funcionario.getEmail(); } public Date getDataCadastro() { return funcionario.getDataCadastro(); } public Date getDataAtualizacao() { return funcionario.getDataAtualizacao(); } public String getUsuario() { return funcionario.getUsuario(); } public String getSenha() { return funcionario.getSenha(); } public boolean isSupervisor() { return funcionario.isSupervisor(); } }
package com.bebidas.br.repository; import java.util.Collection; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.bebidas.br.model.Estoque; public interface EstoqueRepository extends JpaRepository<Estoque, Long> { @Query("SELECT e FROM Estoque e INNER JOIN Bebida b ON e.bebida.idBebida = b.idBebida WHERE b.tipoBebida.idTipoBebida =" + " :tipo") Collection<Estoque> findTipo(@Param("tipo") Integer tipo); @Query("SELECT e FROM Estoque e INNER JOIN Sessao s ON e.sessao.idSessao = s.idSessao WHERE s.idSessao = :idSessao") Collection<Estoque> findSessao(@Param("idSessao") Integer idSessao); @Query("SELECT COALESCE(sum(e.qtd),0) as qtd FROM Estoque e INNER JOIN Sessao s ON e.sessao.idSessao = s.idSessao " + "WHERE s.idSessao = :idSessao") Integer countQtqEstoque(@Param("idSessao") Integer idSessao); @Query("SELECT e FROM Estoque e where e.sessao.idSessao=:idSessao and e.bebida.idBebida = :idBebida") Estoque buscaEstoqueBebida(@Param("idBebida") Long idBebida, @Param("idSessao") Integer idSessao); }
package main.java.com.javacore.multithreading.task2; public class BuzzThread implements Runnable{ private final FizzBuzz foo; public BuzzThread(FizzBuzz foo) { this.foo = foo; } @Override public void run() { foo.buzz(); } }
package xyz.mcallister.seth.HG.commands; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import xyz.mcallister.seth.HG.GameState; /** * Created by sethm on 06/04/2016. */ public class Start implements CommandExecutor { public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) { if(command.getName().equalsIgnoreCase("forcestart") && sender.hasPermission("hg.admin")) { if(!sender.hasPermission("hg.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to execute that command."); return true; } if(GameState.started.get()) sender.sendMessage(ChatColor.RED + "The game has already started."); else { Bukkit.broadcastMessage(ChatColor.GREEN + "The game has been started by " + sender.getName()); GameState.started.set(true); GameState.lobby.set(false); } } return false; } }
package Clases; public class ClaseChofer { public String dni = " "; public String nombre = " "; public String Edad = " "; public String direccion = " "; public ClaseChofer(String dni, String nombre, String edad, String direccion) { this.dni = dni; this.nombre = nombre; Edad = edad; this.direccion = direccion; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getEdad() { return Edad; } public void setEdad(String edad) { Edad = edad; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } }
public static int binarySearch(int A[] int l, int u, int x){ while(l<=u){ int m=(l+u)/2; if (x==A[m]) return m; else if (A[l]<=A[m]){ if (x>=A[l]) u=m-1; else if (x>A[m])l=m+1; } } } //using DP public int maxSubArray(int[] A) { int newSum=A[0]; int maxSum = A[0]; for (int i=1;i<A.length;i++){ newSum = Math.max(newSum+A[i], A[i]); maxSum = Math.max(newSum, maxSum); } return maxSum; }
package cn.itcast.spring.SpringAutoAop; public class UserDaoImpl implements UserDao{ public void add(){ System.out.println("添加用户成功"); } public void find(){ System.out.println("查找用户成功"); } public void update() { System.out.println("更新用户成功"); } public void delete() { System.out.println("删除用户成功"); } }
package com.lesports.albatross.utils.request; import android.content.Context; import android.support.v4.util.ArrayMap; /** * Created by zhouchenbin on 16/6/16. */ public class RequestHelper { private Context mContext; private IResponseCallBack mRealResponseCallBack = new IResponseCallBack() { @Override public void resultDataSuccess(int requestCode, String data) { if (mResponseCallBack != null) { mResponseCallBack.resultDataSuccess(requestCode,data); } taskSet.remove(requestCode); } @Override public void resultDataMistake(int requestCode, FProtocol.NetDataProtocol.ResponseStatus responseStatus, String errorMessage) { if (mResponseCallBack != null) { mResponseCallBack.resultDataMistake(requestCode,responseStatus,errorMessage); } taskSet.remove(requestCode); } }; private IResponseCallBack mResponseCallBack ; private ArrayMap<Integer,ExecutorTask> taskSet = new ArrayMap<>(); public RequestHelper(Context context,IResponseCallBack callBack){ mContext = context.getApplicationContext(); mResponseCallBack = callBack; } public void dispose () { for (ExecutorTask task : taskSet.values()) { task.cancel(); } mResponseCallBack = null; } public ExecutorTaskBuilder getNewTaskBuilder() { return new ExecutorTaskBuilder(mContext,taskSet).setCallBack(mRealResponseCallBack); } }
package modelTest; import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Test; import saboteur.model.Board; import saboteur.model.*; import saboteur.model.Card.*; public class BoardTest { //NOT SUCCESS CURRENTLY : Due to board's constructor @Test public void testIsPossible() { int xStart = Board.getStart().getcX(); int yStart = Board.getStart().getcY(); String cross[] = {"NORTH", "EAST", "SOUTH", "WEST"}; String horizontalBar[] = {"WEST", "EAST"}; String verticalBar[] = {"NORTH", "SOUTH"}; String angleRight[] = {"SOUTH", "EAST"}; String angleLeft [] = {"SOUTH", "WEST"}; PathCard crossCard = new PathCard(cross, false, false, false, false); PathCard horizontalBarCard = new PathCard(horizontalBar, false, false, false, false); PathCard verticalBarCard = new PathCard(verticalBar, false, false, false, false); PathCard angleRightCardSouth = new PathCard(angleRight, false, false, false, false); PathCard angleLeftCardSouth = new PathCard(angleLeft, false, false, false, false); PathCard angleLeftCardNorth = angleRightCardSouth.clone(); angleLeftCardNorth.reverse(); PathCard angleRigthCardNorth = angleLeftCardSouth.clone(); angleRigthCardNorth.reverse(); PathCard start = new PathCard(cross, false, true, false, false); PathCard goalWithGold = new PathCard(cross, false, false, true, true); goalWithGold.setVisible(false); PathCard goal = new PathCard(cross, false, false, true, false); goal.setVisible(false); ArrayList<PathCard> startCards = new ArrayList<>(); startCards.add(start); ArrayList<PathCard> goalCards = new ArrayList<>(); goalCards.add(goal); goalCards.add(goal); goalCards.add(goalWithGold); Board boardTest = new Board(startCards, goalCards); assertEquals(true, boardTest.isPossible(crossCard, new Position(xStart,yStart-1))); assertEquals(true, boardTest.isPossible(crossCard, new Position(xStart+1,yStart))); assertEquals(true, boardTest.isPossible(crossCard, new Position(xStart,yStart+1))); assertEquals(true, boardTest.isPossible(crossCard, new Position(xStart-1,yStart))); boardTest.addCard(crossCard, new Position(xStart,yStart-1)); boardTest.addCard(crossCard, new Position(xStart+1,yStart)); boardTest.addCard(crossCard, new Position(xStart,yStart+1)); boardTest.addCard(crossCard, new Position(xStart-1,yStart)); //test add card without neighbor assertEquals(false, boardTest.isPossible(crossCard, new Position(xStart-10,yStart-10))); assertEquals(false, boardTest.isPossible(verticalBarCard, new Position(xStart-1,yStart-1))); assertEquals(false, boardTest.isPossible(horizontalBarCard, new Position(xStart+1,yStart-1))); assertEquals(false, boardTest.isPossible(verticalBarCard, new Position(xStart+1,yStart+1))); assertEquals(false, boardTest.isPossible(horizontalBarCard, new Position(xStart-1,yStart+1))); assertEquals(true, boardTest.isPossible(angleRightCardSouth, new Position(xStart-1,yStart-1))); assertEquals(true, boardTest.isPossible(angleLeftCardSouth, new Position(xStart+1,yStart-1))); assertEquals(true, boardTest.isPossible(angleLeftCardNorth, new Position(xStart+1,yStart+1))); assertEquals(true, boardTest.isPossible(angleRigthCardNorth, new Position(xStart-1,yStart+1))); boardTest.addCard(angleRightCardSouth, new Position(xStart-1,yStart-1)); boardTest.addCard(angleLeftCardSouth, new Position(xStart+1,yStart-1)); boardTest.addCard(angleLeftCardNorth, new Position(xStart+1,yStart+1)); boardTest.addCard(angleRigthCardNorth, new Position(xStart-1,yStart+1)); assertEquals(true, boardTest.isPossible(angleRightCardSouth, new Position(xStart,yStart-2))); assertEquals(true, boardTest.isPossible(angleLeftCardSouth, new Position(xStart+2,yStart))); assertEquals(true, boardTest.isPossible(angleLeftCardNorth, new Position(xStart,yStart+2))); assertEquals(true, boardTest.isPossible(angleRigthCardNorth, new Position(xStart-2,yStart))); boardTest.addCard(angleRightCardSouth, new Position(xStart,yStart-2)); boardTest.addCard(angleLeftCardSouth, new Position(xStart+2,yStart)); boardTest.addCard(angleLeftCardNorth, new Position(xStart,yStart+2)); boardTest.addCard(angleRigthCardNorth, new Position(xStart-2,yStart)); assertEquals(false, boardTest.isPossible(angleLeftCardSouth, new Position(xStart+1,yStart-2))); assertEquals(false, boardTest.isPossible(angleLeftCardNorth, new Position(xStart+2,yStart+1))); assertEquals(false, boardTest.isPossible(angleRigthCardNorth, new Position(xStart-1,yStart+2))); assertEquals(false, boardTest.isPossible(angleRightCardSouth, new Position(xStart-2,yStart-1))); assertEquals(true, boardTest.isPossible(horizontalBarCard, new Position(xStart+1,yStart-2))); assertEquals(true, boardTest.isPossible(verticalBarCard, new Position(xStart+2,yStart+1))); assertEquals(true, boardTest.isPossible(horizontalBarCard, new Position(xStart-1,yStart+2))); assertEquals(true, boardTest.isPossible(verticalBarCard, new Position(xStart-2,yStart-1))); assertEquals(false, boardTest.isPossible(horizontalBarCard, new Position(xStart+Board.DISTANCE_START_OBJECTIVE_X-1,yStart))); goal.setVisible(true); goalWithGold.setVisible(true); assertEquals(true, boardTest.isPossible(horizontalBarCard, new Position(xStart+Board.DISTANCE_START_OBJECTIVE_X-1,yStart))); } }
package com.junzhao.shanfen.page; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.junzhao.base.base.APPCache; import com.junzhao.base.base.BaseFrag; import com.junzhao.base.http.IHttpResultSuccess; import com.junzhao.base.http.MLHttpRequestMessage; import com.junzhao.base.http.MLHttpType; import com.junzhao.base.http.MLRequestParams; import com.junzhao.base.recycler.ViewHolder; import com.junzhao.base.recycler.recyclerview.CommonAdapter; import com.junzhao.base.recycler.recyclerview.OnItemClickListener; import com.junzhao.base.utils.ImageUtils; import com.junzhao.base.utils.MyLogger; import com.junzhao.base.widget.refresh.SmartRefreshLayout; import com.junzhao.shanfen.EventBusContant; import com.junzhao.shanfen.R; import com.junzhao.shanfen.activity.PostDetail2Activity; import com.junzhao.shanfen.activity.PostPersonActitity; import com.junzhao.shanfen.adapter.PostImgAdapter; import com.junzhao.shanfen.model.LZAttrationData; import com.junzhao.shanfen.model.PHFriend; import com.junzhao.shanfen.model.PHPostData; import com.junzhao.shanfen.model.PHUserData; import com.junzhao.shanfen.service.CommService; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 首页新鲜事 */ public class HotPager extends BaseFrag { View view; @ViewInject(R.id.aprv_post) SmartRefreshLayout aprv_post; @ViewInject(R.id.rv_invitation) RecyclerView rv_invitation; private boolean mIsRefresh; private int currentPage = 1; private int showAttr; private CommonAdapter<PHPostData> adapter; private List<PHPostData> datas = new ArrayList<>(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(R.layout.pager_hot, null); ViewUtils.inject(this, view); EventBus.getDefault().register(this); } return view; } @Override public void onDestroyView() { super.onDestroyView(); EventBus.getDefault().unregister(this); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter = new CommonAdapter<PHPostData>(getActivity(), R.layout.adapter_invitation, datas) { @Override public void convert(ViewHolder holder, PHPostData phPostData) { setTag(holder, phPostData); } }; rv_invitation.setAdapter(adapter); aprv_post.setOnRefreshListener(new SmartRefreshLayout.onRefreshListener() { @Override public void onRefresh() { mIsRefresh = true; currentPage = 1; getPostList(currentPage); } @Override public void onLoadMore() { mIsRefresh = false; getPostList(++currentPage); } }); getPostList(1); adapter.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(ViewGroup parent, View view, Object o, int position, ViewHolder viewHolder) { PHPostData data = datas.get(position); Intent intent = new Intent(getActivity(), PostDetail2Activity.class); intent.putExtra(PostDetail2Activity.POSTID, data.postsId); startActivity(intent); } @Override public boolean onItemLongClick(ViewGroup parent, View view, Object o, int position, ViewHolder viewHolder) { return false; } }); } private void setTag(final ViewHolder holder, final PHPostData itemData) { ImageUtils.dispatchImage(itemData.userPhoto, (ImageView) holder.getView(R.id.civ_topic)); holder.setText(R.id.tv_name, itemData.userName); holder.setText(R.id.tv_data, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(itemData.addTime)))); holder.setText(R.id.tv_replyNum, itemData.evaluateNum); holder.setText(R.id.tv_zhanNum, itemData.goodNum); holder.setText(R.id.tv_shareNum, itemData.transpondNum); if (itemData.isTranspond.equals("1")) { //显示转发帖子 holder.setText(R.id.tv_content, getText(itemData.postsContent + itemData.initialPostsBean.transpondContent + " @" + itemData.initialPostsBean.userName+"-userId_"+itemData.initialPostsBean.userId) ); ((GridView) holder.getView(R.id.rv_photo)).setAdapter(new PostImgAdapter(getContext(), itemData.initialPostsBean.mediaPath)); } else { holder.setText(R.id.tv_content, getText(itemData.postsContent)); ((GridView) holder.getView(R.id.rv_photo)).setAdapter(new PostImgAdapter(getContext(), itemData.mediaPath)); } ((GridView) holder.getView(R.id.rv_photo)).setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getActivity(), PostDetail2Activity.class); intent.putExtra(PostDetail2Activity.POSTID, itemData.postsId); startActivity(intent); } }); holder.getView(R.id.btn_attarition).setVisibility(showAttr); holder.getView(R.id.btn_yiattarition).setVisibility(View.GONE); holder.getView(R.id.btn_attarition).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { attarition(holder.getView(R.id.btn_attarition), holder.getView(R.id.btn_yiattarition), itemData); } }); holder.getView(R.id.btn_yiattarition).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { attarition(holder.getView(R.id.btn_attarition), holder.getView(R.id.btn_yiattarition), itemData); } }); holder.getView(R.id.ll_share).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(itemData); } }); // holder.getView(R.id.ll_reply).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent intent = new Intent(view.getContext(), PostReplyActivity.class); // intent.putExtra(PostReplyActivity.POSTID, itemData.postsId); // intent.putExtra(PostReplyActivity.EVALUATELEVEL, "1"); // intent.putExtra(PostReplyActivity.TOUSERID, itemData.userId); // view.getContext().startActivity(intent); // } // }); holder.getView(R.id.ll_zhan).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { postZan(view, itemData); } }); holder.getView(R.id.civ_topic).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(view.getContext(), PostPersonActitity.class); intent1.putExtra(PostPersonActitity.USERID, itemData.userId); view.getContext().startActivity(intent1); } }); if (showAttr == View.VISIBLE) { if (itemData.isFollow.equals("1")) { holder.getView(R.id.btn_attarition).setVisibility(View.GONE); holder.getView(R.id.btn_yiattarition).setVisibility(View.VISIBLE); } else { holder.getView(R.id.btn_attarition).setVisibility(View.VISIBLE); holder.getView(R.id.btn_yiattarition).setVisibility(View.GONE); } } holder.setOnClickListener(R.id.tv_content, new View.OnClickListener() { @Override public void onClick(View v) { PHPostData data = itemData; Intent intent = new Intent(getActivity(), PostDetail2Activity.class); intent.putExtra(PostDetail2Activity.POSTID, data.postsId); startActivity(intent); } }); if (itemData.userId.equals(((PHUserData)APPCache.getUseData()).userId)){ holder.getView(R.id.tv_del_post).setVisibility(View.VISIBLE); holder.getView(R.id.btn_attarition).setVisibility(View.GONE); holder.getView(R.id.btn_yiattarition).setVisibility(View.GONE); holder.setOnClickListener(R.id.tv_del_post, new View.OnClickListener() { @Override public void onClick(View v) { //TODO 删除帖子 deletePost(itemData.postsId); } }); }else { holder.getView(R.id.tv_del_post).setVisibility(View.GONE); } if (itemData.isLikes.equals("1")){ holder.getView(R.id.iv_zan).setBackgroundResource(R.mipmap.iv_zan_selected); }else { holder.getView(R.id.iv_zan).setBackgroundResource(R.mipmap.iv_zan_unselecter); } } private void getPostList(int pageNo) { if (showAttr == View.GONE){ MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", ((PHUserData) APPCache.getUseData()).token); mlHttpParam.put("pageNo", String.valueOf(pageNo)); mlHttpParam.put("pageSize", "10"); mlHttpParam.put("topicCategoryId", "1"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.ATTRPOST, mlHttpParam, PHPostData.class, CommService.getInstance(), true); message.setResList(true); loadData(getActivity(), message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { List phPostDat = (List<PHPostData>) obj; if (mIsRefresh) { adapter.removeAllDate(); adapter.addDate(phPostDat); aprv_post.stopRefresh(); } else { adapter.addDate(phPostDat); aprv_post.stopLoadMore(); } // rv_invitation.setAdapter(new PostListAdapter(getActivity(),phPostData)); } }); }else { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", ((PHUserData) APPCache.getUseData()).token); mlHttpParam.put("pageNo", String.valueOf(pageNo)); mlHttpParam.put("pageSize", "10"); mlHttpParam.put("topicCategoryId", "1"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.GETPOSTLIST, mlHttpParam, PHPostData.class, CommService.getInstance(), true); message.setResList(true); loadData(getActivity(), message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { List phPostDat = (List<PHPostData>) obj; if (mIsRefresh) { adapter.removeAllDate(); adapter.addDate(phPostDat); aprv_post.stopRefresh(); } else { adapter.addDate(phPostDat); aprv_post.stopLoadMore(); } // rv_invitation.setAdapter(new PostListAdapter(getActivity(),phPostData)); } }); } } private void deletePost(String postId) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", ((PHUserData) APPCache.getUseData()).token); mlHttpParam.put("postsId", postId); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.DELETEPOST, mlHttpParam, String.class, CommService.getInstance(), true); loadData(getActivity(), message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { showMessage(getActivity(),obj.toString()); EventBus.getDefault().post(new EventBusContant(EventBusContant.REFRESSHPOST)); } }); } private void attarition(final View unview, final View yiview, PHPostData itemData) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("token", ((PHUserData) APPCache.getUseData()).token); mlHttpParam.put("followType", "1"); mlHttpParam.put("followObjectId", itemData.userId); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.ATTRATION, mlHttpParam, LZAttrationData.class, CommService.getInstance(), true); loadData(view.getContext(), message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { LZAttrationData data = (LZAttrationData) obj; EventBus.getDefault().post(new EventBusContant(EventBusContant.REFRESSHPOST)); if (Integer.parseInt(data.oprateType) == 1) { showMessage(yiview.getContext(), "关注成功!"); } else if (Integer.parseInt(data.oprateType) == 2) { showMessage(yiview.getContext(), "取消关注成功!"); } } }); } private void postZan(final View view, final PHPostData itemData) { MLRequestParams mlHttpParam = new MLRequestParams(); mlHttpParam.put("goodObjId", itemData.postsId); mlHttpParam.put("token", APPCache.getToken()); mlHttpParam.put("goodType", "1"); MLHttpRequestMessage message = new MLHttpRequestMessage( MLHttpType.RequestType.POSTZAN, mlHttpParam, LZAttrationData.class, CommService.getInstance(), true); loadData(view.getContext(), message, new IHttpResultSuccess() { @Override public void success(MLHttpType.RequestType type, Object obj) { LZAttrationData data = (LZAttrationData) obj; if (Integer.parseInt(data.oprateType) == 1) { showMessage(getActivity(), "点赞成功"); itemData.goodNum = "" + (Integer.parseInt(itemData.goodNum) + 1); itemData.isLikes = "1"; adapter.notifyDataSetChanged(); } else { showMessage(getActivity(), "取消点赞成功"); itemData.goodNum = "" + (Integer.parseInt(itemData.goodNum) - 1); itemData.isLikes = "0"; adapter.notifyDataSetChanged(); } } }); } public HotPager setShowAttr(int showAttr) { this.showAttr = showAttr; return this; } /** * 将后台带有(@userName-userId_userid : @afff-userId_34234224)的字符串转成@字符 @[\\u4e00-\\u9fa5a-zA-Z0-9_-]+(-userId_)+[\\u4e00-\\u9fa5a-zA-Z0-9_-]* * * @param string * @return */ public SpannableStringBuilder getText(String string) { final List<PHFriend> data = getFriends(string); string = string.replaceAll("(-userId_)+[a-zA-Z0-9_-]*", " "); String reg = "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]* "; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(string); SpannableStringBuilder sp = new SpannableStringBuilder(string); while (matcher.find()) { final int start = matcher.start(); final int end = matcher.end(); MyLogger.kLog().e("start=" + start + ",end=" + end); sp.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { //点击了@ MyLogger.kLog().e("---------------"); String spanString = ((TextView) widget).getText().toString().substring(start, end); for (PHFriend friend : data) { if (spanString.equals("@" + friend.userName + " ")) { Intent intent = new Intent(getActivity(), PostPersonActitity.class); intent.putExtra(PostPersonActitity.USERID, friend.userId); startActivity(intent); break; } } } public void updateDrawState(TextPaint ds) { ds.setColor(Color.parseColor("#FC8138")); } }, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } String reg1 = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?"; Pattern pattern1 = Pattern.compile(reg1); Matcher matcher1 = pattern1.matcher(string); while (matcher1.find()) { final int start = matcher1.start(); final int end = matcher1.end(); MyLogger.kLog().e("start=" + start + ",end=" + end + ",string = "+ string.substring(start,end)); final String finalString = string; sp.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { //点击了链接 String url = finalString.substring(start,end); Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } public void updateDrawState(TextPaint ds) { ds.setColor(Color.parseColor("#FC8138")); } }, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } return sp; } public List<PHFriend> getFriends(String string) { List<PHFriend> friends = new ArrayList<>(); String reg = "[\\u4e00-\\u9fa5a-zA-Z0-9_-]+(-userId_)+[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(string); while (matcher.find()) { String userId = matcher.group(); MyLogger.kLog().e(userId); String[] friend = userId.split("-userId_"); PHFriend pf = new PHFriend(friend[1], friend[0]); friends.add(pf); } return friends; } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMessage(EventBusContant contant) { if (contant.getFlag() == EventBusContant.REFRESSHPOST) { mIsRefresh = true; currentPage = 1; getPostList(currentPage); } } }
package com.igs.entity.rsp; /** * 类描述:获取短信验证码(登录前,登陆后) * 创建人:heliang * 创建时间:2015/10/22 10:19 * 修改人:8153 * 修改时间:2015/10/22 10:19 * 修改备注: */ public class RspBodyGetSmsCodeBean extends BaseRsp { private String smsCode; public String getSmsCode() { return smsCode; } public void setSmsCode(String smsCode) { this.smsCode = smsCode; } }
package com.example.prova; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private static final String TAG= "Main Activity"; private Button btnSal, btnAltoBasso, btnAcc, btnTris, btnForza, btnBatnav; private TextView txtS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindComponent(); setupEventListener(); } private void bindComponent(){ btnSal = findViewById(R.id.btnSaluta); txtS = findViewById(R.id.txtSaluta); btnAltoBasso = findViewById(R.id.btnAltoBasso); btnTris = findViewById(R.id.btnTris); btnForza = findViewById(R.id.btnForza); btnBatnav = findViewById(R.id.btnBatnav); } private void setupEventListener(){ btnSal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { txtS.setTextSize(24); txtS.setText("Benvenuto sull'applicazione di Tommaso!"); } }); btnAltoBasso.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Avvio una nuova activity per giocare ad Alto e Basso Intent intent = new Intent(MainActivity.this, AltoBassoActivity.class); intent.putExtra("var", "valore"); startActivity(intent); } }); /*btnAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View w) { //Avvio una nuova activity per visualizzare l'accellerometro Intent intent = new Intent(MainActivity.this, AccActivity.class); startActivity(intent); } });*/ btnTris.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View w) { //Avvio una nuova activity per visualizzare l'accellerometro Intent intent = new Intent(MainActivity.this, TrisActivity.class); intent.putExtra("g1", "Giocatore 1"); intent.putExtra("g2", "Giocatore 2"); startActivity(intent); } }); btnBatnav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, BatNavActivity.class); intent.putExtra("g1", "giocatore 1"); intent.putExtra("g1", "giocatore 2"); startActivity(intent); } }); btnForza.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TrisActivity.class); intent.putExtra("g1", "giocatore 1"); intent.putExtra("g1", "giocatore 2"); startActivity(intent); } }); } }
package Courier.CourierService.Models; // Generated Jan 15, 2014 9:14:07 PM by Hibernate Tools 3.4.0.CR1 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.ccnx.android.ccnlib.JsonMessage; /** * Log generated by hbm2java */ @Entity @Table(name = "Log", catalog = "CourierDB") public class Log extends JsonMessage implements java.io.Serializable { private Integer logId; private String event; private Date time; private String device; public Log() { } public Log(String event, Date time) { this.event = event; this.time = time; } public Log(String event, Date time, String device) { this.event = event; this.time = time; this.device = device; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "LogId", unique = true, nullable = false) public Integer getLogId() { return this.logId; } public void setLogId(Integer logId) { this.logId = logId; } @Column(name = "Event", nullable = false) public String getEvent() { return this.event; } public void setEvent(String event) { this.event = event; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "Time", nullable = false, length = 19) public Date getTime() { return this.time; } public void setTime(Date time) { this.time = time; } @Column(name = "Device", length = 75) public String getDevice() { return this.device; } public void setDevice(String device) { this.device = device; } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; public class Lateness { public static void main(String[] args) { int[] workT = new int[1000];//배열의 크기는 넉넉하게 1000으로 했다. 걸리는 시간과 처음의 갯수를 저장함 int[] deadT = new int[1000];//배열의 크기는 넉넉하게 1000으로 했다. 끝나는 시간을 저장 String work,dead,line; int count = 0;// 현재 빈배열중 가장 앞에 배열의 위치를 나타내는 상수이다 try { FileReader fr = new FileReader("data06_lateness.txt"); BufferedReader br = new BufferedReader(fr);//텍스트파일을 읽어온다. line = br.readLine();//한줄씩 입력받는다. while (line != null) //줄이 없어질때까지 받음 {StringTokenizer tk = new StringTokenizer(line, " "); //tk라는 분해기가 띄어쓰기마다 단어를 자른다 while(tk.hasMoreTokens()){ work = tk.nextToken();//처음 오는 수를 저장한다. if(tk.hasMoreTokens()) {//만약 다음토큰이 있을경우에는 받는다 dead = tk.nextToken(); //다음 토큰이 없다는것은 첫줄을 읽은상태이다. deadT[count] = Integer.parseInt(dead);} workT[count++] = Integer.parseInt(work); } line = br.readLine(); // txt파일의 커서를 다음으로 옮기고, 다음 줄의 내용을 line에 저장한다. }br.close(); }// 자원소모 최소화 catch (IOException e) {} int n= workT[0];//0번째 배열엔 읽은 일의 갯수가 저장되어있다. int time = 0;//시작시간은 0으로 초기화 int lateness = 0;//lateness는 최소 0이기때문에 0으로 초기화했다. System.out.println("Input Data : \n" + n); for(int i=1;i<n+1;i++) {//0에는 일의 갯수라서 1부터 읽으면서 for문을 진행한다 System.out.println(workT[i]+ " " +deadT[i]); time+=workT[i];//일단 일한 시간을 현재 time에 더한다 if(deadT[i]<time) {//그시간이 종료시간을 넘었으면 Lateness 발생 if(lateness<time-deadT[i])//현재 저장된 lateness보다 크다면 lateness=time-deadT[i];//lateness 값을 바꿔준다. } } System.out.println("Output Data : "+lateness); }}
/* * 3- Dada a altura e o peso de uma pessoa, determinar seu grau de obesidade. * O grau de obesidade é determinado pelo índice da massa corpórea * (Massa = Peso / Altura2 ) através da tabela abaixo: */ package exerciciosaula; import java.util.Scanner; public class ExercicioIf3 { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("Escreva a altura: "); float altura = console.nextFloat(); System.out.print("Escreva a peso: "); float peso = console.nextFloat(); float IMC = (peso)/(altura*2); if(IMC>=26){ if(IMC<30){ System.out.println("Obeso IMC: "+ IMC); } else { System.out.println("Obeso Mórbido IMC: "+ IMC); } } else { System.out.println("Normal IMC: "+ IMC); } } }
package ru.job4j.methref; import java.util.ArrayList; import java.util.List; import java.util.function.Function; /** * Класс UserConvert демострирует применение ссылок на методы. * Синтаксис: * Для статических методов: * имя_класса::имя_мутода * Для нестатических методов: * имя_переменной::имя_метода * @see https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-12-17 * @since 2018-09-11 */ public class UserConvert { /** * Создаёт и возвращает список объектов пользователей, над которыми произведена операция. * @param names список имён пользователей. * @param op операция. * @return список пользователей. */ public List<User> factory(List<String> names, Function<String, User> op) { List<User> users = new ArrayList<>(); names.forEach( n -> users.add(op.apply(n)) ); return users; } }
package com.baoxu.controller; /** * * ClassName: LoginController <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * date: 2016年6月25日 下午3:07:12 <br/> * * @author Administrator * @version * @since JDK 1.7 */ public class LoginController { public String loginIndex(){ return null; } }
package com.gci.api.persistence; import java.util.List; import com.gci.api.model.contract.Contract; public interface ContractMapper { List<Contract> getAllContracts(String query); Contract getContract(int id); void insertContract(Contract contract); }
package RMA; import java.sql.SQLException; import java.sql.Types; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; /** DBService extends the initial core {@link DBConnection} class and * implements all logic and functionality for accessing the SQL Server * back-end database. */ class DBService extends DBConnection { /** query contains the most recent {@link String} query used on the database. */ private static String query; /** user contains the {@link String} username that was used to log into the database. */ private static String user; /** role contains the {@link String} role assigned to the username and password credentials used * to initially login to the database. * (Requirement 1.3) */ private static String role; /** instance is a private static instance of this class used to maintain a single point of access throughout * the application. */ private static DBService instance; /** Constructor that takes in a username, password, and instance name, and attempts * to create a connection to the database. * @param username The {@link String} username to use to connect to the database. * @param password The {@link String} password to use to connect to the database. * @param instanceName The {@link String} SQL Server instance name to connect. * @throws SQLException If there is an issue connecting to the database. */ private DBService(String username, String password, String instanceName) throws SQLException { // First instantiate the superclass, DBConnection. super(username, password, instanceName); user = username; role = getDBRole(); } /** overloaded getInstance is used to setup the static DBService instance and then return it. * @param username The {@link String} username to use to connect to the database. * @param password The {@link String} password to use to connect to the database. * @param instanceName The {@link String} SQL Server instance name to connect. * @return The static instance of {@link DBService} stored in the {@link DBService} class. * @throws SQLException If there is an issue connecting to the database. */ public static DBService getInstance(String username, String password, String instanceName) throws SQLException { if (instance == null) instance = new DBService(username, password, instanceName); return instance; } /** getInstance returns the static instance stored in this class. * @return A static instance of DBService. */ public static DBService getInstance() {return instance;} /** getUser returns the {@link String} username stored in this DBService. * @return The {@link String} user field. */ public String getUser() {return user;} /** getRole returns the {@link String} role stored in this DBService. * @return The {@link String} role field. */ public String getRole() {return role;} /** getDBRole returns the logged-in user's assigned role in the database as a {@link String}. * @return A {@link String} containing the logged-in user's role. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ private String getDBRole() throws SQLException { // Set up the SQL query. query = "SELECT DP1.name AS DatabaseRoleName, DP2.name AS DatabaseUserName " + "FROM sys.database_role_members AS DRM " + "RIGHT OUTER JOIN sys.database_principals AS DP1 " + "ON DRM.role_principal_id = DP1.principal_id " + "LEFT OUTER JOIN sys.database_principals AS DP2 " + "ON DRM.member_principal_id = DP2.principal_id " + "WHERE DP2.name = CURRENT_USER " + "ORDER BY DatabaseRoleName;"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("DatabaseRoleName"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getCustomerId fetches the customer ID associated with the passed-in customer name. * @param customerName The {@link String} name of the customer to search for in the database. * @return An int containing the customer's unique id; returns a negative value if the customer name was not found. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public int getCustomerId(String customerName) throws SQLException { // Set up the SQL query. query = "select customerId from customer where customerName ='" + customerName + "';"; // Fetch the results. connect(); executeQuery(query); int result = -1; if (rs.next()) result = rs.getInt("customerId"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getCustomerNames returns an {@link ArrayList} of {@link String} customer names stored in the database. * @return An {@link ArrayList} of {@link String} customer names. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<String> getCustomerNames() throws SQLException { // Set up the SQL query. query = "select customerName from customers order by customerName;"; // Fetch the results. connect(); executeQuery(query); ArrayList<String> result = new ArrayList<>(); while(rs.next()) result.add(rs.getString("customerName")); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getCustomerBusinessNames returns the list of business names associated with a customer name through * a list of CustomerAddress with showBusinessName explicitly set to true. * @param customerName The {@link String} name of the customer to search for in the database. * @return An {@link ArrayList} containing {@link CustomerAddress}es, set to only output the business name. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<CustomerAddress> getCustomerBusinessNames(String customerName) throws SQLException { // Set up the SQL query. query = "select ca.addressId, c.customerName, ca.businessName, ca.address1, ca.address2," + "ca.city, ca.county, ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax " + "from customerAddresses ca, customers c " + "where c.customerId = ca.customerId " + "and c.customerName = '" + customerName + "';"; // Fetch the results. connect(); executeQuery(query); ArrayList<CustomerAddress> result = new ArrayList<>(); while (rs.next()) { CustomerAddress address = new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ); address.setShowBusinessName(true); result.add(address); } // Clean up the connection. closeConnection(); // Return the result. return result; } /** getCustomerAddress returns a CustomerAddress containing the address details for the given int addressId. * @param addressId The int ID of the customer address to find. * @return A CustomerAddress containing the address details. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public CustomerAddress getCustomerAddress(int addressId) throws SQLException { // Set up the SQL query. query = "select ca.addressId, c.customerName, ca.businessName, ca.address1, ca.address2," + "ca.city, ca.county, ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax " + "from customerAddresses ca, customers c " + "where ca.addressId = " + addressId + " " + "and c.customerId = ca.customerId;"; // Fetch the results. connect(); executeQuery(query); CustomerAddress result = null; if (rs.next()) result = new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getCustomerAddresses returns an {@link ArrayList} of CustomerAddress instances containing the * details of each address associated with the specific customer name. * @param customerName The {@link String} name of the customer to search for in the database. * @return An {@link ArrayList} of type CustomerAddress. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<CustomerAddress> getCustomerAddresses(String customerName) throws SQLException { // Set up the SQL query. query = "select ca.addressId, c.customerName, ca.businessName, ca.address1, ca.address2," + "ca.city, ca.county, ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax " + "from customerAddresses ca, customers c " + "where c.customerName = '" + customerName + "' " + "and c.customerId = ca.customerId;"; // Fetch the results. connect(); executeQuery(query); ArrayList<CustomerAddress> result = new ArrayList<>(); while(rs.next()) result.add( new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ) ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getCustomerAddressPONumbers returns the list of PO numbers associated with the given CustomerAddress. * @param address The CustomerAddress to search for in the database. * @return An {@link ArrayList} of type {@link String} PO numbers. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<String> getCustomerAddressPONumbers(CustomerAddress address) throws SQLException { // Set up the SQL query. query = "select poNumber from purchaseOrders where addressId = '" + address.getAddressId() + "' order by poNumber;"; // Fetch the results. connect(); executeQuery(query); ArrayList<String> result = new ArrayList<>(); while(rs.next()) result.add(rs.getString("poNumber")); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getPurchaseOrderProduct returns the requested PurchaseOrderProduct whose id is the passed-in purchaseOrderProductId. * @param purchaseOrderProductId The purchaseOrderProductId of the PurchaseOrderProduct we wish to fetch. * @return A PurchaseOrderProduct containing the information for the specified purchaseOrderProductId. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public PurchaseOrderProduct getPurchaseOrderProduct(int purchaseOrderProductId) throws SQLException { // Set up the SQL query. query = "select pop.purchaseOrderProductId, pop.poNumber, p.productName, pc.categoryName, " + "pop.quantity, pop.orderDate, pop.deliverDate " + "from purchaseOrderProducts pop, products p, productCategories pc " + "where pop.purchaseOrderProductId = " + purchaseOrderProductId + " " + "and pc.categoryId = p.categoryId " + "and p.productId = pop.productId " + "and p.categoryId = pop.categoryId;"; // Fetch the results. connect(); executeQuery(query); PurchaseOrderProduct result = null; if (rs.next()) result = new PurchaseOrderProduct( rs.getInt("purchaseOrderProductId"), rs.getString("poNumber"), rs.getString("productName"), rs.getString("categoryName"), rs.getInt("quantity"), rs.getObject("orderDate", LocalDate.class), rs.getObject("deliverDate", LocalDate.class) ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getPurchaseOrderProducts returns the {@link ArrayList} of PurchaseOrderProducts associated with a * given PO number. * @param poNumber The {@link String} PO number to search for in the database. * @return An {@link ArrayList} of type PurchaseOrderProduct containing the list of products associated * with the purchase order. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<PurchaseOrderProduct> getPurchaseOrderProducts(String poNumber) throws SQLException { // Set up the SQL query. query = "select pop.purchaseOrderProductId, pop.poNumber, p.productName, pc.categoryName, " + "pop.quantity, pop.orderDate, pop.deliverDate " + "from purchaseOrderProducts pop, products p, productCategories pc " + "where pc.categoryId = p.categoryId " + "and p.productId = pop.productId " + "and p.categoryId = pop.categoryId " + "and pop.poNumber = '" + poNumber + "';"; // Fetch the results. connect(); executeQuery(query); ArrayList<PurchaseOrderProduct> result = new ArrayList<>(); while (rs.next()) result.add( new PurchaseOrderProduct( rs.getInt("purchaseOrderProductId"), rs.getString("poNumber"), rs.getString("productName"), rs.getString("categoryName"), rs.getInt("quantity"), rs.getObject("orderDate", LocalDate.class), rs.getObject("deliverDate", LocalDate.class) ) ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAStatusId returns the statusId associated with the passed-in status description. * @param description The description of the status for which we want the identifier. * @return A int containing the value of the statusId; returns a negative value if the status was not found. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public int getRMAStatusId(String description) throws SQLException { // Set up the SQL query. query = "select statusId from rmaStatuses where description ='" + description + "';"; // Fetch the results. connect(); executeQuery(query); int result = -1; if (rs.next()) result = rs.getInt("statusId"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAStatusDescription returns the description associated with an RMA statusId. * @param statusId The RMA status id int to look up in the database. * @return The {@link String} description. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAStatusDescription(int statusId) throws SQLException { // Set up the SQL query. query = "select description from rmaStatuses where statusId =" + statusId + ";"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("description"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAStatuses returns an {@link ArrayList} of type {@link String} containing the RMA status * descriptions in the database. * @return An {@link ArrayList} of type {@link String} containing the RMA status descriptions. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<String> getRMAStatuses() throws SQLException { // Set up the SQL query. query = "select description from rmaStatuses order by description;"; // Fetch the results. connect(); executeQuery(query); ArrayList<String> result = new ArrayList<>(); while (rs.next()) result.add(rs.getString("description")); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getReturnReasonCodes returns a {@link HashMap} containing types {@link String}, whose contents * are the return reason code initials and the associated description. * @return A {@link HashMap} containing types {@link String}, whose contents are * the return reason code initials and the associated description. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public HashMap<String, String> getReturnReasonCodes() throws SQLException { // Set up the SQL query. query = "select returnReasonCode, description from returnReasonCodes order by returnReasonCode;"; // Fetch the results. connect(); executeQuery(query); HashMap<String, String> result = new HashMap<>(); while (rs.next()) result.put( rs.getString("returnReasonCode"), rs.getString("description") ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getDispositionId returns the int identifier for the passed-in disposition {@link String} description. * @param disposition The {@link String} disposition description to search for in the database. * @return A int containing the value of the dispositionId; returns a negative value if the disposition was not found. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public int getDispositionId(String disposition) throws SQLException { // Set up the SQL query. query = "select dispositionId from dispositions where disposition ='" + disposition + "';"; // Fetch the results. connect(); executeQuery(query); int result = -1; if (rs.next()) result = rs.getInt("dispositionId"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getDispositions returns an {@link ArrayList} of type {@link String}, containing the list of available * disposition descriptions in the database. * @return An {@link ArrayList} of type {@link String}, containing the list of available disposition * descriptions in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<String> getDispositions() throws SQLException { // Set up the SQL query. query = "select disposition from dispositions order by disposition;"; // Fetch the results. connect(); executeQuery(query); ArrayList<String> result = new ArrayList<>(); while (rs.next()) result.add(rs.getString("disposition")); // Clean up the connection. closeConnection(); // Return the result. return result; } /** createRMA creates the initial RMA record in the database using the passed-in information. * @param statusDescription The {@link String} status description to use for this RMA. * @return The resulting {@link String} RMA ID for this request. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String createRMA(String statusDescription) throws SQLException { // First fetch the next RMA ID to use. query = "{call GetNextRMAId(?)}"; createCallableStatement(query); cStmt.registerOutParameter(1, Types.VARCHAR); cStmt.execute(); String rmaId = cStmt.getString(1); closeConnection(); // Next fetch the statusId to use. int statusId = getRMAStatusId(statusDescription); // Now execute the insert statement. query = "insert into rma" + "(rmaId, owner, lastModified, lastModifiedBy, statusId)" + "values" + "(?, ?, ?, ?, ?);"; connect(); createPreparedStatement(query); pStmt.setString(1, rmaId); pStmt.setString(2, getUser()); pStmt.setObject(3, LocalDateTime.now()); pStmt.setString(4, getUser()); pStmt.setInt(5, statusId); pStmt.executeUpdate(); closeConnection(); return rmaId; } /** getRMA fetches the details for the given {@link String} RMA ID and returns it as an RMAListViewModel. * @param rmaId The {@link String} ID of the RMA to fetch. * @return An RMAListViewModel containing the details of the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public RMAListViewModel getRMA(String rmaId) throws SQLException { // Set up the SQL query. query = "select r.rmaId, rs.description, rd.shipReplacementRepair, c.customerName, " + "ca.businessName, ca.addressId, ca.address1, ca.address2, ca.city, ca.county, " + "ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax, pop.purchaseOrderProductId, " + "pop.poNumber, p.productName, pc.categoryName, pop.quantity, pop.orderDate, pop.deliverDate, " + "rd.returnQuantity, rd.created " + "from rma r, rmaDetails rd, rmaStatuses rs, purchaseOrders po, purchaseOrderProducts pop, " + "products p, productCategories pc, customerAddresses ca, customers c " + "where r.rmaId = '" + rmaId + "' " + "and r.statusId = rs.statusId " + "and r.rmaId = rd.rmaId " + "and rd.poNumber = po.poNumber " + "and po.poNumber = pop.poNumber " + "and pop.productId = p.productId " + "and pop.categoryId = p.categoryId " + "and p.categoryId = pc.categoryId " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId;"; // Fetch the results. connect(); executeQuery(query); RMAListViewModel result = null; if (rs.next()) result = new RMAListViewModel( rs.getString("rmaId"), rs.getString("description"), rs.getBoolean("shipReplacementRepair"), rs.getString("customerName"), rs.getString("businessName"), new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ), new PurchaseOrderProduct( rs.getInt("purchaseOrderProductId"), rs.getString("poNumber"), rs.getString("productName"), rs.getString("categoryName"), rs.getInt("quantity"), rs.getObject("orderDate", LocalDate.class), rs.getObject("deliverDate", LocalDate.class) ), rs.getInt("returnQuantity"), false, // shouldDelete rs.getObject("created", LocalDateTime.class) ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAs fetches the list of open RMAs in the database. If the user is an engineer, * then the list of RMAs will be all those with an empty engineeringEvaluation in RMADetails. * In both cases, if a critical RMA exists (RMA that has not been modified for five or more days), * then the list will only show critical RMAs. * @return An {@link ArrayList} of RMAListViewModel containing the RMAs' details. * @throws SQLException If there is an issue connecting to the database. */ public ArrayList<RMAListViewModel> getRMAs() throws SQLException { // Create the result list for later use. ArrayList<RMAListViewModel> result = new ArrayList<>(); // First check if there are any critical RMAs. if (!getRole().equals("engineer")) query = "select r.rmaId, rs.description, rd.shipReplacementRepair, c.customerName, " + "ca.businessName, ca.addressId, ca.address1, ca.address2, ca.city, ca.county, " + "ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax, pop.purchaseOrderProductId, " + "pop.poNumber, p.productName, pc.categoryName, pop.quantity, pop.orderDate, pop.deliverDate, " + "rd.returnQuantity, rd.created " + "from rma r, rmaDetails rd, rmaStatuses rs, purchaseOrders po, purchaseOrderProducts pop, " + "products p, productCategories pc, customerAddresses ca, customers c " + "where rs.description != 'Closed' " + "and datediff(day, r.lastModified, ?) >= 5 " + "and rd.purchaseOrderProductId = pop.purchaseOrderProductId " + "and r.statusId = rs.statusId " + "and r.rmaId = rd.rmaId " + "and rd.poNumber = po.poNumber " + "and po.poNumber = pop.poNumber " + "and pop.productId = p.productId " + "and pop.categoryId = p.categoryId " + "and p.categoryId = pc.categoryId " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId " + "order by r.rmaId;"; else query = "select r.rmaId, rs.description, rd.shipReplacementRepair, c.customerName, " + "ca.businessName, ca.addressId, ca.address1, ca.address2, ca.city, ca.county, " + "ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax, pop.purchaseOrderProductId, " + "pop.poNumber, p.productName, pc.categoryName, pop.quantity, pop.orderDate, pop.deliverDate, " + "rd.returnQuantity, rd.created " + "from rma r, rmaDetails rd, rmaStatuses rs, purchaseOrders po, purchaseOrderProducts pop, " + "products p, productCategories pc, customerAddresses ca, customers c " + "where rs.description != 'Closed' " + "and datediff(day, r.lastModified, ?) >= 5 " + "and rd.purchaseOrderProductId = pop.purchaseOrderProductId " + "and rd.engineeringEvaluation = '' " + "and r.statusId = rs.statusId " + "and r.rmaId = rd.rmaId " + "and rd.poNumber = po.poNumber " + "and po.poNumber = pop.poNumber " + "and pop.productId = p.productId " + "and pop.categoryId = p.categoryId " + "and p.categoryId = pc.categoryId " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId " + "order by r.rmaId;"; connect(); createPreparedStatement(query); pStmt.setObject(1, LocalDateTime.now()); executePreparedStatementQuery(); if (rs.next()) { // We have critical RMAs to process. do { result.add( new RMAListViewModel( rs.getString("rmaId"), rs.getString("description"), rs.getBoolean("shipReplacementRepair"), rs.getString("customerName"), rs.getString("businessName"), new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ), new PurchaseOrderProduct( rs.getInt("purchaseOrderProductId"), rs.getString("poNumber"), rs.getString("productName"), rs.getString("categoryName"), rs.getInt("quantity"), rs.getObject("orderDate", LocalDate.class), rs.getObject("deliverDate", LocalDate.class) ), rs.getInt("returnQuantity"), false, // shouldDelete rs.getObject("created", LocalDateTime.class) ) ); } while (rs.next()); } else { // Check if we have non-critical RMAs to process. // Reset the connection and statements. closeConnection(); // Queries for non-critical RMAs. if (!getRole().equals("engineer")) query = "select r.rmaId, rs.description, rd.shipReplacementRepair, c.customerName, " + "ca.businessName, ca.addressId, ca.address1, ca.address2, ca.city, ca.county, " + "ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax, pop.purchaseOrderProductId, " + "pop.poNumber, p.productName, pc.categoryName, pop.quantity, pop.orderDate, pop.deliverDate, " + "rd.returnQuantity, rd.created " + "from rma r, rmaDetails rd, rmaStatuses rs, purchaseOrders po, purchaseOrderProducts pop, " + "products p, productCategories pc, customerAddresses ca, customers c " + "where rs.description != 'Closed' " + "and datediff(day, r.lastModified, ?) < 5 " + "and rd.purchaseOrderProductId = pop.purchaseOrderProductId " + "and r.statusId = rs.statusId " + "and r.rmaId = rd.rmaId " + "and rd.poNumber = po.poNumber " + "and po.poNumber = pop.poNumber " + "and pop.productId = p.productId " + "and pop.categoryId = p.categoryId " + "and p.categoryId = pc.categoryId " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId " + "order by r.rmaId;"; else query = "select r.rmaId, rs.description, rd.shipReplacementRepair, c.customerName, " + "ca.businessName, ca.addressId, ca.address1, ca.address2, ca.city, ca.county, " + "ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax, pop.purchaseOrderProductId, " + "pop.poNumber, p.productName, pc.categoryName, pop.quantity, pop.orderDate, pop.deliverDate, " + "rd.returnQuantity, rd.created " + "from rma r, rmaDetails rd, rmaStatuses rs, purchaseOrders po, purchaseOrderProducts pop, " + "products p, productCategories pc, customerAddresses ca, customers c " + "where rs.description != 'Closed' " + "and datediff(day, r.lastModified, ?) < 5 " + "and rd.purchaseOrderProductId = pop.purchaseOrderProductId " + "and rd.engineeringEvaluation = '' " + "and r.statusId = rs.statusId " + "and r.rmaId = rd.rmaId " + "and rd.poNumber = po.poNumber " + "and po.poNumber = pop.poNumber " + "and pop.productId = p.productId " + "and pop.categoryId = p.categoryId " + "and p.categoryId = pc.categoryId " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId " + "order by r.rmaId;"; connect(); createPreparedStatement(query); pStmt.setObject(1, LocalDateTime.now()); executePreparedStatementQuery(); if (rs.next()) // We have non-critical RMAs to process. do { result.add( new RMAListViewModel( rs.getString("rmaId"), rs.getString("description"), rs.getBoolean("shipReplacementRepair"), rs.getString("customerName"), rs.getString("businessName"), new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ), new PurchaseOrderProduct( rs.getInt("purchaseOrderProductId"), rs.getString("poNumber"), rs.getString("productName"), rs.getString("categoryName"), rs.getInt("quantity"), rs.getObject("orderDate", LocalDate.class), rs.getObject("deliverDate", LocalDate.class) ), rs.getInt("returnQuantity"), false, // shouldDelete rs.getObject("created", LocalDateTime.class) ) ); } while (rs.next()); } // Clean up connection. closeConnection(); // Return the RMAs. return result; } /** createRMADetails creates the rmaDetails record associated with the initial RMA record using the passed-in information. * @param rmaId The {@link String} ID of the RMA whose details we are creating. * @param returnReasonCode The {@link String} Return Reason Code we are assigning to this RMA. * @param creditReplaceRepair Whether we are deciding to credit, replace, or repair the returned items, saved as a {@link String}. * @param purchaseOrderProductId The unique int identifier of the product being returned by the customer. * @param returnQuantity The int amount of product being returned by the customer. * @param returnLabelTracker The {@link String} return label tracking number used to ship the product to us. * @param additionalInfo Any additional info needed to process the RMA, entered in by an Analyst. Stored as a {@link String}. * @param poNumber The {@link String} purchase order number being referenced in this RMA. * @param initialEvaluation The {@link String} initial evaluation by an Analyst of the product's condition and the RMA request. * @param engineeringEvaluation The {@link String} evaluation of the returned product by an Engineer. * @param disposition The {@link String} disposition to assign to the returned product by an Analyst. * @param dispositionNotes Any additional notes on the disposition written by an Analyst. Stored as a {@link String}. * @param replacementTrackingNumber The {@link String} tracking number for the replacement being sent back to the customer. * @param replacementShipDate The {@link LocalDate} date the replacement was or will be shipped back to the customer. * @param shipReplacementRepair A boolean indicating whether or not we will be shipping back a replacement or repair to the customer. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void createRMADetails ( String rmaId, String returnReasonCode, String creditReplaceRepair, int purchaseOrderProductId, int returnQuantity, String returnLabelTracker, String additionalInfo, String poNumber, String initialEvaluation, String engineeringEvaluation, String disposition, String dispositionNotes, String replacementTrackingNumber, LocalDate replacementShipDate, boolean shipReplacementRepair ) throws SQLException { // First setup the SQL query to fetch the dispositionId from the database. query = "select dispositionId from dispositions where disposition = '" + disposition + "';"; // Connect to the database and execute the query. connect(); executeQuery(query); Integer dispositionId = null; if (rs.next()) dispositionId = rs.getInt("dispositionId"); // Setup the SQL query to insert a new RMADetails record into the database. query = "insert into rmaDetails(" + "rmaId, created, createdBy, returnReasonCode, creditReplaceRepair, purchaseOrderProductId, returnQuantity," + "returnLabelTracker, additionalInfo, poNumber, initialEvaluation, engineeringEvaluation, dispositionId, " + "dispositionNotes, replacementTrackingNumber, replacementShipDate, shipReplacementRepair" + ") values (" + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" + ");"; // Create a new PreparedStatement and execute the query. createPreparedStatement(query); pStmt.setString(1, rmaId); pStmt.setObject(2, LocalDateTime.now()); pStmt.setString(3, getUser()); pStmt.setString(4, returnReasonCode); pStmt.setString(5, creditReplaceRepair); pStmt.setInt(6, purchaseOrderProductId); pStmt.setInt(7, returnQuantity); pStmt.setString(8, returnLabelTracker); pStmt.setString(9, additionalInfo); pStmt.setString(10, poNumber); pStmt.setString(11, initialEvaluation); pStmt.setString(12, engineeringEvaluation); if (dispositionId != null) pStmt.setInt(13, dispositionId); else pStmt.setNull(13, Types.INTEGER); pStmt.setString(14, dispositionNotes); pStmt.setString(15, replacementTrackingNumber); pStmt.setObject(16, replacementShipDate); pStmt.setBoolean(17, shipReplacementRepair); pStmt.executeUpdate(); closeConnection(); } /** getRMACustomerName returns the customer name associated with an RMA ID, through its PO number and the PO number's * associated address ID. * @param rmaId The RMA whose customer name we wish to look up. * @return A {@link String} containing the name of the customer associated with the PO and address in the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMACustomerName(String rmaId) throws SQLException { // Set up the SQL query. query = "select c.customerName " + "from customers c, customerAddresses ca, purchaseOrders po, rmaDetails rd " + "where rd.rmaId ='" + rmaId + "' " + "and rd.poNumber = po.poNumber " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId;"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("customerName"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMABusinessName returns a {@link CustomerAddress} set to show the business name associated with the RMA whose * ID we are searching, through its PO number and the PO number's associated address ID. * @param rmaId The RMA whose business name we wish to look up. * @return A {@link CustomerAddress} set to show the name of the business associated with the PO and address in the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public CustomerAddress getRMABusinessName(String rmaId) throws SQLException { // Set up the SQL query. query = "select ca.addressId, c.customerName, ca.businessName, ca.address1, ca.address2, " + "ca.city, ca.county, ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax " + "from rmaDetails rd, purchaseOrders PO, customerAddresses ca, customers c " + "where rd.rmaId = '" + rmaId + "' " + "and rd.poNumber = po.poNumber " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId;"; // Fetch the results. connect(); executeQuery(query); CustomerAddress result = null; if (rs.next()) { result = new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ); result.setShowBusinessName(true); } // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAPONumber returns the PO number associated with the given {@link String} RMA ID. * @param rmaId The RMA whose PO number we wish to look up. * @return A {@link String} containing the PO number associated with the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAPONumber(String rmaId) throws SQLException { // Set up the SQL query. query = "select poNumber from rmaDetails where rmaId ='" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("poNumber"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAAddress returns the address information associated with the {@link String} RMA ID's PO number in a CustomerAddress. * @param rmaId The RMA whose address information we wish to look up. * @return A CustomerAddress containing all the address information associated with the RMA's PO number. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public CustomerAddress getRMAAddress(String rmaId) throws SQLException { // Set up the SQL query. query = "select ca.addressId, c.customerName, ca.businessName, ca.address1, ca.address2, " + "ca.city, ca.county, ca.stateOrProvince, ca.zip, ca.country, ca.phone, ca.fax " + "from rmaDetails rd, purchaseOrders PO, customerAddresses ca, customers c " + "where rd.rmaId = '" + rmaId + "' " + "and rd.poNumber = po.poNumber " + "and po.addressId = ca.addressId " + "and ca.customerId = c.customerId;"; // Fetch the results. connect(); executeQuery(query); CustomerAddress result = null; if (rs.next()) result = new CustomerAddress( rs.getInt("addressId"), rs.getString("customerName"), rs.getString("businessName"), rs.getString("address1"), rs.getString("address2"), rs.getString("city"), rs.getString("county"), rs.getString("stateOrProvince"), rs.getString("zip"), rs.getString("country"), rs.getString("phone"), rs.getString("fax") ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getOwners returns an {@link ArrayList} of usernames stored in the database. * @return An {@link ArrayList} of type {@link String} containing the list of usernames in the RMA database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public ArrayList<String> getOwners() throws SQLException { // Set up the SQL query. query = "select name " + "from sys.database_principals " + "where type not in ('A', 'G', 'R', 'X') " + "and sid is not null " + "and name not in ('guest', 'dbo') " + "order by name;"; // Fetch the results. connect(); executeQuery(query); ArrayList<String> result = new ArrayList<>(); while (rs.next()) result.add(rs.getString("name")); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAOwner returns the {@link String} username of the owner stored in the database for the specified {@link String} RMA ID. * @param rmaId The {@link String} whose owner we wish to fetch. * @return A {@link String} containing the name of the current owner. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAOwner(String rmaId) throws SQLException { // Set up the SQL query. query = "select owner from [rma] where rmaId ='" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("owner"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAOwner updates the RMA owner in the database for the given RMA ID with the passed-in username. * @param rmaId The {@link String} ID of the RMA to update. * @param newOwner The {@link String} new owner name to associate with the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAOwner(String rmaId, String newOwner) throws SQLException { // Setup the SQL query to update the database. query = "update rma " + "set owner = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, newOwner); pStmt.executeUpdate(); closeConnection(); } /** getRMALastModified fetches the {@link LocalDateTime} datetime stored in the database for the given {@link String} RMA ID. * @param rmaId The {@link String} ID of the RMA whose last modified datetime we wish to fetch. * @return A {@link LocalDateTime} containing the date and time of the last time the RMA was modified. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public LocalDateTime getRMALastModified(String rmaId) throws SQLException { // Set up the SQL query. query = "select lastModified from rma where rmaId ='" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); LocalDateTime result = null; if (rs.next()) result = rs.getObject("lastModified", LocalDateTime.class); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMALastModified updates the {@link LocalDateTime} date and time of the RMA's lastModified column to now. * @param rmaId The {@link String} ID of the RMA to update. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMALastModified(String rmaId) throws SQLException { // Setup the SQL query to update the database. query = "update rma " + "set lastModified = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setObject(1, LocalDateTime.now()); pStmt.executeUpdate(); closeConnection(); } /** getRMALastModifiedBy returns the {@link String} username of the user that last modified the RMA with the given {@link String} ID. * @param rmaId The {@link String} ID of the RMA whose last modified username we wish to fetch. * @return A {@link String} containing the username that last modified the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMALastModifiedBy(String rmaId) throws SQLException { // Set up the SQL query. query = "select lastModifiedBy from rma where rmaId ='" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("lastModifiedBy"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMALastModifiedBy updates the {@link String} username in the lastModifiedBy column of the RMA with the given ID to * the current logged-in user. * @param rmaId The {@link String} ID of the RMA to update. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMALastModifiedBy(String rmaId) throws SQLException { // Setup the SQL query to update the database. query = "update rma " + "set lastModifiedBy = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, getUser()); pStmt.executeUpdate(); closeConnection(); } /** getRMAStatus returns the {@link String} status description stored in the database for the given {@link String} RMA ID. * @param rmaId The {@link String} ID of the RMA whose status description we wish to fetch. * @return A {@link String} containing the RMA's status description. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAStatus(String rmaId) throws SQLException { // Set up the SQL query. query = "select rs.description " + "from rma r, rmaStatuses rs " + "where r.rmaId = '" + rmaId + "' " + "and r.statusId = rs.statusId;"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("description"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAStatus updates the status assigned to the RMA with the given {@link String} ID to the passed-in * {@link String} description. * @param rmaId The {@link String} ID of the RMA to update. * @param description The {@link String} status description whose identifier we want to use to update the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAStatus(String rmaId, String description) throws SQLException { // Setup the SQL query to update the database. query = "update rma " + "set statusId = (select statusId from rmaStatuses where description = ?) " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, description); pStmt.executeUpdate(); closeConnection(); } /** getRMACreditReplaceRepair returns the current value (credit, replace, or repair) stored in the database for the * given {@link String} RMA ID. * @param rmaId The {@link String} ID of the RMA whose creditReplaceRepair value we wish to fetch. * @return A {@link String} containing the RMA's creditReplaceRepair value. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMACreditReplaceRepair(String rmaId) throws SQLException { // Set up the SQL query. query = "select creditReplaceRepair from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("creditReplaceRepair"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMACreditReplaceRepair updates the specified RMA with the passed-in credit, replace, or repair value. * @param rmaId The {@link String} ID of the RMA whose details we want to update. * @param creditReplaceRepair The {@link String} new value of credit, replace, or repair that we want to save in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMACreditReplaceRepair(String rmaId, String creditReplaceRepair) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set creditReplaceRepair = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, creditReplaceRepair); pStmt.executeUpdate(); closeConnection(); } /** getRMAReturnReasonCode returns the current return reason code and its description associated with the given * {@link String} RMA ID. * @param rmaId The {@link String} ID of the RMA whose return reason code description we wish to fetch. * @return A {@link String} containing the return reason code and its description, separated by a space, and * associated with the given RMA ID. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAReturnReasonCode(String rmaId) throws SQLException { // Set up the SQL query. query = "select rrc.returnReasonCode, rrc.description " + "from rmaDetails rd, returnReasonCodes rrc " + "where rd.rmaId = '" + rmaId + "' " + "and rd.returnReasonCode = rrc.returnReasonCode;"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("returnReasonCode") + " " + rs.getString("description"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAReturnReasonCode updates the specified RMA with the passed-in returnReasonCodeDescription ("Code Description"). * @param rmaId The {@link String} ID of the RMA whose details we want to update. * @param returnReasonCodeDescription The {@link String} ("Code Description") for the return reason code we want to use in RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAReturnReasonCode(String rmaId, String returnReasonCodeDescription) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set returnReasonCode = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, returnReasonCodeDescription); pStmt.executeUpdate(); closeConnection(); } /** getRMAAdditionalInfo returns a {@link String} containing the additional info notes stored in the RMA Details for * the given {@link String} RMA ID. * @param rmaId The {@link String} ID of the RMA whose return additional info notes we wish to fetch. * @return A {@link String} containing the additional info notes associated with the given RMA ID. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAAdditionalInfo(String rmaId) throws SQLException { // Set up the SQL query. query = "select additionalInfo from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("additionalInfo"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAAdditionalInfo updates the requested RMA's details with the given {@link String} ID with the updated * information passed-in through the {@link String }additionalInfo parameter. * @param rmaId The {@link String} ID of the RMA to update. * @param additionalInfo The updated {@link String} Additional Info value to store in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAAdditionalInfo(String rmaId, String additionalInfo) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set additionalInfo = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, additionalInfo); pStmt.executeUpdate(); closeConnection(); } /** getRMACreated returns a {@link LocalDateTime} object containing the creation date and time of the given RMA. * @param rmaId The {@link String} ID of the RMA whose created datetime we wish to fetch. * @return A {@link LocalDateTime} containing the creation date and time of the given RMA ID. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public LocalDateTime getRMACreated(String rmaId) throws SQLException { // Set up the SQL query. query = "select created from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); LocalDateTime result = null; if (rs.next()) result = rs.getObject("created", LocalDateTime.class); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMACreatedBy returns a {@link String} containing the username that created the given RMA request. * @param rmaId The {@link String} ID of the RMA whose created username we wish to fetch. * @return A {@link String} containing the username that created the RMA request. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMACreatedBy(String rmaId) throws SQLException { // Set up the SQL query. query = "select createdBy from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("createdBy"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** getRMAProduct returns a PurchaseOrderProduct containing the details of the product that is being returned * in the given RMA. * @param rmaId The {@link String} ID of the RMA whose created username we wish to fetch. * @return A PurchaseOrderProduct containing the purchase order product information of the item being returned * in the requested RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public PurchaseOrderProduct getRMAProduct(String rmaId) throws SQLException { // Set up the SQL query. query = "select pop.purchaseOrderProductId, pop.poNumber, p.productName, pc.categoryName, pop.quantity, " + "pop.orderDate, pop.deliverDate " + "from rmaDetails rd, purchaseOrderProducts pop, products p, productCategories pc " + "where rd.rmaId = '" + rmaId + "' " + "and rd.purchaseOrderProductId = pop.purchaseOrderProductId " + "and pop.categoryId = p.categoryId " + "and pop.productId = p.productId " + "and p.categoryId = pc.categoryId;"; // Fetch the results. connect(); executeQuery(query); PurchaseOrderProduct result = null; if (rs.next()) result = new PurchaseOrderProduct( rs.getInt("purchaseOrderProductId"), rs.getString("poNumber"), rs.getString("productName"), rs.getString("categoryName"), rs.getInt("quantity"), rs.getObject("orderDate", LocalDate.class), rs.getObject("deliverDate", LocalDate.class) ); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAProduct updates the product being returned in the RMA with the passed-in int id. * @param rmaId The {@link String} ID of the RMA to update. * @param purchaseOrderProductId The new unique int value to set for the new product. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAProduct(String rmaId, int purchaseOrderProductId) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set purchaseOrderProductId = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setInt(1, purchaseOrderProductId); pStmt.executeUpdate(); closeConnection(); } /** getRMAReturnQuantity fetches the int number of products being returned by the customer for the given {@link String} * RMA ID. * @param rmaId The {@link String} ID of the RMA whose return quantity we wish to fetch. * @return An int containing the return quantity for the item in the given RMA. Returns a negative value if the * return quantity is not found. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public int getRMAReturnQuantity(String rmaId) throws SQLException { // Set up the SQL query. query = "select returnQuantity from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); int result = -1; if (rs.next()) result = rs.getInt("returnQuantity"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAReturnQuantity updates the int value for the amount of product being returned by the customer * for the given {@link String} RMA ID. * @param rmaId The {@link String} ID of the RMA to update. * @param returnQuantity The new int value to set for the product in the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAReturnQuantity(String rmaId, int returnQuantity) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set returnQuantity = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setInt(1, returnQuantity); pStmt.executeUpdate(); closeConnection(); } /** getRMAReturnLabelTracker fetches the {@link String} return label tracking number stored in the referenced RMA. * @param rmaId The {@link String} ID of the RMA whose return label tracking number we wish to fetch. * @return A {@link String} containing the return label tracking number for the item in the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAReturnLabelTracker(String rmaId) throws SQLException { // Set up the SQL query. query = "select returnLabelTracker from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("returnLabelTracker"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAReturnLabelTracker updates the requested RMA's details with the new passed-in {@link String} return label tracking ID. * @param rmaId The {@link String} ID of the RMA to update. * @param returnLabelTracker The new tracking ID to assign to the RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAReturnLabelTracker(String rmaId, String returnLabelTracker) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set returnLabelTracker = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, returnLabelTracker); pStmt.executeUpdate(); closeConnection(); } /** getRMAInitialEvaluation fetches the {@link String} initial evaluation done by an Analyst for the requested RMA. * @param rmaId The {@link String} ID of the RMA whose initial evaluation we wish to fetch. * @return A {@link String} containing the initial evaluation of the returned product for the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAInitialEvaluation(String rmaId) throws SQLException { // Set up the SQL query. query = "select initialEvaluation from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("initialEvaluation"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAInitialEvaluation updates the requested RMA's initial evaluation from an Analyst with the new * {@link String} passed-in initial evaluation text. * @param rmaId The {@link String} ID of the RMA to update. * @param initialEvaluation The updated {@link String} Initial Evaluation value to store in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAInitialEvaluation(String rmaId, String initialEvaluation) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set initialEvaluation = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, initialEvaluation); pStmt.executeUpdate(); closeConnection(); } /** getRMAEngineeringEvaluation fetches the {@link String} engineering evaluation done by an Engineer for the requested RMA. * @param rmaId The {@link String} ID of the RMA whose engineering evaluation we wish to fetch. * @return A {@link String} containing the engineering evaluation of the returned product for the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAEngineeringEvaluation(String rmaId) throws SQLException { // Set up the SQL query. query = "select engineeringEvaluation from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("engineeringEvaluation"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAEngineeringEvaluation updates the requested RMA's engineering evaluation from an Engineer with the new {@link String} * passed-in engineering evaluation text. * @param rmaId The {@link String} ID of the RMA to update. * @param engineeringEvaluation The new {@link String} engineering evaluation to save in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAEngineeringEvaluation(String rmaId, String engineeringEvaluation) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set engineeringEvaluation = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, engineeringEvaluation); pStmt.executeUpdate(); closeConnection(); } /** getRMADisposition fetches the {@link String} disposition for the requested RMA. * @param rmaId The {@link String} ID of the RMA whose disposition we wish to fetch. * @return A {@link String} containing the disposition of the returned product for the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMADisposition(String rmaId) throws SQLException { // Set up the SQL query. query = "select d.disposition " + "from rmaDetails rd, dispositions d " + "where rd.rmaId = '" + rmaId + "' " + "and rd.dispositionId = d.dispositionId;"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("disposition"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMADisposition updates the disposition ID stored in the specified RMA using the passed-in {@link String} disposition. * @param rmaId The {@link String} ID of the RMA to update. * @param disposition The {@link String} disposition description to look up and then use to update. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMADisposition(String rmaId, String disposition) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set dispositionId = (select dispositionId from dispositions where disposition = ?) " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, disposition); pStmt.executeUpdate(); closeConnection(); } /** getRMADispositionNotes fetches the {@link String} disposition notes for the requested RMA. * @param rmaId The {@link String} ID of the RMA whose disposition notes we wish to fetch. * @return A {@link String} containing the disposition notes for the returned product in the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMADispositionNotes(String rmaId) throws SQLException { // Set up the SQL query. query = "select dispositionNotes from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("dispositionNotes"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMADispositionNotes updates the disposition notes stored in the specified RMA using the passed-in {@link String} notes. * @param rmaId The {@link String} ID of the RMA to update. * @param dispositionNotes The new {@link String} dispositionNotes to save to the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMADispositionNotes(String rmaId, String dispositionNotes) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set dispositionNotes = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, dispositionNotes); pStmt.executeUpdate(); closeConnection(); } /** getRMAReplacementTrackingNumber fetches the {@link String} tracking number that will be used to ship the replacement * back to the customer in the requested RMA. * @param rmaId The {@link String} ID of the RMA whose replacement tracking number we wish to fetch. * @return A {@link String} containing the replacement tracking number for the replacement or repair for the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public String getRMAReplacementTrackingNumber(String rmaId) throws SQLException { // Set up the SQL query. query = "select replacementTrackingNumber from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); String result = ""; if (rs.next()) result = rs.getString("replacementTrackingNumber"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAReplacementTrackingNumber updates the specified RMA's tracking number used to ship the replacement product. * @param rmaId The {@link String} ID of the RMA to update. * @param replacementTrackingNumber The {@link String} new replacement tracking number to store in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAReplacementTrackingNumber(String rmaId, String replacementTrackingNumber) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set replacementTrackingNumber = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setString(1, replacementTrackingNumber); pStmt.executeUpdate(); closeConnection(); } /** getRMAReplacementShipDate fetches the {@link LocalDate} of the date that the replacement will be shipped to the customer * for the given RMA. * @param rmaId The {@link String} ID of the RMA whose replacement ship date we wish to fetch. * @return A {@link LocalDate} containing the replacement ship date of the replacement or repair for the given RMA. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public LocalDate getRMAReplacementShipDate(String rmaId) throws SQLException { // Set up the SQL query. query = "select replacementShipDate from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); LocalDate result = null; if (rs.next()) result = rs.getObject("replacementShipDate", LocalDate.class); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAReplacementShipDate updates the {@link LocalDate} date with the passed-in date the replacement will be shipped to * the customer in the RMA with the specified {@link String} ID. * @param rmaId The {@link String} ID of the RMA to update. * @param replacementShipDate The new {@link LocalDate} date to store in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAReplacementShipDate(String rmaId, LocalDate replacementShipDate) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set replacementShipDate = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setObject(1, replacementShipDate); pStmt.executeUpdate(); closeConnection(); } /** getRMAShipReplacementRepair fetches the boolean value of whether we will be shipping a replacement or repair to * the customer referenced in the RMA with the given {@link String} ID. * @param rmaId The {@link String} ID of the RMA to update. * @return A boolean containing the shipReplacementRepair value. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public boolean getRMAShipReplacementRepair(String rmaId) throws SQLException { // Set up the SQL query. query = "select shipReplacementRepair from rmaDetails where rmaId = '" + rmaId + "';"; // Fetch the results. connect(); executeQuery(query); boolean result = false; if (rs.next()) result = rs.getBoolean("shipReplacementRepair"); // Clean up the connection. closeConnection(); // Return the result. return result; } /** updateRMAShipReplacementRepair updates the RMA with the given {@link String} ID with the new shipReplacementRepair * boolean value. * @param rmaId The {@link String} ID of the RMA to update. * @param shipReplacementRepair The new boolean value to store in the database. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void updateRMAShipReplacementRepair(String rmaId, boolean shipReplacementRepair) throws SQLException { // Setup the SQL query to update the database. query = "update rmaDetails " + "set shipReplacementRepair = ? " + "where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(2, rmaId); pStmt.setBoolean(1, shipReplacementRepair); pStmt.executeUpdate(); closeConnection(); } /** deleteRMA deletes the RMA with the given {@link String} ID. * @param rmaId The {@link String} ID of the RMA to delete. * @throws SQLException If there is an issue connecting to the database or an issue with the SQL query. */ public void deleteRMA(String rmaId) throws SQLException { // Setup the SQL query to update the database. query = "delete from rma where rmaId = ?;"; // Connect to the database and execute the query. connect(); createPreparedStatement(query); pStmt.setString(1, rmaId); pStmt.executeUpdate(); closeConnection(); } }
package com.csalazar.materialdesign.activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import com.csalazar.materialdesign.R; public class ListViewActivity extends AppCompatActivity { private ListView lv_lista; private ImageView ivLista; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); initComponents(); } private void initComponents(){ ivLista = (ImageView) findViewById(R.id.iv_list); lv_lista = (ListView) findViewById(R.id.lv_list); String[] listado = getResources().getStringArray(R.array.selected_options); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listado); lv_lista.setAdapter(adapter); lv_lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { switch (position){ case 0: ivLista.setImageResource(R.drawable.atm); break; case 1: ivLista.setImageResource(R.drawable.bag); break; case 2: ivLista.setImageResource(R.drawable.basket); break; case 3: ivLista.setImageResource(R.drawable.box); break; case 4: ivLista.setImageResource(R.drawable.briefcase); break; case 5: ivLista.setImageResource(R.drawable.calculator); break; } } }); } }
package com.edasaki.rpg.spells; import java.util.HashMap; import java.util.Set; import java.util.UUID; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerAnimationEvent; import org.bukkit.event.player.PlayerAnimationType; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.inventory.ItemStack; import com.edasaki.core.utils.RMessages; import com.edasaki.core.utils.RScheduler; import com.edasaki.core.utils.RTicks; import com.edasaki.rpg.AbstractManagerRPG; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.SakiRPG; import com.edasaki.rpg.classes.ClassType; import com.edasaki.rpg.items.EquipType; public class SpellManager extends AbstractManagerRPG { public static HashMap<UUID, Caster> casters = new HashMap<UUID, Caster>(); private static HashMap<UUID, Long> lastPress = new HashMap<UUID, Long>(); public static boolean isCasting(Player p) { if (!casters.containsKey(p.getUniqueId())) return false; Caster caster = casters.get(p.getUniqueId()); return caster.state != CastState.NONE; } public SpellManager(SakiRPG plugin) { super(plugin); } @Override public void initialize() { Spell.plugin = plugin; } public enum CastState { NONE(""), R("Right"), RL("Right-Left"), RLR("Right-Left-Right"), RLL("Right-Left-Left"), RR("Right-Right"), RRL("Right-Right-Left"), RRR("Right-Right-Right"); public String string; @Override public String toString() { return string; } CastState(String s) { this.string = s; } }; public static class Caster { public CastState state = CastState.NONE; public int pressCount = 0; public void press(boolean left) { pressCount++; final int lastPressCount = pressCount; RScheduler.schedule(plugin, new Runnable() { public void run() { if (lastPressCount != pressCount) return; clear(); } }, RTicks.seconds(1)); switch (state) { case NONE: if (!left) state = CastState.R; break; case R: if (left) state = CastState.RL; else state = CastState.RR; break; case RL: if (left) state = CastState.RLL; else state = CastState.RLR; break; case RR: if (left) state = CastState.RRL; else state = CastState.RRR; break; case RLL: case RLR: case RRL: case RRR: state = CastState.NONE; break; default: break; } } public void clear() { state = CastState.NONE; } } @EventHandler public void onSneakEvent(PlayerToggleSneakEvent event) { Player p = event.getPlayer(); if (!casters.containsKey(p.getUniqueId())) casters.put(p.getUniqueId(), new Caster()); final Caster c = casters.get(p.getUniqueId()); PlayerDataRPG pd = plugin.getPD(p); if (pd != null) pd.updateHealthManaDisplay(); c.clear(); } public static boolean isSpellWeapon(ItemStack item) { if (item == null || item.getType() == null) return false; return EquipType.isWeapon(item); // every weapon is a spell weapon :^) } public static boolean validateWeapon(PlayerDataRPG pd, ClassType classType, ItemStack item) { if (item == null || classType == null) return false; boolean rightWep = false; String className = null, weapon = null; switch (classType) { case VILLAGER: rightWep = true; break; case CRUSADER: if (EquipType.SWORD.isType(item)) rightWep = true; className = "a Crusader"; weapon = "a Sword"; break; case PALADIN: if (EquipType.MACE.isType(item)) rightWep = true; className = "a Paladin"; weapon = "a Mace"; break; case ASSASSIN: if (EquipType.DAGGER.isType(item)) rightWep = true; className = "an Assassin"; weapon = "a Dagger"; break; case ALCHEMIST: if (EquipType.ELIXIR.isType(item)) rightWep = true; className = "an Alchemist"; weapon = "an Elixir"; break; case REAPER: if (EquipType.SCYTHE.isType(item)) rightWep = true; className = "a Reaper"; weapon = "a Scythe"; break; case ARCHER: if (EquipType.BOW.isType(item)) rightWep = true; className = "an Archer"; weapon = "a Bow"; break; case WIZARD: if (EquipType.WAND.isType(item)) rightWep = true; className = "a Wizard"; weapon = "a Wand"; break; } if (!rightWep) { pd.sendMessage(ChatColor.GRAY + "> " + ChatColor.RED + "You are " + className + " and can only cast spells with " + weapon + "!"); } return rightWep; } private void click(Player p, boolean left) { if (p.isGliding()) return; if (!casters.containsKey(p.getUniqueId())) casters.put(p.getUniqueId(), new Caster()); PlayerDataRPG pd = plugin.getPD(p); ItemStack item = p.getEquipment().getItemInMainHand(); boolean spellWep = false; if (item != null) spellWep = isSpellWeapon(item); if (pd != null) { if (lastPress.containsKey(p.getUniqueId())) { if (System.currentTimeMillis() - lastPress.get(p.getUniqueId()) < 50) return; } lastPress.put(p.getUniqueId(), System.currentTimeMillis()); final Caster c = casters.get(p.getUniqueId()); if (spellWep) { c.press(left); } else { c.clear(); } checkState(p, pd, c); } } @EventHandler public void onSpellClicksonDamage(EntityDamageByEntityEvent event) { if (event.getDamager() instanceof Player) { Player p = (Player) event.getDamager(); click(p, true); // damage is always left } } @EventHandler public void onSpellClicksOnEntity(PlayerInteractEntityEvent event) { Player p = event.getPlayer(); click(p, false); // interact is always right } @EventHandler public void event(PlayerAnimationEvent event) { Block focused = event.getPlayer().getTargetBlock((Set<Material>) null, 5); if (event.getAnimationType() == PlayerAnimationType.ARM_SWING && focused.getType() != Material.AIR && event.getPlayer().getGameMode() == GameMode.ADVENTURE) { click(event.getPlayer(), true); // anim is left swing } } @EventHandler public void onSpellClicks(PlayerInteractEvent event) { Player p = event.getPlayer(); if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) click(p, true); else if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) click(p, false); } public void checkState(Player p, PlayerDataRPG pd, Caster c) { pd.updateHealthManaDisplay(); ItemStack item = p.getEquipment().getItemInMainHand(); if (c.state == CastState.RLL) { if (item == null || !validateWeapon(pd, pd.classType, item)) return; if (pd.spell_RLL != null) { pd.spell_RLL.cast(p, pd); } else { p.sendMessage(ChatColor.RED + "You don't have any spell bound to the " + ChatColor.GOLD + "RLL" + ChatColor.RED + " spellcast!"); p.sendMessage(ChatColor.RED + "You can bind a spell to the " + ChatColor.GOLD + "RLL" + ChatColor.RED + " spellcast using " + ChatColor.YELLOW + "/spell" + ChatColor.RED + "!"); } RScheduler.schedule(plugin, new Runnable() { public void run() { if (c.state == CastState.RLL) { c.clear(); RMessages.sendActionBar(p, ChatColor.RESET + ""); } } }, RTicks.seconds(0.2)); } else if (c.state == CastState.RLR) { if (item == null || !validateWeapon(pd, pd.classType, item)) return; if (pd.spell_RLR != null) { pd.spell_RLR.cast(p, pd); } else { p.sendMessage(ChatColor.RED + "You don't have any spell bound to the " + ChatColor.GOLD + "RLR" + ChatColor.RED + " spellcast!"); p.sendMessage(ChatColor.RED + "You can bind a spell to the " + ChatColor.GOLD + "RLR" + ChatColor.RED + " spellcast using " + ChatColor.YELLOW + "/spell" + ChatColor.RED + "!"); } RScheduler.schedule(plugin, new Runnable() { public void run() { if (c.state == CastState.RLR) { c.clear(); RMessages.sendActionBar(p, ChatColor.RESET + ""); } } }, RTicks.seconds(0.2)); } else if (c.state == CastState.RRL) { if (item == null || !validateWeapon(pd, pd.classType, item)) return; if (pd.spell_RRL != null) { pd.spell_RRL.cast(p, pd); } else { p.sendMessage(ChatColor.RED + "You don't have any spell bound to the " + ChatColor.GOLD + "RRL" + ChatColor.RED + " spellcast!"); p.sendMessage(ChatColor.RED + "You can bind a spell to the " + ChatColor.GOLD + "RRL" + ChatColor.RED + " spellcast using " + ChatColor.YELLOW + "/spell" + ChatColor.RED + "!"); } RScheduler.schedule(plugin, new Runnable() { public void run() { if (c.state == CastState.RRL) { c.clear(); RMessages.sendActionBar(p, ChatColor.RESET + ""); } } }, RTicks.seconds(0.2)); } else if (c.state == CastState.RRR) { if (item == null || !validateWeapon(pd, pd.classType, item)) return; if (pd.spell_RRR != null) { pd.spell_RRR.cast(p, pd); } else { p.sendMessage(ChatColor.RED + "You don't have any spell bound to the " + ChatColor.GOLD + "RRR" + ChatColor.RED + " spellcast!"); p.sendMessage(ChatColor.RED + "You can bind a spell to the " + ChatColor.GOLD + "RRR" + ChatColor.RED + " spellcast using " + ChatColor.YELLOW + "/spell" + ChatColor.RED + "!"); } RScheduler.schedule(plugin, new Runnable() { public void run() { if (c.state == CastState.RRR) { c.clear(); RMessages.sendActionBar(p, ChatColor.RESET + ""); } } }, RTicks.seconds(0.2)); } pd.updateHealthManaDisplay(); } }
package com.kh.portfolio.board.svc; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.kh.portfolio.board.dao.BoardDAO; import com.kh.portfolio.board.dao.NoticeDAO; import com.kh.portfolio.board.vo.BoardCategoryVO; import com.kh.portfolio.board.vo.BoardFileVO; import com.kh.portfolio.board.vo.BoardVO; import com.kh.portfolio.board.vo.NoticeVO; import com.kh.portfolio.common.FindCriteria; import com.kh.portfolio.common.PageCriteria; import com.kh.portfolio.common.RecordCriteria; @Service public class NoticeSVCImpl implements NoticeSVC { public static final Logger logger = LoggerFactory.getLogger(NoticeSVCImpl.class); @Inject NoticeDAO noticeDAO; //게시글작성 @Transactional @Override public int noticeWrite(NoticeVO noticeVO) { //1) 게시글 작성 int cnt = noticeDAO.noticeWrite(noticeVO); //2) bnum 가져오기 => mybatis: selectkey 사용 //3) 첨부파일 있는경우 // logger.info("첨부갯수:"+boardVO.getFiles().size()); // if(boardVO.getFiles() != null && boardVO.getFiles().size() > 0) { // fileWrite(boardVO.getFiles(),boardVO.getBnum()); // } return cnt; } //게시글수정 @Transactional @Override public int noticeModify(NoticeVO noticeVO) { //1) 게시글 수정 int cnt = noticeDAO.noticeModify(noticeVO); //2) 첨부파일 추가 // if(boardVO.getFiles() != null && boardVO.getFiles().size() > 0) { // fileWrite(boardVO.getFiles(),boardVO.getBnum()); // } return cnt; } //게시글삭제 @Transactional @Override public int noticeDelete(String nnum) { int cnt = 0; cnt = noticeDAO.noticeDelete(nnum); return cnt; } //게시글보기 @Transactional @Override public Map<String,Object> noticeView(String nnum) { //1) 게시글 가져오기 NoticeVO noticeVO = noticeDAO.noticeView(nnum); //2) 첨부파일 가져오기 // List<BoardFileVO> files = boardDAO.fileViews(bnum); //3) 조회수 +1증가 noticeDAO.noticeUpdateHit(nnum); Map<String,Object> map = new HashMap<>(); map.put("notice", noticeVO); // if(files != null && files.size() > 0) { // map.put("files", files); // } return map; } @Override public List<NoticeVO> noticeMain() { return noticeDAO.noticeList(); } //게시글목록 //1)전체 @Override public List<NoticeVO> noticeList() { return noticeDAO.noticeList(); } //2)검색어 없는 게시글페이징 @Override public List<NoticeVO> noticeList(int startRec, int endRec) { // TODO Auto-generated method stub return null; } //3)검색어 있는 게시글검색(요청페이지,검색유형,검색어) @Override public List<NoticeVO> noticeList(String reqPage, String searchType, String keyword) { int l_reqPage = 0; //요청 페이지 정보가 없으면 1로 초기화 if(reqPage == null || reqPage.trim().isEmpty()) { l_reqPage = 1; }else { l_reqPage = Integer.parseInt(reqPage); } RecordCriteria recordCriteria = new RecordCriteria(l_reqPage); return noticeDAO.noticeList( recordCriteria.getStartRec(), recordCriteria.getEndRec(), searchType, keyword); } //페이지 제어 @Override public PageCriteria noticeGetPageCriteria(String reqPage, String searchType, String keyword) { PageCriteria pc = null; //한페이지에 보여줄 페이징 계산하는 클래스 FindCriteria fc = null; //PageCriteira + 검색타입, 검색어 int totalRec = 0; //전체레코드 수 int l_reqPage = 0; //요청 페이지 정보가 없으면 1로 초기화 if(reqPage == null || reqPage.trim().isEmpty()) { l_reqPage = 1; }else { l_reqPage = Integer.parseInt(reqPage); } totalRec = noticeDAO.noticeTotalRecordCount(searchType,keyword); fc = new FindCriteria(l_reqPage, searchType, keyword); pc = new PageCriteria(fc, totalRec); logger.info("totalRec:"+totalRec, searchType, keyword); logger.info("fc:"+fc.toString()); logger.info("rc:"+((RecordCriteria)fc).toString()); logger.info("pc:"+pc.toString()); return pc; } //페이지 제어 @Override public PageCriteria mainGetPageCriteria(String reqPage, String searchType, String keyword) { PageCriteria pc = null; //한페이지에 보여줄 페이징 계산하는 클래스 FindCriteria fc = null; //PageCriteira + 검색타입, 검색어 int totalRec = 0; //전체레코드 수 int l_reqPage = 0; //요청 페이지 정보가 없으면 1로 초기화 if(reqPage == null || reqPage.trim().isEmpty()) { l_reqPage = 1; }else { l_reqPage = Integer.parseInt(reqPage); } totalRec = noticeDAO.noticeTotalRecordCount(searchType,keyword); fc = new FindCriteria(l_reqPage, searchType, keyword); pc = new PageCriteria(fc, totalRec); logger.info("totalRec:"+totalRec, searchType, keyword); logger.info("fc:"+fc.toString()); logger.info("rc:"+((RecordCriteria)fc).toString()); logger.info("pc:"+pc.toString()); return pc; } }
package de.wiltherr.ws2812fx.serial.communication; import java.nio.ByteBuffer; import java.util.Arrays; /* * source: http://www.sureshjoshi.com/development/streaming-protocol-buffers-with-cobs/ * */ public class CobsUtils { public static final int OVERHEAD_LENGTH = 2; // Expected to be the entire packet to encode public static byte[] encode(byte[] packet) { if (packet == null || packet.length == 0) { return new byte[]{}; } byte[] output = new byte[packet.length + OVERHEAD_LENGTH]; byte blockStartValue = 1; int lastZeroIndex = 0; int srcIndex = 0; int destIndex = 1; while (srcIndex < packet.length) { if (packet[srcIndex] == 0) { output[lastZeroIndex] = blockStartValue; lastZeroIndex = destIndex++; blockStartValue = 1; } else { output[destIndex++] = packet[srcIndex]; if (++blockStartValue == 255) { output[lastZeroIndex] = blockStartValue; lastZeroIndex = destIndex++; blockStartValue = 1; } } ++srcIndex; } output[lastZeroIndex] = blockStartValue; return output; } // Expected to be the entire packet to decode with trailing 0 public static byte[] decode(byte[] packet) { if (packet == null || packet.length == 0 || packet[packet.length - 1] != 0) { return new byte[]{}; } if (packet.length - OVERHEAD_LENGTH < 0) { throw new PacketTooShortException("The input packet length is too short for decoding."); } byte[] output = new byte[packet.length - OVERHEAD_LENGTH]; int srcPacketLength = packet.length - 1; int srcIndex = 0; int destIndex = 0; while (srcIndex < srcPacketLength) { int code = packet[srcIndex++] & 0xff; for (int i = 1; srcIndex < srcPacketLength && i < code; ++i) { output[destIndex++] = packet[srcIndex++]; } if (code != 255 && srcIndex != srcPacketLength) { output[destIndex++] = 0; } } return output; } public static byte[] decodeFromBuffer(ByteBuffer byteBuffer) { return decode(Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.position())); } public static byte[] trim(byte[] bytes) { int endIdx = 0; for (int i = 0; i < bytes.length; i++) { if (bytes[i] == 0x00) { return Arrays.copyOfRange(bytes, 0, i + 1); } } throw new IllegalArgumentException("no 0 bytes to trim"); } private static class PacketTooShortException extends RuntimeException { public PacketTooShortException(String message) { super(message); } } }
package br.com.rca.apkRevista.bancoDeDados.beans; import java.io.File; import java.util.List; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import org.hibernate.annotations.PolymorphismType; import br.com.rca.apkRevista.bancoDeDados.beans.enums.Status; import br.com.rca.apkRevista.bancoDeDados.beans.interfaces.Bean; import br.com.rca.apkRevista.bancoDeDados.beans.interfaces.Persistente; import br.com.rca.apkRevista.bancoDeDados.dao.DAOPagina; import br.com.rca.apkRevista.bancoDeDados.excessoes.PaginaNaoEncontrada; @Entity @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT) @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public class Revista implements Persistente,Bean{ @Id @GeneratedValue(strategy=GenerationType.TABLE) private int id; @ManyToOne private Cliente cliente; private String nomeDaRevista; private int edicao; private String subTitulo; private int nPaginas; private int largura; private int altura; private int resolucao; @Enumerated(EnumType.STRING) private Status status = Status.NAO_DEFINIDO; @OneToOne Miniatura miniatura; public Revista(){ super(); } public Revista(Cliente cliente, String nome, int edicao, String subTitulo){ super(); this.cliente = cliente; this.nomeDaRevista = nome; this.edicao = edicao; this.subTitulo = subTitulo; if (!(this instanceof Miniatura)) { this.miniatura = new Miniatura(cliente,nome,edicao,subTitulo); } } public int getId(){ return id; } public Cliente getCliente() { return cliente; } public String getNome() { return nomeDaRevista; } public int getNPaginas() { return nPaginas; } public List<Pagina> getPaginas(String where, String[] paramns) throws PaginaNaoEncontrada{ try { int lengthParamns2 = paramns.length + (where == "" ? 0 : 1); lengthParamns2 += lengthParamns2 == 0 ? 1 : 0; String[] paramns2 = new String[lengthParamns2]; paramns2[0] = getId() + ""; for (int i = 1; i < paramns2.length ; i++) { paramns2[i] = paramns[i-1]; } if(where == "") where = "1 = 1"; List<Pagina> retorno = DAOPagina.getInstance().get("revista_id = ? and " + where, paramns2); if(retorno.isEmpty()){ /*TODO Encontrar uma forma de extrair do where o nome da revista*/ throw new PaginaNaoEncontrada(0, this); }else{ return retorno; } } catch (Exception e) { if (e instanceof PaginaNaoEncontrada) { throw (PaginaNaoEncontrada) e; }else{ e.printStackTrace(); return null; } } } public List<Pagina> getPaginas() throws PaginaNaoEncontrada{ String[] paramns = {""}; return getPaginas("", paramns); } public int getLargura() { return largura; } public int getAltura() { return altura; } public int getResolucao() { return resolucao; } public String getFolder() { return getCliente().getFolder() + File.separator + getNome(); } public void setNPaginas(int nPaginas) { this.nPaginas = nPaginas; if(!(this instanceof Miniatura)) this.getMiniatura().setNPaginas(nPaginas); } public void setStatus(Status status) { /*TODO Log*/ if(status==Status.AGUARDANDO_SCANNER){ try { List<Pagina> paginas = getPaginas(); for (Pagina pagina : paginas) { DAOPagina.getInstance().delete(pagina); } } catch (PaginaNaoEncontrada e) { //Sem problemas! } } //System.out.println("Alteração do status da revista " + getCliente().getUser() + "/" + getNome() + " de " + this.status + " para " + status); if (!(this instanceof Miniatura)) { this.getMiniatura().setStatus(status); } this.status = status; } public Status getStatus() { return status; } public void setLargura(int largura) { this.largura = largura; } public void setAltura(int altura){ this.altura = altura; } public Miniatura getMiniatura(){ return miniatura; } public int getEdicao(){ return edicao; } public String getSubTitulo(){ return subTitulo; } }
package com.cmi.bache24.ui.fragment; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.cmi.bache24.R; import com.cmi.bache24.data.model.Report; import com.cmi.bache24.data.model.User; import com.cmi.bache24.data.remote.ServicesManager; import com.cmi.bache24.data.remote.interfaces.RegisterUserCallback; import com.cmi.bache24.data.remote.interfaces.ReportsCallback; import com.cmi.bache24.ui.activity.LoginActivity; import com.cmi.bache24.ui.adapter.ReportsAdapter; import com.cmi.bache24.util.Constants; import com.cmi.bache24.util.ImagePicker; import com.cmi.bache24.util.PreferencesManager; import com.cmi.bache24.util.Utils; import com.squareup.picasso.Picasso; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; //import android.app.AlertDialog; /** * A placeholder fragment containing a simple view. */ public class UserHistoryFragment extends BaseFragment implements View.OnClickListener { private CircleImageView mProfilePicture; private TextView mTextViewName; private TextView mNoReports; private Button mButtonHistory; private Button mButtonProfile; private LinearLayout mLayoutHistory; private RelativeLayout mLayoutProfile; private RecyclerView mReportsList; private TextView mTextViewPhoneNumber; private TextView mTextViewEmail; private Button mButtonLogout; private CheckBox mCheckNotifications; private LinearLayout mLayoutNormal; private ReportsAdapter mReportsAdapter; private User mCurrentUser; private List<Report> mReports; //PARA EDICION private CircleImageView mImageProfilePicture; private Button mButtonAddPicture; private EditText mEditName; private EditText mEditLastName; private EditText mEditEmail; private EditText mEditPhone; private EditText mEditOldPassword; private EditText mEditNewPassword; private ImageButton mImageFB; private ImageButton mImageTW; private RelativeLayout mLayoutProfileEdit; private View progressView; private UserHistoryAndProfileListener mUserHistoryAndProfileListener; private static final int PICK_IMAGE_ID = 234; private Context mCurrentContext; public UserHistoryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_user_history, container, false); mProfilePicture = (CircleImageView) root.findViewById(R.id.image_profile_picture); mTextViewName = (TextView) root.findViewById(R.id.textview_full_username); mNoReports = (TextView) root.findViewById(R.id.textview_no_reports); mButtonHistory = (Button) root.findViewById(R.id.button_history); mButtonProfile = (Button) root.findViewById(R.id.button_profile); mLayoutHistory = (LinearLayout) root.findViewById(R.id.layout_history); mLayoutProfile = (RelativeLayout) root.findViewById(R.id.layout_profile); mReportsList = (RecyclerView) root.findViewById(R.id.report_list); mTextViewPhoneNumber = (TextView) root.findViewById(R.id.textview_phone_number); mTextViewEmail = (TextView) root.findViewById(R.id.textview_email); mButtonLogout = (Button) root.findViewById(R.id.button_logout); mCheckNotifications = (CheckBox) root.findViewById(R.id.check_notifications); mLayoutNormal = (LinearLayout) root.findViewById(R.id.layout_profile_normal); //EDICION mImageProfilePicture = (CircleImageView) root.findViewById(R.id.image_profile_picture_edit); mButtonAddPicture = (Button) root.findViewById(R.id.button_add_picture); mEditName = (EditText) root.findViewById(R.id.edittext_name); mEditLastName = (EditText) root.findViewById(R.id.edittext_lastname); mEditEmail = (EditText) root.findViewById(R.id.edittext_email); mEditPhone = (EditText) root.findViewById(R.id.edittext_phone_number); mEditOldPassword = (EditText) root.findViewById(R.id.edittext_current_password); mEditNewPassword = (EditText) root.findViewById(R.id.edittext_new_password); mImageFB = (ImageButton) root.findViewById(R.id.image_button_fb); mImageTW = (ImageButton) root.findViewById(R.id.image_button_tw); mLayoutProfileEdit = (RelativeLayout) root.findViewById(R.id.layout_profile_edit); progressView = root.findViewById(R.id.progress_layout); progressView.setVisibility(View.GONE); mButtonAddPicture.setOnClickListener(this); //EDICION mReportsAdapter = new ReportsAdapter(getActivity()); mButtonHistory.setOnClickListener(this); mButtonProfile.setOnClickListener(this); mButtonLogout.setOnClickListener(this); mCurrentUser = PreferencesManager.getInstance().getUserInfo(getActivity()); final float scale = this.getResources().getDisplayMetrics().density; mCheckNotifications.setPadding(mCheckNotifications.getPaddingLeft() + (int) (10.0f * scale + 0.5f), mCheckNotifications.getPaddingTop(), mCheckNotifications.getPaddingRight(), mCheckNotifications.getPaddingBottom()); // Log.i("NotificaitonsEn", "Are notifications enabled? " + PreferencesManager.getInstance().notificationsEnabled(mCurrentContext)); mCheckNotifications.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { PreferencesManager.getInstance().setNotificationsEnabled(mCurrentContext, isChecked); } }); mCheckNotifications.setChecked(PreferencesManager.getInstance().notificationsEnabled(mCurrentContext)); mLayoutNormal.setVisibility(View.VISIBLE); mLayoutProfileEdit.setVisibility(View.GONE); mNoReports.setText(""); showUserInfo(); loadReports(); showViewAtPosition(0); return root; } @Override public void onAttach(Context context) { super.onAttach(context); mCurrentContext = context; try{ if (context instanceof Activity) { mUserHistoryAndProfileListener = (UserHistoryAndProfileListener) context; } } catch (ClassCastException ex) { } } @Override public void onClick(View view) { if (view.getId() == mButtonHistory.getId()) { showViewAtPosition(0); if (mUserHistoryAndProfileListener != null) mUserHistoryAndProfileListener.onHistorySelect(); } else if (view.getId() == mButtonProfile.getId()) { showViewAtPosition(1); if (mUserHistoryAndProfileListener != null) mUserHistoryAndProfileListener.onProfileSelect(); } else if (view.getId() == mButtonLogout.getId()) { logout(); } else if (view.getId() == mButtonAddPicture.getId()) { checkCameraPermissions(); } } private void logout() { AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create(); alertDialog.setTitle(getResources().getString(R.string.profile_logout_title)); alertDialog.setMessage(getResources().getString(R.string.profile_logout_message)); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getResources().getString(R.string.profile_logout_cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(R.string.profile_logout_accept), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); removeFromParse(); PreferencesManager.getInstance().logoutSession(getActivity()); PreferencesManager.getInstance().removeReports(getActivity()); Intent reportActivityIntent = new Intent(getActivity(), LoginActivity.class); reportActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(reportActivityIntent); getActivity().overridePendingTransition(R.anim.enter_from_right, R.anim.enter_from_left); } }); alertDialog.show(); } private void removeFromParse() { /*ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put("userEmail", ""); installation.saveInBackground();*/ } private void showUserInfo() { if (mCurrentUser == null) return; mTextViewName.setText((mCurrentUser.getName() != null ? mCurrentUser.getName() : "") + " " + (mCurrentUser.getFirtsLastName() != null ? mCurrentUser.getFirtsLastName() : "") + " " + (mCurrentUser.getSecondLastName() != null ? mCurrentUser.getSecondLastName() : "")); if (mCurrentUser.getPictureUrl() != null) { if (!mCurrentUser.getPictureUrl().isEmpty()) { Picasso.with(getActivity()) .load(mCurrentUser.getPictureUrl()) .placeholder(R.drawable.user_registro) .error(R.drawable.user_registro).into(mProfilePicture); Picasso.with(getActivity()) .load(mCurrentUser.getPictureUrl()) .placeholder(R.drawable.user_registro) .error(R.drawable.user_registro).into(mImageProfilePicture); } } mTextViewPhoneNumber.setText(mCurrentUser.getPhone()); mTextViewEmail.setText(mCurrentUser.getEmail()); } private void loadReports() { if (!Utils.getInstance().isInternetAvailable(getActivity())) return; progressView.setVisibility(View.VISIBLE); ServicesManager.getReports(mCurrentUser, new ReportsCallback() { @Override public void onReportsCallback(List<Report> reports) { progressView.setVisibility(View.GONE); mReports = reports; mNoReports.setText(mReports.size() + (mReports.size() == 1 ? " reporte" : " reportes")); if (reports.size() == 0) { showEmptyReportsDialog(); return; } mReportsAdapter.addAllSections(mReports); mReportsList.setLayoutManager(new LinearLayoutManager(getActivity())); mReportsList.setAdapter(mReportsAdapter); mReportsAdapter.setReportsListener(new ReportsAdapter.OnReportsListener() { @Override public void onReportClick(Report report) { mUserHistoryAndProfileListener.onReportSelected(report); } }); } @Override public void onReportsFail(String message) { progressView.setVisibility(View.GONE); /*Log.i("BACHE_TIMEOUT", "Message 1");*/ if (mCurrentContext != null) { /*Log.i("BACHE_TIMEOUT", "Message 2");*/ if (message != "") { /*Log.i("BACHE_TIMEOUT", "Message 3");*/ Toast.makeText(mCurrentContext, message, Toast.LENGTH_SHORT).show(); } } } @Override public void userBanned() { Utils.showLogin(getActivity()); } @Override public void onTokenDisabled() { Utils.showLoginForBadToken(getActivity()); } }); } private void showEmptyReportsDialog() { if (getActivity() == null) return; AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setMessage("No has enviado reportes"); dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); dialog.show(); } private void showViewAtPosition(int position) { mLayoutHistory.setVisibility(View.GONE); mLayoutProfile.setVisibility(View.GONE); if (position == 0) { mButtonHistory.setBackgroundResource(R.drawable.btn_activo); mButtonProfile.setBackgroundResource(R.drawable.btn_inactivo); mButtonHistory.setTextColor(getResources().getColor(R.color.text_color_white)); mButtonProfile.setTextColor(getResources().getColor(R.color.primary)); mLayoutHistory.setVisibility(View.VISIBLE); } else { mButtonHistory.setBackgroundResource(R.drawable.btn_inactivo); mButtonProfile.setBackgroundResource(R.drawable.btn_activo); mButtonHistory.setTextColor(getResources().getColor(R.color.primary)); mButtonProfile.setTextColor(getResources().getColor(R.color.text_color_white)); mLayoutProfile.setVisibility(View.VISIBLE); } } public void editUser() { mLayoutNormal.setVisibility(View.GONE); mLayoutProfileEdit.setVisibility(View.VISIBLE); mEditName.setText(mCurrentUser.getName() != null ? mCurrentUser.getName() : ""); mEditLastName.setText(mCurrentUser.getFirtsLastName() != null ? mCurrentUser.getFirtsLastName() : ""); mEditEmail.setText(mCurrentUser.getEmail()); mEditPhone.setText(mCurrentUser.getPhone()); } public boolean validUserInfo() { if (mEditEmail.getText().toString().trim().isEmpty()) { Toast.makeText(getActivity(), "Ingresa tu e-mail", Toast.LENGTH_SHORT).show(); return false; } if (!Utils.isValidEmail(mEditEmail.getText().toString())) { Toast.makeText(getActivity(), "Ingresa tu e-mail", Toast.LENGTH_SHORT).show(); return false; } if (mEditPhone.getText().toString().trim().isEmpty()) { Toast.makeText(getActivity(), "Ingresa tu teléfono", Toast.LENGTH_SHORT).show(); return false; } if (mEditPhone.getText().toString().trim().length() < 8) { Toast.makeText(getActivity(), "El teléfono debe tener entre 8 y 10 digitos", Toast.LENGTH_SHORT).show(); return false; } return true; } public void endEditUser() { if (!Utils.getInstance().isInternetAvailable(getActivity())) return; User updatedUser = mCurrentUser; updatedUser.setPhone(mEditPhone.getText().toString().trim()); updatedUser.setEmail(mEditEmail.getText().toString().trim()); if (!mEditOldPassword.getText().toString().isEmpty()) { if (!mEditNewPassword.getText().toString().isEmpty()) { updatedUser.setOldPassword(mEditOldPassword.getText().toString()); updatedUser.setPassword(mEditNewPassword.getText().toString()); } else updatedUser.setPassword(""); } else updatedUser.setPassword(""); updatedUser.setPicture(""); progressView.setVisibility(View.VISIBLE); Bitmap bitmapProfilePicture = null; bitmapProfilePicture = ((BitmapDrawable)mImageProfilePicture.getDrawable()).getBitmap(); updatedUser.setPicture(bitmapProfilePicture != null ? Utils.bitmapToBase64(bitmapProfilePicture, Constants.PICTURE_CITIZEN_QUALITY) : ""); ServicesManager.updateUser(updatedUser, new RegisterUserCallback() { @Override public void onRegisterSuccess(User userComplete) { progressView.setVisibility(View.GONE); PreferencesManager.getInstance().setUserInfo(getActivity(), userComplete); showUserInfo(); mLayoutNormal.setVisibility(View.VISIBLE); mLayoutProfileEdit.setVisibility(View.GONE); if (mUserHistoryAndProfileListener != null) mUserHistoryAndProfileListener.onUpdateFinished(); } @Override public void onRegisterFail(String message) { progressView.setVisibility(View.GONE); if (mUserHistoryAndProfileListener != null) mUserHistoryAndProfileListener.onUpdateFailed(); } @Override public void userBanned() { Utils.showLogin(getActivity()); } @Override public void onTokenDisabled() { Utils.showLoginForBadToken(getActivity()); } }); } public void cancelEditUser() { showUserInfo(); mLayoutNormal.setVisibility(View.VISIBLE); mLayoutProfileEdit.setVisibility(View.GONE); if (mUserHistoryAndProfileListener != null) mUserHistoryAndProfileListener.onUpdateFinished(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_ID && resultCode == getActivity().RESULT_OK) { Bitmap bitmap = ImagePicker.getImageFromResult(getActivity(), resultCode, data, "", "profile_picture.jpg"); mImageProfilePicture.setImageBitmap(bitmap); mImageProfilePicture.setScaleType(ImageView.ScaleType.CENTER_CROP); } } private void checkCameraPermissions() { checkPermissionsForAction(new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, ACTION_TAKE_OR_CHOOSE_PICTURE, "Los permisos para tomar fotos están desactivados"); } @Override public void doAllowedStuffWithPermissionGrantedForAction(String action) { Intent chooseImageIntent = ImagePicker.getPickImageIntent(getActivity(), "", "profile_picture.jpg"); startActivityForResult(chooseImageIntent, PICK_IMAGE_ID); } @Override public void onPermissionDenied(String message) { Toast.makeText(mCurrentContext, message, Toast.LENGTH_SHORT).show(); } @Override public void onPermissionDeniedPermanently(String message) { Toast.makeText(mCurrentContext, message, Toast.LENGTH_SHORT).show(); } public interface UserHistoryAndProfileListener { void onHistorySelect(); void onProfileSelect(); void onReportSelected(Report report); void onUpdateFinished(); void onUpdateFailed(); } }
package it.polito.tdp.borders.model; import java.util.ArrayList; import java.util.List; import org.jgrapht.Graph; import org.jgrapht.Graphs; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; public class Recursive { //CLASSE CONTENENTE L'ALGORITMO RICORSIVO private Graph<Country, DefaultEdge> grafo = new SimpleGraph<>(DefaultEdge.class); /** * * @param grafo (Grafo creato a partire da un anno specificato) * @param statoPartenza (punto di partenza per la ricerca del cammino) * @return Lista di stati raggiungibili via terra dallo stato passato come parametro */ public List<Country> getListaVicini(Graph<Country, DefaultEdge> graph, Country statoPartenza){ grafo = graph; List<Country> parziale = new ArrayList<>(); parziale.add(statoPartenza); cerca(parziale, statoPartenza); return parziale; } public void cerca(List<Country> parziale, Country paeseVisitato){ /* * CASO GENERALE: dal paese in cui mi trovo prelevo i suoi vicini, * controllo se siano già stati inseriti e, nel caso * rimando la ricorsione */ List<Country> adiacenti = new ArrayList<>(Graphs.neighborListOf(grafo, paeseVisitato)); for(Country c: adiacenti) { //Controllo che il nodo adiacente non sia già nella lista parziale if(!parziale.contains(c)) { parziale.add(c); cerca(parziale, c); } } } }
package com.rizkimufrizal.belajar.retrofit.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.rizkimufrizal.belajar.retrofit.R; import com.rizkimufrizal.belajar.retrofit.model.Item; import java.util.ArrayList; import java.util.List; /** * @Author Rizki Mufrizal <mufrizalrizki@gmail.com> * @Web <https://RizkiMufrizal.github.io> * @Since 09 March 2017 * @Time 9:25 AM * @Project Belajar-Retrofit * @Package com.rizkimufrizal.belajar.retrofit.adapter * @File AdapterRowItem */ public class AdapterRowItem extends RecyclerView.Adapter<AdapterRowItem.ViewHolder> { private List<Item> itemList = new ArrayList<>(); public void clear() { itemList.clear(); } public void addItem(List<Item> itemList) { this.itemList = itemList; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView textView; public ImageView imageView; public ViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.textView); imageView = (ImageView) itemView.findViewById(R.id.imageview); } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_row_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.textView.setText(itemList.get(position).getName()); Glide .with(holder.imageView.getContext()) .load(itemList.get(position).getAlbum().getImages().get(0).getUrl()) .centerCrop() .placeholder(R.mipmap.gears) .crossFade() .diskCacheStrategy(DiskCacheStrategy.RESULT) .into(holder.imageView); } @Override public int getItemCount() { return itemList.size(); } }
package com.travel.community.travel_demo.service; import com.travel.community.travel_demo.mapper.UserMapper; import com.travel.community.travel_demo.model.User; import com.travel.community.travel_demo.model.UserExample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; public void createOrUpdate(User user) { // User dbUser = userMapper.findByAccountId(user.getAccountId()); UserExample userExample = new UserExample(); //这样可以拼接很多的sql语句,就不用我们自己去写了,就像是之前的通用的mapper userExample.createCriteria().andAccountIdEqualTo(user.getAccountId()); List<User> users = userMapper.selectByExample(userExample); if (users.size() == 0){ //插入 user.setGmtCreate(System.currentTimeMillis()); // user.setGmtModified(user.getGmtModified()); userMapper.insert(user); }else { //更新 User dbUser = users.get(0); User updateUser = new User(); updateUser.setAvatarUrl(user.getAvatarUrl()); updateUser.setUserName(user.getUserName()); updateUser.setToken(user.getToken()); UserExample example = new UserExample(); example.createCriteria() .andIdEqualTo(dbUser.getId()); userMapper.updateByExampleSelective(updateUser,example); //为什么要使用updateByExampleSelective因为这个是局部的变动的, // 参数1:这个参数是让传入一个对象,就是你要修改的那条数据所对应的对象,即你要更新的内容, // 参数2:传入xxxExample就可以,这里是基操看看上面的操作即可 } // if (dbUser == null){ // //插入 // user.setGmtCreate(System.currentTimeMillis()); // userMapper.githubInsert(user); // }else { // //更新 // dbUser.setAvatarUrl(user.getAvatarUrl()); // dbUser.setUserName(user.getUserName()); // dbUser.setToken(user.getToken()); // userMapper.githubUpdate(dbUser); // } } }
package com.gmail.filoghost.holographicdisplays.object; import org.bukkit.Location; import org.bukkit.plugin.Plugin; import com.gmail.filoghost.holographicdisplays.util.Validator; /** * This class is only used by the plugin itself. Do not attempt to use it. */ public class PluginHologram extends CraftHologram { private Plugin plugin; public PluginHologram(Location source, Plugin plugin) { super(source); Validator.notNull(plugin, "plugin"); this.plugin = plugin; } public Plugin getOwner() { return plugin; } @Override public void delete() { super.delete(); PluginHologramManager.removeHologram(this); } }
import Intefaces.ReturnValue; public class ReturnSwapedCharIndexToOne implements ReturnValue { // return a specific index to 1 @Override public int returnToInitialValue() { return 1; } }
package org.juxtasoftware.model; import java.util.Map; import eu.interedition.text.Annotation; import eu.interedition.text.Name; import eu.interedition.text.Range; import eu.interedition.text.Text; /** * An extension of the basic annotaion that includes * witness ID and may include text content * * @author loufoster * */ public class JuxtaAnnotation implements Annotation { private Long id; private final Long setId; private final Long witnessId; private final Text text; private final Name qName; private final Range range; private String content; private boolean manual = false; public JuxtaAnnotation(Long setId, Witness witness, Name qname, Range range ) { this(null,setId, witness.getId(), witness.getText(), qname, range); } public JuxtaAnnotation( final Long setId, final Long witnessId, Annotation other) { this(null,setId, witnessId, other.getText(), other.getName(), other.getRange()); } public JuxtaAnnotation( JuxtaAnnotation other ) { this( other.getId(), other.getSetId(), other.getWitnessId(), other.getText(), other.getName(), other.getRange() ); } public JuxtaAnnotation(Long id, Long setId, Long witnessId, Text text, Name qname, Range range ) { this.id = id; this.setId = setId; this.witnessId = witnessId; this.qName = qname; this.text = text; this.range = new Range(range); this.content = ""; } public void setManual() { this.manual = true; } public boolean isManual() { return this.manual; } public void setId(Long id) { this.id = id; } public void setContent( String content ) { this.content = content; } public String getContent() { return this.content; } public Long getWitnessId() { return this.witnessId; } public Long getId() { return this.id; } public Long getSetId() { return this.setId; } @Override public int compareTo(Annotation other) { return getRange().compareTo(other.getRange()); } @Override public Text getText() { return this.text; } @Override public Name getName() { return this.qName; } @Override public Range getRange() { return new Range(this.range); } @Override public Map<Name, String> getData() { return null; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((qName == null) ? 0 : qName.getNamespace().hashCode()); result = prime * result + ((qName == null) ? 0 : qName.getLocalName().hashCode()); result = prime * result + ((range == null) ? 0 : range.hashCode()); result = prime * result + ((setId == null) ? 0 : setId.hashCode()); result = prime * result + ((witnessId == null) ? 0 : witnessId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JuxtaAnnotation other = (JuxtaAnnotation) obj; if (qName == null) { if (other.qName != null) return false; } else if (!qName.equals(other.qName)) return false; if (range == null) { if (other.range != null) return false; } else if (!range.equals(other.range)) return false; if (setId == null) { if (other.setId != null) return false; } else if (!setId.equals(other.setId)) return false; if (witnessId == null) { if (other.witnessId != null) return false; } else if (!witnessId.equals(other.witnessId)) return false; return true; } @Override public String toString() { return "JuxtaAnnotation [id=" + id + ", text=" + text + ", range=" + range + "]"; } }
import java.util.Scanner; public class largestofthree{ public static void main(String Args[]) { System.out.println("Enter three numbers "); Scanner s= new Scanner(System.in); int a= s.nextInt(); int b= s.nextInt(); int c= s.nextInt(); //int if (a>b && a>c) { System.out.println("Your answer is: " + a); } else if (b>a && b>c) { System.out.println("Your answer is: " + b); } else { System.out.println("Your answer is: " + c); } } }
package meli.tmr.solarsystem.models; public class Position { private double X; private double Y; public Position(double X, double Y){ this.setX(X); this.setY(Y); } public double getX() { return X; } public void setX(double x) { X = x; } public double getY() { return Y; } public void setY(double y) { Y = y; } public static String getPositionAsString(Position position){ return "Position (" + position.getX() + ", " + position.getY() + ")"; } }
package gradedGroupProject; public interface RegistrationInterface { public abstract BankClient registerBankClient(); public BankClient executeTransactionStructure(); public void provideClientInformation(); public void returnLoginDetails(); public boolean checkTransactionStructure(); public void printErrorMessage(); public String InvalidInformation(); }
package de.drkhannover.tests.api.conf; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.PasswordEncoder; import de.drkhannover.tests.api.auth.JwtAuthenticationFilter; import de.drkhannover.tests.api.auth.JwtAuthorizationFilter; import de.drkhannover.tests.api.user.UserRole; import de.drkhannover.tests.api.user.UserServiceImpl; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("${recovery.enabled}") private String inMemoryEnabled; @Value("${recovery.password}") private String inMemoryPassword; @Value("${recovery.user}") private String inMemoryUser; @Autowired private ConfigurationValues confValues; @Autowired private UserServiceImpl userServiceImpl; @Autowired private PasswordEncoder passwordEncoder; @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and() .csrf().disable() .authorizeRequests() .antMatchers(ControllerPath.SWAGGER).permitAll() .antMatchers(ControllerPath.AUTHENTICATION_AUTH).permitAll() .antMatchers(ControllerPath.USERS_PREFIX).hasAuthority(UserRole.ADMIN.name()) // admin: allowed to add users .antMatchers(ControllerPath.AUTHENTICATION_CHECK).permitAll() .antMatchers(ControllerPath.FORMULAR_PRIVATE).hasAnyAuthority(UserRole.ADMIN.name(), UserRole.PRIVATE.name()) .antMatchers(ControllerPath.FORMULAR_DEFAULT).hasAnyAuthority(UserRole.ADMIN.name(), UserRole.DEFAULT.name()) .antMatchers(ControllerPath.FORMULAR_KVN).hasAnyAuthority(UserRole.ADMIN.name(), UserRole.KVN.name()) .antMatchers("/**").authenticated() //.antMatchers("/**").permitAll()//maybe remove later .and() .addFilter(new JwtAuthenticationFilter(authenticationManager(), confValues)) .addFilter(new JwtAuthorizationFilter(authenticationManager(), confValues)) .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Override // allow swagger // TODO Marcel: test if necessary public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { if (inMemoryEnabled != null && Boolean.parseBoolean(inMemoryEnabled)) { auth.inMemoryAuthentication() .withUser(inMemoryUser) .password(passwordEncoder.encode(inMemoryPassword)) .roles(UserRole.ADMIN.name()); } auth.userDetailsService(userServiceImpl); } @Bean("authenticationManager") @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package NotepadComFacade; /** * * @author jarde */ public class FacadeNotepad { private Notepad notepad; public FacadeNotepad() { System.out.println("Instanciando Sistema!"); notepad = new Notepad(); notepad.setVisible(true); } public void salvamentoAutomatico() { Thread salvarAutomaticamente = new Thread(notepad, "Salvar"); salvarAutomaticamente.start(); System.out.println("Salvamento automático"); } public void interfaceGrafica() { notepad.janelaNotepad(); System.out.println("Inicializando Sistema Gráfico"); } }
package bos.pearls.algorithms.column1; import java.util.Arrays; import bos.pearls.IAlgorithm; import bos.pearls.util.Data; public class SystemSorting implements IAlgorithm { private int[] input; public void setup() { input = Arrays.copyOf(Data.INTEGERS, Data.INTEGERS.length); System.out.println("System Sorting ... Array Length: " + input.length); } public void run() { Arrays.sort(input); } public void cleanup() {} }
package pl.aaugustyniak.dijkstra; import java.util.HashSet; import java.util.Set; /** * * @author artur */ public class Dijkstra { private final Graph G; private final Set<Vertex> S; private final Set<Vertex> Q; public Dijkstra(Graph G) { this.G = G; this.Q = new HashSet<>(G.getAllVertices()); this.S = new HashSet<>(); } public CostMatrix inspectGraph() { CostMatrix cm = new CostMatrix(this.G); while (!Q.isEmpty()) { Vertex next = cm.getNearestVertexExcludingFeaturedBy(Q); S.add(next); Q.remove(next); cm.update(next); } return cm; } }
package com.code; public class HeightProblem { public static void main(String[] args) { int n = 4; int left[] = { 2, 1, 1, 0 }; System.out.println("Output:"+uniqueValue(n, left)); } public static int[] uniqueValue(int count, int[] tallerCountArray) { int heightArray[] = new int[count]; for (int heightIndex = 0;heightIndex <count;heightIndex++) { int tallCount = tallerCountArray[heightIndex]; // } return heightArray; } }
package com.legaoyi.protocol.down.messagebody; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.down.messagebody.JTT808_8701_2013_MessageBody; import com.legaoyi.protocol.message.MessageBody; /** * 设置初始里程 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2015-01-30 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "8701_C4H_2013" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT808_8701_C4H_2013_MessageBody extends JTT808_8701_2013_MessageBody { private static final long serialVersionUID = 1009597180746858610L; /** 记录仪实时时间,如2014-10-25 18:00:85 **/ @JsonProperty("realTime") private String realTime; /** 记录仪初次安装时间 **/ @JsonProperty("installTime") private String installTime; /** 初始里程 **/ @JsonProperty("initialMileage") private double initialMileage; /** 累计行驶里程 **/ @JsonProperty("mileage") private double mileage; public final String getRealTime() { return realTime; } public final void setRealTime(String realTime) { this.realTime = realTime; } public final String getInstallTime() { return installTime; } public final void setInstallTime(String installTime) { this.installTime = installTime; } public final double getInitialMileage() { return initialMileage; } public final void setInitialMileage(double initialMileage) { this.initialMileage = initialMileage; } public final double getMileage() { return mileage; } public final void setMileage(double mileage) { this.mileage = mileage; } }
package tests; import com.fasterxml.jackson.databind.ObjectMapper; import com.rev.dao.ExcuseRepository; import com.rev.model.Excuse; import com.rev.model.Room; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.io.Serializable; import java.nio.charset.Charset; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * @author Trevor */ @ContextConfiguration(locations = "classpath:application-context.xml") @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration public class ControllerTest { @Autowired WebApplicationContext wac; @Autowired ExcuseRepository dao; private MockMvc mockMvc; private final ObjectMapper om = new ObjectMapper(); @Before public void setup(){ mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void getAll(){ try { mockMvc.perform(get("/excuse/get")).andExpect(status().isOk()); } catch (Exception e){ Assert.fail(e.getMessage()); } } @Test public void postGet(){ try { //post MvcResult result = mockMvc.perform(post("/excuse/post") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(new Excuse("Field Trip")))) .andExpect(status().isCreated()) .andReturn(); String id = result.getResponse().getContentAsString(); //get mockMvc.perform(get("/excuse/get/"+id)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); } catch (Exception e){ Assert.fail(e.getMessage()); } } @Test public void postPutGet(){ try { //post MvcResult result = mockMvc.perform(post("/excuse/post") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(new Excuse("Deceased")))) .andExpect(status().isCreated()) .andReturn(); //put String id = result.getResponse().getContentAsString(); Excuse updatedExcuse = new Excuse("Diseased"); updatedExcuse.setId(Integer.parseInt(id)); mockMvc.perform(put("/excuse/put") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(updatedExcuse))) .andExpect(status().isNoContent()); //get mockMvc.perform(get("/excuse/get/"+id)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().json("{'excuseType':'Diseased'}")); } catch (Exception e){ Assert.fail(e.getMessage()); } } @Test public void postDelete(){ try { //post MvcResult result = mockMvc.perform(post("/excuse/post") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(new Excuse("qwerty")))) .andExpect(status().isCreated()) .andReturn(); String id = result.getResponse().getContentAsString(); //delete mockMvc.perform(delete("/excuse/delete/"+id)) .andExpect(status().isNoContent()); } catch (Exception e){ Assert.fail(e.getMessage()); } } @Test public void postDeleteAndTryWithId(){ try { //make sure id slot is empty by creating then deleting MvcResult result = mockMvc.perform(post("/excuse/post") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(new Excuse("asdfg")))) .andExpect(status().isCreated()) .andReturn(); String id = result.getResponse().getContentAsString(); mockMvc.perform(delete("/excuse/delete/"+id)) .andExpect(status().isNoContent()); //fail get mockMvc.perform(get("/excuse/get/"+id)) .andExpect(status().isInternalServerError()); //fail put Excuse updatedExcuse = new Excuse("zxcvb"); updatedExcuse.setId(Integer.parseInt(id)); String test = om.writeValueAsString(updatedExcuse); try{ mockMvc.perform(put("/excuse/put") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(updatedExcuse))); Assert.fail("Exception not thrown for missing id"); } catch(Exception e){ //were supposed to hit this } //fail delete mockMvc.perform(delete("/excuse/delete/"+id)) .andExpect(status().isInternalServerError()); } catch (Exception e){ Assert.fail(e.getMessage()); } } //tests @JsonIgnore @Test public void postGetRoom(){ try { //post MvcResult result = mockMvc.perform(post("/room/post") .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsString(new Room("Computer lab")))) .andExpect(status().isCreated()) .andReturn(); String id = result.getResponse().getContentAsString(); //get mockMvc.perform(get("/room/get/"+id)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); } catch (Exception e){ Assert.fail(e.getMessage()); } } }
package io.nuls.consensus.utils.manager; import io.nuls.common.NerveCoreConfig; import io.nuls.base.basic.AddressTool; import io.nuls.base.data.NulsHash; import io.nuls.consensus.constant.ConsensusConstant; import io.nuls.consensus.model.bo.Chain; import io.nuls.consensus.model.bo.StackingAsset; import io.nuls.consensus.model.bo.tx.txdata.Deposit; import io.nuls.consensus.model.po.DepositPo; import io.nuls.consensus.storage.DepositStorageService; import io.nuls.consensus.utils.ConsensusAwardUtil; import io.nuls.consensus.utils.compare.DepositComparator; import io.nuls.consensus.utils.enumeration.DepositTimeType; import io.nuls.consensus.utils.enumeration.DepositType; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.exception.NulsException; import io.nuls.core.model.DoubleUtils; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 委托信息管理类,负责委托信息相关处理 * Delegated information management category, responsible for delegated information related processing * * @author tag * 2018/12/5 */ @Component public class DepositManager { @Autowired private DepositStorageService depositStorageService; @Autowired private NerveCoreConfig config; @Autowired private static ChainManager chainManager; /** * 初始化委托信息 * Initialize delegation information * * @param chain 链信息/chain info */ public void loadDeposits(Chain chain) throws Exception { List<Deposit> allDepositList = new ArrayList<>(); List<DepositPo> poList = depositStorageService.getList(chain.getConfig().getChainId()); for (DepositPo po : poList) { Deposit deposit = new Deposit(po); allDepositList.add(deposit); } allDepositList.sort(new DepositComparator()); chain.setDepositList(allDepositList); } /** * 添加委托缓存 * Add delegation cache * * @param chain chain info * @param deposit deposit info */ public boolean addDeposit(Chain chain, Deposit deposit) { if (!depositStorageService.save(new DepositPo(deposit), chain.getConfig().getChainId())) { chain.getLogger().error("Data save error!"); return false; } chain.getDepositList().add(deposit); return true; } /** * 修改委托缓存 * modify delegation cache * * @param chain chain * @param deposit deposit info */ public boolean updateDeposit(Chain chain, Deposit deposit) { if (!depositStorageService.save(new DepositPo(deposit), chain.getChainId())) { chain.getLogger().error("Data save error!"); return false; } for (Deposit oldDeposit : chain.getDepositList()) { if (oldDeposit.getTxHash().equals(deposit.getTxHash())) { oldDeposit.setDelHeight(deposit.getDelHeight()); break; } } return true; } /** * 删除指定链的委托信息 * Delete delegate information for a specified chain * * @param chain chain nfo * @param txHash 创建该委托交易的Hash/Hash to create the delegated transaction */ public boolean removeDeposit(Chain chain, NulsHash txHash) { if (!depositStorageService.delete(txHash, chain.getConfig().getChainId())) { chain.getLogger().error("Data save error!"); return false; } chain.getDepositList().removeIf(s -> s.getTxHash().equals(txHash)); return true; } /** * 获取指定委托信息 * Get the specified delegation information * * @param chain chain nfo * @param txHash 创建该委托交易的Hash/Hash to create the delegated transaction */ public Deposit getDeposit(Chain chain, NulsHash txHash) { for (Deposit deposit : chain.getDepositList()) { if (deposit.getTxHash().equals(txHash)) { return deposit; } } return null; } /** * 计算委托各账户委托金额并返回总的委托金 * * @param chain 链信息 * @param endHeight 高度 * @param depositMap 委托 * @param totalAmount 总委托金额 * @param date 按那一天的喂价计算 */ public BigDecimal getDepositByHeight(Chain chain, long startHeight, long endHeight, Map<String, BigDecimal> depositMap, BigDecimal totalAmount, String date) throws NulsException { BigDecimal realAmount; String address; List<DepositPo> depositList; long depositLockEndTime = Integer.parseInt(date) * ConsensusConstant.ONE_DAY_SECONDS + ConsensusConstant.ONE_DAY_SECONDS + ConsensusConstant.ONE_DAY_SECONDS / 2; try { //这儿不能是有缓存中的数据,因为有可能中途有新数据插入 depositList = depositStorageService.getList(chain.getConfig().getChainId()); } catch (NulsException e) { chain.getLogger().error(e); return totalAmount; } if (depositList == null || depositList.isEmpty()) { return totalAmount; } for (DepositPo deposit : depositList) { //有效委托,委托高度要小指定高度且退出委托高度大于指定高度 if (deposit.getBlockHeight() > endHeight) { continue; } if (deposit.getDelHeight() != -1 && deposit.getDelHeight() <= endHeight) { continue; } if (endHeight > chain.getConfig().getDepositAwardChangeHeight() && deposit.getBlockHeight() > startHeight) { continue; } StringBuilder ss = new StringBuilder(); ss.append(AddressTool.getStringAddressByBytes(deposit.getAddress())); ss.append("-"); ss.append(deposit.getAssetChainId()); ss.append("-"); ss.append(deposit.getAssetId()); ss.append("-"); ss.append(deposit.getDeposit().toString()); realAmount = calcDepositBase(chain, deposit, date, depositLockEndTime, endHeight); ss.append("-real:"); ss.append(realAmount.toString()); totalAmount = totalAmount.add(realAmount); ss.append("-total:"); ss.append(totalAmount.toString()); address = AddressTool.getStringAddressByBytes(deposit.getAddress()); chain.getLogger().info(ss.toString()); depositMap.merge(address, realAmount, (oldValue, value) -> oldValue.add(value)); } return totalAmount; } /** * 计算委托实际对应的NVT * * @param chain 链信息 * @param deposit 委托信息 * @@param date 结算日期 */ private BigDecimal calcDepositBase(Chain chain, DepositPo deposit, String date, long time, long endHeight) throws NulsException { BigDecimal realDeposit = new BigDecimal(deposit.getDeposit()); double weightSqrt = 1; //如果委托资产为本链主资产则乘以相应的基数 if (deposit.getAssetChainId() == chain.getChainId() && deposit.getAssetId() == chain.getAssetId()) { weightSqrt = chain.getConfig().getLocalAssertBase(); } else { StackingAsset stackingAsset = chainManager.getAssetByAsset(deposit.getAssetChainId(), deposit.getAssetId()); if (stackingAsset.getStopHeight() != 0 && stackingAsset.getStopHeight() < endHeight) { //已过期的资产,不再发放收益 return BigDecimal.ZERO; } else { realDeposit = ConsensusAwardUtil.getRealAmount(chain.getChainId(), realDeposit, stackingAsset, date); weightSqrt = chain.getConfig().getWeight(deposit.getAssetChainId(), deposit.getAssetId()); //流动性计划特殊处理代码 // if (deposit.getAssetChainId() == chain.getChainId() && (deposit.getAssetId() == 32 || deposit.getAssetId() == 33) && config.getV1_7_0Height() > endHeight && endHeight < config.getV1_7_0Height() + 30 * 43200) { if (weightSqrt == 25 && config.getV1_7_0Height() > endHeight && endHeight < config.getV1_7_0Height() + 30 * 43200) { weightSqrt = weightSqrt * 36; } } } //如果为定期委托,则根据定期时间乘以相应基数,定期委托到期之后按活期计算权重 if (deposit.getDepositType() == DepositType.REGULAR.getCode()) { DepositTimeType depositTimeType = DepositTimeType.getValue(deposit.getTimeType()); if (depositTimeType != null && deposit.getTime() + depositTimeType.getTime() >= time) { weightSqrt = weightSqrt * depositTimeType.getWeight(); } } realDeposit = DoubleUtils.mul(realDeposit, new BigDecimal(Math.sqrt(weightSqrt)).setScale(4, BigDecimal.ROUND_HALF_UP)); return realDeposit; } }
/** * 19.删除链表的倒数第N个结点 */ public class LC0010 { class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public ListNode removeNthFromEnd(ListNode head, int n) { if (head == null || n == 0) return head; ListNode preHead = new ListNode(0); preHead.next = head; ListNode first = preHead,second = preHead; for (int i = 0;i<n;i++){ first = first.next; if (first == null ) return head; } while (first.next!=null){ first = first.next; second = second.next; } second.next= second.next.next; return preHead.next; } }
package entrepot.dao.bdd; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import entrepot.bean.dimension.Vendeur; public class BddVendeurDAO extends BddDAO<Vendeur> { public BddVendeurDAO(Connection conn) { super(conn); } @Override public boolean create(Vendeur obj) { int res = 0; try{ String query = "INSERT INTO vendeur (code_vendeur) "+ "VALUES ('"+obj.getCode_vendeur()+"')"; res = this.connect.createStatement().executeUpdate(query); }catch(SQLException e){ e.printStackTrace(); } return (res==1); } @Override public boolean delete(Vendeur obj) { int res = 0; try{ String query = "DELETE FROM vendeur WHERE code_vendeur ='"+obj.getCode_vendeur()+"'"; res = this.connect.createStatement().executeUpdate(query); }catch(SQLException e){ e.printStackTrace(); } return (res==1); } @Override public boolean update(Vendeur obj) { int res = 0; try{ String query = "UPDATE vendeur SET " + "code_vendeur = '"+obj.getCode_vendeur()+"' "+ " WHERE code_vendeur ='"+obj.getCode_vendeur()+"'"; res = this.connect.createStatement().executeUpdate(query); }catch(SQLException e){ e.printStackTrace(); } return (res==1); } @Override public Vendeur find(String id) { Vendeur vendeur = new Vendeur(); try{ ResultSet result = this.connect.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ).executeQuery( "SELECT * FROM vendeur WHERE code_vendeur = '"+id+"'" ); if(result.first()){ vendeur.setCode_vendeur(result.getString("code_vendeur")); } }catch(SQLException e){ e.printStackTrace(); } return vendeur; } }
package diplomski.autoceste.repositories.tutorial; import diplomski.autoceste.models.tutorial.Student; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepostory extends JpaRepository<Student,Integer> { }
package University; public interface CompleteWork { public void doWork(); }
package test; import lombok.Data; import lombok.extern.log4j.Log4j2; @Log4j2 @Data public class TestLombok { private Long id; private String summary; private String description; public String test(){ log.info("TEST"); return "return"; } }
package me.ninabernick.cookingapplication; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.DialogFragment; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.TextView; import com.mikhaellopez.circularprogressbar.CircularProgressBar; public class CountDownDialog extends DialogFragment { private TextView counter; private CircularProgressBar progress; public CountDownDialog(){} public static CountDownDialog newInstance(int millisseconds, int interval) { CountDownDialog f = new CountDownDialog(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("millis", millisseconds); args.putInt("interval", interval); f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_countdowntimer_dialog, container); // Not exactly sure why, but this code is required to get the dialog to have rounded corners if (getDialog() != null && getDialog().getWindow() != null) { getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); } counter = (TextView) view.findViewById(R.id.tvCount); progress = (CircularProgressBar) view.findViewById(R.id.determinateBar); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; final int millis = getArguments().getInt("millis"); int interval = getArguments().getInt("interval"); progress.setProgressMax(millis / 1000); CountDownTimer gameTimer = new CountDownTimer(millis, interval) { @Override public void onTick(long l) { int total_seconds = ((int)Math.round(l/1000.0) - 1); int numberOfHours = (total_seconds % 86400 ) / 3600 ; int numberOfMinutes = ((total_seconds % 86400 ) % 3600 ) / 60; int numberOfSeconds = ((total_seconds % 86400 ) % 3600 ) % 60; String hours; String minutes; String seconds; if (numberOfHours == 0){ hours = ""; } else{ hours = Integer.toString(numberOfHours) + ":"; if (hours.length() == 2) { hours = "0" + hours; } } if (numberOfMinutes == 0){ minutes = ""; } else{ minutes = Integer.toString(numberOfMinutes) + ":"; if (minutes.length() == 2) { minutes = "0" + minutes; } } if ((numberOfHours != 0) || (numberOfMinutes != 0)){ seconds = Integer.toString(numberOfSeconds); if (seconds.length() == 1){ seconds = "0" + seconds; } } else{ seconds = Integer.toString(numberOfSeconds); } counter.setText(hours + minutes + seconds); double float_test= (((double) millis) - ((double) l))/(millis); int time_elapsed = (millis / 1000) - total_seconds; /* * Duration here is set for 1.25 seconds, specifically because each tick is slightly * longer than a second so we want the animation to last longer than each tick so the * animation is always moving or barely stopped. */ progress.setProgressWithAnimation(time_elapsed, 1250); } @Override public void onFinish() { progress.setProgress(millis / 1000); counter.setText("Time's Up!\n Click Anywhere to Exit"); if (isAdded()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel("cookingappid", name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext(), "cookingappid") .setSmallIcon(R.drawable.cooking) .setContentTitle("Timer Complete") .setStyle(new NotificationCompat.BigTextStyle() .bigText("Step timer complete, ready to move onto the next step!")) .setPriority(NotificationCompat.PRIORITY_HIGH) .setDefaults(Notification.DEFAULT_SOUND) .setDefaults(Notification.DEFAULT_VIBRATE); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext()); // notificationId is a unique int for each notification that you must define notificationManager.notify(70987, mBuilder.build()); } // dismiss(); } }; gameTimer.start(); } }
package com.gibran.MaximumFlow; import com.mxgraph.layout.mxCircleLayout; import com.mxgraph.swing.mxGraphComponent; import org.jgrapht.ListenableGraph; import org.jgrapht.ext.JGraphXAdapter; import org.jgrapht.graph.*; import javax.swing.*; import java.awt.*; import java.io.FileNotFoundException; /** * Student Name: Gibran Kasif * IIT ID: 2019176 * UoW ID: w1761211 */ class EdgeWeight extends DefaultWeightedEdge { private int capacity; public EdgeWeight(int capacity) { this.capacity = capacity; } @Override public String toString() { return Double.toString(capacity); } } // Creates and displays a graph public class GraphGUI extends JApplet { private static final Dimension DEFAULT_SIZE = new Dimension(1000, 800); private JGraphXAdapter<String, EdgeWeight> jgxAdapter; public static int[][] GUIGraph; static int GUITotalVertices; @Override public void init() { // create a JGraphT graph ListenableGraph<String, EdgeWeight> g = new DefaultListenableGraph<>(new DirectedWeightedMultigraph<>(EdgeWeight.class)); // create a visualization using JGraph, via an adapter jgxAdapter = new JGraphXAdapter<>(g); jgxAdapter.isAutoSizeCells(); setPreferredSize(DEFAULT_SIZE); mxGraphComponent component = new mxGraphComponent(jgxAdapter); component.getViewport().setBackground(new Color(2,2,102)); component.setToolTips(true); component.getViewport().setOpaque(true); component.getViewport().setBackground(Color.YELLOW); component.setTripleBuffered(true); component.setAutoScroll(true); component.setFocusable(true); component.setConnectable(false); component.getGraph().setAllowDanglingEdges(false); getContentPane().add(component); resize(DEFAULT_SIZE); // creating all the nodes of the graph for (int i = 0; i < GUITotalVertices; i++) { g.addVertex(Integer.toString(i)); } // creating all the edges that exists with Capacities for (int u = 0; u < GUITotalVertices; u++) { int[] startingNode = GUIGraph[u]; for (int v = 0; v < GUITotalVertices; v++) { if (startingNode[v] > 0) { // if a capacity exists g.addEdge(Integer.toString(u), Integer.toString(v), new EdgeWeight(GUIGraph[u][v])); } } } // positioning via jgraphx layouts mxCircleLayout layout = new mxCircleLayout(jgxAdapter); // center the circle int radius = 350; layout.setX0((DEFAULT_SIZE.width / 2.0) - 1 * radius); layout.setY0((DEFAULT_SIZE.height / 2.0) - 1 * radius); layout.setRadius(radius); layout.setMoveCircle(true); layout.execute(jgxAdapter.getDefaultParent()); } public static void main(String[] args) { FileRead fr = new FileRead(); Graph graph = null; try { graph = fr.graphReader("bridge_1.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } graph.printGraph(); int maxFlow =findMaxFlow(graph, 0, graph.getNumberOfNodes()-1); System.out.println("The total maximum flow is " + maxFlow); GUIGraph = graph.getAdjacencyMatrix(); GUITotalVertices = graph.getNumberOfNodes(); graph.printGraph(); GraphGUI applet = new GraphGUI(); applet.init(); JFrame frame = new JFrame(); frame.getContentPane().add(applet); frame.setTitle("Final Residual Graph"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static int findMaxFlow(Graph graph, int source, int sink) { BreadthFirstSearch breadthFirstSearch = new BreadthFirstSearch(); if (source == sink) { //Used for validation, only applied for test classes not the Console. return 0; } int numberOfNodes = graph.getNumberOfNodes(); //Creating a residual graph, a copy of the initial graph Graph residualGraph = graph; //Used to store the path from source to node, for use in BFS. int[] parent = new int[numberOfNodes]; //Initialised to store the maximum flow value int maximumFlow = 0; //Used to count the number of all short paths int numAugmentedPaths = 0; //Loops for each existing path traced from the source to the sink node while(breadthFirstSearch.bfs(residualGraph, source, sink, parent)) { /* Bottle neck of the current path, its set to the largest possible number */ int bottleNeck = Integer.MAX_VALUE; /* Looping backwards through parent[], which finds the residual capacity and stores in the bottleNeck of a path. */ for(int i = sink; i != source; i = parent[i]) { int j = parent[i]; //Finding the minimum flow which can be sent from the existing bottleNeck or the capacity of the new edge bottleNeck = Math.min(bottleNeck, residualGraph.getAdjacencyMatrix()[j][i]); } //Used to update the residual graph for (int i = sink; i != source; i = parent[i]) { int j = parent[i]; residualGraph.getAdjacencyMatrix()[j][i] -= bottleNeck; residualGraph.getAdjacencyMatrix()[i][j] += bottleNeck; } /*Adds up the maximum flow of each path to the maximumFlow which would in the end return the total max flow. */ maximumFlow += bottleNeck; //Counts the number of paths numAugmentedPaths++; System.out.println(); System.out.println("Number of augmented paths: " + numAugmentedPaths); System.out.println("The current flow value: " + bottleNeck); System.out.println("Current max-flow value: " + maximumFlow); } // residualGraph.printGraph(); return maximumFlow; } }
package day07stringmanipulations; import java.util.Scanner; public class Substring01 { public static void main(String[] args) { /* A part of a String is called substring substring() of String class is used for getting a substring from the String We used substring() to get a part of a String by using indexes */ String s1 = "Java is Java"; System.out.println(s1.substring(5));//is Java //Index is inclusive System.out.println(s1.substring(7));// Java System.out.println(s1.substring(0));//Java is Java //How can I get the last character? System.out.println(s1.substring(s1.length() - 1));//a System.out.println(s1.substring(12));//nothing //System.out.println(s1.substring(13));// StringIndexOutOfBoundsException /* We have two type of error messages : 1) While we type our codes we get "red underline! this is called "Compile Time Error" 2) While we type our codes we don't get any red underline bt after running our codes we get red messages on the console, it is "Run TIme Error */ String s2 = "Java is oop language"; System.out.println(s2.substring(0, 3)); //How can I get just i ? System.out.println(s2.substring(5, 6)); /* Ask user to enter to a String If the first and the last character of the String are same print "Wooow!" otherwise, pront "Hmmm!" on the console */ Scanner scan = new Scanner(System.in); System.out.println("Enter a String please"); String str5 = scan.nextLine(); String first = str5.substring(0, 1); String last = str5.toUpperCase().substring(str5.length() - 1); if (first.equals(last)) { System.out.println("Woow!"); } else { System.out.println("Hmmm!"); } } }
package com.example.zadek.fotbalky.Model; import android.arch.persistence.db.SupportSQLiteDatabase; import android.arch.persistence.db.SupportSQLiteOpenHelper; import android.arch.persistence.room.Database; import android.arch.persistence.room.DatabaseConfiguration; import android.arch.persistence.room.InvalidationTracker; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; import android.os.AsyncTask; import android.support.annotation.NonNull; @Database(entities = {Player.class}, version = 1) public abstract class FotbalkyRoomDatabase extends RoomDatabase { public abstract PlayerDao playerDao(); private static FotbalkyRoomDatabase INSTANCE; public static FotbalkyRoomDatabase getDatabase(final Context context) { if (INSTANCE == null) { synchronized (FotbalkyRoomDatabase.class) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), FotbalkyRoomDatabase.class, "fotbalky database").addCallback(databaseCallback).build(); } } } return INSTANCE; } private static RoomDatabase.Callback databaseCallback = new RoomDatabase.Callback() { @Override public void onOpen(@NonNull SupportSQLiteDatabase db) { super.onOpen(db); new PopulateDbAsync(INSTANCE).execute(); } }; private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> { private final PlayerDao dao; PopulateDbAsync(FotbalkyRoomDatabase db) { dao = db.playerDao(); } @Override protected Void doInBackground(Void... voids) { return null; } } }
package com.pisen.ott.launcher.localplayer.video; /** * 视频对象 */ public class VideoInfo { String name; String url; long duration; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
package infpp; public class Bubble extends OceanObject { public Bubble() { // TODO Auto-generated constructor stub } public Bubble(int[] position, String name) { super(position, name); // TODO Auto-generated constructor stub } public Bubble(int x, int y, String name) { super(x, y, name); // TODO Auto-generated constructor stub } @Override public void move() { // TODO Auto-generated method stub super.getPosition()[0] += 10; } }
package com.accolite.au.services; import com.accolite.au.dto.BatchDTO; import com.accolite.au.dto.SuccessResponseDTO; import java.util.List; public interface BatchService { BatchDTO addBatch(BatchDTO batch); List<BatchDTO> getAllBatches(); BatchDTO getBatch(int batchId); SuccessResponseDTO deleteBatch(int batchId); BatchDTO updateBatch(BatchDTO batchDTO) throws IllegalAccessException; }
package com.example.android.model; import com.example.android.Board; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Abstract class representing a chess Piece. * @author Krysti Leong, April Dizon */ public abstract class Piece implements Serializable { public static final long serialVersionUID = GameSaver.serialVersionUID; public String name; public String color; public boolean hasMoved; private Position position; private List<Position> directionVectors = null; private int imageResource; /** * Constructor for Piece * @param name Type of the piece, ie. "King", "Queen", etc. * @param color Color of the piece, either "White" or "Black." * @param position Current position of this piece. */ public Piece(String name, String color, Position position){ this.name = name; this.color = color; this.hasMoved = false; this.position = position; } protected void setImageResource(int imageResourceID){ this.imageResource = imageResourceID; } public int getImageResource(){ return imageResource; } /** * @return This piece's current position. */ public Position getPosition(){ return position; } /** * set hasMoved to the boolean value * @param hasMoved */ public void setHasMoved(boolean hasMoved){ this.hasMoved = hasMoved; } /** * Set this piece's current position. * @param p Position representing the current position. */ public void setPosition(Position p){ this.position = p; } /** * Set this piece's current position. * @param rank Rank of the current position. * @param file File of the current position. */ public void setPosition(int rank, int file){ setPosition(new Position(rank,file)); } /** * @return This piece's color. */ public String getColor(){ return color; } /** * Get this piece's direction vectors, which are vectors representing this piece's movement paths. * These vectors are added to the piece through the children's constructors. * @return List of the vectors, or null if there are no vectors. */ public List<Position> getDirectionVectors(){ return directionVectors; } /** * Set this piece's direction vectors. * @param directions List of the vectors. */ public void setDirectionVectors(List<Position> directions){ directionVectors = directions; } /** * See if this piece can reach its destination from its current position by checking the following positions: * 1. The path to the destination from its current position is in its valid movements. * 2. The path is clear of any other pieces. * @param chessBoard Board of the game. * @param destination Position of the destination. * @return True if this piece can reach the destination, false if it cannot. */ public boolean canReachDestination(Board chessBoard, Position destination){ if (!isValidMovement(chessBoard, destination)){ return false; } Position obstacle = isPathClear(chessBoard, destination); if (obstacle != null){ Board.Cell[][] cells = chessBoard.getCells(); // This piece can reach the destination if the there's an obstacle, ONLY // if the obstacle is at the destination, and its the opposing color if (destination.equals(obstacle)){ if (cells[obstacle.rank][obstacle.file].piece.color.equals(getColor())){ return false; } } } return true; } /** * Check if the path to the destination from its current position is in its valid movements. * Each movement will depend on the piece implementing it. * @param chessBoard Board of the game. * @param destination Position of the destination. * @return True if this piece can reach the destination, false if it cannot. */ public abstract boolean isValidMovement(Board chessBoard, Position destination); /** * Check if the path to the destination is clear of any obstacles (other chess pieces). * Note that this also checks if the destination is clear or capturable. * @param chessBoard Board of the game. * @param destination Position of the destination. * @return Null if the path is clear. Else, return the Position of an obstacle in the way. */ public abstract Position isPathClear(Board chessBoard, Position destination); /** * Get all the Positions this piece can move to, given its current position. * @param chessBoard Board of the game. * @return List of positions this piece can move to. */ public abstract List<Position> getAllMoves(Board chessBoard); /** * Used by a piece's getAllMoves(). Use the piece's vectors, and find all the moves it can move to * by simply checking if the position at (current position + vector) has an obstacle. * All moves that are free of obstacles are added to the returned list. * @param chessBoard Board of the game. * @return List of Positions that this piece can move to. */ protected List<Position> getAllDiscreteMoves(Board chessBoard){ List<Position> moves = new ArrayList<Position>(); List<Position> directions = getDirectionVectors(); // Iterate through this piece's directions. for (Position direction : directions){ Position destination = Position.add(getPosition(), direction); // Make sure not to go beyond the board. if (!Position.withinBounds(destination)){ continue; } // If there are no obstacles, add this to the moves! Position obstacle = isPathClear(chessBoard, destination); if (obstacle == null){ moves.add(destination); } else{ moves.add(destination); // If there's an obstacle, then you can move to this position // only if capture is possible // Board.Cell[][] cells = chessBoard.getCells(); // Piece obstaclePiece = cells[obstacle.rank][obstacle.file].piece; // if (obstaclePiece != null){ // if (!obstaclePiece.color.equals(getColor())){ // moves.add(destination); // } // } } } // We're done! if (moves.size() == 0){ return null; } else{ return moves; } } /** * Used by a piece's getAllMoves. Use the piece's vectors, and find all the positions it can * move to by first finding the furthest positions on the board this piece can get to, depending * on its current position, then checking if there are any obstacles in between the current position * and the furthest position. All positions free of obstacles are returned in this list. * @param chessBoard Board of the game. * @return List of Positions that this piece can move to. */ protected List<Position> getAllContinuousMoves(Board chessBoard){ // Setup Position source = getPosition(); Board.Cell[][] board = chessBoard.getBoard(); List<Position> movements = new ArrayList<Position>(); List<Position> directions = getDirectionVectors(); // Find the furthest cells that this piece can travel to and add them to a list. List<Position> bounds = new ArrayList<Position>(); for (Position direction : directions){ bounds.add(Position.getMaxDistance(direction, source)); } // Attempt to travel to these positions. for (int i = 0; i < bounds.size(); i++){ // Check if the path is clear between this max position. Position obstacle = isPathClear(chessBoard, bounds.get(i)); List<Position> newMovements; // If it's not clear, then add the positions that are between the source, up to this obstacle. if (obstacle != null){ newMovements = source.getPositionsBetween(directions.get(i), obstacle); movements.add(obstacle); // Depending on the color of the obstacle, this piece can still travel to the obstacle's position // It cannot move any further though. // if (!board[obstacle.rank][obstacle.file].piece.color.equals(getColor())){ // movements.add(obstacle); // } } // Else, add all the movements between the source and the max position. else{ newMovements = source.getPositionsBetweenMax(directions.get(i)); } movements.addAll(newMovements); } // If no movements are found, return null. if (movements.size() == 0){ return null; } else{ return movements; } } /** * Used by a piece's isPathClear(). Find if the path between this piece's current position and the * destination by checking each position between the current and the destination, as well as the * destination. Note that a piece at the destination is not an obstacle if it has the opposing color. * @param chessBoard Board of the game. * @param destination Position of the destination. * @return Null if the path is clear. Else, return the Position of an obstacle in the way. */ protected Position isContinuousPathClear(Board chessBoard, Position destination){ // Create a vector to express the direction from the starting position to the destination Board.Cell[][] board = chessBoard.getBoard(); Position source = getPosition(); Position distance = Position.distance(source, destination); int rank = 0; int file = 0; if (distance.rank < 0){ rank = 1; } else if (distance.rank > 0){ rank = -1; } if (distance.file < 0){ file = 1; } else if (distance.file > 0){ file = -1; } // Use the vector to iterate to the destination int obstacles = 0; Position direction = new Position(rank, file); Position bounds = Position.add(destination, direction); for (Position i = Position.add(direction, source); (!Position.equals(i, bounds) && Position.withinBounds(i)); i = Position.add(i, direction)){ Board.Cell cell = board[i.rank][i.file]; if (cell.piece != null){ // There is something in the way! return i; // if (!cell.piece.color.equals(getColor()) && obstacles != 1){ // // If there's an obstacle of the opposing color, and it's the first obstacle, this piece // // can still travel to this spot, because this spot can be captured. // obstacles++; // continue; // } // else{ // return i; // } } } return null; } /** * Used by a piece's isPathClear(). Find if this piece can reach its destination by simply checking if the * destination is clear of any pieces of the same color. * @param chessBoard Board of the game. * @param destination Position of the destination. * @return Null if the path is clear. Else, return the Position of an obstacle in the way. */ protected Position isDiscretePathClear(Board chessBoard, Position destination){ Board.Cell[][] board = chessBoard.getBoard(); Piece piece = board[destination.rank][destination.file].piece; if (piece != null){ return destination; // If this piece has the same color, then it is an obstacle. // if (piece.color.equals(getColor())){ // return destination; // } } return null; } @Override public String toString() { return "" + Character.toLowerCase(this.color.charAt(0)) + (this.name=="Knight"? "N" : this.name.charAt(0)); } }
import test.thread.MyRunnable; import test.thread.Thread1; public class MultiThread { // WaitTest.java的源码 class ThreadA extends Thread{ public ThreadA(String name) { super(name); } @Override public void run() { synchronized (this) { System.out.println(Thread.currentThread().getName() + " call notify()"); // 唤醒当前的wait线程 notify(); } } } public static void main(String[] args){ MultiThread multiThread = new MultiThread(); ThreadA t1 = multiThread.new ThreadA("t1"); synchronized(t1) { try { // 启动“线程t1” System.out.println(Thread.currentThread().getName()+" start t1"); t1.start(); // 主线程等待t1通过notify()唤醒。 System.out.println(Thread.currentThread().getName()+" wait()"); t1.wait(); System.out.println(Thread.currentThread().getName()+" continue"); } catch (InterruptedException e) { e.printStackTrace(); } } Thread t4 = new Thread1(); Thread t2 = new Thread(new MyRunnable(5)); t1.start(); t2.start(); Thread t3 = new Thread(new Runnable(){ @Override public void run() { System.out.println("bbb"); }}); t3.start(); // ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,50,100L,TimeUnit.MILLISECONDS,new LinkedBlockingDeque<Runnable>()); // //匿名内部类,省略接口实现类的类名,直接重写方法。省略接口名和方法名就是lambda表达式 // /* // * MyRunnable myrunnable = new MyRunnable(); // * Thread t3 = new Thread(myrunnable); // * t3.start(); // */ // new Runnable(){ @Override public void run() { System.out.println("aaa"); } }.run(); // // ((Runnable) () -> System.out.println("aaa")).run(); // // Future<String> future = threadPoolExecutor.submit((Callable)()->{ // System.out.println("hello"); // return "hello"; // }); } }
package com.pykj.annotation.demo.annotation.configure.configuration; import com.pykj.annotation.project.entity.MyPerson; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * 测试configuration */ public class MyTest { /** * 首先取出方法名称作为Bean的name * 优先取出自定义的Bean的name */ @Test public void test() { ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); Object person1 = context.getBean("person"); Object person2 = context.getBean("person"); System.out.println(person1 == person2); MyPerson person = context.getBean(MyPerson.class); System.out.println(person); } }
package com.pibs.form; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import com.pibs.constant.ActionConstant; import com.pibs.constant.MapConstant; import com.pibs.constant.MiscConstant; import com.pibs.constant.ModuleConstant; import com.pibs.constant.ParamConstant; import com.pibs.model.AdditionalServices; import com.pibs.model.AdditionalServicesCategory; import com.pibs.service.ServiceManager; import com.pibs.service.ServiceManagerImpl; /** * * @author dward * @since 07August2017 */ public class AdditionalServicesFormBean extends PIBSFormBean { private static final long serialVersionUID = 1L; private int id; private int additionalServicesCategoryId; private String description; private String remarks; private String fee; private String criteria; private String category; private int noOfPages; private int currentPage; private List<AdditionalServices> modelList; private boolean transactionStatus; private String transactionMessage; private List<AdditionalServicesCategory> additionalServicesCategoryList; public AdditionalServicesFormBean() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public List<AdditionalServicesCategory> getAdditionalServicesCategoryList() { return additionalServicesCategoryList; } public void setAdditionalServicesCategoryList( List<AdditionalServicesCategory> additionalServicesCategoryList) { this.additionalServicesCategoryList = additionalServicesCategoryList; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCriteria() { return criteria; } public void setCriteria(String criteria) { this.criteria = criteria; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getNoOfPages() { return noOfPages; } public void setNoOfPages(int noOfPages) { this.noOfPages = noOfPages; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public List<AdditionalServices> getModelList() { return modelList; } public void setModelList(List<AdditionalServices> modelList) { this.modelList = modelList; } public boolean isTransactionStatus() { return transactionStatus; } public void setTransactionStatus(boolean transactionStatus) { this.transactionStatus = transactionStatus; } public String getTransactionMessage() { return transactionMessage; } public void setTransactionMessage(String transactionMessage) { this.transactionMessage = transactionMessage; } public void populateFormBean(AdditionalServices model) { setId(model.getId()); setAdditionalServicesCategoryId(model.getAdditionalServicesCategoryId()); setDescription(model.getDescription()); setRemarks(model.getRemarks()); setFee(model.getFee()!=null ? model.getFee().toPlainString() : "0.00"); } public AdditionalServices populateModel (AdditionalServicesFormBean formbean) { AdditionalServices model = new AdditionalServices(); model.setId(formbean.getId()); model.setAdditionalServicesCategoryId(formbean.getAdditionalServicesCategoryId()); model.setDescription(formbean.getDescription()); model.setRemarks(formbean.getRemarks()); model.setFee(formbean.getFee()!=null && formbean.getFee().trim().length()>0 ? new BigDecimal(formbean.getFee()).setScale(2, BigDecimal.ROUND_HALF_UP) : new BigDecimal("0.00"));//2 decimal place formbean.setFee(model.getFee().toPlainString()); return model; } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub ActionErrors errors = new ActionErrors(); String command = (String) request.getParameter("command"); if (command!=null && (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE) || command.equalsIgnoreCase(ParamConstant.AJAX_UPDATE))) { boolean flag = false; if (this.getAdditionalServicesCategoryId() == 0) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("mf.category.req")); flag = true; } if (this.getDescription()==null || this.getDescription().trim().length() < 1) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("mf.description.req")); flag = true; } //check if price is numeric try { Double.parseDouble(this.getFee()!=null && this.getFee().trim().length()>0 ? this.getFee() : "0.00"); } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("mf.fee.num")); flag = true; } if (flag) { try { //get list from session populateDropdownListFromSession(request); } catch(Exception e) {} } } return errors; } public int getAdditionalServicesCategoryId() { return additionalServicesCategoryId; } public void setAdditionalServicesCategoryId(int additionalServicesCategoryId) { this.additionalServicesCategoryId = additionalServicesCategoryId; } public void populateDropdownList(HttpServletRequest request) throws Exception{ HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, ModuleConstant.ADDITIONAL_SERVICES_CATEGORY); dataMap.put(MapConstant.ACTION, ActionConstant.GET_ACTIVE_DATA); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { @SuppressWarnings("unchecked") List<AdditionalServicesCategory> qryList = (List<AdditionalServicesCategory>) resultMap.get(MapConstant.CLASS_LIST); setAdditionalServicesCategoryList(qryList); if (request.getSession().getAttribute(MiscConstant.MF_ADDITIONAL_SERVICES_CATEGORY_LIST)!=null) { request.getSession().removeAttribute(MiscConstant.MF_ADDITIONAL_SERVICES_CATEGORY_LIST); } //save to session request.getSession().setAttribute(MiscConstant.MF_ADDITIONAL_SERVICES_CATEGORY_LIST, qryList); } } public void populateDropdownListFromSession(HttpServletRequest request) throws Exception{ @SuppressWarnings("unchecked") List<AdditionalServicesCategory> qryList = (List<AdditionalServicesCategory>) request.getSession().getAttribute(MiscConstant.MF_ADDITIONAL_SERVICES_CATEGORY_LIST); if (qryList!=null) { setAdditionalServicesCategoryList(qryList); } else { populateDropdownList(request); } } public String getFee() { return fee; } public void setFee(String fee) { this.fee = fee; } }
package com.andtinder.demo; import com.andtinder.model.BaseCardModel; public class DifferentCard extends BaseCardModel { private String title; private String text; public DifferentCard(String title, String text) { this.title = title; this.text = text; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
package com.techboon.service; import com.techboon.domain.Organization; import com.techboon.domain.User; import com.techboon.repository.OrganizationRepository; import com.techboon.repository.UserRepository; import com.techboon.security.AuthoritiesConstants; import com.techboon.security.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static com.techboon.domain.User_.firstName; /** * Service Implementation for managing Organization. */ @Service @Transactional public class OrganizationService { private final Logger log = LoggerFactory.getLogger(OrganizationService.class); private final OrganizationRepository organizationRepository ; private final UserRepository userRepository; public OrganizationService(OrganizationRepository organizationRepository, UserRepository userRepository) { this.organizationRepository = organizationRepository; this.userRepository = userRepository; } /** * Save a organization. * * @param organization the entity to save * @return the persisted entity */ public Organization save(Organization organization) { log.debug("Request to save Organization : {}", organization); return organizationRepository.save(organization); } /** * Get all the organizations. * * @param pageable the pagination information * @return the list of entities */ @Transactional(readOnly = true) public Page<Organization> findAll(Pageable pageable) { log.debug("Request to get all Organizations"); return organizationRepository.findAll(pageable); } /** * Get one organization by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public Organization findOne(Long id) { log.debug("Request to get Organization : {}", id); return organizationRepository.findOne(id); } /** * Delete the organization by id. * * @param id the id of the entity */ public void delete(Long id) { log.debug("Request to delete Organization : {}", id); organizationRepository.delete(id); } /** * 获取当前用户可授权的医院 * @return */ public List<Organization> getAuthorizedOrganizations(){ if ( SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN ) || SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.OPERATOR )){ // return organizationRepository.findAll(); } List<Organization> list = new ArrayList<>(); String currentUser = SecurityUtils.getCurrentUserLogin().get(); Optional<User> user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().get() ); if ( user.isPresent()) { list.addAll(user.get().getOrganizations()); } return list; } }
package br.com.transactions.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.transactions.dto.TransactionDataTransferObject; import br.com.transactions.service.TransactionService; @RestController @RequestMapping(path = "api/transaction/") public class TransactionController { @Autowired private TransactionService service; @PostMapping("save") public ResponseEntity<Void> save( @Validated @RequestBody TransactionDataTransferObject requestDTO) { service.save(requestDTO); return ResponseEntity.ok().build(); } @GetMapping("find") public ResponseEntity<List<TransactionDataTransferObject>> findAll() { return ResponseEntity.ok(service.findAll()); } @GetMapping("/scheduling") public ResponseEntity<String> scheduling() { return ResponseEntity.ok("OK"); } }
package com.example.demo.models.dao; import com.example.demo.models.entity.TipoArchivo; import org.springframework.data.repository.CrudRepository; public interface DITipoArchivo extends CrudRepository<TipoArchivo, Long> { }
package hw10.task1; public class PrintableDemo { public static void main(String[] args) { Printable[] publications = new Printable[10]; publications[0] = new Book("book1title"); publications[1] = new Book("book2title"); publications[2] = new Book("book3title"); publications[3] = new Book("book4title"); publications[4] = new Magazine("magaz1title"); publications[5] = new Magazine("magaz2title"); publications[6] = new Book("book5title"); publications[7] = new Magazine("magaz3title"); publications[8] = new Magazine("magaz4title"); publications[9] = new Magazine("magaz5title"); for (Printable prnt : publications) { prnt.print(); } System.out.println("\n\n--printMagazines()-----------"); Magazine.printMagazines(publications); } }
package com.himanshu.poc.spring.samples.springbootwebreactive.controller.v2; import com.himanshu.poc.spring.samples.springbootwebreactive.repository.UserRepository; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.function.server.RequestPredicate; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; public class RouterConfig { @Bean RouterFunction<?> routes(UserHandler userHandler) { return RouterFunctions.route(RequestPredicates.GET("/user/v2/"), userHandler::all) .andRoute(RequestPredicates.GET("/user/v2/{id}"), userHandler::byId) .andRoute(RequestPredicates.GET("/user/v2/event/stream"), userHandler::steamEvents); } }
package db.essence; import db.essence.Film; import db.essence.User; public class Review implements DaoId { private Film films; private User users; private String text; private double mark; private long id; public Review setFilms(Film films) { this.films = films; return this; } public Review setUsers(User users) { this.users = users; return this; } public Review setText(String text) { this.text = text; return this; } public Review setMark(double mark) { this.mark = mark; return this; } public Review setId(long id) { this.id = id; return this; } public Film getFilms() { return films; } public User getUsers() { return users; } public String getText() { return text; } public double getMark() { return mark; } public long getId() { return id; } }
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ package com.microsoft.office365.meetingfeedback.view; import android.content.Context; import android.content.Intent; import android.support.v4.app.FragmentManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RatingBar; import android.widget.TextView; import com.microsoft.office365.meetingfeedback.CalendarActivity; import com.microsoft.office365.meetingfeedback.MeetingDetailActivity; import com.microsoft.office365.meetingfeedback.R; import com.microsoft.office365.meetingfeedback.model.meeting.EventDecorator; import java.util.List; public class EventsRecyclerViewAdapter extends RecyclerView.Adapter<EventsRecyclerViewAdapter.EventsViewHolder> { private static final String TAG = "EventsRecyclerViewAdapter"; private final List<EventDecorator> mDisplayEvents; private Context mContext; public EventsRecyclerViewAdapter(Context context, List<EventDecorator> displayEvents) { mContext = context; mDisplayEvents = displayEvents; } public EventDecorator getItem(int i) { return mDisplayEvents.get(i); } @Override public EventsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view = LayoutInflater.from(mContext).inflate(R.layout.event_view, viewGroup, false); return new EventsViewHolder(view); } @Override public void onBindViewHolder(EventsViewHolder eventsViewHolder, final int i) { final EventDecorator event = getItem(i); eventsViewHolder.mItemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, MeetingDetailActivity.class); intent.putExtra(MeetingDetailActivity.EVENT_ID_EXTRA, getItem(i).mEventId); mContext.startActivity(intent); } }); eventsViewHolder.mEventName.setText(event.mSubject); eventsViewHolder.mEventHost.setText(event.mOrganizerName); eventsViewHolder.mEventDate.setText(event.mFormattedDate); eventsViewHolder.mEventTime.setText(event.mFormattedTime); eventsViewHolder.mEventRatingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fragmentManager = ((CalendarActivity)mContext).getSupportFragmentManager(); RatingDialogFragment.newInstance(event.mEventId).show(fragmentManager, TAG); } }); event.setupEventDisplay(mContext, eventsViewHolder); } @Override public int getItemCount() { return mDisplayEvents.size(); } public class EventsViewHolder extends RecyclerView.ViewHolder { public final TextView mEventName; public final TextView mEventHost; public final TextView mEventDate; public final TextView mEventTime; public final RatingBar mEventRatingBar; public final Button mEventRatingButton; public final TextView mRatedLabel; public final View mItemView; public final TextView mRatingsCount; public EventsViewHolder(View itemView) { super(itemView); mItemView = itemView; mEventName = (TextView) itemView.findViewById(R.id.event_name); mEventHost = (TextView) itemView.findViewById(R.id.event_host); mEventDate = (TextView) itemView.findViewById(R.id.event_date); mEventTime = (TextView) itemView.findViewById(R.id.event_time); mRatedLabel = (TextView) itemView.findViewById(R.id.average_rating_label); mEventRatingBar = (RatingBar) itemView.findViewById(R.id.rating_bar); mEventRatingButton = (Button) itemView.findViewById(R.id.rate_button); mRatingsCount = (TextView) itemView.findViewById(R.id.ratings_count); } } }
package exemplos.aula13; public class TesteMetodosString { public static void main(String[] args) { String s1 = "olá mundo!!!"; char[] charArray = new char[5]; // uso de length System.out.printf("s1: %s", s1); System.out.printf("%nComprimento de s1: %d", s1.length()); System.out.printf("%nA string reversa é: "); //uso do char at for (int count = s1.length() - 1; count >= 0; count--) { System.out.printf("%c ", s1.charAt(count)); } //uso do get chars s1.getChars(0, 5, charArray, 0); System.out.printf("%nO array de chars é: "); for (char character : charArray) { System.out.print(character); } System.out.println(); //equals e == String s2 = "Teste"; String s3 = "Teste", s4 = s3; String s5 = new String(s4); String s6 = new String("Teste"); System.out.println(s2.equals("Teste")); System.out.println(s2.equals(s3)); System.out.println(s2.equals(s4)); System.out.println(s2.equals(s5)); System.out.println(s2.equals(s6)); System.out.println(s2 == s3); System.out.println(s2 == s4); System.out.println(s2 == s5); System.out.println(s2 == s6); //equalsIgnoreCase String s7 = "testE"; System.out.println(s7.equalsIgnoreCase(s5)); //compareTo String s8 = "aaa"; String s9 = "aab"; String s10 = "aaa"; System.out.println(s8.compareTo(s9)); System.out.println(s9.compareTo(s10)); System.out.println(s8.compareTo(s10)); //regionMatches System.out.println(s8.regionMatches(0, s9, 0, 2)); System.out.println(s8.regionMatches(0, s9, 0, 3)); //Starts with String[] strings = {"started", "starting", "ended", "ending"}; // testa o método startsWith for (String string : strings) { if (string.startsWith("st")) { System.out.printf("\"%s\" começa com \"st\"%n", string); } } System.out.println(); // testa o método startsWith iniciando da posição 2 de string for (String string : strings) { if (string.startsWith("art", 2)) { System.out.printf("\"%s\" começa com \"art\" na posição 2%n", string); System.out.println(); } } //endsWith for (String string : strings) { if (string.endsWith("ed")) System.out.printf("\"%s\" terminam com \"ed\"%n", string); } //teste indexOf e lastIndexof String letras = "abcdefghijklmonpqrstuvwxyzabc"; System.out.println(letras.indexOf('a')); System.out.println(letras.indexOf('z')); System.out.println(letras.indexOf('5')); System.out.println(letras.indexOf('a', 10)); System.out.println(letras.indexOf("abc")); System.out.println(letras.indexOf("abc", 5)); System.out.println(letras.lastIndexOf("abc")); System.out.println(letras.lastIndexOf('c')); System.out.println(letras.lastIndexOf('c', 10)); //substring System.out.println(letras.substring(1, 5)); System.out.println(letras.substring(10)); //concatenação String feliz = "Feliz "; String aniversario = "Aniversario!"; System.out.println(feliz.concat(aniversario)); System.out.println(feliz); //replace e replaceAll String hello = "hello"; System.out.println(hello.replace('l', 'L')); System.out.println(hello.replaceAll("llo", "LLO")); System.out.println(hello); //toLowerCase, toUpperCase, trim e toCharArray String test = " Teste de Letras "; System.out.println(test.toLowerCase()); System.out.println(test.toUpperCase()); System.out.println(test.trim()); char [] caracteres = test.toCharArray(); for(char a : caracteres) { System.out.println(a); } //split String tk = "a;b;cd;ef"; String [] tokens = tk.split(";"); for(String t : tokens) { System.out.println(t); } //valueOf boolean f = false; float fl = 0.000f; long l = 100000l; Object o = "abc"; System.out.println(String.valueOf(f)); System.out.println(String.valueOf(fl)); System.out.println(String.valueOf(l)); System.out.println(String.valueOf(caracteres)); System.out.println(String.valueOf(o)); } }
package cn.wormholestack.eventnicetest.listener; import cn.wormholestack.eventnice.annotation.EventReceive; /** * @description: IntegerListener * @Author MRyan * @Date 2021/10/8 23:01 * @Version 1.0 */ public class IntegerListener { private Integer lastMessage; @EventReceive public void listen(Integer integer) { lastMessage = integer; System.out.println("IntegerListener Message:" + lastMessage); } public Integer getLastMessage() { return lastMessage; } }
public class SortingApp { public static void main(String[] args) { int[] maxSizes = { 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000 }; for (int maxSize : maxSizes) { System.out.println("Size " + maxSize); Array arr = new Array(maxSize); arr.randomInit(maxSize); Array arr1 = new Array(arr); Array arr2 = new Array(arr); Array arr3 = new Array(arr); long startTime1 = TimeUtils.now(); arr1.bubbleSort(); long endTime1 = TimeUtils.now(); System.out.println("Time of bubble sort: " + (endTime1 - startTime1) + "ms"); long startTime2 = TimeUtils.now(); arr2.selectionSort(); long endTime2 = TimeUtils.now(); System.out.println("Time of selection sort: " + (endTime2 - startTime2) + "ms"); long startTime3 = TimeUtils.now(); arr3.insertionSort(); long endTime3 = TimeUtils.now(); System.out.println("Time of insertion sort: " + (endTime3 - startTime3) + "ms"); System.out.println("--------------------------------------------------"); } } }
package com.twu.biblioteca; import java.io.PrintStream; public class WelcomeMessagePrinter { private final PrintStream printStream; public WelcomeMessagePrinter(PrintStream printStream) { this.printStream = printStream; } public void printWelcomeMessage() { printStream.println("Welcome to Biblioteca. Your one-stop-shop for great book titles in Bangalore!"); } }
/* * @(#) IPkiStoreService.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ebms.pkistore.service; import com.esum.appframework.service.IBaseService; /** * * @author sjyim@esumtech.com * @version $Revision: 1.6 $ $Date: 2009/01/16 08:25:40 $ */ public interface IPkiStoreService extends IBaseService { Object searchPkiAlias(Object object); Object selectPkiStoreList(Object object); Object checkPkiStoreDuplicate(Object object); Object selectXMLDsigInfoFK(Object object); Object selectXMLEncInfoFK(Object object); Object selectHTTPAuthInfoFK(Object object); Object selectPkiNodeList(Object object); }
//Holly Bancroft //6/20/2020 public class PurchasedPart extends Part { private double handlingCost; private double purchasePrice; private String vendor; public static final String DEFAULT_VENDOR_NAME = "no vendor name"; public static final double DEFAULT_PURCHASE_PRICE = 0; public static final double DEFAULT_HANDLING_COST = 0; public PurchasedPart(int newID) { this(newID, DEFAULT_DESCRIPTION, DEFAULT_SELL_PRICE, DEFAULT_HANDLING_COST, DEFAULT_PURCHASE_PRICE, DEFAULT_VENDOR_NAME); } public PurchasedPart(int newID, double newHandlingCost, double newPurchPrice, String newVendor) { this(newID, DEFAULT_DESCRIPTION, DEFAULT_SELL_PRICE, newHandlingCost, newPurchPrice, newVendor); } public PurchasedPart (int newID, String newDesc, double newSellPrice, double newHandlingCost, double newPurchPrice, String newVendor) { super(newID, newDesc, newSellPrice); this.handlingCost = DEFAULT_HANDLING_COST; this.purchasePrice = DEFAULT_PURCHASE_PRICE; this.vendor = DEFAULT_VENDOR_NAME; this.setHandlingCost(newHandlingCost); this.setPurchasePrice(newPurchPrice); this.setVendor(newVendor); } @Override public double getTotalCost() { return super.getTotalCost() + purchasePrice + handlingCost; } public double getHandlingCost() { return handlingCost; } public double getPurchasePrice() { return purchasePrice; } public String getVendor() { return vendor; } public void setHandlingCost(double newHandlingCost) { if(newHandlingCost >= 0) { this.handlingCost = newHandlingCost; } } public void setPurchasePrice(double newPurchPrice) { if (newPurchPrice >= 0) { this.purchasePrice = newPurchPrice; } } public void setVendor(String newVendor) { if(newVendor != null && newVendor.length() > 0) { this.vendor = newVendor; } } @Override public String toString() { return super.toString() + getClass() + " Handling Cost: " + handlingCost + " Purchase Price" + purchasePrice + " Vendor: " + vendor; } }
package org.aksw.autosparql.tbsl.algorithm; import org.aksw.autosparql.tbsl.algorithm.sparql.Template; import org.aksw.autosparql.tbsl.algorithm.templator.Templator; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.net.URL; import java.util.Collections; import org.aksw.autosparql.tbsl.algorithm.learning.TemplateInstantiation; import org.aksw.autosparql.tbsl.algorithm.learning.TbslDbpedia; import org.aksw.autosparql.tbsl.algorithm.knowledgebase.DBpediaKnowledgebase; import com.hp.hpl.jena.query.ResultSet; import org.aksw.autosparql.tbsl.algorithm.learning.NoTemplateFoundException; import org.dllearner.kb.sparql.SparqlEndpoint; import org.aksw.autosparql.commons.qald.EvaluationUtils; public class Qald4Test { private static List<String> readQuestions(File file){ List<String> questions = new ArrayList<String>(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); NodeList questionNodes = doc.getElementsByTagName("question"); String question; for(int i = 0; i < questionNodes.getLength(); i++){ Element questionNode = (Element) questionNodes.item(i); for(int j=0;j<questionNode.getElementsByTagName("string").getLength();j++){ Element questionStringNode = (Element) questionNode.getElementsByTagName("string").item(j); if(questionStringNode.getAttribute("lang").equals("zh")){ //Read question //question = ((Element)questionStringNode.getElementsByTagName("string").item(0)).getChildNodes().item(0).getNodeValue().trim(); question = ((Element)questionStringNode).getChildNodes().item(0).getNodeValue().trim(); questions.add(question); } } } } catch (DOMException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return questions; } private static List<String> readQueries(File file){ List<String> queries = new ArrayList<String>(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); NodeList questionNodes = doc.getElementsByTagName("question"); String query; for(int i = 0; i < questionNodes.getLength(); i++){ Element questionNode = (Element) questionNodes.item(i); query = ((Element)questionNode.getElementsByTagName("query").item(0)).getChildNodes().item(0).getNodeValue().trim(); queries.add(query); } } catch (DOMException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return queries; } // boolean Compare(ResultSet model, ResultSet ref){ // QuerySolution s = model.nextSolution(); // // // return false; // } /** * @param args */ public static void main(String[] args) { SparqlEndpoint dbpediaEndpoint; //File file = new File("../DBpediaQA/benchmark/qald4/qald-4_multilingual_train_withanswers_linklabel.xml"); File file = new File("../DBpediaQA/benchmark/qald4/qald-4_multilingual_test_withanswers_linklabel.xml"); List<String> questions = readQuestions(file); List<String> queries = readQueries(file); //only a few questions can be answered int[] ans = new int[] {45,}; // int[] ans = new int[200]; // // for(int i=0;i<200;i++){ // ans[i] = i; // } ArrayList<Integer> corrects = new ArrayList<Integer>(); ArrayList<Integer> incorrects = new ArrayList<Integer>(); ArrayList<Integer> notemps = new ArrayList<Integer>(); try{ dbpediaEndpoint = new SparqlEndpoint(new URL("http://dbpedia.org/sparql"),Collections.<String>singletonList(""), Collections.<String>emptyList()); } catch (MalformedURLException e){ throw new RuntimeException(e); } int cnt = 0; int incnt = 0; for(int i: ans ){ if(i >= questions.size()) continue; String question = questions.get(i); String query = queries.get(i); System.out.println("Question"+i+": " + question); try { TemplateInstantiation ti = TbslDbpedia.INSTANCE.answerQuestion(question); String sparqlQueryString = ti.getQuery(); double accuracy = EvaluationUtils.accuracy(sparqlQueryString,query, dbpediaEndpoint); if(accuracy == 1.0){ System.out.println("Correct"); cnt++; corrects.add(i+1); }else{ ResultSet crs = DBpediaKnowledgebase.INSTANCE.querySelect(query); ResultSet rs = DBpediaKnowledgebase.INSTANCE.querySelect(sparqlQueryString); incorrects.add(i+1); System.out.println("Incorrect answer:"); if(crs!= null && crs.hasNext()) System.out.println(crs.nextSolution().toString()); if(rs!= null && rs.hasNext()) System.out.println(rs.nextSolution().toString()); System.out.println(query); if(ti != null) System.out.println(ti.getQuery()); } }catch (NoTemplateFoundException e){ e.printStackTrace(); notemps.add(i+1); } catch (Exception e) { e.printStackTrace(); incnt++; } } System.out.println("total: " + questions.size()); System.out.println("correct: " + cnt); System.out.println("incorrect: " + (questions.size() - cnt)); System.out.println("correct:"); for(int i: corrects){ System.out.print(i+", "); } System.out.println(); System.out.println("incorrect:" + incorrects.size()); for(int i: incorrects){ System.out.print(i+", "); } System.out.println(); System.out.println("No template:" + notemps.size()); for(int i: notemps){ System.out.print(i+", "); } System.out.println(); } }
/* InterpretContext.java Purpose: Description: History: Sat Sep 17 16:59:44 2005, Created by tomyeh Copyright (C) 2004 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.web.servlet.dsp.impl; import java.io.Writer; import org.zkoss.xel.XelContext; import org.zkoss.xel.FunctionMapper; import org.zkoss.xel.util.SimpleXelContext; import org.zkoss.web.servlet.dsp.*; import org.zkoss.web.servlet.dsp.action.Action; /** * Holds the context for interpreting an {@link Interpretation}. * * @author tomyeh */ class InterpretContext { final DspContext dc; final InterpretResolver resolver; XelContext xelc; /** The action being processing, or null if no such action. */ Action action; /** Constructs an interpret context. */ InterpretContext(DspContext dc) { this.dc = dc; this.resolver = new InterpretResolver(dc.getVariableResolver()); } void init(FunctionMapper mapper) { if (this.xelc != null) throw new IllegalArgumentException(); this.xelc = new SimpleXelContext(this.resolver, mapper); } }
package com.ifeng.recom.mixrecall.common; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * Created by lilg1 on 2017/11/20. */ @Configuration @EnableAutoConfiguration @ComponentScan(basePackageClasses = MixCommonConfig.class) public class MixCommonConfig { }
package com.app.drashti.drashtiapp; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.app.drashti.drashtiapp.Utiliiyy.AppUtilty; import com.app.drashti.drashtiapp.Utiliiyy.Constant; import com.app.drashti.drashtiapp.Utiliiyy.JSONParser; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class ChangePasswordActivity extends AppCompatActivity { private TextView txtFormName; private EditText edtEmailId; private EditText edtPassword; private EditText edtOldPasswoed; private EditText edtNewPassword; private EditText edtRepetPassword; private Button btnChangePassword; private AppUtilty appUtilty; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.change_password); appUtilty = new AppUtilty(ChangePasswordActivity.this); txtFormName = (TextView)findViewById( R.id.txtFormName ); edtEmailId = (EditText)findViewById( R.id.edtEmailId ); edtPassword = (EditText)findViewById( R.id.edtPassword ); edtOldPasswoed = (EditText)findViewById( R.id.edtOldPasswoed ); edtNewPassword = (EditText)findViewById( R.id.edtNewPassword ); edtRepetPassword = (EditText)findViewById( R.id.edtRepetPassword ); btnChangePassword = (Button)findViewById( R.id.btnChangePassword ); edtEmailId.setText(appUtilty.getUserData().getU_email()); btnChangePassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Valide()){ doChangePassword(); } } }); } public void doChangePassword(){ makeToast("Please Wait....."); new Thread(new Runnable() { @Override public void run() { HashMap<String, String> map = new HashMap<String, String>(); map.put("method", "change_password"); map.put("old_password",edtOldPasswoed.getText().toString()); map.put("new_password",edtNewPassword.getText().toString()); map.put("user_id",appUtilty.getUserData().getU_ID()); final JSONObject result; result = JSONParser.doGetRequest(map, Constant.server); Log.e("Result,", result + ""); runOnUiThread(new Runnable() { @Override public void run() { try { if (result.getString("status").equals("true")) { makeToast(result.getString("message")); finish(); } else { Toast.makeText(ChangePasswordActivity.this, result.getString("message"), Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }); } }).start(); } public boolean Valide() { String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; if (edtOldPasswoed.getText().toString().length() < 4) { makeToast("Old Password must be minimum 4 char. long"); return false; } else if (edtNewPassword.getText().toString().length() < 4) { makeToast("New Password must be minimum 4 char. long"); return false; }else if (edtRepetPassword.getText().toString().length() < 4) { makeToast("Repet Pssword must be minimum 4 char. long"); return false; }else if (!edtNewPassword.getText().toString().equalsIgnoreCase(edtRepetPassword.getText().toString())) { makeToast("New Password does not match with repet password "); return false; } return true; } public void makeToast(String name) { Toast.makeText(ChangePasswordActivity.this, name, Toast.LENGTH_LONG).show(); } }
import java.util.*; import java.text.*; /** * Class ini merupakan Class yang digunakan untuk melihat status pesanan * dan juga mengeset pesanan * * * @author Whisnu Samudra * @version 1/3/2018 */ public class Pesanan { // instance variables - replace the example below with your own private double biaya; private double jumlahHari; private Customer pelanggan; private boolean isDiproses; private boolean isSelesai; private Room kamar; private Date tanggalPesan; /** * Constructor for objects of class Pesanan */ public Pesanan(double jumlahHari, Customer pelanggan, Room kamar, int year, int month, int date) { this.jumlahHari=jumlahHari; this.pelanggan=pelanggan; this.kamar=kamar; this.biaya = jumlahHari * getRoom().getDailyTariff(); this.tanggalPesan=new GregorianCalendar(year,month,date).getTime(); // initialise instance variables } public Pesanan(double jumlahHari, Customer pelanggan, Room kamar,Date tanggalPesan) { this.jumlahHari=jumlahHari; this.pelanggan=pelanggan; this.kamar=kamar; this.tanggalPesan=tanggalPesan; } /** * Method untuk mendapatkan biaya yang telah diset * * * @return biaya type double */ public double getBiaya() { return biaya; } public double getJumlahHari() { return jumlahHari; } /** * Method untuk mendapatkan pelanggan yang telah diset * * * @return pelanggan type Customer */ public Customer getPelanggan() { return pelanggan; } /** * Method untuk mendapatkan status yang sedang diproses * * * @return isDiproses type boolean */ public boolean getStatusDiproses() { return isDiproses; } /** * Method untuk mendapatkan status yang telah selesai * * * @return isSelesai type boolean; */ public boolean getStatusSelesai() { return isSelesai; } public Room getRoom() { return kamar; } public Date getTanggalPesan() { return tanggalPesan; } /** * Method untuk mengeset biaya * * @param biaya type double * */ public void setBiaya(double biaya) { biaya = getBiaya() * getRoom().getDailyTariff(); } public void setJumlahHari(double jumlahHari) { this.jumlahHari = jumlahHari; //untuk mengeset biaya yang akan dibayar } /** * Method untuk mengeset pelanggan * * @param baru type Customer * */ public void setPelanggan(Customer pelanggan) { this.pelanggan=pelanggan; } /** * Method untuk mengeset status diproses * * @param diproses type Boolean * */ public void setStatusDiproses(boolean diproses) { isDiproses=diproses; } /** * Method untuk mengeset status selesai * * @param diproses type boolean * */ public void setStatusSelesai(boolean selesai) { isSelesai=selesai; } public void setRoom(Room kamar) { this.kamar=kamar; } public void setTanggalPesan(Date tanggalPesan) { this.tanggalPesan=tanggalPesan; } /** * Method untuk mencetak biaya * * @param biaya type double * */ public void printData() { System.out.println("Nama: " + getPelanggan().getNama()); System.out.println("Status layanan diproses: " + isDiproses); System.out.println("Status layanan selesai: " + isSelesai); System.out.println("Jumlah Hari: " + jumlahHari); System.out.println("Biaya: " +getBiaya()); } }
package com.jrz.bettingsite.player; import com.jrz.bettingsite.team.Team; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.Optional; @Controller public class PlayerController { @Autowired PlayerService playerService; @RequestMapping(path = "/players") public @ResponseBody Iterable<Player> getAllPlayers(){ return playerService.findAll(); } @RequestMapping(path = "/players/{id}") public @ResponseBody Optional<Player> findById(@PathVariable Long id){ return playerService.findById(id); } @RequestMapping(method = RequestMethod.POST, path = "/players") public @ResponseBody void savePlayer(@RequestBody Player player){ playerService.savePlayer(player); } @RequestMapping(method = RequestMethod.PUT, path = "/players/{id}") public @ResponseBody void updatePlayer(@RequestBody Player player, @PathVariable Long id){ playerService.updatePlayer(player, id); } @RequestMapping(method = RequestMethod.DELETE, path = "/players/{id}") public @ResponseBody void deletePlayer(@RequestBody Player player, @PathVariable Long id){ playerService.deleteTeam(player); } }
package com.fgtit.access; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fgtit.access.R; import com.fgtit.app.ActivityList; import com.fgtit.app.UserItem; import com.fgtit.app.UsersList; import com.fgtit.utils.ExtApi; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; 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.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.os.Build; public class EmployeeActivity extends Activity { private ListView listView1,listView2; private List<Map<String, Object>> mData1,mData2; private ImageView photoImage; private int pos=0; private UserItem person=null; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_employee); this.getActionBar().setDisplayHomeAsUpEnabled(true); Bundle bundle = new Bundle(); bundle = this.getIntent().getExtras(); pos = bundle.getInt("pos"); //int pos=this.getIntent().getIntExtra("pos",0); if(pos<UsersList.getInstance().usersList.size()) person=UsersList.getInstance().usersList.get(pos); photoImage=(ImageView)findViewById(R.id.imageView1); if(person.photo.length()>1000){ photoImage.setImageBitmap(Bytes2Bimap(ExtApi.Base64ToBytes(person.photo))); }else{ byte[] photo=ActivityList.getInstance().LoadPhotoByID(String.valueOf(person.userid)); if(photo!=null) photoImage.setImageBitmap(Bytes2Bimap(photo)); else photoImage.setImageBitmap(ExtApi.LoadBitmap(getResources(),R.drawable.guest)); } listView1=(ListView) findViewById(R.id.listView1); SimpleAdapter adapter1 = new SimpleAdapter(this,getData1(),R.layout.listview_empitem, new String[]{"title","info"}, new int[]{R.id.title,R.id.info}); listView1.setAdapter(adapter1); listView2=(ListView) findViewById(R.id.listView2); SimpleAdapter adapter2 = new SimpleAdapter(this,getData2(),R.layout.listview_empitem, new String[]{"title","info"}, new int[]{R.id.title,R.id.info}); listView2.setAdapter(adapter2); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.employee, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch(id){ case android.R.id.home: this.finish(); return true; case R.id.action_delete: if(pos>=0){ UsersList.getInstance().DeleteUser(person.userid); ActivityList.getInstance().DeleteUserByID(String.valueOf(person.userid)); UsersList.getInstance().usersList.remove(pos); //GlobalData.getInstance().SaveUsersList(); Intent resultIntent = new Intent(); //resultIntent.putExtra("reload", 1); setResult(0, resultIntent); this.finish(); } //this.finish(); return true; } return super.onOptionsItemSelected(item); } private List<Map<String, Object>> getData1() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String, Object> map = new HashMap<String, Object>(); if(person!=null){ map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_username)+":"); map.put("info", person.username); list.add(map); map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_userid)+":"); map.put("info", person.userid); list.add(map); } mData1=list; return list; } private List<Map<String, Object>> getData2() { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); if(person!=null){ Map<String, Object> map = new HashMap<String, Object>(); /* map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_statu)+":"); map.put("info", "Normal"); list.add(map); */ map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_usertype)+":"); switch(person.usertype){ case 0: map.put("info", getString(R.string.txt_selact)); break; case 1: map.put("info", getString(R.string.txt_selict)); break; } list.add(map); map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_gender)+":"); switch(person.gender){ case 0: map.put("info", getString(R.string.txt_male)); break; case 1: map.put("info", getString(R.string.txt_female)); break; } list.add(map); map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_phone)+":"); map.put("info", person.phone); list.add(map); map = new HashMap<String, Object>(); map.put("title", getString(R.string.txt_remark)+":"); map.put("info", ""); list.add(map); } mData2=list; return list; } private Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } }
package com.company.config.persistence; import com.company.typemapping.JsonPostgreSQLDialect; import com.zaxxer.hikari.HikariDataSource; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; @Slf4j @Configuration @EnableJpaAuditing @EntityScan(basePackages = {"com.company"}) @EnableJpaRepositories({"com.company"}) @EnableTransactionManagement public class PersistenceConfiguration { @Autowired private DatabaseConfig databaseConfig; @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("com.company"); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } @Bean public DataSource dataSource(){ HikariDataSource dataSource = new HikariDataSource(); dataSource.setMaximumPoolSize(5); dataSource.setConnectionTimeout(5000L); dataSource.setJdbcUrl(databaseConfig.getUrl()); dataSource.setUsername(databaseConfig.getUsername() ); dataSource.setPassword(databaseConfig.getPassword()); return dataSource; } private Properties additionalProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.dialect", JsonPostgreSQLDialect.class.getName()); return properties; } }
package pieces; import java.util.HashSet; import java.util.Set; /** * This class keeps track of the languages spoken in the world today */ public class WorldLanguages { private Set<String> languages = new HashSet<>(); public WorldLanguages() { languages.add("English"); languages.add("Spanish"); languages.add("Russian"); languages.add("Chinese"); } public boolean addLanguage(String lang){ return languages.add(lang); } @Override public String toString() { return "WorldLanguages{" + "languages=" + languages + '}'; } }
package com.jt.common.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class HttpClientService { private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class); @Autowired(required=false) private CloseableHttpClient httpClient; //对象 @Autowired(required=false) private RequestConfig requestConfig; //定义连接的参数 /** * 编辑HttpClient中的get请求 * 1.考虑是否含有参数/考虑字符集编码问题 * url:localhost:8091/addUser?id=1&name=tom * 2.参数如何传递 * 面对不同的用户 都需要传递参数,使用Map数据结构 * */ public String doGet(String uri,Map<String,String> params, String charset){ String result = null; //1.判断是否含有参数 try { if(params !=null){ URIBuilder builder = new URIBuilder(uri); for (Map.Entry<String,String> entry: params.entrySet()) { builder.addParameter(entry.getKey(), entry.getValue()); } //uri= localhost:8091/add?id=1&name=tom uri = builder.build().toString(); System.out.println("获取请求参数:"+uri); } //2.判断字符集是否为null if(charset ==null){ charset = "UTF-8"; } //3.创建请求对象 HttpGet httpGet = new HttpGet(uri); httpGet.setConfig(requestConfig); //设定请求的参数 //4.发起请求 CloseableHttpResponse response = httpClient.execute(httpGet); if(response.getStatusLine().getStatusCode() == 200){ result = EntityUtils.toString(response.getEntity(),charset); } } catch (Exception e) { e.printStackTrace(); } return result; } public String doGet(String uri){ return doGet(uri, null, null); } public String doGet(String uri,Map<String,String> params){ return doGet(uri, params, null); } /*实现httpClient中的post方法 * 知识回顾 : * 1.get localhost:8091/add?id=1&name=tom * 2.post localhost:8091/add * 流处理方式(id=1,name=tom) * */ public String doPost(String uri,Map<String,String> params,String charset){ //1.创建提交方式 HttpPost httpPost = new HttpPost(uri); //2.设定请求的参数 httpPost.setConfig(requestConfig); //3.设定字符集 if(charset == null){ charset = "UTF-8"; } //4.为post提交准备参数 if(params !=null){ //4.1 创建一个提交的List集合对象 List<NameValuePair> parameters = new ArrayList<NameValuePair>(); //4.2为list集合赋值 for (Map.Entry<String,String> entry : params.entrySet()) { parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { //4.3创建提交对象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, charset); //4.4将提交的实体添加到post请求中 httpPost.setEntity(formEntity); } catch (Exception e) { e.printStackTrace(); } } //5.发起http请求 String result = null; try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if(httpResponse.getStatusLine().getStatusCode() == 200){ result = EntityUtils.toString(httpResponse.getEntity(),charset); } } catch (Exception e) { e.printStackTrace(); } return result; } public String doPost(String uri){ return doPost(uri,null,null); } public String doPost(String uri,Map<String,String> params){ return doPost(uri, params,null); } }
package org.squonk.options; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import java.io.Serializable; import java.util.Map; /** * Created by timbo on 15/01/16. */ @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") @JsonInclude(JsonInclude.Include.NON_EMPTY) public interface TypeDescriptor<T> extends Serializable { Class<T> getType(); void putOptionValue(Map<String, Object> options, String key, T value); T readOptionValue(Map<String, Object> options, String key); }
package com.flyusoft.apps.jointoil.action; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.flyusoft.apps.jointoil.entity.Compressor; import com.flyusoft.apps.jointoil.entity.Index; import com.flyusoft.apps.jointoil.entity.MachineRoom; import com.flyusoft.apps.jointoil.service.CompressorService; import com.flyusoft.apps.jointoil.service.IndexService; import com.flyusoft.apps.jointoil.service.MachineRoomService; import com.flyusoft.apps.jointoil.service.WellService; import com.flyusoft.apps.jointoil.util.JointOilInitentity; import com.flyusoft.common.action.CrudActionSupport; import com.flyusoft.common.utils.web.struts2.Struts2Utils; import com.google.common.collect.Lists; @Controller @Scope("prototype") public class MachineRoomIndexAction extends CrudActionSupport<Index>{ private JointOilInitentity jointOilInitentity=JointOilInitentity.getInstance(); private static final long serialVersionUID = 1829968134573595197L; private Index index; private String machineRoomId; @Autowired private MachineRoomService machineRoomService; @Autowired private IndexService indexService; @Autowired private WellService wellService; private MachineRoom machineRoom; private List<Index> indexList; private List<String> indexIdList; private List<String> indexNameList; private List<String> indexCodeList; private List<String> unitList; private List<Integer> statusList; private List<Double> maxList; private List<Double> minList; private List<Double> minLimitList; private List<Double> maxLimitList; private List<Integer> orderByList; @Override public Index getModel() { return index; } @Override public String list() throws Exception { machineRoomId = Struts2Utils.getParameter("roomId"); machineRoom = machineRoomService.getMachineRoom(machineRoomId); if (machineRoom != null) { indexList = machineRoom.getIndexs(); } return SUCCESS; } @Override public String save() throws Exception { MachineRoom machineRoom = machineRoomService.getMachineRoom(machineRoomId); List<Index> newIndexList = Lists.newArrayList(); List<String> deleteIdList = Lists.newArrayList();// 需要删除的指标id集合 boolean isNull = indexIdList != null && indexNameList != null&& orderByList != null && indexCodeList != null; if (isNull) { List<Index> oldIndexs = machineRoom.getIndexs();// 查找以前所有的指标 if (oldIndexs != null) { for (Index oldIndex : oldIndexs) { boolean isHave = indexIdList.contains(oldIndex.getId()); if (!isHave) { deleteIdList.add(oldIndex.getId()); } } } if (deleteIdList.size() > 0) { indexService.delete(deleteIdList);// 删除所有前台不包含的指标ID } for (int i = 0; i < indexNameList.size(); i++) { Index tmpindex = null; if (indexIdList.get(i) != null && !"".equals(indexIdList.get(i))) { tmpindex = indexService.getIndex(indexIdList.get(i)); } else { tmpindex = new Index(); } tmpindex.setIndexName(indexNameList.get(i)); tmpindex.setIndexCode(indexCodeList.get(i)); tmpindex.setUnit(unitList.get(i)); tmpindex.setStatus(statusList.get(i)); tmpindex.setOrderBy(orderByList.get(i)); if(statusList.get(i)==0){ tmpindex.setMax(maxList.get(i)); tmpindex.setMin(minList.get(i)); tmpindex.setMaxLimit(maxLimitList.get(i)); tmpindex.setMinLimit(minLimitList.get(i)); }else{ tmpindex.setMax(null); tmpindex.setMin(null); tmpindex.setMaxLimit(null); tmpindex.setMinLimit(null); } tmpindex.setRoom(machineRoom); wellService.saveIndex(tmpindex); newIndexList.add(tmpindex); } } //machineRoom.setIndexs(newIndexList); //machineRoomService.saveMachineRoom(machineRoom); addActionMessage("保存成功"); jointOilInitentity.setMachineRoomList(machineRoomService.searchAllMachineRoomAndCompressorAndIndex()); return RELOAD; } @Override public String input() throws Exception { return INPUT; } @Override public String delete() throws Exception { return null; } @Override protected void prepareModel() throws Exception { } public String getMachineRoomId() { return machineRoomId; } public void setMachineRoomId(String machineRoomId) { this.machineRoomId = machineRoomId; } public List<Index> getIndexList() { return indexList; } public void setIndexIdList(List<String> indexIdList) { this.indexIdList = indexIdList; } public void setIndexNameList(List<String> indexNameList) { this.indexNameList = indexNameList; } public void setIndexCodeList(List<String> indexCodeList) { this.indexCodeList = indexCodeList; } public void setUnitList(List<String> unitList) { this.unitList = unitList; } public void setStatusList(List<Integer> statusList) { this.statusList = statusList; } public void setMaxList(List<Double> maxList) { this.maxList = maxList; } public void setMinList(List<Double> minList) { this.minList = minList; } public void setMinLimitList(List<Double> minLimitList) { this.minLimitList = minLimitList; } public void setMaxLimitList(List<Double> maxLimitList) { this.maxLimitList = maxLimitList; } public void setOrderByList(List<Integer> orderByList) { this.orderByList = orderByList; } }
package com.ngocdt.tttn.entity; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "ReceiptionDetail") @Data @NoArgsConstructor @IdClass(ReceiptionDetailKey.class) public class ReceiptionDetail { @Id @Column(name = "productID",nullable = false) private int productID; @Id @Column(name = "receiptionID",nullable = false) private int receiptionID; @Column private int quantity; @Column private float price; @ManyToOne(fetch =FetchType.EAGER) @MapsId("productID") @JoinColumn(name = "productID") private Product product; @ManyToOne(fetch =FetchType.EAGER) @MapsId("receiptionID") @JoinColumn(name = "receiptionID") private Receiption receiption; public int getProductID() { return productID; } public void setProductID(int productID) { this.productID = productID; } public int getReceiptionID() { return receiptionID; } public void setReceiptionID(int receiptionID) { this.receiptionID = receiptionID; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public Receiption getReceiption() { return receiption; } public void setReceiption(Receiption receiption) { this.receiption = receiption; } }
package com.leon.meepo.tinyioc; /** * Created by songlin01 on 17/7/21. */ public interface BeanDefinitionReader { void loadBeanDefinitions(String location) throws Exception; }
import java.util.HashMap; public class Coll2 { public static void main(String[] args) { // TODO Auto-generated method stub HashMap<Emp,Project> map= new HashMap(); Emp e1=new Emp(111,"AAA",10000); Emp e2=new Emp(111,"AAA",10000); Emp e3=new Emp(113,"CCC",30000); Emp e4=new Emp(114,"DDD",25000); Emp e5=new Emp(115,"EEE",30000); Project p1=new Project(1001,"qwer","asdf","zxc"); Project p2=new Project(1002,"poi","lkjh","mnb"); Project p3=new Project(1003,"vbc","ghfj","rtyu"); Project p4=new Project(1004,"zxmn","alkj","qpo"); Project p5=new Project(1005,"zdti","mjyt","rfb"); map.put(e1, p1); map.put(e2, p2); map.put(e3, p3); map.put(e4, p4); map.put(e5, p5); System.out.println(e1.equals(e2)); System.out.println(e1.hashCode()); System.out.println(e2.hashCode()); System.out.println(map); } }
package fabio.sicredi.evaluation.repositories; import fabio.sicredi.evaluation.domain.Poll; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; public interface PollRepository extends CrudRepository<Poll, Long> { @Modifying @Query("update Poll p set p.status = :status where p.id = :id") @Transactional int updateStatus(@Param(value = "id") final Long id, @Param(value = "status") final String status); }
/* ------------------------------------------------------------------------------ * 软件名称:BB语音 * 公司名称:乐多科技 * 开发作者:Yongchao.Yang * 开发时间:2016年3月3日/2016 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.ace.web.service * fileName:ShowDao.java * ------------------------------------------------------------------------------- */ package com.ace.database.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import com.ace.database.ds.DBReleaser; import com.rednovo.ace.constant.Constant; import com.rednovo.ace.entity.LiveShow; import com.rednovo.tools.DateUtil; /** * @author yongchao.Yang/2016年3月3日 */ public class ShowDao extends BasicDao { /** * @param connection */ public ShowDao(Connection connection) { super(connection); } /** * 开播 * * @param show * @return * @author Yongchao.Yang * @since 2016年3月3日下午3:37:25 */ public String addShow(LiveShow show) { PreparedStatement ps = null; String exeRes = Constant.OperaterStatus.FAILED.getValue(); try { ps = this.getConnnection().prepareStatement("insert into show_list_live(userId,sortCnt,title,position,startTime,createTime,schemaId) values(?,?,?,?,?,?,?)"); String time = DateUtil.getTimeInMillis(); ps.setString(1, show.getUserId()); ps.setString(2, "0"); ps.setString(3, show.getTitle()); ps.setString(4, show.getPosition()); ps.setString(5, time); ps.setString(6, DateUtil.getStringDate()); ps.setString(7, time); if (ps.executeUpdate() > 0) { exeRes = Constant.OperaterStatus.SUCESSED.getValue(); } } catch (Exception e) { this.getLogger().error("[用户" + show.getUserId() + "开播数据保存失败]", e); return Constant.OperaterStatus.FAILED.getValue(); } finally { DBReleaser.release(ps); } return exeRes; } /** * 获取所有的在线直播 * * @param page * @param pageSize * @return * @author Yongchao.Yang * @since 2016年4月21日下午10:37:35 */ public ArrayList<LiveShow> getShow(int page, int pageSize) { PreparedStatement ps = null; ArrayList<LiveShow> list = new ArrayList<LiveShow>(); ResultSet res = null; try { ps = this.getConnnection().prepareStatement("select userId,sortCnt,title,position,startTime,createTime,schemaId from show_list_live order by id desc limit ?,?"); ps.setInt(1, (page - 1) * pageSize); ps.setInt(2, pageSize); res = ps.executeQuery(); while (res != null && res.next()) { LiveShow li = new LiveShow(); li.setUserId(res.getString("userId")); li.setSortCnt(res.getLong("sortCnt")); li.setTitle(res.getString("title")); li.setPosition(res.getString("position")); li.setStartTime(res.getString("startTime")); li.setLength(res.getString("length")); li.setSupportCnt(res.getString("supportCnt")); li.setCoinCnt(res.getString("coinCnt")); li.setShareCnt(res.getString("shareCnt")); li.setCreateTime(res.getString("createTime")); li.setSchemaId(res.getString("schemaId")); list.add(li); } } catch (Exception e) { this.getLogger().error("[获取所有直播数据失败]", e); } finally { DBReleaser.release(ps, res); } return list; } /** * 获取所有待同步直播数据 * * @param page * @param pageSize * @return * @author Yongchao.Yang * @since 2016年3月8日下午8:15:21 */ public ArrayList<String> updateSort(int page, int pageSize) { if (page <= 0) { page = 1; } ArrayList<String> list = new ArrayList<String>(); PreparedStatement ps = null; ResultSet res = null; String sql = "select userId from show_list_live order by sortCnt DESC limit ?,?"; try { ps = this.getConnnection().prepareStatement(sql); ps.setInt(1, (page - 1) * pageSize); ps.setInt(2, pageSize); res = ps.executeQuery(); while (res != null && res.next()) { list.add(res.getString("userId")); } return list; } catch (Exception e) { this.getLogger().error("[获取直播列表信息失败]", e); } finally { DBReleaser.release(ps, res); } return null; } /** * 刷新直播间实时统计数据 * * @param id * @param supportCnt * @param coinCnt * @param shareCnt * @return * @author Yongchao.Yang * @since 2016年3月8日下午8:14:10 */ public String refreshData(String userId, String length, String memberCnt, String fansCnt, String supportCnt, String coinCnt, String shareCnt) { PreparedStatement ps = null; String exeRes = Constant.OperaterStatus.FAILED.getValue(); try { ps = this.getConnnection().prepareStatement("update show_list_live set length=?,memberCnt=?,fansCnt=?, supportCnt=?,coinCnt=?,shareCnt=? where userId=?"); ps.setString(1, length); ps.setString(2, memberCnt); ps.setString(3, fansCnt); ps.setString(4, supportCnt); ps.setString(5, coinCnt); ps.setString(6, shareCnt); ps.setString(7, userId); if (ps.executeUpdate() > 0) { exeRes = Constant.OperaterStatus.SUCESSED.getValue(); } } catch (Exception e) { this.getLogger().error("[更新" + userId + "直播实时数据]", e); return Constant.OperaterStatus.FAILED.getValue(); } finally { DBReleaser.release(ps); } return exeRes; } /** * 获取新增直播数据,并同步到缓存中 * * @param showId * @param maxCnt * @return * @author Yongchao.Yang * @since 2016年3月8日下午8:09:04 */ public ArrayList<LiveShow> getSynLiveShow(String synId, int maxCnt) { ArrayList<LiveShow> list = new ArrayList<LiveShow>(); PreparedStatement ps = null; ResultSet res = null; String sql = "select userId,sortCnt,title,position,startTime,length,supportCnt,coinCnt,shareCnt,createTime,schemaId from show_list_live where schemaId>? limit ?"; try { ps = this.getConnnection().prepareStatement(sql); ps.setString(1, synId); ps.setInt(2, maxCnt); res = ps.executeQuery(); while (res != null && res.next()) { LiveShow li = new LiveShow(); li.setUserId(res.getString("userId")); li.setSortCnt(res.getLong("sortCnt")); li.setTitle(res.getString("title")); li.setPosition(res.getString("position")); li.setStartTime(res.getString("startTime")); li.setLength(res.getString("length")); li.setSupportCnt(res.getString("supportCnt")); li.setCoinCnt(res.getString("coinCnt")); li.setShareCnt(res.getString("shareCnt")); li.setCreateTime(res.getString("createTime")); li.setSchemaId(res.getString("schemaId")); list.add(li); } return list; } catch (Exception e) { this.getLogger().error("[获取待同步直播信息失败]", e); } finally { DBReleaser.release(ps, res); } return null; } public LiveShow getLiveShow(String userId) { LiveShow li = new LiveShow(); PreparedStatement ps = null; ResultSet res = null; String sql = "select userId,title,position,startTime,length,memberCnt,fansCnt,supportCnt,coinCnt,shareCnt,createTime,schemaId from show_list_live where userId=?"; try { ps = this.getConnnection().prepareStatement(sql); ps.setString(1, userId); res = ps.executeQuery(); if (res != null && res.next()) { li.setUserId(res.getString("userId")); li.setTitle(res.getString("title")); li.setPosition(res.getString("position")); li.setStartTime(res.getString("startTime")); li.setLength(res.getString("length")); li.setMemberCnt(res.getString("memberCnt")); li.setFansCnt(res.getString("fansCnt")); li.setSupportCnt(res.getString("supportCnt")); li.setCoinCnt(res.getString("coinCnt")); li.setShareCnt(res.getString("shareCnt")); li.setCreateTime(res.getString("createTime")); } } catch (Exception e) { this.getLogger().error("[获取直播" + userId + "信息失败]", e); } finally { DBReleaser.release(ps, res); } return li; } /** * 结束本次直播 * * @param showId * @return * @author Yongchao.Yang * @since 2016年3月8日下午9:23:38 */ public String moveShowData(String userId) { PreparedStatement last_ps = null, his_ps = null, live_remove_ps = null; String live_remove_sql = "delete from show_list_live where userId=?"; String last_add_sql = "insert into show_list_last(userId,title,position,startTime,length,supportCnt,coinCnt,shareCnt,createTime) SELECT userId,title, position,startTime, length,supportCnt,coinCnt,shareCnt,createTime FROM show_list_live WHERE userId=?"; String his_add_sql = "insert into show_list_history(userId,title,position,startTime,length,supportCnt,coinCnt,shareCnt,createTime) SELECT userId,title, position,startTime, length,supportCnt,coinCnt,shareCnt,createTime FROM show_list_live WHERE userId=?"; try { // 添加上次记录 last_ps = this.getConnnection().prepareStatement(last_add_sql); last_ps.setString(1, userId); if (last_ps.executeUpdate() <= 0) { return Constant.OperaterStatus.FAILED.getValue(); } // 添加历史记录 his_ps = this.getConnnection().prepareStatement(his_add_sql); his_ps.setString(1, userId); if (his_ps.executeUpdate() <= 0) { return Constant.OperaterStatus.FAILED.getValue(); } // 删除本次直播 live_remove_ps = this.getConnnection().prepareStatement(live_remove_sql); live_remove_ps.setString(1, userId); if (live_remove_ps.executeUpdate() <= 0) { return Constant.OperaterStatus.FAILED.getValue(); } } catch (Exception e) { this.getLogger().error("[将直播数据移入历史操作失败]", e); return Constant.OperaterStatus.FAILED.getValue(); } finally { DBReleaser.release(last_ps); DBReleaser.release(live_remove_ps); DBReleaser.release(his_ps); } return Constant.OperaterStatus.SUCESSED.getValue(); } }
package com.xdc; import java.io.IOException; import java.net.URI; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapred.lib.InputSampler; import org.apache.hadoop.mapred.lib.InputSampler.RandomSampler; import org.apache.hadoop.mapred.lib.TotalOrderPartitioner; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class LocalMaxMain { public static class TokenizerMapper extends Mapper<LongWritable, BytesWritable, LongWritable, BytesWritable> { public void map(LongWritable key, BytesWritable value, Context context) throws IOException, InterruptedException { context.write(key, value); } } public static class IntSumReducer extends Reducer<LongWritable, BytesWritable, LongWritable, BytesWritable> { public void reduce(LongWritable key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException { Iterator<BytesWritable> ite = values.iterator(); int temp; float t; BytesWritable bw = ite.next(); byte[] bytes = bw.getBytes(); int length = bw.getLength(); float[] max = new float[length / 4]; for (int j = 0; j < length; j += 4) { temp = (0xff & bytes[j]) | (0xff00 & (bytes[j + 1] << 8)) | (0xff0000 & (bytes[j + 2] << 16)) | (0xff000000 & (bytes[j + 3] << 24)); t = Float.intBitsToFloat(temp); max[j / 4] = t; } while (ite.hasNext()) { bw = ite.next(); bytes = bw.getBytes(); for (int j = 0; j < length; j += 4) { temp = (0xff & bytes[j]) | (0xff00 & (bytes[j + 1] << 8)) | (0xff0000 & (bytes[j + 2] << 16)) | (0xff000000 & (bytes[j + 3] << 24)); t = Float.intBitsToFloat(temp); if (t > max[j / 4]) max[j / 4] = t; } } int data; byte[] maxbytes = new byte[length]; for (int i = 0; i < length; i += 4) { data = Float.floatToIntBits(max[i / 4]); maxbytes[i] = (byte) (data & 0xff); maxbytes[i + 1] = (byte) ((data & 0xff00) >> 8); maxbytes[i + 2] = (byte) ((data & 0xff0000) >> 16); maxbytes[i + 3] = (byte) ((data & 0xff000000) >> 24); } context.write(key, new BytesWritable(maxbytes)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); if (args.length != 6) { System.out .println("Usage: [inputPath1] [inputPath2] [outputPath] [reduceTaskNum] [mapCompress] [reduceCompress]"); return; } if ("y".equals(args[4])) { conf.setBoolean("mapreduce.output.fileoutputformat.compress", true); } if ("y".equals(args[5])) { conf.setClass("mapreduce.output.fileoutputformat.compress.codec", GzipCodec.class, CompressionCodec.class); conf.set("mapreduce.map.output.compress", "true"); } conf.setBoolean("dfs.support.append", true); String[] temp = args[2].split("/"); Job job = Job.getInstance(conf, "localMaxnoCom_" + temp[temp.length - 1]); //Job job = Job.getInstance(conf, "localMax");// Job(Configuration conf, // String jobName) 设置job名称和 job.setJarByClass(LocalMaxMain.class); job.setMapperClass(TokenizerMapper.class); // 为job设置Mapper类 // job.setCombinerClass(IntSumReducer.class); //为job设置Combiner类 job.setReducerClass(IntSumReducer.class); // 为job设置Reduce类 job.setOutputKeyClass(LongWritable.class); // 设置输出key的类型 job.setOutputValueClass(BytesWritable.class);// 设置输出value的类型 job.setInputFormatClass(BinaryInputFormat.class); job.setOutputFormatClass(BinaryOutputFormat.class); job.setPartitionerClass(TotalOrderPartitioner.class); int tasksNum = Integer.parseInt(args[3]); job.setNumReduceTasks(tasksNum); String s1 = args[0]; String s2 = args[1]; String inputPath1 = "hdfs://master:9000" + s1; String inputPath2 = "hdfs://master:9000" + s2; // Path partitionFile = new // Path("hdfs://192.168.1.200:9000/partitionFile"); String s3 = args[2]; String outputPath = "hdfs://master:9000" + s3; FileInputFormat.addInputPath(job, new Path(inputPath1)); FileInputFormat.addInputPath(job, new Path(inputPath2)); FileOutputFormat.setOutputPath(job, new Path(outputPath));// 为map-reduce任务设置OutputFormat实现类 // 设置输出路径 long startMili = System.currentTimeMillis();// 当前时间对应的毫秒数 if (tasksNum > 1) { // RandomSampler第一个参数表示key会被选中的概率,第二个参数是一个选取samples数,第三个参数是最大读取input // splits数 RandomSampler<LongWritable, BytesWritable> sampler = new InputSampler.RandomSampler<LongWritable, BytesWritable>( 0.1, 1000, 10); // 设置partition file全路径到conf // TotalOrderPartitioner.setPartitionFile(conf, partitionFile); // 写partition file到mapreduce.totalorderpartitioner.path InputSampler.writePartitionFile(job, sampler); String partitionFile = TotalOrderPartitioner.getPartitionFile(conf); URI partitionUri = new URI(partitionFile);// ?? job.addCacheArchive(partitionUri);// 添加一个档案进行本地化 } boolean state = job.waitForCompletion(true); long endMili = System.currentTimeMillis(); System.out.println("总耗时为:" + (endMili - startMili) + "毫秒"); System.exit(state ? 0 : 1); } }
package com.example.front_end_of_clean_up_the_camera_app.Adapter; /*SellerItemAdapter: adapter for sellerItem * sellerMessageList: List<SellerMessage> -- list of sellerMessage for showing * sellerInflater: LayoutInflater -- for recyclerView layoutManager * OnItemClickListener: interface -- for OnClick event listening of sellerItem*/ import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Message; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.front_end_of_clean_up_the_camera_app.MessageCalss.SellerMessage; import com.example.front_end_of_clean_up_the_camera_app.R; import com.example.front_end_of_clean_up_the_camera_app.UserHome.Seller_List_Activity; import android.os.Handler; import java.util.List; public class SellerItemAdapter extends RecyclerView.Adapter<SellerItemAdapter.SMViewHolder> { private List<SellerMessage> sellerMessageList; private LayoutInflater sellerInflater; private OnItemClickListener sellerItemOnClickerListener; private Handler handler;// root handler // declare OnClicked event Listener public interface OnItemClickListener{ void onItemClick(View view, int position); } public void setSellerItemOnClickerListener(OnItemClickListener sellerItemOnClickerListener){ this.sellerItemOnClickerListener = sellerItemOnClickerListener; } // define adapter public SellerItemAdapter(Context context, List<SellerMessage> sellerMessageList, Handler handler){ this.sellerMessageList = sellerMessageList; this.sellerInflater = LayoutInflater.from(context); this.handler = handler; } // define viewHolder public static class SMViewHolder extends RecyclerView.ViewHolder{ public TextView sellerName; public TextView sellerScore; public TextView sellerAddress; public TextView sellerDistance; public TextView sellerCost; public Button sellerOrder; public SMViewHolder(View v){ super(v); } } @NonNull @Override public SMViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = sellerInflater.inflate(R.layout.seller_item_layout, viewGroup, false); SMViewHolder smViewHolder = new SMViewHolder(view); smViewHolder.sellerName = (TextView)view.findViewById(R.id.seller_item_sellerName_textView); smViewHolder.sellerScore = (TextView)view.findViewById(R.id.seller_item_sellerScore_textView); smViewHolder.sellerAddress = (TextView)view.findViewById(R.id.seller_item_sellerAddress_textView); smViewHolder.sellerDistance = (TextView)view.findViewById(R.id.seller_item_distance_textView); smViewHolder.sellerCost = (TextView)view.findViewById(R.id.seller_item_sellerCost_textView); smViewHolder.sellerOrder = (Button)view.findViewById(R.id.seller_item_order_button); return smViewHolder; } @Override public void onBindViewHolder(@NonNull final SMViewHolder holder, final int position) { SellerMessage sellerMessage = sellerMessageList.get(position); holder.sellerName.setText(sellerMessage.getSellerName()); holder.sellerAddress.setText(sellerMessage.getSellerAddress()); holder.sellerScore.setText(sellerMessage.getSellerScore()); holder.sellerDistance.setText(sellerMessage.getSellerDistance()); holder.sellerCost.setText(sellerMessage.getSellerCost()); if(sellerItemOnClickerListener != null){ holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // take seller message detail action sellerItemOnClickerListener.onItemClick(v, position); } }); holder.sellerOrder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // take order action Toast.makeText(v.getContext(), "button" + position + " onClicked", Toast.LENGTH_SHORT).show(); Message msg = new Message(); msg.what = Seller_List_Activity.MAKEORDER; msg.arg1 = position; Bundle bundle = new Bundle(); bundle.putInt("position", position); msg.setData(bundle); handler.sendMessage(msg);// send msg to root handle } }); } } @Override public int getItemCount() { return sellerMessageList.size(); } }
package gov.nih.mipav.model.scripting.actions; import gov.nih.mipav.model.provenance.ProvenanceRecorder; import gov.nih.mipav.model.scripting.*; import gov.nih.mipav.model.scripting.parameters.*; import gov.nih.mipav.model.structures.ModelImage; import gov.nih.mipav.view.MipavUtil; /** * A script action which changes the image's origin */ public class ActionChangeOrigin extends ActionImageProcessorBase { /** * The label to use for the parameter indicating the new origin */ private static final String IMAGE_ORIGIN = "image_origin"; /** * Constructor for the dynamic instantiation and execution of the script action. */ public ActionChangeOrigin() { super(); } /** * Main constructor with parameters for changing the origin * @param image the input image */ public ActionChangeOrigin(ModelImage image) { super(image); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * {@inheritDoc} */ public void insertScriptLine() { ParameterTable parameters = new ParameterTable(); try { parameters.put(createInputImageParameter(isScript)); parameters.put(ParameterFactory.newParameter(IMAGE_ORIGIN, recordingInputImage.getOrigin())); } catch (ParserException pe) { MipavUtil.displayError("Error encountered while recording " + getActionName() + " script action:\n" + pe); return; } if (isScript) { ScriptRecorder.getReference().addLine(getActionName(), parameters); } else { ProvenanceRecorder.getReference().addLine(getActionName(), parameters); } } /** * {@inheritDoc} */ public void scriptRun(ParameterTable parameters) { ModelImage inputImage = parameters.getImage(INPUT_IMAGE_LABEL); float [] origin = parameters.getList(IMAGE_ORIGIN).getAsFloatArray(); for (int i = 0; i < inputImage.getFileInfo().length; i++) { inputImage.getFileInfo()[i].setOrigin(origin); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sc01.seatingchart; /** * * @author bernice.templeman001 */ public class Sc01SeatingChart { /** * @param args the command line arguments */ public static void main(String[] args) { int [][] seats = { {10,10,10,10,10}, {12,12,12,12,12}, {15,15,15,15,15)}, {20,10,12,18,15)}, {59,80,60,35,25)} }; // TODO code application logic here } //where to place public static void displaySeats() { } } /**************************************/ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sc01.seatingchart; /** * * @author azejnilo */ public class Sc01SeatingChart { /** * @param args the command line arguments */ public static void main(String[] args) { int [][] seats = { {10, 10, 10, 10, 10}, {12, 12, 12, 12, 12}, {15, 15, 15, 15, 15}, {20, 10, 12, 18, 15}, {59, 80, 60, 35, 25} }; displaySeats(seats); } public static void displaySeats(int[][]seatingChart) { for(int curRow = 0; curRow < seatingChart.length; curRow++ ) { for (int curCol=0; curCol < seatingChart[curRow].length; curCol++) { System.out.printf("%3d", seatingChart[curRow][curCol]); } System.out.println(" "); } } }
package com.example.administrator.cookman.model.manager; import android.content.SharedPreferences; import android.util.Log; import com.example.administrator.cookman.CookManApplication; import com.example.administrator.cookman.model.entity.CookEntity.CookSearchHistory; import org.litepal.crud.DataSupport; import java.util.ArrayList; import java.util.List; import static android.content.Context.MODE_PRIVATE; /** * Created by Administrator on 2017/2/22. */ public class CookSearchHistoryManager { private static CookSearchHistoryManager Instance = null; public static CookSearchHistoryManager getInstance(){ if(Instance == null) Instance = new CookSearchHistoryManager(); return Instance; } private final static int History_Queue_Max_Size = 10; private List<CookSearchHistory> datas; private List<CookSearchHistory> buffer; private final static String SharedPreference_Key_Num = "num"; private final static String SharedPreference_Key_Search_Pre = "search"; private static String userFilePath = "shareprefer_file_cook_search"; private SharedPreferences shareUserFile; private SharedPreferences.Editor editorUserFile; private CookSearchHistoryManager(){ datas = new ArrayList<>(); buffer = new ArrayList<>(); shareUserFile = CookManApplication.getContext().getSharedPreferences(userFilePath, MODE_PRIVATE); editorUserFile = shareUserFile.edit(); } private List<CookSearchHistory> getDatasFrmFile(){ List<CookSearchHistory> datas = new ArrayList<>(); int num = shareUserFile.getInt(SharedPreference_Key_Num, 0); if(0 == num) return datas; for(int i = 0; i < num; i++){ datas.add(new CookSearchHistory(shareUserFile.getString(SharedPreference_Key_Search_Pre + i, ""))); } return datas; } private void saveDatas2File(List<CookSearchHistory> datas){ int num = datas.size(); editorUserFile.putInt(SharedPreference_Key_Num, num); if(0 == num){ editorUserFile.commit(); return ; } for(int i = 0; i < num; i++){ editorUserFile.putString(SharedPreference_Key_Search_Pre + i, datas.get(i).getName()); } editorUserFile.commit(); } public List<CookSearchHistory> getDatas(){ datas.clear(); buffer.clear(); datas = getDatasFrmFile(); return datas; } public void add2Buffer(CookSearchHistory data){ for(CookSearchHistory item : datas){ if(data.getName().equals(item.getName())) return ; } for(CookSearchHistory item : buffer){ if(data.getName().equals(item.getName())) return ; } buffer.add(data); } public void clean(){ this.datas.clear(); this.buffer.clear(); editorUserFile.putInt(SharedPreference_Key_Num, 0); editorUserFile.commit(); } //耗时操作 public void save(){ if(buffer.size() < 1) return ; if(buffer.size() >= History_Queue_Max_Size){ int end = buffer.size() - History_Queue_Max_Size; datas.clear(); for(int i = buffer.size() - 1; i >= end; i--){ datas.add(buffer.get(i)); } save2TB(); return ; } //队列满 if(datas.size() == History_Queue_Max_Size){ int end = datas.size() - buffer.size(); List<CookSearchHistory> headDatas = new ArrayList<>(); for(int i = 0; i < end; i++){ headDatas.add(datas.get(i)); } datas.clear(); for(int i = buffer.size() - 1; i >= 0; i--){ datas.add(buffer.get(i)); } for(CookSearchHistory item : headDatas){ datas.add(item); } save2TB(); return ; } //队列不满 if(datas.size() + buffer.size() > History_Queue_Max_Size){ int end = History_Queue_Max_Size - buffer.size(); List<CookSearchHistory> headDatas = new ArrayList<>(); for(int i = 0; i < end; i++){ headDatas.add(datas.get(i)); } datas.clear(); for(int i = buffer.size() - 1; i >= 0; i--){ datas.add(buffer.get(i)); } for(CookSearchHistory item : headDatas){ datas.add(item); } save2TB(); return ; } List<CookSearchHistory> headDatas = new ArrayList<>(); for(int i = 0; i < datas.size(); i++){ headDatas.add(datas.get(i)); } datas.clear(); for(int i = buffer.size() - 1; i >= 0; i--){ datas.add(buffer.get(i)); } for(CookSearchHistory item : headDatas){ datas.add(item); } save2TB(); } private void save2TB(){ saveDatas2File(datas); } }
package com.foodgeene; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.widget.LinearLayout; import com.foodgeene.adapters.homeadapters.HomeOneAdapter; import com.foodgeene.adapters.homeadapters.HomeTwoAdapter; import com.foodgeene.models.HomeOne; import com.foodgeene.models.HomeTwo; import com.google.android.material.bottomnavigation.BottomNavigationView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { RecyclerView recyclerViewOne, recyclerViewTwo, recyclerViewThree; BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerViewOne = findViewById(R.id.recyclerViewOne); recyclerViewTwo = findViewById(R.id.recyclerViewTwo); recyclerViewThree = findViewById(R.id.recycleViewThree); firstRecyclerSetup(); secondRecyclerSetup(); thirdRecyclerSetup(); bottomNavigationView=findViewById(R.id.BottomNV); bottomNavigationView.setOnNavigationItemSelectedListener( new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.scan: startActivity(new Intent(MainActivity.this,ScannerActivity.class)); break; } return true; } }); } private void firstRecyclerSetup() { List<HomeOne> data= new ArrayList<>(); data.add(new HomeOne("Paradise Biryani", "https://cdn.grabon.in/gograbon/images/web-images/uploads/1549361194978/zomato-coupons.jpg")); data.add(new HomeOne("Behorouz Biryani", "https://2.bp.blogspot.com/-o0lkcngLMhk/XNVigtsS_OI/AAAAAAAAA10/lqzzgkcVDdI8eduhZEnVnvtyLYgwVoXhwCEwYBhgL/s1600/WhatsApp%2BImage%2B2019-05-10%2Bat%2B5.04.49%2BPM.jpeg")); data.add(new HomeOne("Manju Mamta", "https://thepromox.com/wp-content/uploads/2018/03/swiggy-33-off-coupon.jpg")); data.add(new HomeOne("Chai Govindam", "https://gpcdn.ams3.cdn.digitaloceanspaces.com/promotions/swiggy-new-user-offer.png")); data.add(new HomeOne("Nukkad Teafe", "https://d1m6qo1ndegqmm.cloudfront.net/uploadimages/coupons/11251-Zomato_Online_Food_Ordering_Coupons_1.jpg")); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerViewOne.setLayoutManager(linearLayoutManager); HomeOneAdapter homeOneAdapter = new HomeOneAdapter(data, this); recyclerViewOne.setAdapter(homeOneAdapter); // DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewOne.getContext(), // linearLayoutManager.getOrientation()); // recyclerViewOne.addItemDecoration(dividerItemDecoration); } private void secondRecyclerSetup() { List<HomeTwo> data= new ArrayList<>(); data.add(new HomeTwo("https://content3.jdmagicbox.com/comp/raipur-chhattisgarh/b5/9999px771.x771.170729111452.a4b5/catalogue/chai-govindam-pandri-raipur-chhattisgarh-fast-food-61iqgtft32.jpg")); data.add(new HomeTwo("https://mapemond.com/wp-content/uploads/2019/05/blog-Capture.png")); data.add(new HomeTwo("http://d2jz4nqvi4omcr.cloudfront.net/brandscollection/2017_search_collection_karims.jpg")); data.add(new HomeTwo("https://i.ytimg.com/vi/zWpaDXgRtgg/maxresdefault.jpg")); data.add(new HomeTwo("https://i.ytimg.com/vi/ZazUXHwTkjg/maxresdefault.jpg")); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerViewTwo.setLayoutManager(linearLayoutManager); HomeTwoAdapter homeTwoAdapter = new HomeTwoAdapter(data, this); recyclerViewTwo.setAdapter(homeTwoAdapter); } private void thirdRecyclerSetup(){ List<HomeTwo> data= new ArrayList<>(); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); data.add(new HomeTwo("https://buzzbinpadillaco.com/wp-content/uploads/2013/07/Pizza-Hut-logo.jpg")); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerViewThree.setLayoutManager(linearLayoutManager); HomeTwoAdapter homeTwoAdapter = new HomeTwoAdapter(data, this); recyclerViewThree.setAdapter(homeTwoAdapter); } }
package com.example.administrator.panda_channel_app.Activity; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.example.administrator.panda_channel_app.BuildConfig; import com.example.administrator.panda_channel_app.MVP_Framework.app.App; import com.example.administrator.panda_channel_app.MVP_Framework.base.BaseActivity; import com.example.administrator.panda_channel_app.R; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import butterknife.BindView; import butterknife.OnClick; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by 闫雨婷 on 2017/7/21. */ public class ForgetpasswordActivity extends BaseActivity { @BindView(R.id.imageView) ImageView imageView; @BindView(R.id.register_forget_number) EditText registerForgetNumber; @BindView(R.id.register_forget_photoyanzheng) EditText registerForgetPhotoyanzheng; @BindView(R.id.image) ImageView image; @BindView(R.id.register_forget_reveive) EditText registerForgetReveive; @BindView(R.id.bt_getyanzheng) Button btGetyanzheng; @BindView(R.id.register_forget_setpass) EditText registerForgetSetpass; @BindView(R.id.bt_register) Button btRegister; private String jsonId; private byte[] bytes; @Override protected void initView() { loadImg(); } @Override protected int getLayoutId() { return R.layout.activity_forgetpassword; } @OnClick({R.id.imageView, R.id.register_forget_number, R.id.register_forget_photoyanzheng, R.id.image, R.id.register_forget_reveive, R.id.bt_getyanzheng, R.id.register_forget_setpass, R.id.bt_register}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.imageView: finish(); break; case R.id.bt_getyanzheng: getMessage(); break; case R.id.bt_register: register(); break; } } private void loadImg() { OkHttpClient client = new OkHttpClient.Builder().build(); Request request = new Request.Builder() .url("http://reg.cntv.cn/simple/verificationCode.action") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("TAG", e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { bytes = response.body().bytes(); final Headers headers = response.headers(); jsonId = headers.get("Set-Cookie"); for (int i = 0; i < headers.size(); i++) { String name = headers.name(i); String value = headers.get(name); if (value.contains("JSESSIONID")) { jsonId = value; break; } if (BuildConfig.DEBUG) { Log.d("-=-=-=-=-=", name + value); } App.context.runOnUiThread(new Runnable() { @Override public void run() { image.setImageDrawable(byteToDrawable(bytes)); } }); } } }); } public Drawable byteToDrawable(byte[] byteArray) { try { String string = new String(byteArray, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); return Drawable.createFromStream(inputStream, null); } /* * 短信验证码 * */ private void getMessage() { String url = "http://reg.cntv.cn/regist/getVerifiCode.action"; String from = "http://cbox_mobile.regclientuser.cntv.cn"; // 手机号 String tPhoneNumber = registerForgetNumber.getText().toString().trim(); // 图形验证码 String imgyanzhengma = registerForgetPhotoyanzheng.getText().toString().trim(); // 请求 获取验证码的 网络请求 // post 请求体 OkHttpClient client = new OkHttpClient.Builder().build(); RequestBody body = new FormBody.Builder() .add("method", "getRequestVerifiCodeM") .add("mobile", tPhoneNumber) .add("verfiCodeType", "1") .add("verificationCode", imgyanzhengma) .build(); try { // post 请求头 Request request = new Request.Builder().url(url) .addHeader("Referer", URLEncoder.encode(from, "UTF-8")) .addHeader("User-Agent", URLEncoder.encode("CNTV_APP_CLIENT_CBOX_MOBILE", "UTF-8")) .addHeader("Cookie", jsonId) .post(body).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e("TAG", e.getMessage().toString()); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Log.e("TAG", "手机验证码结果" + string); } }); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /* * 注册 * */ private void register() { String url2 = "https://reg.cntv.cn/regist/mobileRegist.do"; String number = registerForgetNumber.getText().toString().trim(); String tCheckPhone = registerForgetReveive.getText().toString().trim(); String tPassWord = registerForgetSetpass.getText().toString(); try { OkHttpClient client1 = new OkHttpClient.Builder().build(); RequestBody requestBody = new FormBody.Builder() .add("method", "saveMobileRegisterM") .add("mobile", number) .add("verfiCode", tCheckPhone) .add("passWd", URLEncoder.encode(tPassWord, "UTF-8")) .add("verfiCodeType", "1") .add("addons", URLEncoder.encode("http://cbox_mobile.regclientuser.cntv.cn", "UTF-8")) .build(); Request request = new Request.Builder() .url(url2) .addHeader("Referer", URLEncoder.encode("http://cbox_mobile.regclientuser.cntv.cn", "UTF-8")) .addHeader("User-Agent", URLEncoder.encode("CNTV_APP_CLIENT_CBOX_MOBILE", "UTF-8")) .post(requestBody) .build(); client1.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { if (BuildConfig.DEBUG) Log.e("TAG", e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { String loginSate = response.body().string(); if (BuildConfig.DEBUG) Log.e("TAG", "loginSate" + loginSate); finish(); } }); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
package com.stk123.common.util; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.SCPClient; import ch.ethz.ssh2.Session; import lombok.extern.apachecommons.CommonsLog; import java.io.*; @CommonsLog public class ScpUtils { static private ScpUtils instance; static synchronized public ScpUtils getInstance(String IP, int port, String username, String passward) { if (instance == null) { instance = new ScpUtils(IP, port, username, passward); } return instance; } public ScpUtils(String IP, int port, String username, String passward) { this.ip = IP; this.port = port; this.username = username; this.password = passward; } /** * 远程拷贝文件 * @param remoteFile 远程源文件路径 * @param localTargetDirectory 本地存放文件路径 */ public void getFile(String remoteFile, String localTargetDirectory) { Connection conn = new Connection(ip,port); try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) { log.info("authentication failed"); return; } SCPClient client = new SCPClient(conn); client.get(remoteFile, localTargetDirectory); conn.close(); } catch (IOException e) { log.error("",e); } } /** * 远程上传文件 * @param localFile 本地文件路径 * @param remoteTargetDirectory 远程存放文件路径 */ public void putFile(String localFile, String remoteTargetDirectory) throws Exception { Connection conn = new Connection(ip,port); try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) { log.info("authentication failed"); return; } SCPClient client = new SCPClient(conn); client.put(localFile, remoteTargetDirectory); } catch (Exception e) { log.error("",e); throw e; } finally { conn.close(); } } /** * 远程上传文件并对上传文件重命名 * @param localFile 本地文件路径 *@param remoteFileName远程文件名 * @param remoteTargetDirectory 远程存放文件路径 *@param mode 默认"0600",length=4 */ public void putFile(String localFile, String remoteFileName,String remoteTargetDirectory,String mode) { Connection conn = new Connection(ip,port); try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) { log.info("authentication failed"); return; } SCPClient client = new SCPClient(conn); if((mode == null) || (mode.length() == 0)){ mode = "0600"; } client.put(localFile, remoteFileName, remoteTargetDirectory, mode); //重命名 Session sess = conn.openSession(); String tmpPathName = remoteTargetDirectory + File.separator+ remoteFileName; String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf(".")); sess.execCommand("mv " + remoteFileName + " " + newPathName); conn.close(); } catch (IOException e) { log.error("",e); } } private String ip; private int port; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }