text stringlengths 10 2.72M |
|---|
package br.com.fiap.bean;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import br.com.fiap.entity.Aluno;
import br.com.fiap.repository.AlunoRepository;
@ManagedBean
@ViewScoped
public class AlunoBean {
private Aluno aluno;
private List<Aluno> listaAluno;
private AlunoRepository rep;
//private String nomeBusca;
//private List<String> nome;
@PostConstruct
private void init() {
aluno = new Aluno();
aluno.setDataNascimento(Calendar.getInstance());
rep = new AlunoRepository();
}
public void cadastrar() {
FacesMessage msg;
try {
rep.cadastrar(aluno);
msg = new FacesMessage("Aluno cadastrado!");
} catch (Exception e) {
e.printStackTrace();
msg = new FacesMessage("Erro!");
}
FacesContext.getCurrentInstance().addMessage(null, msg);
}
/* public void buscarPorNome() throws Exception {
listaAluno = rep.buscarPorNome(nomeBusca);
}
*/
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
}
public List<Aluno> getListaAluno() {
return listaAluno;
}
public void setListaAluno(List<Aluno> listaAluno) {
this.listaAluno = listaAluno;
}
/* public String getNomeBusca() {
return nomeBusca;
}
public void setNomebusca(String nomeBusca) {
this.nomeBusca = nomeBusca;
}
public List<String> getNome() {
return nome;
}
public void setNome(List<String> nome) {
this.nome = nome;
}
*/
}
|
package com.example.placement.services;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.placement.dao.Placement;
public interface PlacementRepository extends JpaRepository<Placement, Long> {
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wrapper;
/**
*
* @author jayzeegp
*/
public class Board {
private native void JBoard();
private native void JsaveToFile(String sfile);
private native void JreadFromFile(String sfile);
private native void JglGetModelViewMatrix(double modelview_matrix[]);
private native void JOgreGetPoseParameters(double position[], double orientation[]);
private long nativeHandle;
public Board(){
JBoard();
}
public void glGetModelViewMatrix(double modelview_matrix[])throws Exception{
JglGetModelViewMatrix(modelview_matrix);
}
public void OgreGetPoseParameters(double position[], double orientation[])throws Exception{
JOgreGetPoseParameters(position, orientation);
}
public void saveToFile(String filePath)throws Exception{
JsaveToFile(filePath);
}
public void readFromFile(String filePath)throws Exception{
JreadFromFile(filePath);
}
}
|
package com.zxt.compplatform.indexset.dao.impl;
import com.zxt.compplatform.indexset.dao.IndexModelDao;
import com.zxt.framework.common.dao.DAOSupport;
public class IndexModelDaoImpl extends DAOSupport implements IndexModelDao {
}
|
package swea_d2;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution_1284_수도요금경쟁 {
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int P = 0;
int Q = 0;
int R = 0;
int S = 0;
int W = 0;
int A_charge = 0;
int B_charge = 0;
int answer = 0;
for (int tc = 1; tc <= T; tc++) {
StringTokenizer st = new StringTokenizer(br.readLine());
P = Integer.parseInt(st.nextToken());
Q = Integer.parseInt(st.nextToken());
R = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
W = Integer.parseInt(st.nextToken());
A_charge = W*P;
if(W<=R) {
B_charge = Q;
}else {
B_charge = Q+(W-R)*S;
}
if(A_charge<B_charge) {
answer = A_charge;
}else {
answer = B_charge;
}
System.out.println("#"+tc+" "+answer);
}
}
}
|
package com.jalsalabs.ticklemyphonefull;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class AntiTheftBootStartActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onResume() {
super.onResume();
TML_Library.Debug("Inside BootStartActivity Resume");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
TML_Library.Debug("BootStartActivity Debug 1 ");
TML_Library.Debug("BootStartActivity Debug 2 ");
Boolean simchangealert = Boolean.valueOf(prefs.getBoolean("simchangealert", false));
TML_Library.Debug("BootStartActivity Debug 3 ");
String CurrentSimSrlno = TML_Library.GetSimSerialNumber(this);
TML_Library.Debug("BootStartActivity Debug 4 ");
String CurrentOperatorName = TML_Library.GetSimOperatorName(this);
TML_Library.Debug("BootStartActivity Debug 5 ");
String RegisteredSimSrlno = TML_Library.GetPref(this, "REGISTERED_SIM_SRLNO");
TML_Library.Debug("BootStartActivity Debug 6 ");
String RegisteredOperatorName = TML_Library.GetPref(this, "REGISTERED_OPERATOR_NAME");
TML_Library.Debug("BootStartActivity Debug 7 ");
TML_Library.Debug("Showing the alert message");
TML_Library.Debug("Showing the alert completed");
if (simchangealert.booleanValue() && !RegisteredSimSrlno.equals(CurrentSimSrlno)) {
TML_Library.Debug(RegisteredSimSrlno);
TML_Library.Debug(RegisteredOperatorName);
TML_Library.Debug(CurrentSimSrlno);
TML_Library.Debug(CurrentOperatorName);
TML_Library.Debug("Creatig the file");
Boolean sendsmswhenstolen = Boolean.valueOf(prefs.getBoolean("sendsmswhenstolen", false));
Boolean sendemailwhenstolen = Boolean.valueOf(prefs.getBoolean("sendemailwhenstolen", false));
Boolean showmessagestolen = Boolean.valueOf(prefs.getBoolean("showmessagestolen", true));
Boolean bigalaramstolen = Boolean.valueOf(prefs.getBoolean("bigalaramstolen", true));
String SMS_StolenMessage = TML_Library.GetPref(this, "DEFAULT_PHONE_LOST_TEXT");
String SecondoryPhoneNo = TML_Library.GetPref(this, "SIM_SECONDARY_PHONE");
String SecondoryPhoneNo2 = TML_Library.GetPref(this, "SIM_SECONDARY_PHONE2");
String SecondaryEmail = TML_Library.GetPref(this, "SIM_SECONDARY_EMAIL");
String CulprintContact = TML_Library.getUserContactNumber(this);
String CulpritServiceProvider = TML_Library.GetSimOperatorName(this);
String CulpritCountry = TML_Library.GetSimCountry(this);
if (sendsmswhenstolen.booleanValue()) {
TML_Library.Debug("sendsmswhenstolen is true");
String SMS_Message = "You phone (Sim #" + RegisteredSimSrlno + ") is currently with unknown person. \n" + "Contact no is :" + CulprintContact + "\n" + "Culprit SIM Srl no : " + CurrentSimSrlno + "\n" + "His/Her Serv. Provider: " + CulpritServiceProvider + "\n" + "Country : " + CulpritCountry + "\n" + "Now you can contact culprit or send Tickle my Phone commands. \nTickle my Phone";
int i = 0;
if (!SecondoryPhoneNo.equals("")) {
while (i < 5) {
try {
TML_Library.sendSMSBig(this, SecondoryPhoneNo, SMS_Message);
TML_Library.Debug("sent in if");
i = 10;
} catch (Exception e) {
TML_Library.Debug("Got Error sleeping for 10 seconds" + e);
TML_Library.Sleep(10);
i++;
}
}
}
i = 0;
if (!SecondoryPhoneNo2.equals("")) {
while (i < 5) {
try {
TML_Library.sendSMSBig(this, SecondoryPhoneNo, SMS_Message);
TML_Library.Debug("sent in if");
i = 10;
} catch (Exception e2) {
TML_Library.Debug("Got Error sleeping for 10 seconds" + e2);
TML_Library.Sleep(10);
i++;
}
}
}
}
if (showmessagestolen.booleanValue()) {
TML_Library.Debug("showmessagestolen is true");
TML_Library.SetParameter("MESSAGE_BODY", SMS_StolenMessage);
Intent intent = new Intent(getApplicationContext(), ShowPopOutMessage.class);
intent.setFlags(268435456);
startActivity(intent);
}
if (bigalaramstolen.booleanValue()) {
TML_Library.Debug("showmessagestolen is true");
TML_Library.PlayBIGAlaram(this, 1);
}
if (sendemailwhenstolen.booleanValue()) {
TML_Library.Debug("showmessagestolen is true");
String Mail_Message_Body = "You phone (Sim #" + RegisteredSimSrlno + ") is currently with unknown person and his/her\n" + "Contact no is :" + CulprintContact + "\n" + "Culprit SIM Srl no : " + CurrentSimSrlno + "\n" + "His/Her Serv. Provider: " + CulpritServiceProvider + "\n" + "Country : " + CulpritCountry + "\n" + "Now you can contact culprit or send Tickle my Phone commands. \nTickle my Phone";
String FileName = TML_Library.getTMLPath() + "phonelost.txt";
TML_Library.CreateLogText(this, FileName, Mail_Message_Body);
TML_Library.SendEmail(this, TML_Library.GetU(this), TML_Library.GetP(this), SecondaryEmail, "Tickle my Phone Mail from your lost Mobile ", Mail_Message_Body, FileName);
TML_Library.getCallDetails(this, SecondaryEmail);
}
TML_Library.Debug("Boot Receiver completed");
}
finish();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.vishal.si.ui;
import com.vishal.si.main.ImageRenderer;
import com.vishal.si.main.ReadSDF;
import com.vishal.si.main.Utility;
import com.vishal.si.struct.Drug;
import com.vishal.si.struct.Scaffold;
import java.awt.Color;
import java.awt.Component;
import java.io.File;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.exception.InvalidSmilesException;
import org.openscience.cdk.smiles.SmilesParser;
import org.openscience.cdk.smiles.smarts.SMARTSQueryTool;
/**
*
* @author Om Sai Ram
*/
public class MainUI extends javax.swing.JFrame {
TreeMap<String, List<String>> invertedIndexMap;
TreeMap<String, Drug> drugList;
DefaultListModel queryResultData = new DefaultListModel();
TreeMap<String, Scaffold> scaffoldList;
ImageRenderer renderer = new ImageRenderer();
SmilesParser sParser = new SmilesParser(DefaultChemObjectBuilder.getInstance());
QuerySwingWorker queryResultLoader = new QuerySwingWorker();
private boolean initFlag = true;
/**
* Creates new form MainUI
*/
public MainUI() {
initComponents();
hMapLoaderFrame.setSize(586, 200);
queryResultList.setCellRenderer(new PanelRenderer());
loadCachedHMapLoc();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
hMapLoaderFrame = new javax.swing.JFrame();
jLabel3 = new javax.swing.JLabel();
ssHMapLoc = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
dHMapLoc = new javax.swing.JTextField();
scfHMapLoc = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jSplitPane1 = new javax.swing.JSplitPane();
jPanel5 = new javax.swing.JPanel();
jPopupMenu1 = new javax.swing.JPopupMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jSplitPane2 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
queryBox = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
sdFileChooser = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
uniqueSMILE = new javax.swing.JCheckBox();
jPanel4 = new javax.swing.JPanel();
scfStruct = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
scfBMFrame = new javax.swing.JLabel();
scfLogP = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
scfName = new javax.swing.JTextArea();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
queryResultList = new javax.swing.JList();
status = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
hMapLoaderFrame.setTitle("HMap Loader");
hMapLoaderFrame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
hMapLoaderFrame.setLocationByPlatform(true);
hMapLoaderFrame.setResizable(false);
jLabel3.setText("Substructure HMap:");
ssHMapLoc.setText("load...");
ssHMapLoc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ssHMapLocMouseClicked(evt);
}
});
ssHMapLoc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ssHMapLocActionPerformed(evt);
}
});
jLabel4.setText("Drug HMap:");
dHMapLoc.setText("load...");
dHMapLoc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
dHMapLocMouseClicked(evt);
}
});
scfHMapLoc.setText("load...");
scfHMapLoc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
scfHMapLocMouseClicked(evt);
}
});
jLabel7.setText("Scaffold HMap");
jButton3.setText("Load");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout hMapLoaderFrameLayout = new javax.swing.GroupLayout(hMapLoaderFrame.getContentPane());
hMapLoaderFrame.getContentPane().setLayout(hMapLoaderFrameLayout);
hMapLoaderFrameLayout.setHorizontalGroup(
hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(hMapLoaderFrameLayout.createSequentialGroup()
.addContainerGap()
.addGroup(hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(scfHMapLoc)
.addComponent(dHMapLoc)
.addComponent(ssHMapLoc))
.addContainerGap())
.addGroup(hMapLoaderFrameLayout.createSequentialGroup()
.addGap(249, 249, 249)
.addComponent(jButton3)
.addContainerGap(262, Short.MAX_VALUE))
);
hMapLoaderFrameLayout.setVerticalGroup(
hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(hMapLoaderFrameLayout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(ssHMapLoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15)
.addGroup(hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(dHMapLoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(15, 15, 15)
.addGroup(hMapLoaderFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(scfHMapLoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addContainerGap(18, Short.MAX_VALUE))
);
hMapLoaderFrame.getAccessibleContext().setAccessibleParent(getRootPane());
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 29, Short.MAX_VALUE)
);
jSplitPane1.setLeftComponent(jPanel5);
jMenuItem2.setText("Cannonical smile");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jPopupMenu1.add(jMenuItem2);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Scaffold Interpreter");
setLocationByPlatform(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Query box"));
queryBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
queryBoxActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Source Sans Pro", 2, 12)); // NOI18N
jLabel1.setForeground(new java.awt.Color(102, 102, 102));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("input your query here (SMILES,SMARTS) ");
sdFileChooser.setText("SD File");
sdFileChooser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sdFileChooserActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Source Sans Pro", 2, 12)); // NOI18N
jLabel2.setForeground(new java.awt.Color(102, 102, 102));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("or choose an SD file");
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
uniqueSMILE.setText("Canonical SMILE");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
.addComponent(queryBox, javax.swing.GroupLayout.Alignment.LEADING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sdFileChooser))
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(uniqueSMILE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(queryBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sdFileChooser))
.addGap(1, 1, 1)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(uniqueSMILE))
.addContainerGap(18, Short.MAX_VALUE))
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("About the scaffold"));
scfStruct.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
scfStruct.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel5.setText("IUPAC Name:");
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel6.setText("Bemis Murcko framework:");
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel9.setText("Log P:");
scfName.setEditable(false);
scfName.setBackground(javax.swing.UIManager.getDefaults().getColor("Menu.background"));
scfName.setColumns(20);
scfName.setLineWrap(true);
scfName.setRows(2);
scfName.setWrapStyleWord(true);
scfName.setBorder(null);
scfName.setDoubleBuffered(true);
jScrollPane2.setViewportView(scfName);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel9)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(scfBMFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addComponent(scfLogP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(scfStruct, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(scfStruct, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addGap(27, 27, 27)))
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(scfBMFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(scfLogP, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jSplitPane2.setLeftComponent(jPanel1);
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
queryResultList.setModel(queryResultData);
jScrollPane1.setViewportView(queryResultList);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
);
jSplitPane2.setRightComponent(jPanel2);
status.setForeground(new java.awt.Color(102, 102, 102));
status.setText("Type in to search ");
jMenu1.setText("HMaps");
jMenuItem1.setText("Load");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane2)
.addGroup(layout.createSequentialGroup()
.addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 939, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jSplitPane2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void queryBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryBoxActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_queryBoxActionPerformed
private void sdFileChooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sdFileChooserActionPerformed
File sdFile = Utility.UI.getFile(queryBox, new FileNameExtensionFilter(" SD File (*.sdf) ", "sdf"));
if (sdFile != null) {
String smile;
try {
smile = ReadSDF.getSmilesFromFile(sdFile);
smile = ReadSDF.getCanonicalSmiles(smile);
queryBox.setText(smile);
} catch (Exception ex) {
Utility.UI.showInfoMessage(getRootPane(), "Error reading SDF File please check");
}
}
}//GEN-LAST:event_sdFileChooserActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if (queryResultLoader.isDone() || initFlag) {
queryResultLoader = new QuerySwingWorker();
status.setText("Searching... please wait.");
queryResultData.clear();
scfLogP.setText("Not found");
scfBMFrame.setText("Not found");
scfName.setText("Not found");
scfStruct.setIcon(null);
queryResultLoader.execute();
initFlag = false;
} else {
int res = JOptionPane.showConfirmDialog(getRootPane(), "Loading in progress. Cancel loading?", "Progress", JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.YES_OPTION) {
queryResultLoader.cancel(true);
}
}
}//GEN-LAST:event_jButton1ActionPerformed
private void ssHMapLocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ssHMapLocActionPerformed
hMapLoaderFrame.setVisible(true);
}//GEN-LAST:event_ssHMapLocActionPerformed
private void ssHMapLocMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ssHMapLocMouseClicked
File file = Utility.UI.getFile(hMapLoaderFrame.getRootPane(), new FileNameExtensionFilter(" Cached HashMap files (*.hmap) ", "hmap"));
if (file != null) {
ssHMapLoc.setText(file.getAbsolutePath());
}
}//GEN-LAST:event_ssHMapLocMouseClicked
private void dHMapLocMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dHMapLocMouseClicked
File file = Utility.UI.getFile(hMapLoaderFrame.getRootPane(), new FileNameExtensionFilter(" Cached HashMap files (*.hmap) ", "hmap"));
if (file != null) {
dHMapLoc.setText(file.getAbsolutePath());
}
}//GEN-LAST:event_dHMapLocMouseClicked
private void scfHMapLocMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_scfHMapLocMouseClicked
File file = Utility.UI.getFile(hMapLoaderFrame.getRootPane(), new FileNameExtensionFilter(" Cached HashMap files (*.hmap) ", "hmap"));
if (file != null) {
scfHMapLoc.setText(file.getAbsolutePath());
}
}//GEN-LAST:event_scfHMapLocMouseClicked
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
loadHMaps();
hMapLoaderFrame.setVisible(false);
}//GEN-LAST:event_jButton3ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
hMapLoaderFrame.setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
cacheHMapLoc();
}//GEN-LAST:event_formWindowClosing
private boolean isHMapsLoaded() {
if (invertedIndexMap != null && drugList != null && scaffoldList != null) {
return true;
} else {
return false;
}
}
private Object getQueryIndexFromMap(TreeMap map, String query) {
if (uniqueSMILE.isSelected()) {
// System.out.println("map result: "+map.get(query));
return map.get(query);
} else {
SMARTSQueryTool querytool;
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Entry e = (Entry) it.next();
try {
querytool = new SMARTSQueryTool((String) e.getKey());
boolean result = querytool.matches(sParser.parseSmiles(query));
if (result == true) {
return e.getValue();
}
} catch (CDKException ex) {
return null;
}
}
return null;
}
}
private void loadCachedHMapLoc() {
File cacheFile = new File(Utility.USER_DIR + Utility.FILE_SEPERATOR + "si.cache");
if (cacheFile.exists()) {
Object locs[] = Utility.getObjectFromFile(cacheFile);
ssHMapLoc.setText((String) locs[0]);
dHMapLoc.setText((String) locs[1]);
scfHMapLoc.setText((String) locs[2]);
loadHMaps();
}
}
private void cacheHMapLoc() {
File cacheFile = new File(Utility.USER_DIR + Utility.FILE_SEPERATOR + "si.cache");
Utility.saveObjectToFile(cacheFile, ssHMapLoc.getText(), dHMapLoc.getText(), scfHMapLoc.getText());
}
private class QuerySwingWorker extends SwingWorker<Void, Void> {
private int total = 0;
private int loaded = 0;
@Override
protected Void doInBackground() throws Exception {
if (isHMapsLoaded()) {
String query = queryBox.getText().trim();
renderer.setHeight(scfStruct.getHeight());
renderer.setWidth(scfStruct.getWidth());
try {
scfStruct.setIcon(renderer.getIconFromSmiles(query));
} catch (Exception ex) {
ex.printStackTrace();
}
Scaffold scf = (Scaffold) getQueryIndexFromMap(scaffoldList, query);
if (scf != null) {
scfName.setText(scf.getIUPACname());
scfLogP.setText(String.valueOf(scf.getLogP()));
scfBMFrame.setText(scf.getBMframework());
} else {
status.setText("Scaffold not found in the database!");
}
List<String> resList = (List<String>) getQueryIndexFromMap(invertedIndexMap, query);
if (resList != null) {
//
total = resList.size();
status.setText(total + " results found in the database.");
for (String res : resList) {
try {
if (!isCancelled()) {
QueryResultPanel qResultPanel = new QueryResultPanel();
Drug resD = drugList.get(res.toLowerCase());
qResultPanel.setdName(resD.getName());
qResultPanel.setdSMILE(resD.getUniqueSMILE());
qResultPanel.setdInd(resD.getIndication());
qResultPanel.setdRef(resD.getDrugbankID());
renderer.setHeight(qResultPanel.getdStructDimension().height);
renderer.setWidth(qResultPanel.getdStructDimension().width);
qResultPanel.setdStruct(renderer.getIconFromSmiles(resD.getUniqueSMILE()));
queryResultData.addElement(qResultPanel);
loaded++;
setProgress(100 * loaded / total);
// publish();
status.setText(total + " results found in the database. " + getProgress() + "% loading complete");
} else {
status.setText(status.getText() + "--load cancelled!");
break;
}
} catch (InvalidSmilesException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (CDKException ex) {
Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
Utility.UI.showInfoMessage(getRootPane(), "No drug contains the scaffold provided!");
status.setText("Scaffold not found in the database!");
}
// Utility.UI.showInfoMessage(getRootPane(), res.toString());
} else {
Utility.UI.showInfoMessage(getRootPane(), "HMaps not loaded!");
}
return null;
}
@Override
protected void process(List<Void> list) {
status.setText(total + " results found in the database. " + getProgress() + "% loading complete");
}
@Override
protected void done() {
status.setText(total + " results found in the database. finished loading");
}
}
class PanelRenderer implements ListCellRenderer {
@Override
public Component getListCellRendererComponent(JList jlist, Object value, int i, boolean isSelected, boolean bln1) {
QueryResultPanel renderer = (QueryResultPanel) value;
renderer.setBackground(isSelected ? Color.red : jlist.getBackground());
return renderer;
}
}
/**
* @param args the command line argument
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField dHMapLoc;
private javax.swing.JFrame hMapLoaderFrame;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JSplitPane jSplitPane2;
private javax.swing.JTextField queryBox;
private javax.swing.JList queryResultList;
private javax.swing.JLabel scfBMFrame;
private javax.swing.JTextField scfHMapLoc;
private javax.swing.JLabel scfLogP;
private javax.swing.JTextArea scfName;
private javax.swing.JLabel scfStruct;
private javax.swing.JButton sdFileChooser;
private javax.swing.JTextField ssHMapLoc;
private javax.swing.JLabel status;
private javax.swing.JCheckBox uniqueSMILE;
// End of variables declaration//GEN-END:variables
private void loadHMaps() {
try {
invertedIndexMap = (TreeMap<String, List<String>>) Utility.getObjectFromFile(new File(ssHMapLoc.getText()))[0];
drugList = (TreeMap<String, Drug>) Utility.getObjectFromFile(new File(dHMapLoc.getText()))[0];
scaffoldList = (TreeMap<String, Scaffold>) Utility.getObjectFromFile(new File(scfHMapLoc.getText()))[0];
status.setText("Loading successfully done!");
} catch (Exception e) {
status.setText("Error loading HMaps please check.");
}
}
}
|
package com.LambdaExpressions;
import java.util.ArrayList;
public class assignment4 {
public static void main(String[] args)
{
ArrayList <String> list=new ArrayList<String>();
list.add("a");
list.add("aa");
list.add("aaa");
list.add("aaaa");
list.add("aaaaa");
list.add("aaaaaa");
list.add("aaaaaaa");
list.add("aaaaaaaa");
list.removeIf(s->(s.length()%2==1));
for(String s:list)
{
System.out.println(s);
}
}
}
|
package com.findide.util;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class LogUtil {
public static void writeLog(String msg) {
List<String> logList = new ArrayList<String>();
logList.add(msg);
writeLog(logList,"","log") ;
}
public static void writeLog(List<String> resultList, String dirName, String fileName) {
// if (dirName == null || dirName.equals("") || fileName.equals("")) {
// dirName = "nonamelog";
// }
if (fileName == null || fileName.equals("")) {
fileName = "nonamelog";
}
String logFile = "";
if (logFile.equals("")) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String logPath = System.getProperty("user.dir") + "/log/" + dirName;
logPath = logPath.replace("\\", "/");
File logFile2 = new File(logPath);
if (!logFile2.exists()) {
logFile2.mkdir();
}
logFile = logPath + File.separator + fileName + "_" + dateFormat.format(new Date()) + ".txt";
logFile = logFile.replace("\\", "/");
File file = new File(logFile);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter out = new BufferedWriter(new FileWriter(logFile, true));
// ImportLog log = new ImportLog();
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String logRecord = "\r\n\r\n记录时间 " + timeFormat.format(new Date()) + "\r\n";
out.write(logRecord);
// 优先输出失败结果
for (int i = 0; i < resultList.size(); i++) {
logRecord = (String) resultList.get(i);
out.write(logRecord + "\r\n");
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package Topic26FileText;
public class ArraysCopyExample {
public static void main(String[] args) {
int[] numbers1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] numbers2 = new int[(numbers1.length*2)];
System.arraycopy(numbers1, 0, numbers2, 0, numbers1.length);
for(int num: numbers2) {
System.out.print(num + " ");
}
}
}
|
package com.cn.ouyjs.utils;
/**
* @author ouyjs
* @date 2019/7/4 14:04
*/
//当Test的父类TestUtils 只有private的构造函数,test不能继承TestUtils
public class Test extends TestUtils {
public Test(){
super(1);
}
}
|
package edu.upenn.cis350.androidapp.DataInteraction.Management.MessageManagement;
import edu.upenn.cis350.androidapp.AccessWebTask;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import android.util.Log;
import edu.upenn.cis350.androidapp.DataInteraction.Data.Chat;
public class ChatJSONReader {
private final String BASE_URL = "http://10.0.2.2:3000/chat/";
private ChatJSONReader() {}
private static ChatJSONReader instance = new ChatJSONReader();
public static ChatJSONReader getInstance() { return instance; }
public Map<Long, Chat> getAllChats() {
Map<Long, Chat> idToChat = new HashMap<Long, Chat>();
JSONParser parser = new JSONParser();
try {
URL url = new URL(BASE_URL+"get-all");
AccessWebTask task = new AccessWebTask();
task.execute(url);
JSONObject allChatsJSON = (JSONObject) parser.parse(task.get());
JSONArray chatsArr = (JSONArray) allChatsJSON.get("chats");
Iterator iter = chatsArr.iterator();
//iterator through each of the chat json objects
while(iter.hasNext()) {
JSONObject chatJSON = (JSONObject) iter.next();
//extract fields from JSON
long id = (long)chatJSON.get("id");
long initiatorId = (long)chatJSON.get("initiatorId");
long receiverId = (long)chatJSON.get("receiverId");
String item = (String)chatJSON.get("item");
long itemId = (long)chatJSON.get("itemId");
Log.d("ChatReader", "Got chat with id " + id +
" initiator id " + initiatorId +
" receiver id " + receiverId +
" about item " + item);
List<Long> messages = new LinkedList<Long>();
JSONArray messagesJSON = (JSONArray) chatJSON.get("messages");
for (int i = 0; i < messagesJSON.size(); i++) {
messages.add((long)messagesJSON.get(i));
}
Log.d("ChatReader", "Got messages with first id " + messages.get(0));
String rawDate = (String)chatJSON.get("lastActive");
Log.d("ChatReader", "Last active: " + rawDate);
if (rawDate == null) {
throw new IllegalStateException("LAST ACTIVE FROM DB SHOULD NOT BE NULL");
}
Date lastActive = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
lastActive = dateFormat.parse(rawDate.replaceAll("Z$", "+0000"));
} catch (ParseException e) {
Log.d("ChatReader", "TIME PARSE ERROR");
}
Log.d("ChatReader", "Got date " + lastActive.toString());
//create Chat object and add to map
Chat newChat = new Chat(id, initiatorId, receiverId, item, messages, lastActive, itemId);
idToChat.put(id, newChat);
Log.d("ChatReader", "Added chat " + id + " to map");
}
} catch (Exception e) {
Log.d("ChatReader", "Exception trying to get chats " + e);
}
return idToChat;
}
}
|
import javafx.beans.property.SimpleStringProperty;
public class BlockPalletDataHolder {
private final SimpleStringProperty palletId;
private final SimpleStringProperty productName;
private final SimpleStringProperty productionDate;
private final SimpleStringProperty blocked;
public BlockPalletDataHolder(String palletId, String productName, String productionDate, String blocked) {
this.palletId = new SimpleStringProperty(palletId);
this.productName = new SimpleStringProperty(productName);
this.productionDate = new SimpleStringProperty(productionDate);
this.blocked = new SimpleStringProperty(blocked);
}
// GET
public String getPalletId() { return palletId.get();}
public String getProductName() { return productName.get();}
public String getProductionDate() { return productionDate.get();}
public String getBlocked() { return blocked.get();}
// SET
public void setPalletId(String value) { palletId.set(value);}
public void setProductName(String value) { productName.set(value);}
public void setProductionDate(String value) { productionDate.set(value);}
public void setBlocked(String value) { blocked.set(value);}
}
|
package ru.forpda.example.an21utools;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.internal.util.ArrayUtils;
import ru.forpda.example.an21utools.model.ModelFactory;
import ru.forpda.example.an21utools.model.ShortCutModel;
import ru.forpda.example.an21utools.util.ICommand;
/**
* Created by max on 17.11.2014.
*/
public class Shortcuts extends Activity {
ShortCutModel.ShortCutItem[] data;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = new ShortCutModel().getData();
final Intent intent = getIntent();
final String action = intent.getAction();
// If the intent is a request to create a shortcut, we'll do that and exit
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
setupShortcut();
}
setResult(RESULT_CANCELED, intent);
}
private void processShortcut(Intent intent) {
}
private void setupShortcut() {
setContentView(R.layout.shortcuts);
ListView listView = (ListView) findViewById(R.id.shortcutListView);
listView.setAdapter(new ArrayAdapter<ShortCutModel.ShortCutItem>(this, android.R.layout.simple_list_item_1, data));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ShortCutModel.ShortCutItem item = data[i];
final Intent shortcutIntent = new Intent(Shortcuts.this, ShortCutExecute.class);
shortcutIntent.setAction(item.getAction());
final Intent.ShortcutIconResource iconResource = Intent.ShortcutIconResource.fromContext(Shortcuts.this, item.getResourceId());
final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, item.getName());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
intent.setAction(item.getAction());
setResult(RESULT_OK, intent);
finish();
}
});
}
}
|
package com.example.worldpopulation.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Country implements Serializable {
@Id
@GeneratedValue
private Long id;
private String countryName;
private Long population;
private int ranking;
private double worldShare;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Long getPopulation() {
return population;
}
public void setPopulation(Long population) {
this.population = population;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public double getWorldShare() {
return worldShare;
}
public void setWorldShare(double worldShare) {
this.worldShare = worldShare;
}
}
|
package com.metoo.foundation.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: Group.java
* </p>
*
* <p>
* Description:
* 团购管理控制类,用来描述系统团购信息,团购由超级管理员发起,所有卖家都可以申请参加,多个团购时间不允许交叉[],团购商品审核通过后在对应的团购活动中显示
* ,团购到期后,系统自恢复团购商品为普通商品
* </p>
*
* <p>
* Copyright: Copyright (c) 2014
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author erikzhang
*
* @date 2014-4-25
*
*
* @version koala_b2b2c v2.0 2015版
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "group")
public class Group extends IdEntity {
private String group_name;// 团购活动名称
private Date beginTime;// 开始时间
private Date endTime;// 结束时间
private Date joinEndTime;// 报名截止时间
private int status;// 状态,0为正常,-1为关闭,-2为已经结束,1为即将开始
private int group_type;// 0为商品团购,1为生活类团购,生活类需要发送消费码及商家验证消费码
@OneToMany(mappedBy = "group")
private List<Goods> goods_list = new ArrayList<Goods>();// 团购对应的商品列表
@OneToMany(mappedBy = "group")
private List<GroupGoods> gg_list = new ArrayList<GroupGoods>();// 对应的团购商品列表
@OneToMany(mappedBy = "group")
private List<GroupLifeGoods> gl_list = new ArrayList<GroupLifeGoods>();// 对应的生活类团购商品列表
@Transient
private int gg_status = 0;// 大于0的情况则是还有正在进行的商品购 无法关闭货删除团购
@Transient
private int gl_status = 0;;// 大于0的情况则是还有正在进行的生活购 无法关闭货删除团购
public int getGg_status() {
for (GroupGoods gg : gg_list) {
if (gg.getGg_status() == 1) {
this.gg_status = this.gg_status + 1;
}
}
return gg_status;
}
public int getGl_status() {
for (GroupLifeGoods gl : gl_list) {
if (gl.getGroup_status() == 1) {
this.gl_status = this.gl_status + 1;
}
}
return gl_status;
}
public Group(Long id, Date addTime) {
super(id, addTime);
// TODO Auto-generated constructor stub
}
public Group() {
super();
// TODO Auto-generated constructor stub
}
public List<GroupLifeGoods> getGl_list() {
return gl_list;
}
public void setGl_list(List<GroupLifeGoods> gl_list) {
this.gl_list = gl_list;
}
public int getGroup_type() {
return group_type;
}
public void setGroup_type(int group_type) {
this.group_type = group_type;
}
public List<Goods> getGoods_list() {
return goods_list;
}
public void setGoods_list(List<Goods> goods_list) {
this.goods_list = goods_list;
}
public List<GroupGoods> getGg_list() {
return gg_list;
}
public void setGg_list(List<GroupGoods> gg_list) {
this.gg_list = gg_list;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getGroup_name() {
return group_name;
}
public void setGroup_name(String group_name) {
this.group_name = group_name;
}
public Date getBeginTime() {
return beginTime;
}
public void setBeginTime(Date beginTime) {
this.beginTime = beginTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Date getJoinEndTime() {
return joinEndTime;
}
public void setJoinEndTime(Date joinEndTime) {
this.joinEndTime = joinEndTime;
}
}
|
package edu.upenn.cis455.project;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.SparkSession;
import com.google.common.collect.Iterables;
import org.apache.spark.api.java.JavaPairRDD;
import scala.Tuple2;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
public class PagerankMain {
private static final Pattern SPACES = Pattern.compile("\\s+");
public static void main(String args[])
{
if (args.length < 2) {
System.err.println("Usage: PagerankMain <inputFile> <outputFile>");
System.exit(1);
}
SparkSession spark = SparkSession
.builder()
.appName("SparkJob")
.getOrCreate();
// read text file to RDD
JavaRDD<String> lines = spark.read().textFile(args[0]).toJavaRDD();
// JavaRDD<String> lines = spark.read().textFile("links.txt").toJavaRDD();
// System.out.println("*** Author: Sanjna Kashyap (sanjnak)");
// SparkConf sparkConf = new SparkConf().setAppName("Pagerank")
// .setMaster("local[2]").set("spark.executor.memory","2g");
// // start a spark context
// JavaSparkContext sc = new JavaSparkContext(sparkConf);
// provide path to input text file
// String path = "links.txt";
// JavaRDD<String> lines = sc.textFile(path);
JavaPairRDD<String, String> urlmap = lines.mapToPair((String s) -> {
// String[] parts = SPACES.split(s);
String[] parts = s.split("\\|");
// System.out.println(parts[0]+"PARTS"+parts[1]);
if(parts.length<2)
{
return new Tuple2<>(parts[0], "");
}
else
{
return new Tuple2<>(parts[0], parts[1]);
}
});
// System.out.println(urlmap.collect());
JavaPairRDD<String, String> oldlinks = urlmap.flatMapToPair(s -> {
String url = s._1();
String dest = s._2();
String[] parts = dest.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
List<Tuple2<String, String>> results = new ArrayList<>();
for (String n : parts) {
results.add(new Tuple2<>(url, n));
// System.out.println(urlCount+n);
}
return results.iterator();
});
// System.out.println(oldlinks.collect());
JavaPairRDD<String, Iterable<String>> links = oldlinks.distinct().groupByKey().cache();
System.out.println(links.count());
// Double initial = (double) (1/links.count());
Double totalsum = (double) links.count();
// System.out.println(links.collect());
// JavaPairRDD<String, Double> ranks = links.mapValues(rs -> initial);
JavaPairRDD<String, Double> ranks = links.mapValues(rs -> (double) 1);
// System.out.println(ranks.collect());
for (int current = 0; current < 30; current++) {
// Calculates URL contributions to the rank of other URLs.
// JavaPairRDD<String, Double> contribs = links.join(ranks).values()
JavaPairRDD<String, Double> contribs = links.join(ranks)
.flatMapToPair(s -> {
String url = s._1();
Tuple2<Iterable<String>, Double> t = s._2();
int urlCount = Iterables.size(t._1());
// System.out.println(urlCount);
List<Tuple2<String, Double>> results = new ArrayList<>();
for (String n : t._1) {
results.add(new Tuple2<>(n, t._2() / urlCount));
// System.out.println(urlCount+n);
}
results.add(new Tuple2<>(url, (double) 0));
return results.iterator();
});
// System.out.println(contribs.collect());
ranks = contribs.reduceByKey((a, b) -> a+b).mapValues(sum -> 0.15 + sum * 0.85);
// System.out.println(ranks.collect());
// Dealing with dangling links i.e. removing ranks of sinks and dangling links
ranks = links.join(ranks).mapToPair(f -> {
String url = f._1();
Tuple2<Iterable<String>, Double> d = f._2();
return new Tuple2<>(url, d._2());
});
// Normalizing pagerank - all values sum up to 1
Double v = ranks.values().reduce((a, b) -> a+b);
// System.out.println(v);
ranks = ranks.mapToPair(x -> {
Double t = (x._2()/v) * totalsum;
return new Tuple2<>(x._1(), t);
});
}
// flatMap each line to words in the line
// JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(s.split(" ")).iterator());
// JavaRDD<> words = lines.maptoPair(s -> { Tuple2<String, String> first = s.split(" ");});
// collect RDD for printing
ranks.saveAsTextFile(args[1]);
// for(String word:){
// System.out.println(word);
// }
// sc.close();
}
}
|
package code;
import java.util.HashMap;
import java.util.Map;
/**
* 给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
* <p>
* 示例 :
* <p>
* 输入:nums = [1,1,1], k = 2
* 输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
* <p>
*
* @author liyuke
* @date 2021-06-20 14:21
*/
public class SumEqualK {
//解法1 前缀和+暴力枚举
public int subarraySum1(int[] nums, int k) {
int n = nums.length;
int[] sum = new int[n + 1];
int ans = 0;
for (int i = 0; i < n; i++) {
sum[i + 1] = sum[i] + nums[i];
}
for (int j = 0; j < n; j++) {
for (int m = j + 1; m <= n; m++) {
if (sum[m] - sum[j] == k) {
ans++;
}
}
}
return ans;
}
//解法2 前缀和+哈希表
public int subarraySum2(int[] nums, int k) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>();
int ans = 0;
int pre = 0;
map.put(pre, 1);
for (int i = 0; i < n; i++) {
pre += nums[i];
int temp = pre - k;
if (map.containsKey(temp)) {
ans += map.get(temp);
}
map.merge(pre, 1, Integer::sum);
}
return ans;
}
}
|
package ua.training.model.dao.mapper;
import lombok.extern.log4j.Log4j2;
import ua.training.constant.Attributes;
import ua.training.constant.Mess;
import ua.training.controller.commands.exception.DataHttpException;
import ua.training.model.entity.DayRation;
import ua.training.model.entity.User;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.Period;
import static com.mysql.jdbc.StringUtils.isNullOrEmpty;
import static java.util.Objects.isNull;
@Log4j2
public class DayRationMapper implements ObjectMapper<DayRation> {
/**
* @param lifeStyleCoefficient Integer
* @param weight Integer
* @param height Integer
* @param age Integer
* @return amount of calories calculate by formula
*/
public static Integer formulaMifflinSanJerura(Integer lifeStyleCoefficient,
Integer weight,
Integer height,
Integer age) {
if (weight != 0) {
return Math.toIntExact(Math.round(((double) lifeStyleCoefficient / 1000) *
((double) 10 * ((double) weight / 1000) + 6.25 *
((double) height / 100) - ((double) 5 * age))));
}
return 0;
}
/**
* @param req HttpServletRequest
* @return new UserDayRation
*/
@Override
public DayRation extractFromHttpServletRequest(HttpServletRequest req) throws DataHttpException {
User user;
Integer usersAge;
LocalDate date;
Integer userCalories;
Integer userCaloriesDesired;
LocalDate localDate = LocalDate.now();
user = (User) req.getSession().getAttribute(Attributes.REQUEST_USER);
Period period = Period.between(user.getDob(), localDate);
usersAge = period.getYears();
String tempDate = req.getParameter(Attributes.REQUEST_DATE);
date = isNullOrEmpty(tempDate) ? localDate : LocalDate.parse(tempDate);
userCalories = formulaMifflinSanJerura(user.getLifeStyleCoefficient(),
user.getWeight(), user.getHeight(), usersAge);
userCaloriesDesired = formulaMifflinSanJerura(user.getLifeStyleCoefficient(),
user.getWeightDesired(), user.getHeight(), usersAge);
DayRation dayRation = DayRation.builder()
.date(date)
.user(user)
.userCalories(userCalories * 1000)
.userCaloriesDesired(userCaloriesDesired * 1000)
.build();
checkByRegex(dayRation);
return dayRation;
}
/**
* Check UserDayRation by regex
*
* @param dayRation UserDayRation
* @throws DataHttpException
*/
@Override
public void checkByRegex(DayRation dayRation) throws DataHttpException {
boolean flag = true;
LocalDate localDate = LocalDate.now();
Period period = Period.between(dayRation.getDate(), localDate);
if (period.getDays() > 14 || period.getDays() < -14) {
flag = false;
} else if (period.getDays() == period.getDays() && period.getMonths() != 0) {
flag = false;
} else if (isNull(dayRation.getUser())) {
flag = false;
}
if (!flag) {
throw new DataHttpException(Mess.LOG_DAY_RATION_HTTP_NOT_EXTRACT);
}
}
}
|
package service;
import dao.*;
import model.Event;
import model.Person;
import model.User;
import response.ErrorResponse;
import response.FillResponse;
import response.Response;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.UUID;
/**
* FillService will fill the database with generated data for ancestors of a given user
*/
public class FillService {
public FillService() {
}
/**
* fill will generate data for a user's family tree, and delete any pre-existing data
* @param username will be used to map to and from relatives
* @param generations will indicate how many generations of data should be generated
* @return
*/
public Response fill(String username, int generations) {
if (generations < 0) {
ErrorResponse errorResponse = new ErrorResponse("Invalid generation parameter. Please enter a positive number");
return errorResponse;
}
FillResponse fillResponse = null;
NameGenerator names = new NameGenerator();
EventGenerator generator = new EventGenerator();
Queue<Person> fathers = new LinkedList<>();
Queue<Person> mothers = new LinkedList<>();
ArrayList<Event> events = new ArrayList<>();
ArrayList<Person> people = new ArrayList<>();
Database db = new Database();
boolean closed = true;
try {
db.openConnection();
closed = false;
db.createTables();
db.clearUserInfo(username);
String userDad = null;
String userMom = null;
for (int i = generations; i > 0; --i){
int numNewCouples = (int) Math.pow(2, i); //Calculate how many new couples there will be
for (int j = 0; j < (numNewCouples / 2); ++j){
boolean parents = true;
String manDad = null;
String manMom = null;
String womanDad = null;
String womanMom = null;
if (i == generations) { //If this is the oldest generation, then they won't have parent data
parents = false;
}
if (parents) {
manDad = ((LinkedList<Person>) fathers).element().getPersonID();
((LinkedList<Person>) fathers).pop();
manMom = ((LinkedList<Person>) mothers).element().getPersonID();
((LinkedList<Person>) mothers).pop();
womanDad = ((LinkedList<Person>) fathers).element().getPersonID();
((LinkedList<Person>) fathers).pop();
womanMom = ((LinkedList<Person>) mothers).element().getPersonID();
((LinkedList<Person>) mothers).pop();
}
String manID = UUID.randomUUID().toString();
String manFName = names.getBoyName();
String manLName = names.getLastName();
String womanID = UUID.randomUUID().toString();
String womanFName = names.getGirlName();
String womanLName = names.getLastName();
if (i == 1){
userDad = manID;
userMom = womanID;
}
Person man = new Person(manID, username, manFName, manLName, "m", manDad, manMom, womanID);
fathers.add(man);
people.add(man);
Person woman = new Person(womanID, username, womanFName, womanLName, "f", womanDad, womanMom, manID);
mothers.add(woman);
people.add(woman);
EventGenerator.Location newLocation;
newLocation = generator.getLocation();
Event manBirth = new Event(UUID.randomUUID().toString(), username, manID,
newLocation.getLatitude(), newLocation.getLongitude(), newLocation.getCountry(),
newLocation.getCity(), "birth", generator.getBirthYear(i));
events.add(manBirth);
newLocation = generator.getLocation();
Event womanBirth = new Event(UUID.randomUUID().toString(), username, womanID,
newLocation.getLatitude(), newLocation.getLongitude(), newLocation.getCountry(),
newLocation.getCity(), "birth", generator.getBirthYear(i));
events.add(womanBirth);
newLocation = generator.getLocation();
Event manDeath = new Event(UUID.randomUUID().toString(), username, manID,
newLocation.getLatitude(), newLocation.getLongitude(), newLocation.getCountry(),
newLocation.getCity(), "death", generator.getDeathYear(manBirth.getYear()));
events.add(manDeath);
newLocation = generator.getLocation();
Event womanDeath = new Event(UUID.randomUUID().toString(), username, womanID,
newLocation.getLatitude(), newLocation.getLongitude(), newLocation.getCountry(),
newLocation.getCity(), "death", generator.getDeathYear(womanBirth.getYear()));
events.add(womanDeath);
newLocation = generator.getLocation();
Event marriage = new Event(UUID.randomUUID().toString(), username, manID,
newLocation.getLatitude(), newLocation.getLongitude(), newLocation.getCountry(),
newLocation.getCity(), "marriage", generator.getMarriageYear(manBirth.getYear()));
Event marriageMomCopy = new Event(UUID.randomUUID().toString(), username, womanID,
marriage.getLatitude(), marriage.getLongitude(), marriage.getCountry(),
marriage.getCity(), "marriage", marriage.getYear());
events.add(marriage);
events.add(marriageMomCopy);
}
}
UserDao userDao = new UserDao(db.getConn());
User user = userDao.find(username);
//Create person data for the user
Person person = new Person(user.getPersonID(), user.getUserName(), user.getFirstName(),
user.getLastName(), user.getGender(), userDad, userMom, "");
people.add(person);
EventGenerator.Location newLocation = new EventGenerator().getLocation();
Event userBirth = new Event(UUID.randomUUID().toString(), username, person.getPersonID(),
newLocation.getLatitude(), newLocation.getLongitude(), newLocation.getCountry(),
newLocation.getCity(), "birth", generator.getBirthYear(0));
events.add(userBirth);
PersonDao personDao = new PersonDao(db.getConn());
Person[] personArray = new Person[people.size()];
for (int i = 0; i < people.size(); ++i) {
personArray[i] = people.get(i);
}
personDao.insertMany(personArray);
EventDao eventDao = new EventDao(db.getConn());
Event[] eventArray = new Event[events.size()];
for (int i = 0; i < events.size(); ++i) {
eventArray[i] = events.get(i);
}
eventDao.insertMany(eventArray);
db.closeConnection(true);
closed = true;
db = null;
}
catch (DataAccessException e) {
ErrorResponse error = new ErrorResponse(e.getMessage());
return error;
}
finally {
if (!closed) {
try {
db.closeConnection(false);
closed = true;
}
catch (DataAccessException d) {
ErrorResponse error = new ErrorResponse(d.getMessage());
}
}
}
StringBuilder response = new StringBuilder();
int pSize = people.size();
int eSize = events.size();
response.append("Successfully added " + pSize + " persons and " + eSize + " events to the database.");
fillResponse = new FillResponse(response.toString());
return fillResponse;
}
}
|
package com.logicbig.example.implicitconstructorinjection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class OrderServiceClient {
private OrderService orderService;
//@Autowired is no longer required in Spring 4.3 and later.
public OrderServiceClient (OrderService orderService) {
this.orderService = orderService;
}
public void showPendingOrderDetails () {
System.out.println(orderService.getOrderDetails("100"));
}
} |
package com.safframework.bytekit.utils;
import java.nio.ByteBuffer;
/**
* Created by tony on 2018-12-19.
*/
public class Utils {
public static int parse(char c) {
if (c >= 'a')
return (c - 'a' + 10) & 0x0f;
if (c >= 'A')
return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
/**
* 克隆ByteBuffer
* @param original
* @return
*/
public static ByteBuffer cloneByteBuffer(ByteBuffer original) {
ByteBuffer clone = ByteBuffer.allocate(original.capacity());
original.rewind();//copy from the beginning
clone.put(original);
original.rewind();
clone.flip();
return clone;
}
}
|
/*
* Copyright 2014 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.application.ui.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListView;
import com.application.beans.Chat;
import com.application.beans.MIS;
import com.application.beans.Mobcast;
import com.application.beans.Training;
import com.application.ui.adapter.SimpleHeaderRecyclerAdapter;
import com.application.ui.adapter.SimpleRecyclerAdapter;
import com.application.ui.calligraphy.CalligraphyContextWrapper;
import com.application.ui.view.BottomSheet;
import com.application.ui.view.MaterialRippleLayout;
import com.application.utils.AndroidUtilities;
import com.application.utils.AppConstants;
import com.application.utils.ApplicationLoader;
import com.application.utils.BuildVars;
import com.application.utils.FileLog;
import com.mobcast.R;
public abstract class BaseActivity extends AppCompatActivity {
private static final String TAG = BaseActivity.class.getSimpleName();
private static final int NUM_OF_ITEMS = 20;
private static final int NUM_OF_ITEMS_FEW = 3;
@Override
protected void attachBaseContext(Context newBase) {
try{
if(AndroidUtilities.isAppLanguageIsEnglish()){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}else{
super.attachBaseContext(newBase);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
protected int getActionBarSize() {
TypedValue typedValue = new TypedValue();
int[] textSizeAttr = new int[] { R.attr.actionBarSize };
int indexOfAttrTextSize = 0;
TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr);
int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
return actionBarSize;
}
protected int getScreenHeight() {
return findViewById(android.R.id.content).getHeight();
}
public static ArrayList<String> getDummyData() {
return getDummyData(NUM_OF_ITEMS);
}
public static ArrayList<String> getDummyData(int num) {
ArrayList<String> items = new ArrayList<String>();
for (int i = 1; i <= num; i++) {
items.add("Item " + i);
}
return items;
}
public static ArrayList<Mobcast> getDummyMobcastData() {
return getDummyMobcastData(NUM_OF_ITEMS);
}
public static ArrayList<Mobcast> getDummyMobcastData(int num) {
ArrayList<Mobcast> items = new ArrayList<Mobcast>();
/*for (int i = 1; i <= num; i++) {
Mobcast Obj = new Mobcast();
if (i % 3 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.VIDEO);
} else if (i % 5 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.IMAGE);
} else if (i % 7 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.AUDIO);
} else if (i % 11 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.PDF);
} else if (i % 13 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.DOC);
} else if (i % 17 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.XLS);
} else if (i % 19 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.FEEDBACK);
} else if (i % 23 == 0) {
Obj.setmFileType(AppConstants.MOBCAST.NEWS);
} else {
Obj.setmFileType(AppConstants.MOBCAST.TEXT);
}
items.add(Obj);
}*/
/*for (int i = 0; i <= 15; i++) {
Mobcast Obj = new Mobcast();
if (i == 0 || i == 8) {
Obj.setmFileType(AppConstants.MOBCAST.TEXT);
} else if (i == 1 || i == 9) {
Obj.setmFileType(AppConstants.MOBCAST.VIDEO);
} else if (i == 2 || i == 10) {
Obj.setmFileType(AppConstants.MOBCAST.IMAGE);
} else if (i == 3 || i == 11) {
Obj.setmFileType(AppConstants.MOBCAST.AUDIO);
} else if (i == 4 || i == 12) {
Obj.setmFileType(AppConstants.MOBCAST.PDF);
} else if (i == 5 || i == 13) {
Obj.setmFileType(AppConstants.MOBCAST.DOC);
} else if (i == 6 || i == 14) {
Obj.setmFileType(AppConstants.MOBCAST.XLS);
} else if (i == 7 || i == 15) {
Obj.setmFileType(AppConstants.MOBCAST.FEEDBACK);
} else {
Obj.setmFileType(AppConstants.MOBCAST.TEXT);
}
items.add(Obj);
}*/
for (int i = 0; i <= 8; i++) {
Mobcast Obj = new Mobcast();
if (i == 0) {
Obj.setmBy("By : Consumer 360");
Obj.setmTitle("Welcome address - Piyush Mathur, President, Nielsen India Region.");
Obj.setRead(true);
Obj.setmExpiryDate("a");
Obj.setmFileType(AppConstants.MOBCAST.IMAGE);
} else if (i == 1) {
Obj.setmBy("By : Thought Leadership");
Obj.setmTitle("Hinterlands Become FMCG's Trump Card : Nielsen Featured Insights ");
Obj.setRead(false);
Obj.setmExpiryTime("8 Pages");
Obj.setmTime("a");
Obj.setmExpiryDate("Trump Card.pdf");
Obj.setmFileType(AppConstants.MOBCAST.PDF);
} else if (i == 2) {
Obj.setmBy("By : Press Releases");
Obj.setmTitle("CCI Q1 2015");
Obj.setRead(false);
Obj.setmExpiryDate("CCI Q1 2015 - Press Release.docx");
Obj.setmExpiryTime("3 Pages");
Obj.setmTime("a");
Obj.setmFileType(AppConstants.MOBCAST.DOC);
} else if (i == 3) {
Obj.setmBy("By : Event Video");
Obj.setmTitle("MASTER PROMO VIDEO");
Obj.setRead(false);
Obj.setmFileType(AppConstants.MOBCAST.VIDEO);
} else if (i == 4) {
Obj.setmBy("By : Consumer 360");
Obj.setmTitle("Keynote Address - Harish Manwani, Non-Executive Chairman, Hindustan Unilever Ltd.");
Obj.setRead(true);
Obj.setmExpiryDate("b");
Obj.setmFileType(AppConstants.MOBCAST.IMAGE);
} else if (i == 5) {
Obj.setmBy("By : Consumer 360");
Obj.setmTitle("Dharavi Rocks.");
Obj.setRead(false);
Obj.setmExpiryDate("c");
Obj.setmFileType(AppConstants.MOBCAST.IMAGE);
} else if (i == 6) {
Obj.setmBy("By : Thought Leadership");
Obj.setmTitle("Super Consumers - Racing to the Top : Nielsen Featured Insights ");
Obj.setRead(true);
Obj.setmExpiryTime("12 Pages");
Obj.setmTime("b");
Obj.setmExpiryDate("Racing to the Top.pdf");
Obj.setmFileType(AppConstants.MOBCAST.PDF);
} else if (i == 7) {
Obj.setmBy("By : Press Releases");
Obj.setmTitle("FMCG is the most preferred sector for campus placements, for the fourth year, followed by E-Commerce. HUL is the top recruiter, followed by P&G and Google.");
Obj.setRead(false);
Obj.setmExpiryDate("Bschool24thFeb.docx");
Obj.setmExpiryTime("5 Pages");
Obj.setmTime("b");
Obj.setmFileType(AppConstants.MOBCAST.DOC);
} else {
Obj.setmBy("By : Press Releases");
Obj.setmTitle("PCM Workshop & Consumer 360");
Obj.setmFileType(AppConstants.MOBCAST.FEEDBACK);
Obj.setRead(false);
}
Obj.setmLikeCount("12K+");
Obj.setmViewCount("10K+");
items.add(Obj);
}
return items;
}
public static ArrayList<Training> getDummyTrainingData() {
return getDummyTrainingData(NUM_OF_ITEMS);
}
public static ArrayList<Training> getDummyTrainingData(int num) {
ArrayList<Training> items = new ArrayList<Training>();
/* for (int i = 1; i <= num; i++) {
Training Obj = new Training();
if (i % 3 == 0) {
Obj.setmFileType(AppConstants.TRAINING.VIDEO);
} else if (i % 5 == 0) {
Obj.setmFileType(AppConstants.TRAINING.IMAGE);
} else if (i % 7 == 0) {
Obj.setmFileType(AppConstants.TRAINING.AUDIO);
} else if (i % 11 == 0) {
Obj.setmFileType(AppConstants.TRAINING.PDF);
} else if (i % 13 == 0) {
Obj.setmFileType(AppConstants.TRAINING.DOC);
} else if (i % 17 == 0) {
Obj.setmFileType(AppConstants.TRAINING.XLS);
} else if (i % 19 == 0) {
Obj.setmFileType(AppConstants.TRAINING.QUIZ);
} else if (i % 23 == 0) {
Obj.setmFileType(AppConstants.TRAINING.INTERACTIVE);
} else {
Obj.setmFileType(AppConstants.TRAINING.TEXT);
}
items.add(Obj);
}*/
for (int i = 0; i <= 15; i++) {
Training Obj = new Training();
if (i == 0 || i == 8) {
Obj.setmFileType(AppConstants.TRAINING.TEXT);
} else if (i == 1 || i == 9) {
Obj.setmFileType(AppConstants.TRAINING.VIDEO);
} else if (i == 2 || i == 10) {
Obj.setmFileType(AppConstants.TRAINING.IMAGE);
} else if (i == 3 || i == 11) {
Obj.setmFileType(AppConstants.TRAINING.AUDIO);
} else if (i == 4 || i == 12) {
Obj.setmFileType(AppConstants.TRAINING.PDF);
} else if (i == 7 || i == 15) {
Obj.setmFileType(AppConstants.TRAINING.QUIZ);
} else {
Obj.setmFileType(AppConstants.TRAINING.TEXT);
}
items.add(Obj);
}
return items;
}
public static ArrayList<Chat> getDummyChatData() {
return getDummyChatData(1);
}
public static ArrayList<Chat> getDummyChatData(int num) {
ArrayList<Chat> items = new ArrayList<Chat>();
for (int i = 0; i < num; i++) {
Chat Obj = new Chat();
if(ApplicationLoader.getPreferences().getUserName().equalsIgnoreCase(AppConstants.mChatUser1)){
Obj.setmName(AppConstants.mChatName2);
Obj.setIsRead(AppConstants.mChatUser1);//from
Obj.setmLastMessageTime(AppConstants.mChatUser2);//to
Obj.setmUserDpLink(AppConstants.mChatUserDp1);
ApplicationLoader.getPreferences().setChatOppositePerson(AppConstants.mChatName2);
ApplicationLoader.getPreferences().setChatFrom(AppConstants.mChatUser1);
ApplicationLoader.getPreferences().setChatTo(AppConstants.mChatUser2);
items.add(Obj);
}else if(ApplicationLoader.getPreferences().getUserName().equalsIgnoreCase(AppConstants.mChatUser2)){
Obj.setmName(AppConstants.mChatName1);
Obj.setIsRead(AppConstants.mChatUser2);//from
Obj.setmLastMessageTime(AppConstants.mChatUser1);//to
Obj.setmUserDpLink(AppConstants.mChatUserDp2);
ApplicationLoader.getPreferences().setChatOppositePerson(AppConstants.mChatName1);
ApplicationLoader.getPreferences().setChatFrom(AppConstants.mChatUser2);
ApplicationLoader.getPreferences().setChatTo(AppConstants.mChatUser1);
items.add(Obj);
}
}
return items;
}
public static ArrayList<MIS> getDummyMISData() {
return getDummyMISData(9);
}
public static ArrayList<MIS> getDummyMISData(int num) {
ArrayList<MIS> items = new ArrayList<MIS>();
for (int i = 0; i < num; i++) {
MIS Obj = new MIS();
switch(i){
case 0:
Obj.setmTitle("My Office – Attendance & PJP");
Obj.setmLink("in.jts.myapp");
break;
case 1:
Obj.setmTitle("Cavinkomm Reports");
Obj.setmLink("http://124.7.223.32/CKN");
break;
case 2:
Obj.setmTitle("Take Insight Reports – Secondary Sales MIS");
Obj.setmLink("http://www.ckinsight.com");
break;
case 3:
Obj.setmTitle("RSSM wise Productivity, ECO and Unbilled Outlets");
Obj.setmLink("http://www.cavinkomm.net/RSConnectMISReport/");
break;
case 4:
Obj.setmTitle("Top Outlet Performance(Outlet Trend Report - Week wise)");
Obj.setmLink("http://www.cavinkomm.net/RSConnectMISReport/");
break;
case 5:
Obj.setmTitle("SFA Reports – IVY Mobility");
Obj.setmLink("http://idistcavinkarein.ivymobileapps.com/web");
break;
case 6:
Obj.setmTitle("Utility Reports");
Obj.setmLink("http://cavinkomm.net/ckplreport/utilityreports/upgraded/home.asp");
break;
case 7:
Obj.setmTitle("Market Working Report");
Obj.setmLink("http://cavinkomm.net/mktg/upgraded/reports/loginfo.asp");
break;
case 8:
Obj.setmTitle("CK HRIMS – Employee Portal");
Obj.setmLink("http://my.cavinkare.com");
break;
}
items.add(Obj);
}
return items;
}
protected void setDummyData(ListView listView) {
setDummyData(listView, NUM_OF_ITEMS);
}
protected void setDummyDataFew(ListView listView) {
setDummyData(listView, NUM_OF_ITEMS_FEW);
}
protected void setDummyData(ListView listView, int num) {
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getDummyData(num)));
}
protected void setDummyDataWithHeader(ListView listView, int headerHeight) {
setDummyDataWithHeader(listView, headerHeight, NUM_OF_ITEMS);
}
protected void setDummyDataWithHeader(ListView listView, int headerHeight,
int num) {
View headerView = new View(this);
headerView.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, headerHeight));
headerView.setMinimumHeight(headerHeight);
// This is required to disable header's list selector effect
headerView.setClickable(true);
setDummyDataWithHeader(listView, headerView, num);
}
protected void setDummyDataWithHeader(ListView listView, View headerView,
int num) {
listView.addHeaderView(headerView);
setDummyData(listView, num);
}
protected void setDummyData(GridView gridView) {
gridView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getDummyData()));
}
protected void setDummyData(RecyclerView recyclerView) {
setDummyData(recyclerView, NUM_OF_ITEMS);
}
protected void setDummyDataFew(RecyclerView recyclerView) {
setDummyData(recyclerView, NUM_OF_ITEMS_FEW);
}
protected void setDummyData(RecyclerView recyclerView, int num) {
recyclerView.setAdapter(new SimpleRecyclerAdapter(this,
getDummyData(num)));
}
protected void setDummyDataWithHeader(RecyclerView recyclerView,
int headerHeight) {
View headerView = new View(this);
headerView.setLayoutParams(new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, headerHeight));
headerView.setMinimumHeight(headerHeight);
// This is required to disable header's list selector effect
headerView.setClickable(true);
setDummyDataWithHeader(recyclerView, headerView);
}
protected void setDummyDataWithHeader(RecyclerView recyclerView,
View headerView) {
recyclerView.setAdapter(new SimpleHeaderRecyclerAdapter(this,
getDummyData(), headerView));
}
/**
* Security : Couldn't capture ScreenShot
*
* @author Vikalp Patel(VikalpPatelCE)
*/
protected void setSecurity() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (!BuildVars.DEBUG_SCREENSHOT) {
getWindow().setFlags(LayoutParams.FLAG_SECURE,LayoutParams.FLAG_SECURE);
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void setFullScreen(){
try{
if(AndroidUtilities.isAboveKitKat()){
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}else{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
protected BottomSheet.Builder getShareActions(BottomSheet.Builder builder,
String text) {
PackageManager pm = this.getPackageManager();
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
final List<ResolveInfo> list = pm.queryIntentActivities(shareIntent, 0);
for (int i = 0; i < list.size(); i++) {
builder.sheet(i, list.get(i).loadIcon(pm), list.get(i)
.loadLabel(pm));
}
builder.listener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityInfo activity = list.get(which).activityInfo;
ComponentName name = new ComponentName(
activity.applicationInfo.packageName, activity.name);
Intent newIntent = (Intent) shareIntent.clone();
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
newIntent.setComponent(name);
startActivity(newIntent);
}
});
return builder;
}
protected void setMaterialRippleWithGrayOnView(View mView) {
MaterialRippleLayout
.on(mView)
.rippleColor(Color.parseColor("#aaaaaa"))
.rippleAlpha(0.2f)
.rippleHover(true)
.rippleOverlay(true)
.rippleBackground(
Color.parseColor("#00000000"))
.create();
}
protected void setMaterialRippleOnView(View mView) {
MaterialRippleLayout.on(mView).rippleColor(Color.parseColor("#ffffff"))
.rippleAlpha(0.2f).rippleHover(true).rippleOverlay(true)
.rippleBackground(Color.parseColor("#00000000")).create();
}
protected void setToolBarOption(){
supportInvalidateOptionsMenu();
}
protected boolean isFileCorrupted(String mFilePath, String mFileSize){
try{
if(new File(mFilePath).length() == Long.parseLong(mFileSize)){
return false;
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
return false;
}
return true;
}
protected int isFromTraining(String mCategory){
try{
if(mCategory.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.MOBCAST)){
return 0;
}else if(mCategory.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.TRAINING)){
return 1;
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
return 0;
}
}
|
/*
* Copyright 2014. AppDynamics LLC and its affiliates.
* All Rights Reserved.
* This is unpublished proprietary source code of AppDynamics LLC and its affiliates.
* The copyright notice above does not evidence any actual or intended publication of such source code.
*/
package com.appdynamics.monitors.iPlanet.beans;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
@XStreamAlias("connection-queue-bucket")
public class ConnectionQueueBucket {
@XStreamAsAttribute()
@XStreamAlias("connection-queue")
private String connectionQueue;
@XStreamAsAttribute()
private String countTotalConnections;
@XStreamAsAttribute()
private String countQueued;
@XStreamAsAttribute()
private String peakQueued;
@XStreamAsAttribute()
private String maxQueued;
@XStreamAsAttribute()
private String countOverflows;
@XStreamAsAttribute()
private String countTotalQueued;
@XStreamAsAttribute()
private String ticksTotalQueued;
@XStreamAsAttribute()
private String countQueued1MinuteAverage;
@XStreamAsAttribute()
private String countQueued5MinuteAverage;
@XStreamAsAttribute()
private String countQueued15MinuteAverage;
public String getConnectionQueue() {
return connectionQueue;
}
public void setConnectionQueue(String connectionQueue) {
this.connectionQueue = connectionQueue;
}
public String getCountTotalConnections() {
return countTotalConnections;
}
public void setCountTotalConnections(String countTotalConnections) {
this.countTotalConnections = countTotalConnections;
}
public String getCountQueued() {
return countQueued;
}
public void setCountQueued(String countQueued) {
this.countQueued = countQueued;
}
public String getPeakQueued() {
return peakQueued;
}
public void setPeakQueued(String peakQueued) {
this.peakQueued = peakQueued;
}
public String getMaxQueued() {
return maxQueued;
}
public void setMaxQueued(String maxQueued) {
this.maxQueued = maxQueued;
}
public String getCountOverflows() {
return countOverflows;
}
public void setCountOverflows(String countOverflows) {
this.countOverflows = countOverflows;
}
public String getCountTotalQueued() {
return countTotalQueued;
}
public void setCountTotalQueued(String countTotalQueued) {
this.countTotalQueued = countTotalQueued;
}
public String getTicksTotalQueued() {
return ticksTotalQueued;
}
public void setTicksTotalQueued(String ticksTotalQueued) {
this.ticksTotalQueued = ticksTotalQueued;
}
public String getCountQueued1MinuteAverage() {
return countQueued1MinuteAverage;
}
public void setCountQueued1MinuteAverage(String countQueued1MinuteAverage) {
this.countQueued1MinuteAverage = countQueued1MinuteAverage;
}
public String getCountQueued5MinuteAverage() {
return countQueued5MinuteAverage;
}
public void setCountQueued5MinuteAverage(String countQueued5MinuteAverage) {
this.countQueued5MinuteAverage = countQueued5MinuteAverage;
}
public String getCountQueued15MinuteAverage() {
return countQueued15MinuteAverage;
}
public void setCountQueued15MinuteAverage(String countQueued15MinuteAverage) {
this.countQueued15MinuteAverage = countQueued15MinuteAverage;
}
}
|
package com.hcl.cms.data.session;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Iterator;
import java.util.Vector;
import com.filenet.api.collection.ObjectStoreSet;
import com.filenet.api.core.Connection;
import com.filenet.api.core.Domain;
import com.filenet.api.core.Factory;
import com.filenet.api.core.ObjectStore;
import com.hcl.cms.data.params.CmsSessionObjectParams;
/**
* @author sakshi_ja
*
*/
public class CEConnectionManager {
CmsSessionObjectParams objectParams;
Connection con;
/******** Development Content Engine Connection ********/
public CEConnectionManager(Connection con) {
this.con=con;
}
/**
* method to get object store object through object store name
* @param objectStoreName
* @return
* @throws GeneralSecurityException
* @throws IOException
*/
public CmsSessionObjectParams getObjectStore(String objectStoreName) throws GeneralSecurityException, IOException
{
ObjectStore store = null;
try{
Domain domain = Factory.Domain.fetchInstance((com.filenet.api.core.Connection)this.con, null, null);
objectParams=new CmsSessionObjectParams();
objectParams.setDomain(domain.get_Name());
store=Factory.ObjectStore.fetchInstance(domain, objectStoreName, null);
objectParams.setStore(store);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return objectParams;
}
}
|
package com.iblogstreet.titlebarchangecolor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.iblogstreet.titlebarchangecolor.view.MyListView;
import com.iblogstreet.titlebarchangecolor.view.ObservableScrollView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity
extends AppCompatActivity
implements ObservableScrollView.IScrollViewListener
{
private static final String TAG = "MainActivity";
//ScrollView
ObservableScrollView obserView;
TextView tvTitle;
MyListView lvData;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
initData();
initEvent();
}
int height;
private void initEvent() {
ViewTreeObserver viewTreeObserver = image.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
image.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
height = image.getHeight();
Log.e(TAG, "height:" + height);
obserView.setScrollViewListener(MainActivity.this);
}
});
}
List<String> mData;
private void initData() {
mData = new ArrayList<>();
for (int i = 0; i < 30; i++) {
mData.add("This is Test" + i);
}
lvData.setAdapter(new MyAdapter());
}
class MyAdapter
extends BaseAdapter
{
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewholder = null;
if (convertView == null) {
viewholder = new ViewHolder();
convertView = View.inflate(getApplicationContext(), R.layout.item_lv, null);
viewholder.tvDesc = (TextView) convertView.findViewById(R.id.tvdesc);
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
viewholder.tvDesc.setText("" + mData.get(position));
return convertView;
}
class ViewHolder {
TextView tvDesc;
}
}
private void initView() {
obserView = (ObservableScrollView) findViewById(R.id.scroll);
tvTitle = (TextView) findViewById(R.id.tv_title);
lvData = (MyListView) findViewById(R.id.lv_data);
image = (ImageView) findViewById(R.id.iv);
}
@Override
public void onScrollChanged(int x, int y, int oldx, int oldy) {
if (y <= 0) {
Log.e(TAG, "Top");
tvTitle.setBackgroundColor(Color.argb((int) 0, 227, 29, 26));//AGB由相关工具获得,或
} else if (y > 0 && y < height) {
Log.e(TAG, "middle");
float scale = (float) y / height;
float alpha = (255 * scale);
Log.e(TAG, "alpha:" + alpha);
// 只是layout背景透明(仿知乎滑动效果)
tvTitle.setBackgroundColor(Color.argb((int) alpha, 227, 29, 26));
} else {
Log.e(TAG, "Bottom");
tvTitle.setBackgroundColor(Color.argb((int) 255, 227, 29, 26));
}
}
}
|
package com.project.universitystudentassistant.utils;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class AppConstants {
public static final String USERS = "users";
public static final String DUMMY_EMAIL = "dummy@email.com";
public static final String DUMMY_PASSWORD = "123456";
public static final String FRAGMENT_SEARCH_UNIVERSITIES = "fragment_search_universities";
public static final String FRAGMENT_MY_UNIVERSITIES = "fragment_my_universities";
public static final String APP_SHARED_PREFERENCES = "app_shared_preferences";
public static final String NAME = "name";
public static final String STATE = "state";
public static final String ATTENDANCE_COST = "cost";
public static final String ACCEPTANCE_RATE = "acceptance";
public static final String GRADUATION_RATE = "graduation";
public static final String SAVED = "saved";
}
|
package com.napier.sem;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
/**
*
*/
public class App
{
public static void main(String[] args)
{
// Connect to MongoDB on local system - we're using port 27000
MongoClient mongoClient = new MongoClient("localhost", 27000);
// Get a database - will create when we use it
MongoDatabase database = mongoClient.getDatabase("mydb");
// Get a collection from the database
MongoCollection<Document> collection = database.getCollection("test");
// Create a document to store
Document doc = new Document("name", "Kevin Chalmers")
.append("class", "Software Engineering Methods")
.append("year", "2018/19")
.append("result", new Document("CW", 95).append("EX", 85));
// Add document to collection
collection.insertOne(doc);
// Check document in collection
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
}
} |
package com.bakerystudios.game.questions;
import java.util.List;
public class State {
private String name;
private List<Question> questions;
public State(String name, List<Question> questions) {
this.name = name;
this.questions = questions;
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public List<Question> getQuestions() {return questions;}
public void setQuestions(List<Question> questions) {this.questions = questions;}
}
|
package ziegler.philosophers;
public class Fork {
private boolean inUse;
private int forkNum;
private String name;
public Fork(int forkNum){
this.forkNum = forkNum;
name = String.valueOf(forkNum);
}
public void pickUp(){
inUse = true;
}
public void putDown(){
inUse = false;
}
public boolean inUse(){
return inUse;
}
public int getForkNum(){
return forkNum;
}
public String getName(){
return name;
}
}
|
package GBN;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Client{
//发送端缓存
private Map<Integer,DatagramPacket> sendBuf = new HashMap<>();
//接收的内容(有序)
private ByteArrayOutputStream receive=new ByteArrayOutputStream();
//本机socket
private DatagramSocket socket;
//本机地址
private InetAddress address = null;
//socket绑定的端口号
private int port;
//发送窗口大小
private int sendWin = 20;
//序列号最大数maxSeq>=sendWin+receiveWin
private int maxSeq = 40;
//发送窗口起始
private int sendBase = 0;
private int expectReceive = 0;
//每个分组包含的最大数据字节数
private int maxData = 1200;
//发送窗口下一个序列号
private int sendNext = 0;
//计时器
private Time clock= new Time(this);
//过期时间
private int restTime = 3;
/**
* 构造函数,需指定绑定的端口
* @param port 绑定的端口号
*/
public Client(int port) {
try {
//创建socket
socket = new DatagramSocket(port);
this.port = port;
} catch (SocketException e) {
e.printStackTrace();
}
}
/**
* 向指定地址与端口号发送文件内容,由于窗口大小有效,可能不能一次完成所有发送,需要重复调用该方法,因此
* 返回值为下次发送的文件起始位置。
* @param content 发送的文件内容
* @param seq 开始发送时报文开始的序号
* @param sendAddress 目的地址
* @param sendPort 目的端口号
* @param start 开始发送的起点
* @return 此次发送结束点,也就是下次发送时的起点。若文件已经全部发送,则返回-1
*/
public int send(byte[] content,int seq,InetAddress sendAddress,int sendPort,int start,int end){
if(content.length==0) {
ByteArrayOutputStream Send = new ByteArrayOutputStream();
Send.write((byte)seq);
sendData(Send.toByteArray(),seq,sendAddress,sendPort);
try {
Send.close();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
if(start<0) {
return -1;
}
//若发送窗口未满,则可以继续发送
while(((sendNext<sendBase)&&((sendBase+sendWin)%maxSeq>sendNext))||
((sendNext>sendBase)&&(sendBase+sendWin>sendNext))||
(sendNext==sendBase)) {
try {
ByteArrayOutputStream Send = new ByteArrayOutputStream();
seq = sendNext;
sendNext = (sendNext+1)%maxSeq;
Send.write((byte)seq);
System.out.println("正在发送Seq为:"+seq+"的数据包");
if(end-start<=maxData) {
byte[]sendcontent = Arrays.copyOfRange(content, start, end);
Send.write(sendcontent);
sendData(Send.toByteArray(),seq,sendAddress,sendPort);
return -1;
}
else {
byte[]sendcontent = Arrays.copyOfRange(content, start, start+maxData);
Send.write(sendcontent);
sendData(Send.toByteArray(),seq,sendAddress,sendPort);
start += maxData;
}
Send.close();
}catch(IOException e) {
}
}
System.out.println("发送窗口已满,等待接收ACK移动窗口");
return start;
}
/**
* 组建报文并发送到指定地址与指定端口
* @param send 需要发送的报文的数据部分
* @param seq 报文的序号
* @param sendAddress 目的地址
* @param sendPort 目的端口号
*/
public void sendData(byte[] send,int seq,InetAddress sendAddress,int sendPort) {
DatagramPacket data = new DatagramPacket(send,send.length,sendAddress,sendPort);
if(send.length>1) {
sendBuf.put(seq, data);
if(seq == sendBase) {
clock.begin();
}
}
//非结束标志报文,均有可能丢失
if(seq>=0) {
//丢包率为0.4
if(Math.random()<0.4)
return;
}
try {
socket.send(data);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发送content,目的地址为targetAddress,目的端口为targetPort
* @param content 将要发生的内容
* @param targetAddress 目的地址
* @param targetPort 目的端口号
*/
@SuppressWarnings("deprecation")
public void sendTo(byte content[],InetAddress targetAddress,int targetPort) {
int start = 0;
//打开定时器
clock.start();
while((start =send(content,-1,targetAddress,targetPort,start,content.length))>=0||!sendBuf.isEmpty()) {
//接收ACK数据报并从数据报中获取ACK值
getInfo(receive(100));
}
clock.stop();
//收到所有ACK时,标志文件发送结束,因此发送一个seq为-1的空数据报表示发送的完成
send(new byte[0],-1,targetAddress,targetPort,0,0);
System.out.println("发送已经结束");
}
/**
* 当报文超时时,由定时器调用该方法,重发超时报文
* @param seq 超时的报文seq
*/
public void timeOut() {
int seq = sendBase;
while(sendBuf.containsKey(seq)) {
try {
socket.send(sendBuf.get(seq));
System.err.println("重传:"+seq+" 号报文");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
seq++;
}
clock.begin();
}
/**
* 查询发送缓存中是否存在指定seq数据包(序号为seq的数据包是否收到ACK)
* @param seq 查询的数据包序号
* @return 若序号为seq的数据包仍未进行确认,仍然在发送缓存中,则返回true
*/
public boolean containsAck(int seq) {
return sendBuf.containsKey(seq);
}
/**
* 读取指定路径的文件内容
* @param filepath 文件路径
* @return 文件内容
*/
public byte[] getContent(String filepath) {
File file = new File(filepath);
byte content[]=new byte[(int) file.length()];
try {
FileInputStream input = new FileInputStream(file);
input.read(content);
input.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
/**
* 开始向指定地址与端口号发送文件
* @param sendAddress 文件发送的目的地址
* @param port 文件发送的目的端口号
* @param filepath 文件的所在路径
*/
public void startSend(InetAddress sendAddress,int port,String filepath) {
InetAddress targetAddress = sendAddress;
int targetPort = port;
byte content[] = getContent(filepath);
System.out.println("开始发送文件:"+filepath);
sendTo(content,targetAddress,targetPort);
}
/**
* 开始进行文件的接收
*/
public void startReceive() {
DatagramPacket data;
while(true) {
data = receive(100);
if(getInfo(data)==true) {
break;
}
}
System.err.println("接收已结束,结束数据为:");
System.err.println(new String(receive.toByteArray()));
}
/**
* 获取本机地址,为了进行测试,以本机地址作为接收地址
* @return 本机的地址
*/
public InetAddress getAddress() {
if(address==null) {
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return address;
}
/**
* 获取绑定的Port
* @return 返回本客户端绑定的端口号(发送方与接收方不同)
*/
public int getPort() {
return port;
}
/**
* 接收数据报
* @param time 等待接收的超时时间,由于DatagramSocket.receive()是阻塞式方法,必须进行超时设置,否则程序将一直阻塞无法运行
* @return 所获取的数据包,若在等待时间内未接收到任何数据,将返回null
*/
public DatagramPacket receive(int time) {
byte[] bytes = new byte[1500];
DatagramPacket data = new DatagramPacket(bytes,bytes.length);
try {
socket.setSoTimeout(time);
socket.receive(data);
} catch(SocketTimeoutException e) {
//数据包中端口号为-1,表示该等待时间内未接收任何数据包
if(data.getPort()==-1) {
return null;
}
}catch (IOException e) {
e.printStackTrace();
}
return data;
}
/**
* 从数据报中获取所需信息:为ACK数据报或携带传输内容并进行相应处理。
* 接收到ACK后,窗口可能进行相应移动,且对应定时器需要进行关闭。
* 接收到数据后,需要获取传输的内容,并放入接收缓存或组装交给上层(此处进行简化,若为从receiveBase开始的连续数据
* ,则将其加入receive中)
* @param data 收到的数据报
* @return 数据报是否表示发送结束(数据报中Seq是否为0)
*/
public boolean getInfo(DatagramPacket data) {
if(data == null)
return false;
byte receiveData[] = data.getData();
InetAddress sendAddress = data.getAddress();
int sendPort = data.getPort();
data.getAddress();
data.getPort();
int seq = (int)receiveData[0];
int length = data.getLength();
if(length == 1) {
if(seq==-1) {
return true;
}
System.out.println("报文:"+seq+" 已经正确接收");
if((sendBase<seq&&sendBase+sendWin>seq)||(((sendBase+sendWin)%maxSeq>seq)&&(sendBase<seq))){
while(sendBase<seq&&sendBase+sendWin>seq) {
sendBuf.remove(sendBase);
sendBase = (sendBase+1)%maxSeq;
}
}
if(seq == sendBase) {
System.out.println("报文:"+seq+" 已经正确接收");
sendBuf.remove(seq);
sendBase = (sendBase+1)%maxSeq;
System.out.println("SendBase加1,现为"+sendBase);
if(sendBase == sendNext) {
clock.Stop();
}
else {
clock.begin();
}
}
}else {
if(seq==expectReceive) {
System.out.println("Seq:"+seq+" 等于receiveBase,按序到达,成功接收");
receive.write(receiveData, 1, length-1);
send(new byte[0],expectReceive,sendAddress,sendPort,0,0);
expectReceive = (expectReceive+1)%maxSeq;
System.out.println("expectReceive="+expectReceive);
}
else {
send(new byte[0],expectReceive-1,sendAddress,sendPort,0,0);
System.err.println(seq+"不为expectReceive,丢弃");
}
}
return false;
}
/**
* 将收到的内容写入指定文件
* @param filepath 写入文件的路径
*/
public void writeFile(String filepath) {
File file = new File(filepath);
try {
FileOutputStream output = new FileOutputStream(file);
output.write(receive.toByteArray(), 0, receive.size());
output.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.practice.java8.newfeatures.lambda;
import java.util.Objects;
public class Student {
private String name;
private String grade;
private String total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String name, String grade, String total) {
this.name = name;
this.grade = grade;
this.total = total;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade='" + grade + '\'' +
", total='" + total + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(grade, student.grade) &&
Objects.equals(total, student.total);
}
@Override
public int hashCode() {
return Objects.hash(name, grade, total);
}
}
|
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package jp.ac.kyushu_u.csce.modeltool.base.utility;
import jp.ac.kyushu_u.csce.modeltool.base.ModelToolBasePlugin;
import org.eclipse.core.commands.common.EventManager;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
/**
* The <code>ColorSelector</code> is a wrapper for a button that displays a
* selected <code>Color</code> and allows the user to change the selection.
*
* 未使用のためそのうち削除します
*
* @deprecated
*/
public class ColorSelector extends EventManager {
/**
* Property name that signifies the selected color of this
* <code>ColorSelector</code> has changed.
*
* @since 3.0
*/
public static final String PROP_COLORCHANGE = "colorValue"; //$NON-NLS-1$
private Button fButton;
private Color fColor;
private RGB fColorValue;
private Point fExtent;
private Image fImage;
/**
* Create a new instance of the reciever and the button that it wrappers in
* the supplied parent <code>Composite</code>.
*
* @param parent
* The parent of the button.
*/
public ColorSelector(Composite parent) {
fButton = new Button(parent, SWT.PUSH);
fExtent = computeImageSize(parent);
fImage = new Image(parent.getDisplay(), fExtent.x, fExtent.y);
GC gc = new GC(fImage);
gc.setBackground(fButton.getBackground());
gc.fillRectangle(0, 0, fExtent.x, fExtent.y);
gc.dispose();
fButton.setImage(fImage);
fButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
open();
}
});
fButton.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent event) {
if (fImage != null) {
fImage.dispose();
fImage = null;
}
if (fColor != null) {
fColor.dispose();
fColor = null;
}
}
});
fButton.getAccessible().addAccessibleListener(new AccessibleAdapter() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.accessibility.AccessibleAdapter#getName(org.eclipse.swt.accessibility.AccessibleEvent)
*/
public void getName(AccessibleEvent e) {
e.result = JFaceResources.getString("ColorSelector.Name"); //$NON-NLS-1$
}
});
}
/**
* Adds a property change listener to this <code>ColorSelector</code>.
* Events are fired when the color in the control changes via the user
* clicking an selecting a new one in the color dialog. No event is fired in
* the case where <code>setColorValue(RGB)</code> is invoked.
*
* @param listener
* a property change listener
* @since 3.0
*/
public void addListener(IPropertyChangeListener listener) {
addListenerObject(listener);
}
/**
* Compute the size of the image to be displayed.
*
* @param window -
* the window used to calculate
* @return <code>Point</code>
*/
private Point computeImageSize(Control window) {
GC gc = new GC(window);
Font f = JFaceResources.getFontRegistry().get(
JFaceResources.DIALOG_FONT);
gc.setFont(f);
int height = gc.getFontMetrics().getHeight();
gc.dispose();
Point p = new Point(height * 3 - 6, height);
return p;
}
/**
* Get the button control being wrappered by the selector.
*
* @return <code>Button</code>
*/
public Button getButton() {
return fButton;
}
/**
* Return the currently displayed color.
*
* @return <code>RGB</code>
*/
public RGB getColorValue() {
return fColorValue;
}
/**
* Removes the given listener from this <code>ColorSelector</code>. Has
* no affect if the listener is not registered.
*
* @param listener
* a property change listener
* @since 3.0
*/
public void removeListener(IPropertyChangeListener listener) {
removeListenerObject(listener);
}
/**
* Set the current color value and update the control.
*
* @param rgb
* The new color.
*/
public void setColorValue(RGB rgb) {
fColorValue = rgb;
updateColorImage();
}
/**
* Set whether or not the button is enabled.
*
* @param state
* the enabled state.
*/
public void setEnabled(boolean state) {
getButton().setEnabled(state);
}
/**
* Update the image being displayed on the button using the current color
* setting.
*/
protected void updateColorImage() {
Display display = fButton.getDisplay();
GC gc = new GC(fImage);
gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
gc.drawRectangle(0, 2, fExtent.x - 1, fExtent.y - 4);
if (fColor != null) {
fColor.dispose();
}
fColor = new Color(display, fColorValue);
gc.setBackground(fColor);
gc.fillRectangle(1, 3, fExtent.x - 2, fExtent.y - 5);
gc.dispose();
fButton.setImage(fImage);
}
/**
* Activate the editor for this selector. This causes the color selection
* dialog to appear and wait for user input.
*
* @since 3.2
*/
public void open() {
ColorDialog colorDialog = new ColorDialog(fButton.getShell());
colorDialog.setRGB(fColorValue);
RGB newColor = colorDialog.open();
IStatus status = new Status(
IStatus.ERROR, ModelToolBasePlugin.PLUGIN_ID,
"ColorSelector " + newColor, //$NON-NLS-1$
null);
ModelToolBasePlugin.getDefault().getLog().log(status);
if (newColor != null) {
RGB oldValue = fColorValue;
fColorValue = newColor;
final Object[] finalListeners = getListeners();
if (finalListeners.length > 0) {
PropertyChangeEvent pEvent = new PropertyChangeEvent(
this, PROP_COLORCHANGE, oldValue, newColor);
for (int i = 0; i < finalListeners.length; ++i) {
IPropertyChangeListener listener = (IPropertyChangeListener) finalListeners[i];
listener.propertyChange(pEvent);
}
}
updateColorImage();
}
}
}
|
package fr.lteconsulting.pomexplorer;
/**
* Identifies a section in the pom.xml
*
* @author Arnaud
*/
public enum PomSection
{
PROJECT,
PARENT,
DEPENDENCY_MNGT,
DEPENDENCY,
PLUGIN_MNGT,
PLUGIN;
} |
package model.match;
public enum MatchState {
Fixture, Result, Toss, InningsOneInProgress, InningsBreak, InningsTwoInProgress
} |
package com.alibaba.druid.bvt.sql.sqlserver.grants;
import org.junit.Assert;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor;
import com.alibaba.druid.sql.parser.Token;
import com.alibaba.druid.util.JdbcConstants;
import junit.framework.TestCase;
public class SQLServerGrantTest_0 extends TestCase {
public void test_grants() throws Exception {
String sql = "grant all on database::TestDataBase to User1";
SQLServerStatementParser parser = new SQLServerStatementParser(sql);
SQLStatement stmt = parser.parseStatementList().get(0);
parser.match(Token.EOF);
SQLServerSchemaStatVisitor visitor = new SQLServerSchemaStatVisitor();
stmt.accept(visitor);
System.out.println("Tables : " + visitor.getTables());
System.out.println("fields : " + visitor.getColumns());
System.out.println("coditions : " + visitor.getConditions());
System.out.println("orderBy : " + visitor.getOrderByColumns());
String output = SQLUtils.toSQLString(stmt, JdbcConstants.SQL_SERVER);
Assert.assertEquals("GRANT ALL ON DATABASE::TestDataBase TO User1", output);
Assert.assertEquals(0, visitor.getTables().size());
Assert.assertEquals(0, visitor.getColumns().size());
}
}
|
package com.beike.service.diancai;
import java.util.List;
import java.util.Map;
import com.beike.entity.catlog.RegionCatlog;
import com.beike.entity.onlineorder.AbstractEngine;
import com.beike.entity.onlineorder.BookingGoods;
import com.beike.entity.onlineorder.BranchInfo;
import com.beike.entity.onlineorder.OrderMenu;
import com.beike.page.Pager;
import com.beike.util.json.JSONArray;
/**
* com.beike.service.diancai.DianCaiService.java
* @description:点菜Service
* @Author:xuxiaoxian
* Copyright:Copyright (c) 2012
* @Compony:Sinobo
* @date: 2012-11-7
*/
public interface DianCaiService {
/**
*
* janwen
* @param branchid
* @return 分店信息
*
*/
public BranchInfo getBranchInfo(Long branchid);
public List<BranchInfo> getHistroyBranchesInfo(List<Long> branchids);
/**
*
* janwen
* @param branchid
* @return 分店卖的最好的商品
*
*/
public BookingGoods getTopone(Long branchid);
/**
*
* janwen
* @param branchid
* @return 分店促销信息
*
*/
public AbstractEngine getPromotionInfo(Long branchid);
public List<List<OrderMenu>> getOrderMenuListByID(Long order_id,List<String> tags);
public List<List<OrderMenu>> getOrderMenuListByBranchid(Long branchid,List<String> tags);
/**
*
* @Title: getOrderByMerId
* @Description: 获取品牌支持点菜菜的分店
* @param @param merId:品牌标识
* @return 支持点菜分店集合
* @throws :sql异常
*/
public List<Object> getOrderByMerId(Long merId) throws Exception;
/**
*
* janwen
* @param promotionid
* @return 分类
*
*/
public List<String> getCategory(Long branchid);
/**
*
* janwen
* @param order_id
* @param items
* @return 计算折扣后的价格
*
*/
public double caculateAmount(Long branchid,List<OrderMenu> items);
/**
*
* janwen
* @param sn
* @return 用户点餐详细信息
*
*/
public Map<String,List<OrderMenu>> getPaidOrderMenuByTrxGoodsid(String trx_goods_id);
/**
*
* janwen
* @param historyjson
* @return 历史分店订单
*
*/
public Map<String,List<OrderMenu>> gethistoryOrderMenus(JSONArray historyjson,Long selectedBranchid) throws Exception;
/**
*
* @Title: listOfOrders
* @Description: 可点餐的分店列表
* @param @param paramMap 设定文件
* @return void 返回类型
* @throws
*/
public List<Map<String, Object>> listOfOrders(Map<String, String> paramMap,Pager pager);
/**
*
* @Title: getCountListOfOrders
* @Description: 可点餐的分店列表的总数
* @param @param paramMap
* @param @return 设定文件
* @return int 返回类型
* @throws
*/
public Integer getCountListOfOrders(Map<String, String> paramMap);
/**
*
* @Title: getSupportOrderRegion
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param cityId
* @param @return 设定文件
* @return Map<Long,List<RegionCatlog>> 返回类型
* @throws
*/
public Map<Long, List<RegionCatlog>> getSupportOrderRegion(Long cityId,String nowStr);
/**
* @return
*
* @Title: getBranchMenuList
* @Description: 分店下的点菜
* @param @param branchids 设定文件
* @return void 返回类型
* @throws
*/
public List<OrderMenu> getBranchMenuList(String branchids,Integer limitNum);
}
|
package com.itmayiedu.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class MemberService {
//添加用户的时候会发送邮件
@Async //相当于这个方法开辟了单独现场进行执行
public String addMemberAndEmail(){
System.out.println("Service addMemberAndEmail>>>>>>>>>>>>>1");
try {
Thread.sleep(5000);
}catch (Exception e){
}
System.out.println("Service addMemberAndEmail>>>>>>>>>>>>>2");
return "MemberService OK";
}
}
|
package 设计模式.建造者模式.improve;
//抽象的建造者
public abstract class HouseBuilder {
protected House house=new House();
//将建造的流程写好,抽象的方法
public abstract void buildBasic();
public abstract void buildBWalls();
public abstract void roofed();
//建造房子好,将产品返回
public House buildHouse(){
return house;
}
}
|
package com.ferreusveritas.growingtrees.entities;
import net.minecraft.client.particle.EntityAuraFX;
import net.minecraft.world.World;
public class EntityParticleLeaf extends EntityAuraFX {
public EntityParticleLeaf(World world, double x, double y, double z, double velx, double vely, double velz) {
super(world, x, y, z, velx, vely, velz);
motionY = vely;
setParticleTextureIndex(82);
particleScale = 1.0f;
setRBGColorF(1.0f, 1.0f, 1.0f);
}
@Override
public void onUpdate(){
super.onUpdate();
}
}
|
package softagi.urdecision.Models;
public class UserModel
{
private String name,gender;
public UserModel() {
}
public UserModel(String name, String gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
|
/*
* Copyright 2020 WeBank
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.wedatasphere.schedulis.eventcheck;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import com.webank.wedatasphere.schedulis.jobtype.util.EventChecker;
import com.webank.wedatasphere.schedulis.jobtype.util.ShellUtils;
/**
* @author peacewong
* @Title: EventcheckReceiver
* @date 2019/9/1822:17
*/
public class DefaultEventcheckReceiver extends AbstractEventCheckReceiver{
String todayStartTime;
String todayEndTime;
String allStartTime;
String allEndTime;
String nowStartTime;
public DefaultEventcheckReceiver(Properties props) {
initECParams(props);
initReceiverTimes();
}
private void initReceiverTimes(){
todayStartTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
todayEndTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59");
allStartTime = DateFormatUtils.format(new Date(), "10000-01-01 00:00:00");
allEndTime = DateFormatUtils.format(new Date(), "9999-12-31 23:59:59");
nowStartTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
}
@Override
public boolean reciveMsg(int jobId, Properties props, Logger log) {
Long startTime = System.currentTimeMillis();
Long currentTime = startTime;
Double doubleWaitTime = Double.valueOf(waitTime) * 3600 * 1000;
Long waitTime = Long.valueOf(doubleWaitTime.longValue());
int queryFrequency = Integer.valueOf(query_frequency);
if(wait_for_time!=null && props.containsKey(EventChecker.WAIT_FOR_TIME)){
waitForTime(log,waitTime);
}
log.info("-------------------------------------- waiting time(unit:millisecond) : " + waitTime);
log.info("-------------------------------------- Number of query frequency in waiting time : " + queryFrequency);
Long sleepTime = waitTime / queryFrequency;
if(sleepTime < 60000L){
log.info("your setting is less than the minimum polling time(60s), the system will automatically set it to 60s");
sleepTime = 60000L;
}
boolean result = false;
while ((currentTime - startTime) <= waitTime) {
boolean flag = false;
try{
//step1
//这里让线程随机休眠0到1秒,防止多个receiver在同一时刻重复更新event_status;
Thread.sleep(new Random().nextInt(1000));
String lastMsgId = getOffset(jobId,props,log);
String[] executeType = createExecuteType(jobId,props,log,lastMsgId);
if(executeType!=null && executeType.length ==3){
//step2
String[] consumedMsgInfo = getMsg(props, log,executeType);
if(consumedMsgInfo!=null && consumedMsgInfo.length == 4){
//step3
flag = updateMsgOffset(jobId,props,log,consumedMsgInfo,lastMsgId);
}else if (trigger_time != null && !"".equals(trigger_time.trim())){
flag = autoTrigger(log,props);
}
}else{
log.error("executeType error {} " + Arrays.toString(executeType));
return result;
}
int i = 1 ;
String azkabanPid = "0";
while(i < 5){
azkabanPid = ShellUtils.getPPid(ShellUtils.getPid());
if("1".equals(azkabanPid)){
i++;
Thread.sleep(new Random().nextInt(1000));
}else{
break;
}
}
if ("1".equals(azkabanPid)) {
throw new RuntimeException("Azkaban-exec has been terminated!");
}
}catch (Exception e){
log.error("EventChecker failed to receive the message {}" + e);
return result;
}
if (flag) {
result = flag;
break;
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw new RuntimeException("An exception occurred in the waiting for rotation training!" + e);
}
currentTime = System.currentTimeMillis();
}
if (!result) {
throw new RuntimeException("EventChecker receives the message timeout!");
}
return result;
}
private String[] createExecuteType(int jobId, Properties props, Logger log,String lastMsgId){
boolean receiveTodayFlag = (null != receiveToday && "true".equals(receiveToday.trim().toLowerCase()));
boolean afterSendFlag = (null != afterSend && "true".equals(afterSend.trim().toLowerCase()));
String[] executeType = null;
try {
if ("0".equals(lastMsgId)){
if(receiveTodayFlag){
if(afterSendFlag){
executeType = new String[]{nowStartTime,todayEndTime,"0"};
}else{
executeType = new String[]{todayStartTime,todayEndTime,"0"};
}
}else{
if(afterSendFlag){
executeType = new String[]{nowStartTime,allEndTime,"0"};
}else{
executeType = new String[]{allStartTime,allEndTime,"0"};
}
}
}else{
if(receiveTodayFlag){
if(afterSendFlag){
executeType = new String[]{nowStartTime,todayEndTime,lastMsgId};
}else{
executeType = new String[]{todayStartTime,todayEndTime,lastMsgId};
}
}else{
if(afterSendFlag){
executeType = new String[]{nowStartTime,allEndTime,lastMsgId};
}else{
executeType = new String[]{allStartTime,allEndTime,lastMsgId};
}
}
}
}catch(Exception e){
log.error("create executeType failed {}" + e);
}
return executeType;
}
private void waitForTime(Logger log,Long waitTime){
String waitForTime = wait_for_time;
String formatWaitForTime = DateFormatUtils.format(new Date(),"yyyy-MM-dd " + waitForTime + ":00");
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date targetWaitTime = null;
try {
targetWaitTime = fmt.parse(formatWaitForTime);
} catch (ParseException e) {
log.error("parse date failed {}" + e);
}
log.info("It will success at a specified time: " + targetWaitTime);
long wt = targetWaitTime.getTime() - System.currentTimeMillis();
if(wt > 0){
//wt must less than wait.time
if(wt <= waitTime){
log.info("EventChecker will wait "+ wt + " milliseconds before starting execution");
try {
Thread.sleep(wt);
} catch (InterruptedException e) {
throw new RuntimeException("EventChecker throws an exception during the waiting time {}"+e);
}
}else{
throw new RuntimeException("The waiting time from Job starttime to wait.for.time"+ wt +"(ms) greater than wait.time , unreasonable setting!");
}
}else{
log.info("EventChecker has reached the specified time");
}
}
private boolean autoTrigger(Logger log,Properties props){
String formatTriggerTime = DateFormatUtils.format(new Date(),"yyyy-MM-dd " + trigger_time + ":00");
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date targetTriggerTime = null;
try {
targetTriggerTime = fmt.parse(formatTriggerTime);
} catch (ParseException e) {
log.error("parse date failed {}" + e);
}
long wt = targetTriggerTime.getTime() - System.currentTimeMillis();
if(wt < 0){
log.info("EventChecker has reached the automatic trigger time point:" + targetTriggerTime);
if (null == trigger_param) {
props.put(EventChecker.MSG, "NULL");
} else {
props.put(EventChecker.MSG, trigger_param);
}
return true;
}
return false;
}
}
|
package asktechforum.repositorio;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import asktechforum.dominio.Pergunta;
import asktechforum.dominio.Resposta;
import asktechforum.dominio.Usuario;
import asktechforum.interfaces.CadastroResposta;
import asktechforum.util.ConnectionUtil;
public class CadastroRespostaDAO implements CadastroResposta {
private Connection con = null;
public CadastroRespostaDAO() {
}
public String adicionarResposta(Resposta resposta) throws SQLException {
String retorno = "cadastroSucesso";
String sql = "insert into RESPOSTA(descricao, idUsuario, idPergunta, data, hora)values(?,?,?,?,?)";
PreparedStatement stmt = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
int index = 0;
stmt.setString(++index, resposta.getDescricao());
stmt.setInt(++index, resposta.getIdUsuario());
stmt.setInt(++index, resposta.getIdPergunta());
stmt.setDate(++index, resposta.getData());
stmt.setTime(++index, resposta.getHora());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stmt.close();
this.con.close();
}
return retorno;
}
public void deletarResposta(int id) throws SQLException {
String sql = "delete from RESPOSTA where idResposta = " + id;
PreparedStatement stmt = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stmt.close();
this.con.close();
}
}
public Resposta consultarRespostaPorIdResposta(int id) throws SQLException {
Resposta resposta = new Resposta();
String sql = "select * from RESPOSTA where idResposta = " + id;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
resposta.setData(rs.getDate("data"));
resposta.setDescricao(rs.getString("descricao"));
resposta.setHora(rs.getTime("hora"));
resposta.setIdPergunta(rs.getInt("idPergunta"));
resposta.setIdResposta(rs.getInt("idResposta"));
resposta.setIdUsuario(rs.getInt("idUsuario"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
this.con.close();
}
return resposta;
}
public ArrayList<Resposta> consultarRespostaPorIdUsuario(int id)
throws SQLException {
ArrayList<Resposta> resposta = new ArrayList<Resposta>();
String sql = "select * from RESPOSTA where idUsuario = " + id
+ " order by data, hora";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Resposta r = new Resposta();
r.setData(rs.getDate("data"));
r.setDescricao(rs.getString("descricao"));
r.setHora(rs.getTime("hora"));
r.setIdPergunta(rs.getInt("idPergunta"));
r.setIdResposta(rs.getInt("idResposta"));
r.setIdUsuario(rs.getInt("idUsuario"));
resposta.add(r);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
this.con.close();
}
return resposta;
}
public ArrayList<Resposta> consultarTodasRespostas() throws SQLException {
ArrayList<Resposta> resposta = new ArrayList<Resposta>();
String sql = "select * from Resposta order by data, hora";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Resposta r = new Resposta();
r.setData(rs.getDate("data"));
r.setDescricao(rs.getString("descricao"));
r.setHora(rs.getTime("hora"));
r.setIdPergunta(rs.getInt("idPergunta"));
r.setIdResposta(rs.getInt("idResposta"));
r.setIdUsuario(rs.getInt("idUsuario"));
resposta.add(r);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
this.con.close();
}
return resposta;
}
public ArrayList<Resposta> consultarRespostaPorPergunta(int id)
throws SQLException {
ArrayList<Resposta> resposta = new ArrayList<Resposta>();
String sql = "SELECT u.nome, r.idResposta, r.descricao, r.idUsuario, r.idPergunta, r.data, r.hora , r.votos FROM usuario u, resposta r " +
"WHERE idPergunta=" + id + " and u.idUsuario = r.idUsuario order by data, hora ";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Resposta r = new Resposta();
r.setData(rs.getDate("data"));
r.setDescricao(rs.getString("descricao"));
r.setHora(rs.getTime("hora"));
r.setIdPergunta(rs.getInt("idPergunta"));
r.setIdResposta(rs.getInt("idResposta"));
r.setIdUsuario(rs.getInt("idUsuario"));
r.setNomeUsuario(rs.getString("nome"));
r.setVotos(rs.getInt("votos"));
resposta.add(r);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
this.con.close();
}
return resposta;
}
public void adcionarVotoResposta(int id) throws SQLException{
String sql = "update resposta set votos = votos + 1 where idResposta = ?";
PreparedStatement stmt = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
int index = 0;
stmt.setInt(++index, id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stmt.close();
this.con.close();
}
}
public void removerVotoResposta(int id) throws SQLException{
String sql = "update resposta set votos = votos - 1 where idResposta = ?";
PreparedStatement stmt = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
int index = 0;
stmt.setInt(++index, id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stmt.close();
this.con.close();
}
}
/**
* Método para consultar todos os usuários que contribuíram com alguma resposta
* @param id da pergunta
* @return
* @throws SQLException
*/
public ArrayList<Usuario> consultarContribuintesPergunta(int id)
throws SQLException {
ArrayList<Usuario> usuarios = new ArrayList<Usuario>();
String sql = "SELECT distinct u.email, u.nome, r.idUsuario, p.titulo FROM usuario u, resposta r, pergunta p " +
"WHERE p.idPergunta = r.idPergunta and p.idPergunta= "+ id +" and u.idUsuario = r.idUsuario ;";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Usuario u = new Usuario();
Pergunta p = new Pergunta();
u.setIdUsuario(rs.getInt("idUsuario"));
u.setNome(rs.getString("nome"));
u.setEmail(rs.getString("email"));
p.setTitulo(rs.getString("titulo"));
u.setPergunta(p);
usuarios.add(u);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
this.con.close();
}
return usuarios;
}
/**
* Método para consultar todos os usuários que contribuíram com alguma resposta
* @param id da pergunta
* @return
* @throws SQLException
*/
public Usuario consultarAutorPergunta(int id)
throws SQLException {
Usuario usuario = new Usuario();
Pergunta pergunta = new Pergunta();
String sql = "SELECT u.email, u.nome, u.idUsuario,p.titulo FROM usuario u, pergunta p " +
"WHERE p.idUsuario = u.idUsuario and p.idPergunta = " + id;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
if(rs.next()){
usuario.setIdUsuario(rs.getInt("idUsuario"));
usuario.setEmail(rs.getString("email"));
usuario.setNome(rs.getString("nome"));
pergunta.setTitulo(rs.getString("titulo"));
usuario.setPergunta(pergunta);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rs.close();
stmt.close();
this.con.close();
}
return usuario;
}
@Override
public String alterarResposta(Resposta resposta) throws SQLException {
String retorno = "alteracaoSucesso";
String sql = "update RESPOSTA set descricao=?, idUsuario=?, idPergunta=?, data=?, hora=? where idResposta = ?";
PreparedStatement stmt = null;
try {
this.con = ConnectionUtil.getConnection();
stmt = con.prepareStatement(sql);
int index = 0;
stmt.setString(++index, resposta.getDescricao());
stmt.setInt(++index, resposta.getIdUsuario());
stmt.setInt(++index, resposta.getIdPergunta());
stmt.setDate(++index, resposta.getData());
stmt.setTime(++index, resposta.getHora());
stmt.setInt(++index, resposta.getIdResposta());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
stmt.close();
this.con.close();
}
return retorno;
}
}
|
/*
* Conexion.java
*
* Programa de prueba para conexión a una base de datos de MySQL.
* Presupone que el servidor de base de datos está arrancado, disponible,
* en el puerto por defecto.
* El usuario y password de conexión con la base de datos debe cambiarse.
* En la base de datos se supone que hay una base de datos llamada prueba y que
* tiene una tabla persona con tres campos, de esta manera:
* mysql> create database prueba;
* mysql> use prueba;
* mysql> create table persona (id smallint auto_increment, nombre varchar(60),
* nacimiento date, primary key(id));
*/
package model;
import java.sql.*;
import java.util.ArrayList;
/**
* Clase de prueba de conexión con una base de datos MySQL
* @author Chudiang, modificado por Edison Arango
*/
public class Conexion {
private String url = "jdbc:mysql://localhost:3306/loginMVCJSP";
private String user = "root";
private String contraseña = "";
private Connection conexion;
/**
* Crea una instancia de la clase MySQL y realiza todo el código
* de conexión, consulta y muestra de resultados.
*/
public Conexion()
{
// Se mete todo en un try por los posibles errores de MySQL
try
{
// Se registra el Driver de MySQL
DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
}
catch (Exception e)
{
e.printStackTrace();
}
}
public boolean conectar(){
try
{
// Se obtiene una conexión con la base de datos. Hay que
// cambiar el usuario "root" y la clave "la_clave" por las
// adecuadas a la base de datos que estemos usando.
conexion = DriverManager.getConnection (url,user,contraseña);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
public int usuario (String usuario,String contraseña){
try
{
// Se crea un Statement, para realizar la consulta
Statement s = conexion.createStatement();
// Se realiza la consulta. Los resultados se guardan en el
// ResultSet rs
ResultSet rs = s.executeQuery ("select * from usuario where usuario='"+usuario+"' and clave='"+contraseña+"';");
rs.first();
return rs.getInt("tipousuario");
// Se recorre el ResultSet, mostrando por pantalla los resultados.
// while (rs.next())
// {
// System.out.println (rs.getInt ("Id") + " " + rs.getString (2)+
// " " + rs.getDate(3));
// }
}
catch (Exception e)
{
e.printStackTrace();
return -1;
}
}
public void desconectar (){
try
{
// Se cierra la conexión con la base de datos.
conexion.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public ArrayList<Usuario> obtenerUsuarios() {
try
{
// Se crea un Statement, para realizar la consulta
Statement s = conexion.createStatement();
// Se realiza la consulta. Los resultados se guardan en el
// ResultSet rs
ResultSet rs = s.executeQuery ("select * from usuario;");
//rs.first();
ArrayList<Usuario> usuarios = new ArrayList();
// Se recorre el ResultSet, mostrando por pantalla los resultados.
while (rs.next())
{
usuarios.add(new Usuario(rs.getString("usuario"),rs.getInt("tipousuario")));
}
return usuarios;
}
catch (Exception e)
{
e.printStackTrace();
return new ArrayList<Usuario>();
}
}
public boolean modificarUsuario(String usuario, String nuevousuario, String nuevaclave, String nuevotipo) {
try {
Statement s = conexion.createStatement();
s.execute("update usuario set usuario='"+nuevousuario+"',clave='"+nuevaclave+"',tipousuario='"+nuevotipo+"' where usuario='"+usuario+"'");
return true;
} catch (Exception e) {
return false;
}
}
public boolean eliminarUsuario (String usuario){
try {
Statement s = conexion.createStatement();
s.execute("delete from usuario where usuario='"+usuario+"'");
return true;
} catch (Exception e) {
return false;
}
}
} |
package com.tecsup.cps.lab02b_git;
public class Modelo {
}
|
package com.example.hemil.papa_johns;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.hemil.papa_johns.AbstractFactory.AbstractFactory;
import com.example.hemil.papa_johns.AbstractFactory.FactoryProducer;
import com.example.hemil.papa_johns.R;
import com.example.hemil.papa_johns.Utility.MenuGridAdapter;
/**
* Created by hemil on 11/17/2015.
*/
public class MenuScreen extends AppCompatActivity {
int[] imageResource = {
R.drawable.menu_1_pizzas, R.drawable.menu_2_sandwitches, R.drawable.menu_3_pastas,
R.drawable.menu_4_drinks, R.drawable.menu_5_desserts, R.drawable.menu_6_sides
};
String[] menuItemText = {
"Pizzas", "Sandwitches", "Pastas", "Drinks", "Desserts", "Sides"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_screen);
GridView gridView = (GridView) (findViewById(R.id.mainMenuGrid));
gridView.setAdapter(new MenuGridAdapter(this,menuItemText,imageResource));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
category(position);
}
});
}
public void category(int position){
switch (position){
case 0 : Toast.makeText(MenuScreen.this,""+ position, Toast.LENGTH_SHORT).show();
Intent intent_pizza = new Intent(this,ChooseItem.class);
intent_pizza.putExtra("position",position);
startActivity(intent_pizza);
break;
case 1 : Toast.makeText(MenuScreen.this,""+ position, Toast.LENGTH_SHORT).show();
Intent intent_sand = new Intent(this,ChooseItem.class);
intent_sand.putExtra("position",position);
startActivity(intent_sand);
break;
case 2 : Toast.makeText(MenuScreen.this,""+ position, Toast.LENGTH_SHORT).show();
Intent intent_pasta = new Intent(this,ChooseItem.class);
intent_pasta.putExtra("position",position);
startActivity(intent_pasta);
break;
case 3 : Toast.makeText(MenuScreen.this,""+ position, Toast.LENGTH_SHORT).show();
Intent intent_drink = new Intent(this,ChooseItem.class);
intent_drink.putExtra("position",position);
startActivity(intent_drink);
break;
case 4 : Toast.makeText(MenuScreen.this,""+ position, Toast.LENGTH_SHORT).show();
Intent intent_dessert = new Intent(this,ChooseItem.class);
intent_dessert.putExtra("position",position);
startActivity(intent_dessert);
break;
case 5 : Toast.makeText(MenuScreen.this,""+ position, Toast.LENGTH_SHORT).show();
Intent intent_side = new Intent(this,ChooseItem.class);
intent_side.putExtra("position",position);
startActivity(intent_side);
break;
}
}
}
|
package ggboy.study.java.springBeanReq.info;
import java.io.Serializable;
public class RespInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String code;
private String result;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
|
package bin;
import control.ControlAuthentification;
import control.ControlChangerConfiguration;
import control.ControlChangerMdp;
import control.ControlEffacerHistorique;
import control.ControlEnregistrerDansHistorique;
import control.ControlLancerIndexation;
import control.ControlLancerRecherche;
import control.ControlVerifierID;
import control.ControlVisualiserDescripteurs;
import control.ControlVisualiserHistorique;
import view.BoundaryAuthentification;
import view.BoundaryChangerConfiguration;
import view.BoundaryChangerMdp;
import view.BoundaryEffacerHistorique;
import view.BoundaryLancerIndexation;
import view.BoundaryLancerRecherche;
import view.BoundaryVisualiserDescripteurs;
import view.BoundaryVisualiserHistorique;
import view.Clavier;
/**
* DFSearch
*/
public class DFSearch {
public static void main(String[] args) {
/* Mise en place de l'environnement */
ControlVerifierID controlVerifierID = new ControlVerifierID();
ControlEnregistrerDansHistorique controlEnregistrerDansHistorique = new ControlEnregistrerDansHistorique();
ControlLancerRecherche controlLancerRecherche = new ControlLancerRecherche(controlEnregistrerDansHistorique);
BoundaryLancerRecherche boundaryLancerRecherche = new BoundaryLancerRecherche(controlLancerRecherche);
ControlVisualiserHistorique controlVisualiserHistorique = new ControlVisualiserHistorique();
BoundaryVisualiserHistorique boundaryVisualiserHistorique = new BoundaryVisualiserHistorique(controlVisualiserHistorique);
ControlLancerIndexation controlLancerIndexation = new ControlLancerIndexation(controlVerifierID);
BoundaryLancerIndexation boundaryLancerIndexation = new BoundaryLancerIndexation(controlLancerIndexation);
ControlVisualiserDescripteurs controlVisualiserDescripteurs = new ControlVisualiserDescripteurs(controlVerifierID);
BoundaryVisualiserDescripteurs boundaryVisualiserDescripteurs = new BoundaryVisualiserDescripteurs(controlVisualiserDescripteurs);
ControlChangerConfiguration controlChangerConfiguration = new ControlChangerConfiguration(controlVerifierID);
BoundaryChangerConfiguration boundaryChangerConfiguration = new BoundaryChangerConfiguration(controlChangerConfiguration);
ControlEffacerHistorique controlEffacerHistorique = new ControlEffacerHistorique(controlVerifierID);
BoundaryEffacerHistorique boundaryEffacerHistorique = new BoundaryEffacerHistorique(controlEffacerHistorique);
ControlChangerMdp controlChangerMdp = new ControlChangerMdp(controlVerifierID);
BoundaryChangerMdp boundaryChangerMdp = new BoundaryChangerMdp(controlChangerMdp);
ControlAuthentification controlAuthentification = new ControlAuthentification(controlVerifierID);
BoundaryAuthentification boundaryAuthentification = new BoundaryAuthentification(controlAuthentification);
/* Main */
System.out.println(" *** DFSEARCH *** ");
boolean continuer = true;
while (continuer) {
boolean admin = controlVerifierID.verifierID();
menu(admin);
int choix = Clavier.entrerClavierInt();
if ((admin && choix >= 1 && choix <= 8) || (!admin && choix >= 1 && choix <= 4)) {
if (admin) {
continuer = actionAdmin(boundaryLancerRecherche, boundaryVisualiserHistorique,
boundaryLancerIndexation, boundaryVisualiserDescripteurs, boundaryChangerConfiguration,
boundaryEffacerHistorique, boundaryChangerMdp, continuer, choix);
} else {
continuer = actionNonAdmin(boundaryLancerRecherche, boundaryVisualiserHistorique,
boundaryAuthentification, continuer, choix);
}
}
}
}
private static boolean actionNonAdmin(BoundaryLancerRecherche boundaryLancerRecherche,
BoundaryVisualiserHistorique boundaryVisualiserHistorique,
BoundaryAuthentification boundaryAuthentification, boolean continuer, int choix) {
switch (choix) {
case 1:
boundaryLancerRecherche.lancerRecherche();
break;
case 2:
boundaryVisualiserHistorique.VisualiserHistorique();
break;
case 3:
boundaryAuthentification.authentification();
break;
default:
continuer = false;
break;
}
return continuer;
}
private static boolean actionAdmin(BoundaryLancerRecherche boundaryLancerRecherche,
BoundaryVisualiserHistorique boundaryVisualiserHistorique,
BoundaryLancerIndexation boundaryLancerIndexation,
BoundaryVisualiserDescripteurs boundaryVisualiserDescripteurs,
BoundaryChangerConfiguration boundaryChangerConfiguration,
BoundaryEffacerHistorique boundaryEffacerHistorique, BoundaryChangerMdp boundaryChangerMdp,
boolean continuer, int choix) {
switch (choix) {
case 1:
boundaryLancerRecherche.lancerRecherche();
break;
case 2:
boundaryVisualiserHistorique.VisualiserHistorique();
break;
case 3:
boundaryLancerIndexation.lancerIndexation();
break;
case 4:
boundaryVisualiserDescripteurs.visualiserDescripteurs();
break;
case 5:
boundaryChangerConfiguration.changerConfiguration();
break;
case 6:
boundaryEffacerHistorique.effacerHistorique();
break;
case 7:
boundaryChangerMdp.changerMdp();
break;
default:
continuer = false;
break;
}
return continuer;
}
private static void menu(boolean admin) {
System.out.println("Que souhaitez-vous faire : \n");
System.out.println("1) Lancer une recherche");
System.out.println("2) Visualiser l'historique");
if (admin) {
System.out.println("3) Lancer l'indexation");
System.out.println("4) Visualiser les descripteurs");
System.out.println("5) Changer la configuration");
System.out.println("6) Effacer l'historique");
System.out.println("7) Changer le mot de passe");
System.out.println("8) Quitter\n");
} else {
System.out.println("3) Se connecter en mode admin");
System.out.println("4) Quitter\n");
}
}
} |
package TicketOrder;
// Generated Oct 30, 2016 10:49:21 PM by Hibernate Tools 4.3.1
/**
* Timetrain generated by hbm2java
*/
public class Timetrain implements java.io.Serializable {
private int timeId;
private int trainId;
private int price;
private String provice;
private String dateTrain;
private String timeTrain;
public Timetrain() {
}
public Timetrain(int timeId, int trainId, int price, String provice) {
this.timeId = timeId;
this.trainId = trainId;
this.price = price;
this.provice = provice;
}
public Timetrain(int timeId, int trainId, int price, String provice, String dateTrain, String timeTrain) {
this.timeId = timeId;
this.trainId = trainId;
this.price = price;
this.provice = provice;
this.dateTrain = dateTrain;
this.timeTrain = timeTrain;
}
public int getTimeId() {
return this.timeId;
}
public void setTimeId(int timeId) {
this.timeId = timeId;
}
public int getTrainId() {
return this.trainId;
}
public void setTrainId(int trainId) {
this.trainId = trainId;
}
public int getPrice() {
return this.price;
}
public void setPrice(int price) {
this.price = price;
}
public String getProvice() {
return this.provice;
}
public void setProvice(String provice) {
this.provice = provice;
}
public String getDateTrain() {
return this.dateTrain;
}
public void setDateTrain(String dateTrain) {
this.dateTrain = dateTrain;
}
public String getTimeTrain() {
return this.timeTrain;
}
public void setTimeTrain(String timeTrain) {
this.timeTrain = timeTrain;
}
}
|
package boletin77;
/**
*
* @author agomezcastro
*/
public class Cadrado {
private double lado;
public Cadrado(double lado){
this.lado=lado;
}
public double calcularArea(){
double area;
area= lado*lado;
return area;
}
}
|
package saga.controllers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import saga.entities.*;
import saga.repositories.ClienteRepositorio;
import saga.repositories.FornecedorRepositorio;
import static org.junit.jupiter.api.Assertions.*;
class ContaControllerTest {
private ContaController controller;
private Conta conta;
@BeforeEach
void init() {
ClienteRepositorio clienteRepositorio = new ClienteRepositorio();
Cliente cliente1 = new Cliente("00023827490", "Victor Emanuel", "vitao@ccc.ufcg.edu.br", "Labarc");
Cliente cliente2 = new Cliente("64269141198", "Ana Amari", "ana_amari@ccc.ufcg.edu.br", "SPG");
clienteRepositorio.adicionaCliente("00023827490", cliente1);
clienteRepositorio.adicionaCliente("64269141198", cliente2);
FornecedorRepositorio fornecedorRepositorio = new FornecedorRepositorio();
Fornecedor fornecedor1 = new Fornecedor("Helhao", "quiosque@gmail.com", "83 98736-5050");
Fornecedor fornecedor2 = new Fornecedor("Marcos", "marcos@gmail.com", "83 99945-1294");
fornecedorRepositorio.adicionaFornecedor("Helhao", fornecedor1);
fornecedorRepositorio.adicionaFornecedor("Marcos", fornecedor2);
Produto produto1 = new Produto("X-frango", "Hamburguer de frango com queijo e calabresa", 5.00);
fornecedor1.adicionaProduto(produto1);
Compra compra1 = new Compra("X-frango", "Hamburguer de frango com queijo e calabresa", 5.00, "25/08/2019", "Victor Emanuel", "Helhao");
cliente1.adicionaNaConta("Helhao", compra1);
this.conta= new Conta("Helhao");
this.conta.adicionaCompra(compra1);
this.controller = new ContaController(clienteRepositorio, fornecedorRepositorio);
}
@Test
void testGetDebitoCpfNull() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito(null, "Helhao");
});
}
@Test
void testGetDebitoCpfVazio() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("", "Helhao");
});
}
@Test
void testGetDebitoCpfInvalidoTamanho() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("0002382749011", "Helhao");
});
}
@Test
void testGetDebitoCpfInvalidoLetra() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("00a23827490", "Helhao");
});
}
@Test
void testGetDebitoFornecedorNull() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("00023827490", null);
});
}
@Test
void testGetDebitoFornecedorVazio() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("00023827490", "");
});
}
@Test
void testGetDebitoFornecedorInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("00023827490", "Joao");
});
}
@Test
void testGetDebitoClienteInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("00000000000", "Helhao");
});
}
@Test
void testGetDebitoInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.getDebito("00023827490", "Marcos");
});
}
@Test
void testGetDebitoExistente() {
assertEquals("5.00", this.controller.getDebito("00023827490" , "Helhao"));
}
@Test
void testExibeContasCpfNull() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas(null, "Helhao");
});
}
@Test
void testExibeContasCpfVazio() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("", "Helhao");
});
}
@Test
void testExibeContasCpfInvalidoTamanho() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("0002382749011", "Helhao");
});
}
@Test
void testExibeContasCpfInvalidoLetra() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("00a23827490", "Helhao");
});
}
@Test
void testExibeContasFornecedorNull() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("00023827490", null);
});
}
@Test
void testExibeContasFornecedorVazio() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("00023827490", "");
});
}
@Test
void testExibeContasClienteInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("00000000000", "Helhao");
});
}
@Test
void testExibeContasFornecedorInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("00023827490", "Joao");
});
}
@Test
void testExibeContasInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContas("00023827490", "Marcos");
});
}
@Test
void testExibeContasExistente() {
String representacao = "Cliente: Victor Emanuel | " + this.conta.toString();
assertEquals(representacao, this.controller.exibeContas("00023827490", "Helhao"));
}
@Test
void testExibeContasClientesCpfNull() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContasClientes(null);
});
}
@Test
void testExibeContasClientesCpfVazio() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContasClientes("");
});
}
@Test
void testExibeContasClientesCpfInvalidoTamanho() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContasClientes("0002382749011");
});
}
@Test
void testExibeContasClientesCpfInvalidoLetra() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContasClientes("00a23827490");
});
}
@Test
void testExibeContasClientesClienteInexistente() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContasClientes("00000000000");
});
}
@Test
void testExibeContasClientesClienteSemContas() {
assertThrows(IllegalArgumentException.class, () -> {
this.controller.exibeContasClientes("64269141198");
});
}
@Test
void testExibeContasClientesClienteExistente() {
String listagemEsperada = "Cliente: Victor Emanuel | " + this.conta.toString();
assertEquals(listagemEsperada, this.controller.exibeContasClientes("00023827490"));
}
} |
package com.example.zhenqiangli.customview.customized;
import android.view.MotionEvent;
import java.util.LinkedList;
import static android.view.MotionEvent.ACTION_CANCEL;
import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
/*
* TouchEvent to action
* */
public class MotionTracker {
static final int MOTION_TRACKER_ACTION_UNTRACK = 0;
static final int MOTION_TRACKER_ACTION_CLICK = 0x11; // click -> show definition
static final int MOTION_TRACKER_ACTION_DOUBLE_CLICK = 0x12; // double click ->
static final int MOTION_TRACKER_ACTION_DRAG = 0x20; // drag -> read more content?
static final int MOTION_TRACKER_ACTION_PRESS = 0x21; // press -> select word
static final int MOTION_TRACKER_ACTION_PRESS_AND_DRAG = 0x22; // press and drag -> select more content
static final int MOTION_TRACKER_ACTION_INIT = 0xff;
public static final long CLICK_GAP_TIME_THRESHOLD = 200;
public static final long CLICK_TIME_THRESHOLD = 200;
public static final float CLICK_MOVE_THRESHOLD = 10.0f;
private float distance(float x1, float y1, float x2, float y2) {
return (float) sqrt(pow(x1 - x2, 2.0) + pow(y1 - y2, 2.0));
}
public static class EventInfo {
private float x;
private float y;
private long eventTime;
private int action;
EventInfo(MotionEvent e) {
x = e.getX();
y = e.getY();
eventTime = e.getEventTime();
action = e.getAction();
}
public EventInfo(float x, float y, long eventTime, int action) {
this.x = x;
this.y = y;
this.eventTime = eventTime;
this.action = action;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public long getEventTime() {
return eventTime;
}
public int getAction() {
return action;
}
}
private EventInfo lastEventInfo;
private int lastAction = MOTION_TRACKER_ACTION_INIT;
int actionFrom(EventInfo event) {
int step = 0, res = MOTION_TRACKER_ACTION_INIT;
switch (event.getAction()) {
case ACTION_DOWN:
lastEventInfo = event;
step = 1;
res = MOTION_TRACKER_ACTION_UNTRACK;
break;
case ACTION_CANCEL:
lastEventInfo = null;
step = 2;
res = MOTION_TRACKER_ACTION_INIT;
break;
case ACTION_MOVE: // press OR drag
if (event.getEventTime() - lastEventInfo.getEventTime() < CLICK_TIME_THRESHOLD
&& distance(lastEventInfo.getX(), lastEventInfo.getY(), event.getX(), event.getY()) < CLICK_MOVE_THRESHOLD) {
step =3;
res = MOTION_TRACKER_ACTION_UNTRACK;
} else if (distance(lastEventInfo.getX(), lastEventInfo.getY(), event.getX(), event.getY()) >= CLICK_MOVE_THRESHOLD) {
lastEventInfo = event;
if (lastAction == MOTION_TRACKER_ACTION_INIT) {
step = 4;
res = MOTION_TRACKER_ACTION_DRAG;
} else if (lastAction == MOTION_TRACKER_ACTION_PRESS) {
step = 5;
res = MOTION_TRACKER_ACTION_PRESS_AND_DRAG;
} else {
step = 6;
res = MOTION_TRACKER_ACTION_UNTRACK;
}
} else {
lastEventInfo = event;
if (lastAction == MOTION_TRACKER_ACTION_PRESS) {
step = 7;
res = MOTION_TRACKER_ACTION_UNTRACK;
} else {
step = 8;
res = MOTION_TRACKER_ACTION_PRESS;
}
}
break;
case ACTION_UP: // click * x
if (event.getEventTime() - lastEventInfo.getEventTime() >= CLICK_TIME_THRESHOLD
|| distance(lastEventInfo.getX(), lastEventInfo.getY(), event.getX(), event.getY()) >= CLICK_MOVE_THRESHOLD) {
step = 9;
res = MOTION_TRACKER_ACTION_UNTRACK;
break;
}
if (lastAction == MOTION_TRACKER_ACTION_INIT) {
step = 10;
res = MOTION_TRACKER_ACTION_CLICK;
} else if (lastAction == MOTION_TRACKER_ACTION_CLICK){
step = 11;
res = MOTION_TRACKER_ACTION_DOUBLE_CLICK;
return MOTION_TRACKER_ACTION_DOUBLE_CLICK;
} else {
step = 12;
res = MOTION_TRACKER_ACTION_UNTRACK;
}
break;
default:
step = 13;
res = MOTION_TRACKER_ACTION_UNTRACK;
}
return res;
}
} |
package cn.test.annotation;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.Element;
import java.util.Set;
import cn.test.annotation.NameChecker;
/**
* Created by xiaoni on 2018/11/6.
*/
//*表示支持所有的Annotations
@SupportedAnnotationTypes("*")
//表示只支持jdk某版本的代码
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class NameCheckProcessor extends AbstractProcessor {
private NameChecker nameChecker;
/**
* 初始化名称检查插件
*
* @param processingEnvironment
*/
@Override
public void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
nameChecker = new NameChecker(processingEnvironment);
}
/**
* 对输入的语法树的各个节点进行名称检查
* 这是AbstractProcessor唯一一个必需覆盖的abstract方法
*
* @param annotations 此注解处理器所要处理的注解集合
* @param roundEnv 访问到当前这个Round中的语法树节点,每个节点表示一个Element。
* 在javax.lang.model包中定义了16类Element。详见ElementKind。
* @return
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
for (Element element : roundEnv.getRootElements()) {
nameChecker.checkNames(element);
}
}
return false;
}
public static void main(String[] args) {
/**
* 注解属于早期(编译期)优化,在运行期间发生作用(与java代码一样)。
*
* 插入式注解处理器的初始化是在initProcessAnnotations()方法中,
* 它的执行过程是在processAnnotations()方法中,该方法判断是否还有新的注解处理器需要执行,
* 如果有的话,通过com.sun.tools.javac.processing.JavacProcessingEnvironment类的doProcessing()方法生成
* 一个新的JavaCompiler对象对编译的后续步骤进行处理。
*/
/**
* G:\WorkSpaceSSD\DesignModeTestPrj\target\classes>javac -processor cn.test.annotation.NameCheckProcessor ../../src/main/java/cn/test/annotation/BADLY_NAMED_CODE.java
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:6: 警告: 名称“BADLY_NAMED_CODE”应当符合驼式命名法(Camel Case Names)
public class BADLY_NAMED_CODE {
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:8: 警告: 名称“colors”应当以大写字母开头
enum colors {
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:9: 警告: 常量“red”应当全部以大写字母或下划线命名,并且以字母开头
red, blue, green;
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:9: 警告: 常量“blue”应当全部以大写字母或下划线命名,并且以字母开头
red, blue, green;
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:9: 警告: 常量“green”应当全部以大写字母或下划线命名,并且以字母开头
red, blue, green;
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:12: 警告: 常量“_FORTY_TWO”应当全部以大写字母或下划线命名,并且以字母开头
static final int _FORTY_TWO = 42;
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:14: 警告: 名称“NOT_A_CONSTANT”应当以小写字母开头
public static int NOT_A_CONSTANT = _FORTY_TWO;
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:16: 警告: 一个普通方法 “BADLY_NAMED_CODE”不应当与类名重复,避免与构造函数产生混淆
protected void BADLY_NAMED_CODE() {
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:16: 警告: 名称“BADLY_NAMED_CODE”应当以小写字母开头
protected void BADLY_NAMED_CODE() {
^
..\..\src\main\java\cn\test\annotation\BADLY_NAMED_CODE.java:20: 警告: 名称“NOTcamelCASEmethodNAME”应当以小写字母开头
public void NOTcamelCASEmethodNAME() {
^
10 个警告
*/
}
}
|
package network.nerve.swap.cache.impl;
import io.nuls.base.basic.AddressTool;
import io.nuls.core.core.annotation.Autowired;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.model.StringUtils;
import network.nerve.swap.cache.SwapPairCache;
import network.nerve.swap.manager.ChainManager;
import network.nerve.swap.model.NerveToken;
import network.nerve.swap.model.dto.SwapPairDTO;
import network.nerve.swap.model.dto.stable.StableSwapPairDTO;
import network.nerve.swap.model.po.SwapPairPO;
import network.nerve.swap.model.po.SwapPairReservesPO;
import network.nerve.swap.storage.SwapPairReservesStorageService;
import network.nerve.swap.storage.SwapPairStorageService;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author Niels
*/
@Component
public class SwapPairCacheImpl implements SwapPairCache {
@Autowired
private SwapPairStorageService swapPairStorageService;
@Autowired
private SwapPairReservesStorageService swapPairReservesStorageService;
@Autowired
private ChainManager chainManager;
//不同的链地址不会相同,所以不再区分链
private Map<String, SwapPairDTO> CACHE_MAP = new HashMap<>();
private Map<String, String> LP_CACHE_MAP = new HashMap<>();
@Override
public SwapPairDTO get(String address) {
SwapPairDTO dto = CACHE_MAP.get(address);
if (dto == null) {
SwapPairPO pairPO = swapPairStorageService.getPair(address);
if (pairPO == null) {
return null;
}
dto = new SwapPairDTO();
dto.setPo(pairPO);
SwapPairReservesPO reservesPO = swapPairReservesStorageService.getPairReserves(address);
if (reservesPO == null) {
reservesPO = new SwapPairReservesPO(AddressTool.getAddress(address));
}
dto.setReserve0(reservesPO.getReserve0());
dto.setReserve1(reservesPO.getReserve1());
dto.setTotalLP(reservesPO.getTotalLP());
dto.setBlockTimeLast(reservesPO.getBlockTimeLast());
dto.setBlockHeightLast(reservesPO.getBlockHeightLast());
CACHE_MAP.put(address, dto);
}
return dto;
}
@Override
public SwapPairDTO put(String address, SwapPairDTO dto) {
return CACHE_MAP.put(address, dto);
}
@Override
public SwapPairDTO reload(String address) {
CACHE_MAP.remove(address);
SwapPairDTO dto = this.get(address);
return dto;
}
@Override
public SwapPairDTO remove(String address) {
SwapPairDTO remove = CACHE_MAP.remove(address);
if (remove != null) {
LP_CACHE_MAP.remove(remove.getPo().getTokenLP().str());
}
return remove;
}
@Override
public Collection<SwapPairDTO> getList() {
return CACHE_MAP.values();
}
@Override
public boolean isExist(String pairAddress) {
return this.get(pairAddress) != null;
}
@Override
public String getPairAddressByTokenLP(int chainId, NerveToken tokenLP) {
String tokenLPStr = tokenLP.str();
String pairAddress = LP_CACHE_MAP.get(tokenLPStr);
if (StringUtils.isBlank(pairAddress)) {
pairAddress = swapPairStorageService.getPairAddressByTokenLP(chainId, tokenLP);
if (StringUtils.isBlank(pairAddress)) {
return null;
}
LP_CACHE_MAP.put(tokenLPStr, pairAddress);
}
return pairAddress;
}
}
|
package videoshop.model;
import java.math.RoundingMode;
import javax.persistence.Entity;
import videoshop.controller.BossController;
import org.joda.money.Money;
import org.salespointframework.order.Order;
import org.salespointframework.payment.PaymentMethod;
import org.salespointframework.useraccount.UserAccount;
@Entity
public class SaleOrder extends Order {
public boolean isSale = false;
public SaleOrder() {
}
public SaleOrder(UserAccount userAccount, PaymentMethod paymentMethod)
{
super(userAccount, paymentMethod);
}
public Money getTotalPrice() {
Money money = super.getTotalPrice();
if (isSale)
money.multipliedBy(BossController.sale, RoundingMode.UNNECESSARY);
return money;
}
}
|
package com.cs.game;
import com.cs.bonus.PlayerBonus;
import com.cs.payment.Currency;
import com.cs.payment.Money;
import com.cs.player.Player;
import org.springframework.data.domain.Page;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @author Joakim Gottzén
*/
public interface GameTransactionService {
@Nonnull
Long addTransaction(final Player player, final Money moneyDeposit, final Money moneyWithdraw, final Money bonusDeposit, final Money bonusWithdraw,
final Money moneyBalance, final Money bonusBalance, final Currency currency, final String transactionRef, final String reason,
final Boolean reachedBonusConversionGoal, @Nullable final PlayerBonus activePlayerBonus);
@Nonnull
Long addTransaction(final Player player, final Money moneyDeposit, final Money moneyWithdraw, final Money bonusDeposit, final Money bonusWithdraw,
final Money moneyBalance, final Money bonusBalance, final Currency currency, final String gameRoundRef, final String transactionRef,
final String gameId, final String sessionId, final String reason, final Boolean reachedBonusConversionGoal,
@Nullable final PlayerBonus activePlayerBonus);
@Nonnull
Long addTransaction(final Player player, final Money moneyDeposit, final Money moneyWithdraw, final Money bonusDeposit, final Money bonusWithdraw,
final Money moneyBalance, final Money bonusBalance, final Currency currency, final String gameRoundRef, final String transactionRef,
final String gameId, final String sessionId, final String reason, final String source, final Boolean reachedBonusConversionGoal,
@Nullable final PlayerBonus activePlayerBonus);
@Nullable
GameTransaction getTransaction(final String transactionRef);
void updateTransaction(final GameTransaction gameTransaction);
@Nonnull
List<GameTransaction> getTransactionsByPlayerAndGameRound(final Player player, final String gameRef);
Page<GameTransaction> getGameTransactions(Player player, Date startDate, Date endDate, final Integer page, final Integer size);
Iterable<GameTransaction> getGameTransactions(final Player player, final Date startDate, final Date endDate);
Map<BigInteger, Money> getPlayersBetAmounts(final Date startDateTrimmed, final Date endDateTrimmed);
List<LeaderboardEntry> getLeaderPlayersOfTheWeek(@Nonnull Date desiredDate);
Map<BigInteger, GameTransactionSummary> getAffiliatePlayersGameTransactionSummary(final Date startDate, final Date endDate);
}
|
package com.example.cantri.doctoronline;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by cantri on 27/04/2017.
*/
public class ClinicDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clinic_detail);
final Intent intent = getIntent();
Clinic clinic = intent.getParcelableExtra("detail");
if (clinic == null)
return;
TextView name = (TextView) findViewById(R.id.clinic_name_detail);
name.setText(clinic.getName());
Button listDoctor = (Button) findViewById(R.id.list_doctor);
listDoctor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent1 = new Intent(getApplicationContext(), ListDoctorActivity.class);
startActivity(intent1);
}
});
}
}
|
package commands.server.ingame;
import java.util.LinkedList;
import java.util.Queue;
import cards.Card;
import cards.specials.instant.Brotherhood;
import core.player.PlayerCompleteServer;
import core.server.game.GameInternal;
import core.server.game.controllers.GameController;
import core.server.game.controllers.specials.instants.BrotherhoodGameController;
import exceptions.server.game.IllegalPlayerActionException;
public class InitiateBrotherhoodInGameServerCommand extends AbstractAOEInstantInitiationInGameServerCommand {
private static final long serialVersionUID = 1L;
public InitiateBrotherhoodInGameServerCommand(Card card) {
super(card);
}
@Override
protected GameController getAOEInitiationGameController(PlayerCompleteServer self, Queue<PlayerCompleteServer> others) {
Queue<PlayerCompleteServer> queue = new LinkedList<>();
queue.add(self);
queue.addAll(others);
return new BrotherhoodGameController(self, queue);
}
@Override
protected void validateCardType(GameInternal game) throws IllegalPlayerActionException {
if (!(card instanceof Brotherhood)) {
throw new IllegalPlayerActionException("Brotherhood: Card is not a Brotherhood");
}
}
}
|
package com.project.daicuongbachkhoa.model;
public class Chapter {
private String chapterCode,chapterName,chapterContent;
public Chapter() {
}
public Chapter(String chapterCode, String chapterName, String chapterContent) {
this.chapterCode = chapterCode;
this.chapterName = chapterName;
this.chapterContent = chapterContent;
}
public String getChapterCode() {
return chapterCode;
}
public void setChapterCode(String chapterCode) {
this.chapterCode = chapterCode;
}
public String getChapterName() {
return chapterName;
}
public void setChapterName(String chapterName) {
this.chapterName = chapterName;
}
public String getChapterContent() {
return chapterContent;
}
public void setChapterContent(String chapterContent) {
this.chapterContent = chapterContent;
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.interceptor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.testfixture.beans.ITestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.core.testfixture.io.ResourceTestUtils.qualifiedResource;
/**
* Non-XML tests are in AbstractAopProxyTests
*
* @author Rod Johnson
* @author Chris Beams
*/
public class ExposeInvocationInterceptorTests {
@Test
public void testXmlConfig() {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
qualifiedResource(ExposeInvocationInterceptorTests.class, "context.xml"));
ITestBean tb = (ITestBean) bf.getBean("proxy");
String name = "tony";
tb.setName(name);
// Fires context checks
assertThat(tb.getName()).isEqualTo(name);
}
}
|
/*
Write a complete program that demonstrates these classes
by asking the user to enter the amounts
of deposits and
withdrawals
for a savings account and checking account.
The program should display statistics for the month,
including beginning balance,
total amount of deposits,
total amount of withdrawals,
service charges,
and ending balance.
Feel free to add more member variables and functions to the classes than those listed above.
*/
package icw.bankingdriver;
/**
*
* @author bernice.templeman001
*/
public class ICWBankingDriver {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
double balance = 10000.00;
double annualInterestRate =0.71;
Checking mychecking = new Checking(balance, annualInterestRate);
Savings mysavings = new Savings(balance, annualInterestRate);
//amount to withdraw
//amount to deposit
// display monthly statisics
// beginning balanc
// total amount of deposits
// total amount of withdrawals
// service charges
// ending balance
System.out.println(" " +mychecking.getBalance());
System.out.println(" " +mysavings.getBalance());
mysavings.deposit(10000);
System.out.println(" " +mysavings.getBalance());
}
}
|
package def;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class SobelOperator {
public static void main(String[] args) {
// load library
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String fpath = new String("C:\\Users\\Shirley\\eclipse-workspace\\HelloUI\\src\\drawable\\blackpink.jpg");
// matrix object
Mat src = Imgcodecs.imread(fpath), dst = new Mat();
// get start time
long startTime = System.currentTimeMillis();
// create the Sobel Image
Imgproc.Sobel(src, dst, -1, 1, 1);
// calculate time elapsed for operation
System.out.println(String.format("Time elapsed: %s miliseconds.", System.currentTimeMillis() - startTime));
String out_path = new String("C:\\\\Users\\\\Shirley\\\\eclipse-workspace\\\\HelloUI\\\\src\\\\drawable\\\\blackpink_sobel.jpg");
Imgcodecs.imwrite(out_path, dst);
// create MatOfByte object
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", dst, matOfByte);
byte[] byteArray = matOfByte.toArray();
InputStream in = new ByteArrayInputStream(byteArray);
try {
BufferedImage img = ImageIO.read(in);
JFrame frame = new JFrame();
frame.getContentPane().add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setTitle("Sobel Edge Detection by Jake SJK...");
frame.setVisible(true);
} catch (Exception e) {
// TODO: handle exception
}
}
}
|
package com.lti.Algorithms.Codility.PrefixSum;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class GenomicRangeQuery {
public static void main(String[] args) {
int[] p={2,5,0};
int[] q={4,5,6};
String s="CAGCCTA";
System.out.println(Arrays.toString(new GenomicRangeQuery().solution(s, p, q)));
}
public int[] solution(String s, int[] p, int [] q){
int queries=p.length;
int[] ans=new int[queries];
int strLen=s.length();
int[][] freq=new int[strLen+1][4];
Map<Character,Integer> map=new HashMap<Character, Integer>();
map.put('A',0);
map.put('C',1);
map.put('G',2);
map.put('T',3);
for(int i=0;i<strLen;i++){
int index=i+1;
for(int j=0;j<4;j++){
freq[index][j]=freq[index-1][j];
}
char c = s.charAt(i);
int mapIndex=map.get(c);
freq[index][mapIndex]+=1;
}
for(int i=0;i<queries;i++){
int a=p[i];
int b=q[i]+1;
for(int j=0;j<4;j++){
if(freq[b][j]>freq[a][j]) {
ans[i] = j + 1;
break;
}
}
}
return ans;
}
}
|
package com.zks.server;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public class WeatherInterfaceImpl implements IWeatherInterface {
@WebMethod
@Override
public String queryWeather(String cityName) {
System.out.println(cityName);
return cityName;
}
}
|
/*
* Copyright (C) 2011 Marvell International Ltd., All Rights Reserved
*
* MARVELL CONFIDENTIAL
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Marvell International Ltd or its
* suppliers or licensors. Title to the Material remains with Marvell International Ltd
* or its suppliers and licensors. The Material contains trade secrets and
* proprietary and confidential information of Marvell or its suppliers and
* licensors. The Material is protected by worldwide copyright and trade secret
* laws and treaty provisions. No part of the Material may be used, copied,
* reproduced, modified, published, uploaded, posted, transmitted, distributed,
* or disclosed in any way without Marvell's prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Marvell in writing.
*
*/
package com.marvell.wifidirect.apitest.tests;
import android.net.wifi.MrvlWuControllerWifiDirect;
import junit.framework.TestCase;
/**
* Test cases to exercise the android.net.wifi.MrvlWuControllerWifiDirectTest
* class
*
* @since Marvell-0.01
*/
public class MrvlWuControllerWifiDirectTest extends TestCase {
// Declare variables ()
// MrvlWuControllerWifiDirect controller;
static final String TAG = "MrvlWuControllerWifiDirectTest";
public void setUp() throws Exception {
super.setUp();
// Create the object to be tested (if necessary )
// MrvlWuControllerWifiDirect controller = new
// MrvlWuControllerWifiDirect();
}
public void testRandomWifiDirectPin() {
String pin = MrvlWuControllerWifiDirect.getRandomWifiDirectPin();
// implement the test
// assertEquals(expected, actual);
// etc.
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
package org.xbill.DNS.lookup;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.xbill.DNS.DClass.IN;
import static org.xbill.DNS.LookupTest.DUMMY_NAME;
import static org.xbill.DNS.LookupTest.LONG_LABEL;
import static org.xbill.DNS.LookupTest.answer;
import static org.xbill.DNS.LookupTest.fail;
import static org.xbill.DNS.Type.A;
import static org.xbill.DNS.Type.AAAA;
import static org.xbill.DNS.Type.CNAME;
import static org.xbill.DNS.Type.MX;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.xbill.DNS.*;
import org.xbill.DNS.Record;
import org.xbill.DNS.hosts.HostsFileParser;
@ExtendWith(MockitoExtension.class)
class LookupSessionTest {
@Mock Resolver mockResolver;
@TempDir Path tempDir;
private static final ARecord LOOPBACK_A =
new ARecord(DUMMY_NAME, IN, 3600, InetAddress.getLoopbackAddress());
private static final AAAARecord LOOPBACK_AAAA;
private HostsFileParser lookupSessionTestHostsFileParser;
static {
AAAARecord record = null;
try {
record =
new AAAARecord(
DUMMY_NAME,
IN,
3600,
InetAddress.getByAddress(Address.toByteArray("::1", Address.IPv6)));
} catch (UnknownHostException e) {
// cannot happen
}
LOOPBACK_AAAA = record;
}
@BeforeEach
void beforeEach() throws URISyntaxException {
lookupSessionTestHostsFileParser =
new HostsFileParser(
Paths.get(LookupSessionTest.class.getResource("/hosts_example").toURI()));
}
@AfterEach
void afterEach() {
verifyNoMoreInteractions(mockResolver);
}
@Test
void lookupAsync_absoluteQuery() throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_absoluteQuery_defaultClass() throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_absoluteQueryWithHosts() throws InterruptedException, ExecutionException {
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.hostsFileParser(lookupSessionTestHostsFileParser)
.build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(
singletonList(LOOPBACK_A.withName(name("kubernetes.docker.internal."))),
result.getRecords());
}
@Test
void lookupAsync_absoluteQueryWithFailedHosts() throws IOException {
wireUpMockResolver(mockResolver, q -> fail(q, Rcode.NXDOMAIN));
HostsFileParser mockHosts = mock(HostsFileParser.class);
when(mockHosts.getAddressForHost(any(), anyInt())).thenThrow(IOException.class);
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).hostsFileParser(mockHosts).build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal."), A, IN);
assertThrowsCause(NoSuchDomainException.class, () -> resultFuture.toCompletableFuture().get());
}
@Test
void lookupAsync_absoluteQueryWithHostsInvalidType() {
wireUpMockResolver(mockResolver, query -> fail(query, Rcode.NXDOMAIN));
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.hostsFileParser(lookupSessionTestHostsFileParser)
.build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal."), MX, IN);
assertThrowsCause(NoSuchDomainException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_absoluteAaaaQueryWithHosts() throws InterruptedException, ExecutionException {
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.hostsFileParser(lookupSessionTestHostsFileParser)
.build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal."), AAAA, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(
singletonList(LOOPBACK_AAAA.withName(name("kubernetes.docker.internal."))),
result.getRecords());
}
@Test
void lookupAsync_relativeQueryWithHosts() throws InterruptedException, ExecutionException {
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.hostsFileParser(lookupSessionTestHostsFileParser)
.build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal"), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(
singletonList(LOOPBACK_A.withName(name("kubernetes.docker.internal."))),
result.getRecords());
}
@Test
void lookupAsync_relativeQueryWithHostsNdots3() throws InterruptedException, ExecutionException {
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.ndots(3)
.hostsFileParser(lookupSessionTestHostsFileParser)
.build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal"), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(
singletonList(LOOPBACK_A.withName(name("kubernetes.docker.internal."))),
result.getRecords());
}
@Test
void lookupAsync_relativeQueryWithInvalidHosts() throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.hostsFileParser(
new HostsFileParser(tempDir.resolve("lookupAsync_relativeQueryWithInvalidHosts")))
.build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("kubernetes.docker.internal"), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(
singletonList(LOOPBACK_A.withName(name("kubernetes.docker.internal."))),
result.getRecords());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_absoluteQueryWithCacheMiss() throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
Cache mockCache = mock(Cache.class);
when(mockCache.getDClass()).thenReturn(IN);
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).cache(mockCache).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
verify(mockResolver).sendAsync(any(), any(Executor.class));
verify(mockCache).lookupRecords(name("a.b."), A, Credibility.NORMAL);
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockCache).addMessage(messageCaptor.capture());
Record question = messageCaptor.getValue().getQuestion();
assertEquals(IN, question.getDClass());
assertEquals(A, question.getType());
assertEquals(name("a.b."), question.getName());
verifyNoMoreInteractions(mockCache);
}
@Test
void lookupAsync_absoluteQueryWithoutCache() throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).clearCaches().build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_absoluteQueryWithMultipleCaches()
throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
Cache mockCache1 = mock(Cache.class);
when(mockCache1.getDClass()).thenReturn(IN);
Cache mockCache2 = mock(Cache.class);
when(mockCache2.getDClass()).thenReturn(IN);
List<Cache> caches = new ArrayList<>(2);
caches.add(mockCache1);
caches.add(mockCache2);
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).caches(caches).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
verify(mockResolver).sendAsync(any(), any(Executor.class));
verify(mockCache2).lookupRecords(name("a.b."), A, Credibility.NORMAL);
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockCache2).addMessage(messageCaptor.capture());
Record question = messageCaptor.getValue().getQuestion();
assertEquals(IN, question.getDClass());
assertEquals(A, question.getType());
assertEquals(name("a.b."), question.getName());
verifyNoMoreInteractions(mockCache1);
verifyNoMoreInteractions(mockCache2);
}
@Test
void lookupAsync_absoluteQueryWithCacheHit() throws InterruptedException, ExecutionException {
Name aName = name("a.b.");
Cache mockCache = mock(Cache.class);
SetResponse response = mock(SetResponse.class);
when(response.isSuccessful()).thenReturn(true);
when(response.answers()).thenReturn(singletonList(new RRset(LOOPBACK_A.withName(aName))));
when(mockCache.getDClass()).thenReturn(IN);
when(mockCache.lookupRecords(aName, A, Credibility.NORMAL)).thenReturn(response);
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).cache(mockCache).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(aName, A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(aName)), result.getRecords());
verify(mockCache).lookupRecords(aName, A, Credibility.NORMAL);
verifyNoMoreInteractions(mockCache);
}
@Test
void lookupAsync_searchPathWithCacheMissAndHit() throws InterruptedException, ExecutionException {
wireUpMockResolver(mockResolver, q -> answer(q, n -> cname("host.tld.", "another.tld.")));
Cache mockCache = mock(Cache.class);
when(mockCache.getDClass()).thenReturn(IN);
// interestingly, a non-configured mock behaves the same way as a cache miss return value.
when(mockCache.lookupRecords(name("host.tld."), A, Credibility.NORMAL))
.thenReturn(mock(SetResponse.class));
SetResponse second = mock(SetResponse.class);
when(second.isSuccessful()).thenReturn(true);
when(second.answers())
.thenReturn(singletonList(new RRset(LOOPBACK_A.withName(name("another.tld.")))));
when(mockCache.lookupRecords(name("another.tld."), A, Credibility.NORMAL)).thenReturn(second);
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.cache(mockCache)
.searchPath(name("tld."))
.build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("host"), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("another.tld."))), result.getRecords());
verify(mockCache).lookupRecords(name("host.tld."), A, Credibility.NORMAL);
verify(mockCache).addMessage(any());
verify(mockCache).lookupRecords(name("another.tld."), A, Credibility.NORMAL);
verifyNoMoreInteractions(mockCache);
}
@Test
void lookupAsync_negativeCacheRecords() throws InterruptedException, ExecutionException {
Cache mockCache = mock(Cache.class);
when(mockCache.getDClass()).thenReturn(IN);
SetResponse first = mock(SetResponse.class);
when(first.isNXDOMAIN()).thenReturn(true);
when(mockCache.lookupRecords(name("host.tld1."), A, Credibility.NORMAL)).thenReturn(first);
SetResponse second = mock(SetResponse.class);
when(second.isNXRRSET()).thenReturn(true);
when(mockCache.lookupRecords(name("host.tld2."), A, Credibility.NORMAL)).thenReturn(second);
SetResponse third = mock(SetResponse.class);
when(third.isSuccessful()).thenReturn(true);
when(third.answers())
.thenReturn(singletonList(new RRset(LOOPBACK_A.withName(name("host.tld3.")))));
when(mockCache.lookupRecords(name("host.tld3."), A, Credibility.NORMAL)).thenReturn(third);
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.cache(mockCache)
.searchPath(asList(name("tld1"), name("tld2"), name("tld3")))
.build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("host"), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("host.tld3."))), result.getRecords());
InOrder inOrder = inOrder(mockCache);
inOrder.verify(mockCache).lookupRecords(name("host.tld1."), A, Credibility.NORMAL);
inOrder.verify(mockCache).lookupRecords(name("host.tld2."), A, Credibility.NORMAL);
inOrder.verify(mockCache).lookupRecords(name("host.tld3."), A, Credibility.NORMAL);
verifyNoMoreInteractions(mockCache);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void lookupAsync_twoCnameRedirectMultipleQueries(boolean useCache) throws Exception {
Function<Name, Record> nameToRecord =
name -> {
switch (name.toString()) {
case "cname.a.":
return cname("cname.a.", "cname.b.");
case "cname.b.":
return cname("cname.b.", "a.b.");
default:
return LOOPBACK_A.withName(name("a.b."));
}
};
wireUpMockResolver(mockResolver, q -> answer(q, nameToRecord));
LookupSession lookupSession =
useCache
? LookupSession.builder().cache(new Cache()).resolver(mockResolver).build()
: LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("cname.a."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
assertEquals(
Stream.of(name("cname.a."), name("cname.b.")).collect(Collectors.toList()),
result.getAliases());
verify(mockResolver, times(3)).sendAsync(any(), any(Executor.class));
}
@ParameterizedTest
@CsvSource({
"false,false",
"true,false",
"false,true",
"true,true",
})
void lookupAsync_twoDnameRedirectOneQuery(boolean useCache, boolean includeSyntheticCnames)
throws Exception {
wireUpMockResolver(
mockResolver,
query -> {
Message answer = new Message(query.getHeader().getID());
answer.addRecord(query.getQuestion(), Section.QUESTION);
answer.addRecord(dname("example.org.", "example.net."), Section.ANSWER);
if (includeSyntheticCnames) {
answer.addRecord(cname("www.example.org.", "www.example.net."), Section.ANSWER);
}
answer.addRecord(dname("example.net.", "example.com."), Section.ANSWER);
if (includeSyntheticCnames) {
answer.addRecord(cname("www.example.net.", "www.example.com."), Section.ANSWER);
}
answer.addRecord(cname("www.example.com.", "example.com."), Section.ANSWER);
answer.addRecord(LOOPBACK_A.withName(name("example.com.")), Section.ANSWER);
return answer;
});
LookupSession lookupSession =
useCache
? LookupSession.builder().cache(new Cache()).resolver(mockResolver).build()
: LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("www.example.org."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("example.com."))), result.getRecords());
assertEquals(
Stream.of(name("www.example.org."), name("www.example.net."), name("www.example.com."))
.collect(Collectors.toList()),
result.getAliases());
verify(mockResolver, times(1)).sendAsync(any(), any(Executor.class));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void lookupAsync_twoCnameRedirectOneQuery(boolean useCache) throws Exception {
wireUpMockResolver(
mockResolver,
query -> {
Message answer = new Message(query.getHeader().getID());
answer.addRecord(query.getQuestion(), Section.QUESTION);
answer.addRecord(cname("cname.a.", "cname.b."), Section.ANSWER);
answer.addRecord(cname("cname.b.", "a.b."), Section.ANSWER);
answer.addRecord(LOOPBACK_A.withName(name("a.b.")), Section.ANSWER);
return answer;
});
LookupSession lookupSession =
useCache
? LookupSession.builder().cache(new Cache()).resolver(mockResolver).build()
: LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("cname.a."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
assertEquals(
Stream.of(name("cname.a."), name("cname.b.")).collect(Collectors.toList()),
result.getAliases());
verify(mockResolver, times(1)).sendAsync(any(), any(Executor.class));
}
@ParameterizedTest
@CsvSource({
"true,1", "false,1", "true,2", "false,2",
})
void lookupAsync_twoCnameRedirectIncompleteResponse(boolean useCache, int firstResponseCnames)
throws Exception {
wireUpMockResolver(
mockResolver,
query -> {
Message answer = new Message(query.getHeader().getID());
answer.addRecord(query.getQuestion(), Section.QUESTION);
if (query.getQuestion().getName().equals(name("cname.a."))) {
answer.addRecord(cname("cname.a.", "cname.b."), Section.ANSWER);
if (firstResponseCnames == 1) {
answer.addRecord(cname("cname.b.", "a.b."), Section.ANSWER);
}
} else {
if (firstResponseCnames == 2) {
answer.addRecord(cname("cname.b.", "a.b."), Section.ANSWER);
}
answer.addRecord(LOOPBACK_A.withName(name("a.b.")), Section.ANSWER);
}
return answer;
});
LookupSession lookupSession =
useCache
? LookupSession.builder().cache(new Cache()).resolver(mockResolver).build()
: LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("cname.a."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
assertEquals(
Stream.of(name("cname.a."), name("cname.b.")).collect(Collectors.toList()),
result.getAliases());
verify(mockResolver, times(2)).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_simpleCnameRedirect_oneQuery() throws Exception {
wireUpMockResolver(
mockResolver,
query -> {
Message answer = new Message(query.getHeader().getID());
answer.addRecord(query.getQuestion(), Section.QUESTION);
answer.addRecord(cname("cname.r.", DUMMY_NAME.toString()), Section.ANSWER);
answer.addRecord(LOOPBACK_A, Section.ANSWER);
return answer;
});
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("cname.r."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A), result.getRecords());
assertEquals(singletonList(name("cname.r.")), result.getAliases());
verify(mockResolver, times(1)).sendAsync(any(), any(Executor.class));
}
@ParameterizedTest
@CsvSource({
"true,NXDOMAIN,A",
"false,NXDOMAIN,A",
"true,NOERROR,MX",
"false,NOERROR,MX",
})
void lookupAsync_simpleCnameRedirect(boolean useCache, String rcode, String type)
throws ExecutionException, InterruptedException {
wireUpMockResolver(
mockResolver,
q -> {
if (q.getQuestion().getName().equals(name("cname.r."))) {
return answer(q, n -> cname("cname.r.", "a.b."));
} else {
return fail(q, Rcode.value(rcode));
}
});
LookupSession lookupSession =
useCache
? LookupSession.builder().cache(new Cache()).resolver(mockResolver).build()
: LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("cname.r."), Type.value(type), IN);
CompletableFuture<LookupResult> future = resultFuture.toCompletableFuture();
if (rcode.equals("NXDOMAIN")) {
assertThrowsCause(NoSuchDomainException.class, future::get);
} else {
LookupResult result = future.get();
assertEquals(0, result.getRecords().size());
}
verify(mockResolver, times(2)).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_simpleCnameRedirect() throws Exception {
Function<Name, Record> nameToRecord =
name -> name("cname.r.").equals(name) ? cname("cname.r.", "a.b.") : LOOPBACK_A;
wireUpMockResolver(mockResolver, q -> answer(q, nameToRecord));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("cname.r."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("a.b."))), result.getRecords());
assertEquals(singletonList(name("cname.r.")), result.getAliases());
verify(mockResolver, times(2)).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_cnameQuery() throws Exception {
Name query = name("cname.r.");
CNAMERecord response = cname(query, "a.b.");
Function<Name, Record> nameToRecord = name -> query.equals(name) ? response : LOOPBACK_A;
wireUpMockResolver(mockResolver, q -> answer(q, nameToRecord));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(query, CNAME, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(response), result.getRecords());
assertEquals(emptyList(), result.getAliases());
verify(mockResolver, times(1)).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_simpleDnameRedirect() throws Exception {
Function<Name, Record> nameToRecord =
n -> name("x.y.to.dname.").equals(n) ? dname("to.dname.", "to.a.") : LOOPBACK_A;
wireUpMockResolver(mockResolver, q -> answer(q, nameToRecord));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("x.y.to.dname."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(singletonList(LOOPBACK_A.withName(name("x.y.to.a."))), result.getRecords());
verify(mockResolver, times(2)).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_redirectLoop() {
Function<Name, Record> nameToRecord =
name -> name("a.b.").equals(name) ? cname("a.", "b.") : cname("b.", "a.");
wireUpMockResolver(mockResolver, q -> answer(q, nameToRecord));
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).maxRedirects(2).build();
CompletionStage<LookupResult> resultFuture =
lookupSession.lookupAsync(name("first.example.com."), A, IN);
assertThrowsCause(
RedirectOverflowException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver, times(3)).sendAsync(any(), any(Executor.class));
}
@ParameterizedTest
@ValueSource(ints = {3, 4})
void lookupAsync_redirectLoopOneAnswer(int maxRedirects) {
wireUpMockResolver(
mockResolver,
query -> {
Message answer = new Message(query.getHeader().getID());
answer.addRecord(query.getQuestion(), Section.QUESTION);
answer.addRecord(cname("a.", "b."), Section.ANSWER);
answer.addRecord(cname("b.", "c."), Section.ANSWER);
answer.addRecord(cname("c.", "d."), Section.ANSWER);
answer.addRecord(cname("d.", "a."), Section.ANSWER);
return answer;
});
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).maxRedirects(maxRedirects).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a."), A, IN);
assertThrowsCause(
RedirectOverflowException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver, times(1)).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_NODATA() throws ExecutionException, InterruptedException {
wireUpMockResolver(mockResolver, q -> fail(q, Rcode.NOERROR));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(0, result.getRecords().size());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_NXDOMAIN() {
wireUpMockResolver(mockResolver, q -> fail(q, Rcode.NXDOMAIN));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
assertThrowsCause(NoSuchDomainException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_SERVFAIL() {
wireUpMockResolver(mockResolver, q -> fail(q, Rcode.SERVFAIL));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
assertThrowsCause(ServerFailedException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_unknownFailure() {
wireUpMockResolver(mockResolver, q -> fail(q, Rcode.NOTIMP));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
assertThrowsCause(LookupFailedException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_NXRRSET() {
wireUpMockResolver(mockResolver, q -> fail(q, Rcode.NXRRSET));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
assertThrowsCause(NoSuchRRSetException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_TooLongNameDNAME() {
wireUpMockResolver(
mockResolver, q -> answer(q, n -> dname("to.dname.", format("%s.to.a.", LONG_LABEL))));
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
Name toLookup = name(format("%s.%s.%s.to.dname.", LONG_LABEL, LONG_LABEL, LONG_LABEL));
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(toLookup, A, IN);
assertThrowsCause(
InvalidZoneDataException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
@Test
void lookupAsync_MultipleCNAMEs() {
// According to https://docstore.mik.ua/orelly/networking_2ndEd/dns/ch10_07.htm this is
// apparently something that BIND 4 did.
wireUpMockResolver(mockResolver, LookupSessionTest::multipleCNAMEs);
LookupSession lookupSession = LookupSession.builder().resolver(mockResolver).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("a.b."), A, IN);
assertThrowsCause(
InvalidZoneDataException.class, () -> resultFuture.toCompletableFuture().get());
verify(mockResolver).sendAsync(any(), any(Executor.class));
}
private static Message multipleCNAMEs(Message query) {
Message answer = new Message(query.getHeader().getID());
Record question = query.getQuestion();
answer.addRecord(question, Section.QUESTION);
answer.addRecord(
new CNAMERecord(question.getName(), CNAME, IN, name("target1.")), Section.ANSWER);
answer.addRecord(
new CNAMERecord(question.getName(), CNAME, IN, name("target2.")), Section.ANSWER);
return answer;
}
@Test
void lookupAsync_searchAppended() throws Exception {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.searchPath(singletonList(name("example.com")))
.build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("host"), A, IN);
LookupResult lookupResult = resultFuture.toCompletableFuture().get();
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockResolver).sendAsync(messageCaptor.capture(), any(Executor.class));
assertEquals(
Record.newRecord(name("host.example.com."), Type.A, DClass.IN, 0L),
messageCaptor.getValue().getSection(Section.QUESTION).get(0));
assertEquals(
singletonList(LOOPBACK_A.withName(name("host.example.com."))), lookupResult.getRecords());
}
@Test
void lookupAsync_searchAppendTooLongName() throws Exception {
wireUpMockResolver(mockResolver, query -> answer(query, name -> LOOPBACK_A));
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.searchPath(singletonList(name(format("%s.%s.%s", LONG_LABEL, LONG_LABEL, LONG_LABEL))))
.build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name(LONG_LABEL), A, IN);
LookupResult lookupResult = resultFuture.toCompletableFuture().get();
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockResolver).sendAsync(messageCaptor.capture(), any(Executor.class));
assertEquals(
Record.newRecord(name(LONG_LABEL + "."), A, IN, 0L),
messageCaptor.getValue().getSection(Section.QUESTION).get(0));
assertEquals(
singletonList(LOOPBACK_A.withName(name(LONG_LABEL + "."))), lookupResult.getRecords());
}
@Test
void lookupAsync_twoItemSearchPath() throws Exception {
wireUpMockResolver(
mockResolver,
query -> answer(query, name -> name.equals(name("host.a.")) ? null : LOOPBACK_A));
LookupSession lookupSession =
LookupSession.builder()
.resolver(mockResolver)
.searchPath(asList(name("a"), name("b")))
.build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(name("host"), A, IN);
LookupResult lookupResult = resultFuture.toCompletableFuture().get();
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
verify(mockResolver, times(2)).sendAsync(messageCaptor.capture(), any(Executor.class));
List<Message> allValues = messageCaptor.getAllValues();
assertEquals(
Record.newRecord(name("host.a."), Type.A, DClass.IN, 0L),
allValues.get(0).getSection(Section.QUESTION).get(0));
assertEquals(
Record.newRecord(name("host.b."), Type.A, DClass.IN, 0L),
allValues.get(1).getSection(Section.QUESTION).get(0));
assertEquals(singletonList(LOOPBACK_A.withName(name("host.b."))), lookupResult.getRecords());
}
@Test
void lookupAsync_absoluteQueryWithCacheNoCycleResults()
throws InterruptedException, ExecutionException, UnknownHostException {
Name aName = name("a.b.");
InetAddress anotherAddress = InetAddress.getByName("192.168.168.1");
ARecord anotherA = new ARecord(aName, IN, 3600, anotherAddress);
Cache mockCache = mock(Cache.class);
when(mockCache.getDClass()).thenReturn(IN);
SetResponse response = mock(SetResponse.class);
when(response.isSuccessful()).thenReturn(true);
RRset rrSet = new RRset();
rrSet.addRR(LOOPBACK_A.withName(aName));
rrSet.addRR(anotherA);
when(response.answers()).thenReturn(singletonList(rrSet));
when(mockCache.lookupRecords(aName, A, Credibility.NORMAL)).thenReturn(response);
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).cache(mockCache).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(aName, A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(asList(LOOPBACK_A.withName(aName), anotherA), result.getRecords());
// should come out in the other order on the second try
resultFuture = lookupSession.lookupAsync(aName, A, IN);
result = resultFuture.toCompletableFuture().get();
assertEquals(asList(LOOPBACK_A.withName(aName), anotherA), result.getRecords());
verify(mockCache, times(2)).lookupRecords(aName, A, Credibility.NORMAL);
verifyNoMoreInteractions(mockCache);
}
@Test
void lookupAsync_absoluteQueryWithCacheCycleResults()
throws InterruptedException, ExecutionException, UnknownHostException {
Name aName = name("a.b.");
InetAddress anotherAddress = InetAddress.getByName("192.168.168.1");
ARecord anotherA = new ARecord(aName, IN, 3600, anotherAddress);
Cache mockCache = mock(Cache.class);
when(mockCache.getDClass()).thenReturn(IN);
SetResponse response = mock(SetResponse.class);
when(response.isSuccessful()).thenReturn(true);
RRset rrSet = new RRset();
rrSet.addRR(LOOPBACK_A.withName(aName));
rrSet.addRR(anotherA);
when(response.answers()).thenReturn(singletonList(rrSet));
when(mockCache.lookupRecords(aName, A, Credibility.NORMAL)).thenReturn(response);
LookupSession lookupSession =
LookupSession.builder().resolver(mockResolver).cache(mockCache).cycleResults(true).build();
CompletionStage<LookupResult> resultFuture = lookupSession.lookupAsync(aName, A, IN);
LookupResult result = resultFuture.toCompletableFuture().get();
assertEquals(asList(LOOPBACK_A.withName(aName), anotherA), result.getRecords());
// should come out in the other order on the second try
resultFuture = lookupSession.lookupAsync(aName, A, IN);
result = resultFuture.toCompletableFuture().get();
assertEquals(asList(anotherA, LOOPBACK_A.withName(aName)), result.getRecords());
verify(mockCache, times(2)).lookupRecords(aName, A, Credibility.NORMAL);
verifyNoMoreInteractions(mockCache);
}
@Test
void expandName_absolute() {
LookupSession session = LookupSession.builder().resolver(mockResolver).build();
List<Name> nameStream = session.expandName(name("a."));
assertEquals(singletonList(name("a.")), nameStream);
}
@Test
void expandName_singleSearchPath() {
LookupSession session =
LookupSession.builder().resolver(mockResolver).searchPath(name("example.com.")).build();
List<Name> nameStream = session.expandName(name("host"));
assertEquals(asList(name("host.example.com."), name("host.")), nameStream);
}
@Test
void expandName_notSetSearchPath() {
LookupSession session = LookupSession.builder().resolver(mockResolver).build();
List<Name> nameStream = session.expandName(name("host"));
assertEquals(singletonList(name("host.")), nameStream);
}
@Test
void expandName_searchPathIsMadeAbsolute() {
LookupSession session =
LookupSession.builder().resolver(mockResolver).searchPath(name("example.com")).build();
List<Name> nameStream = session.expandName(name("host"));
assertEquals(asList(name("host.example.com."), name("host.")), nameStream);
}
@Test
void expandName_defaultNdots() {
LookupSession session =
LookupSession.builder().resolver(mockResolver).searchPath(name("example.com")).build();
List<Name> nameStream = session.expandName(name("a.b"));
assertEquals(asList(name("a.b."), name("a.b.example.com.")), nameStream);
}
@Test
void expandName_ndotsMoreThanOne() {
LookupSession session =
LookupSession.builder()
.searchPath(name("example.com."))
.resolver(mockResolver)
.ndots(2)
.build();
List<Name> nameStream = session.expandName(name("a.b"));
assertEquals(asList(name("a.b.example.com."), name("a.b.")), nameStream);
}
private static CNAMERecord cname(String name, String target) {
return cname(name(name), target);
}
private static CNAMERecord cname(Name name, String target) {
return new CNAMERecord(name, IN, 0, name(target));
}
@SuppressWarnings("SameParameterValue")
private static DNAMERecord dname(String name, String target) {
return new DNAMERecord(name(name), IN, 0, name(target));
}
private static Name name(String name) {
return Name.fromConstantString(name);
}
@SuppressWarnings("SameParameterValue")
private <T extends Throwable> void assertThrowsCause(Class<T> ex, Executable executable) {
Throwable outerException = assertThrows(Throwable.class, executable);
assertEquals(ex, outerException.getCause().getClass());
}
private void wireUpMockResolver(Resolver mockResolver, Function<Message, Message> handler) {
when(mockResolver.sendAsync(any(Message.class), any(Executor.class)))
.thenAnswer(
invocation -> {
Message query = invocation.getArgument(0);
return CompletableFuture.completedFuture(handler.apply(query));
});
}
}
|
package Stream;
import java.io.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main_Stream {
public static void main(String[] args) throws IOException, DoublePatientException {
Scanner scanner = new Scanner(System.in);
Set<Patient> patientOne = new HashSet<>();
PatienInput patienInput = new InputConsolePatient();
GetRemotePatients remotePatients = new GetRemotePatients();
OutputLocalPatients localPatients = new OutputLocalPatients();
StartUpMenu menu = new StartUpMenu();
do {
switch (menu.startMenu()) {
case 1:
remotePatients.addRemote();
break;
case 2:
do {
patientOne = patienInput.addPatient();
scanner.nextLine();
System.out.println("Do you want to add one more patient (enter 'y' or 'n') ? ");
} while (scanner.nextLine().equals("y"));
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("base1.date"))) {
oos.writeObject(patientOne);
oos.flush();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
break;
case 3:
localPatients.getLocalPatientsInfo();
break;
}
System.out.println("Do you want to contitnue the work with patients list (press 'y' or 'n') ? ");
} while (scanner.nextLine().equals("y"));
System.out.println("See you next time !");
}
}
|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.neuro4j.studio.debug.ui.views;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.debug.internal.core.IInternalDebugCoreConstants;
import org.eclipse.debug.internal.ui.viewers.model.IInternalTreeModelViewer;
import org.eclipse.debug.internal.ui.viewers.model.ILabelUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.ITreeModelContentProvider;
import org.eclipse.debug.internal.ui.viewers.model.ITreeModelLabelProvider;
import org.eclipse.debug.internal.ui.viewers.model.ViewerAdapterService;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ICheckUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentation;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentation2;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IColumnPresentationFactory;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelChangedListener;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelSelectionPolicy;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IStateUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ITreeModelViewer;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdateListener;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.PresentationContext;
import org.eclipse.jdt.internal.debug.ui.variables.JavaVariableColumnPresentation;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ILazyTreePathContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerLabel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IMemento;
/**
* A tree viewer that displays a model.
*
* @since 3.3
*/
public class InternalTreeModelViewer extends TreeViewer
implements IInternalTreeModelViewer, org.eclipse.debug.internal.ui.viewers.model.ITreeModelViewer
{
static final TreePath EMPTY_TREE_PATH = new TreePath(new Object[0]);
private IPresentationContext fContext;
/**
* Current column presentation or <code>null</code>
*/
private IColumnPresentation fColumnPresentation = null;
/**
* Map of columns presentation id to its visible columns id's (String[])
* When a columns presentation is not in the map, default settings are used.
*/
private Map fVisibleColumns = new HashMap();
/**
* Map of column id's to persisted sizes
*/
private Map fColumnSizes = new HashMap();
/**
* Map of column presentation id's to an array of integers representing the column order
* for that presentation, or <code>null</code> if default.
*/
private Map fColumnOrder = new HashMap();
/**
* Map of column presentation id to whether columns should be displayed
* for that presentation (the user can toggle columns on/off when a
* presentation is optional.
*/
private Map fShowColumns = new HashMap();
/**
* Item's tree path cache
*/
private static final String TREE_PATH_KEY = "TREE_PATH_KEY"; //$NON-NLS-1$
/**
* Memento type for column sizes. Sizes are keyed by column presentation id
*/
private static final String COLUMN_SIZES = "COLUMN_SIZES"; //$NON-NLS-1$
/**
* Memento type for the column order for a presentation context.
* A memento is created for each column presentation
*/
private static final String COLUMN_ORDER = "COLUMN_ORDER"; //$NON-NLS-1$
/**
* Memento type for the visible columns for a presentation context.
* A memento is created for each column presentation keyed by column number
*/
private static final String VISIBLE_COLUMNS = "VISIBLE_COLUMNS"; //$NON-NLS-1$
/**
* Memento type for whether columns are visible for a presentation context.
* Booleans are keyed by column presentation id
*/
private static final String SHOW_COLUMNS = "SHOW_COLUMNS"; //$NON-NLS-1$
/**
* Memento key for the number of visible columns in a VISIBLE_COLUMNS memento
* or for the width of a column
*/
private static final String SIZE = "SIZE"; //$NON-NLS-1$
/**
* Memento key prefix a visible column
*/
private static final String COLUMN = "COLUMN"; //$NON-NLS-1$
/**
* True while performing an insert... we allow insert with filters
*/
private boolean fInserting = false;
/**
* Whether to notify the content provider when an element is unmapped
*/
private boolean fNotifyUnmap = true;
/**
* Persist column sizes when they change.
*
* @since 3.2
*/
class ColumnListener implements ControlListener {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.ControlListener#controlMoved(org.eclipse.swt.events.ControlEvent)
*/
public void controlMoved(ControlEvent e) {
persistColumnOrder();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.ControlListener#controlResized(org.eclipse.swt.events.ControlEvent)
*/
public void controlResized(ControlEvent e) {
persistColumnSizes();
}
}
private ColumnListener fListener = new ColumnListener();
/**
* Proxy to cell modifier/editor support
*/
class CellModifierProxy implements ICellModifier {
private ICellModifier fModifier;
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ICellModifier#canModify(java.lang.Object, java.lang.String)
*/
public boolean canModify(Object element, String property) {
IElementEditor editor = ViewerAdapterService.getElementEditor(element);
if (editor != null) {
fModifier = editor.getCellModifier(getPresentationContext(), element);
if (fModifier != null) {
if (fModifier.canModify(element, property)) {
// install cell editor
CellEditor cellEditor = editor.getCellEditor(getPresentationContext(), property, element, (Composite) getControl());
if (cellEditor != null) {
disposeCellEditors();
CellEditor[] newEditors = new CellEditor[getVisibleColumns().length];
for (int i = 0; i < newEditors.length; i++) {
newEditors[i] = cellEditor;
}
setCellEditors(newEditors);
return true;
}
}
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ICellModifier#getValue(java.lang.Object, java.lang.String)
*/
public Object getValue(Object element, String property) {
if (fModifier != null) {
return fModifier.getValue(element, property);
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ICellModifier#modify(java.lang.Object, java.lang.String, java.lang.Object)
*/
public void modify(Object element, String property, Object value) {
if (fModifier != null) {
if (element instanceof Item) {
element = ((Item) element).getData();
}
fModifier.modify(element, property, value);
}
}
/**
* Clears client's column editor and cell editors
*/
protected void clear() {
fModifier = null;
disposeCellEditors();
setCellEditors(null);
}
/**
* Disposes current cell editors
*/
protected void disposeCellEditors() {
CellEditor[] cellEditors = getCellEditors();
if (cellEditors != null) {
for (int i = 0; i < cellEditors.length; i++) {
CellEditor editor = cellEditors[i];
if (editor != null) {
editor.dispose();
}
}
}
}
}
private CellModifierProxy fCellModifier;
/**
* @param parent
* the parent composite
* @param style
* the widget style bits
* @param context
* the presentation context
*/
public InternalTreeModelViewer(Composite parent, int style, IPresentationContext context) {
super(parent, style);
if ((style & SWT.VIRTUAL) == 0) {
throw new IllegalArgumentException("style must include SWT.VIRTUAL"); //$NON-NLS-1$
}
setUseHashlookup(true);
fCellModifier = new CellModifierProxy();
fContext = context;
setContentProvider(createContentProvider());
setLabelProvider(createLabelProvider());
// A pop-up viewer is transient and does not automatically expand
// and select elements up when requested by the model
if ((style & SWT.POP_UP) != 0) {
((ITreeModelContentProvider) getContentProvider()).setModelDeltaMask(
~ITreeModelContentProvider.CONTROL_MODEL_DELTA_FLAGS);
}
if ((style & SWT.CHECK) != 0) {
context.setProperty(ICheckUpdate.PROP_CHECK, Boolean.TRUE);
}
}
/**
* @return content provider for this tree viewer
*/
protected ITreeModelContentProvider createContentProvider()
{
return new TreeModelContentProvider();
}
/**
* @return label provider for this tree viewer
*/
protected ITreeModelLabelProvider createLabelProvider()
{
return new MyTreeModelLabelProvider(this);
}
/*
* (non-Javadoc)
*
* Workaround for bug 159461: when an item is cleared it's label is cleared. To avoid
* flashing, restore its label to its previous value.
*
* @see org.eclipse.jface.viewers.TreeViewer#hookControl(org.eclipse.swt.widgets.Control)
*/
protected void hookControl(Control control) {
Tree treeControl = (Tree) control;
treeControl.addListener(SWT.SetData, new Listener() {
public void handleEvent(Event event) {
// to avoid flash, reset previous label data
TreeItem item = (TreeItem) event.item;
preserveItem(item);
}
});
super.hookControl(control);
}
/**
* @param item
* the item
*/
private void preserveItem(TreeItem item) {
Object[] labels = (Object[]) item.getData(PREV_LABEL_KEY);
if (labels != null) {
for (int i = 0; i < labels.length; i++) {
if (labels[i] != null) {
item.setText(i, (String) labels[i]);
}
}
}
Object[] images = (Object[]) item.getData(PREV_IMAGE_KEY);
if (images != null) {
for (int i = 0; i < images.length; i++) {
item.setImage(i, (Image) images[i]);
}
}
Object[] fonts = (Object[]) item.getData(PREV_FONT_KEY);
if (fonts != null) {
for (int i = 0; i < fonts.length; i++) {
item.setFont(i, (Font) fonts[i]);
}
}
Object[] foregrounds = (Object[]) item.getData(PREV_FOREGROUND_KEY);
if (foregrounds != null) {
for (int i = 0; i < foregrounds.length; i++) {
item.setForeground(i, (Color) foregrounds[i]);
}
}
Object[] backgrounds = (Object[]) item.getData(PREV_BACKGROUND_KEY);
if (backgrounds != null) {
for (int i = 0; i < backgrounds.length; i++) {
item.setBackground(i, (Color) backgrounds[i]);
}
}
Boolean checked = (Boolean) item.getData(PREV_CHECKED_KEY);
if (checked != null) {
item.setChecked(checked.booleanValue());
}
Boolean grayed = (Boolean) item.getData(PREV_GRAYED_KEY);
if (grayed != null) {
item.setGrayed(grayed.booleanValue());
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#handleInvalidSelection
*
* Override the default handler for invalid selection to allow model
* selection policy to select the new selection.
*/
protected void handleInvalidSelection(ISelection selection, ISelection newSelection) {
IModelSelectionPolicy selectionPolicy = ViewerAdapterService.getSelectionPolicy(selection, getPresentationContext());
if (selectionPolicy != null) {
while (!selection.equals(newSelection)) {
ISelection temp = newSelection;
selection = selectionPolicy.replaceInvalidSelection(selection, newSelection);
if (selection == null) {
selection = TreeSelection.EMPTY;
}
if (!temp.equals(selection)) {
setSelectionToWidget(selection, false);
newSelection = getSelection();
} else {
break;
}
}
}
super.handleInvalidSelection(selection, newSelection);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ContentViewer#handleDispose(org.eclipse.swt.events.DisposeEvent)
*/
protected void handleDispose(DisposeEvent event) {
if (fColumnPresentation != null) {
fColumnPresentation.dispose();
}
fCellModifier.clear();
super.handleDispose(event);
}
/**
* Returns this viewer's presentation context.
*
* @return presentation context
*/
public IPresentationContext getPresentationContext() {
return fContext;
}
protected void unmapElement(Object element, Widget widget) {
if (fNotifyUnmap) {
// TODO: should we update the filter with the "new non-identical element"?
((ITreeModelContentProvider) getContentProvider()).unmapPath((TreePath) widget.getData(TREE_PATH_KEY));
}
super.unmapElement(element, widget);
}
protected void associate(Object element, Item item) {
// see AbstractTreeViewer.associate(...)
Object data = item.getData();
if (data != null && data != element && equals(data, element)) {
// elements are equal but not identical
// -> being removed from map, but should not change filters
try {
fNotifyUnmap = false;
super.associate(element, item);
} finally {
fNotifyUnmap = true;
}
} else {
super.associate(element, item);
}
}
/*
* (non-Javadoc)
*
* We need tree paths when disposed/unmapped in any order so cache the tree path.
*
* @see org.eclipse.jface.viewers.TreeViewer#mapElement(java.lang.Object, org.eclipse.swt.widgets.Widget)
*/
protected void mapElement(Object element, Widget widget) {
super.mapElement(element, widget);
if (widget instanceof Item) {
widget.setData(TREE_PATH_KEY, getTreePathFromItem((Item) widget));
} else {
widget.setData(TREE_PATH_KEY, EMPTY_TREE_PATH);
}
}
/*
* (non-Javadoc)
*
* Override because we allow inserting with filters present.
*
* @see org.eclipse.jface.viewers.AbstractTreeViewer#insert(java.lang.Object, java.lang.Object, int)
*/
public void insert(Object parentElementOrTreePath, Object element, int position) {
try {
fInserting = true;
super.insert(parentElementOrTreePath, element, position);
} finally {
fInserting = false;
}
}
/*
* (non-Javadoc)
*
* Override because we allow inserting with filters present.
*
* @see org.eclipse.jface.viewers.StructuredViewer#hasFilters()
*/
protected boolean hasFilters() {
if (fInserting) {
return false;
}
return super.hasFilters();
}
protected void unmapAllElements() {
// Do nothing when called from StructuredViewer.setInput(), to avoid
// clearing elements before viewer state is saved.
// Bug 326917
if (getControl().isDisposed()) {
unmapAllElements();
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.AbstractTreeViewer#inputChanged(java.lang.Object, java.lang.Object)
*/
protected void inputChanged(Object input, Object oldInput) {
fCellModifier.clear();
// Clear items map now that ITreeModelContentProvider.inputChanged() was already called.
// Bug 326917
super.unmapAllElements();
((ITreeModelContentProvider) getContentProvider()).postInputChanged(this, oldInput, input);
super.inputChanged(input, oldInput);
resetColumns(input);
}
/**
* Configures the columns for the given viewer input.
*
* @param input
* the viewer input
*/
protected void resetColumns(Object input) {
if (input != null) {
// only change columns if the input is non-null (persist when empty)
IColumnPresentationFactory factory = ViewerAdapterService.getColumnPresentationFactory(input);
PresentationContext context = (PresentationContext) getPresentationContext();
String type = null;
if (factory != null) {
type = factory.getColumnPresentationId(context, input);
}
fColumnPresentation = new JavaVariableColumnPresentation();
if (type != null && factory != null) {
if (fColumnPresentation != null) {
if (!fColumnPresentation.getId().equals(type)) {
// dispose old, create new
fColumnPresentation.dispose();
fColumnPresentation = null;
}
}
if (fColumnPresentation == null) {
fColumnPresentation = factory.createColumnPresentation(context, input);
if (fColumnPresentation != null) {
fColumnPresentation.init(context);
configureColumns();
}
}
} else {
if (fColumnPresentation != null) {
fColumnPresentation.dispose();
fColumnPresentation = null;
configureColumns();
}
}
}
}
/**
* Configures the columns based on the current settings.
*/
protected void configureColumns() {
if (fColumnPresentation != null) {
IColumnPresentation build = null;
if (isShowColumns(fColumnPresentation.getId())) {
build = fColumnPresentation;
}
buildColumns(build);
} else {
// get rid of columns
buildColumns(null);
}
}
/**
* Toggles columns on/off for the current column presentation, if any.
*
* @param show
* whether to show columns if the current input supports
* columns
*/
public void setShowColumns(boolean show) {
if (show) {
if (!isShowColumns()) {
fShowColumns.remove(fColumnPresentation.getId());
}
} else {
if (isShowColumns()) {
fShowColumns.put(fColumnPresentation.getId(), Boolean.FALSE);
}
}
refreshColumns();
}
/**
* Resets any persisted column size for the given columns
*
* @param columnIds
* the identifiers of the columns to reset
*/
public void resetColumnSizes(String[] columnIds) {
for (int i = 0; i < columnIds.length; i++) {
fColumnSizes.remove(columnIds[i]);
}
}
/**
* Sets the id's of visible columns, or <code>null</code> to set default columns.
* Only affects the current column presentation.
*
* @param ids
* visible columns
*/
public void setVisibleColumns(String[] ids) {
if (ids != null && ids.length == 0) {
ids = null;
}
IColumnPresentation presentation = getColumnPresentation();
if (presentation != null) {
fColumnOrder.remove(presentation.getId());
fVisibleColumns.remove(presentation.getId());
if (ids != null) {
// put back in table if not default
String[] columns = presentation.getInitialColumns();
if (columns.length == ids.length) {
for (int i = 0; i < columns.length; i++) {
if (!ids[i].equals(columns[i])) {
fVisibleColumns.put(presentation.getId(), ids);
break;
}
}
} else {
fVisibleColumns.put(presentation.getId(), ids);
}
}
PresentationContext presentationContext = (PresentationContext) getPresentationContext();
presentationContext.setColumns(getVisibleColumns());
refreshColumns();
}
}
protected void internalRefresh(Object element, boolean updateLabels) {
ITreeModelContentProvider contentProvider = (ITreeModelContentProvider) getContentProvider();
if (element == null) {
internalRefresh(getControl(), getRoot(), true, updateLabels);
contentProvider.preserveState(TreePath.EMPTY);
} else {
Widget[] items = findItems(element);
if (items.length != 0) {
for (int i = 0; i < items.length; i++) {
if (items[i] instanceof TreeItem) {
contentProvider.preserveState(getTreePathFromItem((TreeItem) items[i]));
} else {
contentProvider.preserveState(TreePath.EMPTY);
}
}
}
}
super.internalRefresh(element, updateLabels);
}
/**
* Refreshes the columns in the view, based on the viewer input.
*/
protected void refreshColumns() {
configureColumns();
refresh();
}
/**
* Returns whether columns are being displayed currently.
*
* @return if columns are being shown
*/
public boolean isShowColumns() {
if (fColumnPresentation != null) {
return isShowColumns(fColumnPresentation.getId());
}
return false;
}
/**
* Returns whether columns can be toggled on/off for the current input.
*
* @return whether columns can be toggled on/off for the current input
*/
public boolean canToggleColumns() {
return fColumnPresentation != null && fColumnPresentation.isOptional();
}
protected boolean isShowColumns(String columnPresentationId) {
Boolean bool = (Boolean) fShowColumns.get(columnPresentationId);
if (bool == null) {
return true;
}
return bool.booleanValue();
}
/**
* Creates new columns for the given presentation.
*
* TODO: does this need to be asynchronous?
*
* @param presentation
* the column presentation to build from
*/
protected void buildColumns(IColumnPresentation presentation) {
// dispose current columns, persisting their weights
Tree tree = getTree();
final TreeColumn[] columns = tree.getColumns();
String[] visibleColumnIds = getVisibleColumns();
// remove all listeners before disposing - see bug 223233
for (int i = 0; i < columns.length; i++) {
columns[i].removeControlListener(fListener);
}
for (int i = 0; i < columns.length; i++) {
columns[i].dispose();
}
PresentationContext presentationContext = (PresentationContext) getPresentationContext();
if (presentation != null) {
for (int i = 0; i < visibleColumnIds.length; i++) {
String id = visibleColumnIds[i];
String header = presentation.getHeader(id);
// TODO: allow client to specify style
TreeColumn column = new TreeColumn(tree, SWT.LEFT, i);
column.setMoveable(true);
column.setText(header);
column.setWidth(1);
ImageDescriptor image = presentation.getImageDescriptor(id);
if (image != null) {
column.setImage(((ITreeModelLabelProvider) getLabelProvider()).getImage(image));
}
column.setData(id);
}
int[] order = (int[]) fColumnOrder.get(presentation.getId());
if (order != null) {
tree.setColumnOrder(order);
}
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
presentationContext.setColumns(visibleColumnIds);
setColumnProperties(visibleColumnIds);
setCellModifier(fCellModifier);
} else {
tree.setHeaderVisible(false);
tree.setLinesVisible(false);
presentationContext.setColumns(null);
setCellModifier(null);
setColumnProperties(null);
}
int treeWidgetWidth = tree.getSize().x;
int avg = treeWidgetWidth;
if (visibleColumnIds != null)
avg /= visibleColumnIds.length;
if (avg == 0) {
tree.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Tree tree2 = getTree();
String[] visibleColumns = getVisibleColumns();
if (visibleColumns != null) {
int treeWidgetWidth1 = tree2.getSize().x;
int avg1 = treeWidgetWidth1 / visibleColumns.length;
initColumns(avg1, treeWidgetWidth1, visibleColumns);
}
tree2.removePaintListener(this);
}
});
} else {
initColumns(avg, treeWidgetWidth, visibleColumnIds);
}
}
private void initColumns(int widthHint, int treeWidgetWidth, String[] visibleColumnIds) {
TreeColumn[] columns = getTree().getColumns();
for (int i = 0; i < columns.length; i++) {
TreeColumn treeColumn = columns[i];
Object colData = treeColumn.getData();
String columnId = colData instanceof String ? (String) colData : null;
Integer width = (Integer) fColumnSizes.get(colData);
if (width == null) {
int ans = getInitialColumnWidth(columnId, treeWidgetWidth, visibleColumnIds);
if (ans == -1) {
treeColumn.setWidth(widthHint);
} else {
treeColumn.setWidth(ans);
}
} else {
treeColumn.setWidth(width.intValue());
}
treeColumn.addControlListener(fListener);
}
}
/**
* Returns the current column presentation for this viewer, or <code>null</code> if none.
*
* @return column presentation or <code>null</code>
*/
public IColumnPresentation getColumnPresentation() {
return fColumnPresentation;
}
/**
* Returns identifiers of the visible columns in this viewer, or <code>null</code> if there is currently no column
* presentation.
*
* @return visible columns or <code>null</code>
*/
public String[] getVisibleColumns() {
if (isShowColumns()) {
IColumnPresentation presentation = getColumnPresentation();
if (presentation != null) {
String[] columns = (String[]) fVisibleColumns.get(presentation.getId());
if (columns == null) {
return presentation.getInitialColumns();
} else {
String[] available = presentation.getAvailableColumns();
for (int i = 0; i < columns.length; i++) {
boolean columnAvailable = false;
for (int j = 0; j < available.length; j++) {
if (columns[i].equals(available[j]))
columnAvailable = true;
}
if (!columnAvailable || presentation.getHeader(columns[i]) == null) {
// We found a column ID which is not in current list of available column IDs.
// Or the presentation cannot return a header title for the given column.
// Clear out saved column data for given column presentation.
fVisibleColumns.remove(presentation.getId());
fColumnOrder.remove(presentation.getId());
fColumnSizes.remove(presentation.getId());
return presentation.getInitialColumns();
}
}
}
return columns;
}
}
return null;
}
/**
* Returns initial column width of a given column, or -1
*
* @param columnId
* column Id
* @param treeWidgetWidth
* tree widget width
* @param visibleColumnIds
* visible columns
*
* @return column width
*/
public int getInitialColumnWidth(String columnId, int treeWidgetWidth, String[] visibleColumnIds) {
if (isShowColumns()) {
IColumnPresentation presentation = getColumnPresentation();
if (presentation instanceof IColumnPresentation2) {
int ans = ((IColumnPresentation2) presentation).getInitialColumnWidth(columnId, treeWidgetWidth, visibleColumnIds);
return ans;
}
}
return -1;
}
/**
* Persists column sizes in cache
*/
protected void persistColumnSizes() {
Tree tree = getTree();
TreeColumn[] columns = tree.getColumns();
for (int i = 0; i < columns.length; i++) {
TreeColumn treeColumn = columns[i];
Object id = treeColumn.getData();
fColumnSizes.put(id, new Integer(treeColumn.getWidth()));
}
}
/**
* Persists column ordering
*/
protected void persistColumnOrder() {
IColumnPresentation presentation = getColumnPresentation();
if (presentation != null) {
Tree tree = getTree();
int[] order = tree.getColumnOrder();
if (order.length > 0) {
for (int i = 0; i < order.length; i++) {
if (i != order[i]) {
// non default order
fColumnOrder.put(presentation.getId(), order);
return;
}
}
}
// default order
fColumnOrder.remove(presentation.getId());
}
}
/**
* Save viewer state into the given memento.
*
* @param memento
* the {@link IMemento} to save to
*/
public void saveState(IMemento memento) {
if (!fColumnSizes.isEmpty()) {
Iterator iterator = fColumnSizes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Entry) iterator.next();
IMemento sizes = memento.createChild(COLUMN_SIZES, (String) entry.getKey());
sizes.putInteger(SIZE, ((Integer) entry.getValue()).intValue());
}
}
if (!fShowColumns.isEmpty()) {
Iterator iterator = fShowColumns.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Entry) iterator.next();
IMemento sizes = memento.createChild(SHOW_COLUMNS, (String) entry.getKey());
sizes.putString(SHOW_COLUMNS, ((Boolean) entry.getValue()).toString());
}
}
if (!fVisibleColumns.isEmpty()) {
Iterator iterator = fVisibleColumns.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Entry) iterator.next();
String id = (String) entry.getKey();
IMemento visible = memento.createChild(VISIBLE_COLUMNS, id);
String[] columns = (String[]) entry.getValue();
visible.putInteger(SIZE, columns.length);
for (int i = 0; i < columns.length; i++) {
visible.putString(COLUMN + Integer.toString(i), columns[i]);
}
}
}
if (!fColumnOrder.isEmpty()) {
Iterator iterator = fColumnOrder.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Entry) iterator.next();
String id = (String) entry.getKey();
IMemento orderMemento = memento.createChild(COLUMN_ORDER, id);
int[] order = (int[]) entry.getValue();
orderMemento.putInteger(SIZE, order.length);
for (int i = 0; i < order.length; i++) {
orderMemento.putInteger(COLUMN + Integer.toString(i), order[i]);
}
}
}
// save presentation context properties
IPresentationContext context = getPresentationContext();
if (context instanceof PresentationContext) {
PresentationContext pc = (PresentationContext) context;
pc.saveProperites(memento);
}
}
/**
* Initializes viewer state from the memento
*
* @param memento
* the {@link IMemento} to read from
*/
public void initState(IMemento memento) {
IMemento[] mementos = memento.getChildren(COLUMN_SIZES);
for (int i = 0; i < mementos.length; i++) {
IMemento child = mementos[i];
String id = child.getID();
Integer size = child.getInteger(SIZE);
if (size != null) {
fColumnSizes.put(id, size);
}
}
mementos = memento.getChildren(SHOW_COLUMNS);
for (int i = 0; i < mementos.length; i++) {
IMemento child = mementos[i];
String id = child.getID();
Boolean bool = Boolean.valueOf(child.getString(SHOW_COLUMNS));
if (!bool.booleanValue()) {
fShowColumns.put(id, bool);
}
}
mementos = memento.getChildren(VISIBLE_COLUMNS);
for (int i = 0; i < mementos.length; i++) {
IMemento child = mementos[i];
String id = child.getID();
Integer integer = child.getInteger(SIZE);
if (integer != null) {
int length = integer.intValue();
String[] columns = new String[length];
for (int j = 0; j < length; j++) {
columns[j] = child.getString(COLUMN + Integer.toString(j));
}
fVisibleColumns.put(id, columns);
}
}
mementos = memento.getChildren(COLUMN_ORDER);
for (int i = 0; i < mementos.length; i++) {
IMemento child = mementos[i];
String id = child.getID();
Integer integer = child.getInteger(SIZE);
if (integer != null) {
int length = integer.intValue();
int[] order = new int[length];
for (int j = 0; j < length; j++) {
order[j] = child.getInteger(COLUMN + Integer.toString(j)).intValue();
}
fColumnOrder.put(id, order);
}
}
// restore presentation context properties
// save presentation context properties
IPresentationContext context = getPresentationContext();
if (context instanceof PresentationContext) {
PresentationContext pc = (PresentationContext) context;
pc.initProperties(memento);
}
}
/**
* Returns whether the candidate selection should override the current
* selection.
*
* @param current
* the current selection
* @param candidate
* the candidate for the new selection
* @return if the current selection should be replaced with the candidate selection
*/
public boolean overrideSelection(ISelection current, ISelection candidate) {
IModelSelectionPolicy selectionPolicy = ViewerAdapterService.getSelectionPolicy(current, getPresentationContext());
if (selectionPolicy == null) {
return true;
}
if (selectionPolicy.contains(candidate, getPresentationContext())) {
return selectionPolicy.overrides(current, candidate, getPresentationContext());
}
return !selectionPolicy.isSticky(current, getPresentationContext());
}
/*
* (non-Javadoc)
*
* Consider selection policy
*
* @see org.eclipse.jface.viewers.StructuredViewer#setSelection(org.eclipse.jface.viewers.ISelection, boolean)
*/
public void setSelection(ISelection selection, boolean reveal) {
if (!overrideSelection(getSelection(), selection)) {
return;
}
super.setSelection(selection, reveal);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.internal.ui.viewers.model.ITreeModelViewer#setSelection(org.eclipse.jface.viewers.ISelection,
* boolean, boolean)
*/
public void setSelection(ISelection selection, boolean reveal, boolean force) {
trySelection(selection, reveal, force);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.internal.ui.viewers.model.ITreeModelViewer#trySelection(org.eclipse.jface.viewers.ISelection,
* boolean, boolean)
*/
public boolean trySelection(ISelection selection, boolean reveal, boolean force) {
if (force || overrideSelection(getSelection(), selection)) {
super.setSelection(selection, reveal);
return true;
}
return false;
}
/**
* Registers the specified listener for view update notifications.
*
* @param listener
* listener
*/
public void addViewerUpdateListener(IViewerUpdateListener listener) {
((ITreeModelContentProvider) getContentProvider()).addViewerUpdateListener(listener);
}
/**
* Removes the specified listener from update notifications.
*
* @param listener
* listener
*/
public void removeViewerUpdateListener(IViewerUpdateListener listener) {
ITreeModelContentProvider cp = (ITreeModelContentProvider) getContentProvider();
if (cp != null) {
cp.removeViewerUpdateListener(listener);
}
}
/**
* Registers the given listener for model delta notification.
*
* @param listener
* model delta listener
*/
public void addModelChangedListener(IModelChangedListener listener) {
((ITreeModelContentProvider) getContentProvider()).addModelChangedListener(listener);
}
/**
* Unregisters the given listener from model delta notification.
*
* @param listener
* model delta listener
*/
public void removeModelChangedListener(IModelChangedListener listener) {
ITreeModelContentProvider cp = (ITreeModelContentProvider) getContentProvider();
if (cp != null) {
cp.removeModelChangedListener(listener);
}
}
public void addStateUpdateListener(IStateUpdateListener listener) {
((ITreeModelContentProvider) getContentProvider()).addStateUpdateListener(listener);
}
public void removeStateUpdateListener(IStateUpdateListener listener) {
ITreeModelContentProvider cp = (ITreeModelContentProvider) getContentProvider();
if (cp != null) {
cp.removeStateUpdateListener(listener);
}
}
/*
* (non-Javadoc) Method declared in AbstractTreeViewer.
*/
protected void doUpdateItem(final Item item, Object element) {
if (!(item instanceof TreeItem)) {
return;
}
TreeItem treeItem = (TreeItem) item;
if (treeItem.isDisposed()) {
unmapElement(element, treeItem);
return;
}
if (!((ITreeModelLabelProvider) getLabelProvider()).update(getTreePathFromItem(item))) {
if (element instanceof String) {
item.setData(PREV_LABEL_KEY, new String[] { (String) element });
}
}
// As it is possible for user code to run the event
// loop check here.
if (item.isDisposed()) {
unmapElement(element, item);
}
}
public void addLabelUpdateListener(ILabelUpdateListener listener) {
((ITreeModelLabelProvider) getLabelProvider()).addLabelUpdateListener(listener);
}
public void removeLabelUpdateListener(ILabelUpdateListener listener) {
if (!getControl().isDisposed()) {
((ITreeModelLabelProvider) getLabelProvider()).removeLabelUpdateListener(listener);
}
}
/**
* Returns the item for the element at the given tree path or <code>null</code> if none.
*
* @param path
* tree path
* @return item or <code>null</code>
*/
public Widget findItem(TreePath path) {
if (path.getSegmentCount() == 0) {
return getTree();
}
Widget[] items = super.findItems(path.getLastSegment());
if (items.length == 1) {
return items[0];
}
for (int i = 0; i < items.length; i++) {
if (getTreePathFromItem((Item) items[i]).equals(path)) {
return items[i];
}
}
return null;
}
public Item[] getChildren(Widget widget) {
return super.getChildren(widget);
}
/**
* Returns the tree path for the given item.
*
* @param item
* the item to compute the {@link TreePath} for
* @return {@link TreePath}
*/
protected TreePath getTreePathFromItem(Item item) {
return super.getTreePathFromItem(item);
}
// **************************************************************************
// These methods were copied from TreeViewer as a workaround for bug 183463:
// Expanded nodes in tree viewer flash on refresh
/*
* (non-Javadoc)
*
* workaround for bug 183463
*
* @see org.eclipse.jface.viewers.AbstractTreeViewer#internalRefreshStruct(org.eclipse.swt.widgets.Widget,
* java.lang.Object, boolean)
*/
protected void internalRefreshStruct(Widget widget, Object element,
boolean updateLabels) {
// clear all starting with the given widget
if (widget instanceof Tree) {
((Tree) widget).clearAll(true);
} else if (widget instanceof TreeItem) {
((TreeItem) widget).clearAll(true);
}
int index = 0;
Widget parent = null;
if (widget instanceof TreeItem) {
TreeItem treeItem = (TreeItem) widget;
parent = treeItem.getParentItem();
if (parent == null) {
parent = treeItem.getParent();
}
if (parent instanceof Tree) {
index = ((Tree) parent).indexOf(treeItem);
} else {
index = ((TreeItem) parent).indexOf(treeItem);
}
}
virtualRefreshExpandedItems(parent, widget, element, index);
}
/**
* Traverses the visible (expanded) part of the tree and updates child
* counts.
* <p>
* workaround for bug 183463
* </p>
*
* @param parent
* the parent of the widget, or <code>null</code> if the widget is the tree
* @param widget
* the parent widget
* @param element
* the underlying object
* @param index
* the index of the widget in the children array of its parent, or 0 if the widget is the tree
*/
private void virtualRefreshExpandedItems(Widget parent, Widget widget, Object element, int index) {
if (widget instanceof Tree) {
if (element == null) {
((Tree) widget).setItemCount(0);
return;
}
virtualLazyUpdateChildCount(widget, getChildren(widget).length);
} else if (((TreeItem) widget).getExpanded()) {
// prevent SetData callback
preserveItem((TreeItem) widget);
//((TreeItem)widget).setText(" "); //$NON-NLS-1$
virtualLazyUpdateWidget(parent, index);
} else {
return;
}
Item[] items = getChildren(widget);
for (int i = 0; i < items.length; i++) {
Item item = items[i];
Object data = item.getData();
virtualRefreshExpandedItems(widget, item, data, i);
}
}
/**
* workaround for bug 183463
*
* Update the child count
*
* @param widget
* the widget
* @param currentChildCount
* the current child count
*/
private void virtualLazyUpdateChildCount(Widget widget, int currentChildCount) {
TreePath treePath;
if (widget instanceof Item) {
treePath = getTreePathFromItem((Item) widget);
} else {
treePath = TreePath.EMPTY;
}
((ILazyTreePathContentProvider) getContentProvider())
.updateChildCount(treePath, currentChildCount);
}
/**
* Update the widget at index.
* <p>
* workaround for bug 183463
* </p>
*
* @param widget
* the widget
* @param index
* the index to update
*/
private void virtualLazyUpdateWidget(Widget widget, int index) {
TreePath treePath;
if (widget instanceof Item) {
if (widget.getData() == null) {
// we need to materialize the parent first
// see bug 167668
// however, that would be too risky
// see bug 182782 and bug 182598
// so we just ignore this call altogether
// and don't do this: virtualMaterializeItem((TreeItem) widget);
return;
}
treePath = getTreePathFromItem((Item) widget);
} else {
treePath = TreePath.EMPTY;
}
((ILazyTreePathContentProvider) getContentProvider())
.updateElement(treePath, index);
}
// **************************************************************************
// Another couple of methods copied from TreeViewer to workaround the UI bug 266189.
//
protected void createChildren(Widget widget) {
Object element = widget.getData();
if (element == null && widget instanceof TreeItem) {
// parent has not been materialized
virtualMaterializeItem((TreeItem) widget);
// try getting the element now that updateElement was called
element = widget.getData();
}
if (element == null) {
// give up because the parent is still not materialized
return;
}
Item[] children = getChildren(widget);
if (children.length == 1 && children[0].getData() == null) {
// found a dummy node
virtualLazyUpdateChildCount(widget, children.length);
children = getChildren(widget);
}
// DO NOT touch all children
return;
}
private void virtualMaterializeItem(TreeItem treeItem) {
if (treeItem.getData() != null) {
// already materialized
return;
}
int index;
Widget parent = treeItem.getParentItem();
if (parent == null) {
parent = treeItem.getParent();
}
Object parentElement = parent.getData();
if (parentElement != null) {
if (parent instanceof Tree) {
index = ((Tree) parent).indexOf(treeItem);
} else {
index = ((TreeItem) parent).indexOf(treeItem);
}
virtualLazyUpdateWidget(parent, index);
}
}
/**
* Performs auto expand on an element at the specified path if the auto expand
* level dictates the element should be expanded.
*
* @param elementPath
* tree path to element to consider for expansion
*/
public void autoExpand(TreePath elementPath) {
int level = getAutoExpandLevel();
if (level > 0 || level == ITreeModelViewer.ALL_LEVELS) {
if (level == ITreeModelViewer.ALL_LEVELS || level >= elementPath.getSegmentCount()) {
expandToLevel(elementPath, 1);
}
}
}
public int findElementIndex(TreePath parentPath, Object element) {
Widget parentItem = findItem(parentPath);
if (parentItem != null) {
Item[] children = getChildren(parentItem);
for (int i = 0; i < children.length; i++) {
Item item = children[i];
Object data = item.getData();
if ((element != null && element.equals(data)) || (element == null && data == null)) {
return i;
}
}
}
return -1;
}
public boolean getElementChildrenRealized(TreePath parentPath) {
Widget parentItem = findItem(parentPath);
if (parentItem != null) {
Item[] children = getChildren(parentItem);
for (int i = 0; i < children.length; i++) {
if (children[i].getData() == null) {
return false;
}
}
}
return true;
}
public Display getDisplay() {
Control control = getControl();
if (control != null) {
return control.getDisplay();
}
return null;
}
protected static final String[] STATE_PROPERTIES = new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE };
public void update(Object element) {
update(element, STATE_PROPERTIES);
}
/**
* Label data cache keys
* TODO: workaround for bug 159461
*/
static String PREV_LABEL_KEY = "PREV_LABEL_KEY"; //$NON-NLS-1$
static String PREV_IMAGE_KEY = "PREV_IMAGE_KEY"; //$NON-NLS-1$
static String PREV_FONT_KEY = "PREV_FONT_KEY"; //$NON-NLS-1$
static String PREV_FOREGROUND_KEY = "PREV_FOREGROUND_KEY"; //$NON-NLS-1$
static String PREV_BACKGROUND_KEY = "PREV_BACKGROUND_KEY"; //$NON-NLS-1$
static String PREV_CHECKED_KEY = "PREV_CHECKED_KEY"; //$NON-NLS-1$
static String PREV_GRAYED_KEY = "PREV_GRAYED_KEY"; //$NON-NLS-1$
public void setElementData(TreePath path, int numColumns, String[] labels, ImageDescriptor[] imageDescriptors,
FontData[] fontDatas, RGB[] _foregrounds, RGB[] _backgrounds)
{
Widget widget = findItem(path);
String[] columnIds = getVisibleColumns();
if (widget != null && widget instanceof TreeItem && !widget.isDisposed()) {
TreeItem item = (TreeItem) widget;
/*
* Object data = item.getData();
* int itemCount = item.getItemCount();
* item.clearAll(false);
* item.setData(data);
* item.setItemCount(itemCount);
*/
for (int i = 0; i < numColumns; i++) {
// text might be null if the launch has been terminated
item.setText(i, (labels[i] == null ? IInternalDebugCoreConstants.EMPTY_STRING : labels[i]));
}
item.setData(PREV_LABEL_KEY, labels);
if (imageDescriptors == null) {
for (int i = 0; i < numColumns; i++) {
item.setImage(i, null);
}
item.setData(PREV_IMAGE_KEY, null);
} else {
Image[] images = new Image[imageDescriptors.length];
for (int i = 0; i < imageDescriptors.length; i++) {
images[i] = ((ITreeModelLabelProvider) getLabelProvider()).getImage(imageDescriptors[i]);
}
if (columnIds == null) {
item.setImage(images[0]);
} else {
item.setImage(images);
}
item.setData(PREV_IMAGE_KEY, images);
}
if (_foregrounds == null) {
for (int i = 0; i < numColumns; i++) {
item.setForeground(i, null);
}
item.setData(PREV_FOREGROUND_KEY, null);
} else {
Color[] foregrounds = new Color[_foregrounds.length];
for (int i = 0; i < foregrounds.length; i++) {
foregrounds[i] = ((ITreeModelLabelProvider) getLabelProvider()).getColor(_foregrounds[i]);
}
if (columnIds == null) {
item.setForeground(0, foregrounds[0]);
} else {
for (int i = 0; i < foregrounds.length; i++) {
item.setForeground(i, foregrounds[i]);
}
}
item.setData(PREV_FOREGROUND_KEY, foregrounds);
}
if (_backgrounds == null) {
for (int i = 0; i < numColumns; i++) {
item.setBackground(i, null);
}
item.setData(PREV_BACKGROUND_KEY, null);
} else {
Color[] backgrounds = new Color[_backgrounds.length];
for (int i = 0; i < backgrounds.length; i++) {
backgrounds[i] = ((ITreeModelLabelProvider) getLabelProvider()).getColor(_backgrounds[i]);
}
if (columnIds == null) {
item.setBackground(0, backgrounds[0]);
} else {
for (int i = 0; i < backgrounds.length; i++) {
item.setBackground(i, backgrounds[i]);
}
}
item.setData(PREV_BACKGROUND_KEY, backgrounds);
}
if (fontDatas == null) {
for (int i = 0; i < numColumns; i++) {
item.setFont(i, null);
}
item.setData(PREV_FONT_KEY, null);
} else {
Font[] fonts = new Font[fontDatas.length];
for (int i = 0; i < fontDatas.length; i++) {
fonts[i] = ((ITreeModelLabelProvider) getLabelProvider()).getFont(fontDatas[i]);
}
if (columnIds == null) {
item.setFont(0, fonts[0]);
} else {
for (int i = 0; i < fonts.length; i++) {
item.setFont(i, fonts[i]);
}
}
item.setData(PREV_FONT_KEY, fonts);
}
}
}
public ViewerLabel getElementLabel(TreePath path, String columnId) {
if (path.getSegmentCount() == 0) {
return null;
}
int columnIdx = -1;
String[] visibleColumns = getVisibleColumns();
if (columnId != null && visibleColumns != null) {
int i = 0;
for (i = 0; i < visibleColumns.length; i++) {
if (columnId.equals(getVisibleColumns()[i])) {
columnIdx = i;
break;
}
}
if (i == visibleColumns.length) {
return null;
}
} else {
columnIdx = 0;
}
TreeItem item = (TreeItem) findItem(path);
if (item != null) {
ViewerLabel label = new ViewerLabel(item.getText(columnIdx), item.getImage(columnIdx));
label.setFont(item.getFont(columnIdx));
label.setBackground(item.getBackground(columnIdx));
label.setForeground(item.getForeground(columnIdx));
return label;
}
return null;
}
public void reveal(TreePath path, int index) {
Widget item = findItem(path);
TreeItem[] children = null;
if (item instanceof TreeItem) {
children = ((TreeItem) item).getItems();
} else if (item instanceof Tree) {
children = ((Tree) item).getItems();
}
if (children != null && index < children.length) {
getTree().setTopItem(children[index]);
}
}
public int getChildCount(TreePath path) {
if (path.getSegmentCount() == 0) {
return ((Tree) getControl()).getItemCount();
} else {
Widget[] items = internalFindItems(path);
if (items.length > 0) {
if (items[0] instanceof TreeItem) {
return ((TreeItem) items[0]).getItemCount();
}
}
}
return -1;
}
public Object getChildElement(TreePath path, int index) {
TreeItem childItem = null;
if (path.getSegmentCount() == 0) {
Tree tree = (Tree) getControl();
try {
childItem = tree.getItem(index);
} catch (IllegalArgumentException e) {
}
} else {
try {
Widget[] items = internalFindItems(path);
if (items.length > 0) {
if (items[0] instanceof TreeItem) {
childItem = ((TreeItem) items[0]).getItem(index);
}
}
} catch (IllegalArgumentException e) {
}
}
if (childItem != null) {
return childItem.getData();
}
return null;
}
public TreePath getTopElementPath() {
TreeItem topItem = ((Tree) getControl()).getTopItem();
if (topItem != null && topItem.getData() != null) {
return getTreePathFromItem(topItem);
}
return null;
}
public boolean saveElementState(TreePath path, ModelDelta delta, int flagsToSave) {
Tree tree = (Tree) getControl();
TreeItem[] selection = tree.getSelection();
Set set = new HashSet();
for (int i = 0; i < selection.length; i++) {
set.add(selection[i]);
}
TreeItem[] items = null;
Widget w = internalGetWidgetToSelect(path);
if (w instanceof Tree) {
delta.setChildCount(
((ITreeModelContentProvider) getContentProvider()).viewToModelCount(path, tree.getItemCount()));
if ((flagsToSave & IModelDelta.EXPAND) != 0) {
delta.setFlags(delta.getFlags() | IModelDelta.EXPAND);
}
items = tree.getItems();
} else if (w instanceof TreeItem) {
TreeItem item = (TreeItem) w;
if (item.getExpanded()) {
int itemCount = item.getData() != null ? item.getItemCount() : -1;
delta.setChildCount(((ITreeModelContentProvider) getContentProvider()).viewToModelCount(path, itemCount));
if ((flagsToSave & IModelDelta.EXPAND) != 0) {
delta.setFlags(delta.getFlags() | IModelDelta.EXPAND);
}
} else if ((flagsToSave & IModelDelta.COLLAPSE) != 0) {
delta.setFlags(delta.getFlags() | IModelDelta.COLLAPSE);
}
if (set.contains(item) && (flagsToSave & IModelDelta.SELECT) != 0) {
delta.setFlags(delta.getFlags() | IModelDelta.SELECT);
}
items = ((TreeItem) w).getItems();
}
if (items != null && items.length != 0) {
for (int i = 0; i < items.length; i++) {
doSaveElementState(path, delta, items[i], set, i, flagsToSave);
}
return true;
} else {
return false;
}
}
private void doSaveElementState(TreePath parentPath, ModelDelta delta, TreeItem item, Collection set, int index, int flagsToSave) {
Object element = item.getData();
if (element != null) {
boolean expanded = item.getExpanded();
boolean selected = set.contains(item);
int flags = IModelDelta.NO_CHANGE;
if (expanded && (flagsToSave & IModelDelta.EXPAND) != 0) {
flags = flags | IModelDelta.EXPAND;
}
if (!expanded && (flagsToSave & IModelDelta.COLLAPSE) != 0) {
flags = flags | IModelDelta.COLLAPSE;
}
if (selected && (flagsToSave & IModelDelta.SELECT) != 0) {
flags = flags | IModelDelta.SELECT;
}
if (expanded || flags != IModelDelta.NO_CHANGE) {
int modelIndex = ((ITreeModelContentProvider) getContentProvider()).viewToModelIndex(parentPath, index);
TreePath elementPath = parentPath.createChildPath(element);
ModelDelta childDelta = delta.addNode(element, modelIndex, flags, -1);
if (expanded) {
// Only get the item count if the item is expanded. Getting
// item count triggers an update of the element (bug 335734).
int itemCount = item.getItemCount();
int numChildren = ((ITreeModelContentProvider) getContentProvider()).viewToModelCount(elementPath, itemCount);
childDelta.setChildCount(numChildren);
TreeItem[] items = item.getItems();
for (int i = 0; i < items.length; i++) {
doSaveElementState(elementPath, childDelta, items[i], set, i, flagsToSave);
}
}
}
}
}
public void updateViewer(IModelDelta delta) {
((ITreeModelContentProvider) getContentProvider()).updateModel(delta, ITreeModelContentProvider.UPDATE_MODEL_DELTA_FLAGS);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.internal.ui.viewers.model.ITreeModelCheckProvider#setElementChecked(org.eclipse.jface.viewers
* .TreePath, boolean, boolean)
*/
public void setElementChecked(TreePath path, boolean checked, boolean grayed) {
Widget widget = findItem(path);
if (widget != null && widget instanceof TreeItem && !widget.isDisposed()) {
TreeItem item = (TreeItem) widget;
item.setChecked(checked);
item.setGrayed(grayed);
item.setData(PREV_CHECKED_KEY, checked ? Boolean.TRUE : Boolean.FALSE);
item.setData(PREV_GRAYED_KEY, grayed ? Boolean.TRUE : Boolean.FALSE);
}
}
public boolean getElementChecked(TreePath path) {
Widget widget = findItem(path);
if (widget != null && widget instanceof TreeItem && !widget.isDisposed()) {
TreeItem item = (TreeItem) widget;
return item.getChecked();
}
return false;
}
/**
* Retrieves the element's check box grayed state.
*
* @param path
* the path of the element to set grayed
* @return grayed
*/
public boolean getElementGrayed(TreePath path) {
Widget widget = findItem(path);
if (widget != null && widget instanceof TreeItem && !widget.isDisposed()) {
TreeItem item = (TreeItem) widget;
return item.getGrayed();
}
return false;
}
public boolean getHasChildren(Object elementOrTreePath) {
if (elementOrTreePath instanceof TreePath &&
((TreePath) elementOrTreePath).getSegmentCount() == 0)
{
return getTree().getItemCount() > 0;
}
Widget[] items = internalFindItems(elementOrTreePath);
if (items != null && items.length > 0) {
if (items[0] instanceof TreeItem) {
return ((TreeItem) items[0]).getItemCount() > 0;
} else {
return ((Tree) items[0]).getItemCount() > 0;
}
}
return false;
}
public TreePath[] getElementPaths(Object element) {
Widget[] items = internalFindItems(element);
TreePath[] paths = new TreePath[items.length];
for (int i = 0; i < items.length; i++) {
if (items[i] instanceof Tree) {
paths[i] = TreePath.EMPTY;
} else {
paths[i] = getTreePathFromItem((Item) items[i]);
}
}
return paths;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.StructuredViewer#handleSelect(org.eclipse.swt.events.SelectionEvent)
*/
protected void handleSelect(SelectionEvent event) {
super.handleSelect(event);
TreeItem item = (TreeItem) event.item;
if (item != null) { // item can be null when de-selected (bug 296703)
Object element = item.getData();
IContentProvider contentProvider = getContentProvider();
if (element != null && contentProvider instanceof TreeModelContentProvider) {
TreePath path = getTreePathFromItem(item);
if (event.detail == SWT.CHECK) {
boolean checked = item.getChecked();
boolean accepted = ((ITreeModelContentProvider) contentProvider).setChecked(path, checked);
// if the listen rejects the change or there is not ICheckboxModelProxy, than revert the check state
if (!accepted) {
item.setChecked(!checked);
} else {
item.setData(PREV_CHECKED_KEY, new Boolean(checked));
}
} else {
((TreeModelContentProvider) contentProvider).cancelRestore(path, IModelDelta.SELECT | IModelDelta.REVEAL);
}
}
}
}
protected void handleTreeExpand(TreeEvent event) {
super.handleTreeExpand(event);
IContentProvider contentProvider = getContentProvider();
if (contentProvider instanceof TreeModelContentProvider && event.item.getData() != null) {
TreePath path = getTreePathFromItem((TreeItem) event.item);
((TreeModelContentProvider) contentProvider).cancelRestore(path, IModelDelta.COLLAPSE);
}
}
protected void handleTreeCollapse(TreeEvent event) {
super.handleTreeCollapse(event);
IContentProvider contentProvider = getContentProvider();
if (contentProvider instanceof TreeModelContentProvider && event.item.getData() != null) {
TreePath path = getTreePathFromItem((TreeItem) event.item);
((TreeModelContentProvider) contentProvider).cancelRestore(path, IModelDelta.EXPAND);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.debug.internal.ui.viewers.model.ITreeModelContentProviderTarget#clearSelectionQuiet()
*/
public void clearSelectionQuiet() {
getTree().setSelection(new TreeItem[0]);
}
}
|
package com.daikit.graphql.meta.custommethod;
import java.util.List;
import com.daikit.graphql.custommethod.GQLCustomMethod;
/**
* GraphQL dynamic method returning a {@link List} of entities meta data
*
* @author Thibaut Caselli
*/
public class GQLMethodListScalarMetaData extends GQLAbstractMethodMetaData {
private String scalarTypeCode;
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// CONSTRUCTORS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
/**
* Default constructor
*/
public GQLMethodListScalarMetaData() {
// Nothing done
}
/**
* Constructor passing name, whether this is a mutation or a query, method
* and return type
*
* @param method
* the {@link GQLCustomMethod}
* @param scalarTypeCode
* the scalar type code for method return type
*/
public GQLMethodListScalarMetaData(final GQLCustomMethod method, final String scalarTypeCode) {
super(method);
this.scalarTypeCode = scalarTypeCode;
}
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// METHODS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
@Override
protected void appendToString(final StringBuilder stringBuilder) {
stringBuilder.append("{METHOD-LIST-SCALAR(").append(scalarTypeCode == null ? "" : scalarTypeCode).append(")}");
super.appendToString(stringBuilder);
}
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// GETTERS / SETTERS
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
/**
* Get the method scalar return type
*
* @return the scalarTypeCode
*/
public String getScalarType() {
return scalarTypeCode;
}
/**
* Set the method scalar return type
*
* @param scalarTypeCode
* the scalarTypeCode to set
* @return this instance
*/
public GQLMethodListScalarMetaData setScalarType(final String scalarTypeCode) {
this.scalarTypeCode = scalarTypeCode;
return this;
}
}
|
package edu.mit.cci.simulation.util;
import org.junit.Assert;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* User: jintrone
* Date: 3/17/11
* Time: 10:26 AM
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/META-INF/spring/applicationContext.xml","classpath:/webmvc-test-config.xml"})
public class SpringControllerEnvironment {
@Inject
protected ApplicationContext applicationContext;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected HandlerAdapter handlerAdapter;
@Before
public void setUp() throws Exception {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
Map beans = applicationContext.getBeansOfType(AnnotationMethodHandlerAdapter.class);
//this is pretty goofy, I'm not sure how to get the correct handler
this.handlerAdapter = (HandlerAdapter) beans.values().toArray()[0];
}
protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response)
throws Exception {
final HandlerMapping handlerMapping = applicationContext.getBean(DefaultAnnotationHandlerMapping.class);
final HandlerExecutionChain handler = handlerMapping.getHandler(request);
Assert.assertNotNull("No handler found for request, check you request mapping", handler);
final Object controller = handler.getHandler();
// if you want to override any injected attributes do it here
final HandlerInterceptor[] interceptors =
handlerMapping.getHandler(request).getInterceptors();
for (HandlerInterceptor interceptor : interceptors) {
final boolean carryOn = interceptor.preHandle(request, response, controller);
if (!carryOn) {
return null;
}
}
final ModelAndView mav = handlerAdapter.handle(request, response, controller);
return mav;
}
}
|
package fr.skytasul.quests.gui.templates;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import fr.skytasul.quests.editors.TextEditor;
import fr.skytasul.quests.gui.CustomInventory;
import fr.skytasul.quests.gui.Inventories;
import fr.skytasul.quests.gui.ItemUtils;
import fr.skytasul.quests.utils.Lang;
import fr.skytasul.quests.utils.LevenshteinComparator;
import fr.skytasul.quests.utils.XMaterial;
/**
* An inventory with an infinite amount of pages of 35 items (integer limit).
* @author SkytAsul
*
* @param <T> type of objects stocked in the inventory
*/
public abstract class PagedGUI<T> implements CustomInventory {
private static ItemStack itemSearch = ItemUtils.item(XMaterial.COMPASS, Lang.search.toString());
protected Player p;
protected Inventory inv;
protected int page = 0;
protected int maxPage;
private String name;
private DyeColor color;
protected List<T> objects;
protected Consumer<List<T>> validate;
private ItemStack validationItem = ItemUtils.itemDone;
protected LevenshteinComparator<T> comparator;
protected PagedGUI(String name, DyeColor color, Collection<T> objects) {
this(name, color, objects, null, null);
}
protected PagedGUI(String name, DyeColor color, Collection<T> objects, Consumer<List<T>> validate, Function<T, String> searchName) {
this.name = name;
this.color = color;
this.objects = new ArrayList<>(objects);
this.validate = validate;
if (searchName != null) this.comparator = new LevenshteinComparator<>(searchName);
}
@Override
public Inventory open(Player p) {
this.p = p;
calcMaxPages();
inv = Bukkit.createInventory(null, 45, name);
setBarItem(0, ItemUtils.itemLaterPage);
setBarItem(4, ItemUtils.itemNextPage);
if (validate != null) setBarItem(2, validationItem);
if (comparator != null) setBarItem(3, itemSearch);
for (int i = 0; i < 5; i++) inv.setItem(i * 9 + 7, ItemUtils.itemSeparator(color));
setItems();
inv = p.openInventory(inv).getTopInventory();
return inv;
}
public PagedGUI<T> setValidate(Consumer<List<T>> validate, ItemStack validationItem) {
if (this.validate != null) throw new IllegalStateException("A validation has already be added.");
if (this.inv != null) throw new IllegalStateException("Cannot add a validation after inventory opening.");
if (validationItem == null) throw new IllegalArgumentException("Cannot set a null validation item.");
this.validate = validate;
this.validationItem = validationItem;
return this;
}
public PagedGUI<T> sortValuesByName() {
Validate.notNull(comparator);
sortValues(comparator.getFunction());
return this;
}
public <C extends Comparable<C>> PagedGUI<T> sortValues(Function<T, C> mapper) {
objects.sort((o1, o2) -> {
C map1;
if (o1 == null || (map1 = mapper.apply(o1)) == null) return 1;
C map2;
if (o2 == null || (map2 = mapper.apply(o2)) == null) return -1;
return map1.compareTo(map2);
});
return this;
}
protected void calcMaxPages() {
this.maxPage = objects.isEmpty() ? 1 : (int) Math.ceil(objects.size() * 1D / 35D);
}
protected void setItems() {
for (int i = 0; i < 35; i++) setMainItem(i, null);
for (int i = page * 35; i < objects.size(); i++){
if (i == (page + 1) * 35) break;
T obj = objects.get(i);
setMainItem(i - page * 35, getItemStack(obj));
}
}
private int setMainItem(int mainSlot, ItemStack is){
int line = (int) Math.floor(mainSlot * 1.0 / 7.0);
int slot = mainSlot + (2 * line);
setItem(is, slot);
return slot;
}
private int setBarItem(int barSlot, ItemStack is){
int slot = barSlot * 9 + 8;
setItem(is, slot);
return slot;
}
private void setItem(ItemStack is, int rawSlot) {
inv.setItem(rawSlot, is);
if (is != null && is.getType() != Material.AIR) {
ItemStack invItem = inv.getItem(rawSlot);
if (invItem == null || invItem.getType() == Material.AIR) {
// means the item was a material that cannot be put in an inventory:
// fire, water block, crops...
is = is.clone();
is.setType(Material.STONE);
inv.setItem(rawSlot, is);
}
}
}
/**
* @param object T object to get the slot from
* @return slot in the inventory, -1 if the object is on another page
*/
public int getObjectSlot(T object){
int index = objects.indexOf(object);
if (index < page*35 || index > (page + 1)*35) return -1;
int line = (int) Math.floor(index * 1.0 / 7.0);
return index + (2 * line);
}
@Override
public boolean onClick(Player p, Inventory inv, ItemStack current, int slot, ClickType click) {
switch (slot % 9){
case 8:
int barSlot = (slot - 8) / 9;
switch (barSlot){
case 0:
if (page == 0) break;
page--;
setItems();
break;
case 4:
if (page+1 == maxPage) break;
page++;
setItems();
break;
case 2:
validate.accept(objects);
break;
case 3:
new TextEditor<String>(p, () -> p.openInventory(inv), (obj) -> {
//objects.stream().filter(x -> getName(x).contains((String) obj));
objects.sort(comparator.setReference(obj));
page = 0;
setItems();
p.openInventory(inv);
}).enter();
break;
}
break;
case 7:
break;
default:
int line = (int) Math.floor(slot * 1D / 9D);
int objectSlot = slot - line*2 + page*35;
click(objects.get(objectSlot), current, click);
//inv.setItem(slot, getItemStack(objects.get(objectSlot)));
}
return true;
}
public void reopen() {
Inventories.closeWithoutExit(p);
Inventories.put(p, this, inv);
inv = p.openInventory(inv).getTopInventory();
}
/**
* @param object existing object to represent
* @return ItemStack who represents the object
*/
public abstract ItemStack getItemStack(T object);
/**
* Called when an object is clicked
* @param existing clicked object
* @param item item clicked
* @param clickType click type
*/
public abstract void click(T existing, ItemStack item, ClickType clickType);
}
|
package com.infosys.androidbarchartassignment.retrofit.data;
import java.util.ArrayList;
public class GraphResponse {
// list of graph values
public ArrayList<Graph> graph;
}
|
package pro.likada.service;
import pro.likada.model.Product;
import pro.likada.model.ProductPrice;
import java.util.List;
/**
* Created by bumur on 13.02.2017.
*/
public interface ProductPriceService {
void save(ProductPrice productPrice);
ProductPrice getProductActualPrice(List<ProductPrice> productPrices);
int getPriceDirection(Product product, ProductPrice productPrice);
double getPriceDifference(Product product,ProductPrice productPrice);
}
|
package crescendo.sheetmusic;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class AdviceFrameTest
{
private AdviceFrame af;
@Before
public void setup()
{
this.af=new AdviceFrame(null,null);
JFrame frame=new JFrame("AdviceFrame Test");
frame.setSize(400,200);
frame.add(this.af);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Test
public void testDisplay()
{
}
@Test
public void testEarlyNotes()
{
/*for (int i=0; i<10; i++)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
}
af.handleProcessedNoteEvent(new ProcessedNoteEvent(new NoteEvent(null,null,System.currentTimeMillis()+100),new MidiEvent(60,100,null),false));
}*/
}
@After
public void confirm()
{
JOptionPane.showMessageDialog(null,"Press ok to proceed");
af.setVisible(false);
}
}
|
package com.noturaun.posapp.repository;
import com.noturaun.posapp.entity.Customer;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static com.noturaun.posapp.util.Helper.isExist;
public class CustomerRepositoryImpl implements CustomerRepository{
private HikariDataSource dataSource;
private String sql;
public CustomerRepositoryImpl(HikariDataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Customer[] getAll() {
sql = "SELECT * FROM customers;";
try(Connection connection = dataSource.getConnection()){
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql);
List<Customer> customers = new ArrayList<>();
while (result.next()){
Customer customer = new Customer();
customer.setId(result.getInt("id"));
customer.setFirstName(result.getString("firstName"));
customer.setLastName(result.getString("lastName"));
customer.setAddress(result.getString("address"));
customers.add(customer);
}
return customers.toArray(new Customer[]{});
} catch (SQLException exception) {
throw new RuntimeException(exception.getMessage());
}
}
@Override
public Customer get(Integer customerId) {
sql = "SELECT * FROM customers where id = ?;";
try(Connection connection = dataSource.getConnection()){
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,customerId);
ResultSet result = statement.executeQuery();
Customer customer = new Customer();
while (result.next()){
customer.setId(result.getInt("id"));
customer.setFirstName(result.getString("firstName"));
customer.setLastName(result.getString("lastName"));
customer.setAddress(result.getString("address"));
}
return customer;
} catch (SQLException exception) {
throw new RuntimeException(exception.getMessage());
}
}
@Override
public void create(Customer customer) {
sql = "INSERT INTO customers(firstName, lastName, address) values(?,?,?);";
try(Connection connection = dataSource.getConnection()) {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, customer.getFirstName());
statement.setString(2, customer.getLastName());
statement.setString(3, customer.getAddress());
statement.executeUpdate();
} catch (SQLException e){
throw new RuntimeException(e.getMessage());
}
}
@Override
public void update(Integer customerId, Customer changes) {
sql = """
UPDATE customers
SET firstName = ?,
lastName = ?,
address = ?
WHERE id = ? ;
""";
try(Connection connection = dataSource.getConnection()) {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, changes.getFirstName());
statement.setString(2, changes.getLastName());
statement.setString(3, changes.getAddress());
statement.setInt(4, customerId);
statement.executeUpdate();
} catch (SQLException e){
throw new RuntimeException(e.getMessage());
}
}
@Override
public boolean delete(Integer customerId) {
String table = "customers";
String clause = "id";
if (isExist(dataSource, customerId, table, clause)){
sql = " DELETE FROM " + table +" WHERE id = ? ;";
try(Connection connection = dataSource.getConnection()) {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, customerId);
statement.executeUpdate();
} catch (SQLException e){
throw new RuntimeException(e.getMessage());
}
return true;
} else {
return false;
}
}
}
|
package com.beike.model.lucene;
import java.util.List;
import org.apache.lucene.document.Document;
/**
* 查询结果
* @author ye.tian
*
*/
public class QueryResult {
private int recordCount; //记录总数
private List<Document> recordList; //搜索记录列表
private List<QueryParam> queryParamList;//查询结果参数
public List<QueryParam> getQueryParamList() {
return queryParamList;
}
public void setQueryParamList(List<QueryParam> queryParamList) {
this.queryParamList = queryParamList;
}
public QueryResult(int recordCount, List<Document> recordList) {
}
public int getRecordCount() {
return recordCount;
}
public void setRecordCount(int recordCount) {
this.recordCount = recordCount;
}
public List<Document> getRecordList() {
return recordList;
}
public void setRecordList(List<Document> recordList) {
this.recordList = recordList;
}
}
|
package com.example.selenge;
import java.util.ArrayList;
import com.example.selenge.adapter.InfoListViewAdapter;
import com.example.selenge.model.InfoModel;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InfoFragment extends Fragment {
private ListView infoLv;
private InfoListViewAdapter infoLvAdapter;
private ProgressBar progressBar;
private ArrayList<InfoModel> infoList = null;
private int visibleThreshold = 10;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_info, container, false);
if (!MainActivity.isNetworkAvailable(getActivity())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.no_network_connection_title);
builder.setMessage(R.string.no_network_connection_message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
return rootView;
}
progressBar = (ProgressBar) rootView.findViewById(R.id.progressbar1);
this.infoList = new ArrayList<InfoModel>();
this.infoLv = (ListView) rootView.findViewById(R.id.infoLv);
new JSONInfoTask().execute(currentPage);
this.infoLvAdapter = new InfoListViewAdapter(getActivity(), infoList);
this.infoLv.setAdapter((ListAdapter) infoLvAdapter);
this.infoLv.invalidate();
this.infoLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), InfoDetailActivity.class);
intent.putExtra("url", infoList.get(position).getUrl());
startActivity(intent);
}
});
this.infoLv.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage ++;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
new JSONInfoTask().execute(currentPage + 1);
loading = true;
}
}
});
return rootView;
}
private class JSONInfoTask extends AsyncTask<Integer, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Integer... params) {
String jsonData = ( (new SelengeMobileHttpClient()).getInfoData(Integer.valueOf(params[0])));
if (jsonData != null) {
try {
JSONArray info = new JSONArray(jsonData);
for (int i = 0; i < info.length(); i ++) {
JSONObject c = info.getJSONObject(i);
String title = c.getString("title");
String image = c.getString("thumb_image");
String description = c.getString("description_text");
String date = c.getString("date");
String url = c.getString("url");
InfoModel infoModel = new InfoModel(title, image, description, date, url);
infoList.add(infoModel);
infoLvAdapter.add(infoModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
infoLvAdapter.notifyDataSetChanged();
}
}
}
|
package com.easytoolsoft.commons.lang.tree;
import java.util.ArrayList;
import java.util.List;
/**
* dhtmxTree(http://dhtmlx.com/docs/products/dhtmlxTree/)控件的树结点数据模型类
* http://docs.dhtmlx.com/tree__syntax_templates.html#jsonformattemplate
*
* @author zhiwei.deng
*/
public class DhtmlXTreeNode {
private final List<DhtmlXTreeNode> item;
private String id;
private String pid;
private String text;
private String tooltip;
private int checked;
private int child = 0;
private int open;
private int sequence = 10;
public DhtmlXTreeNode() {
this.item = new ArrayList<>(10);
}
public String getId() {
return this.id;
}
public void setId(final String id) {
this.id = id;
}
public String getPid() {
return this.pid;
}
public void setPid(final String pid) {
this.pid = pid;
}
public String getText() {
return this.text;
}
public void setText(final String text) {
this.text = text;
}
public String getTooltip() {
return this.tooltip;
}
public void setTooltip(final String tooltip) {
this.tooltip = tooltip;
}
public int getChecked() {
return this.checked;
}
public void setChecked(final int checked) {
this.checked = checked;
}
public int getChild() {
return this.child;
}
public void setChild(final int child) {
this.child = child;
}
public int getOpen() {
return this.open;
}
public void setOpen(final int open) {
this.open = open;
}
public int getSequence() {
return this.sequence;
}
public void setSequence(final int sequence) {
this.sequence = sequence;
}
public List<DhtmlXTreeNode> getItem() {
return this.item;
}
}
|
package collections.demo;
public class VecSalary {
VecEmploye emp;
double salary;
public VecEmploye getEmp() {
return emp;
}
public void setEmp(VecEmploye emp) {
this.emp = emp;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
|
package com.lmz.javabase;
public class While {
public static void main(String[] args) {
//循环语句就是让计算机根据条件做循环计算,在条件满足时继续循环,条件不满足时退出循环。
//while循环在每次循环开始前,首先判断条件是否成立。如果计算结果为true,就把循环体内的语句执行一遍,如果计算结果为false,那就直接跳到while循环的末尾,继续往下执行。
//注意到while循环是先判断循环条件,再循环,因此,有可能一次循环都不做。
int sum = 0;
int m = 20;
int n = 100;
// 使用while计算M+...+N:
while (m<=n){
sum+=m;
m++;
}
System.out.println("M+...+N:"+sum);
}
}
|
package org.lfy.admin;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* AdminApplication
* ① : @EnableAdminServer,开启监控
*
* @author lfy
* @date 2021/3/20
**/
@Slf4j
@EnableAdminServer
@EnableEurekaClient
@SpringBootApplication
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class);
log.info("AdminApplication start successfully...");
}
}
|
public class Solution {
public String compress(String input) {
// Write your solution here
if (input == null || input.length() == 0) {
return input;
}
char[] array = input.toCharArray();
int slow = 0;
int fast = 0;
int globalCounter = 0;
while (fast + 1 < array.length) {
if (array[fast] != array[fast + 1]) {
globalCounter++;
array[slow] = array[fast];
slow++;
fast++;
} else if (array[fast] == array[fast + 1]) {
array[slow] = array[fast];
slow++;
int counter = 1;
while (fast + 1 < array.length && array[fast] == array[fast + 1]) {
counter++;
fast++;
}
String count = String.valueOf(counter); // 处理连续字母字母数量大于9的情况
for (int i = 0; i < count.length(); i++) {
array[slow++] = count.charAt(i);
}
fast++;
}
}
// 明确slow的物理意义:slow左边是处理过的字母
// post process:因为上面可能没有遍历到原字符串最后一个字母
if (fast <= 1 || (fast < input.length() && input.charAt(fast) != input.charAt(fast - 1))) {
globalCounter++; // edge case: len(input) = 1;
array[slow] = array[fast];
slow++;
}
char[] result = new char[slow + globalCounter];
fast = slow - 1;
slow = result.length - 1;
while (fast >= 0) {
if (fast > 0 && Character.isDigit(array[fast]) && Character.isDigit(array[fast - 1])) {
result[slow--] = array[fast--];
} else if (Character.isDigit(array[fast])) {
result[slow--] = array[fast--];
result[slow--] = array[fast--];
} else {
result[slow--] = (char) '0' + 1;
result[slow--] = array[fast--];
}
}
return new String(result);
}
}
// Time: O(n) -- did not consider the time consuming on assign counter number in
// case that counter > 9
// Space: O(1) -- did not consider the space of new arranged char array; |
package com.ssa.startmeetingwidget.screens;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ssa.startmeetingwidget.R;
import com.ssa.startmeetingwidget.common.BasePermissionActivity;
import com.ssa.startmeetingwidget.screens.contacts.ContactsActivity;
import com.ssa.startmeetingwidget.widget.EmailViewWithPopup;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends BasePermissionActivity {
private final static int REQUEST_CONTACT_CODE = 101;
@BindView(R.id.email_view)
EmailViewWithPopup mEmailView;
@BindView(R.id.email_list)
ListView mEmailList;
ArrayAdapter<String> mAdapter;
@Override
protected String[] getDesiredPermissions() {
return new String[] {Manifest.permission.READ_CONTACTS};
}
@Override
protected void onPermissionDenied() {}
@Override
protected void onPermissionGranted() {}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mEmailView.setOnClickFindUser(view -> startActivityForResult(ContactsActivity.createIntent(MainActivity.this), REQUEST_CONTACT_CODE));
}
@OnClick(R.id.get_valid_emails_button)
void onClickGetValidEmails() {
mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mEmailView.getValidEmails());
mEmailList.setAdapter(mAdapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case REQUEST_CONTACT_CODE: {
String email = data.getStringExtra(ContactsActivity.EXTRA_EMAIL);
mEmailView.appendEmail(email);
break;
}
}
}
}
|
package settings;
public class Settings {
public static String username="kamrul1157024";
public static String password="falsepassword";
public static String gitFolderLink="/home/kamrul/Desktop/kamrul1157024.github.io/";
public static String code_adding_path="Solutions/";
public static String html_search_path="Solution_Searcher/";
public static String faebook_id="https://www.facebook.com/kamrul1157024";
public static String name="kamrul";
public static String githublink="http://kamrul1157024.github.io/";
public static String files="/home/kamrul/Desktop/kamrul1157024.github.io/files/";
public Settings()
{
Information information=new SaveSettings().getInformation();
username=information.getUsername();
password=information.getPassword();
gitFolderLink=information.getGitfolder();
code_adding_path=information.getCode_adding_path();
html_search_path=information.getHtml_search_path();
faebook_id=information.getFaebook_id();
name=information.getName();
githublink=information.getGitHub_link();
}
@Override
public void finalize()
{
Information information=new Information();
information.setCode_adding_path(code_adding_path);
information.setFaebook_id(faebook_id);
information.setGitfolder(gitFolderLink);
information.setHtml_search_path(html_search_path);
information.setUsername(username);
information.setPassword(password);
information.setName(name);
information.setGitHub_link(githublink);
information.setFiles(files);
new SaveSettings().saveInformations(information);
System.out.println("Settings saved");
}
}
|
package revolt.backend.dto;
import lombok.*;
import lombok.experimental.FieldDefaults;
import java.util.List;
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class BrandDto {
Long id;
String name;
List<Long> accessoriesIds;
List<Long> batteryIds;
List<Long> boxmodIds;
List<Long> chargerIds;
List<Long> complectsIds;
List<Long> componentsIds;
List<Long> consumablesIds;
List<Long> liquidIds;
List<Long> mechmodIds;
List<Long> rdaIds;
List<Long> rdtaIds;
List<Long> rtaIds;
}
|
package com.syntax.class06;
import java.util.Scanner;
public class LargestNuber1 {
public static void main(String[] args) {
;
Scanner input;
int number1;
int number2;
int number3;
int max;
System.out.println("Please enter three different numbers:");
input = new Scanner(System.in);
number1 = input.nextInt();
number2 = input.nextInt();
number3 = input.nextInt();
if (number1 > number2) {
if (number1>number3) {
max = number1;
}else {
max = number3;
}
}else{//number 2 is larger than number 1
if (number2>number3) {
max = number2;
}else {
max = number3;
}
}
System.out.println("The largest number is " + max);
}
}
// with Nested If
/*
* Write a program to find largest number among three numbers using nested if
* provided by a user (numbers must be distinct)
*
* better with Logical Operators
*/
|
package br.com.poli.application;
import br.com.poli.repositorio.Repositorio;
import br.com.poli.view.Layout;
import br.com.poli.view.Tela;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
public class PuzzleN extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/br/com/poli/view/Menu.fxml"));
Tela tela = new Tela();
Repositorio r = new Repositorio();
AnchorPane fundo = tela.gerarTela(Layout.gameLayout(r.getLayout()), root);
Scene scene = new Scene(fundo);
primaryStage.setTitle("Puzzle-N");
primaryStage.getIcons().add(new Image("/br/com/poli/resources/a-void.png"));
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.sizeToScene();
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.soldevelo.vmi.logging.utils;
import com.soldevelo.vmi.logging.entities.Location;
import com.soldevelo.vmi.logging.entities.Request;
import com.soldevelo.vmi.packets.TestLocation;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class LocationManager {
private static final Logger LOG = LoggerFactory.getLogger(ResultManager.class);
private HibernateUtil util;
@Autowired
public LocationManager(HibernateUtil util) {
this.util = util;
}
public Location saveLocation(TestLocation locationPacket, Request request) {
if (util.isSqlLiteDialect()) {
synchronized (util.getSqlLiteLock()) {
return saveLocationImpl(locationPacket, request);
}
} else {
return saveLocationImpl(locationPacket, request);
}
}
private Location saveLocationImpl(TestLocation locationPacket, Request request) {
Session session = util.getSessionFactory().getCurrentSession();
session.beginTransaction();
Location location = new Location();
location.setDownstreamSpeedTier(locationPacket.getDownstreamSpeedTier());
location.setUpstreamSpeedTier(locationPacket.getUpstreamSpeedTier());
location.setBhrMACAddress(locationPacket.getBhrMACAddress());
location.setBhrIpAddress(locationPacket.getBhrIPAddress());
location.setDeviceSerialNumber(locationPacket.getDeviceSerialNumber());
location.setLataId(locationPacket.getLataId());
location.setGwrId(locationPacket.getGwrId());
location.setOltId(locationPacket.getOltId());
location.setOntModel(locationPacket.getOntModel());
location.setRequest(request);
session.save(location);
session.getTransaction().commit();
LOG.debug("Saved test location for test with id " + request.getId());
return location;
}
public Location findLocation(String address) {
if (util.isSqlLiteDialect()) {
synchronized (util.getSqlLiteLock()) {
return findLocationImpl(address);
}
} else {
return findLocationImpl(address);
}
}
private Location findLocationImpl(String address) {
Session session = util.getSessionFactory().getCurrentSession();
session.beginTransaction();
Location location = findLocation(session, address);
session.getTransaction().commit();
return location;
}
private Location findLocation(Session session, String address) {
Query query = session
.createQuery("from com.soldevelo.vmi.logging.entities.Location l where l.bhrIpAddress = :address order by l.id desc");
query.setMaxResults(1);
query.setString("address", address);
return (Location) query.uniqueResult();
}
}
|
package evolutionYoutube;
import com.vaadin.navigator.View;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.UI;
import database.BD_general;
public class Recordar_Contrasenia extends Recordar_Contrasenia_ventana implements View {
/**
*
*/
private static final long serialVersionUID = 1L;
public Iniciar_Sesion _unnamed_Iniciar_Sesion_;
//public Enviar_Correo_Electronico _unnamed_Enviar_Correo_Electronico_;
public Recordar_Contrasenia() {
recuperar.addClickListener(new Button.ClickListener(){
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
recuperar_contrasenia();
}
});
cancelar.addClickListener(new Button.ClickListener(){
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
cancelar();
}
});
}
public void cancelar() {
((MyUI) UI.getCurrent()).iniciar_sesion();
}
public void recuperar_contrasenia() {
BD_general bd = new BD_general();
bd.recuperar_contrasenia(correo.getValue());
((MyUI) UI.getCurrent()).iniciar_sesion();
}
} |
package top.docstorm.documentstormcommon.service.impl;
import lombok.Cleanup;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.docstorm.documentstormcommon.service.AbstractTransService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* @Description: PDF转Word<p>
* @author: passer<p>
* @version:2019年5月19日 下午9:46:12<p>
*/
@Service("pdfToWordService")
public class PDFToWordService extends AbstractTransService {
private static final Logger LOGGER = LoggerFactory.getLogger(PDFToWordService.class);
/**
*
* <p>Description: PDF -- > DOC 文件转换 </p>
* @param srcPath 文件绝对路径名 </p>
* @return 返回修改之后文件的绝对路径 </p>
*/
private boolean transToWord(String srcPath, String destPath) {
try {
@Cleanup
PDDocument doc = PDDocument.load(new File(srcPath));
// 获取总页数
int pagenumber = doc.getNumberOfPages();
@Cleanup
FileOutputStream fos = new FileOutputStream(destPath);
@Cleanup
Writer writer = new OutputStreamWriter(fos, "UTF-8");// 文件按字节读取,然后按照UTF-8的格式编码显示
PDFTextStripper stripper = new PDFTextStripper();
// 排序
stripper.setSortByPosition(true);
// 设置转换的开始页
stripper.setStartPage(1);
// 设置转换的结束页
stripper.setEndPage(pagenumber);
stripper.writeText(doc, writer);
return true;
} catch (Exception e) {
LOGGER.error(String.format("srcPath: {}, destPath: {}, errorMsg: {}", srcPath, destPath, e.getMessage()));
return false;
}
}
@Override
public boolean transCore(String srcPath, String destPath) {
return transToWord(srcPath, destPath);
}
}
|
package com.git.cloud.resmgt.compute.model.vo;
public class CloudServiceVoByRmHost {
private String cloudServiceName;
private String cloudServiceId;
public String getCloudServiceName() {
return cloudServiceName;
}
public void setCloudServiceName(String cloudServiceName) {
this.cloudServiceName = cloudServiceName;
}
public String getCloudServiceId() {
return cloudServiceId;
}
public void setCloudServiceId(String cloudServiceId) {
this.cloudServiceId = cloudServiceId;
}
}
|
package com.lenovohit.ssm.treat.model;
/**
* 预存记录
*
*/
public class DepositRecord {
private String requestNo; //请求流水号
private String cardNo; //卡号
private String paymentWay; //支付类型
private String outTradeNo; //订单号
private String amount; //金额
private String userId; //用户id
private String paymentTime; //交易时间/预存时间 Yyyy-mm-dd hh24:mi:ss
private String patientNo; //病人编号
private String tradeType; //交易类型 充值,退款
private String balance; //预存余额 2位小数
private String serialNumber;//HIS预存交易流水号 10位
private String status ; //预存记录(充值,退款)状态 0为受理中,1为成功
public String getRequestNo() {
return requestNo;
}
public void setRequestNo(String requestNo) {
this.requestNo = requestNo;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getPaymentWay() {
return paymentWay;
}
public void setPaymentWay(String paymentWay) {
this.paymentWay = paymentWay;
}
public String getOutTradeNo() {
return outTradeNo;
}
public void setOutTradeNo(String outTradeNo) {
this.outTradeNo = outTradeNo;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPaymentTime() {
return paymentTime;
}
public void setPaymentTime(String paymentTime) {
this.paymentTime = paymentTime;
}
public String getPatientNo() {
return patientNo;
}
public void setPatientNo(String patientNo) {
this.patientNo = patientNo;
}
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getTradeType() {
return tradeType;
}
public void setTradeType(String tradeType) {
this.tradeType = tradeType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package controller.member.sell;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import model.Menu_DTO;
import model.Sell_DTO;
public class Member_Sell_DAO extends SqlSessionDaoSupport {
public List<Menu_DTO> getMenuList() {
List<Menu_DTO> mlist= getSqlSession().selectList("member_sell.menu_all");
return mlist;
}
public int sell_exe(ArrayList<Sell_DTO> sell_list) { //주문정보가 있을 때만 호출됨
int x = 0;
for(int i=0;i<sell_list.size();i++) {
x+=getSqlSession().insert("member_sell.sell_exe",sell_list.get(i));
if(x==0)
return x;
}
return x;
}
public boolean stock_confirm(int[] m_no,int[] m_count, int s_no) {//메뉴,수량,지점번호
ArrayList need_stock = new ArrayList(); //실제 필요한 양
for(int i=0;i<m_no.length;i++) { //레시피 구해옴
String m_recipe = getSqlSession().selectOne("member_sell.recipe_confirm",m_no[i]);
String[] split_receipe = m_recipe.split(",");//[원두 | 20 | 우유 | 200]
HashMap<String,Integer> map = new HashMap<String,Integer>();
for(int j=0;j<split_receipe.length;j=j+2) {
int need_sell = Integer.parseInt(split_receipe[j+1])*m_count[i]; //레시피*주문수량 => 판매에 필요한 재고 갯수
HashMap sno_stname = new HashMap();
sno_stname.put("s_no", s_no);
sno_stname.put("st_name", split_receipe[j]);
sno_stname.put("need_sell", need_sell);
String exist = getSqlSession().selectOne("member_sell.exist_stock",sno_stname);
if(exist==null) //재고에 해당 물품이 없는경우
return false; //판매불가
int stock_count = getSqlSession().selectOne("member_sell.get_stock",sno_stname); //매장에 존재하는 재고의 갯수
if(stock_count<need_sell) { //재고의 갯수가 실제 필요한 양보다 적다면 재고부족!
return false; // 판매불가
}
need_stock.add(sno_stname);
}
System.out.println(m_recipe+"수량:"+m_count[i]);
}
//문제가 없으면 판매가능 -> 재고에서 물품 빼기
for(int i=0;i<need_stock.size();i++) { //필요한 정보들
int x =getSqlSession().update("member_sell.use_stock",need_stock.get(i));
if(x!=1) {
return false;
}
}
return true;
}
public boolean stock_confirm(int m_no,int m_count, int s_no) {
String m_recipe = getSqlSession().selectOne("member_sell.recipe_confirm",m_no);
String[] split_receipe = m_recipe.split(",");
HashMap<String,Integer> map = new HashMap<String,Integer>();
for(int j=0;j<split_receipe.length;j=j+2) {
//map.put(split_receipe[j], Integer.parseInt(split_receipe[j+1])*m_count[i]);
int need_sell = Integer.parseInt(split_receipe[j+1])*m_count; //판매에 필요한 재고 갯수
HashMap sno_stname = new HashMap();
sno_stname.put("s_no", s_no);
sno_stname.put("st_name", split_receipe[j]);
sno_stname.put("need_sell", need_sell);
String exist = getSqlSession().selectOne("member_sell.exist_stock",sno_stname);
if(exist==null) //재고에 해당 물품이 없는경우
return false; //판매불가
int stock_count = getSqlSession().selectOne("member_sell.get_stock",sno_stname); //매장에 존재하는 재고의 갯수
if(stock_count<need_sell) { //재고의 갯수가 실제 필요한 양보다 적다면 재고부족!
return false; // 판매불가
}
}
//문제가 없으면 판매가능
return true;
}
}
|
package org.apache.commons.dbcp;
import com.alibaba.druid.pool.DruidDataSourceMBean;
public interface BasicDataSourceMBean extends DruidDataSourceMBean {
}
|
/* Test 54:
*
* Istruzione continue.
*/
package gimnasium;
class s1 {
void pippo()
{
double i,j;
boolean t;
int a;
for (;;)
if (i>j)
continue;
while (i>j)
{
if (t)
continue;
}
do {
if (t)
continue;
} while (i>j);
continue; // errore!!! continue deve stare in un loop.
switch (a)
{
case 10:
continue; // errore!!! continue deve stare in un loop.
case 11:
continue; // errore!!! continue deve stare in un loop.
}
/*
* L'introduzione nello switch di label costanti e' possibile solo
* quando il Constant Folding e' completo al 100 %
*/
}
}
|
package br.com.gestor.database.modelo;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Dev extends Usuario implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1841117084413632239L;
@ManyToOne
@JoinColumn(nullable = true, name = "id_equipe")
private Equipe equipe;
public Equipe getEquipe() {
return equipe;
}
public void setEquipe(Equipe equipe) {
this.equipe = equipe;
}
@Override
public String toString() {
return this.login.toString();
}
}
|
package com.bogdanovpd.spring.webapp.spring.webapp.client.config;
import com.bogdanovpd.spring.webapp.spring.webapp.client.model.User;
import com.bogdanovpd.spring.webapp.spring.webapp.client.service.RoleRestService;
import com.bogdanovpd.spring.webapp.spring.webapp.client.service.UserRestService;
import com.bogdanovpd.spring.webapp.spring.webapp.client.util.OAuth2UserAuthentificationSuccessHandler;
import com.bogdanovpd.spring.webapp.spring.webapp.client.util.UserAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.Filter;
import java.security.Principal;
@EnableWebSecurity
@Configuration
@EnableOAuth2Client
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Autowired
private OAuth2ClientContext oauth2ClientContext;
@Autowired
private UserRestService userRestService;
@Autowired
private RoleRestService roleRestService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter googleFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/google");
OAuth2RestTemplate googleTemplate = new OAuth2RestTemplate(google(), oauth2ClientContext);
googleFilter.setRestTemplate(googleTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(googleResource().getUserInfoUri(), google().getClientId());
tokenServices.setRestTemplate(googleTemplate);
googleFilter.setTokenServices(tokenServices);
googleFilter.setAuthenticationSuccessHandler(new OAuth2UserAuthentificationSuccessHandler(userRestService, roleRestService));
return googleFilter;
}
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
return new OAuth2RestTemplate(resource, context);
}
@Bean
@ConfigurationProperties("google.client")
public AuthorizationCodeResourceDetails google() {
return new AuthorizationCodeResourceDetails();
}
@Bean
@ConfigurationProperties("google.resource")
public ResourceServerProperties googleResource() {
return new ResourceServerProperties();
}
@Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(
OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/login**").permitAll()
.antMatchers("/user**").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
.antMatchers("/admin**").hasAuthority("ROLE_ADMIN")
.and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class)
.formLogin().loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("login")
.passwordParameter("pass")
.successHandler(new UserAuthenticationSuccessHandler())
.and()
.logout().logoutSuccessUrl("/login")
.and()
.csrf().disable();
}
}
|
package asset_code;
public class VerticalShot {
}
|
package com.caiyi.ui;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build.VERSION;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Scroller;
import com.caiyi.interfaces.ITrendChart;
public class LottoTrendView extends View implements OnDoubleTapListener, OnGestureListener, OnTouchListener {
private ITrendChart mChart;
private GestureDetector mGestureDetector;
private float mLastDistance;
final int mMinDistance;
private float mNowX;
private float mNowY;
final int mPosition3;
private float mScale;
private Scroller mScroller;
public LottoTrendView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.mMinDistance = 10;
this.mNowX = 0.0f;
this.mNowY = 0.0f;
this.mScale = 1.0f;
this.mLastDistance = 0.0f;
this.mPosition3 = 3;
initView();
}
public LottoTrendView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public LottoTrendView(Context context) {
this(context, null, 0);
}
public void setChart(ITrendChart iTrendChart) {
this.mChart = iTrendChart;
}
public void setNowX(float f) {
this.mNowX = f;
refreshPos();
}
public void setNowY(float f) {
this.mNowY = f;
refreshPos();
}
public void setScale(float f) {
this.mScale = f;
if (this.mChart != null && this.mChart.getCanScale()) {
float[] scaleRange = this.mChart.getScaleRange();
this.mScale = Math.max(scaleRange[0], Math.min(this.mScale, scaleRange[1]));
}
refreshPos();
}
public float getScale() {
return this.mScale;
}
/**
* 设置是否硬件加速
* @param view
* @param z
*/
@SuppressLint({"NewApi"})
public static void setHardwareAccelerated(View view, boolean z) {
if (VERSION.SDK_INT < 11) {
return;
}
if (z) {
view.setLayerType(2, null);
} else {
view.setLayerType(1, null);
}
}
private void initView() {
this.mGestureDetector = new GestureDetector(getContext(), this);
this.mGestureDetector.setOnDoubleTapListener(this);
this.mScroller = new Scroller(getContext());
setOnTouchListener(this);
}
public boolean performClick() {
return super.performClick();
}
protected void onSizeChanged(int i, int i2, int i3, int i4) {
if (this.mChart != null) {
this.mChart.initChart(getContext(), i, i2, this.mScale);
}
super.onSizeChanged(i, i2, i3, i4);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (this.mChart != null ) {
if (this.mScroller.computeScrollOffset()) {
boolean[] canScroll = this.mChart.getCanScroll();
if (canScroll[0]) {
this.mNowX = (float) this.mScroller.getCurrX();
}
if (canScroll[1]) {
this.mNowY = (float) this.mScroller.getCurrY();
}
postInvalidate();
}
this.mChart.draw(canvas, (int) this.mNowX, (int) this.mNowY, getWidth(), getHeight(), this.mScale);
}
}
public boolean onTouch(View view, MotionEvent motionEvent) {
if (this.mChart == null ) {
return false;
}
if (this.mChart.getCanScale() && motionEvent.getPointerCount() == 2 && motionEvent.getAction() == 2) {
float x = motionEvent.getX(0) - motionEvent.getX(1);
float y = motionEvent.getY(0) - motionEvent.getY(1);
x = (float) Math.sqrt((double) ((x * x) + (y * y)));
if (this.mLastDistance == 0.0f) {
this.mLastDistance = x;
return true;
} else if (Math.abs(x - this.mLastDistance) <= 10) {
return true;
} else {
float[] scaleRange = this.mChart.getScaleRange();
this.mScale=1.0f;
//去掉放大
// this.mScale = Math.max(scaleRange[0], Math.min((this.mScale * x) / this.mLastDistance, scaleRange[1]));
this.mLastDistance = x;
refreshPos();
return true;
}
}
if (motionEvent.getPointerCount() < 2) {
this.mLastDistance = 0.0f;
}
return this.mGestureDetector.onTouchEvent(motionEvent);
}
public boolean onDown(MotionEvent motionEvent) {
if (!this.mScroller.isFinished()) {
this.mScroller.forceFinished(true);
}
this.mLastDistance = 0.0f;
return true;
}
public void onShowPress(MotionEvent motionEvent) {
}
public boolean onSingleTapUp(MotionEvent motionEvent) {
if (!this.mChart.onClick(motionEvent, this.mNowX, this.mNowY, getWidth(), getHeight(), this.mScale)) {
return false;
}
invalidate();
return true;
}
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) {
boolean[] canScroll = this.mChart.getCanScroll();
if (!canScroll[0] && !canScroll[1]) {
return false;
}
int[] scrollRange = this.mChart.getScrollRange();
if (canScroll[0]) {
this.mNowX -= f;
this.mNowX = Math.max((float) scrollRange[0], Math.min(this.mNowX, (float) scrollRange[1]));
}
if (canScroll[1]) {
this.mNowY -= f2;
this.mNowY = Math.max((float) scrollRange[2], Math.min(this.mNowY, (float) scrollRange[3]));
}
invalidate();
return true;
}
public void onLongPress(MotionEvent motionEvent) {
if (this.mChart.onLongClick(motionEvent, this.mNowX, this.mNowY, getWidth(), getHeight(), this.mScale)) {
invalidate();
}
}
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) {
this.mScroller.forceFinished(true);
int[] scrollRange = this.mChart.getScrollRange();
this.mScroller.fling((int) this.mNowX, (int) this.mNowY, (int) f, (int) f2, scrollRange[0], scrollRange[1], scrollRange[2], scrollRange[3]);
return true;
}
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
return false;
}
public boolean onDoubleTap(MotionEvent motionEvent) {
this.mScale = 1.0f;
refreshPos();
return false;
}
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
return false;
}
public void refreshPos() {
this.mScroller.forceFinished(true);
if (this.mChart != null) {
this.mChart.reCalcScroll(this.mScale, getWidth(), getHeight());
int[] scrollRange = this.mChart.getScrollRange();
this.mNowX = Math.min((float) scrollRange[1], Math.max((float) scrollRange[0], this.mNowX));
this.mNowY = Math.min((float) scrollRange[3], Math.max((float) scrollRange[2], this.mNowY));
invalidate();
}
}
}
|
import java.util.Scanner;
/**
* @author joshua.s.george@stonybrook.edu
* ID: 112839378
* <p>
* This class acts as main method for executing the terminal
*/
public class BashTerminal {
/**
* This is the main method of the class. Runs the Bash Terminal
* @param args Command line args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
DirectoryTree tree = new DirectoryTree();
System.out.println("Starting bash terminal.");
String selection = "";
while (!selection.equalsIgnoreCase("exit")) {
try {
System.out.print("[jsgeorge@cortana] : $ ");
selection = scan.nextLine();
if (selection.equalsIgnoreCase("pwd")) {
System.out.println("root/");
} else if (selection.contains("ls")) {
if (selection.contains("-R") || selection.contains("-r")) {
tree.printDirectoryTree(tree.getCursor(), 0);
} else
System.out.println(tree.listDirectory());
} else if (selection.contains("cd ")) {
String[] values = selection.split(" ");
if (values[1].equalsIgnoreCase("/"))
tree.resetCursor();
else {
tree.changeDirectory(values[1]);
}
} else if (selection.contains("mkdir")) {
String[] values = selection.split(" ");
tree.makeDirectory(values[1]);
} else if (selection.contains("touch ")) {
String[] values = selection.split(" ");
tree.makeFile(values[1]);
} else if (selection.equalsIgnoreCase("exit")) {
System.out.println("Closing bash terminal...");
} else {
System.out.println("Error: Command not found");
}
} catch (NotADirectoryException e) {
System.out.println(e);
} catch (FullDirectoryException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println("Error: Please enter a valid input");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.