repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
victoralvesabreu/ImobiliariaMarvi | src/domain/Usuario.java | 2203 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
/**
*
* @author victor alves abreu
*/
public class Usuario {
public static Usuario logado;
private int id;
private String nome;
private String email;
private String senha;
private String Acesso;
private String cpf;
private String cargo;
public String getAcesso() {
return Acesso;
}
public void setAcesso(String Acesso) throws Exception {
if (!Acesso.isEmpty()) {
this.Acesso = Acesso;
} else {
throw new Exception("o campo acesso precisa ser preenchido!");
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) throws Exception {
if (!nome.isEmpty()) {
this.nome = nome;
} else {
throw new Exception("Nome Invalido!");
}
}
public String getEmail() {
return email;
}
public void setEmail(String email) throws Exception {
if (email.contains("@")) {
this.email = email;
} else {
throw new Exception("email invalido!");
}
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
if (!senha.isEmpty()) {
this.senha = senha;
}else{
throw new IllegalArgumentException("Senha Invalida");
}
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) throws Exception {
if (!cpf.isEmpty()) {
this.cpf = cpf;
} else {
throw new Exception("Cpf Invalido!");
}
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) throws Exception {
if (!cargo.isEmpty()) {
this.cargo = cargo;
} else {
throw new Exception("Cargo invalido!");
}
}
}
| mit |
Crazzi-Boii/Tic-Tac-Toe | src/tictactoe/PlayerDetails.java | 23101 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tictactoe;
/**
*
* @author Crazzi_Boii
*/
public class PlayerDetails extends javax.swing.JFrame {
public static String P1,P2;
public static String Pt1,Pt2;
/**
* Creates new form PlayerDetails
*/
public PlayerDetails() {
initComponents();
this.setLocation(350, 130);
//System.out.println("hi");
//System.out.println(a);
jLPlayer1.setVisible(false);
jLPlayer2.setVisible(false);
if(a>0){
jB_start.setVisible(false);
jB_rsm.setVisible(true);
jLabel5.setText(P1);
jLabel6.setText(P2);
jLabel5.setVisible(true);
jLabel6.setVisible(true);
}else{
jB_rsm.setVisible(false);
jLabel5.setVisible(false);
jLabel6.setVisible(false);
}
}
/**
* 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() {
jSpinner1 = new javax.swing.JSpinner();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLPlayer1 = new javax.swing.JLabel();
jLPlayer2 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jTFp2 = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTFp1 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jB_start = new javax.swing.JButton();
jB_rsm = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Tic Tac Toe");
setBackground(new java.awt.Color(255, 255, 255));
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.darkGray, java.awt.Color.lightGray, java.awt.Color.darkGray, java.awt.Color.lightGray), javax.swing.BorderFactory.createTitledBorder(null, "Tic Tac toe", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Times New Roman", 1, 18)))); // NOI18N
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 204, 204));
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("Enter Players Details");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 0, 0));
jLabel4.setText("I hope you will enjoy the game . . ! !");
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jLPlayer1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLPlayer1.setForeground(new java.awt.Color(255, 51, 51));
jLPlayer1.setText("Player 1 ,Please enter your name . .");
jLPlayer2.setBackground(new java.awt.Color(255, 255, 255));
jLPlayer2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLPlayer2.setForeground(new java.awt.Color(255, 51, 51));
jLPlayer2.setText("Player 2 ,Please enter your name . .");
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLPlayer1, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLPlayer2, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLPlayer1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLPlayer2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE))
);
jPanel6.setBackground(null);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setText("Player 2 Name :");
jTFp2.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jTFp2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTFp2ActionPerformed(evt);
}
});
jLabel6.setBackground(new java.awt.Color(255, 255, 255));
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText("jLabel6");
jLabel6.setIconTextGap(2);
jLabel6.setOpaque(true);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTFp2, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTFp2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel7.setBackground(null);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setText("Player 1 Name :");
jTFp1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jTFp1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTFp1ActionPerformed(evt);
}
});
jLabel5.setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("jLabel5");
jLabel5.setIconTextGap(2);
jLabel5.setOpaque(true);
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTFp1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTFp1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))
);
jB_start.setBackground(new java.awt.Color(153, 153, 153));
jB_start.setFont(new java.awt.Font("Trebuchet MS", 0, 20)); // NOI18N
jB_start.setForeground(new java.awt.Color(0, 153, 153));
jB_start.setText("START");
jB_start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jB_startActionPerformed(evt);
}
});
jB_rsm.setBackground(new java.awt.Color(153, 153, 153));
jB_rsm.setFont(new java.awt.Font("Trebuchet MS", 0, 20)); // NOI18N
jB_rsm.setForeground(new java.awt.Color(0, 153, 153));
jB_rsm.setText("Resume");
jB_rsm.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jB_rsmActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 6, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jB_rsm, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jB_start, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(193, 193, 193))))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jB_start, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jB_rsm))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(7, 7, 7))
);
jMenu1.setText("File");
jMenu1.setIconTextGap(0);
jMenuItem2.setText("New Game");
jMenuItem2.setIconTextGap(0);
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem1.setText("Edit Playes Details");
jMenuItem1.setHideActionText(true);
jMenuItem1.setIconTextGap(0);
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
jMenu3.setText("Help");
jMenuItem3.setText("Gameplay");
jMenuItem3.setIconTextGap(0);
jMenu3.add(jMenuItem3);
jMenuItem4.setText("About");
jMenuItem4.setIconTextGap(0);
jMenu3.add(jMenuItem4);
jMenuBar1.add(jMenu3);
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()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTFp2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTFp2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTFp2ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jTFp1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTFp1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTFp1ActionPerformed
private void jB_startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_startActionPerformed
// TODO add your handling code her
System.out.println("hi");
P1=jTFp1.getText();
P2=jTFp2.getText();
if("".equals(jTFp1.getText())){
System.out.println("1 true");
jLPlayer1.setVisible(true);
jLPlayer2.setVisible(false);
}else if("".equals(jTFp2.getText())){
jLPlayer1.setVisible(false);
jLPlayer2.setVisible(true);
}else{
bridge();
}
}//GEN-LAST:event_jB_startActionPerformed
private void bridge(){
Pt1=jTFp1.getText();
Pt2=jTFp2.getText();
new GameScreen().setVisible(true);
this.dispose();
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jB_rsmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jB_rsmActionPerformed
// TODO add your handling code here:
P1=jTFp1.getText();
P2=jTFp2.getText();
if("".equals(jTFp1.getText())){
P1=Pt1;
}
if("".equals(jTFp2.getText())){
P2=Pt2;
}
obj1.pla1=P1;
obj1.pla2=P2;
a=0;
obj1.disp();
obj1.setVisible(true);
this.dispose();
}//GEN-LAST:event_jB_rsmActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PlayerDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PlayerDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PlayerDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PlayerDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PlayerDetails().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jB_rsm;
private javax.swing.JButton jB_start;
private javax.swing.JLabel jLPlayer1;
private javax.swing.JLabel jLPlayer2;
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.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JTextField jTFp1;
private javax.swing.JTextField jTFp2;
// End of variables declaration//GEN-END:variables
private static GameScreen obj1;
private static int a;
public static void objCatcher1(GameScreen obj,int a1){
obj1=obj;
a=a1;
}
}
| mit |
brijeshsmita/base | 016RegexProject/src/RegexExample1.java | 608 |
//There are three ways to write the regex example in java.
import java.util.regex.*;
public class RegexExample1{
public static void main(String args[]){
//1st way
String input="has";
String regexPattern=".s";
Pattern p = Pattern.compile(regexPattern);//. represents single character
Matcher m = p.matcher(input);
boolean b = m.matches();
//2nd way
boolean b2=Pattern.compile(regexPattern).matcher(input).matches();
//3rd way
boolean b3 = Pattern.matches(regexPattern, input);
System.out.println(b+" "+b2+" "+b3);
}
}
| mit |
loxal/FreeEthereum | free-ethereum-core/src/main/java/org/ethereum/vm/CallCreate.java | 1990 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.vm;
/**
* @author Roman Mandeleil
* @since 03.07.2014
*/
public class CallCreate {
private final byte[] data;
private final byte[] destination;
private final byte[] gasLimit;
private final byte[] value;
public CallCreate(final byte[] data, final byte[] destination, final byte[] gasLimit, final byte[] value) {
this.data = data;
this.destination = destination;
this.gasLimit = gasLimit;
this.value = value;
}
public byte[] getData() {
return data;
}
public byte[] getDestination() {
return destination;
}
public byte[] getGasLimit() {
return gasLimit;
}
public byte[] getValue() {
return value;
}
}
| mit |
mRabitsky/RIPmrHorn | RIP Mr Horn/src/pEight/BinarySearchTree.java | 5166 | package pEight;
public class BinarySearchTree<T extends Comparable<? super T>> {
private TreeNode<T> root;
public BinarySearchTree() {
root=null;
}
public boolean add(Comparable<T> val) {
return root==(root=add(val, root));
}
private TreeNode<T> add(Comparable<T> val, TreeNode<T> tree) {
if(tree==null) return tree=new TreeNode<T>(val);
Comparable<T> treeValue=tree.getValue();
int dirTest=val.compareTo((T)treeValue);
if(dirTest<=0)
tree.setLeft(add(val, tree.getLeft()));
else if(dirTest>0) tree.setRight(add(val, tree.getRight()));
return tree;
}
public void inOrder() {
inOrder(root);
System.out.println("\n");
}
private void inOrder(TreeNode<T> tree) {
if(tree!=null) {
inOrder(tree.getLeft());
System.out.print(tree.getValue()+" ");
inOrder(tree.getRight());
}
}
public void preOrder() {
preOrder(root);
System.out.println("\n");
}
private void preOrder(TreeNode<T> tree) {
if(null==tree) return;
System.out.print(tree.getValue()+" ");
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
public void postOrder() {
postOrder(root);
System.out.println("\n");
}
private void postOrder(TreeNode<T> tree) {
if(null==tree) return;
postOrder(tree.getLeft());
postOrder(tree.getRight());
System.out.print(tree.getValue()+" ");
}
public void reverseOrder() {
reverseOrder(root);
System.out.println("\n");
}
private void reverseOrder(TreeNode<T> node) {
if(null!=node) {
reverseOrder(node.getRight());
System.out.print(node.getValue()+" ");
reverseOrder(node.getLeft());
}
}
public TreeNode<T> getRoot() {
return root;
}
public int getNumLevels() {
return getNumLevels(root);
}
private int getNumLevels(TreeNode<T> tree) {
if(tree==null) return 0;
else if(getNumLevels(tree.getLeft())>getNumLevels(tree.getRight())) return 1+getNumLevels(tree.getLeft());
else return 1+getNumLevels(tree.getRight());
}
public int getHeight() {
return getHeight(root);
}
private int getHeight(TreeNode<T> node) {
return getNumLevels(node);
}
public int getNumNodes() {
return getNumNodes(root);
}
private int getNumNodes(TreeNode<T> node) {
if(null==node) return 0;
return 1+getNumNodes(node.getLeft())+getNumNodes(node.getRight());
}
public int getNumLeaves() {
return getNumLeaves(root);
}
private int getNumLeaves(TreeNode<T> node) {
if(null!=node&&node.getLeft()==null&&node.getRight()==null) return 1;
return getNumLeaves(node.getLeft())+getNumLeaves(node.getRight());
}
protected void changeRoot(TreeNode<T> root) {
this.root=root;
}
public int getWidth() {
return getMaxDepth(root.getLeft())+getMaxDepth(root.getRight())+1;
}
private int getMaxDepth(TreeNode<T> node) {
if(null==node) return 0;
return Math.max(getMaxDepth(node.getLeft()), getMaxDepth(node.getRight())) + 1;
}
public boolean isFull() {
final int leaves=getNumLeaves(), nodes=getNumNodes();
for(int i=0; i++<32;) if(nodes==(int)Math.pow(2, i)-1) return (leaves&(leaves-1))==0;
return false;
}
public boolean remove(Comparable<T> t) {
return t.compareTo((T)remove(t, root).getValue())==0;
}
private TreeNode<T> remove(Comparable<T> t, TreeNode<T> node) {
if(null!=node) {
int dir=t.compareTo((T)node.getValue());
if(dir<0) node.setLeft(remove(t, node.getLeft()));
else if(dir>0) node.setRight(remove(t, node.getRight()));
else {
final TreeNode<T> succ=getSmallest(node.getRight());
node.setValue(succ.getValue());
node.setRight(remove(succ.getValue(), node.getRight()));
}
}
return node;
}
private TreeNode<T> getSmallest(TreeNode<T> node) {
if(null!=node) {
if(node.getLeft()!=null) return getSmallest(node.getLeft());
return node;
}
return null;
}
private TreeNode<T> getLargest(TreeNode<T> node) {
if(null!=node&&null!=node.getRight()) return getLargest(node.getRight());
return node;
}
public T search(T t) {
return search(t, root);
}
private T search(T t, TreeNode<T> node) {
if(null==node) return null;
switch(Integer.signum(t.compareTo((T)node.getValue()))) {
case -1: return search(t, node.getRight());
case 0: return (T)node.getValue();
case 1: return search(t, node.getRight());
default: return null;
}
}
public String toString() {
//return toString(root);
String str="";
for(int i=1; i<=getHeight(root); i++) str+=tabs(getHeight(root)+1-i)+toString(root, i)+"\n";
return str;
}
private String tabs(int n) {
String s="";
for(int i=0; i<n; i++) s+=" ";
return s;
}
private String toString(TreeNode<T> node, int level) {
if(node==null) return "";
if(level==1) return node.getValue()+" ";
return toString(node.getLeft(), level-1)+toString(node.getRight(), level-1);
}
private String toString(TreeNode<T> tree) {
if(null!=tree&&null!=tree.getValue()&&tree.getLeft()==null&&tree.getRight()==null) return tree.getValue().toString();
return tree.getValue()+" "+toString(tree.getLeft())+" "+toString(tree.getRight());
}
} | mit |
hscells/CSC241 | Homework 6/Room.java | 6894 | import java.util.Arrays;
public class Room{
private String name;
private String description;
private LinkedList<Creature> creatures = new LinkedList<Creature>();
private PC player;
private String state = "clean";
// 0 - N
// 1 - E
// 2 - S
// 3 - W
private Room[] rooms = new Room[4];
Room(String n, String d){
name = n;
description = d;
}
Room(){
name = "";
description = "";
}
/**
* I am unsure if a room is clean and then cleaning it should continue to
* notfify the creatures
*/
/**
* clean the room by one state
*/
public void clean(){
if(state.equals("dirty")){
state = "half-dirty";
} else if (state.equals("half-dirty")){
state = "clean";
}
notifyCreatures();
}
/**
* dirty the room by one state
*/
public void dirty(){
if(state.equals("clean")){
state = "half-dirty";
} else if (state.equals("half-dirty")){
state = "dirty";
}
notifyCreatures();
}
/**
* Adds a creature to the Room
* @param c A creature
* @return True if creature added False if room was full
*/
public Boolean addCreature(Creature c){
if (creatures.length() < 10){
creatures.append(c);
c.setRoom(this);
return true;
} else{
System.out.println("The room is full.");
return false;
}
}
/**
* Remove creature from Room
* @param c A creature
* @return True if creature was removed, False if it failed
*/
public Boolean removeCreature(Creature c){
return creatures.removeAt(creatures.getIndexOfObject(c));
}
/**
* Adds a room to the Room
* @param A room reference
* @param Direction inside the room
*/
public void addRoom(Room room, int direction){
rooms[direction] = room;
}
/**
* Gets a room from a direction
* @param direction A NESW int direction
* @return a room
*/
public Room getRoom(int direction){
return rooms[direction];
}
/**
* Sets the state of the Room
* @param s State of the room
*/
public void setState(String s){
state = s;
}
/**
* Gets the state of the Room
* @return the state of the room
*/
public String getState(){
return state;
}
/**
* Sets the description of the room
* @param desc description
*/
public void setDescription(String desc){
description = desc;
}
/**
* Get the description of the room
* @return description
*/
public String getDescription(){
return description;
}
/**
* Gets the player within the room
* @return null if the player is in the room, otherwise the player
*/
public PC getPlayer(){
return player;
}
/**
* Sets the player in the room or not
* @param p null if removing, PC if adding
*/
public void setPlayer(PC p){
player = p;
}
/**
* Notify all animals in the room of a state change
*/
public void notifyCreatures(){
LinkedList<Creature> tmp = creatures.shallowCopy();
for(Creature c : tmp){
if (c != null){
c.notifyCreature();
}
}
}
/**
* return the total number of creatures currently in the room
* @return # of creatures
*/
public int getNumberOfCreatures(){
return creatures.length();
}
/**
* Get the array of creatures
* @Deprecated
*/
public LinkedList<Creature> getCreatures(){
return creatures;
}
@Deprecated
private int searchCreature(String name, LinkedList<Creature> creature_array, int l, int h){
// binary search
if (h <= l){
return -1;
}
int m = l + (h - l) / 2;
int c = creature_array.getObjectAtIndex(m).compareTo(name);
if (c > 0){
return searchCreature(name,creature_array,l,m);
} else if (c < 0){
return searchCreature(name,creature_array,m+1,h);
} else {
return m;
}
}
public int searchCreature(String name){
int location = 0;
// linear search
for(Creature c : creatures){
if(c != null && c.name().toLowerCase().equals(name.toLowerCase())){
return location;
}
location++;
}
return -1;
}
/**
* Sort the creatures in the room using the Quicksort algorithm
* @param The list of creatures
* @param The low value
* @param The high value
* @Deprecated
*/
@Deprecated
private void sortRoom(LinkedList<Creature> c, int l, int h){
if(c.isEmpty()){
return;
}
if (l >= h){
return;
}
int m = l + (h - l) / 2;
Creature p = c.getObjectAtIndex(m);
int i = l;
int j = h;
while (i <= j){
while (c.getObjectAtIndex(i).compareTo(p) < p.compareTo(c.getObjectAtIndex(i))){
i++;
}
while (c.getObjectAtIndex(j).compareTo(p) > p.compareTo(c.getObjectAtIndex(j))){
j--;
}
if (i <= j){
c.swap(i,j);
i++;
j--;
}
}
if (l < j){
sortRoom(c,l,j);
}
if (h > i){
sortRoom(c,i,h);
}
}
/**
* Override of the private sortRoom method which fills in the blanks for you
* @Deprecated
*/
@Deprecated
public void sortRoom(){
sortRoom(creatures,0,creatures.length()-1);
}
/**
* name
* @return returns only the name of the room
*/
public String name(){
return name;
}
/**
* represent the numerical direction as a string
* @param direction number of direction
* @return a string representation of the direction
*/
private String coerceDirection(int direction){
switch(direction){
case 0:
return "North";
case 1:
return "East";
case 2:
return "South";
case 3:
return "West";
}
return "????";
}
/**
* Override method to print out the room name and animals in it
* @return A formatted string of the room and animals in it
*/
public String toString(){
String names = "Room " + name + "\n";
names += "Description: " + description + "\n";
names += "State: " + state + "\n";
for (Creature c : creatures){
names += " - (" + c.getClass().getName() + ") " + c.toString() + "\n";
}
for (int i = 0; i < 4; i++){
if(rooms[i] != null){
names += "Direction " + coerceDirection(i) + ": " + rooms[i].name() + "\n";
}
}
return names;
}
}
| mit |
stelian56/geometria | archive/3.2/src/net/geocentral/geometria/action/GProblemAnswerAction.java | 2132 | /**
* Copyright 2000-2013 Geometria Contributors
* http://geocentral.net/geometria
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License
* http://www.gnu.org/licenses
*/
package net.geocentral.geometria.action;
import net.geocentral.geometria.model.GProblem;
import net.geocentral.geometria.model.answer.GAnswer;
import net.geocentral.geometria.view.GProblemAnswerDialog;
import org.apache.log4j.Logger;
public class GProblemAnswerAction implements GUndoable, GActionWithHelp {
private GAnswer oldAnswer;
private GAnswer newAnswer;
private String helpId;
private static Logger logger = Logger.getLogger("net.geocentral.geometria");
public boolean execute() {
return execute(false);
}
public boolean execute(boolean silent) {
logger.info("");
GDocumentHandler documentHandler = GDocumentHandler.getInstance();
GProblem document = (GProblem)documentHandler.getActiveDocument();
if (silent) {
document.setAnswer(newAnswer);
}
else {
oldAnswer = document.getAnswer();
GProblemAnswerDialog dialog = new GProblemAnswerDialog( documentHandler.getOwnerFrame(), this, document);
dialog.setVisible(true);
GAnswer answer = dialog.getAnswer();
if (answer == null) {
return false;
}
document.setAnswer(answer);
newAnswer = answer;
}
documentHandler.setDocumentModified(true);
logger.info(oldAnswer + ", " + newAnswer);
return true;
}
public void undo(GDocumentHandler documentHandler) {
logger.info("");
GProblem document = (GProblem)documentHandler.getActiveDocument();
document.setAnswer(oldAnswer);
logger.info(oldAnswer + ", " + newAnswer);
}
public String getShortDescription() {
return "answer";
}
public String getHelpId() {
return helpId;
}
public void setHelpId(String helpId) {
this.helpId = helpId;
}
}
| mit |
Sukora-Stas/JavaRushTasks | 3.JavaMultithreading/src/com/javarush/task/task25/task2513/Solution.java | 2029 | //package com.javarush.task.task25.task2513;
//
//import java.util.Random;
//
///*
//Обеспечение отсутствия прерывания важной операции
//*/
//public class Solution {
// private static final Integer THRESHOLD_VALUE = 500;
// private static final Random RANDOM = new Random();
//
// public synchronized void moveMoney(Account from, Account to, int amount) throws InterruptedException {
// from.setBalance(from.getBalance() - amount);
// if (RANDOM.nextInt(5000) > THRESHOLD_VALUE)
// Thread.yield();
// to.setBalance(to.getBalance() + amount);
// }
//
//
// private class Account {
// private int balance;
//
// public int getBalance() {
// return balance;
// }
//
// public void setBalance(int balance) {
// this.balance = balance;
// }
// }
//
//}
package com.javarush.task.task25.task2513;
import java.util.Random;
/*
Просмотри метод moveMoney.
Если RANDOM.nextInt(5000) больше порогового значения THRESHOLD_VALUE, то обеспечь переуступку кванта времени (переход хода для текущей нити).
Добавь этот код в единственное допустимое место.
*/
public class Solution {
private static final Integer THRESHOLD_VALUE = 500;
private static final Random RANDOM = new Random();
public synchronized void moveMoney(Account from, Account to, int amount) {
from.setBalance(from.getBalance() - amount);
if(RANDOM.nextInt(5000) > THRESHOLD_VALUE) {
Thread.yield();
}
to.setBalance(to.getBalance() + amount);
}
class Account {
private int balance;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
public static void main(String[] args) {
}
}
| mit |
tiffit/TaleCraft | src/main/java/talecraft/blocks/util/CollisionTriggerBlock.java | 2080 | package talecraft.blocks.util;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import talecraft.TaleCraft;
import talecraft.blocks.TCBlockContainer;
import talecraft.client.gui.blocks.GuiCollisionTriggerBlock;
import talecraft.tileentity.CollisionTriggerBlockTileEntity;
public class CollisionTriggerBlock extends TCBlockContainer {
@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
return new CollisionTriggerBlockTileEntity();
}
@Override
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
if(entityIn instanceof EntityPlayerMP) {
EntityPlayerMP p = (EntityPlayerMP) entityIn;
if(p.capabilities.isCreativeMode)return;
}else return;
TileEntity tileEntity = worldIn.getTileEntity(pos);
if(tileEntity != null && tileEntity instanceof CollisionTriggerBlockTileEntity) {
((CollisionTriggerBlockTileEntity)tileEntity).collision(entityIn);
}
}
@Override
@SideOnly(Side.CLIENT)
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
if(!worldIn.isRemote)
return true;
if(!TaleCraft.proxy.isBuildMode())
return false;
if(playerIn.isSneaking())
return true;
Minecraft mc = Minecraft.getMinecraft();
mc.displayGuiScreen(new GuiCollisionTriggerBlock((CollisionTriggerBlockTileEntity)worldIn.getTileEntity(pos)));
return true;
}
@Override
public boolean isPassable(IBlockAccess worldIn, BlockPos pos) {
return true;
}
}
| mit |
kenyonduan/amazon-mws | src/main/java/com/amazonservices/mws/products/model/GetLowestPricedOffersForASINResponse.java | 7203 | /*******************************************************************************
* Copyright 2009-2017 Amazon Services. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
* This file 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.
*******************************************************************************
* Get Lowest Priced Offers For ASIN Response
* API Version: 2011-10-01
* Library Version: 2017-03-22
* Generated: Wed Mar 22 23:24:32 UTC 2017
*/
package com.amazonservices.mws.products.model;
import javax.xml.bind.annotation.*;
import com.amazonservices.mws.client.*;
/**
* GetLowestPricedOffersForASINResponse complex type.
*
* XML schema:
*
* <pre>
* <complexType name="GetLowestPricedOffersForASINResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="GetLowestPricedOffersForASINResult" type="{http://mws.amazonservices.com/schema/Products/2011-10-01}GetLowestPricedOffersForASINResult" minOccurs="0"/>
* <element name="ResponseMetadata" type="{http://mws.amazonservices.com/schema/Products/2011-10-01}ResponseMetadata" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="GetLowestPricedOffersForASINResponse", propOrder={
"getLowestPricedOffersForASINResult",
"responseMetadata"
})
@XmlRootElement(name = "GetLowestPricedOffersForASINResponse")
public class GetLowestPricedOffersForASINResponse extends AbstractMwsObject implements MWSResponse {
@XmlElement(name="GetLowestPricedOffersForASINResult")
private GetLowestPricedOffersForASINResult getLowestPricedOffersForASINResult;
@XmlElement(name="ResponseMetadata")
private ResponseMetadata responseMetadata;
@XmlTransient
private ResponseHeaderMetadata responseHeaderMetadata;
/**
* Get the value of GetLowestPricedOffersForASINResult.
*
* @return The value of GetLowestPricedOffersForASINResult.
*/
public GetLowestPricedOffersForASINResult getGetLowestPricedOffersForASINResult() {
return getLowestPricedOffersForASINResult;
}
/**
* Set the value of GetLowestPricedOffersForASINResult.
*
* @param getLowestPricedOffersForASINResult
* The new value to set.
*/
public void setGetLowestPricedOffersForASINResult(GetLowestPricedOffersForASINResult getLowestPricedOffersForASINResult) {
this.getLowestPricedOffersForASINResult = getLowestPricedOffersForASINResult;
}
/**
* Check to see if GetLowestPricedOffersForASINResult is set.
*
* @return true if GetLowestPricedOffersForASINResult is set.
*/
public boolean isSetGetLowestPricedOffersForASINResult() {
return getLowestPricedOffersForASINResult != null;
}
/**
* Set the value of GetLowestPricedOffersForASINResult, return this.
*
* @param getLowestPricedOffersForASINResult
* The new value to set.
*
* @return This instance.
*/
public GetLowestPricedOffersForASINResponse withGetLowestPricedOffersForASINResult(GetLowestPricedOffersForASINResult getLowestPricedOffersForASINResult) {
this.getLowestPricedOffersForASINResult = getLowestPricedOffersForASINResult;
return this;
}
/**
* Get the value of ResponseMetadata.
*
* @return The value of ResponseMetadata.
*/
public ResponseMetadata getResponseMetadata() {
return responseMetadata;
}
/**
* Set the value of ResponseMetadata.
*
* @param responseMetadata
* The new value to set.
*/
public void setResponseMetadata(ResponseMetadata responseMetadata) {
this.responseMetadata = responseMetadata;
}
/**
* Check to see if ResponseMetadata is set.
*
* @return true if ResponseMetadata is set.
*/
public boolean isSetResponseMetadata() {
return responseMetadata != null;
}
/**
* Set the value of ResponseMetadata, return this.
*
* @param responseMetadata
* The new value to set.
*
* @return This instance.
*/
public GetLowestPricedOffersForASINResponse withResponseMetadata(ResponseMetadata responseMetadata) {
this.responseMetadata = responseMetadata;
return this;
}
/**
* Get the value of ResponseHeaderMetadata.
*
* @return The value of ResponseHeaderMetadata.
*/
public ResponseHeaderMetadata getResponseHeaderMetadata() {
return responseHeaderMetadata;
}
/**
* Set the value of ResponseHeaderMetadata.
*
* @param responseHeaderMetadata
* The new value to set.
*/
public void setResponseHeaderMetadata(ResponseHeaderMetadata responseHeaderMetadata) {
this.responseHeaderMetadata = responseHeaderMetadata;
}
/**
* Check to see if ResponseHeaderMetadata is set.
*
* @return true if ResponseHeaderMetadata is set.
*/
public boolean isSetResponseHeaderMetadata() {
return responseHeaderMetadata != null;
}
/**
* Set the value of ResponseHeaderMetadata, return this.
*
* @param responseHeaderMetadata
* The new value to set.
*
* @return This instance.
*/
public GetLowestPricedOffersForASINResponse withResponseHeaderMetadata(ResponseHeaderMetadata responseHeaderMetadata) {
this.responseHeaderMetadata = responseHeaderMetadata;
return this;
}
/**
* Read members from a MwsReader.
*
* @param r
* The reader to read from.
*/
@Override
public void readFragmentFrom(MwsReader r) {
getLowestPricedOffersForASINResult = r.read("GetLowestPricedOffersForASINResult", GetLowestPricedOffersForASINResult.class);
responseMetadata = r.read("ResponseMetadata", ResponseMetadata.class);
}
/**
* Write members to a MwsWriter.
*
* @param w
* The writer to write to.
*/
@Override
public void writeFragmentTo(MwsWriter w) {
w.write("GetLowestPricedOffersForASINResult", getLowestPricedOffersForASINResult);
w.write("ResponseMetadata", responseMetadata);
}
/**
* Write tag, xmlns and members to a MwsWriter.
*
* @param w
* The Writer to write to.
*/
@Override
public void writeTo(MwsWriter w) {
w.write("http://mws.amazonservices.com/schema/Products/2011-10-01", "GetLowestPricedOffersForASINResponse",this);
}
/** Default constructor. */
public GetLowestPricedOffersForASINResponse() {
super();
}
}
| mit |
patrickneubauer/XMLIntellEdit | xmlintelledit/xmltext/src/main/java/isostdisots_29002_4ed_1techxmlschemabasicSimplified/impl/InternationalTextImpl.java | 4371 | /**
*/
package isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import isostdisots_29002_4ed_1techxmlschemabasicSimplified.InternationalText;
import isostdisots_29002_4ed_1techxmlschemabasicSimplified.Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage;
import isostdisots_29002_4ed_1techxmlschemabasicSimplified.LanguageString;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>International Text</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link isostdisots_29002_4ed_1techxmlschemabasicSimplified.impl.InternationalTextImpl#getLocalStrings <em>Local Strings</em>}</li>
* </ul>
*
* @generated
*/
public class InternationalTextImpl extends MinimalEObjectImpl.Container implements InternationalText {
/**
* The cached value of the '{@link #getLocalStrings() <em>Local Strings</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLocalStrings()
* @generated
* @ordered
*/
protected EList<LanguageString> localStrings;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected InternationalTextImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.Literals.INTERNATIONAL_TEXT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<LanguageString> getLocalStrings() {
if (localStrings == null) {
localStrings = new EObjectContainmentEList<LanguageString>(LanguageString.class, this, Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.INTERNATIONAL_TEXT__LOCAL_STRINGS);
}
return localStrings;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.INTERNATIONAL_TEXT__LOCAL_STRINGS:
return ((InternalEList<?>)getLocalStrings()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.INTERNATIONAL_TEXT__LOCAL_STRINGS:
return getLocalStrings();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.INTERNATIONAL_TEXT__LOCAL_STRINGS:
getLocalStrings().clear();
getLocalStrings().addAll((Collection<? extends LanguageString>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.INTERNATIONAL_TEXT__LOCAL_STRINGS:
getLocalStrings().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Isostdisots_29002_4ed_1techxmlschemabasicSimplifiedPackage.INTERNATIONAL_TEXT__LOCAL_STRINGS:
return localStrings != null && !localStrings.isEmpty();
}
return super.eIsSet(featureID);
}
} //InternationalTextImpl
| mit |
VincentK2000/KartoffelKanaalPlugin | plugin/kartoffelsystems/PulserSystem/PNCondition.java | 18038 | package KartoffelKanaalPlugin.plugin.kartoffelsystems.PulserSystem;
import KartoffelKanaalPlugin.plugin.AttribSystem;
import KartoffelKanaalPlugin.plugin.IObjectCommandHandable;
import KartoffelKanaalPlugin.plugin.kartoffelsystems.PlayerSystem.Person;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.logging.Logger;
public abstract class PNCondition implements IObjectCommandHandable {
// DEPRECATED: Dit zorgt misschien wel voor sneller bewaren, maar trager voor laden en kan soms verwarrend zijn//4 byte's: vrij houden, is nl. gebruikt bij PulserNoticationExtended om de length aan te duiden
//1 byte: Type
//1 byte: Special Data
// 1 bit: ~ leeg ~
// 1 bit: closed (de value wordt niet berekend en de default value wordt gebruikt)
// 1 bit: default value
// 1 bit: last value
// 4 bits: leeg
//4 bytes: ConditionID
//<...> byte's: Customized Condition Data
protected byte options;
protected boolean invisible;
protected int conditionID;
protected PNTechCondition root;
protected PNCondition(byte options, boolean invisible, int conditionID, PNTechCondition root){
this.root = root;
this.options = options;
this.invisible = invisible;
this.conditionID = conditionID;
}
protected PNCondition(byte[] src){
if(src == null || src.length < 6){
this.options = 0x40;
this.invisible = true;
this.conditionID = -1;
}else{
this.options = src[1];
this.invisible = (src[0] & 0x80) == 0x80;
this.conditionID = src[2] << 24 | src[3] << 16 | src[4] << 8 | src[5];
}
}
public boolean isInvisible(){
return this.invisible;
}
public void setInvisible(boolean newValue) throws Exception{
this.checkDenyChanges();
this.invisible = newValue;
this.notifyChange();
}
protected abstract byte getConditionType();
//return new PNCondition(this.source);
//}
protected abstract int getEstimatedSize();
protected abstract boolean calculateValue();
//return new PNCondition(this.source);
//}
protected final boolean getConditionValue(){
boolean value = true;
if((options & 0x40) == 0x40){
value = ((options & 0x20) == 0x20);
}else{
value = this.calculateValue();
}
if(value){
options |= 0x10;
}else{
options &= 0xEF;
}
return value;
}
protected static PNCondition loadFromBytes(byte[] src){
if(src == null || src.length < PNCondition.generalInfoLength())return new PNConditionNLOADED(src);
byte t = (byte) (src[0] & 0x7F);
// 0: AND**
// 1: OR**
// 2: XOR**
// 3: NOT**
// 4: NUMB
// 5: PORT
// 6: DataField
// 7: Time
// 8: Constant
// 9: ~ leeg ~
// 10: Random
PNCondition a = null;
if(t == 0){
a = PNConditionAND.loadFromBytes(src);
}else if(t == 1){
a = PNConditionOR.loadFromBytes(src);
}else if(t == 2){
a = PNConditionXOR.loadFromBytes(src);
}else if(t == 3){
a = PNConditionNOT.loadFromBytes(src);
}else if(t == 4){
a = PNConditionNUMB.loadFromBytes(src);
}else if(t == 5){
a = PNConditionPORT.loadFromBytes(src);
}else if(t == 6){
a = PNConditionDataField.loadFromBytes(src);
}else if(t == 7){
a = PNConditionTimeRanged.loadFromBytes(src);
}else if(t == 8){
a = PNConditionConstant.loadFromBytes(src);
}else if(t == 10){
a = PNConditionRandom.loadFromBytes(src);
}else{
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Pulser: Een Condition is incorrect (het type is onbekend: \"" + t + "\")");
}
if(a == null){
a = new PNConditionNLOADED(src);
}
return a;
}
protected abstract byte[] saveCondition();
//return new PNCondition(this.source);
//}
protected static final int generalInfoLength(){return 6;}
//return new PNCondition(this.source);
//}
protected final boolean saveGeneralInfo(byte[] ans){
if(ans == null || ans.length < 6)return false;
ans[0] = this.getConditionType();
if(this.invisible)ans[0] |= 0x80;
ans[1] = this.options;
ans[2] = (byte) ((this.conditionID >>> 24) & 0xFF);
ans[3] = (byte) ((this.conditionID >>> 16) & 0xFF);
ans[4] = (byte) ((this.conditionID >>> 8) & 0xFF);
ans[5] = (byte) ((this.conditionID ) & 0xFF);
return true;
}
//return new PNCondition(this.source);
//}
public static PNCondition createFromParams(String[] params, byte options, int ID, PNTechCondition root) throws Exception{
if(params == null)throw new Exception("De parameters zijn null");
if(params.length == 0){
throw new Exception("De eerste creatie parameter moet het PNTech-type zijn. Die kan zijn: \"TextProvider\",\"Condition\",\"DataFieldConn\",\"NotifSize\",\"SpecEditAccess\"");
}
String[] conditionSpecificParams = new String[params.length - 1];
System.arraycopy(params, 1, conditionSpecificParams, 0, conditionSpecificParams.length);
String conditionType = params[0].toLowerCase();
if(conditionType.equals("and") || conditionType.equals("0")){
return PNConditionAND.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("or") || conditionType.equals("1")){
return PNConditionOR.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("xor") || conditionType.equals("2")){
return PNConditionXOR.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("not") || conditionType.equals("3")){
return PNConditionNOT.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("numb") || conditionType.equals("4")){
return PNConditionNUMB.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("port") || conditionType.equals("5")){
return PNConditionPORT.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("datafield") || conditionType.equals("6")){
return PNConditionDataField.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("timeranged") || conditionType.equals("7")){
return PNConditionTimeRanged.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("constant") || conditionType.equals("8")){
return PNConditionConstant.createFromParams(conditionSpecificParams, options, ID, root);
}else if(conditionType.equals("random") || conditionType.equals("10")){
return PNConditionRandom.createFromParams(conditionSpecificParams, options, ID, root);
}else{
throw new Exception("Onbekend PNCondition-type");
}
}
protected abstract PNCondition createCopy(int conditionID, PNTechCondition base) throws Exception;
@Override
public boolean handleObjectCommand(Person executor, CommandSender a, AttribSystem attribSys, String[] args) throws Exception {
String label = args[0];
if(label.equals("visibility")){
if(executor.getSpelerOptions().getOpStatus() < 2){
throw new Exception("§4Je hebt geen toegang tot dit commando");
}
if(args.length < 2){
a.sendMessage("§eDe Condition is " + (this.isInvisible()?"§4invisible":"§2visible"));
}else{
args[1] = args[1].toLowerCase();
boolean invisibilityValue;
if(args[1].equals("visible") || args[1].equals("on") || args[1].equals("+")){
invisibilityValue = false;
}else if(args[1].equals("invisibile") || args[1].equals("invis") || args[1].equals("off") || args[1].equals("-")){
invisibilityValue = true;
}else{
a.sendMessage("§4Mogelijke nieuwe waarden voor de staat zijn: §2visible, aan, +§f of §4invisible, off, -");
return true;
}
this.setInvisible(invisibilityValue);
a.sendMessage("§eDe Condition is nu " + (this.isInvisible()?"§4invisible":"§2visible"));
}
}else if(label.equals("value")){
if(executor.getSpelerOptions().getOpStatus() < 2){
throw new Exception("§4Je hebt geen toegang tot dit commando");
}
if(args.length < 2){
a.sendMessage("§eWaardes van de condition-value:");
a.sendMessage("§eDe value is " + (((this.options & 0x40) == 0x40)?"§4closed (de waarde wordt niet berekend maar de defaultValue wordt gebruikt)":"§2niet-closed (de waarde wordt elke keer berekend)"));
a.sendMessage("§eDe defaultValue is " + (((this.options & 0x20) == 0x20)?"§2aan":"§4uit") + "§e (" + ((this.options & 0x20) == 0x20) + ")");
a.sendMessage("§eDe laatste value (kan incorrect zijn als de waarde nog niet is opgevraagd na inladen) is " + (((this.options & 0x10) == 0x10)?"§2aan":"§4uit") + "§e (" + ((this.options & 0x10) == 0x10) + ")");
}else{
args[1] = args[1].toLowerCase();
if(args[1].equals("closed")){
if(args.length == 2){
a.sendMessage("§eDe value is " + (((this.options & 0x40) == 0x40)?"§4closed (de waarde wordt niet berekend maar de defaultValue wordt gebruikt)":"§2niet-closed (de waarde wordt elke keer berekend)"));
}else if(args.length == 3){
boolean newValue;
if(args[2].equals("closed") || args[2].equals("on") || args[2].equals("aan")){
newValue = true;
}else if(args[2].equals("niet-closed") || args[2].equals("off") || args[2].equals("uit")){
newValue = false;
}else{
a.sendMessage("§4Mogelijke nieuwe waarden voor de staat zijn: §2closed, on, aan§f of §4niet-closed, off, uit");
return true;
}
this.checkDenyChanges();
if(newValue){
this.options |= 0x40;
}else{
this.options &= 0xBF;
}
this.notifyChange();
a.sendMessage("§eDe value is nu " + (((this.options & 0x40) == 0x40)?"§4closed (de waarde wordt niet berekend maar de defaultValue wordt gebruikt)":"§2niet-closed (de waarde wordt elke keer berekend)"));
}else{
a.sendMessage("§eCondition-command: §cvalue last [nieuwe waarde]");
}
}else if(args[1].equals("default")){
if(args.length == 2){
a.sendMessage("§eDe defaultValue is " + (((this.options & 0x20) == 0x20)?"§2aan":"§4uit") + "§e (" + ((this.options & 0x20) == 0x20) + ")");
}else if(args.length == 3){
boolean newValue;
if(args[2].equals("aan") || args[2].equals("on") || args[2].equals("+")){
newValue = true;
}else if(args[2].equals("uit") || args[2].equals("off") || args[2].equals("-")){
newValue = false;
}else{
a.sendMessage("§4Mogelijke nieuwe waarden voor de staat zijn: §2aan, on, +§f of §4uit, off, -");
return true;
}
this.checkDenyChanges();
if(newValue){
this.options |= 0x20;
}else{
this.options &= 0xDF;
}
this.notifyChange();
a.sendMessage("§eDe defaultValue is nu " + (((this.options & 0x20) == 0x20)?"§2aan":"§4uit") + "§e (" + ((this.options & 0x20) == 0x20) + ")");
}else{
a.sendMessage("§eCondition-command: §cvalue default [nieuwe waarde]");
}
}else if(args[1].equals("laatste")){
if(args.length == 2){
a.sendMessage("§eDe laatste value (kan incorrect zijn als de waarde nog niet is opgevraagd na inladen) is " + (((this.options & 0x10) == 0x10)?"§2aan":"§4uit") + "§e (" + ((this.options & 0x10) == 0x10) + ")");
}else{
a.sendMessage("§eCondition-command: §cvalue last");
}
}else if(args[1].equals("calculate")){
if(args.length == 2){
long start = System.currentTimeMillis();
boolean value = this.getConditionValue();
long stop = System.currentTimeMillis();
long duration = stop - start;
a.sendMessage("§eDe berekende waarde is " + (value?"§2aan":"§4uit") + "§e (" + value + "). Het duurde ongeveer " + duration + " milliseconden om de waarde te berekenen");
}else{
a.sendMessage("§eCondition-command: §cvalue calculate");
}
}else{
a.sendMessage("§eCondition-command: §cvalue <closed|default|laatste|calculate> <...>");
}
}
}else if(label.equals("conditionid")){
if(executor.getSpelerOptions().getOpStatus() < 2){
throw new Exception("Je hebt geen toegang tot dit commando");
}
a.sendMessage("§eConditionID = " + this.conditionID);
}else if(label.equals("gettype")){
if(executor.getSpelerOptions().getOpStatus() < 2){
throw new Exception("Je hebt geen toegang tot dit commando");
}
a.sendMessage("§eConditionType = " + this.getConditionType());
}else if(label.equals("tostring")){
if(executor.getSpelerOptions().getOpStatus() < 2){
throw new Exception("Je hebt geen toegang tot dit commando");
}
a.sendMessage("§etoString() = " + this.toString());
}else{
return false;
}
return true;
}
//public abstract void handleLocalCommand(Person executor, CommandSender a, AttribSystem attribSys, String[] args) throws Exception;
@Override
public ArrayList<String> autoCompleteObjectCommand(String[] args, ArrayList<String> a) throws Exception {
String label = args[0];
if(args.length == 1){
if("visibility".startsWith(label))a.add("visibility");
if("value".startsWith(label))a.add("value");
}else{
if(label.equals("visibility")){
if(args.length == 2){
args[1] = args[1].toLowerCase();
if("visible".startsWith(args[1]))a.add("visible");
if("invisible".startsWith(args[1]))a.add("invisible");
}
}else if(label.equals("value")){
args[1] = args[1].toLowerCase();
if(args.length == 2){
if("closed".startsWith(args[1]))a.add("closed");
if("default".startsWith(args[1]))a.add("default");
if("laatste".startsWith(args[1]))a.add("laatste");
if("calculate".startsWith(args[1]))a.add("calculate");
}else if(args.length == 3){
if(args[1].equals("closed")){
args[1] = args[1].toLowerCase();
if("closed".startsWith(args[1]))a.add("closed");
if("niet-closed".startsWith(args[1]))a.add("niet-closed");
if("aan".startsWith(args[1]))a.add("aan");
if("uit".startsWith(args[1]))a.add("uit");
}else if(args[1].equals("default")){
args[1] = args[1].toLowerCase();
if("aan".startsWith(args[1]))a.add("aan");
if("uit".startsWith(args[1]))a.add("uit");
}
}
}
}
return a;
}
@Override
public IObjectCommandHandable getSubObjectCH(String s) throws Exception{
return null;
}
@Override
public ArrayList<String> autoCompleteSubObjectCH(String s, ArrayList<String> a) throws Exception{
return a;
}
/*public String getTopLevelPossibilitiesString(){
ArrayList<String> al = new ArrayList<String>(1);
try {
al = this.autoCompleteObjectCommand(new String[]{""}, al);
} catch (Exception e) {
return "Fout_bij_zoeken";
}
if(al.size() == 0)return "";
StringBuilder sb = new StringBuilder(20);
for(int i = 0; i < al.size() - 1; i++){
String s = al.get(i);
if(s == null || s.length() == 0)continue;
sb.append(s);
sb.append('|');
}
String last = al.get(al.size() - 1);
if(last != null){
sb.append(last);
}
return sb.toString();
}*/
/*public String getTopLevelPossibilitiesString(){
String[] total = this.getTotalTopLevelArgsPossibilities();
if(total.length == 0)return "";
StringBuilder sb = new StringBuilder(20);
for(int i = 0; i < total.length - 1; i++){
if(total[i] == null || total[i].length() == 0)continue;
sb.append(total[i]);
sb.append('|');
}
if(total[total.length - 1] != null){
sb.append(total[total.length - 1]);
}
return sb.toString();
}
public final String[] getTotalTopLevelArgsPossibilities(){
String[] general = new String[]{"visibility","value"};
String[] local = this.getLocalTopLevelArgsPossibilities();
if(local == null)local = new String[0];
String[] total = new String[general.length + local.length];
System.arraycopy(general, 0, total, 0, general.length);
System.arraycopy(local, 0, total, general.length, local.length);
return total;
}
public abstract String[] getLocalTopLevelArgsPossibilities();*/
public boolean denyChanges(){
return this.root != null && this.root.notificationBase != null && this.root.notificationBase.denyChanges();
}
public void checkDenyChanges() throws Exception{
if(this.denyChanges())throw new Exception("Veranderingen zijn niet toegestaan voor de PulserNotif. Controleer read-only");
}
/*public String getTopLevelPossibilitiesString(){
ArrayList<String> al = new ArrayList<String>(1);
try {
al = this.autoCompleteObjectCommand(new String[]{""}, al);
} catch (Exception e) {
return "Fout_bij_zoeken";
}
if(al.size() == 0)return "";
StringBuilder sb = new StringBuilder(20);
for(int i = 0; i < al.size() - 1; i++){
String s = al.get(i);
if(s == null || s.length() == 0)continue;
sb.append(s);
sb.append('|');
}
String last = al.get(al.size() - 1);
if(last != null){
sb.append(last);
}
return sb.toString();
}*/
/*public String getTopLevelPossibilitiesString(){
String[] total = this.getTotalTopLevelArgsPossibilities();
if(total.length == 0)return "";
StringBuilder sb = new StringBuilder(20);
for(int i = 0; i < total.length - 1; i++){
if(total[i] == null || total[i].length() == 0)continue;
sb.append(total[i]);
sb.append('|');
}
if(total[total.length - 1] != null){
sb.append(total[total.length - 1]);
}
return sb.toString();
}
public final String[] getTotalTopLevelArgsPossibilities(){
String[] general = new String[]{"visibility","value"};
String[] local = this.getLocalTopLevelArgsPossibilities();
if(local == null)local = new String[0];
String[] total = new String[general.length + local.length];
System.arraycopy(general, 0, total, 0, general.length);
System.arraycopy(local, 0, total, general.length, local.length);
return total;
}
public abstract String[] getLocalTopLevelArgsPossibilities();*/
protected void notifyChange(){
if(this.root != null)this.root.notifyChange();
}
@Override
public String toString(){
return "PNCondition[conditionID=" + this.conditionID + ",invisible=" + this.invisible + ",valueClosed=" + ((this.options & 0x40) == 0x40) + ",valueDefault=" + ((this.options & 0x20) == 0x20) + ",valueLast=" + ((this.options & 0x10) == 0x10) + "]";
}
}
| mit |
byronka/xenos | utils/pmd-bin-5.2.2/src/pmd-core/src/test/java/net/sourceforge/pmd/jaxen/AttributeTest.java | 1124 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.jaxen;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Method;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.xpath.Attribute;
import org.junit.Test;
public class AttributeTest{
@Test
public void testConstructor() {
DummyNode p = new DummyNode(1);
p.testingOnly__setBeginLine(5);
Method[] methods = p.getClass().getMethods();
Method m = null;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("getBeginLine")) {
m = methods[i];
break;
}
}
Attribute a = new Attribute(p, "BeginLine", m);
assertEquals("BeginLine", a.getName());
assertEquals(5, a.getValue());
assertEquals("5", a.getStringValue());
assertEquals(p, a.getParent());
}
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(AttributeTest.class);
}
}
| mit |
Menkachev/Java | Java DB Fundamentals/Java Introduction/03. Java OOP Principles/BirthdayCelebrations/Main.java | 2565 | package BorderControl;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Identifiable> identifiables = new ArrayList<>();
List<Birthdays> birthday = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.nextLine();
if (input.equals("End")) {
break;
}
String[] info = input.split("\\s");
//
// if (info.length == 2) {
// String name = info[0];
// String id = info[1];
// Identifiable robot = new RobotsImpl(id, name);
// identifiables.add(robot);
// } else if (info.length == 3) {
// String name = info[0];
// int age = Integer.parseInt(info[1]);
// String id = info[2];
// Identifiable citizen = new CitizensImpl(id, name, age);
// identifiables.add(citizen);
// }
switch (info[0]){
case "Citizen":
String name = info[1];
int age = Integer.parseInt(info[2]);
String id = info[3];
String birthdate = info[4];
Citizens citizen = new CitizensImpl(id, name, age, birthdate);
birthday.add(citizen);
identifiables.add(citizen);
break;
case "Pet":
String petName = info[1];
String petBirthday = info[2];
Pets pet = new PetsImpl(petName, petBirthday);
birthday.add(pet);
break;
case "Robot":
String model = info[1];
String robotId = info[2];
Robots robot = new RobotsImpl(model, robotId);
identifiables.add(robot);
break;
}
}
// String fakeId = scanner.nextLine();
String date = scanner.nextLine();
// for (Identifiable identifiable : identifiables) {
// if (identifiable.getId().endsWith(fakeId)) {
// System.out.println(identifiable.getId());
// }
// }
for (Birthdays birthdate:birthday) {
if (birthdate.getBirthday().endsWith(date)){
System.out.println(birthdate.getBirthday());
}
}
}
} | mit |
aczartoryski/gpo.app | src/main/java/com/app/gpo/configuration/AppConfig.java | 4435 | /*
* The MIT License
*
* Copyright 2017 Artur Czartoryski <artur at czartoryski.wroclaw.pl>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.app.gpo.configuration;
import com.app.gpo.security.SecurityConfig;
import com.app.gpo.services.OrderItemAutoChangeStatus;
import javax.servlet.Filter;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
/**
*
* @author Artur Czartoryski <artur at czartoryski.wroclaw.pl>
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.app.gpo.*")
@Import(value={ SecurityConfig.class })
@EnableScheduling
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public ResourceBundleViewResolver viewResolver2() {
ResourceBundleViewResolver viewResolver2 = new ResourceBundleViewResolver();
viewResolver2.setOrder(1);
viewResolver2.setBasename("views");
return viewResolver2;
}
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setOrder(2);
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Bean
public Filter characterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return filter;
}
@Bean
public OrderItemAutoChangeStatus orderItemAutoChangeStatus() {
return new OrderItemAutoChangeStatus();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
| mit |
CS2103AUG2016-W13-C1/main | src/test/java/seedu/todo/commons/core/VersionTest.java | 4864 | package seedu.todo.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class VersionTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void versionParsing_acceptableVersionString_parsedVersionCorrectly() {
verifyVersionParsedCorrectly("V0.0.0ea", 0, 0, 0, true);
verifyVersionParsedCorrectly("V3.10.2", 3, 10, 2, false);
verifyVersionParsedCorrectly("V100.100.100ea", 100, 100, 100, true);
}
@Test
public void versionParsing_wrongVersionString_throwIllegalArgumentException() {
thrown.expect(IllegalArgumentException.class);
Version.fromString("This is not a version string");
}
@Test
public void versionConstructor_correctParameter_valueAsExpected() {
Version version = new Version(19, 10, 20, true);
assertEquals(19, version.getMajor());
assertEquals(10, version.getMinor());
assertEquals(20, version.getPatch());
assertEquals(true, version.isEarlyAccess());
}
@Test
public void versionToString_validVersion_correctStringRepresentation() {
// boundary at 0
Version version = new Version(0, 0, 0, true);
assertEquals("V0.0.0ea", version.toString());
// normal values
version = new Version(4, 10, 5, false);
assertEquals("V4.10.5", version.toString());
// big numbers
version = new Version(100, 100, 100, true);
assertEquals("V100.100.100ea", version.toString());
}
@Test
public void versionComparable_validVersion_compareToIsCorrect() {
Version one, another;
// Tests equality
one = new Version(0, 0, 0, true);
another = new Version(0, 0, 0, true);
assertTrue(one.compareTo(another) == 0);
one = new Version(11, 12, 13, false);
another = new Version(11, 12, 13, false);
assertTrue(one.compareTo(another) == 0);
// Tests different patch
one = new Version(0, 0, 5, false);
another = new Version(0, 0, 0, false);
assertTrue(one.compareTo(another) > 0);
// Tests different minor
one = new Version(0, 0, 0, false);
another = new Version(0, 5, 0, false);
assertTrue(one.compareTo(another) < 0);
// Tests different major
one = new Version(10, 0, 0, true);
another = new Version(0, 0, 0, true);
assertTrue(one.compareTo(another) > 0);
// Tests high major vs low minor
one = new Version(10, 0, 0, true);
another = new Version(0, 1, 0, true);
assertTrue(one.compareTo(another) > 0);
// Tests high patch vs low minor
one = new Version(0, 0, 10, false);
another = new Version(0, 1, 0, false);
assertTrue(one.compareTo(another) < 0);
// Tests same major minor different patch
one = new Version(2, 15, 0, false);
another = new Version(2, 15, 5, false);
assertTrue(one.compareTo(another) < 0);
// Tests early access vs not early access on same version number
one = new Version(2, 15, 0, true);
another = new Version(2, 15, 0, false);
assertTrue(one.compareTo(another) < 0);
// Tests early access lower version vs not early access higher version compare by version number first
one = new Version(2, 15, 0, true);
another = new Version(2, 15, 5, false);
assertTrue(one.compareTo(another) < 0);
// Tests early access higher version vs not early access lower version compare by version number first
one = new Version(2, 15, 0, false);
another = new Version(2, 15, 5, true);
assertTrue(one.compareTo(another) < 0);
}
@Test
public void versionComparable_validVersion_hashCodeIsCorrect() {
Version version = new Version(100, 100, 100, true);
assertEquals(100100100, version.hashCode());
version = new Version(10, 10, 10, false);
assertEquals(1010010010, version.hashCode());
}
@Test
public void versionComparable_validVersion_equalIsCorrect() {
Version one, another;
one = new Version(0, 0, 0, false);
another = new Version(0, 0, 0, false);
assertTrue(one.equals(another));
one = new Version(100, 191, 275, true);
another = new Version(100, 191, 275, true);
assertTrue(one.equals(another));
}
private void verifyVersionParsedCorrectly(String versionString,
int major, int minor, int patch, boolean isEarlyAccess) {
assertEquals(new Version(major, minor, patch, isEarlyAccess), Version.fromString(versionString));
}
}
| mit |
ClubObsidian/ObsidianEngine | src/com/clubobsidian/obsidianengine/snakeyaml/scanner/ScannerImpl.java | 83726 | /**
* Copyright (c) 2008, http://www.snakeyaml.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 com.clubobsidian.obsidianengine.snakeyaml.scanner;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.clubobsidian.obsidianengine.snakeyaml.error.Mark;
import com.clubobsidian.obsidianengine.snakeyaml.error.YAMLException;
import com.clubobsidian.obsidianengine.snakeyaml.reader.StreamReader;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.AliasToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.AnchorToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.BlockEndToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.BlockEntryToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.BlockMappingStartToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.BlockSequenceStartToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.DirectiveToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.DocumentEndToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.DocumentStartToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.FlowEntryToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.FlowMappingEndToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.FlowMappingStartToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.FlowSequenceEndToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.FlowSequenceStartToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.KeyToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.ScalarToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.StreamEndToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.StreamStartToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.TagToken;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.TagTuple;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.Token;
import com.clubobsidian.obsidianengine.snakeyaml.tokens.ValueToken;
import com.clubobsidian.obsidianengine.snakeyaml.util.ArrayStack;
import com.clubobsidian.obsidianengine.snakeyaml.util.UriEncoder;
/**
* <pre>
* Scanner produces tokens of the following types:
* STREAM-START
* STREAM-END
* DIRECTIVE(name, value)
* DOCUMENT-START
* DOCUMENT-END
* BLOCK-SEQUENCE-START
* BLOCK-MAPPING-START
* BLOCK-END
* FLOW-SEQUENCE-START
* FLOW-MAPPING-START
* FLOW-SEQUENCE-END
* FLOW-MAPPING-END
* BLOCK-ENTRY
* FLOW-ENTRY
* KEY
* VALUE
* ALIAS(value)
* ANCHOR(value)
* TAG(value)
* SCALAR(value, plain, style)
* Read comments in the Scanner code for more details.
* </pre>
*/
public final class ScannerImpl implements Scanner {
/**
* A regular expression matching characters which are not in the hexadecimal
* set (0-9, A-F, a-f).
*/
private final static Pattern NOT_HEXA = Pattern.compile("[^0-9A-Fa-f]");
/**
* A mapping from an escaped character in the input stream to the character
* that they should be replaced with.
*
* YAML defines several common and a few uncommon escape sequences.
*
* @see <a href="http://www.yaml.org/spec/current.html#id2517668">4.1.6.
* Escape Sequences</a>
*/
public final static Map<Character, String> ESCAPE_REPLACEMENTS = new HashMap<Character, String>();
/**
* A mapping from a character to a number of bytes to read-ahead for that
* escape sequence. These escape sequences are used to handle unicode
* escaping in the following formats, where H is a hexadecimal character:
*
* <pre>
* \xHH : escaped 8-bit Unicode character
* \uHHHH : escaped 16-bit Unicode character
* \UHHHHHHHH : escaped 32-bit Unicode character
* </pre>
*
* @see <a href="http://yaml.org/spec/1.1/current.html#id872840">5.6. Escape
* Sequences</a>
*/
public final static Map<Character, Integer> ESCAPE_CODES = new HashMap<Character, Integer>();
static {
// ASCII null
ESCAPE_REPLACEMENTS.put(Character.valueOf('0'), "\0");
// ASCII bell
ESCAPE_REPLACEMENTS.put(Character.valueOf('a'), "\u0007");
// ASCII backspace
ESCAPE_REPLACEMENTS.put(Character.valueOf('b'), "\u0008");
// ASCII horizontal tab
ESCAPE_REPLACEMENTS.put(Character.valueOf('t'), "\u0009");
// ASCII newline (line feed; \n maps to 0x0A)
ESCAPE_REPLACEMENTS.put(Character.valueOf('n'), "\n");
// ASCII vertical tab
ESCAPE_REPLACEMENTS.put(Character.valueOf('v'), "\u000B");
// ASCII form-feed
ESCAPE_REPLACEMENTS.put(Character.valueOf('f'), "\u000C");
// carriage-return (\r maps to 0x0D)
ESCAPE_REPLACEMENTS.put(Character.valueOf('r'), "\r");
// ASCII escape character (Esc)
ESCAPE_REPLACEMENTS.put(Character.valueOf('e'), "\u001B");
// ASCII space
ESCAPE_REPLACEMENTS.put(Character.valueOf(' '), "\u0020");
// ASCII double-quote
ESCAPE_REPLACEMENTS.put(Character.valueOf('"'), "\"");
// ASCII backslash
ESCAPE_REPLACEMENTS.put(Character.valueOf('\\'), "\\");
// Unicode next line
ESCAPE_REPLACEMENTS.put(Character.valueOf('N'), "\u0085");
// Unicode non-breaking-space
ESCAPE_REPLACEMENTS.put(Character.valueOf('_'), "\u00A0");
// Unicode line-separator
ESCAPE_REPLACEMENTS.put(Character.valueOf('L'), "\u2028");
// Unicode paragraph separator
ESCAPE_REPLACEMENTS.put(Character.valueOf('P'), "\u2029");
// 8-bit Unicode
ESCAPE_CODES.put(Character.valueOf('x'), 2);
// 16-bit Unicode
ESCAPE_CODES.put(Character.valueOf('u'), 4);
// 32-bit Unicode (Supplementary characters are supported)
ESCAPE_CODES.put(Character.valueOf('U'), 8);
}
private final StreamReader reader;
// Had we reached the end of the stream?
private boolean done = false;
// The number of unclosed '{' and '['. `flow_level == 0` means block
// context.
private int flowLevel = 0;
// List of processed tokens that are not yet emitted.
private List<Token> tokens;
// Number of tokens that were emitted through the `get_token` method.
private int tokensTaken = 0;
// The current indentation level.
private int indent = -1;
// Past indentation levels.
private ArrayStack<Integer> indents;
// Variables related to simple keys treatment. See PyYAML.
/**
* <pre>
* A simple key is a key that is not denoted by the '?' indicator.
* Example of simple keys:
* ---
* block simple key: value
* ? not a simple key:
* : { flow simple key: value }
* We emit the KEY token before all keys, so when we find a potential
* simple key, we try to locate the corresponding ':' indicator.
* Simple keys should be limited to a single line and 1024 characters.
*
* Can a simple key start at the current position? A simple key may
* start:
* - at the beginning of the line, not counting indentation spaces
* (in block context),
* - after '{', '[', ',' (in the flow context),
* - after '?', ':', '-' (in the block context).
* In the block context, this flag also signifies if a block collection
* may start at the current position.
* </pre>
*/
private boolean allowSimpleKey = true;
/*
* Keep track of possible simple keys. This is a dictionary. The key is
* `flow_level`; there can be no more that one possible simple key for each
* level. The value is a SimpleKey record: (token_number, required, index,
* line, column, mark) A simple key may start with ALIAS, ANCHOR, TAG,
* SCALAR(flow), '[', or '{' tokens.
*/
private Map<Integer, SimpleKey> possibleSimpleKeys;
public ScannerImpl(StreamReader reader) {
this.reader = reader;
this.tokens = new ArrayList<Token>(100);
this.indents = new ArrayStack<Integer>(10);
// The order in possibleSimpleKeys is kept for nextPossibleSimpleKey()
this.possibleSimpleKeys = new LinkedHashMap<Integer, SimpleKey>();
fetchStreamStart();// Add the STREAM-START token.
}
/**
* Check whether the next token is one of the given types.
*/
public boolean checkToken(Token.ID... choices) {
while (needMoreTokens()) {
fetchMoreTokens();
}
if (!this.tokens.isEmpty()) {
if (choices.length == 0) {
return true;
}
// since profiler puts this method on top (it is used a lot), we
// should not use 'foreach' here because of the performance reasons
Token.ID first = this.tokens.get(0).getTokenId();
for (int i = 0; i < choices.length; i++) {
if (first == choices[i]) {
return true;
}
}
}
return false;
}
/**
* Return the next token, but do not delete it from the queue.
*/
public Token peekToken() {
while (needMoreTokens()) {
fetchMoreTokens();
}
return this.tokens.get(0);
}
/**
* Return the next token, removing it from the queue.
*/
public Token getToken() {
if (!this.tokens.isEmpty()) {
this.tokensTaken++;
return this.tokens.remove(0);
}
return null;
}
// Private methods.
/**
* Returns true if more tokens should be scanned.
*/
private boolean needMoreTokens() {
// If we are done, we do not require more tokens.
if (this.done) {
return false;
}
// If we aren't done, but we have no tokens, we need to scan more.
if (this.tokens.isEmpty()) {
return true;
}
// The current token may be a potential simple key, so we
// need to look further.
stalePossibleSimpleKeys();
return nextPossibleSimpleKey() == this.tokensTaken;
}
/**
* Fetch one or more tokens from the StreamReader.
*/
private void fetchMoreTokens() {
// Eat whitespaces and comments until we reach the next token.
scanToNextToken();
// Remove obsolete possible simple keys.
stalePossibleSimpleKeys();
// Compare the current indentation and column. It may add some tokens
// and decrease the current indentation level.
unwindIndent(reader.getColumn());
// Peek the next character, to decide what the next group of tokens
// will look like.
char ch = reader.peek();
switch (ch) {
case '\0':
// Is it the end of stream?
fetchStreamEnd();
return;
case '%':
// Is it a directive?
if (checkDirective()) {
fetchDirective();
return;
}
break;
case '-':
// Is it the document start?
if (checkDocumentStart()) {
fetchDocumentStart();
return;
// Is it the block entry indicator?
} else if (checkBlockEntry()) {
fetchBlockEntry();
return;
}
break;
case '.':
// Is it the document end?
if (checkDocumentEnd()) {
fetchDocumentEnd();
return;
}
break;
// TODO support for BOM within a stream. (not implemented in PyYAML)
case '[':
// Is it the flow sequence start indicator?
fetchFlowSequenceStart();
return;
case '{':
// Is it the flow mapping start indicator?
fetchFlowMappingStart();
return;
case ']':
// Is it the flow sequence end indicator?
fetchFlowSequenceEnd();
return;
case '}':
// Is it the flow mapping end indicator?
fetchFlowMappingEnd();
return;
case ',':
// Is it the flow entry indicator?
fetchFlowEntry();
return;
// see block entry indicator above
case '?':
// Is it the key indicator?
if (checkKey()) {
fetchKey();
return;
}
break;
case ':':
// Is it the value indicator?
if (checkValue()) {
fetchValue();
return;
}
break;
case '*':
// Is it an alias?
fetchAlias();
return;
case '&':
// Is it an anchor?
fetchAnchor();
return;
case '!':
// Is it a tag?
fetchTag();
return;
case '|':
// Is it a literal scalar?
if (this.flowLevel == 0) {
fetchLiteral();
return;
}
break;
case '>':
// Is it a folded scalar?
if (this.flowLevel == 0) {
fetchFolded();
return;
}
break;
case '\'':
// Is it a single quoted scalar?
fetchSingle();
return;
case '"':
// Is it a double quoted scalar?
fetchDouble();
return;
}
// It must be a plain scalar then.
if (checkPlain()) {
fetchPlain();
return;
}
// No? It's an error. Let's produce a nice error message.We do this by
// converting escaped characters into their escape sequences. This is a
// backwards use of the ESCAPE_REPLACEMENTS map.
String chRepresentation = String.valueOf(ch);
for (Character s : ESCAPE_REPLACEMENTS.keySet()) {
String v = ESCAPE_REPLACEMENTS.get(s);
if (v.equals(chRepresentation)) {
chRepresentation = "\\" + s;// ' ' -> '\t'
break;
}
}
if (ch == '\t')
chRepresentation += "(TAB)";
String text = String
.format("found character '%s' that cannot start any token. (Do not use %s for indentation)",
chRepresentation, chRepresentation);
throw new ScannerException("while scanning for the next token", null, text,
reader.getMark());
}
// Simple keys treatment.
/**
* Return the number of the nearest possible simple key. Actually we don't
* need to loop through the whole dictionary.
*/
private int nextPossibleSimpleKey() {
/*
* the implementation is not as in PyYAML. Because
* this.possibleSimpleKeys is ordered we can simply take the first key
*/
if (!this.possibleSimpleKeys.isEmpty()) {
return this.possibleSimpleKeys.values().iterator().next().getTokenNumber();
}
return -1;
}
/**
* <pre>
* Remove entries that are no longer possible simple keys. According to
* the YAML specification, simple keys
* - should be limited to a single line,
* - should be no longer than 1024 characters.
* Disabling this procedure will allow simple keys of any length and
* height (may cause problems if indentation is broken though).
* </pre>
*/
private void stalePossibleSimpleKeys() {
if (!this.possibleSimpleKeys.isEmpty()) {
for (Iterator<SimpleKey> iterator = this.possibleSimpleKeys.values().iterator(); iterator
.hasNext();) {
SimpleKey key = iterator.next();
if ((key.getLine() != reader.getLine())
|| (reader.getIndex() - key.getIndex() > 1024)) {
// If the key is not on the same line as the current
// position OR the difference in column between the token
// start and the current position is more than the maximum
// simple key length, then this cannot be a simple key.
if (key.isRequired()) {
// If the key was required, this implies an error
// condition.
throw new ScannerException("while scanning a simple key", key.getMark(),
"could not find expected ':'", reader.getMark());
}
iterator.remove();
}
}
}
}
/**
* The next token may start a simple key. We check if it's possible and save
* its position. This function is called for ALIAS, ANCHOR, TAG,
* SCALAR(flow), '[', and '{'.
*/
private void savePossibleSimpleKey() {
// The next token may start a simple key. We check if it's possible
// and save its position. This function is called for
// ALIAS, ANCHOR, TAG, SCALAR(flow), '[', and '{'.
// Check if a simple key is required at the current position.
// A simple key is required if this position is the root flowLevel, AND
// the current indentation level is the same as the last indent-level.
boolean required = (this.flowLevel == 0) && (this.indent == this.reader.getColumn());
if (allowSimpleKey || !required) {
// A simple key is required only if it is the first token in the
// current line. Therefore it is always allowed.
} else {
throw new YAMLException(
"A simple key is required only if it is the first token in the current line");
}
// The next token might be a simple key. Let's save it's number and
// position.
if (this.allowSimpleKey) {
removePossibleSimpleKey();
int tokenNumber = this.tokensTaken + this.tokens.size();
SimpleKey key = new SimpleKey(tokenNumber, required, reader.getIndex(),
reader.getLine(), this.reader.getColumn(), this.reader.getMark());
this.possibleSimpleKeys.put(this.flowLevel, key);
}
}
/**
* Remove the saved possible key position at the current flow level.
*/
private void removePossibleSimpleKey() {
SimpleKey key = possibleSimpleKeys.remove(flowLevel);
if (key != null && key.isRequired()) {
throw new ScannerException("while scanning a simple key", key.getMark(),
"could not find expected ':'", reader.getMark());
}
}
// Indentation functions.
/**
* * Handle implicitly ending multiple levels of block nodes by decreased
* indentation. This function becomes important on lines 4 and 7 of this
* example:
*
* <pre>
* 1) book one:
* 2) part one:
* 3) chapter one
* 4) part two:
* 5) chapter one
* 6) chapter two
* 7) book two:
* </pre>
*
* In flow context, tokens should respect indentation. Actually the
* condition should be `self.indent >= column` according to the spec. But
* this condition will prohibit intuitively correct constructions such as
* key : { } </pre>
*/
private void unwindIndent(int col) {
// In the flow context, indentation is ignored. We make the scanner less
// restrictive then specification requires.
if (this.flowLevel != 0) {
return;
}
// In block context, we may need to issue the BLOCK-END tokens.
while (this.indent > col) {
Mark mark = reader.getMark();
this.indent = this.indents.pop();
this.tokens.add(new BlockEndToken(mark, mark));
}
}
/**
* Check if we need to increase indentation.
*/
private boolean addIndent(int column) {
if (this.indent < column) {
this.indents.push(this.indent);
this.indent = column;
return true;
}
return false;
}
// Fetchers.
/**
* We always add STREAM-START as the first token and STREAM-END as the last
* token.
*/
private void fetchStreamStart() {
// Read the token.
Mark mark = reader.getMark();
// Add STREAM-START.
Token token = new StreamStartToken(mark, mark);
this.tokens.add(token);
}
private void fetchStreamEnd() {
// Set the current intendation to -1.
unwindIndent(-1);
// Reset simple keys.
removePossibleSimpleKey();
this.allowSimpleKey = false;
this.possibleSimpleKeys.clear();
// Read the token.
Mark mark = reader.getMark();
// Add STREAM-END.
Token token = new StreamEndToken(mark, mark);
this.tokens.add(token);
// The stream is finished.
this.done = true;
}
/**
* Fetch a YAML directive. Directives are presentation details that are
* interpreted as instructions to the processor. YAML defines two kinds of
* directives, YAML and TAG; all other types are reserved for future use.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id864824"></a>
*/
private void fetchDirective() {
// Set the current intendation to -1.
unwindIndent(-1);
// Reset simple keys.
removePossibleSimpleKey();
this.allowSimpleKey = false;
// Scan and add DIRECTIVE.
Token tok = scanDirective();
this.tokens.add(tok);
}
/**
* Fetch a document-start token ("---").
*/
private void fetchDocumentStart() {
fetchDocumentIndicator(true);
}
/**
* Fetch a document-end token ("...").
*/
private void fetchDocumentEnd() {
fetchDocumentIndicator(false);
}
/**
* Fetch a document indicator, either "---" for "document-start", or else
* "..." for "document-end. The type is chosen by the given boolean.
*/
private void fetchDocumentIndicator(boolean isDocumentStart) {
// Set the current intendation to -1.
unwindIndent(-1);
// Reset simple keys. Note that there could not be a block collection
// after '---'.
removePossibleSimpleKey();
this.allowSimpleKey = false;
// Add DOCUMENT-START or DOCUMENT-END.
Mark startMark = reader.getMark();
reader.forward(3);
Mark endMark = reader.getMark();
Token token;
if (isDocumentStart) {
token = new DocumentStartToken(startMark, endMark);
} else {
token = new DocumentEndToken(startMark, endMark);
}
this.tokens.add(token);
}
private void fetchFlowSequenceStart() {
fetchFlowCollectionStart(false);
}
private void fetchFlowMappingStart() {
fetchFlowCollectionStart(true);
}
/**
* Fetch a flow-style collection start, which is either a sequence or a
* mapping. The type is determined by the given boolean.
*
* A flow-style collection is in a format similar to JSON. Sequences are
* started by '[' and ended by ']'; mappings are started by '{' and ended by
* '}'.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*
* @param isMappingStart
*/
private void fetchFlowCollectionStart(boolean isMappingStart) {
// '[' and '{' may start a simple key.
savePossibleSimpleKey();
// Increase the flow level.
this.flowLevel++;
// Simple keys are allowed after '[' and '{'.
this.allowSimpleKey = true;
// Add FLOW-SEQUENCE-START or FLOW-MAPPING-START.
Mark startMark = reader.getMark();
reader.forward(1);
Mark endMark = reader.getMark();
Token token;
if (isMappingStart) {
token = new FlowMappingStartToken(startMark, endMark);
} else {
token = new FlowSequenceStartToken(startMark, endMark);
}
this.tokens.add(token);
}
private void fetchFlowSequenceEnd() {
fetchFlowCollectionEnd(false);
}
private void fetchFlowMappingEnd() {
fetchFlowCollectionEnd(true);
}
/**
* Fetch a flow-style collection end, which is either a sequence or a
* mapping. The type is determined by the given boolean.
*
* A flow-style collection is in a format similar to JSON. Sequences are
* started by '[' and ended by ']'; mappings are started by '{' and ended by
* '}'.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchFlowCollectionEnd(boolean isMappingEnd) {
// Reset possible simple key on the current level.
removePossibleSimpleKey();
// Decrease the flow level.
this.flowLevel--;
// No simple keys after ']' or '}'.
this.allowSimpleKey = false;
// Add FLOW-SEQUENCE-END or FLOW-MAPPING-END.
Mark startMark = reader.getMark();
reader.forward();
Mark endMark = reader.getMark();
Token token;
if (isMappingEnd) {
token = new FlowMappingEndToken(startMark, endMark);
} else {
token = new FlowSequenceEndToken(startMark, endMark);
}
this.tokens.add(token);
}
/**
* Fetch an entry in the flow style. Flow-style entries occur either
* immediately after the start of a collection, or else after a comma.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchFlowEntry() {
// Simple keys are allowed after ','.
this.allowSimpleKey = true;
// Reset possible simple key on the current level.
removePossibleSimpleKey();
// Add FLOW-ENTRY.
Mark startMark = reader.getMark();
reader.forward();
Mark endMark = reader.getMark();
Token token = new FlowEntryToken(startMark, endMark);
this.tokens.add(token);
}
/**
* Fetch an entry in the block style.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchBlockEntry() {
// Block context needs additional checks.
if (this.flowLevel == 0) {
// Are we allowed to start a new entry?
if (!this.allowSimpleKey) {
throw new ScannerException(null, null, "sequence entries are not allowed here",
reader.getMark());
}
// We may need to add BLOCK-SEQUENCE-START.
if (addIndent(this.reader.getColumn())) {
Mark mark = reader.getMark();
this.tokens.add(new BlockSequenceStartToken(mark, mark));
}
} else {
// It's an error for the block entry to occur in the flow
// context,but we let the parser detect this.
}
// Simple keys are allowed after '-'.
this.allowSimpleKey = true;
// Reset possible simple key on the current level.
removePossibleSimpleKey();
// Add BLOCK-ENTRY.
Mark startMark = reader.getMark();
reader.forward();
Mark endMark = reader.getMark();
Token token = new BlockEntryToken(startMark, endMark);
this.tokens.add(token);
}
/**
* Fetch a key in a block-style mapping.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchKey() {
// Block context needs additional checks.
if (this.flowLevel == 0) {
// Are we allowed to start a key (not necessary a simple)?
if (!this.allowSimpleKey) {
throw new ScannerException(null, null, "mapping keys are not allowed here",
reader.getMark());
}
// We may need to add BLOCK-MAPPING-START.
if (addIndent(this.reader.getColumn())) {
Mark mark = reader.getMark();
this.tokens.add(new BlockMappingStartToken(mark, mark));
}
}
// Simple keys are allowed after '?' in the block context.
this.allowSimpleKey = this.flowLevel == 0;
// Reset possible simple key on the current level.
removePossibleSimpleKey();
// Add KEY.
Mark startMark = reader.getMark();
reader.forward();
Mark endMark = reader.getMark();
Token token = new KeyToken(startMark, endMark);
this.tokens.add(token);
}
/**
* Fetch a value in a block-style mapping.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchValue() {
// Do we determine a simple key?
SimpleKey key = this.possibleSimpleKeys.remove(this.flowLevel);
if (key != null) {
// Add KEY.
this.tokens.add(key.getTokenNumber() - this.tokensTaken, new KeyToken(key.getMark(),
key.getMark()));
// If this key starts a new block mapping, we need to add
// BLOCK-MAPPING-START.
if (this.flowLevel == 0) {
if (addIndent(key.getColumn())) {
this.tokens.add(key.getTokenNumber() - this.tokensTaken,
new BlockMappingStartToken(key.getMark(), key.getMark()));
}
}
// There cannot be two simple keys one after another.
this.allowSimpleKey = false;
} else {
// It must be a part of a complex key.
// Block context needs additional checks. Do we really need them?
// They will be caught by the parser anyway.
if (this.flowLevel == 0) {
// We are allowed to start a complex value if and only if we can
// start a simple key.
if (!this.allowSimpleKey) {
throw new ScannerException(null, null, "mapping values are not allowed here",
reader.getMark());
}
}
// If this value starts a new block mapping, we need to add
// BLOCK-MAPPING-START. It will be detected as an error later by
// the parser.
if (flowLevel == 0) {
if (addIndent(reader.getColumn())) {
Mark mark = reader.getMark();
this.tokens.add(new BlockMappingStartToken(mark, mark));
}
}
// Simple keys are allowed after ':' in the block context.
allowSimpleKey = flowLevel == 0;
// Reset possible simple key on the current level.
removePossibleSimpleKey();
}
// Add VALUE.
Mark startMark = reader.getMark();
reader.forward();
Mark endMark = reader.getMark();
Token token = new ValueToken(startMark, endMark);
this.tokens.add(token);
}
/**
* Fetch an alias, which is a reference to an anchor. Aliases take the
* format:
*
* <pre>
* *(anchor name)
* </pre>
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863390"></a>
*/
private void fetchAlias() {
// ALIAS could be a simple key.
savePossibleSimpleKey();
// No simple keys after ALIAS.
this.allowSimpleKey = false;
// Scan and add ALIAS.
Token tok = scanAnchor(false);
this.tokens.add(tok);
}
/**
* Fetch an anchor. Anchors take the form:
*
* <pre>
* &(anchor name)
* </pre>
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863390"></a>
*/
private void fetchAnchor() {
// ANCHOR could start a simple key.
savePossibleSimpleKey();
// No simple keys after ANCHOR.
this.allowSimpleKey = false;
// Scan and add ANCHOR.
Token tok = scanAnchor(true);
this.tokens.add(tok);
}
/**
* Fetch a tag. Tags take a complex form.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id861700"></a>
*/
private void fetchTag() {
// TAG could start a simple key.
savePossibleSimpleKey();
// No simple keys after TAG.
this.allowSimpleKey = false;
// Scan and add TAG.
Token tok = scanTag();
this.tokens.add(tok);
}
/**
* Fetch a literal scalar, denoted with a vertical-bar. This is the type
* best used for source code and other content, such as binary data, which
* must be included verbatim.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchLiteral() {
fetchBlockScalar('|');
}
/**
* Fetch a folded scalar, denoted with a greater-than sign. This is the type
* best used for long content, such as the text of a chapter or description.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*/
private void fetchFolded() {
fetchBlockScalar('>');
}
/**
* Fetch a block scalar (literal or folded).
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*
* @param style
*/
private void fetchBlockScalar(char style) {
// A simple key may follow a block scalar.
this.allowSimpleKey = true;
// Reset possible simple key on the current level.
removePossibleSimpleKey();
// Scan and add SCALAR.
Token tok = scanBlockScalar(style);
this.tokens.add(tok);
}
/**
* Fetch a single-quoted (') scalar.
*/
private void fetchSingle() {
fetchFlowScalar('\'');
}
/**
* Fetch a double-quoted (") scalar.
*/
private void fetchDouble() {
fetchFlowScalar('"');
}
/**
* Fetch a flow scalar (single- or double-quoted).
*
* @see <a href="http://www.yaml.org/spec/1.1/#id863975"></a>
*
* @param style
*/
private void fetchFlowScalar(char style) {
// A flow scalar could be a simple key.
savePossibleSimpleKey();
// No simple keys after flow scalars.
this.allowSimpleKey = false;
// Scan and add SCALAR.
Token tok = scanFlowScalar(style);
this.tokens.add(tok);
}
/**
* Fetch a plain scalar.
*/
private void fetchPlain() {
// A plain scalar could be a simple key.
savePossibleSimpleKey();
// No simple keys after plain scalars. But note that `scan_plain` will
// change this flag if the scan is finished at the beginning of the
// line.
this.allowSimpleKey = false;
// Scan and add SCALAR. May change `allow_simple_key`.
Token tok = scanPlain();
this.tokens.add(tok);
}
// Checkers.
/**
* Returns true if the next thing on the reader is a directive, given that
* the leading '%' has already been checked.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id864824"></a>
*/
private boolean checkDirective() {
// DIRECTIVE: ^ '%' ...
// The '%' indicator is already checked.
return reader.getColumn() == 0;
}
/**
* Returns true if the next thing on the reader is a document-start ("---").
* A document-start is always followed immediately by a new line.
*/
private boolean checkDocumentStart() {
// DOCUMENT-START: ^ '---' (' '|'\n')
if (reader.getColumn() == 0) {
if ("---".equals(reader.prefix(3)) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
return true;
}
}
return false;
}
/**
* Returns true if the next thing on the reader is a document-end ("..."). A
* document-end is always followed immediately by a new line.
*/
private boolean checkDocumentEnd() {
// DOCUMENT-END: ^ '...' (' '|'\n')
if (reader.getColumn() == 0) {
if ("...".equals(reader.prefix(3)) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
return true;
}
}
return false;
}
/**
* Returns true if the next thing on the reader is a block token.
*/
private boolean checkBlockEntry() {
// BLOCK-ENTRY: '-' (' '|'\n')
return Constant.NULL_BL_T_LINEBR.has(reader.peek(1));
}
/**
* Returns true if the next thing on the reader is a key token.
*/
private boolean checkKey() {
// KEY(flow context): '?'
if (this.flowLevel != 0) {
return true;
} else {
// KEY(block context): '?' (' '|'\n')
return Constant.NULL_BL_T_LINEBR.has(reader.peek(1));
}
}
/**
* Returns true if the next thing on the reader is a value token.
*/
private boolean checkValue() {
// VALUE(flow context): ':'
if (flowLevel != 0) {
return true;
} else {
// VALUE(block context): ':' (' '|'\n')
return Constant.NULL_BL_T_LINEBR.has(reader.peek(1));
}
}
/**
* Returns true if the next thing on the reader is a plain token.
*/
private boolean checkPlain() {
/**
* <pre>
* A plain scalar may start with any non-space character except:
* '-', '?', ':', ',', '[', ']', '{', '}',
* '#', '&', '*', '!', '|', '>', '\'', '\"',
* '%', '@', '`'.
*
* It may also start with
* '-', '?', ':'
* if it is followed by a non-space character.
*
* Note that we limit the last rule to the block context (except the
* '-' character) because we want the flow context to be space
* independent.
* </pre>
*/
char ch = reader.peek();
// If the next char is NOT one of the forbidden chars above or
// whitespace, then this is the start of a plain scalar.
return Constant.NULL_BL_T_LINEBR.hasNo(ch, "-?:,[]{}#&*!|>\'\"%@`")
|| (Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(1)) && (ch == '-' || (this.flowLevel == 0 && "?:"
.indexOf(ch) != -1)));
}
// Scanners.
/**
* <pre>
* We ignore spaces, line breaks and comments.
* If we find a line break in the block context, we set the flag
* `allow_simple_key` on.
* The byte order mark is stripped if it's the first character in the
* stream. We do not yet support BOM inside the stream as the
* specification requires. Any such mark will be considered as a part
* of the document.
* TODO: We need to make tab handling rules more sane. A good rule is
* Tabs cannot precede tokens
* BLOCK-SEQUENCE-START, BLOCK-MAPPING-START, BLOCK-END,
* KEY(block), VALUE(block), BLOCK-ENTRY
* So the checking code is
* if <TAB>:
* self.allow_simple_keys = False
* We also need to add the check for `allow_simple_keys == True` to
* `unwind_indent` before issuing BLOCK-END.
* Scanners for block, flow, and plain scalars need to be modified.
* </pre>
*/
private void scanToNextToken() {
// If there is a byte order mark (BOM) at the beginning of the stream,
// forward past it.
if (reader.getIndex() == 0 && reader.peek() == '\uFEFF') {
reader.forward();
}
boolean found = false;
while (!found) {
int ff = 0;
// Peek ahead until we find the first non-space character, then
// move forward directly to that character.
while (reader.peek(ff) == ' ') {
ff++;
}
if (ff > 0) {
reader.forward(ff);
}
// If the character we have skipped forward to is a comment (#),
// then peek ahead until we find the next end of line. YAML
// comments are from a # to the next new-line. We then forward
// past the comment.
if (reader.peek() == '#') {
ff = 0;
while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) {
ff++;
}
if (ff > 0) {
reader.forward(ff);
}
}
// If we scanned a line break, then (depending on flow level),
// simple keys may be allowed.
if (scanLineBreak().length() != 0) {// found a line-break
if (this.flowLevel == 0) {
// Simple keys are allowed at flow-level 0 after a line
// break
this.allowSimpleKey = true;
}
} else {
found = true;
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Token scanDirective() {
// See the specification for details.
Mark startMark = reader.getMark();
Mark endMark;
reader.forward();
String name = scanDirectiveName(startMark);
List<?> value = null;
if ("YAML".equals(name)) {
value = scanYamlDirectiveValue(startMark);
endMark = reader.getMark();
} else if ("TAG".equals(name)) {
value = scanTagDirectiveValue(startMark);
endMark = reader.getMark();
} else {
endMark = reader.getMark();
int ff = 0;
while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) {
ff++;
}
if (ff > 0) {
reader.forward(ff);
}
}
scanDirectiveIgnoredLine(startMark);
return new DirectiveToken(name, value, startMark, endMark);
}
/**
* Scan a directive name. Directive names are a series of non-space
* characters.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id895217"></a>
*/
private String scanDirectiveName(Mark startMark) {
// See the specification for details.
int length = 0;
// A Directive-name is a sequence of alphanumeric characters
// (a-z,A-Z,0-9). We scan until we find something that isn't.
// FIXME this disagrees with the specification.
char ch = reader.peek(length);
while (Constant.ALPHA.has(ch)) {
length++;
ch = reader.peek(length);
}
// If the name would be empty, an error occurs.
if (length == 0) {
throw new ScannerException("while scanning a directive", startMark,
"expected alphabetic or numeric character, but found " + ch + "(" + ((int) ch)
+ ")", reader.getMark());
}
String value = reader.prefixForward(length);
ch = reader.peek();
if (Constant.NULL_BL_LINEBR.hasNo(ch)) {
throw new ScannerException("while scanning a directive", startMark,
"expected alphabetic or numeric character, but found " + ch + "(" + ((int) ch)
+ ")", reader.getMark());
}
return value;
}
private List<Integer> scanYamlDirectiveValue(Mark startMark) {
// See the specification for details.
while (reader.peek() == ' ') {
reader.forward();
}
Integer major = scanYamlDirectiveNumber(startMark);
if (reader.peek() != '.') {
throw new ScannerException("while scanning a directive", startMark,
"expected a digit or '.', but found " + reader.peek() + "("
+ ((int) reader.peek()) + ")", reader.getMark());
}
reader.forward();
Integer minor = scanYamlDirectiveNumber(startMark);
if (Constant.NULL_BL_LINEBR.hasNo(reader.peek())) {
throw new ScannerException("while scanning a directive", startMark,
"expected a digit or ' ', but found " + reader.peek() + "("
+ ((int) reader.peek()) + ")", reader.getMark());
}
List<Integer> result = new ArrayList<Integer>(2);
result.add(major);
result.add(minor);
return result;
}
/**
* Read a %YAML directive number: this is either the major or the minor
* part. Stop reading at a non-digit character (usually either '.' or '\n').
*
* @see <a href="http://www.yaml.org/spec/1.1/#id895631"></a>
* @see <a href="http://www.yaml.org/spec/1.1/#ns-dec-digit"></a>
*/
private Integer scanYamlDirectiveNumber(Mark startMark) {
// See the specification for details.
char ch = reader.peek();
if (!Character.isDigit(ch)) {
throw new ScannerException("while scanning a directive", startMark,
"expected a digit, but found " + ch + "(" + ((int) ch) + ")", reader.getMark());
}
int length = 0;
while (Character.isDigit(reader.peek(length))) {
length++;
}
Integer value = Integer.parseInt(reader.prefixForward(length));
return value;
}
/**
* <p>
* Read a %TAG directive value:
*
* <pre>
* s-ignored-space+ c-tag-handle s-ignored-space+ ns-tag-prefix s-l-comments
* </pre>
*
* </p>
*
* @see <a href="http://www.yaml.org/spec/1.1/#id896044"></a>
*/
private List<String> scanTagDirectiveValue(Mark startMark) {
// See the specification for details.
while (reader.peek() == ' ') {
reader.forward();
}
String handle = scanTagDirectiveHandle(startMark);
while (reader.peek() == ' ') {
reader.forward();
}
String prefix = scanTagDirectivePrefix(startMark);
List<String> result = new ArrayList<String>(2);
result.add(handle);
result.add(prefix);
return result;
}
/**
* Scan a %TAG directive's handle. This is YAML's c-tag-handle.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id896876"></a>
* @param startMark
* @return
*/
private String scanTagDirectiveHandle(Mark startMark) {
// See the specification for details.
String value = scanTagHandle("directive", startMark);
char ch = reader.peek();
if (ch != ' ') {
throw new ScannerException("while scanning a directive", startMark,
"expected ' ', but found " + reader.peek() + "(" + ch + ")", reader.getMark());
}
return value;
}
/**
* Scan a %TAG directive's prefix. This is YAML's ns-tag-prefix.
*
* @see <a href="http://www.yaml.org/spec/1.1/#ns-tag-prefix"></a>
*/
private String scanTagDirectivePrefix(Mark startMark) {
// See the specification for details.
String value = scanTagUri("directive", startMark);
if (Constant.NULL_BL_LINEBR.hasNo(reader.peek())) {
throw new ScannerException("while scanning a directive", startMark,
"expected ' ', but found " + reader.peek() + "(" + ((int) reader.peek()) + ")",
reader.getMark());
}
return value;
}
private String scanDirectiveIgnoredLine(Mark startMark) {
// See the specification for details.
int ff = 0;
while (reader.peek(ff) == ' ') {
ff++;
}
if (ff > 0) {
reader.forward(ff);
}
if (reader.peek() == '#') {
ff = 0;
while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) {
ff++;
}
reader.forward(ff);
}
char ch = reader.peek();
String lineBreak = scanLineBreak();
if (lineBreak.length() == 0 && ch != '\0') {
throw new ScannerException("while scanning a directive", startMark,
"expected a comment or a line break, but found " + ch + "(" + ((int) ch) + ")",
reader.getMark());
}
return lineBreak;
}
/**
* <pre>
* The specification does not restrict characters for anchors and
* aliases. This may lead to problems, for instance, the document:
* [ *alias, value ]
* can be interpreted in two ways, as
* [ "value" ]
* and
* [ *alias , "value" ]
* Therefore we restrict aliases to numbers and ASCII letters.
* </pre>
*/
private Token scanAnchor(boolean isAnchor) {
Mark startMark = reader.getMark();
char indicator = reader.peek();
String name = indicator == '*' ? "alias" : "anchor";
reader.forward();
int length = 0;
char ch = reader.peek(length);
while (Constant.ALPHA.has(ch)) {
length++;
ch = reader.peek(length);
}
if (length == 0) {
throw new ScannerException("while scanning an " + name, startMark,
"expected alphabetic or numeric character, but found " + ch,
reader.getMark());
}
String value = reader.prefixForward(length);
ch = reader.peek();
if (Constant.NULL_BL_T_LINEBR.hasNo(ch, "?:,]}%@`")) {
throw new ScannerException("while scanning an " + name, startMark,
"expected alphabetic or numeric character, but found " + ch + "("
+ ((int) reader.peek()) + ")", reader.getMark());
}
Mark endMark = reader.getMark();
Token tok;
if (isAnchor) {
tok = new AnchorToken(value, startMark, endMark);
} else {
tok = new AliasToken(value, startMark, endMark);
}
return tok;
}
/**
* <p>
* Scan a Tag property. A Tag property may be specified in one of three
* ways: c-verbatim-tag, c-ns-shorthand-tag, or c-ns-non-specific-tag
* </p>
*
* <p>
* c-verbatim-tag takes the form !<ns-uri-char+> and must be delivered
* verbatim (as-is) to the application. In particular, verbatim tags are not
* subject to tag resolution.
* </p>
*
* <p>
* c-ns-shorthand-tag is a valid tag handle followed by a non-empty suffix.
* If the tag handle is a c-primary-tag-handle ('!') then the suffix must
* have all exclamation marks properly URI-escaped (%21); otherwise, the
* string will look like a named tag handle: !foo!bar would be interpreted
* as (handle="!foo!", suffix="bar").
* </p>
*
* <p>
* c-ns-non-specific-tag is always a lone '!'; this is only useful for plain
* scalars, where its specification means that the scalar MUST be resolved
* to have type tag:yaml.org,2002:str.
* </p>
*
* TODO SnakeYaml incorrectly ignores c-ns-non-specific-tag right now.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id900262"></a>
*
* TODO Note that this method does not enforce rules about local versus
* global tags!
*/
private Token scanTag() {
// See the specification for details.
Mark startMark = reader.getMark();
// Determine the type of tag property based on the first character
// encountered
char ch = reader.peek(1);
String handle = null;
String suffix = null;
// Verbatim tag! (c-verbatim-tag)
if (ch == '<') {
// Skip the exclamation mark and >, then read the tag suffix (as
// a URI).
reader.forward(2);
suffix = scanTagUri("tag", startMark);
if (reader.peek() != '>') {
// If there are any characters between the end of the tag-suffix
// URI and the closing >, then an error has occurred.
throw new ScannerException("while scanning a tag", startMark,
"expected '>', but found '" + reader.peek() + "' (" + ((int) reader.peek())
+ ")", reader.getMark());
}
reader.forward();
} else if (Constant.NULL_BL_T_LINEBR.has(ch)) {
// A NUL, blank, tab, or line-break means that this was a
// c-ns-non-specific tag.
suffix = "!";
reader.forward();
} else {
// Any other character implies c-ns-shorthand-tag type.
// Look ahead in the stream to determine whether this tag property
// is of the form !foo or !foo!bar.
int length = 1;
boolean useHandle = false;
while (Constant.NULL_BL_LINEBR.hasNo(ch)) {
if (ch == '!') {
useHandle = true;
break;
}
length++;
ch = reader.peek(length);
}
handle = "!";
// If we need to use a handle, scan it in; otherwise, the handle is
// presumed to be '!'.
if (useHandle) {
handle = scanTagHandle("tag", startMark);
} else {
handle = "!";
reader.forward();
}
suffix = scanTagUri("tag", startMark);
}
ch = reader.peek();
// Check that the next character is allowed to follow a tag-property;
// if it is not, raise the error.
if (Constant.NULL_BL_LINEBR.hasNo(ch)) {
throw new ScannerException("while scanning a tag", startMark,
"expected ' ', but found '" + ch + "' (" + ((int) ch) + ")", reader.getMark());
}
TagTuple value = new TagTuple(handle, suffix);
Mark endMark = reader.getMark();
return new TagToken(value, startMark, endMark);
}
private Token scanBlockScalar(char style) {
// See the specification for details.
boolean folded;
// Depending on the given style, we determine whether the scalar is
// folded ('>') or literal ('|')
if (style == '>') {
folded = true;
} else {
folded = false;
}
StringBuilder chunks = new StringBuilder();
Mark startMark = reader.getMark();
// Scan the header.
reader.forward();
Chomping chompi = scanBlockScalarIndicators(startMark);
int increment = chompi.getIncrement();
scanBlockScalarIgnoredLine(startMark);
// Determine the indentation level and go to the first non-empty line.
int minIndent = this.indent + 1;
if (minIndent < 1) {
minIndent = 1;
}
String breaks = null;
int maxIndent = 0;
int indent = 0;
Mark endMark;
if (increment == -1) {
Object[] brme = scanBlockScalarIndentation();
breaks = (String) brme[0];
maxIndent = ((Integer) brme[1]).intValue();
endMark = (Mark) brme[2];
indent = Math.max(minIndent, maxIndent);
} else {
indent = minIndent + increment - 1;
Object[] brme = scanBlockScalarBreaks(indent);
breaks = (String) brme[0];
endMark = (Mark) brme[1];
}
String lineBreak = "";
// Scan the inner part of the block scalar.
while (this.reader.getColumn() == indent && reader.peek() != '\0') {
chunks.append(breaks);
boolean leadingNonSpace = " \t".indexOf(reader.peek()) == -1;
int length = 0;
while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(length))) {
length++;
}
chunks.append(reader.prefixForward(length));
lineBreak = scanLineBreak();
Object[] brme = scanBlockScalarBreaks(indent);
breaks = (String) brme[0];
endMark = (Mark) brme[1];
if (this.reader.getColumn() == indent && reader.peek() != '\0') {
// Unfortunately, folding rules are ambiguous.
//
// This is the folding according to the specification:
if (folded && "\n".equals(lineBreak) && leadingNonSpace
&& " \t".indexOf(reader.peek()) == -1) {
if (breaks.length() == 0) {
chunks.append(" ");
}
} else {
chunks.append(lineBreak);
}
// Clark Evans's interpretation (also in the spec examples) not
// imported from PyYAML
} else {
break;
}
}
// Chomp the tail.
if (chompi.chompTailIsNotFalse()) {
chunks.append(lineBreak);
}
if (chompi.chompTailIsTrue()) {
chunks.append(breaks);
}
// We are done.
return new ScalarToken(chunks.toString(), false, startMark, endMark, style);
}
/**
* Scan a block scalar indicator. The block scalar indicator includes two
* optional components, which may appear in either order.
*
* A block indentation indicator is a non-zero digit describing the
* indentation level of the block scalar to follow. This indentation is an
* additional number of spaces relative to the current indentation level.
*
* A block chomping indicator is a + or -, selecting the chomping mode away
* from the default (clip) to either -(strip) or +(keep).
*
* @see <a href="http://www.yaml.org/spec/1.1/#id868988"></a>
* @see <a href="http://www.yaml.org/spec/1.1/#id927035"></a>
* @see <a href="http://www.yaml.org/spec/1.1/#id927557"></a>
*/
private Chomping scanBlockScalarIndicators(Mark startMark) {
// See the specification for details.
Boolean chomping = null;
int increment = -1;
char ch = reader.peek();
if (ch == '-' || ch == '+') {
if (ch == '+') {
chomping = Boolean.TRUE;
} else {
chomping = Boolean.FALSE;
}
reader.forward();
ch = reader.peek();
if (Character.isDigit(ch)) {
increment = Integer.parseInt(String.valueOf(ch));
if (increment == 0) {
throw new ScannerException("while scanning a block scalar", startMark,
"expected indentation indicator in the range 1-9, but found 0",
reader.getMark());
}
reader.forward();
}
} else if (Character.isDigit(ch)) {
increment = Integer.parseInt(String.valueOf(ch));
if (increment == 0) {
throw new ScannerException("while scanning a block scalar", startMark,
"expected indentation indicator in the range 1-9, but found 0",
reader.getMark());
}
reader.forward();
ch = reader.peek();
if (ch == '-' || ch == '+') {
if (ch == '+') {
chomping = Boolean.TRUE;
} else {
chomping = Boolean.FALSE;
}
reader.forward();
}
}
ch = reader.peek();
if (Constant.NULL_BL_LINEBR.hasNo(ch)) {
throw new ScannerException("while scanning a block scalar", startMark,
"expected chomping or indentation indicators, but found " + ch,
reader.getMark());
}
return new Chomping(chomping, increment);
}
/**
* Scan to the end of the line after a block scalar has been scanned; the
* only things that are permitted at this time are comments and spaces.
*/
private String scanBlockScalarIgnoredLine(Mark startMark) {
// See the specification for details.
int ff = 0;
// Forward past any number of trailing spaces
while (reader.peek(ff) == ' ') {
ff++;
}
if (ff > 0) {
reader.forward(ff);
}
// If a comment occurs, scan to just before the end of line.
if (reader.peek() == '#') {
ff = 0;
while (Constant.NULL_OR_LINEBR.hasNo(reader.peek(ff))) {
ff++;
}
if (ff > 0) {
reader.forward(ff);
}
}
// If the next character is not a null or line break, an error has
// occurred.
char ch = reader.peek();
String lineBreak = scanLineBreak();
if (lineBreak.length() == 0 && ch != '\0') {
throw new ScannerException("while scanning a block scalar", startMark,
"expected a comment or a line break, but found " + ch, reader.getMark());
}
return lineBreak;
}
/**
* Scans for the indentation of a block scalar implicitly. This mechanism is
* used only if the block did not explicitly state an indentation to be
* used.
*
* @see <a href="http://www.yaml.org/spec/1.1/#id927035"></a>
*/
private Object[] scanBlockScalarIndentation() {
// See the specification for details.
StringBuilder chunks = new StringBuilder();
int maxIndent = 0;
Mark endMark = reader.getMark();
// Look ahead some number of lines until the first non-blank character
// occurs; the determined indentation will be the maximum number of
// leading spaces on any of these lines.
while (Constant.LINEBR.has(reader.peek(), " \r")) {
if (reader.peek() != ' ') {
// If the character isn't a space, it must be some kind of
// line-break; scan the line break and track it.
chunks.append(scanLineBreak());
endMark = reader.getMark();
} else {
// If the character is a space, move forward to the next
// character; if we surpass our previous maximum for indent
// level, update that too.
reader.forward();
if (this.reader.getColumn() > maxIndent) {
maxIndent = reader.getColumn();
}
}
}
// Pass several results back together.
return new Object[] { chunks.toString(), maxIndent, endMark };
}
private Object[] scanBlockScalarBreaks(int indent) {
// See the specification for details.
StringBuilder chunks = new StringBuilder();
Mark endMark = reader.getMark();
int ff = 0;
int col = this.reader.getColumn();
// Scan for up to the expected indentation-level of spaces, then move
// forward past that amount.
while (col < indent && reader.peek(ff) == ' ') {
ff++;
col++;
}
if (ff > 0) {
reader.forward(ff);
}
// Consume one or more line breaks followed by any amount of spaces,
// until we find something that isn't a line-break.
String lineBreak = null;
while ((lineBreak = scanLineBreak()).length() != 0) {
chunks.append(lineBreak);
endMark = reader.getMark();
// Scan past up to (indent) spaces on the next line, then forward
// past them.
ff = 0;
col = this.reader.getColumn();
while (col < indent && reader.peek(ff) == ' ') {
ff++;
col++;
}
if (ff > 0) {
reader.forward(ff);
}
}
// Return both the assembled intervening string and the end-mark.
return new Object[] { chunks.toString(), endMark };
}
/**
* Scan a flow-style scalar. Flow scalars are presented in one of two forms;
* first, a flow scalar may be a double-quoted string; second, a flow scalar
* may be a single-quoted string.
*
* @see <a href="http://www.yaml.org/spec/1.1/#flow"></a> style/syntax
*
* <pre>
* See the specification for details.
* Note that we loose indentation rules for quoted scalars. Quoted
* scalars don't need to adhere indentation because " and ' clearly
* mark the beginning and the end of them. Therefore we are less
* restrictive then the specification requires. We only need to check
* that document separators are not included in scalars.
* </pre>
*/
private Token scanFlowScalar(char style) {
boolean _double;
// The style will be either single- or double-quoted; we determine this
// by the first character in the entry (supplied)
if (style == '"') {
_double = true;
} else {
_double = false;
}
StringBuilder chunks = new StringBuilder();
Mark startMark = reader.getMark();
char quote = reader.peek();
reader.forward();
chunks.append(scanFlowScalarNonSpaces(_double, startMark));
while (reader.peek() != quote) {
chunks.append(scanFlowScalarSpaces(startMark));
chunks.append(scanFlowScalarNonSpaces(_double, startMark));
}
reader.forward();
Mark endMark = reader.getMark();
return new ScalarToken(chunks.toString(), false, startMark, endMark, style);
}
/**
* Scan some number of flow-scalar non-space characters.
*/
private String scanFlowScalarNonSpaces(boolean doubleQuoted, Mark startMark) {
// See the specification for details.
StringBuilder chunks = new StringBuilder();
while (true) {
// Scan through any number of characters which are not: NUL, blank,
// tabs, line breaks, single-quotes, double-quotes, or backslashes.
int length = 0;
while (Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(length), "\'\"\\")) {
length++;
}
if (length != 0) {
chunks.append(reader.prefixForward(length));
}
// Depending on our quoting-type, the characters ', " and \ have
// differing meanings.
char ch = reader.peek();
if (!doubleQuoted && ch == '\'' && reader.peek(1) == '\'') {
chunks.append("'");
reader.forward(2);
} else if ((doubleQuoted && ch == '\'') || (!doubleQuoted && "\"\\".indexOf(ch) != -1)) {
chunks.append(ch);
reader.forward();
} else if (doubleQuoted && ch == '\\') {
reader.forward();
ch = reader.peek();
if (ESCAPE_REPLACEMENTS.containsKey(Character.valueOf(ch))) {
// The character is one of the single-replacement
// types; these are replaced with a literal character
// from the mapping.
chunks.append(ESCAPE_REPLACEMENTS.get(Character.valueOf(ch)));
reader.forward();
} else if (ESCAPE_CODES.containsKey(Character.valueOf(ch))) {
// The character is a multi-digit escape sequence, with
// length defined by the value in the ESCAPE_CODES map.
length = ESCAPE_CODES.get(Character.valueOf(ch)).intValue();
reader.forward();
String hex = reader.prefix(length);
if (NOT_HEXA.matcher(hex).find()) {
throw new ScannerException("while scanning a double-quoted scalar",
startMark, "expected escape sequence of " + length
+ " hexadecimal numbers, but found: " + hex,
reader.getMark());
}
int decimal = Integer.parseInt(hex, 16);
String unicode = new String(Character.toChars(decimal));
chunks.append(unicode);
reader.forward(length);
} else if (scanLineBreak().length() != 0) {
chunks.append(scanFlowScalarBreaks(startMark));
} else {
throw new ScannerException("while scanning a double-quoted scalar", startMark,
"found unknown escape character " + ch + "(" + ((int) ch) + ")",
reader.getMark());
}
} else {
return chunks.toString();
}
}
}
private String scanFlowScalarSpaces(Mark startMark) {
// See the specification for details.
StringBuilder chunks = new StringBuilder();
int length = 0;
// Scan through any number of whitespace (space, tab) characters,
// consuming them.
while (" \t".indexOf(reader.peek(length)) != -1) {
length++;
}
String whitespaces = reader.prefixForward(length);
char ch = reader.peek();
if (ch == '\0') {
// A flow scalar cannot end with an end-of-stream
throw new ScannerException("while scanning a quoted scalar", startMark,
"found unexpected end of stream", reader.getMark());
}
// If we encounter a line break, scan it into our assembled string...
String lineBreak = scanLineBreak();
if (lineBreak.length() != 0) {
String breaks = scanFlowScalarBreaks(startMark);
if (!"\n".equals(lineBreak)) {
chunks.append(lineBreak);
} else if (breaks.length() == 0) {
chunks.append(" ");
}
chunks.append(breaks);
} else {
chunks.append(whitespaces);
}
return chunks.toString();
}
private String scanFlowScalarBreaks(Mark startMark) {
// See the specification for details.
StringBuilder chunks = new StringBuilder();
while (true) {
// Instead of checking indentation, we check for document
// separators.
String prefix = reader.prefix(3);
if (("---".equals(prefix) || "...".equals(prefix))
&& Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
throw new ScannerException("while scanning a quoted scalar", startMark,
"found unexpected document separator", reader.getMark());
}
// Scan past any number of spaces and tabs, ignoring them
while (" \t".indexOf(reader.peek()) != -1) {
reader.forward();
}
// If we stopped at a line break, add that; otherwise, return the
// assembled set of scalar breaks.
String lineBreak = scanLineBreak();
if (lineBreak.length() != 0) {
chunks.append(lineBreak);
} else {
return chunks.toString();
}
}
}
/**
* Scan a plain scalar.
*
* <pre>
* See the specification for details.
* We add an additional restriction for the flow context:
* plain scalars in the flow context cannot contain ',', ':' and '?'.
* We also keep track of the `allow_simple_key` flag here.
* Indentation rules are loosed for the flow context.
* </pre>
*/
private Token scanPlain() {
StringBuilder chunks = new StringBuilder();
Mark startMark = reader.getMark();
Mark endMark = startMark;
int indent = this.indent + 1;
String spaces = "";
while (true) {
char ch;
int length = 0;
// A comment indicates the end of the scalar.
if (reader.peek() == '#') {
break;
}
while (true) {
ch = reader.peek(length);
if (Constant.NULL_BL_T_LINEBR.has(ch)
|| (this.flowLevel == 0 && ch == ':' && Constant.NULL_BL_T_LINEBR
.has(reader.peek(length + 1)))
|| (this.flowLevel != 0 && ",:?[]{}".indexOf(ch) != -1)) {
break;
}
length++;
}
// It's not clear what we should do with ':' in the flow context.
if (this.flowLevel != 0 && ch == ':'
&& Constant.NULL_BL_T_LINEBR.hasNo(reader.peek(length + 1), ",[]{}")) {
reader.forward(length);
throw new ScannerException("while scanning a plain scalar", startMark,
"found unexpected ':'", reader.getMark(),
"Please check http://pyyaml.org/wiki/YAMLColonInFlowContext for details.");
}
if (length == 0) {
break;
}
this.allowSimpleKey = false;
chunks.append(spaces);
chunks.append(reader.prefixForward(length));
endMark = reader.getMark();
spaces = scanPlainSpaces();
// System.out.printf("spaces[%s]\n", spaces);
if (spaces.length() == 0 || reader.peek() == '#'
|| (this.flowLevel == 0 && this.reader.getColumn() < indent)) {
break;
}
}
return new ScalarToken(chunks.toString(), startMark, endMark, true);
}
/**
* See the specification for details. SnakeYAML and libyaml allow tabs
* inside plain scalar
*/
private String scanPlainSpaces() {
int length = 0;
while (reader.peek(length) == ' ' || reader.peek(length) == '\t') {
length++;
}
String whitespaces = reader.prefixForward(length);
String lineBreak = scanLineBreak();
if (lineBreak.length() != 0) {
this.allowSimpleKey = true;
String prefix = reader.prefix(3);
if ("---".equals(prefix) || "...".equals(prefix)
&& Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
return "";
}
StringBuilder breaks = new StringBuilder();
while (true) {
if (reader.peek() == ' ') {
reader.forward();
} else {
String lb = scanLineBreak();
if (lb.length() != 0) {
breaks.append(lb);
prefix = reader.prefix(3);
if ("---".equals(prefix) || "...".equals(prefix)
&& Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
return "";
}
} else {
break;
}
}
}
if (!"\n".equals(lineBreak)) {
return lineBreak + breaks;
} else if (breaks.length() == 0) {
return " ";
}
return breaks.toString();
}
return whitespaces;
}
/**
* <p>
* Scan a Tag handle. A Tag handle takes one of three forms:
*
* <pre>
* "!" (c-primary-tag-handle)
* "!!" (ns-secondary-tag-handle)
* "!(name)!" (c-named-tag-handle)
* </pre>
*
* Where (name) must be formatted as an ns-word-char.
* </p>
*
* @see <a href="http://www.yaml.org/spec/1.1/#c-tag-handle"></a>
* @see <a href="http://www.yaml.org/spec/1.1/#ns-word-char"></a>
*
* <pre>
* See the specification for details.
* For some strange reasons, the specification does not allow '_' in
* tag handles. I have allowed it anyway.
* </pre>
*/
private String scanTagHandle(String name, Mark startMark) {
char ch = reader.peek();
if (ch != '!') {
throw new ScannerException("while scanning a " + name, startMark,
"expected '!', but found " + ch + "(" + ((int) ch) + ")", reader.getMark());
}
// Look for the next '!' in the stream, stopping if we hit a
// non-word-character. If the first character is a space, then the
// tag-handle is a c-primary-tag-handle ('!').
int length = 1;
ch = reader.peek(length);
if (ch != ' ') {
// Scan through 0+ alphabetic characters.
// FIXME According to the specification, these should be
// ns-word-char only, which prohibits '_'. This might be a
// candidate for a configuration option.
while (Constant.ALPHA.has(ch)) {
length++;
ch = reader.peek(length);
}
// Found the next non-word-char. If this is not a space and not an
// '!', then this is an error, as the tag-handle was specified as:
// !(name) or similar; the trailing '!' is missing.
if (ch != '!') {
reader.forward(length);
throw new ScannerException("while scanning a " + name, startMark,
"expected '!', but found " + ch + "(" + ((int) ch) + ")", reader.getMark());
}
length++;
}
String value = reader.prefixForward(length);
return value;
}
/**
* <p>
* Scan a Tag URI. This scanning is valid for both local and global tag
* directives, because both appear to be valid URIs as far as scanning is
* concerned. The difference may be distinguished later, in parsing. This
* method will scan for ns-uri-char*, which covers both cases.
* </p>
*
* <p>
* This method performs no verification that the scanned URI conforms to any
* particular kind of URI specification.
* </p>
*
* @see <a href="http://www.yaml.org/spec/1.1/#ns-uri-char"></a>
*/
private String scanTagUri(String name, Mark startMark) {
// See the specification for details.
// Note: we do not check if URI is well-formed.
StringBuilder chunks = new StringBuilder();
// Scan through accepted URI characters, which includes the standard
// URI characters, plus the start-escape character ('%'). When we get
// to a start-escape, scan the escaped sequence, then return.
int length = 0;
char ch = reader.peek(length);
while (Constant.URI_CHARS.has(ch)) {
if (ch == '%') {
chunks.append(reader.prefixForward(length));
length = 0;
chunks.append(scanUriEscapes(name, startMark));
} else {
length++;
}
ch = reader.peek(length);
}
// Consume the last "chunk", which would not otherwise be consumed by
// the loop above.
if (length != 0) {
chunks.append(reader.prefixForward(length));
length = 0;
}
if (chunks.length() == 0) {
// If no URI was found, an error has occurred.
throw new ScannerException("while scanning a " + name, startMark,
"expected URI, but found " + ch + "(" + ((int) ch) + ")", reader.getMark());
}
return chunks.toString();
}
/**
* <p>
* Scan a sequence of %-escaped URI escape codes and convert them into a
* String representing the unescaped values.
* </p>
*
* FIXME This method fails for more than 256 bytes' worth of URI-encoded
* characters in a row. Is this possible? Is this a use-case?
*
* @see <a href="http://www.ietf.org/rfc/rfc2396.txt"></a>, section 2.4, Escaped Encoding.
*/
private String scanUriEscapes(String name, Mark startMark) {
// First, look ahead to see how many URI-escaped characters we should
// expect, so we can use the correct buffer size.
int length = 1;
while (reader.peek(length * 3) == '%') {
length++;
}
// See the specification for details.
// URIs containing 16 and 32 bit Unicode characters are
// encoded in UTF-8, and then each octet is written as a
// separate character.
Mark beginningMark = reader.getMark();
ByteBuffer buff = ByteBuffer.allocate(length);
while (reader.peek() == '%') {
reader.forward();
try {
byte code = (byte) Integer.parseInt(reader.prefix(2), 16);
buff.put(code);
} catch (NumberFormatException nfe) {
throw new ScannerException("while scanning a " + name, startMark,
"expected URI escape sequence of 2 hexadecimal numbers, but found "
+ reader.peek() + "(" + ((int) reader.peek()) + ") and "
+ reader.peek(1) + "(" + ((int) reader.peek(1)) + ")",
reader.getMark());
}
reader.forward(2);
}
buff.flip();
try {
return UriEncoder.decode(buff);
} catch (CharacterCodingException e) {
throw new ScannerException("while scanning a " + name, startMark,
"expected URI in UTF-8: " + e.getMessage(), beginningMark);
}
}
/**
* Scan a line break, transforming:
*
* <pre>
* '\r\n' : '\n'
* '\r' : '\n'
* '\n' : '\n'
* '\x85' : '\n'
* default : ''
* </pre>
*/
private String scanLineBreak() {
// Transforms:
// '\r\n' : '\n'
// '\r' : '\n'
// '\n' : '\n'
// '\x85' : '\n'
// default : ''
char ch = reader.peek();
if (ch == '\r' || ch == '\n' || ch == '\u0085') {
if (ch == '\r' && '\n' == reader.peek(1)) {
reader.forward(2);
} else {
reader.forward();
}
return "\n";
} else if (ch == '\u2028' || ch == '\u2029') {
reader.forward();
return String.valueOf(ch);
}
return "";
}
/**
* Chomping the tail may have 3 values - yes, no, not defined.
*/
private static class Chomping {
private final Boolean value;
private final int increment;
public Chomping(Boolean value, int increment) {
this.value = value;
this.increment = increment;
}
public boolean chompTailIsNotFalse() {
return value == null || value;
}
public boolean chompTailIsTrue() {
return value != null && value;
}
public int getIncrement() {
return increment;
}
}
}
| mit |
x3r/WarpImage | src/com/jhlabs/image/MapFilter.java | 1414 | /*
Copyright 2006 Jerry Huxtable
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.jhlabs.image;
import com.jhlabs.math.Function2D;
public class MapFilter extends TransformFilter {
private Function2D xMapFunction;
private Function2D yMapFunction;
public MapFilter() {
}
public void setXMapFunction(Function2D xMapFunction) {
this.xMapFunction = xMapFunction;
}
public Function2D getXMapFunction() {
return xMapFunction;
}
public void setYMapFunction(Function2D yMapFunction) {
this.yMapFunction = yMapFunction;
}
public Function2D getYMapFunction() {
return yMapFunction;
}
protected void transformInverse(int x, int y, float[] out) {
float xMap, yMap;
xMap = xMapFunction.evaluate(x, y);
yMap = yMapFunction.evaluate(x, y);
out[0] = xMap * transformedSpace.width;
out[1] = yMap * transformedSpace.height;
}
public String toString() {
return "Distort/Map Coordinates...";
}
}
| mit |
eduardodaluz/xfire | xfire-core/src/test/org/codehaus/xfire/soap/handler/SoapTransportTest.java | 621 | package org.codehaus.xfire.soap.handler;
import org.codehaus.xfire.soap.SoapTransportHelper;
import org.codehaus.xfire.test.AbstractXFireTest;
import org.codehaus.xfire.transport.Transport;
import org.codehaus.xfire.transport.http.HttpTransport;
public class SoapTransportTest
extends AbstractXFireTest
{
public void testHandler() throws Exception
{
Transport t = SoapTransportHelper.createSoapTransport(new HttpTransport());
assertEquals(5, t.getInHandlers().size());
assertEquals(2, t.getOutHandlers().size());
assertEquals(1, t.getFaultHandlers().size());
}
} | mit |
jabrena/NyARToolkit-4.1.1 | sample/sandbox/src.sandbox/jp/nyatla/nyartoolkit/core/rasterfilter/NyARRasterOperator_Mul.java | 3141 | /*
* PROJECT: NyARToolkit
* --------------------------------------------------------------------------------
* This work is based on the original ARToolKit developed by
* Hirokazu Kato
* Mark Billinghurst
* HITLab, University of Washington, Seattle
* http://www.hitl.washington.edu/artoolkit/
*
* The NyARToolkit is Java edition ARToolKit class library.
* Copyright (C)2008-2009 Ryo Iizuka
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* For further information please contact.
* http://nyatla.jp/nyatoolkit/
* <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp>
*
*/
package jp.nyatla.nyartoolkit.core.rasterfilter;
import jp.nyatla.nyartoolkit.core.NyARException;
import jp.nyatla.nyartoolkit.core.raster.*;
import jp.nyatla.nyartoolkit.core.types.NyARBufferType;
import jp.nyatla.nyartoolkit.core.types.NyARIntSize;
/**
* 入力Aと入力Bの積を出力します。
*
*/
public class NyARRasterOperator_Mul
{
private IdoFilterImpl _dofilterimpl;
public NyARRasterOperator_Mul(int i_raster_type) throws NyARException
{
switch (i_raster_type) {
case NyARBufferType.INT1D_GRAY_8:
this._dofilterimpl=new IdoFilterImpl_INT1D_GRAY_8();
break;
default:
throw new NyARException();
}
}
//
public void doFilter(INyARRaster i_input_a,INyARRaster i_input_b, INyARRaster i_output) throws NyARException
{
assert (i_input_a.getSize().isEqualSize(i_output.getSize()) == true);
assert (i_input_b.getSize().isEqualSize(i_output.getSize()) == true);
this._dofilterimpl.doFilter(i_input_a,i_input_b,i_output,i_output.getSize());
}
abstract class IdoFilterImpl
{
int[] _window_ref;
public abstract void doFilter(INyARRaster i_input_a,INyARRaster i_input_b,INyARRaster i_output,NyARIntSize i_size) throws NyARException;
}
class IdoFilterImpl_INT1D_GRAY_8 extends IdoFilterImpl
{
public void doFilter(INyARRaster i_input_a,INyARRaster i_input_b,INyARRaster i_output,NyARIntSize i_size) throws NyARException
{
assert(i_input_a.isEqualBufferType(NyARBufferType.INT1D_GRAY_8));
assert(i_input_b.isEqualBufferType(NyARBufferType.INT1D_GRAY_8));
assert(i_output.isEqualBufferType(NyARBufferType.INT1D_GRAY_8));
int[] out_buf = (int[]) i_output.getBuffer();
int[] in_buf1 = (int[]) i_input_a.getBuffer();
int[] in_buf2 = (int[]) i_input_b.getBuffer();
for(int i=i_size.h*i_size.w-1;i>=0;i--)
{
out_buf[i]=(in_buf1[i]*in_buf2[i])>>8;
}
return;
}
}
} | mit |
Playtika/testcontainers-spring-boot | embedded-keycloak/src/main/java/com/playtika/test/keycloak/KeycloakContainer.java | 5074 | package com.playtika.test.keycloak;
import com.playtika.test.common.utils.ContainerUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.containers.wait.strategy.WaitStrategy;
import org.testcontainers.utility.MountableFile;
import static java.lang.String.format;
@Slf4j
public class KeycloakContainer extends GenericContainer<KeycloakContainer> {
private static final int DEFAULT_HTTP_PORT_INTERNAL = 8080;
private final KeycloakProperties properties;
private final ResourceLoader resourceLoader;
public KeycloakContainer(KeycloakProperties properties,
ResourceLoader resourceLoader) {
super(ContainerUtils.getDockerImageName(properties));
this.properties = properties;
this.resourceLoader = resourceLoader;
}
@Override
protected void configure() {
withEnv("KEYCLOAK_HTTP_PORT", String.valueOf(DEFAULT_HTTP_PORT_INTERNAL));
withEnv("KEYCLOAK_USER", properties.getAdminUser());
withEnv("KEYCLOAK_PASSWORD", properties.getAdminPassword());
withDB();
withCommand(properties.getCommand());
withExposedPorts(DEFAULT_HTTP_PORT_INTERNAL);
waitingFor(waitForListeningPort());
withImportFile(properties.getImportFile());
}
private void withDB() {
withDBVendor();
withDBAddr();
withDBPort();
withDBDatabase();
withDBSchema();
withDBUser();
withDBUserFile();
withDBPassword();
withDBPasswordFile();
}
private void withDBVendor() {
String dbVendor = properties.getDbVendor();
if (dbVendor != null) {
withEnv("DB_VENDOR", dbVendor);
}
}
private void withDBAddr() {
String dbAddr = properties.getDbAddr();
if (dbAddr != null) {
withEnv("DB_ADDR", dbAddr);
}
}
private void withDBPort() {
String dbPort = properties.getDbPort();
if (dbPort != null) {
withEnv("DB_PORT", dbPort);
}
}
private void withDBDatabase() {
String dbDatabase = properties.getDbDatabase();
if (dbDatabase != null) {
withEnv("DB_DATABASE", dbDatabase);
}
}
private void withDBSchema() {
String dbSchema = properties.getDbSchema();
if (dbSchema != null) {
withEnv("DB_SCHEMA", dbSchema);
}
}
private void withDBUser() {
String dbUser = properties.getDbUser();
if (dbUser != null) {
withEnv("DB_USER", dbUser);
}
}
private void withDBUserFile() {
String dbUserFile = properties.getDbUserFile();
if (dbUserFile != null) {
withEnv("DB_USER_FILE", dbUserFile);
}
}
private void withDBPassword() {
String dbPassword = properties.getDbPassword();
if (dbPassword != null) {
withEnv("DB_PASSWORD", dbPassword);
}
}
private void withDBPasswordFile() {
String dbPasswordFile = properties.getDbPasswordFile();
if (dbPasswordFile != null) {
withEnv("DB_PASSWORD_FILE", dbPasswordFile);
}
}
private void withImportFile(String importFile) {
if (importFile == null) {
return;
}
checkExists(importFile);
String importFileInContainer = "/tmp/" + importFile;
withCopyFileToContainer(
MountableFile.forClasspathResource(importFile),
importFileInContainer
);
withEnv("KEYCLOAK_IMPORT", importFileInContainer);
}
private void checkExists(String importFile) {
Resource resource = resourceLoader.getResource("classpath:" + importFile);
if (resource.exists()) {
log.debug("Using import file: {}", resource.getFilename());
return;
}
throw new ImportFileNotFoundException(importFile);
}
private WaitStrategy waitForListeningPort() {
return Wait
.forListeningPort()
.withStartupTimeout(properties.getTimeoutDuration());
}
public String getIp() {
return getContainerIpAddress();
}
public Integer getHttpPort() {
return getMappedPort(DEFAULT_HTTP_PORT_INTERNAL);
}
public String getAuthServerUrl() {
return format("http://%s:%d%s", getIp(), getHttpPort(), properties.getAuthBasePath());
}
public static final class ImportFileNotFoundException extends IllegalArgumentException {
private static final long serialVersionUID = 6350884396691857560L;
ImportFileNotFoundException(String importFile) {
super(format(
"Classpath resource '%s' defined through 'embedded.keycloak.import-file' does not exist.",
importFile));
}
}
}
| mit |
Arttuv/louhieditor | Louhieditor/src/com/louhigames/editor/util/StringTool.java | 304 | package com.louhigames.editor.util;
public class StringTool {
public static int occurrences(String str, char c) {
int occurrences = 0;
for (int i = 0; i < str.length(); i++) {
char ic = str.charAt(i);
if (ic == c) {
occurrences++;
}
}
return occurrences;
}
}
| mit |
lekster/devicehive-java-server | src/test/java/com/devicehive/base/AbstractResourceTest.java | 5521 | package com.devicehive.base;
import com.devicehive.application.DeviceHiveApplication;
import com.devicehive.auth.HivePrincipal;
import com.devicehive.base.rule.EmbeddedKafkaRule;
import com.devicehive.json.GsonFactory;
import com.devicehive.model.Device;
import com.devicehive.resource.converters.CollectionProvider;
import com.devicehive.resource.converters.HiveEntityProvider;
import com.devicehive.service.AbstractHazelcastEntityService;
import com.google.gson.Gson;
import com.hazelcast.core.HazelcastInstance;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.CollectionUtils;
import javax.ws.rs.client.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Base64;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DeviceHiveApplication.class)
@DirtiesContext
@WebAppConfiguration
@IntegrationTest
public abstract class AbstractResourceTest {
public static final String ADMIN_LOGIN = "test_admin";
public static final String ADMIN_PASS = "admin_pass";
public static final String ACCESS_KEY = "1jwKgLYi/CdfBTI9KByfYxwyQ6HUIEfnGSgakdpFjgk=";
public static final String DEVICE_ID = "E50D6085-2ABA-48E9-B1C3-73C673E414BE";
public static final String DEVICE_KEY = "05F94BF509C8";
@Autowired
private HazelcastInstance hzInstance;
@ClassRule
public static EmbeddedKafkaRule kafkaRule = new EmbeddedKafkaRule();
@Value("${server.port}")
protected Integer port;
private String httpBaseUri;
private String wsBaseUrl;
private WebTarget target;
protected final Gson gson = GsonFactory.createGson();
@Before
public void initSpringBootIntegrationTest() {
httpBaseUri = "http://localhost:" + port;
wsBaseUrl = "ws://localhost:" + port;
Client client = ClientBuilder.newClient();
client.register(HiveEntityProvider.class);
client.register(CollectionProvider.class);
target = client.target(httpBaseUri).path("rest");
}
@After
public void clearHZ() {
hzInstance.getMap(AbstractHazelcastEntityService.COMMANDS_MAP).clear();
hzInstance.getMap(AbstractHazelcastEntityService.NOTIFICATIONS_MAP).clear();
}
protected WebTarget target() {
return target;
}
protected String baseUri() {
return httpBaseUri;
}
protected String wsBaseUri() {
return wsBaseUrl;
}
protected String basicAuthHeader(String login, String password) {
String str = String.format("%s:%s", login, password);
String base64 = Base64.getEncoder().encodeToString(str.getBytes());
return String.format("Basic %s", base64);
}
@SuppressWarnings("unchecked")
protected final <T> T performRequest(String path, String method, Map<String, Object> params, Map<String, String> headers, Object body,
Response.Status expectedStatus, Class<T> responseClass) {
WebTarget wt = target;
if (StringUtils.isNoneBlank(path)) {
wt = wt.path(path);
}
if (!CollectionUtils.isEmpty(params)) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
wt = wt.queryParam(entry.getKey(), entry.getValue());
}
}
Invocation.Builder builder = wt.request(MediaType.APPLICATION_JSON_TYPE);
if (!CollectionUtils.isEmpty(headers)) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder = builder.header(entry.getKey(), entry.getValue());
}
}
if (StringUtils.isBlank(method)) {
method = "GET";
}
final Response response;
switch (method.toUpperCase()) {
case "GET":
response = builder.get();
break;
case "POST":
response = builder.post(createJsonEntity(body));
break;
case "PUT":
response = builder.put(createJsonEntity(body));
break;
case "DELETE":
response = builder.delete();
break;
default:
throw new IllegalArgumentException(String.format("Unknown http method '%s'", method));
}
if (expectedStatus != null) {
assertThat(response.getStatus(), is(expectedStatus.getStatusCode()));
}
if (responseClass == null || Response.class.isAssignableFrom(responseClass)) {
return (T) response;
}
return response.readEntity(responseClass);
}
private Entity<String> createJsonEntity(Object body) {
String val = gson.toJson(body);
return Entity.json(val);
}
}
| mit |
SalamaSoft/REST-framework | src/SalamaCloudDataService/src/main/java/com/salama/service/clouddata/CloudDataService.java | 31512 | package com.salama.service.clouddata;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.salama.service.core.net.http.AbstractRequestWrapper;
import javassist.NotFoundException;
import javassist.bytecode.LocalVariableAttribute;
import org.apache.log4j.Logger;
import MetoXML.Cast.BaseTypesMapping;
import com.salama.reflect.MethodInvokeUtil;
import com.salama.reflect.PreScanClassFinder;
import com.salama.service.clouddata.core.AppContext;
import com.salama.service.clouddata.core.AppException;
import com.salama.service.clouddata.core.AppServiceFilter;
import com.salama.service.clouddata.core.AppServiceFilter.ServiceFilterResult;
import com.salama.service.clouddata.core.ICloudDataService;
import com.salama.service.clouddata.core.annotation.ClientService;
import com.salama.service.clouddata.core.annotation.ClientService.NotificationNameParamType;
import com.salama.service.clouddata.core.annotation.ConverterType;
import com.salama.service.clouddata.core.annotation.ReturnValueConverter;
import com.salama.service.clouddata.defaultsupport.DefaultSupportService;
import com.salama.service.clouddata.util.JavaAssistUtil;
import com.salama.service.clouddata.util.SimpleJSONDataUtil;
import com.salama.service.clouddata.util.XmlDataUtil;
import com.salama.service.core.annotation.AccessibleRoles;
import com.salama.service.core.auth.MethodAccessNoAuthorityException;
import com.salama.service.core.net.RequestWrapper;
import com.salama.service.core.net.ResponseWrapper;
import com.salama.service.core.net.http.ContentTypeHelper;
import com.salama.service.core.net.http.MultipartFile;
import com.salama.service.core.net.http.MultipartRequestWrapper;
/**
*
* @author XingGu Liu
*/
public final class CloudDataService implements ICloudDataService {
private static Logger logger = Logger.getLogger(CloudDataService.class);
static {
logger.info("VERSION:1.9.6");
}
public static final String DefaultEncoding = "utf-8";
public static final Charset DefaultCharset = Charset.forName(DefaultEncoding);
public static final String DefaultContentTypeCharset = ";charset=utf-8";
private static final String ReturnValue_Xml_MethodAccessNoAuthority =
"<Error><type>MethodAccessNoAuthorityException</type></Error>";
private static final String ReturnValue_Json_MethodAccessNoAuthority =
"{\"type\":\"MethodAccessNoAuthorityException\"}";
private static final String ClassName_DefaultSupportService = DefaultSupportService.class.getName();
private static final String PackageName_ThisClass = CloudDataService.class.getPackage().getName();
//public static final String HTTP_HEAD_NAME_WEB_CLIENT_SERVICE = "webclientservice_callback";
private final static Class<?>[] StandardCloudDataServiceParamTypes = new Class[]{RequestWrapper.class, ResponseWrapper.class};
private PreScanClassFinder _allAppClassFinder = null;
//key:serviceClassName value:AppContext
private final HashMap<String, AppContext> _serviceClassContextMap;
private final String[] _allAppExposedPackages;
public CloudDataService(
PreScanClassFinder allAppClassFinder,
HashMap<String, AppContext> serviceClassContextMap,
String[] allAppExposedPackages
) {
_allAppClassFinder = allAppClassFinder;
_serviceClassContextMap = serviceClassContextMap;
_allAppExposedPackages = allAppExposedPackages;
}
@Override
public String cloudDataService(
String serviceType,
String serviceMethod,
RequestWrapper request, ResponseWrapper response) {
final long reqId = AbstractRequestWrapper.getCurrentRequestId();
try {
if(logger.isDebugEnabled()) {
logger.debug("req_" + reqId + " cloudDataService() serviceType:" + serviceType + " serviceMethod:" + serviceMethod);
}
response.setStatus(HttpServletResponse.SC_OK);
AppContext appContext = _serviceClassContextMap.get(serviceType);
//verify accessible of serviceType
if(appContext == null) {
if(serviceType.equals(ClassName_DefaultSupportService)) {
//in DefaultSupport
} else {
String exposedPackage = isTypeInPackageExposed(serviceType);
if(exposedPackage == null) {
throw new RuntimeException("Service(" + serviceType + ") is not under exposed packge, then not allowed to invoke");
} else {
appContext = _serviceClassContextMap.get(exposedPackage);
//could be override by filter
AppServiceFilter serviceFilter = ((CloudDataAppContext)appContext).getAppServiceFilter();
if(serviceFilter != null) {
ServiceFilterResult serviceFilterResult = serviceFilter.filter(
request, response, true, null, null, null);
if(serviceFilterResult != null && serviceFilterResult.isServiceOverrided) {
return (String) serviceFilterResult.serviceReturnValue;
}
}
return null;
}
}
} else {
if(!((CloudDataAppContext)appContext).isPackageExposed(serviceType)) {
throw new RuntimeException("Service(" + serviceType + ") is not under exposed packge, then not allowed to invoke");
}
}
Class<?> serviceTypeClass = getServiceType(serviceType);
Method method = findMethod(serviceTypeClass, serviceMethod);
//could be override by filter
if(serviceTypeClass == null || method == null) {
AppServiceFilter serviceFilter = ((CloudDataAppContext)appContext).getAppServiceFilter();
if(serviceFilter != null) {
ServiceFilterResult serviceFilterResult = serviceFilter.filter(
request, response, true, null, null, null);
if(serviceFilterResult != null && serviceFilterResult.isServiceOverrided) {
return (String) serviceFilterResult.serviceReturnValue;
}
}
}
//check the authority of accessible
try {
boolean isAccessible = checkServiceAccessAuthority(method, request, appContext);
if(!isAccessible) {
logger.error("No authority to access method:" + serviceType + "." + serviceMethod + "()");
return "";
}
} catch(MethodAccessNoAuthorityException noAuthError) {
return ReturnValue_Xml_MethodAccessNoAuthority;
}
String returnVal = invokeMethod(serviceType, serviceMethod, serviceTypeClass, method, request, response, appContext);
if(logger.isDebugEnabled()) {
logger.debug("req_" + reqId + " returnValue:\r\n" + returnVal);
}
return returnVal;
} catch (Exception e) {
logger.error("req_" + reqId + " dataService()", e);
return null;
}
}
/**
*
* @param packageName
* @return the matched exposed package.
*/
private String isTypeInPackageExposed(String packageName) {
if(_allAppExposedPackages.length == 1) {
if(packageName.startsWith(_allAppExposedPackages[0])) {
return _allAppExposedPackages[0];
}
} else {
for(String exposedPkgName : _allAppExposedPackages) {
if(packageName.startsWith(exposedPkgName)) {
return exposedPkgName;
}
}
}
return null;
}
private Class<?> getServiceType(String className) throws ClassNotFoundException {
//get class of serviceType
if(className.indexOf('.') < 0) {
char firstChar = className.charAt(0);
if(firstChar >= 'a' && firstChar <= 'z') {
return _allAppClassFinder.findClass(
className.substring(0, 1).toUpperCase().concat(
className.substring(1)));
} else {
return _allAppClassFinder.findClass(className);
}
} else {
return _allAppClassFinder.findClass(className);
}
}
private static Method findMethod(Class<?> serviceTypeClass, String serviceMethod) {
Method method = null;
try {
method = MethodInvokeUtil.GetMethod(serviceTypeClass,
serviceMethod, StandardCloudDataServiceParamTypes);
if(!((method.getModifiers() & Modifier.PUBLIC) != 0)) {
logger.debug("try to access nonpublic method:" + method.getName());
throw new NoSuchMethodException();
}
return method;
} catch (NoSuchMethodException e) {
//find by name
Method[] methods = serviceTypeClass.getMethods();
for(Method methodTmp : methods) {
if(methodTmp.getName().equals(serviceMethod)
&& (methodTmp.getModifiers() & Modifier.PUBLIC) != 0
) {
method = methodTmp;
break;
}
}
return method;
}
}
private static String invokeMethod(
String serviceType, String serviceMethod,
Class<?> serviceTypeClass, Method method,
RequestWrapper request,
ResponseWrapper response,
AppContext appContext
) throws IntrospectionException, IllegalAccessException, InvocationTargetException, IOException, InstantiationException, NotFoundException {
final long reqId = AbstractRequestWrapper.getCurrentRequestId();
//create service instance if this method is not static method
Object service = null;
boolean isStaticMethod = true;
if(!MethodInvokeUtil.IsMethodStatic(method)) {
service = serviceTypeClass.newInstance();
isStaticMethod = false;
}
//before invoke set the default content type
ReturnValueConverter returnValueConverter = null;
try {
returnValueConverter = method.getAnnotation(ReturnValueConverter.class);
} catch(Throwable e) {
logger.error(null, e);
}
String callbackFunc = null;
String notificationName = null;
ClientService clientService = null;
try {
clientService = method.getAnnotation(ClientService.class);
} catch(Throwable e) {
logger.error(null, e);
}
/*
if(returnValueConverter != null) {
if(returnValueConverter.value() == ConverterType.PLAIN_TEXT) {
response.setContentType(ContentTypeHelper.TextPlain);
} else if(returnValueConverter.value() == ConverterType.XML) {
response.setContentType("text/xml");
} else if(returnValueConverter.value() == ConverterType.JSON) {
response.setContentType("text/json");
}
} else {
response.setContentType(ContentTypeHelper.TextPlain);
}
*/
try {
Class<?>[] paramTypes = method.getParameterTypes();
boolean isStandardServiceMethd = false;
if((paramTypes.length == 2)
&& RequestWrapper.class.isAssignableFrom(paramTypes[0])
&& ResponseWrapper.class.isAssignableFrom(paramTypes[1])
) {
isStandardServiceMethd = true;
}
Object returnValue = null;
//String webServiceClientCallBack = ((HttpServletRequest)request.getRequest()).getHeader(HTTP_HEAD_NAME_WEB_CLIENT_SERVICE);
//logger.debug("webServiceClientCallBack:" + webServiceClientCallBack);
//appServiceFilter
boolean isNeedDoAppServiceFilter = false;
if(appContext != null && CloudDataAppContext.class.isAssignableFrom(appContext.getClass())) {
/* moved to the position before getServiceType()
if(!((CloudDataAppContext)appContext).isPackageExposed(serviceType)) {
throw new RuntimeException("Service(" + serviceType + ") is not under exposed packge, then not allowed to invoke");
}
*/
if(((CloudDataAppContext)appContext).getAppServiceFilter() != null) {
isNeedDoAppServiceFilter = true;
}
} else {
/* moved to the position before getServiceType()
//check whether the serviceType is enabled to be exposed
if(serviceTypeClass.getPackage().getName().equals(
DefaultSupportService.class.getPackage().getName())) {
//in DefaultSupport
} else {
throw new RuntimeException("Service(" + serviceType + ") is not under exposed packge, then not allowed to invoke");
}
*/
}
if(isStandardServiceMethd) {
if(isNeedDoAppServiceFilter) {
ServiceFilterResult serviceFilterResult = ((CloudDataAppContext)appContext).getAppServiceFilter().filter(
request, response, isStandardServiceMethd, method, service, null);
if(serviceFilterResult != null && serviceFilterResult.isServiceOverrided) {
returnValue = serviceFilterResult.serviceReturnValue;
} else {
returnValue = method.invoke(service, request, response);
}
} else {
returnValue = method.invoke(service, request, response);
}
} else {
//handle parameters ----------
Object[] paramValues = null;
if(clientService == null) {
//parameter value is achieved from request parameter
final int paramCount = paramTypes.length;
if(paramCount > 0) {
paramValues = new Object[paramCount];
/*
LocalVariableAttribute localVarAttr = JavaAssistUtil.getLocalVariableAttribute(serviceType, serviceMethod);
if(localVarAttr == null) {
throw new RuntimeException("getLocalVariableAttribute() failed. ServiceType:" + serviceType + " serviceMethod:" + serviceMethod);
}
*/
String[] paramNames = JavaAssistUtil.getParameterNames(serviceType, serviceMethod, isStaticMethod, paramCount);
/* no need to decode URI parameter, because the web server has decoded it.
boolean isParamNeedDecode = isParamNeedDecode(request, returnValueConverter);
String requestEncoding = request.getCharacterEncoding();
if(requestEncoding == null || requestEncoding.length() == 0) {
requestEncoding = "utf-8";
}
*/
for(int i = 0; i < paramCount; i++) {
final Class<?> paramType = paramTypes[i];
//paramName = JavaAssistUtil.getParameterName(localVarAttr, i, isStaticMethod);
final String paramName = paramNames[i];
if(paramType == (String.class)) {
/* no need to decode URI parameter, because the web server has decoded it.
if(isParamNeedDecode) {
paramValues[i] = getDecodedRequestParam(request, paramName, requestEncoding);
} else {
paramValues[i] = request.getParameter(paramName);
}
*/
paramValues[i] = request.getParameter(paramName);
if(logger.isTraceEnabled()) {
logger.trace("req_" + reqId + " paramName:" + paramName + " paramValue:" + paramValues[i]);
}
} else if (paramType == (MultipartFile.class)) {
paramValues[i] = ((MultipartRequestWrapper)request).getFile(paramName);
if(logger.isTraceEnabled()) {
logger.trace("req_" + reqId + " paramName:" + paramName + " (MultiPartFile)");
}
} else if (paramType == (RequestWrapper.class)) {
paramValues[i] = request;
} else if (paramType == (ResponseWrapper.class)) {
paramValues[i] = response;
} else if (paramType.isPrimitive()) {
String val;
/* no need to decode URI parameter, because the web server has decoded it.
if(isParamNeedDecode) {
val = getDecodedRequestParam(request, paramName, requestEncoding);
} else {
val = request.getParameter(paramName);
}
*/
val = request.getParameter(paramName);
paramValues[i] = convertStringToPrimitiveType(val, paramType);
if(logger.isTraceEnabled()) {
logger.trace("req_" + reqId + " paramName:" + paramName + " paramValue:" + val);
}
} else {
throw new RuntimeException("Not support the param type:" + paramType.getName());
}
}
}
} else {
int index = 0;
String paramNamePrefix = "params[";
String paramNameSuffix = "]";
if(paramTypes.length > 0) {
paramValues = new Object[paramTypes.length];
/* no need to decode URI parameter, because the web server has decoded it.
boolean isParamNeedDecode = isParamNeedDecode(request, returnValueConverter);
String requestEncoding = request.getCharacterEncoding();
if(requestEncoding == null || requestEncoding.length() == 0) {
requestEncoding = "utf-8";
}
*/
Class<?> paramType = null;
for(int i = 0; i < paramTypes.length; i++) {
paramType = paramTypes[i];
if (paramType == (RequestWrapper.class)) {
paramValues[i] = request;
} else if (paramType == (ResponseWrapper.class)) {
paramValues[i] = response;
} else {
String paramName = paramNamePrefix + Integer.toString(index++) + paramNameSuffix;
if(clientService.notificationNameParamType() == NotificationNameParamType.FirstParam
&& index == 0) {
notificationName = request.getParameter(paramName);
}
if(paramType == (String.class)) {
/* no need to decode URI parameter, because the web server has decoded it.
if(isParamNeedDecode) {
paramValues[i] = getDecodedRequestParam(request, paramName, requestEncoding);
} else {
paramValues[i] = request.getParameter(paramName);
}
*/
paramValues[i] = request.getParameter(paramName);
if(logger.isTraceEnabled()) {
logger.trace("req_" + reqId + " paramName:" + paramName + " paramValue:" + paramValues[i]);
}
} else if (paramType == (MultipartFile.class)) {
paramValues[i] = ((MultipartRequestWrapper)request).getFile(paramName);
if(logger.isTraceEnabled()) {
logger.trace("req_" + reqId + " paramName:" + paramName + " (MultiPartFile)");
}
} else if (paramType.isPrimitive()) {
String val;
/* no need to decode URI parameter, because the web server has decoded it.
if(isParamNeedDecode) {
val = getDecodedRequestParam(request, paramName, requestEncoding);
} else {
val = request.getParameter(paramName);
}
*/
val = request.getParameter(paramName);
paramValues[i] = convertStringToPrimitiveType(val, paramType);
if(logger.isTraceEnabled()) {
logger.trace("req_" + reqId + " paramName:" + paramName + " paramValue:" + val);
}
} else {
throw new RuntimeException("Not support the param type:" + paramType.getName());
}
} //
} // for
}
if(clientService.notificationNameParamType() == NotificationNameParamType.ByName) {
notificationName = request.getParameter(clientService.notificationNameFromRequestParam());
} else if(clientService.notificationNameParamType() == NotificationNameParamType.LastParam) {
String paramName = paramNamePrefix + Integer.toString(index) + paramNameSuffix;
notificationName = request.getParameter(paramName);
if(notificationName == null && index > 0) {
paramName = paramNamePrefix + Integer.toString(index-1) + paramNameSuffix;
}
}
if(notificationName != null) {
notificationName = notificationName.trim();
}
if(clientService.callBackNameFromRequestParam() != null) {
callbackFunc = request.getParameter(clientService.callBackNameFromRequestParam());
if(callbackFunc != null) {
callbackFunc = callbackFunc.trim();
}
}
} //if
//invoke ----------
if(isNeedDoAppServiceFilter) {
ServiceFilterResult serviceFilterResult = ((CloudDataAppContext)appContext).getAppServiceFilter().filter(
request, response, isStandardServiceMethd, method, service, paramValues);
if(serviceFilterResult != null && serviceFilterResult.isServiceOverrided) {
returnValue = serviceFilterResult.serviceReturnValue;
} else {
returnValue = method.invoke(service, paramValues);
}
} else {
returnValue = method.invoke(service, paramValues);
}
}
//invoke the method
if(method.getReturnType() == (void.class)) {
return null;
} else {
//convert return value
return convertReturnValue(request, response,
returnValueConverter, returnValue,
clientService, callbackFunc, notificationName,
false
);
}
} catch (InvocationTargetException e) {
if(e.getCause() != null && e.getCause().getClass() == MethodAccessNoAuthorityException.class) {
String returnValue = ReturnValue_Xml_MethodAccessNoAuthority;
if(returnValueConverter != null && returnValueConverter.valueFromRequestParam() != null) {
String strConverterType = request.getParameter(returnValueConverter.valueFromRequestParam());
if(strConverterType != null
&& strConverterType.startsWith(ReturnValueConverter.COVERT_TYPE_JSON)
) {
returnValue = ReturnValue_Json_MethodAccessNoAuthority;
}
}
return convertReturnValue(request, response,
returnValueConverter, returnValue,
clientService, callbackFunc, notificationName,
true
);
} else {
throw e;
}
}
}
private static Object convertStringToPrimitiveType(String valueStr, Class<?> cls) {
if(valueStr == null) {
if(cls == boolean.class) {
return false;
} else {
return 0;
}
} else {
if(cls == boolean.class) {
return Boolean.valueOf(valueStr);
} else if(cls == byte.class) {
return Byte.valueOf(valueStr);
} else if(cls == short.class) {
return Short.valueOf(valueStr);
} else if(cls == int.class) {
return Integer.valueOf(valueStr);
} else if(cls == long.class) {
return Long.valueOf(valueStr);
} else if(cls == float.class) {
return Float.valueOf(valueStr);
} else if(cls == double.class) {
return Double.valueOf(valueStr);
} else if(cls == char.class) {
return (char)Integer.parseInt(valueStr);
} else if(cls == Boolean.class) {
return Boolean.valueOf(valueStr);
} else if(cls == Byte.class) {
return Byte.valueOf(valueStr);
} else if(cls == Short.class) {
return Short.valueOf(valueStr);
} else if(cls == Integer.class) {
return Integer.valueOf(valueStr);
} else if(cls == Long.class) {
return Long.valueOf(valueStr);
} else if(cls == Float.class) {
return Float.valueOf(valueStr);
} else if(cls == Double.class) {
return Double.valueOf(valueStr);
} else if(cls == Character.class) {
return (char)Integer.parseInt(valueStr);
} else {
//not support
logger.error("Not support the param type:" + cls.getName());
return null;
}
}
}
private static boolean checkServiceAccessAuthority(
Method method, RequestWrapper request, AppContext appContext
) throws MethodAccessNoAuthorityException
{
AccessibleRoles accessibleRoles = null;
try {
accessibleRoles = method.getAnnotation(AccessibleRoles.class);
} catch(Exception ex) {
}
if(accessibleRoles == null || accessibleRoles.roles() == null || accessibleRoles.roles().length == 0 ) {
return true;
} else {
//String authTicket = request.getParameter(AUTH_TICKET);
String authTicket = getAuthTicketFromRequest(request);
boolean isAccessible = false;
String role = null;
try {
role = appContext.getAuthUserInfo(authTicket).getRole();
} catch(Throwable e) {
//return false;
}
for(String roleTmp : accessibleRoles.roles()) {
if(roleTmp.equals(role)) {
isAccessible = true;
break;
}
}
if(!isAccessible && accessibleRoles.returnError()) {
throw new MethodAccessNoAuthorityException();
} else {
return isAccessible;
}
}
}
/*
private static boolean isParamNeedDecode(RequestWrapper request, ReturnValueConverter returnValueConverter) {
if(returnValueConverter != null) {
if((returnValueConverter.valueFromRequestParam() != null)
&& (returnValueConverter.valueFromRequestParam().length() > 0)
) {
// When valueFromRequestParam() is not null, then default converter type is set to xml.
String strConverterType = request.getParameter(returnValueConverter.valueFromRequestParam());
if(strConverterType == null) {
return false;
} else {
strConverterType = strConverterType.trim().toLowerCase();
if(strConverterType.endsWith(".jsonp")) {
return true;
} else {
return false;
}
}
} else {
if(returnValueConverter.value() == ConverterType.XML_JSONP
|| returnValueConverter.value() == ConverterType.JSON_JSONP
|| returnValueConverter.value() == ConverterType.PLAIN_TEXT_JSONP
) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
private static String getDecodedRequestParam(RequestWrapper request, String paramName, String encoding) {
String rawValue = request.getParameter(paramName);
try {
String urlDecodedVal = URLDecoder.decode(rawValue, encoding);
return new String(urlDecodedVal.getBytes("iso-8859-1"), encoding);
} catch (Exception e) {
return rawValue;
}
}
*/
private static String convertReturnValue(
RequestWrapper request, ResponseWrapper response,
ReturnValueConverter returnValueConverter, Object returnValue,
ClientService clientService, String callbackFunc, String notificationName,
boolean overrideSkipObjectConvert
)
throws IntrospectionException, IllegalAccessException, InvocationTargetException, IOException {
//judge the convert type
ConverterType converterType = ConverterType.PLAIN_TEXT;
if(returnValueConverter != null) {
if((returnValueConverter.valueFromRequestParam() != null)
&& (returnValueConverter.valueFromRequestParam().length() > 0)
) {
// When valueFromRequestParam() is not null, then default converter type is set to xml.
String strConverterType = request.getParameter(returnValueConverter.valueFromRequestParam());
if(strConverterType == null) {
converterType = ConverterType.XML;
} else {
strConverterType = strConverterType.trim().toLowerCase();
if(strConverterType.equals(ReturnValueConverter.COVERT_TYPE_XML_JSONP)) {
converterType = ConverterType.XML_JSONP;
} else if(strConverterType.equals(ReturnValueConverter.COVERT_TYPE_XML)) {
converterType = ConverterType.XML;
} else if(strConverterType.equals(ReturnValueConverter.COVERT_TYPE_JSON_JSONP)) {
converterType = ConverterType.JSON_JSONP;
} else if(strConverterType.equals(ReturnValueConverter.COVERT_TYPE_JSON)) {
converterType = ConverterType.JSON;
} else if(strConverterType.equals(ReturnValueConverter.COVERT_TYPE_PLAIN_TEXT_JSONP)) {
converterType = ConverterType.PLAIN_TEXT_JSONP;
} else if(strConverterType.equals(ReturnValueConverter.COVERT_TYPE_PLAIN_TEXT)) {
converterType = ConverterType.PLAIN_TEXT;
} else {
converterType = ConverterType.XML;
}
}
} else {
converterType = returnValueConverter.value();
}
}
String value;
if(returnValue == null) {
value = "";
} else {
if(returnValueConverter != null
&& (overrideSkipObjectConvert
|| returnValueConverter.skipObjectConvert()
)
) {
if(String.class.isAssignableFrom(returnValue.getClass())) {
value = (String) returnValue;
} else {
value = BaseTypesMapping.ConvertBaseTypeValueToStr(returnValue.getClass(), returnValue);
}
} else {
//convert to xml or json or not convert -------------
if (converterType == ConverterType.XML_JSONP || converterType == ConverterType.XML) {
//xml
value = XmlDataUtil.convertObjectToXml(returnValue, returnValue.getClass());
} else if (converterType == ConverterType.JSON_JSONP || converterType == ConverterType.JSON) {
//JSON
//For now, only support the simple data or List<SimpleData>
if(List.class.isAssignableFrom(returnValue.getClass())) {
//List
value = SimpleJSONDataUtil.convertListObjectToJSON((List<?>)returnValue);
} else {
//simple data
value = SimpleJSONDataUtil.convertObjectToJSON(returnValue);
}
} else {
//plain text
if(String.class.isAssignableFrom(returnValue.getClass())) {
value = (String) returnValue;
} if(BaseTypesMapping.IsSupportedBaseType(returnValue.getClass())) {
value = BaseTypesMapping.ConvertBaseTypeValueToStr(returnValue.getClass(), returnValue);
} else {
value = XmlDataUtil.convertObjectToXml(returnValue, returnValue.getClass());
}
}
} // end of if(returnValueConverter.skipObjectConvert()
} //end of if(returnValue == null) {
boolean isWrapToClientService = false;
if(clientService != null
&& callbackFunc != null && callbackFunc.length() > 0
&& notificationName != null && notificationName.length() > 0) {
isWrapToClientService = true;
}
if(isWrapToClientService) {
response.setContentType(ContentTypeHelper.TextJavaScript + DefaultContentTypeCharset);
return wrapToClientService(callbackFunc, notificationName, value);
} else if (converterType == ConverterType.XML_JSONP
|| converterType == ConverterType.JSON_JSONP
|| converterType == ConverterType.PLAIN_TEXT_JSONP
) {
//wrap into jsonp format
response.setContentType(ContentTypeHelper.TextJavaScript + DefaultContentTypeCharset);
String jsonpVarName = request.getParameter(
returnValueConverter.jsonpReturnVariableNameFromRequestParam());
return wrapToJsonp(jsonpVarName, value);
} else if (converterType == ConverterType.JSON) {
response.setContentType("text/json" + DefaultContentTypeCharset);
return value;
} else if (converterType == ConverterType.XML) {
response.setContentType("text/xml" + DefaultContentTypeCharset);
return value;
} else {
response.setContentType(ContentTypeHelper.TextPlain + DefaultContentTypeCharset);
return value;
}
}
private static String wrapToJsonp(String variableName, String value) throws UnsupportedEncodingException {
return
"var " + variableName + " = \""
+ URLEncoder.encode(value, DefaultEncoding).replace("+", "%20")
+ "\";";
}
private static String wrapToClientService(String callbackFunc, String notificationName, String value) throws UnsupportedEncodingException {
return callbackFunc + "(\"" + notificationName + "\", \""
+ URLEncoder.encode(value, DefaultEncoding).replace("+", "%20")
+ "\")";
}
private final static String getAuthTicketFromRequest(RequestWrapper request) {
String authTicket = request.getParameter(AUTH_TICKET);
if(authTicket == null) {
//check cookies
HttpServletRequest httpRequest = (HttpServletRequest) request.getRequest();
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null) {
for(int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if(AUTH_TICKET.equals(c.getName())) {
authTicket = c.getValue();
break;
}
}
}
}
return authTicket;
}
}
| mit |
apothecarius/anderoids | app/src/main/java/de/apoth/anderoids/logic/CollisionSystem.java | 903 | package de.apoth.anderoids.logic;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import android.util.Pair;
import de.apoth.anderoids.logic.entities.EntityManager;
import de.apoth.anderoids.logic.events.CollisionEvent;
import de.apoth.anderoids.logic.events.Event;
import de.apoth.anderoids.resource.Time;
public class CollisionSystem extends AbstractSystem{
public CollisionSystem(EntityManager myEM) {
super(myEM);
// TODO Auto-generated constructor stub
}
public Set<CollisionEvent> checkCollisions() {
Set<CollisionEvent> collisions = new LinkedHashSet<CollisionEvent>();
//TODO check if the spaceship or the bullets collide with the asteroids
//add each collision to the set and return them for the event handler to react upon
//
return collisions;
}
@Override
public List<Pair<Time, Event>> handleEvent(Event ev) {
return null;
}
}
| mit |
elBroom/atom | lecture06/src/main/java/ru/atom/lecture07/server/dao/DbConnector.java | 1225 | package ru.atom.lecture07.server.dao;
/**
* Created by sergey on 3/25/17.
*/
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
class DbConnector {
private static final Logger log = LogManager.getLogger(DbConnector.class);
private static final String URL_TEMPLATE = "jdbc:postgresql://%s:%d/%s";
private static final String URL;
private static final String HOST = "wtfis.ru";
private static final int PORT = 5432;
private static final String DB_NAME = "chatdb_atom0";
private static final String USER = "atom0";
private static final String PASSWORD = "atom0";
static {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
log.error("Failed to load jdbc driver.", e);
System.exit(-1);
}
URL = String.format(URL_TEMPLATE, HOST, PORT, DB_NAME);
log.info("Success. DbConnector init.");
}
static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
private DbConnector() { }
} | mit |
shvets/cafebabe | cafebabe/src/main/java/org/sf/cafebabe/gadget/classtree/ShortNode.java | 624 | // ShortNode.java
package org.sf.cafebabe.gadget.classtree;
/**
* This class represents the node with the short value
*
* @version 1.0 02/06/2002
* @author Alexander Shvets
*/
public class ShortNode extends ClassTreeNode {
private short value;
/**
* Creates new attribute node
*
* @param text the text that will be displayed on the node
* @param value the short value
*/
public ShortNode(String text, short value) {
super(text, false);
this.value = value;
}
/**
* Gets the short value
*
* @return the short value
*/
public short getValue() {
return value;
}
}
| mit |
terzerm/mmap | mmap-region/src/main/java/org/tools4j/mmap/region/impl/InitialBytes.java | 1780 | /**
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 mmap (tools4j), Marco Terzer, Anton Anufriev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.tools4j.mmap.region.impl;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
public enum InitialBytes implements ReadableByteChannel {
ZERO(0L),
MINUS_ONE(-1L);
private final long initialValue;
InitialBytes(final long initialValue) {
this.initialValue = initialValue;
}
@Override
public int read(ByteBuffer dst) {
dst.putLong(initialValue);
return 8;
}
@Override
public boolean isOpen() {
return true;
}
@Override
public void close() {
//cannot be closed
}
}
| mit |
NewEconomyMovement/nem.core | src/main/java/org/nem/core/utils/SetOnce.java | 807 | package org.nem.core.utils;
/**
* Wrapper that allows an object to be set once (or reset and set again).
*
* @param <T> The inner type.
*/
public class SetOnce<T> {
private final T defaultValue;
private T value;
/**
* Creates a wrapper.
*
* @param defaultValue The default value.
*/
public SetOnce(final T defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Gets the inner object.
*
* @return The inner object.
*/
public T get() {
return null == this.value ? this.defaultValue : this.value;
}
/**
* Sets the inner object.
*
* @param value The inner object.
*/
public void set(final T value) {
if (null != this.value && null != value) {
throw new IllegalStateException("cannot change value because it is already set");
}
this.value = value;
}
}
| mit |
accelazh/TetrixGame | src/com/accela/tetrixgame/conn/support/SynchronizeSupport/standard/FailedToCloseException.java | 735 | package com.accela.tetrixgame.conn.support.SynchronizeSupport.standard;
import com.accela.tetrixgame.conn.support.SynchronizeSupport.shared.IConstants;
/**
*
* 这个异常应IOpenClosable接口而设计,表示在关闭方法中遇到了异常。 使得关闭失败。
*
*/
public class FailedToCloseException extends Exception {
private static final long serialVersionUID = IConstants.SERIAL_VERSION_UID;
public FailedToCloseException() {
super();
}
public FailedToCloseException(String message) {
super(message);
}
public FailedToCloseException(String message, Throwable cause) {
super(message, cause);
}
public FailedToCloseException(Throwable cause) {
super(cause);
}
}
| mit |
Web-of-Building-Data/Ifc2Rdf | software/drumbeat-ifc2ld-1.0.0/drumbeat-ifc.data/src/main/java/fi/hut/cs/drumbeat/ifc/data/schema/IfcAttributeInfo.java | 3490 | package fi.hut.cs.drumbeat.ifc.data.schema;
import java.io.Serializable;
//import fi.hut.cs.drumbeat.ifc.data.Cardinality;
public class IfcAttributeInfo implements Comparable<IfcAttributeInfo>,
Serializable {
private static final long serialVersionUID = 1L;
private IfcEntityTypeInfo entityTypeInfo;
private String name;
private String uniqueName;
private int attributeIndex;
private IfcTypeInfo attributeTypeInfo;
private boolean isOptional;
// private Cardinality cardinality;
private boolean isFunctional;
private boolean isInverseFunctional;
public IfcAttributeInfo(IfcEntityTypeInfo entityTypeInfo, String name, IfcTypeInfo attributeTypeInfo) {
this.entityTypeInfo = entityTypeInfo;
this.name = name;
this.attributeTypeInfo = attributeTypeInfo;
}
public IfcEntityTypeInfo getEntityTypeInfo() {
return entityTypeInfo;
}
public String getName() {
return name;
}
/**
* @return the uniqueName
*/
public String getUniqueName() {
return uniqueName != null ? uniqueName : name;
}
/**
* @param uniqueName
* the uniqueName to set
*/
public void setUniqueName(String rdfName) {
this.uniqueName = rdfName;
}
public int getAttributeIndex() {
return attributeIndex;
}
public void setAttributeIndex(int attributeIndex) {
this.attributeIndex = attributeIndex;
}
public IfcTypeInfo getAttributeTypeInfo() {
return attributeTypeInfo;
}
public boolean isOptional() {
return isOptional;
}
public void setOptional(boolean isOptional) {
this.isOptional = isOptional;
// if (cardinality != null) {
// cardinality.setOptional(isOptional);
// }
}
// public Cardinality getCardinality() {
// return cardinality;
// }
//
// public void setCardinality(Cardinality cardinality) {
// this.cardinality = cardinality;
// cardinality.setOptional(isOptional);
// }
//
// public boolean isMultiple() {
// return cardinality.isMultiple();
// }
public boolean isCollection() {
return getAttributeTypeInfo() instanceof IfcCollectionTypeInfo;
}
/**
* @return the isFunctional
*/
public boolean isFunctional() {
return isFunctional;
}
/**
* @param isFunctional
* the isFunctional to set
*/
public void setFunctional(boolean isFunctional) {
this.isFunctional = isFunctional;
}
/**
* @return the isInverseFunctional
*/
public boolean isInverseFunctional() {
return isInverseFunctional;
}
/**
* @param isInverseFunctional
* the isInverseFunctional to set
*/
public void setInverseFunctional(boolean isInverseFunctional) {
this.isInverseFunctional = isInverseFunctional;
}
@Override
public String toString() {
return name; // String.format("%s.%s", entityTypeInfo.getName(), name);
}
public boolean equals(IfcAttributeInfo o) {
return name.equals(o.name);
}
@Override
public int compareTo(IfcAttributeInfo o) {
int compare = name.compareTo(o.name);
if (compare == 0) {
compare = entityTypeInfo.compareTo(o.entityTypeInfo);
}
return compare;
}
// @Override
// public RdfNodeTypeEnum getRdfNodeType() {
// return RdfNodeTypeEnum.Uri;
// }
//
// @Override
// public RdfUri toRdfUri() {
// return
// Ifc2RdfConverter.getDefaultConverter().convertAttributeToRdfUri(this);
// }
//
// @Override
// public List<IRdfLink> getRdfLinks() {
// // TODO: Implement this
// throw new RuntimeException("Not implemented");
// }
//
// @Override
// public StatusFlag getStatusFlag() {
// return statusFlag;
// }
}
| mit |
rubenlagus/TelegramApi | src/main/java/org/telegram/api/functions/auth/TLRequestAuthCheckPassword.java | 2113 | package org.telegram.api.functions.auth;
import org.telegram.api.auth.TLAuthorization;
import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLBytes;
import org.telegram.tl.TLContext;
import org.telegram.tl.TLMethod;
import org.telegram.tl.TLObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The type TL request auth check password.
*/
public class TLRequestAuthCheckPassword extends TLMethod<TLAuthorization> {
/**
* The constant CLASS_ID.
*/
public static final int CLASS_ID = 0xa63011e;
private TLBytes passwordHash;
/**
* Instantiates a new TL request auth check password.
*/
public TLRequestAuthCheckPassword() {
super();
}
public int getClassId() {
return CLASS_ID;
}
public TLAuthorization deserializeResponse(InputStream stream, TLContext context)
throws IOException {
TLObject res = StreamingUtils.readTLObject(stream, context);
if (res == null)
throw new IOException("Unable to parse response");
if ((res instanceof TLAuthorization))
return (TLAuthorization) res;
throw new IOException("Incorrect response type. Expected org.telegram.api.auth.TLAuthorization, got: " + res.getClass().getCanonicalName());
}
/**
* Gets password hash.
*
* @return the password hash
*/
public TLBytes getPasswordHash() {
return this.passwordHash;
}
/**
* Sets password hash.
*
* @param passwordHash the password hash
*/
public void setPasswordHash(TLBytes passwordHash) {
this.passwordHash = passwordHash;
}
public void serializeBody(OutputStream stream)
throws IOException {
StreamingUtils.writeTLBytes(this.passwordHash, stream);
}
public void deserializeBody(InputStream stream, TLContext context)
throws IOException {
this.passwordHash = StreamingUtils.readTLBytes(stream, context);
}
public String toString() {
return "auth.checkPassword#a63011e";
}
} | mit |
rgllm/uminho | 02/POO/imoobiliaria/src/imoobiliaria/Vendedor.java | 2481 | import java.util.*;
public class Vendedor extends Utilizador{
private Set<Imovel> portfolio;
private Set<Imovel> historico;
/* Construtores */
public Vendedor(){
super();
portfolio=new TreeSet<Imovel>();
historico=new TreeSet<Imovel>();
}
public Vendedor(String email,String nome,String password,String morada,String data_nascimento){
super(email,nome,password,morada,data_nascimento);
this.portfolio=new TreeSet<>();
this.historico=new TreeSet<>();
}
public Vendedor(Vendedor x){
super(x.getEmail() , x.getNome() , x.getPassword() , x.getMorada() , x.getDataNasc() );
this.portfolio=x.getPortfolio();
this.historico=x.getHistorico();
}
public Vendedor(Set<Imovel>portfolio , Set<Imovel> historico){
this();
setPortfolio(portfolio);
setHistorico(historico);
}
/* Métodos de instância */
public Set<Imovel> getPortfolio(){
Set<Imovel> res = new TreeSet<Imovel>();
for(Imovel i: portfolio){
res.add(i.clone());
}
return res;
}
public Set<Imovel> getHistorico(){
Set<Imovel> res = new TreeSet<Imovel>();
for(Imovel i: historico){
res.add(i.clone());
}
return res;
}
public void setPortfolio(Set<Imovel> portfolio){
this.portfolio.clear();
for(Imovel i: portfolio){
this.portfolio.add(i.clone());
}
}
public void setHistorico(Set<Imovel> historico){
this.historico.clear();
for(Imovel i: historico){
this.historico.add(i.clone());
}
}
public void paraVenda(Imovel i){
portfolio.add(i.clone());
}
public boolean equals(Object obj) {
if (this == obj) {return true;}
if (obj == null) {return false;}
if (getClass() != obj.getClass()) {
return false;
}
final Vendedor other = (Vendedor) obj;
if (Objects.equals(this.portfolio, other.portfolio) &&
Objects.equals(this.historico, other.historico)) {
return true;
}
return false;
}
public Vendedor clone(){
return new Vendedor(this);
}
public boolean pertencePortfolio(Imovel i){
return (portfolio.contains(i));
}
public void addHistorico(Imovel i){
historico.add(i.clone());
}
}
| mit |
byronka/xenos | src/com/renomad/xenos/schema/Build_procedures.java | 358 | package com.renomad.xenos.schema;
import com.renomad.xenos.schema.Build_db_schema;
public final class Build_procedures {
private Build_procedures () {
//we don't want anyone instantiating this
//do nothing.
}
public static void main(String[] args) {
Build_db_schema.run_multiple_statements(
"db_scripts/procedures.sql");
}
}
| mit |
tianshaojie/common-framework | src/main/java/io/github/jsbd/common/dispatcher/course/BizMethod.java | 203 | package io.github.jsbd.common.dispatcher.course;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface BizMethod {
}
| mit |
Adyen/adyen-java-api-library | src/main/java/com/adyen/model/checkout/details/CellulantDetails.java | 3240 | /*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Java API Library
*
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.model.checkout.details;
import com.adyen.model.checkout.PaymentMethodDetails;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
/**
* CellulantDetails
*/
public class CellulantDetails implements PaymentMethodDetails {
/**
* Possible types
*/
public static final String CELLULANT = "cellulant";
@SerializedName("issuerId")
private String issuerId = null;
@SerializedName("type")
private String type = CELLULANT;
public CellulantDetails issuerId(String issuerId) {
this.issuerId = issuerId;
return this;
}
/**
* The issuer's ID
*
* @return issuerId
**/
public String getIssuerId() {
return issuerId;
}
public void setIssuerId(String issuerId) {
this.issuerId = issuerId;
}
public CellulantDetails type(String type) {
this.type = type;
return this;
}
/**
* **Cellulant**
*
* @return type
**/
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CellulantDetails cellulantDetails = (CellulantDetails) o;
return Objects.equals(this.issuerId, cellulantDetails.issuerId) &&
Objects.equals(this.type, cellulantDetails.type);
}
@Override
public int hashCode() {
return Objects.hash(issuerId, type);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CellulantDetails {\n");
sb.append(" issuerId: ").append(toIndentedString(issuerId)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| mit |
StubbornJava/StubbornJava | stubbornjava-webapp/src/main/java/com/stubbornjava/webapp/HelperRoutes.java | 1956 | package com.stubbornjava.webapp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.stubbornjava.common.Metrics;
import com.stubbornjava.common.undertow.Exchange;
import io.undertow.server.HttpServerExchange;
public class HelperRoutes {
private static final Logger logger = LoggerFactory.getLogger(HelperRoutes.class);
public static void getMetrics(HttpServerExchange exchange) {
Exchange.body().sendJson(exchange, Metrics.registry());
}
// public static void getLoggers(HttpServerExchange exchange) {
// Response data = Response.fromExchange(exchange).with("loggers", Logging.getLoggers());
// Exchange.body().sendHtmlTemplate(exchange, "templates/loggers", data);
// }
// public static void getProperties(HttpServerExchange exchange) {
// boolean hidden = RequestUtil.getQueryParam(exchange, "hidden")
// .map(val -> !Strings.isNullOrEmpty(val))
// .orElse(false);
// RequestUtil.sendHtml(exchange, "static/html/properties.html",
// new Response()
// .with("properties", Config.propsAsMap()
// .entrySet()
// .stream()
// .filter((entry) -> !entry.getKey().startsWith("db") || hidden)
// .filter((entry) -> !entry.getKey().startsWith("hmac") || hidden)
// .filter((entry) -> !entry.getKey().startsWith("jooq") || hidden)
// .collect(Collectors.toList())));
// }
//
// public static void getSystem(HttpServerExchange exchange) {
// RequestUtil.sendHtml(exchange, "static/html/properties.html",
// Response.fromExchange(exchange)
// .with("properties", Config.systemAsMap().entrySet()));
// }
}
| mit |
gobiiproject/GOBii-System | loaderui/src/edu/cornell/gobii/gdi/forms/FrmExperiments.java | 22470 | package edu.cornell.gobii.gdi.forms;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import java.util.Date;
import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolTip;
import org.gobiiproject.gobiiapimodel.payload.PayloadEnvelope;
import org.gobiiproject.gobiiapimodel.restresources.common.RestUri;
import org.gobiiproject.gobiiapimodel.types.GobiiServiceRequestId;
import org.gobiiproject.gobiiclient.core.gobii.GobiiClientContext;
import org.gobiiproject.gobiiclient.core.gobii.GobiiEnvelopeRestResource;
import org.gobiiproject.gobiimodel.headerlesscontainer.ExperimentDTO;
import org.gobiiproject.gobiimodel.types.GobiiProcessType;
import edu.cornell.gobii.gdi.main.App;
import edu.cornell.gobii.gdi.main.Main2;
import edu.cornell.gobii.gdi.services.Controller;
import edu.cornell.gobii.gdi.services.IDs;
import edu.cornell.gobii.gdi.utils.FormUtils;
import edu.cornell.gobii.gdi.utils.Utils;
import edu.cornell.gobii.gdi.utils.WizardUtils;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.wb.swt.SWTResourceManager;
public class FrmExperiments extends AbstractFrm {
private static Logger log = Logger.getLogger(FrmExperiments.class.getName());
private Text txtName;
private Text txtDatafile;
private Combo cbVendorProtocol;
private Button btnAddNew;
private Button btnUpdate;
private Button btnDnaWiz;
private Label lblCode;
private Text txtCode;
private Combo comboManifest;
private Button btnMarkerWiz;
private ModifyListener listener;
private String config;
private Combo comboProject;
private TableColumn tblColumn;
private Button btnClearFields;
protected int currentProjectId;
protected int currentExperimentId;
protected int currentPiId;
private Button btnAddAnalysisDataset;
/**
* Create the composite.
* @param parent
* @param style
* @wbp.parser.constructor
*/
public FrmExperiments(final Shell shell, Composite parent, int style, final String config) {
super(shell, parent, style);
this.config = config;
currentProjectId = 0;
currentExperimentId = 0;
currentPiId = 0;
populateCbListAndTbList();
}
public FrmExperiments(Shell shell, Composite parent, int style, String config, int PiId, int projectId) {
// TODO Auto-generated constructor stub
super(shell, parent, style);
this.config = config;
currentPiId = PiId;
currentProjectId = projectId;
currentExperimentId = 0;
populateCbListAndTbList();
}
@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
@Override
protected void createContent() {
cbList.addListener (SWT.Selection, new Listener() {
public void handleEvent(Event e) {
try{
String selected = cbList.getText(); //single selection
comboProject.select(comboProject.indexOf(selected));
comboProject.setText(selected);
currentProjectId = FormUtils.getIdFromFormList(cbList);
currentExperimentId = 0;
for(int i=0; i<cbList.getItemCount(); i++){
String item = cbList.getItem(i);
Integer key = Integer.parseInt((String) cbList.getData(item));
if(key == currentProjectId){
cbList.select(i);
break;
}
}
cleanExperimentDetails();
populateExperimentsListFromSelectedProject(currentProjectId); //retrieve and display projects by contact Id
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Project", err);
}
}
});
tbList.addListener (SWT.Selection, new Listener() {
public void handleEvent(Event e) {
currentExperimentId = FormUtils.getIdFromTableList(tbList);
populateExperimentDetails(currentExperimentId); //retrieve and display projects by contact Id
tblColumn.pack();
}
});
btnRefresh.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Integer id = FormUtils.getIdFromFormList(cbList);
if(id>0){
if (currentPiId>0) FormUtils.entrySetToComboSelectId(Controller.getProjectNamesByContactId(currentPiId), cbList, id);
else FormUtils.entrySetToComboSelectId(Controller.getProjectNames(), cbList, id);
populateExperimentsListFromSelectedProject(id);
}
else{
populateCbListAndTbList();
}
populateProjectsListByContactId(comboProject);
FormUtils.entrySetToCombo(Controller.getVendorProtocolNames(), cbVendorProtocol);
FormUtils.entrySetToCombo(Controller.getManifestNames(), comboManifest);
cleanExperimentDetails();
currentExperimentId = 0;
}
});
lblCbList.setText("Projects:");
tblColumn = new TableColumn(tbList, SWT.NONE);
tblColumn.setText("Experiments:");
tblColumn.setWidth(300);
listener = new ModifyListener() {
/** {@inheritDoc} */
public void modifyText(ModifyEvent e) {
// Handle event
if(cbList.getItems().length>0) btnUpdate.setEnabled(true);
}
};
GridLayout gridLayout = (GridLayout) cmpForm.getLayout();
gridLayout.numColumns = 2;
Label lblName = new Label(cmpForm, SWT.NONE);
lblName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblName.setText("*Experiment Name:");
txtName = new Text(cmpForm, SWT.BORDER);
txtName.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
txtName.addModifyListener((ModifyListener) listener);
txtName.addFocusListener(new FocusListener() {
ToolTip tip = new ToolTip(shell, SWT.BALLOON);
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
if(cbList.getSelectionIndex()<0){
Point loc = cbList.toDisplay(cbList.getLocation());
tip.setMessage("Please select a Project before creating or updating an entry.");
tip.setLocation(loc.x + cbList.getSize().x , loc.y-cbList.getSize().y);
tip.setVisible(true);
}
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
tip.setVisible(false);
}
});
lblCode = new Label(cmpForm, SWT.NONE);
lblCode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblCode.setText("Code:");
txtCode = new Text(cmpForm, SWT.BORDER);
txtCode.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
txtCode.setEditable(false);
txtCode.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblProject = new Label(cmpForm, SWT.NONE);
lblProject.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblProject.setText("*Project:");
comboProject = new Combo(cmpForm, SWT.NONE);
comboProject.setEnabled(false);
comboProject.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label lblVendorProtocol = new Label(cmpForm, SWT.NONE);
lblVendorProtocol.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblVendorProtocol.setText("*Vendor-Protocol:");
cbVendorProtocol = new Combo(cmpForm, SWT.NONE);
cbVendorProtocol.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
FormUtils.entrySetToCombo(Controller.getVendorProtocolNames(), cbVendorProtocol);
Label lblManifest = new Label(cmpForm, SWT.NONE);
lblManifest.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblManifest.setText("Manifest:");
comboManifest = new Combo(cmpForm, SWT.NONE);
comboManifest.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
comboManifest.addModifyListener((ModifyListener) listener);
FormUtils.entrySetToCombo(Controller.getManifestNames(), comboManifest);
Label lblDataFile = new Label(cmpForm, SWT.NONE);
lblDataFile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblDataFile.setText("Data File:");
txtDatafile = new Text(cmpForm, SWT.BORDER);
txtDatafile.setEditable(false);
txtDatafile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
new Label(cmpForm, SWT.NONE);
txtDatafile.addModifyListener((ModifyListener) listener);
btnAddNew = new Button(cmpForm, SWT.NONE);
btnAddNew.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try{
if(!validate(true)) return;
ExperimentDTO experimentDTO = new ExperimentDTO();
experimentDTO.setCreatedBy(1);
experimentDTO.setModifiedBy(1);
experimentDTO.setStatusId(1);
experimentDTO.setExperimentName(txtName.getText());
String name = txtName.getText().replaceAll(" ", "_");
String platform = cbVendorProtocol.getText().replaceAll(" ", "_");
String project = comboProject.getText().replaceAll(" ", "_");
experimentDTO.setExperimentCode(name+"_"+platform+"_"+project);
experimentDTO.setProjectId(currentProjectId);
String strVendorProtocolId = (String) cbVendorProtocol.getData(cbVendorProtocol.getItem(cbVendorProtocol.getSelectionIndex()));
experimentDTO.setVendorProtocolId(Integer.parseInt(strVendorProtocolId));
if(comboManifest.getSelectionIndex() >= 0){
int index = comboManifest.getSelectionIndex();
String strMId = (String) comboManifest.getData(comboManifest.getItem(index));
if(strMId != null) experimentDTO.setManifestId(Integer.parseInt(strMId));
}
if(!txtDatafile.getText().isEmpty()) experimentDTO.setExperimentDataFile(txtDatafile.getText());
try{
RestUri experimentsUri = GobiiClientContext.getInstance(null, false).getUriFactory().resourceColl(GobiiServiceRequestId.URL_EXPERIMENTS);
GobiiEnvelopeRestResource<ExperimentDTO> restResourceForExperiments = new GobiiEnvelopeRestResource<>(experimentsUri);
PayloadEnvelope<ExperimentDTO> payloadEnvelope = new PayloadEnvelope<>(experimentDTO, GobiiProcessType.CREATE);
PayloadEnvelope<ExperimentDTO> resultEnvelope = restResourceForExperiments
.post(ExperimentDTO.class, payloadEnvelope);
if(Controller.getDTOResponse(shell, resultEnvelope.getHeader(), memInfo,true)){
populateExperimentsListFromSelectedProject(currentProjectId);
currentExperimentId = resultEnvelope.getPayload().getData().get(0).getExperimentId();
populateExperimentDetails(currentExperimentId);
FormUtils.selectRowById(tbList,currentExperimentId);
};
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error saving Experiemnts", err);
}
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error saving Experiemnts", err);
}
}
});
btnAddNew.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnAddNew.setText("Add New");
new Label(cmpForm, SWT.NONE);
btnUpdate = new Button(cmpForm, SWT.NONE);
btnUpdate.setEnabled(false);
btnUpdate.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try{
if(!validate(false)) return;
if(!FormUtils.updateForm(getShell(), "Experiment", selectedName)) return;
ExperimentDTO experimentDTO = new ExperimentDTO();
experimentDTO.setCreatedBy(1);
experimentDTO.setCreatedDate(new Date());
experimentDTO.setModifiedBy(1);
experimentDTO.setStatusId(2);
experimentDTO.setExperimentId(currentExperimentId);
experimentDTO.setExperimentName(txtName.getText());
String name = txtName.getText().replaceAll(" ", "_");
String platform = cbVendorProtocol.getText().replaceAll(" ", "_");
String project = comboProject.getText().replaceAll(" ", "_");
experimentDTO.setExperimentCode(name+"_"+platform+"_"+project);
Integer projectId = currentProjectId > 0 ? currentProjectId : FormUtils.getIdFromFormList(cbList);
experimentDTO.setProjectId(projectId);
String strVendorProtocolId = (String) cbVendorProtocol.getData(cbVendorProtocol.getItem(cbVendorProtocol.getSelectionIndex()));
experimentDTO.setVendorProtocolId(Integer.parseInt(strVendorProtocolId));
if(comboManifest.getSelectionIndex() >= 0){
int index = comboManifest.getSelectionIndex();
String strMId = (String) comboManifest.getData(comboManifest.getItem(index));
if(strMId != null) experimentDTO.setManifestId(Integer.parseInt(strMId));
}
if(!txtDatafile.getText().isEmpty()) experimentDTO.setExperimentDataFile(txtDatafile.getText());
try{
RestUri experimentsUriById = GobiiClientContext.getInstance(null, false).getUriFactory()
.resourceByUriIdParam(GobiiServiceRequestId.URL_EXPERIMENTS);
experimentsUriById.setParamValue("id", Integer.toString(currentExperimentId));
GobiiEnvelopeRestResource<ExperimentDTO> restResourceForExperimentsById = new GobiiEnvelopeRestResource<>(experimentsUriById);
PayloadEnvelope<ExperimentDTO> postRequestEnvelope = new PayloadEnvelope<>(experimentDTO,GobiiProcessType.UPDATE);
PayloadEnvelope<ExperimentDTO> resultEnvelope = restResourceForExperimentsById
.put(ExperimentDTO.class,postRequestEnvelope);
if(Controller.getDTOResponse(shell, resultEnvelope.getHeader(), memInfo, true)){
populateExperimentsListFromSelectedProject(currentProjectId);
FormUtils.selectRowById(tbList,currentExperimentId);
txtCode.setText(resultEnvelope.getPayload().getData().get(0).getExperimentCode());
};
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error saving Experiemnts", err);
}
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error saving Experiemnts", err);
}
}
});
btnUpdate.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnUpdate.setText("Update");
new Label(cmpForm, SWT.NONE);
btnClearFields = new Button(cmpForm, SWT.NONE);
btnClearFields.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
cleanExperimentDetails();
if(currentProjectId==0)comboProject.setText("");
// currentExperimentId = 0;
}
});
btnClearFields.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnClearFields.setText("Clear Fields");
new Label(cmpForm, SWT.NONE);
btnAddAnalysisDataset = new Button(cmpForm, SWT.NONE);
btnAddAnalysisDataset.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FrmDatasets frm = new FrmDatasets(shell, getParent(), SWT.NONE, config, currentProjectId, currentExperimentId);
CTabFolder tabContent = (CTabFolder) getParent();
CTabItem item = new CTabItem(tabContent, SWT.NONE);
item.setText("Datasets");
item.setShowClose(true);
item.setControl(frm);
tabContent.setSelection(item);
}
});
btnAddAnalysisDataset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnAddAnalysisDataset.setText("Add Dataset");
new Label(cmpForm, SWT.NONE);
btnMarkerWiz = new Button(cmpForm, SWT.FLAT);
btnMarkerWiz.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN));
btnMarkerWiz.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WizardUtils.CreateMarkerWizard(shell, config, currentPiId, currentProjectId, currentExperimentId, 0);
}
});
btnMarkerWiz.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnMarkerWiz.setText("Marker Wizard");
new Label(cmpForm, SWT.NONE);
btnDnaWiz = new Button(cmpForm, SWT.FLAT);
btnDnaWiz.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN));
btnDnaWiz.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WizardUtils.createDNASampleWizard(shell, config, currentPiId, currentProjectId, currentExperimentId);
}
});
btnDnaWiz.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
btnDnaWiz.setText("DNA Sample Wizard");
}
private void populateCbListAndTbList() {
try{
// get projects
cbList.setText("*Select a Project");
tbList.removeAll();
if(currentPiId>0 ){
if(currentProjectId>0){
FormUtils.entrySetToComboSelectId(Controller.getProjectNamesByContactId(currentPiId), cbList, currentProjectId);
comboProject.setText(cbList.getText());
}
else FormUtils.entrySetToCombo(Controller.getProjectNamesByContactId(currentPiId), cbList);
}else{
if(currentProjectId>0){
FormUtils.entrySetToComboSelectId(Controller.getProjectNames(), cbList, currentProjectId);
comboProject.setText(cbList.getText());
}
else FormUtils.entrySetToCombo(Controller.getProjectNames(), cbList);
}
// get experiments
if(currentProjectId>0){
FormUtils.entrySetToTable(Controller.getExperimentNamesByProjectId(currentProjectId), tbList);
}
else{FormUtils.entrySetToTable(Controller.getExperimentNames(), tbList);
}
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Projects and Experiemnts", err);
}
currentExperimentId = 0;
}
protected void populateExperimentDetails(int experimentId) {
cleanExperimentDetails();
ExperimentDTO experimentDTO = null;
try {
PayloadEnvelope<ExperimentDTO> resultEnvelope = Controller.getExperimentDetailsById(experimentId);
if(Controller.getDTOResponse(shell, resultEnvelope.getHeader(), memInfo, false)){
experimentDTO = resultEnvelope.getPayload().getData().get(0);
selectedName = experimentDTO.getExperimentName();
//displayDetails
txtCode.setText(experimentDTO.getExperimentCode());
txtName.setText(experimentDTO.getExperimentName());
if(experimentDTO.getExperimentDataFile() != null){
txtDatafile.setText(experimentDTO.getExperimentDataFile());
}
populateProjectsComboAndSelect(comboProject, experimentDTO.getProjectId());
populateVendorProtocolComboAndSelect(cbVendorProtocol, experimentDTO.getVendorProtocolId());
if(experimentDTO.getManifestId() != null){
populateManifestComboAndSelect(comboManifest, experimentDTO.getManifestId());
}
}
} catch (Exception e) {
Utils.log(shell, memInfo, log, "Error retrieving Experiemnts", e);
}
}
private void populateProjectsComboAndSelect(Combo comboProject, int projectId) {
try{
FormUtils.entrySetToComboSelectId(Controller.getProjectNames(), comboProject, projectId);
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Projects", err);
}
}
private void populateManifestComboAndSelect(Combo comboManifest, int manifestId) {
try{
FormUtils.entrySetToComboSelectId(Controller.getManifestNames(), comboManifest, manifestId);
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Manifests", err);
}
}
private void populateVendorProtocolComboAndSelect(Combo combo, int vendorProtocolId) {
try{
FormUtils.entrySetToComboSelectId(Controller.getVendorProtocolNames(), combo, vendorProtocolId);
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Vendot Protocol Names", err);
}
}
private void populateProjectsListByContactId(Combo cbList) {
try{
if(currentProjectId > 0){
FormUtils.entrySetToComboSelectId(Controller.getProjectNamesByContactId(currentPiId), cbList, currentProjectId);
for(int i=0; i<cbList.getItemCount(); i++){
String key = (String) cbList.getData(cbList.getItem(i));
if(Integer.parseInt(key) == currentProjectId){
cbList.select(i);
break;
}
}
populateExperimentsListFromSelectedProject(currentProjectId);
}else{
FormUtils.entrySetToCombo(Controller.getProjectNamesByContactId(currentPiId), cbList);
if (cbList.getItemCount()<1) FormUtils.entrySetToCombo(Controller.getProjectNames(), comboProject);
}
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Projects", err);
}
}
//retrieve and display experiments by project Id
public void populateExperimentsListFromSelectedProject(Integer selectedId) {
try{
tbList.removeAll();
FormUtils.entrySetToTable(Controller.getExperimentNamesByProjectId(selectedId), tbList);
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error retrieving Experiemnts", err);
}
}
private void cleanExperimentDetails() {
try{
txtCode.setText("");
txtName.setText("");
cbVendorProtocol.deselectAll(); cbVendorProtocol.setText("");
comboManifest.deselectAll(); comboManifest.setText("");
txtDatafile.setText("");
}catch(Exception err){
Utils.log(shell, memInfo, log, "Error clearing fields", err);
}
}
private boolean validate(boolean isNew){
boolean successful = true;
String message = null;
MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
if(txtName.getText().isEmpty()){
message = "Name field is required!";
successful = false;
}else if(cbList.getSelectionIndex() < 0){
message = "Project is a required field!";
successful = false;
}else if(cbVendorProtocol.getSelectionIndex() < 0){
message = "Vendor-Protocol is a required filed!";
successful = false;
}else if(!isNew && currentExperimentId==0){
message = "'"+txtName.getText()+"' is recognized as a new value. Please use Add instead.";
successful = false;
}else if(isNew|| !txtName.getText().equalsIgnoreCase(selectedName)){
for(int i=0; i<tbList.getItemCount(); i++){
if(tbList.getItem(i).getText(0).equalsIgnoreCase(txtName.getText())){
successful = false;
message = "Name of Experiment already exists for this Project!";
break;
}
}
}
if(!successful){
dialog.setMessage(message);
dialog.open();
}
return successful;
}
}
| mit |
pagehelper/pagehelper-spring-boot | pagehelper-spring-boot-samples/pagehelper-spring-boot-sample-xml/src/main/java/tk/mybatis/pagehelper/domain/Hotel.java | 2122 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 abel533@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @author Eduardo Macarron
*/
package tk.mybatis.pagehelper.domain;
import java.io.Serializable;
public class Hotel implements Serializable {
private static final long serialVersionUID = 1L;
private Long city;
private String name;
private String address;
private String zip;
public Long getCity() {
return city;
}
public void setCity(Long city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
@Override
public String toString() {
return getCity() + "," + getName() + "," + getAddress() + "," + getZip();
}
} | mit |
Greedylightning/LeetCode_Second | Tree/CountCompleteTreeNodes.java | 412 | class CountCompleteTreeNodes{
public int countNodes(TreeNode root) {
if(root == null) return 0;
TreeNode l = root, r = root;
int hl = 0, hr = 0;
while(l.left != null){hl++;l = l.left;}
while(r.right != null){hr++;r = r.right;}
if(hl == hr) return (2 << hl) - 1;
else return countNodes(root.left) + countNodes(root.right) + 1;
}
} | mit |
farzadfarazmand/slider | slider/src/main/java/ir/apend/slider/ui/indicators/SquareIndicator.java | 1613 | package ir.apend.slider.ui.indicators;
import android.content.Context;
import android.os.Build;
import android.support.v4.content.res.ResourcesCompat;
import ir.apend.sliderlibrary.R;
/**
* @author S.Shahini
* @since 11/27/16
*/
public class SquareIndicator extends IndicatorShape {
public SquareIndicator(Context context, int indicatorSize, boolean mustAnimateChanges) {
super(context, indicatorSize, mustAnimateChanges);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.indicator_square_unselected, null));
} else {
setBackgroundDrawable(getResources().getDrawable(R.drawable.indicator_square_unselected));
}
}
@Override
public void onCheckedChange(boolean isChecked) {
super.onCheckedChange(isChecked);
if (isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.indicator_square_selected, null));
} else {
setBackgroundDrawable(getResources().getDrawable(R.drawable.indicator_square_selected));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.indicator_square_unselected, null));
} else {
setBackgroundDrawable(getResources().getDrawable(R.drawable.indicator_square_unselected));
}
}
}
}
| mit |
testinfected/molecule | src/main/java/com/vtence/molecule/middlewares/Router.java | 1583 | package com.vtence.molecule.middlewares;
import com.vtence.molecule.Application;
import com.vtence.molecule.Request;
import com.vtence.molecule.Response;
import com.vtence.molecule.routing.Route;
import com.vtence.molecule.routing.RouteBuilder;
import com.vtence.molecule.routing.RouteSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
public class Router implements Application, RouteSet {
public static Router draw(RouteBuilder routeBuilder) {
Router router = new Router();
routeBuilder.build(router);
return router;
}
private final List<Route> routingTable = new ArrayList<>();
private final Application fallback;
public Router() {
this(new NotFound());
}
public Router(final Application fallback) {
this.fallback = fallback;
}
public Router route(Predicate<Request> condition, Application app) {
return route(new StaticRoute(condition, app));
}
public Router route(Route route) {
routingTable.add(route);
return this;
}
public Response handle(Request request) throws Exception {
return routeFor(request).handle(request);
}
private Application routeFor(Request request) {
return routingTable.stream()
.map(route -> route.route(request))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElse(fallback);
}
} | mit |
github-ribbon/issue-tracker | issuetracker/issuetracker-provider/src/main/java/com/company/issuetracker/provider/validation/VersionDTOValidator.java | 1219 | package com.company.issuetracker.provider.validation;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import com.company.issuetracker.core.dto.VersionDTO;
import com.company.issuetracker.provider.domain.ProjectEntity;
import com.company.issuetracker.provider.domain.ProjectPKEntity;
import com.company.issuetracker.provider.domain.VersionEntity;
import com.company.issuetracker.provider.domain.VersionPKEntity;
@Component
public class VersionDTOValidator{
@Autowired
private DozerBeanMapper mapper;
@Autowired
private VersionEntity versionEntity;
@Autowired
private ProjectEntity projectEntity;
public void validate(VersionDTO versionDTO, Errors errors) {
if(versionEntity.exists(mapper.map(versionDTO.getVersion().getId(),VersionPKEntity.class))){
errors.rejectValue("version.id.versionId", "error.versionExists");
}
if(!projectEntity.exists(new ProjectPKEntity(versionDTO.getVersion().getId().getOwnerId(),
versionDTO.getVersion().getId().getProjectId()))){
errors.rejectValue("version.id.versionId", "error.projectNotMatched");
}
}
}
| mit |
OzansDeepMind/iflas-technologies-ltd | src/com/yildizozan/ComponentCPURAM8Core.java | 283 | package com.yildizozan;
public class ComponentCPURAM8Core extends ComponentCPURAM {
public ComponentCPURAM8Core(double cpu, int ram) {
super(cpu, ram);
}
@Override
public String toString() {
return "8 core " + cpu + " GHz, " + ram + " GB.";
}
}
| mit |
joshsh/rdfagents | rdfagents-core/src/main/java/net/fortytwo/rdfagents/util/properties/InvalidPropertyValueException.java | 357 | package net.fortytwo.rdfagents.util.properties;
/**
* @author Joshua Shinavier (http://fortytwo.net)
*/
public class InvalidPropertyValueException extends PropertyException {
public InvalidPropertyValueException(final String propertyName,
final Throwable cause) {
super(propertyName, cause);
}
}
| mit |
bing-ads-sdk/BingAds-Java-SDK | src/main/java/com/microsoft/bingads/v12/bulk/entities/BulkEntityNegativeKeyword.java | 2786 | package com.microsoft.bingads.v12.bulk.entities;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.internal.functionalinterfaces.Function;
import com.microsoft.bingads.v12.internal.bulk.BulkMapping;
import com.microsoft.bingads.v12.internal.bulk.DynamicColumnNameMapping;
import com.microsoft.bingads.v12.internal.bulk.MappingHelpers;
import com.microsoft.bingads.v12.internal.bulk.RowValues;
/**
* This abstract base class for all bulk negative keywords that are assigned individually to a campaign or ad group entity.
*
* @see BulkAdGroupNegativeKeyword
* @see BulkCampaignNegativeKeyword
*/
abstract class BulkEntityNegativeKeyword extends BulkNegativeKeyword {
private String entityName;
private static final List<BulkMapping<BulkEntityNegativeKeyword>> MAPPINGS;
static {
List<BulkMapping<BulkEntityNegativeKeyword>> m = new ArrayList<BulkMapping<BulkEntityNegativeKeyword>>();
m.add(new DynamicColumnNameMapping<BulkEntityNegativeKeyword, String>(
new Function<BulkEntityNegativeKeyword, String>() {
@Override
public String apply(BulkEntityNegativeKeyword c) {
return c.getEntityColumnName();
}
},
new Function<BulkEntityNegativeKeyword, String>() {
@Override
public String apply(BulkEntityNegativeKeyword c) {
return c.getEntityName();
}
},
new BiConsumer<String, BulkEntityNegativeKeyword>() {
@Override
public void accept(String v, BulkEntityNegativeKeyword c) {
c.setEntityName(v);
}
}
));
MAPPINGS = Collections.unmodifiableList(m);
}
@Override
public void processMappingsFromRowValues(RowValues values) {
super.processMappingsFromRowValues(values);
MappingHelpers.convertToEntity(values, MAPPINGS, this);
}
@Override
public void processMappingsToRowValues(RowValues values, boolean excludeReadonlyData) {
super.processMappingsToRowValues(values, excludeReadonlyData);
MappingHelpers.convertToValues(this, values, MAPPINGS);
}
/**
* Reserved for internal use.
*/
String getEntityName() {
return entityName;
}
/**
* Reserved for internal use.
*/
void setEntityName(String entityName) {
this.entityName = entityName;
}
/**
* Reserved for internal use.
*/
abstract String getEntityColumnName();
}
| mit |
groupdocs-viewer/GroupDocs.Viewer-for-Java | Demos/Dropwizard/src/main/java/com/groupdocs/ui/viewer/resources/ViewerResources.java | 7902 | package com.groupdocs.ui.viewer.resources;
import com.groupdocs.ui.common.config.GlobalConfiguration;
import com.groupdocs.ui.common.exception.TotalGroupDocsException;
import com.groupdocs.ui.common.resources.Resources;
import com.groupdocs.ui.viewer.config.ViewerConfiguration;
import com.groupdocs.ui.viewer.model.request.FileTreeRequest;
import com.groupdocs.ui.viewer.model.request.LoadDocumentPageRequest;
import com.groupdocs.ui.viewer.model.request.LoadDocumentRequest;
import com.groupdocs.ui.viewer.model.request.RotateDocumentPagesRequest;
import com.groupdocs.ui.viewer.model.response.FileDescriptionEntity;
import com.groupdocs.ui.viewer.model.response.LoadDocumentEntity;
import com.groupdocs.ui.viewer.model.response.PageDescriptionEntity;
import com.groupdocs.ui.viewer.model.response.UploadedDocumentEntity;
import com.groupdocs.ui.viewer.service.ViewerService;
import com.groupdocs.ui.viewer.service.ViewerServiceImpl;
import com.groupdocs.ui.viewer.views.Viewer;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
import static javax.ws.rs.core.MediaType.*;
/**
* Viewer Resources
*
* @author Aspose Pty Ltd
*/
@Path(value = "/viewer")
public class ViewerResources extends Resources {
private final ViewerService viewerService;
/**
* Constructor
*
* @param globalConfiguration global configuration object
* @throws UnknownHostException
*/
public ViewerResources(GlobalConfiguration globalConfiguration) throws UnknownHostException {
super(globalConfiguration);
viewerService = new ViewerServiceImpl(globalConfiguration);
}
/**
* Get and set viewer page
*
* @return html view
*/
@GET
public Viewer getView() {
// initiate index page
return new Viewer(globalConfiguration, DEFAULT_CHARSET);
}
@GET
@Path(value = "/loadConfig")
@Produces(APPLICATION_JSON)
public ViewerConfiguration loadConfig() {
return ViewerConfiguration.createViewerConfiguration(globalConfiguration.getViewer(), globalConfiguration.getCommon());
}
/**
* Get files and directories
*
* @param fileTreeRequest request's object with specified path
* @return files and directories list
*/
@POST
@Path(value = "/loadFileTree")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public List<FileDescriptionEntity> loadFileTree(FileTreeRequest fileTreeRequest) {
return viewerService.getFileList(fileTreeRequest.getPath());
}
/**
* Get document description
*
* @param loadDocumentRequest request's object with parameters
* @return document description
*/
@POST
@Path(value = "/loadDocumentDescription")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public LoadDocumentEntity loadDocumentDescription(LoadDocumentRequest loadDocumentRequest) {
if (StringUtils.isEmpty(loadDocumentRequest.getGuid())) {
throw new TotalGroupDocsException("Document guid is empty!");
}
return viewerService.loadDocument(loadDocumentRequest, globalConfiguration.getViewer().getPreloadPageCount() == 0, false);
}
/**
* Get all pages for thumbnails
*
* @param loadDocumentRequest
* @return
*/
@POST
@Path(value = "/loadThumbnails")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public LoadDocumentEntity loadThumbnails(LoadDocumentRequest loadDocumentRequest) {
return viewerService.loadDocument(loadDocumentRequest, true, false);
}
/**
* Get document page
*
* @param loadDocumentPageRequest request's object with parameters
* @return document page
*/
@POST
@Path(value = "/loadDocumentPage")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public PageDescriptionEntity loadDocumentPage(LoadDocumentPageRequest loadDocumentPageRequest) {
return viewerService.loadDocumentPage(loadDocumentPageRequest);
}
/**
* Get document for printing
*
* @param loadDocumentRequest
* @return
*/
@POST
@Path(value = "/loadPrint")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public LoadDocumentEntity loadPrint(LoadDocumentRequest loadDocumentRequest) {
return viewerService.loadDocument(loadDocumentRequest, true, true);
}
/**
* Get pdf document for printing
*
* @return
*/
@POST
@Path(value = "/printPdf")
@Consumes(APPLICATION_JSON)
public void printPdf(LoadDocumentRequest loadDocumentRequest, @Context HttpServletResponse response) {
String fileName = FilenameUtils.getName(loadDocumentRequest.getGuid());
String fileExtension = FilenameUtils.getExtension(fileName);
String pdfFileName = fileName.replace(fileExtension, "pdf");
InputStream fileStream = viewerService.getPdf(loadDocumentRequest);
respondWithPdf(response, fileStream, pdfFileName);
}
/**
* Rotate page(s)
*
* @param rotateDocumentPagesRequest request's object with parameters
* @return rotated pages list (each object contains page number and rotated angle information)
*/
@POST
@Path(value = "/rotateDocumentPages")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public PageDescriptionEntity rotateDocumentPages(RotateDocumentPagesRequest rotateDocumentPagesRequest) {
return viewerService.rotateDocumentPages(rotateDocumentPagesRequest);
}
/**
* Download document
*
* @param documentGuid path to document parameter
* @param response
*/
@GET
@Path(value = "/downloadDocument")
@Produces(APPLICATION_OCTET_STREAM)
public void downloadDocument(@QueryParam("path") String documentGuid, @Context HttpServletResponse response) {
downloadFile(response, documentGuid);
}
@GET
@Path(value = "resources/{guid}/{resourceName}")
@Produces(APPLICATION_OCTET_STREAM)
public Response downloadDocument(@PathParam("guid") String guid, @PathParam("resourceName") String resourceName) {
return viewerService.getResource(guid, resourceName);
}
/**
* Upload document
*
* @param inputStream file content
* @param fileDetail file description
* @param documentUrl url for document
* @param rewrite flag for rewriting file
* @return uploaded document object (the object contains uploaded document guid)
*/
@POST
@Path(value = "/uploadDocument")
@Produces(APPLICATION_JSON)
@Consumes(MULTIPART_FORM_DATA)
public UploadedDocumentEntity uploadDocument(@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("url") String documentUrl,
@FormDataParam("rewrite") Boolean rewrite) {
// upload file
String pathname = uploadFile(documentUrl, inputStream, fileDetail, rewrite, null);
// create response
UploadedDocumentEntity uploadedDocument = new UploadedDocumentEntity();
uploadedDocument.setGuid(pathname);
return uploadedDocument;
}
@Override
protected String getStoragePath(Map<String, Object> params) {
return globalConfiguration.getViewer().getFilesDirectory();
}
}
| mit |
jaredkoontz/lintcode | java/sha/Others/old records/LintCode-Backup/Segment Tree Build.java | 2123 | 按定义:
左孩子:(A.left,(A.left+A.rigth)/2)
右孩子:((A.left+A.rigth)/2+1, A.right)
```
/*
The structure of Segment Tree is a binary tree which each node has two attributes start and end denote an segment / interval.
start and end are both integers, they should be assigned in following rules:
The root's start and end is given by build method.
The left child of node A has start=A.left, end=(A.left + A.right) / 2.
The right child of node A has start=(A.left + A.right) / 2 + 1, end=A.right.
if start equals to end, there will be no children for this node.
Implement a build method with two parameters start and end, so that we can create a corresponding segment tree with every node has the correct start and end value, return the root of this segment tree.
Example
Given start=0, end=3. The segment tree will be:
[0, 3]
/ \
[0, 1] [2, 3]
/ \ / \
[0, 0] [1, 1] [2, 2] [3, 3]
Given start=1, end=6. The segment tree will be:
[1, 6]
/ \
[1, 3] [4, 6]
/ \ / \
[1, 2] [3,3] [4, 5] [6,6]
/ \ / \
[1,1] [2,2] [4,4] [5,5]
Clarification
Segment Tree (a.k.a Interval Tree) is an advanced data structure which can support queries like:
which of these intervals contain a given point
which of these points are in a given interval
See wiki:
Segment Tree
Interval Tree
Tags Expand
LintCode Copyright Binary Tree Segment Tree
*/
public class Solution {
/**
* @param start, end: Denote an segment / interval
* @return: The root of Segment Tree
*/
public SegmentTreeNode build(int start, int end) {
if (start > end) {
return null;
} else if (start == end) {
return new SegmentTreeNode(start, end);
}
SegmentTreeNode node = new SegmentTreeNode(start, end);
node.left = build(start, (start + end) / 2);
node.right = build((start + end) / 2 + 1, end);
return node;
}
}
``` | mit |
stackprobe/Java3 | evergarden/violet/TwoTower.java | 2138 | package evergarden.violet;
import java.awt.Color;
import charlotte.tools.Bmp;
import charlotte.tools.Canvas;
import charlotte.tools.IntTools;
import charlotte.tools.XYPoint;
public class TwoTower {
public static void main(String[] args) {
try {
//main2();
main3();
System.out.println("OK!");
}
catch(Throwable e) {
e.printStackTrace();
}
}
private static void main2() throws Exception {
Bmp bmp = new Bmp(700, 600);
XYPoint tower1 = new XYPoint(300, 300);
XYPoint tower2 = new XYPoint(400, 300);
for(int x = 0; x < 700; x++) {
for(int y = 0; y < 600; y++) {
XYPoint curr = new XYPoint(x, y);
double d1 = curr.getDistance(tower1);
double d2 = curr.getDistance(tower2);
double rate = d1 / d2;
//rate -= 0.25; // -= TARGET_RATE
rate -= 0.5; // -= TARGET_RATE
//rate -= 0.75; // -= TARGET_RATE
rate = Math.abs(rate);
int level = 0;
if(rate < 0.1) {
rate *= 10.0;
rate = 1.0 - rate;
rate *= rate;
rate *= rate;
rate *= rate;
level = IntTools.toInt(rate * 255.0);
level = IntTools.toRange(level, 0, 255);
}
bmp.setDot(x, y, new Bmp.Dot(255, 255, 255 - level, 255 - level));
}
}
bmp.setDot(300, 300, new Bmp.Dot(Color.BLACK));
bmp.setDot(400, 300, new Bmp.Dot(Color.BLACK));
bmp.writeToFile("C:/temp/TwoTower.png");
}
private static void main3() throws Exception {
Bmp bmp = new Bmp(700, 600);
new Canvas(bmp).fill(Color.WHITE);
XYPoint tower1 = new XYPoint(300, 300);
XYPoint tower2 = new XYPoint(400, 300);
for(double r = 5.0; r <= 105.0; r += 0.1) {
Canvas c1 = new Canvas(new Bmp(700, 600));
Canvas c2 = new Canvas(new Bmp(700, 600));
c1.drawCircle(300.0, 300.0, r, Color.WHITE);
c2.drawCircle(400.0, 300.0, r * 2.0, Color.WHITE);
for(int x = 0; x < 700; x++) {
for(int y = 0; y < 600; y++) {
if(c1.getBmp().get(x, y) != 0 && c2.getBmp().get(x, y) != 0) {
bmp.set(x, y, 0x0000ffff);
}
}
}
}
bmp.setDot(300, 300, new Bmp.Dot(Color.BLACK));
bmp.setDot(400, 300, new Bmp.Dot(Color.BLACK));
bmp.writeToFile("C:/temp/TwoTower.png");
}
}
| mit |
SpongePowered/SpongeAPI | src/main/java/org/spongepowered/api/item/inventory/entity/UserInventory.java | 1694 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.item.inventory.entity;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
/**
* Represents a {@link User}'s inventory with {@link CarriedInventory}
* capabilities.
*
* <p>This is thought of as the inventory data component of a player's data.</p>
*/
public interface UserInventory extends StandardInventory, CarriedInventory<User> {
}
| mit |
dbasedow/prospecter | src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java | 5454 | package de.danielbasedow.prospecter.server;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.danielbasedow.prospecter.core.*;
import de.danielbasedow.prospecter.core.document.Document;
import de.danielbasedow.prospecter.core.document.MalformedDocumentException;
import de.danielbasedow.prospecter.core.schema.Schema;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpApiRequestHandler extends SimpleChannelInboundHandler<Object> {
private static final ObjectMapper mapper = new ObjectMapper();
private final Instance instance;
private FullHttpRequest request;
private static final Logger LOGGER = LoggerFactory.getLogger(HttpApiRequestHandler.class);
public HttpApiRequestHandler(Instance instance) {
this.instance = instance;
}
private final StringBuilder responseBuffer = new StringBuilder();
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
this.request = (FullHttpRequest) msg;
} else {
throw new Exception();
}
FullHttpResponse response;
try {
response = dispatch();
} catch (Exception e) {
LOGGER.warn(e.getLocalizedMessage(), e);
response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.INTERNAL_SERVER_ERROR,
Unpooled.copiedBuffer(e.getLocalizedMessage(), CharsetUtil.UTF_8)
);
}
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
protected FullHttpResponse dispatch() throws UndefinedIndexFieldException, MalformedQueryException, MalformedDocumentException, JsonProcessingException {
String uri = request.getUri();
String[] uriParts = uri.split("/");
if (uriParts.length == 0) {
LOGGER.warn("root uri specified, please supply a valid uri! Doing nothing!");
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
String schemaName = uriParts[1];
LOGGER.debug("method: " + request.getMethod() + ", schema: '" + schemaName + "'");
if (request.getMethod() == HttpMethod.POST && schemaName != null) {
return matchDocument(instance.getSchema(schemaName));
}
if (request.getMethod() == HttpMethod.PUT && schemaName != null) {
return addQuery(instance.getSchema(schemaName));
}
if (request.getMethod() == HttpMethod.DELETE && schemaName != null) {
String queryId = uriParts[1];
return deleteQuery(instance.getSchema(schemaName), queryId);
}
return null;
}
protected DefaultFullHttpResponse addQuery(Schema schema) throws MalformedQueryException, UndefinedIndexFieldException {
ByteBuf content = request.content();
if (content.isReadable()) {
schema.addQuery(content.toString(CharsetUtil.UTF_8));
}
return new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.copiedBuffer("", CharsetUtil.UTF_8)
);
}
protected FullHttpResponse matchDocument(Schema schema) throws MalformedDocumentException, JsonProcessingException {
ByteBuf content = request.content();
int matchCount = 0;
ObjectNode node = mapper.getNodeFactory().objectNode();
if (content.isReadable()) {
LOGGER.debug("start matching");
Document doc = schema.getDocumentBuilder().build(content.toString(CharsetUtil.UTF_8));
Matcher matcher = schema.matchDocument(doc);
ArrayNode results = node.putArray("matches");
for (Integer queryId : matcher.getMatchedQueries()) {
matchCount++;
ObjectNode queryNode = results.addObject();
queryNode.put("id", queryId);
}
LOGGER.debug("finished matching");
}
node.put("count", matchCount);
return new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.copiedBuffer(mapper.writeValueAsString(node), CharsetUtil.UTF_8)
);
}
protected DefaultFullHttpResponse deleteQuery(Schema schema, String queryId) {
if (queryId == null || "".equals(queryId)) {
LOGGER.warn("No query id supplied in DELETE request.");
return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
Integer qid = Integer.parseInt(queryId, 10);
schema.deleteQuery(qid);
return new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.copiedBuffer("", CharsetUtil.UTF_8)
);
}
}
| mit |
snf4j/snf4j | snf4j-core/src/test/java/org/snf4j/longevity/datagram/SessionStructureFactory.java | 2709 | /*
* -------------------------------- MIT License --------------------------------
*
* Copyright (c) 2020 SNF4J contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* -----------------------------------------------------------------------------
*/
package org.snf4j.longevity.datagram;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import org.snf4j.core.allocator.CachingAllocator;
import org.snf4j.core.allocator.DefaultAllocator;
import org.snf4j.core.allocator.DefaultAllocatorMetric;
import org.snf4j.core.allocator.IByteBufferAllocator;
import org.snf4j.core.factory.ISessionStructureFactory;
import org.snf4j.core.timer.DefaultTimer;
import org.snf4j.core.timer.ITimeoutModel;
import org.snf4j.core.timer.ITimer;
import org.snf4j.longevity.Config;
import org.snf4j.longevity.Utils;
public class SessionStructureFactory implements ISessionStructureFactory {
private static final ITimer TIMER = new DefaultTimer(true);
static final DefaultAllocatorMetric METRIC = org.snf4j.longevity.SessionStructureFactory.METRIC;
public static final CachingAllocator CACHING_ALLOCATOR = new CachingAllocator(true, METRIC);
@Override
public IByteBufferAllocator getAllocator() {
if (Config.DATAGRAM_CACHING_ALLOCATOR) {
return CACHING_ALLOCATOR;
}
return new DefaultAllocator(Utils.randomBoolean(Config.DIRECT_ALLOCATOR_RATIO));
}
@Override
public ConcurrentMap<Object, Object> getAttributes() {
return null;
}
@Override
public Executor getExecutor() {
return null;
}
@Override
public ITimer getTimer() {
return TIMER;
}
@Override
public ITimeoutModel getTimeoutModel() {
return null;
}
}
| mit |
pbsds/TDT4145-Trebo | src/com/trebo/trebo.java | 600 | package com.trebo;
import java.sql.SQLException;
public class trebo {
public static void main(String[] args) {
System.out.println("Starting up...");
Database db = new Database("jdbc:mysql://mysql.stud.ntnu.no:3306/pederbs_trebodb?characterEncoding=latin1",
"pederbs_trebodb",
"pederbs_trebo",
"spismeg");
Menu menu = new Menu(db);
try {
menu.run();
} catch (Exception e){
e.printStackTrace();
System.out.println(e);
System.exit(1);
}
}
}
| mit |
SpongePowered/SpongeCommon | src/main/java/org/spongepowered/common/mixin/core/block/BlockEndPortalFrameMixin.java | 4192 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.core.block;
import com.google.common.collect.ImmutableList;
import net.minecraft.block.BlockEndPortalFrame;
import net.minecraft.block.state.IBlockState;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.manipulator.immutable.block.ImmutableDirectionalData;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.util.Direction;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.common.data.ImmutableDataCachingUtil;
import org.spongepowered.common.data.manipulator.immutable.block.ImmutableSpongeDirectionalData;
import org.spongepowered.common.util.Constants;
import java.util.Optional;
@Mixin(BlockEndPortalFrame.class)
public abstract class BlockEndPortalFrameMixin extends BlockMixin {
@SuppressWarnings("RedundantTypeArguments") // some java compilers will not calculate this generic correctly
@Override
public ImmutableList<ImmutableDataManipulator<?, ?>> bridge$getManipulators(final IBlockState blockState) {
return ImmutableList.<ImmutableDataManipulator<?, ?>>of(impl$getDirectionalData(blockState));
}
@Override
public boolean bridge$supports(final Class<? extends ImmutableDataManipulator<?, ?>> immutable) {
return ImmutableDirectionalData.class.isAssignableFrom(immutable);
}
@Override
public Optional<BlockState> bridge$getStateWithData(final IBlockState blockState, final ImmutableDataManipulator<?, ?> manipulator) {
if (manipulator instanceof ImmutableDirectionalData) {
final Direction dir = Constants.DirectionFunctions.checkDirectionToHorizontal(((ImmutableDirectionalData) manipulator).direction().get());
return Optional.of((BlockState) blockState.withProperty(BlockEndPortalFrame.FACING, Constants.DirectionFunctions.getFor(dir)));
}
return super.bridge$getStateWithData(blockState, manipulator);
}
@Override
public <E> Optional<BlockState> bridge$getStateWithValue(final IBlockState blockState, final Key<? extends BaseValue<E>> key, final E value) {
if (key.equals(Keys.DIRECTION)) {
final Direction dir = Constants.DirectionFunctions.checkDirectionToHorizontal((Direction) value);
return Optional.of((BlockState) blockState.withProperty(BlockEndPortalFrame.FACING, Constants.DirectionFunctions.getFor(dir)));
}
return super.bridge$getStateWithValue(blockState, key, value);
}
private ImmutableDirectionalData impl$getDirectionalData(final IBlockState blockState) {
return ImmutableDataCachingUtil.getManipulator(ImmutableSpongeDirectionalData.class,
Constants.DirectionFunctions.getFor(blockState.getValue(BlockEndPortalFrame.FACING)));
}
}
| mit |
mrosinski/representatives | src/main/java/com/cohesiva/representatives/model/RepresentativeConfirmationRequest.java | 1637 | package com.cohesiva.representatives.model;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "representatives_confirmation_reqs")
public class RepresentativeConfirmationRequest {
@Id
@GeneratedValue
private Long id;
@OneToOne
private User user;
// @formatter:off
@OneToMany
@JoinTable(name = "representatives_confirmation_acks",
joinColumns = @JoinColumn(name = "request_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
// @formatter:on
private Set<User> confirmations = new HashSet<User>();
public boolean confirmBy(User confirmer) {
return confirmer.getRole() == UserRole.REPRESENTATIVE ? confirmations.add(confirmer) : false;
}
public Long getId() {
return id;
}
public User getUser() {
return user;
}
public int getConfirmationsCount() {
return confirmations.size();
}
@Override
public int hashCode() {
return Objects.hash(user, confirmations);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!(obj instanceof RepresentativeConfirmationRequest))
return false;
// @formatter:off
RepresentativeConfirmationRequest other = (RepresentativeConfirmationRequest) obj;
return Objects.equals(this.user, other.user)
&& Objects.equals(this.confirmations, other.confirmations);
// @formatter:on
}
}
| mit |
JPAT-ROSEMARY/SCUBA | org.jpat.scuba.common/src/main/java/org/jpat/scuba/common/util/args/Constants.java | 583 | package org.jpat.scuba.common.util.args;
public enum Constants
{
inst;
public static final String MSG_NULL_OR_EMPTY_ARGS = "\n\n\t(!) Expected one argument: 'a benchmark configuration file path'\n\tAnalyser has refused to start.\n";
public static final String MSG_ARGS_VALUE_NOT_EXISTENT = "\n\n\t(!) The specified file path does not exist: '{}' \n\tAnalyser has refused to start.\n";
public static final String MSG_ARGS_HAS_MORE_THAN_ONE_ARGS = "\n\n\t(!) Expected only one argument: 'a benchmark configuration file path'. \n\tAnalyser has refused to start.\n";
}
| mit |
plumer/codana | tomcat_files/6.0.0/RequestDumperValve.java | 7218 | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* 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.apache.catalina.valves;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.StringManager;
import org.apache.juli.logging.Log;
/**
* <p>Implementation of a Valve that logs interesting contents from the
* specified Request (before processing) and the corresponding Response
* (after processing). It is especially useful in debugging problems
* related to headers and cookies.</p>
*
* <p>This Valve may be attached to any Container, depending on the granularity
* of the logging you wish to perform.</p>
*
* @author Craig R. McClanahan
* @version $Revision: 303133 $ $Date: 2004-08-29 18:46:15 +0200 (dim., 29 août 2004) $
*/
public class RequestDumperValve
extends ValveBase {
// ----------------------------------------------------- Instance Variables
/**
* The descriptive information related to this implementation.
*/
private static final String info =
"org.apache.catalina.valves.RequestDumperValve/1.0";
/**
* The StringManager for this package.
*/
protected static StringManager sm =
StringManager.getManager(Constants.Package);
// ------------------------------------------------------------- Properties
/**
* Return descriptive information about this Valve implementation.
*/
public String getInfo() {
return (info);
}
// --------------------------------------------------------- Public Methods
/**
* Log the interesting request parameters, invoke the next Valve in the
* sequence, and log the interesting response parameters.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void invoke(Request request, Response response)
throws IOException, ServletException {
Log log = container.getLogger();
// Log pre-service information
log.info("REQUEST URI =" + request.getRequestURI());
log.info(" authType=" + request.getAuthType());
log.info(" characterEncoding=" + request.getCharacterEncoding());
log.info(" contentLength=" + request.getContentLength());
log.info(" contentType=" + request.getContentType());
log.info(" contextPath=" + request.getContextPath());
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++)
log.info(" cookie=" + cookies[i].getName() + "=" +
cookies[i].getValue());
}
Enumeration hnames = request.getHeaderNames();
while (hnames.hasMoreElements()) {
String hname = (String) hnames.nextElement();
Enumeration hvalues = request.getHeaders(hname);
while (hvalues.hasMoreElements()) {
String hvalue = (String) hvalues.nextElement();
log.info(" header=" + hname + "=" + hvalue);
}
}
log.info(" locale=" + request.getLocale());
log.info(" method=" + request.getMethod());
Enumeration pnames = request.getParameterNames();
while (pnames.hasMoreElements()) {
String pname = (String) pnames.nextElement();
String pvalues[] = request.getParameterValues(pname);
StringBuffer result = new StringBuffer(pname);
result.append('=');
for (int i = 0; i < pvalues.length; i++) {
if (i > 0)
result.append(", ");
result.append(pvalues[i]);
}
log.info(" parameter=" + result.toString());
}
log.info(" pathInfo=" + request.getPathInfo());
log.info(" protocol=" + request.getProtocol());
log.info(" queryString=" + request.getQueryString());
log.info(" remoteAddr=" + request.getRemoteAddr());
log.info(" remoteHost=" + request.getRemoteHost());
log.info(" remoteUser=" + request.getRemoteUser());
log.info("requestedSessionId=" + request.getRequestedSessionId());
log.info(" scheme=" + request.getScheme());
log.info(" serverName=" + request.getServerName());
log.info(" serverPort=" + request.getServerPort());
log.info(" servletPath=" + request.getServletPath());
log.info(" isSecure=" + request.isSecure());
log.info("---------------------------------------------------------------");
// Perform the request
getNext().invoke(request, response);
// Log post-service information
log.info("---------------------------------------------------------------");
log.info(" authType=" + request.getAuthType());
log.info(" contentLength=" + response.getContentLength());
log.info(" contentType=" + response.getContentType());
Cookie rcookies[] = response.getCookies();
for (int i = 0; i < rcookies.length; i++) {
log.info(" cookie=" + rcookies[i].getName() + "=" +
rcookies[i].getValue() + "; domain=" +
rcookies[i].getDomain() + "; path=" + rcookies[i].getPath());
}
String rhnames[] = response.getHeaderNames();
for (int i = 0; i < rhnames.length; i++) {
String rhvalues[] = response.getHeaderValues(rhnames[i]);
for (int j = 0; j < rhvalues.length; j++)
log.info(" header=" + rhnames[i] + "=" + rhvalues[j]);
}
log.info(" message=" + response.getMessage());
log.info(" remoteUser=" + request.getRemoteUser());
log.info(" status=" + response.getStatus());
log.info("===============================================================");
}
/**
* Return a String rendering of this object.
*/
public String toString() {
StringBuffer sb = new StringBuffer("RequestDumperValve[");
if (container != null)
sb.append(container.getName());
sb.append("]");
return (sb.toString());
}
}
| mit |
umutdurak/MDSceE | ConceptualScenarioMetaModel.edit/src/ConceptualScenarioMetaModel/provider/StateItemProvider.java | 6274 | /**
*/
package ConceptualScenarioMetaModel.provider;
import ConceptualScenarioMetaModel.ConceptualScenarioMetaModelFactory;
import ConceptualScenarioMetaModel.ConceptualScenarioMetaModelPackage;
import ConceptualScenarioMetaModel.State;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link ConceptualScenarioMetaModel.State} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class StateItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StateItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addNamePropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_State_Name_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_State_Name_feature", "_UI_State_type"),
ConceptualScenarioMetaModelPackage.Literals.STATE__NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(ConceptualScenarioMetaModelPackage.Literals.STATE__GUARD);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns State.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/State"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((State)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_State_type") :
getString("_UI_State_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(State.class)) {
case ConceptualScenarioMetaModelPackage.STATE__NAME:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case ConceptualScenarioMetaModelPackage.STATE__GUARD:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(ConceptualScenarioMetaModelPackage.Literals.STATE__GUARD,
ConceptualScenarioMetaModelFactory.eINSTANCE.createExitCondition()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return ConceptualScenarioEditPlugin.INSTANCE;
}
}
| mit |
m45t3r/retrobreaker | RetroBreaker/app/src/main/java/br/usp/ime/retrobreaker/forms/Brick.java | 909 | package br.usp.ime.retrobreaker.forms;
public class Brick extends Quad {
public static final int BRICK_EXPLOSION_SIZE = 8;
public enum Type {
NORMAL, EXPLOSIVE, HARD, MOBILE
}
private static final float SCALE = 0.1f;
private static final float[] VERTICES = {
-0.5f, -0.2f, // bottom left
-0.5f, 0.2f, // top left
0.5f, -0.2f, // bottom right
0.5f, 0.2f, // top right
};
private int mLives;
private final Type mType;
public Brick(float[] colors, float posX, float posY, Type type) {
super(VERTICES, SCALE, colors, posX, posY);
mType = type;
switch (type) {
case NORMAL:
mLives = 0;
break;
case EXPLOSIVE:
mLives = 0;
break;
case HARD:
mLives = 1;
break;
case MOBILE:
mLives = 0;
break;
}
}
public void decrementLives() {
mLives--;
}
public int getLives() {
return mLives;
}
public Type getType() {
return mType;
}
}
| mit |
nico01f/z-pec | ZimbraTagLib/src/java/com/zimbra/cs/taglib/tag/filter/FileIntoActionTag.java | 1251 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.taglib.tag.filter;
import com.zimbra.cs.taglib.tag.ZimbraSimpleTag;
import com.zimbra.client.ZFilterAction.ZFileIntoAction;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
public class FileIntoActionTag extends ZimbraSimpleTag {
private String mPath;
public void setPath(String path) { mPath = path; }
public void doTag() throws JspException {
FilterRuleTag rule = (FilterRuleTag) findAncestorWithClass(this, FilterRuleTag.class);
if (rule == null)
throw new JspTagException("The fileIntoAction tag must be used within a filterRule tag");
rule.addAction(new ZFileIntoAction(mPath));
}
}
| mit |
Despector/Despector | src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeIfEmitter.java | 3941 | /*
* The MIT License (MIT)
*
* Copyright (c) Despector <https://despector.voxelgenesis.com>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.despector.emitter.bytecode.statement;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.spongepowered.despector.ast.insn.condition.AndCondition;
import org.spongepowered.despector.ast.insn.condition.BooleanCondition;
import org.spongepowered.despector.ast.insn.condition.CompareCondition;
import org.spongepowered.despector.ast.insn.condition.Condition;
import org.spongepowered.despector.ast.stmt.Statement;
import org.spongepowered.despector.ast.stmt.branch.If;
import org.spongepowered.despector.emitter.StatementEmitter;
import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext;
public class BytecodeIfEmitter implements StatementEmitter<BytecodeEmitterContext, If> {
private Label start;
private Label end;
@Override
public void emit(BytecodeEmitterContext ctx, If stmt, boolean semicolon) {
MethodVisitor mv = ctx.getMethodVisitor();
this.start = new Label();
this.end = new Label();
emit(ctx, stmt.getCondition());
mv.visitLabel(this.start);
for (Statement b : stmt.getBody()) {
ctx.emitStatement(b);
}
mv.visitLabel(this.end);
}
private void emit(BytecodeEmitterContext ctx, Condition cond) {
if (cond instanceof AndCondition) {
AndCondition and = (AndCondition) cond;
for (Condition op : and.getOperands()) {
emitInverse(ctx, op);
}
}
}
private void emitInverse(BytecodeEmitterContext ctx, Condition cond) {
MethodVisitor mv = ctx.getMethodVisitor();
if (cond instanceof CompareCondition) {
CompareCondition cmp = (CompareCondition) cond;
ctx.emitInstruction(cmp.getLeft(), null);
ctx.emitInstruction(cmp.getRight(), null);
switch (cmp.getOperator()) {
case NOT_EQUAL:
mv.visitJumpInsn(Opcodes.IF_ACMPEQ, this.end);
break;
case EQUAL:
mv.visitJumpInsn(Opcodes.IF_ACMPNE, this.end);
break;
default:
throw new IllegalStateException("Unsupported compare operator: " + cmp.getOperator().name());
}
} else if(cond instanceof BooleanCondition) {
BooleanCondition bool = (BooleanCondition) cond;
ctx.emitInstruction(bool.getConditionValue(), null);
if(bool.isInverse()) {
mv.visitJumpInsn(Opcodes.IFNE, this.end);
} else {
mv.visitJumpInsn(Opcodes.IFEQ, this.end);
}
} else {
throw new IllegalStateException();
}
}
}
| mit |
longde123/MultiversePlatform | server/src/multiverse/server/events/DirectedEvent.java | 4614 | /********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
package multiverse.server.events;
import multiverse.server.engine.*;
import multiverse.server.network.*;
import multiverse.server.objects.*;
import multiverse.server.util.*;
import java.util.*;
/**
* use this event when you want to send a particular event to multiple
* recipients on a single connection. this is used when the world
* server is sending a message to the entity manager. there is only
* one shared connection but the message is supposed to go to a set of
* entities
*/
public class DirectedEvent extends Event {
public DirectedEvent() {
super();
}
public DirectedEvent(Collection<MVObject> recipients,
Event event) {
setRecipients(recipients);
setContainedEvent(event);
}
public String getName() {
return "DirectedEvent";
}
public void setContainedEvent(Event e) {
containedEvent = e;
}
public Event getContainedEvent() {
return containedEvent;
}
private Event containedEvent = null;
public void setRecipients(Collection<MVObject> c) {
recipientCol = c;
}
public Collection<MVObject> getRecipients() {
return recipientCol;
}
private Collection<MVObject> recipientCol = null;
public MVByteBuffer toBytes() {
int msgId = Engine.getEventServer().getEventID(this.getClass());
MVByteBuffer buf = new MVByteBuffer(1000);
buf.putLong(-1); // dummy id
buf.putInt(msgId);
// write out the recipient list
if (recipientCol == null) {
throw new MVRuntimeException("DirectedEvent: recipient list size is 0");
}
buf.putInt(recipientCol.size());
// Log.debug("DirectedEvent: recipient list size=" + recipientCol.size());
Iterator<MVObject> iter = recipientCol.iterator();
while(iter.hasNext()) {
MVObject e = iter.next();
buf.putLong(e.getOid());
// Log.debug("DirectedEvent: recipient oid=" + e.getOid());
}
// write out the event itself
MVByteBuffer subEventBuf = getContainedEvent().toBytes();
buf.putByteBuffer(subEventBuf);
buf.flip();
return buf;
}
protected void parseBytes(MVByteBuffer buf) {
buf.rewind();
// read in the message id
/* long playerId = */ buf.getLong();
/* int msgId = */ buf.getInt();
// Log.debug("DirectedEvent.parseBytes: msgid=" + msgId);
// read in the recipient list
Collection<MVObject> col = new HashSet<MVObject>();
int len = buf.getInt();
// Log.debug("DirectedEvent.parseBytes: recipient list size=" + len);
for (int i=0; i<len; i++) {
Long oid = buf.getLong();
// Log.debug("DirectedEvent.parseBytes: recipient oid: " + oid);
MVObject e = MVObject.getObject(oid);
if (e == null) {
log.warn("could not find entity with oid " + oid);
continue;
}
// Log.debug("DirectedEvent.parseBytes: recipient: " + e);
col.add(e);
}
setRecipients(col);
// parse the event
// Log.debug("DirectedEvent.parseBytes: parsing subevent");
MVByteBuffer subBuf = buf.getByteBuffer();
Event subEvent = Engine.getEventServer().parseBytes(subBuf,
getConnection());
// Log.debug("DirectedEvent.parseBytes: subevent=" + subEvent.getName());
setContainedEvent(subEvent);
}
public void setMessage(String msg) {
mMessage = msg;
}
public String getMessage() {
return mMessage;
}
private String mMessage = null;
static final Logger log = new Logger("ComEvent");
}
| mit |
CS2103JAN2017-F14-B2/main | src/main/java/seedu/task/model/tag/Tag.java | 1556 | package seedu.task.model.tag;
import seedu.task.commons.exceptions.IllegalValueException;
/**
* Represents a Tag in KIT.
* Guarantees: immutable; name is valid as declared in {@link #isValidTagName(String)}
*/
public class Tag {
public static final String MESSAGE_TAG_CONSTRAINTS = "Tags names should be alphanumeric";
public static final String TAG_VALIDATION_REGEX = "\\p{Alnum}+";
public final String tagName;
/**
* Validates given tag name.
*
* @throws IllegalValueException if the given tag name string is invalid.
*/
public Tag(String name) throws IllegalValueException {
assert name != null;
String trimmedName = name.trim();
if (!isValidTagName(trimmedName)) {
throw new IllegalValueException(MESSAGE_TAG_CONSTRAINTS);
}
this.tagName = trimmedName;
}
/**
* Returns true if a given string is a valid tag name.
*/
public static boolean isValidTagName(String test) {
return test.matches(TAG_VALIDATION_REGEX);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Tag // instanceof handles nulls
&& this.tagName.equals(((Tag) other).tagName)); // state check
}
@Override
public int hashCode() {
return tagName.hashCode();
}
/**
* Format state as text for viewing.
*/
@Override
public String toString() {
return '[' + tagName + ']';
}
}
| mit |
uhef/Oskari-Routing | service-map/src/main/java/fi/nls/oskari/map/userlayer/service/UserLayerDbServiceIbatisImpl.java | 4097 | package fi.nls.oskari.map.userlayer.service;
import com.ibatis.sqlmap.client.SqlMapSession;
import fi.nls.oskari.domain.map.userlayer.UserLayer;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.userlayer.service.UserLayerDbService;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.service.db.BaseIbatisService;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserLayerDbServiceIbatisImpl extends
BaseIbatisService<UserLayer> implements UserLayerDbService {
private static final Logger log = LogFactory.getLogger(UserLayerDbServiceIbatisImpl.class);
@Override
protected String getNameSpace() {
return "UserLayer";
}
/*
* The purpose of this method is to allow many SqlMapConfig.xml files in a
* single portlet
*/
protected String getSqlMapLocation() {
return "META-INF/SqlMapConfig_UserLayer.xml";
}
/**
* insert UserLayer table row
*
* @param userLayer
*/
public long insertUserLayerRow(final UserLayer userLayer) {
log.debug("Insert user_layer row:", userLayer);
final Long id = queryForObject(getNameSpace() + ".insertUserLayer", userLayer);
userLayer.setId(id);
log.debug("Got user_layer id:", id);
return id;
}
/**
* update UserLayer table row field mapping
*
* @param userLayer
*/
public int updateUserLayerCols(final UserLayer userLayer) {
try {
return getSqlMapClient().update(
getNameSpace() + ".updateUserLayerCols", userLayer);
} catch (SQLException e) {
log.error(e, "Failed to update userLayer col mapping", userLayer);
}
return 0;
}
/**
* Get UserLayer row by id
*
* @param id
* @return userLayer object
*/
public UserLayer getUserLayerById(long id) {
return queryForObject(getNameSpace() + ".findUserLayer", id);
}
/**
* Get UserLayer rows of one user by uuid
*
* @param uid user uuid
* @return List of userLayer objects
*/
public List<UserLayer> getUserLayerByUid(String uid) {
return queryForList(getNameSpace() + ".findUserLayerByUid", uid);
}
public void deleteUserLayerById(final long id) throws ServiceException {
final UserLayer userLayer = getUserLayerById(id);
deleteUserLayer(userLayer);
}
public void deleteUserLayer(final UserLayer userLayer) throws ServiceException {
if(userLayer == null) {
throw new ServiceException("Tried to delete userLayer with <null> param");
}
final SqlMapSession session = openSession();
try {
session.startTransaction();
session.delete(getNameSpace() + ".delete-userLayer-data", userLayer.getId());
session.delete(getNameSpace() + ".delete-userLayer", userLayer.getId());
// style is for now 1:1 to userLayer so we can delete it here
session.delete(getNameSpace() + ".delete-userLayer-style", userLayer.getStyle_id());
session.commitTransaction();
} catch (Exception e) {
throw new ServiceException("Error deleting userLayer data with id:" + userLayer.getId(), e);
} finally {
endSession(session);
}
}
/**
* Updates a userLayer publisher screenName
*
* @param id
* @param uuid
* @param name
*/
public int updatePublisherName(final long id, final String uuid, final String name) {
final Map<String, Object> data = new HashMap<String,Object>();
data.put("publisher_name", name);
data.put("uuid", uuid);
data.put("id", id);
try {
return getSqlMapClient().update(
getNameSpace() + ".updatePublisherName", data);
} catch (SQLException e) {
log.error(e, "Failed to update publisher name", data);
}
return 0;
}
}
| mit |
chilejiang1024/codes | java-web/srpingboot2/springboot2-template/server/src/main/java/work/zhili/springboot2template/configurer/CachingConfig.java | 1137 | package work.zhili.springboot2template.configurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Title : work.zhili.springboot2template.configurer <br>
* Description :
* cache config
*
* @author chile
* @version 1.0
* @date 2018/5/18 15:01
*/
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
| mit |
docusign/docusign-java-client | src/main/java/com/docusign/esign/model/RecipientSMSAuthentication.java | 4484 | package com.docusign.esign.model;
import java.util.Objects;
import java.util.Arrays;
import com.docusign.esign.model.PropertyMetadata;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Contains the element senderProvidedNumbers which is an Array of phone numbers the recipient can use for SMS text authentication..
*
*/
@ApiModel(description = "Contains the element senderProvidedNumbers which is an Array of phone numbers the recipient can use for SMS text authentication.")
public class RecipientSMSAuthentication {
@JsonProperty("senderProvidedNumbers")
private java.util.List<String> senderProvidedNumbers = null;
@JsonProperty("senderProvidedNumbersMetadata")
private PropertyMetadata senderProvidedNumbersMetadata = null;
/**
* senderProvidedNumbers.
*
* @return RecipientSMSAuthentication
**/
public RecipientSMSAuthentication senderProvidedNumbers(java.util.List<String> senderProvidedNumbers) {
this.senderProvidedNumbers = senderProvidedNumbers;
return this;
}
/**
* addSenderProvidedNumbersItem.
*
* @return RecipientSMSAuthentication
**/
public RecipientSMSAuthentication addSenderProvidedNumbersItem(String senderProvidedNumbersItem) {
if (this.senderProvidedNumbers == null) {
this.senderProvidedNumbers = new java.util.ArrayList<String>();
}
this.senderProvidedNumbers.add(senderProvidedNumbersItem);
return this;
}
/**
* An Array containing a list of phone numbers the recipient may use for SMS text authentication. .
* @return senderProvidedNumbers
**/
@ApiModelProperty(value = "An Array containing a list of phone numbers the recipient may use for SMS text authentication. ")
public java.util.List<String> getSenderProvidedNumbers() {
return senderProvidedNumbers;
}
/**
* setSenderProvidedNumbers.
**/
public void setSenderProvidedNumbers(java.util.List<String> senderProvidedNumbers) {
this.senderProvidedNumbers = senderProvidedNumbers;
}
/**
* senderProvidedNumbersMetadata.
*
* @return RecipientSMSAuthentication
**/
public RecipientSMSAuthentication senderProvidedNumbersMetadata(PropertyMetadata senderProvidedNumbersMetadata) {
this.senderProvidedNumbersMetadata = senderProvidedNumbersMetadata;
return this;
}
/**
* Get senderProvidedNumbersMetadata.
* @return senderProvidedNumbersMetadata
**/
@ApiModelProperty(value = "")
public PropertyMetadata getSenderProvidedNumbersMetadata() {
return senderProvidedNumbersMetadata;
}
/**
* setSenderProvidedNumbersMetadata.
**/
public void setSenderProvidedNumbersMetadata(PropertyMetadata senderProvidedNumbersMetadata) {
this.senderProvidedNumbersMetadata = senderProvidedNumbersMetadata;
}
/**
* Compares objects.
*
* @return true or false depending on comparison result.
*/
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RecipientSMSAuthentication recipientSMSAuthentication = (RecipientSMSAuthentication) o;
return Objects.equals(this.senderProvidedNumbers, recipientSMSAuthentication.senderProvidedNumbers) &&
Objects.equals(this.senderProvidedNumbersMetadata, recipientSMSAuthentication.senderProvidedNumbersMetadata);
}
/**
* Returns the HashCode.
*/
@Override
public int hashCode() {
return Objects.hash(senderProvidedNumbers, senderProvidedNumbersMetadata);
}
/**
* Converts the given object to string.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class RecipientSMSAuthentication {\n");
sb.append(" senderProvidedNumbers: ").append(toIndentedString(senderProvidedNumbers)).append("\n");
sb.append(" senderProvidedNumbersMetadata: ").append(toIndentedString(senderProvidedNumbersMetadata)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| mit |
lp0/slf4j-android | src/main/java/uk/uuid/slf4j/android/LogAdapter.java | 15656 | /**
* Copyright 2013,2016 Simon Arlott
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package uk.uuid.slf4j.android;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import android.util.Log;
/**
* A wrapper for {@link android.util.Log android.util.Log} conforming to the {@link Logger} interface.
*
* <p>
* Note that the logging levels mentioned in this class refer to those defined in the <a href="http://developer.android.com/reference/android/util/Log.html">
* <code>android.util.Log</code></a> class.
*
* @author Simon Arlott
*/
final class LogAdapter implements Logger {
private static final ConcurrentMap<String, LogLevel> nativeLevelMap = new ConcurrentHashMap<String, LogLevel>();
private static final int DIRECT_FRAMES = 2;
private static final int FORMAT_FRAMES = 3;
private final String name;
private final String tag;
private final String prefixName;
private final boolean showThread;
private final boolean showCaller;
private final boolean complexRewriteMsg;
private final boolean ERROR;
private final boolean WARN;
private final boolean INFO;
private final boolean DEBUG;
private final boolean TRACE;
LogAdapter(final String name, final LoggerConfig config) {
this.name = name;
this.tag = config.tag;
if (config.level == LogLevel.NATIVE) {
config.level = getNativeLogLevel();
}
TRACE = (config.level == LogLevel.VERBOSE);
DEBUG = TRACE || (config.level == LogLevel.DEBUG);
INFO = DEBUG || (config.level == LogLevel.INFO);
WARN = INFO || (config.level == LogLevel.WARN);
ERROR = WARN || (config.level == LogLevel.ERROR);
switch (config.showName) {
case CALLER:
prefixName = null;
showCaller = true;
break;
case LONG:
prefixName = name.concat(": ");
showCaller = false;
break;
case COMPACT:
prefixName = getCompactName().concat(": ");
showCaller = false;
break;
case SHORT:
prefixName = name.substring(name.lastIndexOf('.') + 1).concat(": ");
showCaller = false;
break;
case FALSE:
default:
showCaller = false;
prefixName = null;
break;
}
showThread = config.showThread;
complexRewriteMsg = showThread || showCaller;
}
private final LogLevel getNativeLogLevel() {
LogLevel level = nativeLevelMap.get(tag);
if (level != null) {
return level;
}
/* Requires no more than 3 calls to isLoggable to find any level */
if (Log.isLoggable(tag, Log.INFO)) {
if (Log.isLoggable(tag, Log.DEBUG)) {
if (Log.isLoggable(tag, Log.VERBOSE)) {
level = LogLevel.VERBOSE;
} else {
level = LogLevel.DEBUG;
}
} else {
/* Default log level */
level = LogLevel.INFO;
}
} else if (Log.isLoggable(tag, Log.WARN)) {
level = LogLevel.WARN;
} else if (Log.isLoggable(tag, Log.ERROR)) {
level = LogLevel.ERROR;
} else {
level = LogLevel.SUPPRESS;
}
nativeLevelMap.put(tag, level);
return level;
}
private final String getCompactName() {
final char[] compactName = name.toCharArray();
final int arrayLen = compactName.length;
int len = 0;
int mark = 0;
for (int i = 0; i < arrayLen; i++, len++) {
if (compactName[i] == '.') {
len = mark;
if (compactName[len] != '.') {
len++;
}
mark = len;
if (i + 1 < arrayLen && compactName[i + 1] != '.') {
mark++;
}
}
compactName[len] = compactName[i];
}
return new String(compactName, 0, len);
}
@Override
public final String getName() {
return name;
}
private final String rewriteMsg(String msg, final int frames) {
if (msg == null) {
msg = "null";
}
if (complexRewriteMsg) {
final StringBuilder sb = new StringBuilder(msg.length() + 64);
if (showThread) {
sb.append('[').append(Thread.currentThread().getName()).append("] ");
}
if (showCaller) {
sb.append(new CallerStackTrace(frames).toString()).append(": ");
} else if (prefixName != null) {
sb.append(prefixName);
}
sb.append(msg);
return sb.toString();
} else if (prefixName != null) {
return prefixName.concat(msg);
} else {
return msg;
}
}
/* Trace */
@Override
public final boolean isTraceEnabled() {
return TRACE;
}
private final void __trace(final String msg, final Throwable t) {
if (t == null) {
Log.v(tag, msg);
} else {
Log.v(tag, msg, t);
}
}
private final void __traceFormat(final String format, final Object... arguments) {
final FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
__trace(rewriteMsg(ft.getMessage(), FORMAT_FRAMES), ft.getThrowable());
}
@Override
public final void trace(final String msg) {
if (TRACE) {
Log.v(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void trace(final String format, final Object arg) {
if (TRACE) {
__traceFormat(format, arg);
}
}
@Override
public final void trace(final String format, final Object arg1, final Object arg2) {
if (TRACE) {
__traceFormat(format, arg1, arg2);
}
}
@Override
public final void trace(final String format, final Object... arguments) {
if (TRACE) {
__traceFormat(format, arguments);
}
}
@Override
public final void trace(final String msg, final Throwable t) {
if (TRACE) {
__trace(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
@Override
public final boolean isTraceEnabled(final Marker marker) {
return TRACE;
}
@Override
public final void trace(final Marker marker, final String msg) {
if (TRACE) {
Log.v(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void trace(final Marker marker, final String format, final Object arg) {
if (TRACE) {
__traceFormat(format, arg);
}
}
@Override
public final void trace(final Marker marker, final String format, final Object arg1, final Object arg2) {
if (TRACE) {
__traceFormat(format, arg1, arg2);
}
}
@Override
public final void trace(final Marker marker, final String format, final Object... argArray) {
if (TRACE) {
__traceFormat(format, argArray);
}
}
@Override
public final void trace(final Marker marker, final String msg, final Throwable t) {
if (TRACE) {
__trace(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
/* Debug */
@Override
public final boolean isDebugEnabled() {
return DEBUG;
}
private final void __debug(final String msg, final Throwable t) {
if (t == null) {
Log.d(tag, msg);
} else {
Log.d(tag, msg, t);
}
}
private final void __debugFormat(final String format, final Object... arguments) {
final FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
__debug(rewriteMsg(ft.getMessage(), FORMAT_FRAMES), ft.getThrowable());
}
@Override
public final void debug(final String msg) {
if (DEBUG) {
Log.d(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void debug(final String format, final Object arg) {
if (DEBUG) {
__debugFormat(format, arg);
}
}
@Override
public final void debug(final String format, final Object arg1, final Object arg2) {
if (DEBUG) {
__debugFormat(format, arg1, arg2);
}
}
@Override
public final void debug(final String format, final Object... arguments) {
if (DEBUG) {
__debugFormat(format, arguments);
}
}
@Override
public final void debug(final String msg, final Throwable t) {
if (DEBUG) {
__debug(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
@Override
public final boolean isDebugEnabled(final Marker marker) {
return DEBUG;
}
@Override
public final void debug(final Marker marker, final String msg) {
if (DEBUG) {
Log.d(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void debug(final Marker marker, final String format, final Object arg) {
if (DEBUG) {
__debugFormat(format, arg);
}
}
@Override
public final void debug(final Marker marker, final String format, final Object arg1, final Object arg2) {
if (DEBUG) {
__debugFormat(format, arg1, arg2);
}
}
@Override
public final void debug(final Marker marker, final String format, final Object... argArray) {
if (DEBUG) {
__debugFormat(format, argArray);
}
}
@Override
public final void debug(final Marker marker, final String msg, final Throwable t) {
if (DEBUG) {
__debug(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
/* Info */
@Override
public final boolean isInfoEnabled() {
return INFO;
}
private final void __info(final String msg, final Throwable t) {
if (t == null) {
Log.i(tag, msg);
} else {
Log.i(tag, msg, t);
}
}
private final void __infoFormat(final String format, final Object... arguments) {
final FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
__info(rewriteMsg(ft.getMessage(), FORMAT_FRAMES), ft.getThrowable());
}
@Override
public final void info(final String msg) {
if (INFO) {
Log.i(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void info(final String format, final Object arg) {
if (INFO) {
__infoFormat(format, arg);
}
}
@Override
public final void info(final String format, final Object arg1, final Object arg2) {
if (INFO) {
__infoFormat(format, arg1, arg2);
}
}
@Override
public final void info(final String format, final Object... arguments) {
if (INFO) {
__infoFormat(format, arguments);
}
}
@Override
public final void info(final String msg, final Throwable t) {
if (INFO) {
__info(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
@Override
public final boolean isInfoEnabled(final Marker marker) {
return INFO;
}
@Override
public final void info(final Marker marker, final String msg) {
if (INFO) {
Log.i(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void info(final Marker marker, final String format, final Object arg) {
if (INFO) {
__infoFormat(format, arg);
}
}
@Override
public final void info(final Marker marker, final String format, final Object arg1, final Object arg2) {
if (INFO) {
__infoFormat(format, arg1, arg2);
}
}
@Override
public final void info(final Marker marker, final String format, final Object... argArray) {
if (INFO) {
__infoFormat(format, argArray);
}
}
@Override
public final void info(final Marker marker, final String msg, final Throwable t) {
if (INFO) {
__info(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
/* Warn */
@Override
public final boolean isWarnEnabled() {
return WARN;
}
private final void __warn(final String msg, final Throwable t) {
if (t == null) {
Log.w(tag, msg);
} else {
Log.w(tag, msg, t);
}
}
private final void __warnFormat(final String format, final Object... arguments) {
final FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
__warn(rewriteMsg(ft.getMessage(), FORMAT_FRAMES), ft.getThrowable());
}
@Override
public final void warn(final String msg) {
if (WARN) {
Log.w(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void warn(final String format, final Object arg) {
if (WARN) {
__warnFormat(format, arg);
}
}
@Override
public final void warn(final String format, final Object arg1, final Object arg2) {
if (WARN) {
__warnFormat(format, arg1, arg2);
}
}
@Override
public final void warn(final String format, final Object... arguments) {
if (WARN) {
__warnFormat(format, arguments);
}
}
@Override
public final void warn(final String msg, final Throwable t) {
if (WARN) {
__warn(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
@Override
public final boolean isWarnEnabled(final Marker marker) {
return WARN;
}
@Override
public final void warn(final Marker marker, final String msg) {
if (WARN) {
Log.w(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void warn(final Marker marker, final String format, final Object arg) {
if (WARN) {
__warnFormat(format, arg);
}
}
@Override
public final void warn(final Marker marker, final String format, final Object arg1, final Object arg2) {
if (WARN) {
__warnFormat(format, arg1, arg2);
}
}
@Override
public final void warn(final Marker marker, final String format, final Object... argArray) {
if (WARN) {
__warnFormat(format, argArray);
}
}
@Override
public final void warn(final Marker marker, final String msg, final Throwable t) {
if (WARN) {
__warn(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
/* Error */
@Override
public final boolean isErrorEnabled() {
return ERROR;
}
private final void __error(final String msg, final Throwable t) {
if (t == null) {
Log.e(tag, msg);
} else {
Log.e(tag, msg, t);
}
}
private final void __errorFormat(final String format, final Object... arguments) {
final FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
__error(rewriteMsg(ft.getMessage(), FORMAT_FRAMES), ft.getThrowable());
}
@Override
public final void error(final String msg) {
if (ERROR) {
Log.e(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void error(final String format, final Object arg) {
if (ERROR) {
__errorFormat(format, arg);
}
}
@Override
public final void error(final String format, final Object arg1, final Object arg2) {
if (ERROR) {
__errorFormat(format, arg1, arg2);
}
}
@Override
public final void error(final String format, final Object... arguments) {
if (ERROR) {
__errorFormat(format, arguments);
}
}
@Override
public final void error(final String msg, final Throwable t) {
if (ERROR) {
__error(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
@Override
public final boolean isErrorEnabled(final Marker marker) {
return ERROR;
}
@Override
public final void error(final Marker marker, final String msg) {
if (ERROR) {
Log.e(tag, rewriteMsg(msg, DIRECT_FRAMES));
}
}
@Override
public final void error(final Marker marker, final String format, final Object arg) {
if (ERROR) {
__errorFormat(format, arg);
}
}
@Override
public final void error(final Marker marker, final String format, final Object arg1, final Object arg2) {
if (ERROR) {
__errorFormat(format, arg1, arg2);
}
}
@Override
public final void error(final Marker marker, final String format, final Object... argArray) {
if (ERROR) {
__errorFormat(format, argArray);
}
}
@Override
public final void error(final Marker marker, final String msg, final Throwable t) {
if (ERROR) {
__error(rewriteMsg(msg, DIRECT_FRAMES), t);
}
}
}
| mit |
arjan/beacon_lib | src/main/java/nl/miraclethings/beaconlib/detector/BeaconZoneVotingDetector.java | 4138 | package nl.miraclethings.beaconlib.detector;
import org.altbeacon.beacon.Beacon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import nl.miraclethings.beaconlib.Zone;
import nl.miraclethings.beaconlib.ZoneMap;
/**
* Created by arjan on 23-9-15.
*/
public class BeaconZoneVotingDetector implements BeaconZoneDetector {
static Logger logger = LoggerFactory.getLogger(BeaconZoneVotingDetector.class);
private int mCandidateRegionCount;
private String mCandidateZone;
private ZoneMap mZoneMap;
private String mCurrentZone;
@Override
public DetectorResult run(Collection<Beacon> beacons) {
int numBeaconsFound = 0;
List<String> zoneCandidates = new ArrayList<String>();
Beacon foundBeacon = null;
for (Beacon beacon : beacons) {
if (beacon.getDistance() > 50) {
logger.info("Skipping beacon {}, distance too big", beacon.toString());
continue;
}
//logger.info("Beacon {} {} {} distance {}", beacon.getId1().toUuidString(), beacon.getId2().toInt(), beacon.getId3().toInt(), beacon.getDistance());
for (Map.Entry<String, Zone> entry : mZoneMap.entrySet()) {
String zoneIdentifier = entry.getKey();
Zone zone = entry.getValue();
for (Zone.Beacon checkBeacon : zone.beacons) {
if (checkBeacon.uuid != null && !checkBeacon.uuid.equalsIgnoreCase(beacon.getId1().toUuidString())) {
continue;
}
if (checkBeacon.major != 0 && checkBeacon.major != beacon.getId2().toInt()) {
continue;
}
if (checkBeacon.minor != 0 && checkBeacon.minor != beacon.getId3().toInt()) {
continue;
}
foundBeacon = beacon;
if (!zoneCandidates.contains(zoneIdentifier)) {
zoneCandidates.add(zoneIdentifier);
}
numBeaconsFound++;
}
}
}
int zonesFound = zoneCandidates.size();
boolean zoneChanged = determineRegionWinner(zonesFound == 1 ? zoneCandidates.get(0) : "", zonesFound > 1);
String msg = "No beacons";
if (numBeaconsFound >= 1) {
msg = "B: " + numBeaconsFound+ " L: " + zonesFound;
}
msg += " Z: " + mCurrentZone;
return new DetectorResult(mCurrentZone, zoneChanged, msg);
}
@Override
@Nullable
public Beacon getLastBeacon() {
return null;
}
private boolean determineRegionWinner(String region, boolean hasMultiple) {
boolean zoneChanged = false;
if (mCurrentZone == null && !region.equals("")) {
// shortcut
mCurrentZone = region;
zoneChanged = true;
} else if (!hasMultiple) {
if (!region.equals(mCurrentZone)) {
if (region.equals(mCandidateZone)) {
mCandidateRegionCount++;
} else {
mCandidateZone = region;
mCandidateRegionCount = 0;
}
int limit = 2;
if (mCandidateZone.equals("")) {
limit = 2;
}
if (mCandidateRegionCount >= limit) {
mCurrentZone = mCandidateZone;
mCandidateRegionCount = 0;
zoneChanged = true;
logger.info("Change region to: " + mCurrentZone);
}
}
}
if (zoneChanged && "".equals(mCurrentZone)) {
mCurrentZone = null;
}
return zoneChanged;
}
@Override
public void setZoneMap(ZoneMap zoneMap) {
mZoneMap = zoneMap;
}
@Override
public boolean isConfigured() {
return mZoneMap != null;
}
}
| mit |
fl0co/RC24-Bot | src/main/java/xyz/rc24/bot/core/SimpleCacheBuilder.java | 1799 | /*
* MIT License
*
* Copyright (c) 2017-2019 RiiConnect24 and its contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package xyz.rc24.bot.core;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
/**
* Easy cache builder for our needs.
*
* @author Artuto
*/
public class SimpleCacheBuilder<K, V>
{
private int expireHours = 1;
public SimpleCacheBuilder() {}
public SimpleCacheBuilder(int expireHours)
{
this.expireHours = expireHours;
}
public <K1 extends K, V1 extends V> Cache<K1, V1> build()
{
return CacheBuilder.newBuilder()
.expireAfterAccess(expireHours, TimeUnit.HOURS)
.maximumSize(500).build();
}
}
| mit |
pshynin/JavaRushTasks | 3.JavaMultithreading/src/com/javarush/task/task24/task2408/SuperDog.java | 295 | package com.javarush.task.task24.task2408;
import java.text.SimpleDateFormat;
public abstract class SuperDog {
protected String getSuperQuotes() {
//some logic here
return " *** ";
}
protected SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy EE");
}
| mit |
swaplicado/siie32 | src/erp/mtrn/form/SFormSystemNotes.java | 24184 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* SFormSystemNotes.java
*/
package erp.mtrn.form;
import erp.data.SDataConstants;
import erp.lib.SLibConstants;
import erp.lib.form.SFormComboBoxGroup;
import erp.lib.form.SFormComponentItem;
import erp.lib.form.SFormField;
import erp.lib.form.SFormUtilities;
import erp.lib.form.SFormValidation;
import erp.mtrn.data.SDataSystemNotes;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
/**
*
* @author Juan Barajas, Sergio Flores
*/
public class SFormSystemNotes extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener, java.awt.event.ItemListener {
private int mnFormType;
private int mnFormResult;
private int mnFormStatus;
private boolean mbFirstTime;
private boolean mbResetingForm;
private java.util.Vector<erp.lib.form.SFormField> mvFields;
private erp.client.SClientInterface miClient;
private erp.mtrn.data.SDataSystemNotes moSystemNotes;
private erp.lib.form.SFormComboBoxGroup moComboBoxGroup;
private erp.lib.form.SFormField moFieldNotes;
private erp.lib.form.SFormField moFieldIsDeleted;
private erp.lib.form.SFormField moFieldFkDpsCategoryId;
private erp.lib.form.SFormField moFieldFkDpsClassId;
private erp.lib.form.SFormField moFieldFkDpsTypeId;
private erp.lib.form.SFormField moFieldFkCurrencyId;
private erp.lib.form.SFormField moFieldIsAutomatic;
private erp.lib.form.SFormField moFieldIsPrintable;
private erp.lib.form.SFormField moFieldIsCfdComplement;
private erp.lib.form.SFormField moFieldCfdComplementDisposition;
private erp.lib.form.SFormField moFieldCfdComplementRule;
/** Creates new form SFormSystemNotes
* @param client GUI client.
*/
public SFormSystemNotes(erp.client.SClientInterface client) {
super(client.getFrame(), true);
miClient = client;
mnFormType = SDataConstants.TRN_SYS_NTS;
initComponents();
initComponentsExtra();
}
/** 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() {
jpRegistry = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel12 = new javax.swing.JPanel();
jlNotes = new javax.swing.JLabel();
jckIsDeleted = new javax.swing.JCheckBox();
jspNotes = new javax.swing.JScrollPane();
jtaNotes = new javax.swing.JTextArea();
jPanel13 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jlFkDpsCategoryId = new javax.swing.JLabel();
jcbFkDpsCategoryId = new javax.swing.JComboBox<SFormComponentItem>();
jPanel7 = new javax.swing.JPanel();
jlFkDpsClassId = new javax.swing.JLabel();
jcbFkDpsClassId = new javax.swing.JComboBox<SFormComponentItem>();
jPanel8 = new javax.swing.JPanel();
jlFkDpsTypeId = new javax.swing.JLabel();
jcbFkDpsTypeId = new javax.swing.JComboBox<SFormComponentItem>();
jPanel10 = new javax.swing.JPanel();
jlFkCurrencyId = new javax.swing.JLabel();
jcbFkCurrencyId = new javax.swing.JComboBox<SFormComponentItem>();
jPanel9 = new javax.swing.JPanel();
jckIsAutomatic = new javax.swing.JCheckBox();
jckIsPrintable = new javax.swing.JCheckBox();
jPanel1 = new javax.swing.JPanel();
jckIsCfdComplement = new javax.swing.JCheckBox();
jPanel3 = new javax.swing.JPanel();
jlCfdComplementDisposition = new javax.swing.JLabel();
jtfCfdComplementDisposition = new javax.swing.JTextField();
jlCfdComplementDispositionHint = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jlCfdComplementRule = new javax.swing.JLabel();
jtfCfdComplementRule = new javax.swing.JTextField();
jlCfdComplementRuleHint = new javax.swing.JLabel();
jpControls = new javax.swing.JPanel();
jbOk = new javax.swing.JButton();
jbCancel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Nota predefinida de documento");
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
jpRegistry.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:"));
jpRegistry.setLayout(new java.awt.BorderLayout());
jPanel2.setLayout(new java.awt.BorderLayout(0, 3));
jPanel5.setLayout(new java.awt.BorderLayout());
jPanel12.setLayout(new java.awt.BorderLayout());
jlNotes.setForeground(new java.awt.Color(0, 102, 102));
jlNotes.setText("Notas predeterminadas: *");
jlNotes.setPreferredSize(new java.awt.Dimension(150, 23));
jPanel12.add(jlNotes, java.awt.BorderLayout.CENTER);
jckIsDeleted.setForeground(java.awt.Color.red);
jckIsDeleted.setText("Registro eliminado");
jckIsDeleted.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jckIsDeleted.setPreferredSize(new java.awt.Dimension(150, 23));
jPanel12.add(jckIsDeleted, java.awt.BorderLayout.EAST);
jPanel5.add(jPanel12, java.awt.BorderLayout.NORTH);
jspNotes.setPreferredSize(new java.awt.Dimension(100, 100));
jtaNotes.setColumns(20);
jtaNotes.setRows(5);
jspNotes.setViewportView(jtaNotes);
jPanel5.add(jspNotes, java.awt.BorderLayout.CENTER);
jPanel2.add(jPanel5, java.awt.BorderLayout.NORTH);
jPanel13.setLayout(new java.awt.GridLayout(8, 1, 0, 3));
jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlFkDpsCategoryId.setText("Categoría documento: *");
jlFkDpsCategoryId.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel6.add(jlFkDpsCategoryId);
jcbFkDpsCategoryId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbFkDpsCategoryId.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel6.add(jcbFkDpsCategoryId);
jPanel13.add(jPanel6);
jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlFkDpsClassId.setText("Clase documento: *");
jlFkDpsClassId.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel7.add(jlFkDpsClassId);
jcbFkDpsClassId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbFkDpsClassId.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel7.add(jcbFkDpsClassId);
jPanel13.add(jPanel7);
jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlFkDpsTypeId.setText("Tipo documento: *");
jlFkDpsTypeId.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel8.add(jlFkDpsTypeId);
jcbFkDpsTypeId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbFkDpsTypeId.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel8.add(jcbFkDpsTypeId);
jPanel13.add(jPanel8);
jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlFkCurrencyId.setText("Moneda: *");
jlFkCurrencyId.setPreferredSize(new java.awt.Dimension(125, 23));
jPanel10.add(jlFkCurrencyId);
jcbFkCurrencyId.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jcbFkCurrencyId.setPreferredSize(new java.awt.Dimension(200, 23));
jPanel10.add(jcbFkCurrencyId);
jPanel13.add(jPanel10);
jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jckIsAutomatic.setText("Adición automática al crear documentos");
jckIsAutomatic.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel9.add(jckIsAutomatic);
jckIsPrintable.setText("Visible al imprimir");
jckIsPrintable.setPreferredSize(new java.awt.Dimension(150, 23));
jPanel9.add(jckIsPrintable);
jPanel13.add(jPanel9);
jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jckIsCfdComplement.setText("Se integra como complemento CFDI Leyendas Fiscales");
jckIsCfdComplement.setPreferredSize(new java.awt.Dimension(300, 23));
jPanel1.add(jckIsCfdComplement);
jPanel13.add(jPanel1);
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlCfdComplementDisposition.setForeground(new java.awt.Color(0, 102, 102));
jlCfdComplementDisposition.setText("Disposición fiscal:");
jlCfdComplementDisposition.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel3.add(jlCfdComplementDisposition);
jtfCfdComplementDisposition.setPreferredSize(new java.awt.Dimension(450, 23));
jPanel3.add(jtfCfdComplementDisposition);
jlCfdComplementDispositionHint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N
jlCfdComplementDispositionHint.setToolTipText("Ley, resolución o disposición fiscal que regula la leyenda, en siglas en mayúsculas y sin puntuación, p. ej., ISR");
jlCfdComplementDispositionHint.setPreferredSize(new java.awt.Dimension(18, 23));
jPanel3.add(jlCfdComplementDispositionHint);
jPanel13.add(jPanel3);
jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));
jlCfdComplementRule.setForeground(new java.awt.Color(0, 102, 102));
jlCfdComplementRule.setText("Norma:");
jlCfdComplementRule.setPreferredSize(new java.awt.Dimension(100, 23));
jPanel4.add(jlCfdComplementRule);
jtfCfdComplementRule.setPreferredSize(new java.awt.Dimension(450, 23));
jPanel4.add(jtfCfdComplementRule);
jlCfdComplementRuleHint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/icon_view_help.png"))); // NOI18N
jlCfdComplementRuleHint.setToolTipText("Artículo o regla que regula la obligación de la leyenda");
jlCfdComplementRuleHint.setPreferredSize(new java.awt.Dimension(18, 23));
jPanel4.add(jlCfdComplementRuleHint);
jPanel13.add(jPanel4);
jPanel2.add(jPanel13, java.awt.BorderLayout.CENTER);
jpRegistry.add(jPanel2, java.awt.BorderLayout.NORTH);
getContentPane().add(jpRegistry, java.awt.BorderLayout.CENTER);
jpControls.setPreferredSize(new java.awt.Dimension(392, 33));
jpControls.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
jbOk.setText("Aceptar");
jbOk.setToolTipText("[Ctrl + Enter]");
jbOk.setPreferredSize(new java.awt.Dimension(75, 23));
jpControls.add(jbOk);
jbCancel.setText("Cancelar");
jbCancel.setToolTipText("[Escape]");
jpControls.add(jbCancel);
getContentPane().add(jpControls, java.awt.BorderLayout.SOUTH);
setSize(new java.awt.Dimension(656, 439));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
windowActivated();
}//GEN-LAST:event_formWindowActivated
private void initComponentsExtra() {
moComboBoxGroup = new SFormComboBoxGroup(miClient);
moFieldNotes = new SFormField(miClient, SLibConstants.DATA_TYPE_STRING, true, jtaNotes, jlNotes);
moFieldNotes.setLengthMax(1023);
moFieldNotes.setAutoCaseType(0);
moFieldIsDeleted = new SFormField(miClient, SLibConstants.DATA_TYPE_BOOLEAN, false, jckIsDeleted);
moFieldFkDpsCategoryId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, true, jcbFkDpsCategoryId, jlFkDpsCategoryId);
moFieldFkDpsClassId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, true, jcbFkDpsClassId, jlFkDpsClassId);
moFieldFkDpsTypeId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, true, jcbFkDpsTypeId, jlFkDpsTypeId);
moFieldFkCurrencyId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, true, jcbFkCurrencyId, jlFkCurrencyId);
moFieldIsAutomatic = new SFormField(miClient, SLibConstants.DATA_TYPE_BOOLEAN, false, jckIsAutomatic);
moFieldIsPrintable = new SFormField(miClient, SLibConstants.DATA_TYPE_BOOLEAN, false, jckIsPrintable);
moFieldIsCfdComplement = new SFormField(miClient, SLibConstants.DATA_TYPE_BOOLEAN, false, jckIsCfdComplement);
moFieldCfdComplementDisposition = new SFormField(miClient, SLibConstants.DATA_TYPE_STRING, false, jtfCfdComplementDisposition, jlCfdComplementDisposition);
moFieldCfdComplementDisposition.setLengthMax(255);
moFieldCfdComplementDisposition.setAutoCaseType(0);
moFieldCfdComplementRule = new SFormField(miClient, SLibConstants.DATA_TYPE_STRING, false, jtfCfdComplementRule, jlCfdComplementRule);
moFieldCfdComplementRule.setLengthMax(255);
moFieldCfdComplementRule.setAutoCaseType(0);
mvFields = new Vector<>();
mvFields.add(moFieldNotes);
mvFields.add(moFieldIsDeleted);
mvFields.add(moFieldFkDpsCategoryId);
mvFields.add(moFieldFkDpsClassId);
mvFields.add(moFieldFkDpsTypeId);
mvFields.add(moFieldFkCurrencyId);
mvFields.add(moFieldIsAutomatic);
mvFields.add(moFieldIsPrintable);
mvFields.add(moFieldIsCfdComplement);
mvFields.add(moFieldCfdComplementDisposition);
mvFields.add(moFieldCfdComplementRule);
jbOk.addActionListener(this);
jbCancel.addActionListener(this);
jckIsCfdComplement.addItemListener(this);
AbstractAction actionOk = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { actionOk(); }
};
SFormUtilities.putActionMap(getRootPane(), actionOk, "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);
AbstractAction action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) { actionCancel(); }
};
SFormUtilities.putActionMap(getRootPane(), action, "cancel", KeyEvent.VK_ESCAPE, 0);
}
private void windowActivated() {
if (mbFirstTime) {
mbFirstTime = false;
jtaNotes.requestFocus();
}
}
private void actionOk() {
SFormValidation validation = formValidate();
if (validation.getIsError()) {
if (validation.getComponent() != null) {
validation.getComponent().requestFocus();
}
if (validation.getMessage().length() > 0) {
miClient.showMsgBoxWarning(validation.getMessage());
}
}
else {
mnFormResult = SLibConstants.FORM_RESULT_OK;
setVisible(false);
}
}
private void actionCancel() {
mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
setVisible(false);
}
private void itemStateChangedCfdComplement() {
if (jckIsCfdComplement.isSelected()) {
jtfCfdComplementDisposition.setEditable(true);
jtfCfdComplementDisposition.setFocusable(true);
jtfCfdComplementRule.setEditable(true);
jtfCfdComplementRule.setFocusable(true);
jtfCfdComplementDisposition.requestFocusInWindow();
}
else {
jtfCfdComplementDisposition.setEditable(false);
jtfCfdComplementDisposition.setFocusable(false);
jtfCfdComplementRule.setEditable(false);
jtfCfdComplementRule.setFocusable(false);
moFieldCfdComplementDisposition.resetField();
moFieldCfdComplementRule.resetField();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JButton jbCancel;
private javax.swing.JButton jbOk;
private javax.swing.JComboBox<SFormComponentItem> jcbFkCurrencyId;
private javax.swing.JComboBox<SFormComponentItem> jcbFkDpsCategoryId;
private javax.swing.JComboBox<SFormComponentItem> jcbFkDpsClassId;
private javax.swing.JComboBox<SFormComponentItem> jcbFkDpsTypeId;
private javax.swing.JCheckBox jckIsAutomatic;
private javax.swing.JCheckBox jckIsCfdComplement;
private javax.swing.JCheckBox jckIsDeleted;
private javax.swing.JCheckBox jckIsPrintable;
private javax.swing.JLabel jlCfdComplementDisposition;
private javax.swing.JLabel jlCfdComplementDispositionHint;
private javax.swing.JLabel jlCfdComplementRule;
private javax.swing.JLabel jlCfdComplementRuleHint;
private javax.swing.JLabel jlFkCurrencyId;
private javax.swing.JLabel jlFkDpsCategoryId;
private javax.swing.JLabel jlFkDpsClassId;
private javax.swing.JLabel jlFkDpsTypeId;
private javax.swing.JLabel jlNotes;
private javax.swing.JPanel jpControls;
private javax.swing.JPanel jpRegistry;
private javax.swing.JScrollPane jspNotes;
private javax.swing.JTextArea jtaNotes;
private javax.swing.JTextField jtfCfdComplementDisposition;
private javax.swing.JTextField jtfCfdComplementRule;
// End of variables declaration//GEN-END:variables
@Override
public void formClearRegistry() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void formReset() {
mnFormResult = SLibConstants.UNDEFINED;
mnFormStatus = SLibConstants.UNDEFINED;
mbFirstTime = true;
moSystemNotes = null;
for (int i = 0; i < mvFields.size(); i++) {
((erp.lib.form.SFormField) mvFields.get(i)).resetField();
}
moComboBoxGroup.reset();
moFieldIsAutomatic.setFieldValue(true);
moFieldIsPrintable.setFieldValue(true);
moFieldIsCfdComplement.setFieldValue(false);
itemStateChangedCfdComplement();
jckIsDeleted.setEnabled(false);
}
@Override
public void formRefreshCatalogues() {
moComboBoxGroup.clear();
moComboBoxGroup.addComboBox(SDataConstants.TRNS_CT_DPS, jcbFkDpsCategoryId);
moComboBoxGroup.addComboBox(SDataConstants.TRNS_CL_DPS, jcbFkDpsClassId);
moComboBoxGroup.addComboBox(SDataConstants.TRNU_TP_DPS, jcbFkDpsTypeId);
SFormUtilities.populateComboBox(miClient, jcbFkCurrencyId, SDataConstants.CFGU_CUR, new int[] { miClient.getSessionXXX().getParamsErp().getFkCurrencyId() });
}
@Override
public erp.lib.form.SFormValidation formValidate() {
SFormValidation validation = new SFormValidation();
for (int i = 0; i < mvFields.size(); i++) {
if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) {
validation.setIsError(true);
validation.setComponent(((erp.lib.form.SFormField) mvFields.get(i)).getComponent());
break;
}
}
return validation;
}
@Override
public void setFormStatus(int status) {
mnFormStatus = status;
}
@Override
public void setFormVisible(boolean visible) {
setVisible(visible);
}
@Override
public int getFormStatus() {
return mnFormStatus;
}
@Override
public int getFormResult() {
return mnFormResult;
}
@Override
public void setRegistry(erp.lib.data.SDataRegistry registry) {
moSystemNotes = (SDataSystemNotes) registry;
moFieldNotes.setFieldValue(moSystemNotes.getNotes());
moFieldIsDeleted.setFieldValue(moSystemNotes.getIsDeleted());
moFieldFkDpsCategoryId.setFieldValue(new int[] { moSystemNotes.getFkDpsCategoryId() });
moFieldFkDpsClassId.setFieldValue(new int[] { moSystemNotes.getFkDpsCategoryId(), moSystemNotes.getFkDpsClassId() });
moFieldFkDpsTypeId.setFieldValue(new int[] { moSystemNotes.getFkDpsCategoryId(), moSystemNotes.getFkDpsClassId(), moSystemNotes.getFkDpsTypeId() });
moFieldFkCurrencyId.setFieldValue(new int[] { moSystemNotes.getFkCurrencyId() });
moFieldIsAutomatic.setFieldValue(moSystemNotes.getIsAutomatic());
moFieldIsPrintable.setFieldValue(moSystemNotes.getIsPrintable());
moFieldIsCfdComplement.setFieldValue(moSystemNotes.getIsCfdComplement());
moFieldCfdComplementDisposition.setFieldValue(moSystemNotes.getCfdComplementDisposition());
moFieldCfdComplementRule.setFieldValue(moSystemNotes.getCfdComplementRule());
jckIsDeleted.setEnabled(true);
}
@Override
public erp.lib.data.SDataRegistry getRegistry() {
if (moSystemNotes == null) {
moSystemNotes = new SDataSystemNotes();
moSystemNotes.setFkUserNewId(miClient.getSession().getUser().getPkUserId());
}
else {
moSystemNotes.setFkUserEditId(miClient.getSession().getUser().getPkUserId());
}
moSystemNotes.setNotes(moFieldNotes.getString());
moSystemNotes.setCfdComplementDisposition(moFieldCfdComplementDisposition.getString());
moSystemNotes.setCfdComplementRule(moFieldCfdComplementRule.getString());
moSystemNotes.setIsAutomatic(moFieldIsAutomatic.getBoolean());
moSystemNotes.setIsPrintable(moFieldIsPrintable.getBoolean());
moSystemNotes.setIsCfdComplement(moFieldIsCfdComplement.getBoolean());
moSystemNotes.setIsDeleted(moFieldIsDeleted.getBoolean());
moSystemNotes.setFkDpsCategoryId(moFieldFkDpsTypeId.getKeyAsIntArray()[0]);
moSystemNotes.setFkDpsClassId(moFieldFkDpsTypeId.getKeyAsIntArray()[1]);
moSystemNotes.setFkDpsTypeId(moFieldFkDpsTypeId.getKeyAsIntArray()[2]);
moSystemNotes.setFkCurrencyId(moFieldFkCurrencyId.getKeyAsIntArray()[0]);
return moSystemNotes;
}
@Override
public void setValue(int type, java.lang.Object value) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public java.lang.Object getValue(int type) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public javax.swing.JLabel getTimeoutLabel() {
return null;
}
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if (e.getSource() instanceof javax.swing.JButton) {
javax.swing.JButton button = (javax.swing.JButton) e.getSource();
if (button == jbOk) {
actionOk();
}
else if (button == jbCancel) {
actionCancel();
}
}
}
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof javax.swing.JCheckBox) {
javax.swing.JCheckBox checkBox = (javax.swing.JCheckBox) e.getSource();
if (checkBox == jckIsCfdComplement) {
itemStateChangedCfdComplement();
}
}
}
}
| mit |
jhsx/hacklang-idea | gen/io/github/josehsantos/hack/lang/psi/impl/HackStaticScalarAttributeImpl.java | 1627 | // This is a generated file. Not intended for manual editing.
package io.github.josehsantos.hack.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static io.github.josehsantos.hack.lang.psi.HackTypes.*;
import io.github.josehsantos.hack.lang.psi.*;
public class HackStaticScalarAttributeImpl extends HackPsiElementImpl implements HackStaticScalarAttribute {
public HackStaticScalarAttributeImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof HackVisitor) ((HackVisitor)visitor).visitStaticScalarAttribute(this);
else super.accept(visitor);
}
@Override
@Nullable
public HackIdentifier getIdentifier() {
return findChildByClass(HackIdentifier.class);
}
@Override
@Nullable
public HackLiteralScalarAttribute getLiteralScalarAttribute() {
return findChildByClass(HackLiteralScalarAttribute.class);
}
@Override
@Nullable
public HackStaticArrayPairListAttribute getStaticArrayPairListAttribute() {
return findChildByClass(HackStaticArrayPairListAttribute.class);
}
@Override
@Nullable
public HackStaticNumericScalarAttribute getStaticNumericScalarAttribute() {
return findChildByClass(HackStaticNumericScalarAttribute.class);
}
@Override
@Nullable
public HackStaticShapePairListAttribute getStaticShapePairListAttribute() {
return findChildByClass(HackStaticShapePairListAttribute.class);
}
}
| mit |
garymabin/YGOMobile | apache-async-http-HC4/src/org/apache/http/HC4/impl/conn/CPoolEntry.java | 3303 | /*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.HC4.impl.conn;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.http.HC4.HttpClientConnection;
import org.apache.http.HC4.annotation.ThreadSafe;
import org.apache.http.HC4.conn.ManagedHttpClientConnection;
import org.apache.http.HC4.pool.PoolEntry;
import org.apache.http.HC4.conn.routing.HttpRoute;
/**
* @since 4.3
*/
@ThreadSafe
class CPoolEntry extends PoolEntry<HttpRoute, ManagedHttpClientConnection> {
private final Log log;
private volatile boolean routeComplete;
public CPoolEntry(
final Log log,
final String id,
final HttpRoute route,
final ManagedHttpClientConnection conn,
final long timeToLive, final TimeUnit tunit) {
super(id, route, conn, timeToLive, tunit);
this.log = log;
}
public void markRouteComplete() {
this.routeComplete = true;
}
public boolean isRouteComplete() {
return this.routeComplete;
}
public void closeConnection() throws IOException {
final HttpClientConnection conn = getConnection();
conn.close();
}
public void shutdownConnection() throws IOException {
final HttpClientConnection conn = getConnection();
conn.shutdown();
}
@Override
public boolean isExpired(final long now) {
final boolean expired = super.isExpired(now);
if (expired && this.log.isDebugEnabled()) {
this.log.debug("Connection " + this + " expired @ " + new Date(getExpiry()));
}
return expired;
}
@Override
public boolean isClosed() {
final HttpClientConnection conn = getConnection();
return !conn.isOpen();
}
@Override
public void close() {
try {
closeConnection();
} catch (final IOException ex) {
this.log.debug("I/O error closing connection", ex);
}
}
}
| mit |
jjsalomon/chess_game | src/com/chess/engine/board/MoveTransition.java | 812 | package com.chess.engine.board;
import com.chess.engine.board.Move.MoveStatus;
public final class MoveTransition {
private final Board fromBoard;
private final Board toBoard;
private final Move move;
private final MoveStatus moveStatus;
public MoveTransition(final Board fromBoard,
final Board toBoard,
final Move move,
final MoveStatus moveStatus) {
this.fromBoard = fromBoard;
this.toBoard = toBoard;
this.move = move;
this.moveStatus = moveStatus;
}
public Board getToBoard() {
return this.toBoard;
}
public Board getFromBoard() {
return this.fromBoard;
}
public MoveStatus getMoveStatus() {
return this.moveStatus;
}
}
| mit |
yoo2001818/RogueBox | src/main/java/kr/kkiro/roguebox/game/item/type/BreadItem.java | 607 | package kr.kkiro.roguebox.game.item.type;
import kr.kkiro.roguebox.game.item.ItemEntryUseable;
import kr.kkiro.roguebox.game.item.ItemStack;
import kr.kkiro.roguebox.game.item.ItemType;
import kr.kkiro.roguebox.util.I18n;
public class BreadItem extends ItemEntryUseable {
public BreadItem() {
super(I18n._("bread"), ItemType.FOOD);
}
@Override
public String use(ItemStack stack) {
stack.getInventory().getCharacter().heal(4);
stack.getInventory().removeItem(stack.getCode(), 1);
return I18n._("eatMsg", getName());
}
@Override
public void obtain(ItemStack stack) {
}
}
| mit |
CS2103AUG2016-W13-C2/main | src/main/java/seedu/ggist/model/task/UniqueTaskList.java | 8556 | package seedu.ggist.model.task;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.ggist.commons.core.Messages;
import seedu.ggist.commons.exceptions.DuplicateDataException;
import seedu.ggist.commons.exceptions.IllegalValueException;
import seedu.ggist.commons.util.CollectionUtil;
import seedu.ggist.logic.parser.DateTimeParser;
import java.util.*;
import org.ocpsoft.prettytime.nlp.PrettyTimeParser;
/**
* A list of tasks that enforces uniqueness between its elements and does not allow nulls.
*
* Supports a minimal set of list operations.
*
* @see Task#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueTaskList implements Iterable<Task> {
/**
* Signals that an operation would have violated the 'no duplicates' property of the list.
*/
public static class DuplicateTaskException extends DuplicateDataException {
protected DuplicateTaskException() {
super("Operation would result in duplicate task");
}
}
/**
* Signals that an operation targeting a specified task in the list would fail because
* there is no such matching task in the list.
*/
public static class TaskNotFoundException extends Exception {
public TaskNotFoundException() {
super("Target task is not found");
}
}
private final ObservableList<Task> internalList = FXCollections.observableArrayList();
/**
* Constructs empty TaskList.
*/
public UniqueTaskList() {}
/**
* Returns true if the list contains an equivalent task as the given argument.
*/
public boolean contains(ReadOnlyTask toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/**
* Adds a task to the list.
*
* @throws DuplicateTaskException if the task to add is a duplicate of an existing task in the list.
*/
public void add(Task toAdd) throws DuplicateTaskException {
assert toAdd != null;
if (contains(toAdd)) {
throw new DuplicateTaskException();
}
internalList.add(toAdd);
}
/**
* Removes the equivalent task from the list.
*
* @throws TaskNotFoundException if no such task could be found in the list.
*/
public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException {
assert toRemove != null;
final boolean taskFoundAndDeleted = internalList.remove(toRemove);
if (!taskFoundAndDeleted) {
throw new TaskNotFoundException();
}
return taskFoundAndDeleted;
}
//@@author A0138411N
public void edit(ReadOnlyTask toEdit, String field, String value) throws IllegalValueException {
assert toEdit != null;
switch (field) {
case "task":
toEdit.getTaskName().editTaskName(value);
break;
case "start date":
Task.checkTimeClash(Task.formatMissingDateTime(new TaskDate(value),toEdit.getStartTime()),(toEdit.getEndDateTime()));
toEdit.getStartDate().editDate(value);
toEdit.constructStartDateTime(toEdit.getStartDate(), toEdit.getStartTime());
toEdit.checkTimeOverdue();
break;
case "start time":
if (!toEdit.getEndDate().value.equals(Messages.MESSAGE_NO_END_DATE_SPECIFIED)
&& toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED)){
Task.checkTimeClash(Task.formatMissingDateTime(toEdit.getEndDate(), new TaskTime(value)), toEdit.getEndDateTime());
toEdit.getStartTime().editTime(value);
} else {
Task.checkTimeClash(Task.formatMissingDateTime(toEdit.getEndDate(), new TaskTime(value)), toEdit.getEndDateTime());
toEdit.getStartTime().editTime(value);
}
//if there is no start time saved and there is an end date
//use the end date as the start date
if (toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED)
&& !toEdit.getEndDate().value.equals(Messages.MESSAGE_NO_END_DATE_SPECIFIED) ) {
toEdit.constructStartDateTime(toEdit.getEndDate(), toEdit.getStartTime());
//if there is no start and end date
//use the current date as start date
} else if (toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED)) {
toEdit.constructStartDateTime(new TaskDate(new DateTimeParser(new Date().toString()).getDate()), toEdit.getStartTime());
//if there is a start date and an end date
} else {
toEdit.constructStartDateTime(toEdit.getStartDate(), toEdit.getStartTime());
}
toEdit.checkTimeOverdue();
break;
case "end date":
//if it is a deadline task, construct the start using the end date and times
if (toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED) && toEdit.getStartTime().value.equals(Messages.MESSAGE_NO_START_TIME_SET)) {
toEdit.getEndDate().editDate(value);
toEdit.constructStartDateTime(toEdit.getEndDate(), toEdit.getEndTime());
} else {
Task.checkTimeClash(toEdit.getStartDateTime(), Task.formatMissingDateTime(new TaskDate(value),toEdit.getEndTime()));
toEdit.getEndDate().editDate(value);
}
toEdit.constructEndDateTime(toEdit.getEndDate(), toEdit.getEndTime());
toEdit.checkTimeOverdue();
break;
case "end time":
//if it is a deadline task, construct the start using the end date and times
if (toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED) && toEdit.getStartTime().value.equals(Messages.MESSAGE_NO_START_TIME_SET)) {
toEdit.getEndTime().editTime(value);
toEdit.constructStartDateTime(toEdit.getEndDate(), toEdit.getEndTime());
} else if (!toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED)
&& toEdit.getEndDate().value.equals(Messages.MESSAGE_NO_END_DATE_SPECIFIED)){
Task.checkTimeClash(toEdit.getStartDateTime(), Task.formatMissingDateTime(toEdit.getStartDate(), new TaskTime(value)));
toEdit.getEndTime().editTime(value);
} else {
Task.checkTimeClash(toEdit.getStartDateTime(), Task.formatMissingDateTime(toEdit.getEndDate(), new TaskTime(value)));
toEdit.getEndTime().editTime(value);
}
//if there is no end date but has a start date
//use the start date as the end date
if (toEdit.getEndDate().value.equals(Messages.MESSAGE_NO_END_DATE_SPECIFIED)
&& !toEdit.getStartDate().value.equals(Messages.MESSAGE_NO_START_DATE_SPECIFIED) ) {
toEdit.constructEndDateTime(toEdit.getStartDate(), toEdit.getEndTime());
//if there is no start and end dates
//use current date as end date
} else if (toEdit.getEndDate().value.equals(Messages.MESSAGE_NO_END_DATE_SPECIFIED)) {
toEdit.constructEndDateTime(new TaskDate(new DateTimeParser(new Date().toString()).getDate()), toEdit.getEndTime());
}
toEdit.constructEndDateTime(toEdit.getEndDate(), toEdit.getEndTime());
toEdit.checkTimeOverdue();
break;
case "priority":
toEdit.getPriority().editPriority(value);
break;
}
}
//@@author
public ObservableList<Task> getInternalList() {
return internalList;
}
@Override
public Iterator<Task> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueTaskList // instanceof handles nulls
&& this.internalList.equals(
((UniqueTaskList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/SqlPoolTable.java | 944 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.synapse.v2019_06_01_preview;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.implementation.SqlPoolTableInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.synapse.v2019_06_01_preview.implementation.SynapseManager;
/**
* Type representing SqlPoolTable.
*/
public interface SqlPoolTable extends HasInner<SqlPoolTableInner>, HasManager<SynapseManager> {
/**
* @return the id value.
*/
String id();
/**
* @return the name value.
*/
String name();
/**
* @return the type value.
*/
String type();
}
| mit |
stocky37/dropwizard-util | db/src/main/java/com/github/stocky37/util/db/OgmResourceDAO.java | 860 | package com.github.stocky37.util.db;
import org.hibernate.ogm.OgmSession;
import org.hibernate.ogm.OgmSessionFactory;
import java.io.Serializable;
public abstract class OgmResourceDAO<E, I extends Serializable> extends AbstractResourceDAO<E, I> {
public static final String ID_PARAM = "id";
public OgmResourceDAO(OgmSessionFactory sessionFactory) {
super(sessionFactory);
}
@Override
protected OgmSession currentSession() {
return (OgmSession)super.currentSession();
}
// Note: this is only required for the apparent bug in ogm where get() with polymorphic types
// will only return the parameters required for the base type and not the implementing types
@Override
protected E get(Serializable id) {
return uniqueResult(namedQuery(nameOfFindQuery()).setParameter(ID_PARAM, id));
}
protected abstract String nameOfFindQuery();
}
| mit |
testinfected/molecule | src/test/java/com/vtence/molecule/middlewares/URLMapTest.java | 3664 | package com.vtence.molecule.middlewares;
import com.vtence.molecule.Application;
import com.vtence.molecule.Request;
import com.vtence.molecule.Response;
import org.junit.Test;
import static com.vtence.molecule.http.HttpStatus.NOT_FOUND;
import static com.vtence.molecule.http.HttpStatus.OK;
import static com.vtence.molecule.testing.ResponseAssert.assertThat;
public class URLMapTest {
URLMap map = new URLMap();
@Test
public void fallsBackToApplicationForUnmappedPaths() throws Exception {
Response response = map.then(new NotFound())
.handle(Request.get("/unmapped"));
assertThat(response).hasStatus(NOT_FOUND)
.hasBodyText("Not found: /unmapped");
}
@Test
public void dispatchesBasedOnRequestPath() throws Exception {
map.mount("/foo", describeMount())
.mount("/baz", describeMount());
Response response = map.then(ok())
.handle(Request.get("/baz/quux"));
assertThat(response).hasStatus(OK)
.hasBodyText("/baz at /quux (/baz/quux)");
}
@Test
public void matchesMountPointsAsWords() throws Exception {
map.mount("/foo", request -> Response.ok().done("mounted!?!"));
Response response = map.then(new NotFound())
.handle(Request.get("/foobar"));
assertThat(response).hasStatus(NOT_FOUND);
}
@Test
public void dispatchesToServerRootCorrectly() throws Exception {
map.mount("/", describeMount());
Response response = map.then(ok())
.handle(Request.get("/"));
assertThat(response).hasStatus(OK)
.hasBodyText("/ at / (/)");
response = map.then(ok())
.handle(Request.get("/foo"));
assertThat(response).hasStatus(OK)
.hasBodyText("/ at /foo (/foo)");
}
@Test
public void dispatchesToImplicitMountRootCorrectly() throws Exception {
map.mount("/foo", describeMount());
Response response = map.then(ok())
.handle(Request.get("/foo"));
assertThat(response).hasStatus(OK)
.hasBodyText("/foo at / (/foo)");
}
@Test
public void dispatchesToExplicitMountRootCorrectly() throws Exception {
map.mount("/foo", describeMount());
Response response = map.then(ok())
.handle(Request.get("/foo/"));
assertThat(response).hasStatus(OK)
.hasBodyText("/foo at / (/foo)");
}
@Test
public void dispatchesToMostSpecificPath() throws Exception {
map.mount("/foo", describeMount())
.mount("/foo/bar", describeMount());
Response response = map.then(ok())
.handle(Request.get("/foo/bar/quux"));
assertThat(response).hasStatus(OK)
.hasBodyText("/foo/bar at /quux (/foo/bar/quux)");
}
private Application ok() {
return request -> Response.ok().done();
}
public Application describeMount() {
return request -> {
URLMap.MountPoint mountPoint = request.attribute(URLMap.MountPoint.class);
return Response.ok()
.done(String.format("%s at %s (%s)",
mountPoint.app(),
request.path(),
mountPoint.uri(request.path())));
};
}
}
| mit |
daemontus/VuforiaTransparentVideo | app/src/main/java/com/vuforia/samples/VideoPlayback/ui/SampleAppMenu/SampleAppMenuAnimator.java | 2012 | /*===============================================================================
Copyright (c) 2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
===============================================================================*/
package com.vuforia.samples.VideoPlayback.ui.SampleAppMenu;
import android.animation.Animator;
import android.animation.ValueAnimator;
public class SampleAppMenuAnimator extends ValueAnimator implements
ValueAnimator.AnimatorUpdateListener, ValueAnimator.AnimatorListener
{
private static long MENU_ANIMATION_DURATION = 300;
private SampleAppMenu mSampleAppMenu;
private float mMaxX;
private float mEndX;
public SampleAppMenuAnimator(SampleAppMenu menu)
{
mSampleAppMenu = menu;
setDuration(MENU_ANIMATION_DURATION);
addUpdateListener(this);
addListener(this);
}
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
Float f = (Float) animation.getAnimatedValue();
mSampleAppMenu.setAnimationX(f.floatValue());
}
@Override
public void onAnimationCancel(Animator animation)
{
}
@Override
public void onAnimationEnd(Animator animation)
{
mSampleAppMenu.setDockMenu(mEndX == mMaxX);
if (mEndX == 0)
mSampleAppMenu.hide();
}
@Override
public void onAnimationRepeat(Animator animation)
{
}
@Override
public void onAnimationStart(Animator animation)
{
}
public void setStartEndX(float start, float end)
{
mEndX = end;
setFloatValues(start, end);
setDuration((int) (MENU_ANIMATION_DURATION * (Math.abs(end - start) / mMaxX)));
}
public void setMaxX(float maxX)
{
mMaxX = maxX;
}
}
| mit |
skoechle/sobek | source/sobek-workflow-engine/pgraph-ejb/src/test/java/com/sobek/pgraph/test/pgraphdao/GetPgraphTest.java | 1357 | package com.sobek.pgraph.test.pgraphdao;
public class GetPgraphTest{
// @Test
// public void validParam() throws Exception{
// // Setup
// EntityManager entityManager = Mockito.mock(EntityManager.class);
//
// long pgraphId = 5;
// PgraphEntity pgraphEntity = new PgraphEntity();
//
// Mockito.when(entityManager.find(PgraphEntity.class, pgraphId)).thenReturn(pgraphEntity);
//
// // Call the dao
// PgraphDaoLocal dao = createPgraphDao(entityManager);
// PgraphEntity result = dao.getPgraph(pgraphId);
//
// // Check result
// Assert.assertEquals(pgraphEntity, result);
// }
//
// @Test
// public void noGraphFound() throws Exception{
// // Setup
// EntityManager entityManager = Mockito.mock(EntityManager.class);
//
// long pgraphId = 5;
//
// Mockito.when(entityManager.find(PgraphEntity.class, pgraphId)).thenReturn(null);
//
// // Call the dao
// PgraphDaoLocal dao = createPgraphDao(entityManager);
// PgraphEntity result = dao.getPgraph(pgraphId);
//
// // Result should be null
// Assert.assertNull(result);
// }
//
// private PgraphDaoLocal createPgraphDao(EntityManager em) throws Exception{
// PgraphDaoLocal dao = new PgraphDaoBean();
//
// Field emField = PgraphDaoBean.class.getDeclaredField("entityManager");
// emField.setAccessible(true);
// emField.set(dao, em);
//
// return dao;
// }
}
| mit |
michael-groble/polybuf-java | core/src/main/java/polybuf/core/StringParser.java | 2896 | /*
* Copyright (c) 2012 Michael Groble
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package polybuf.core;
import com.google.protobuf.ByteString;
/**
* Protobuf allows two types of compatiblity for strings:
* <ul>
* <li>strings are compatible with bytes "as long as bytes are utf-8"</li>
* <li>messages are compatible with bytes "if the bytes contain the encoded version of the message"</li>
* </ul>
*
* Taken together, these present a challenge. The default behavior is to store binary types as Base64 encoded strings
* which allows them to be easily serialized in text formats like XML and JSON. But this means that "plain" strings can
* look the same as encoded bytes. Distinguishing between compatible bytes and strings is potentially complex. This
* interface allows different parser implementations to trade off complexity vs. accuracy in distinguishing betwee the
* two cases.
*/
public interface StringParser {
/**
* Strictly parse bytes from the string.
*/
ByteString asStrictBytes(String string);
/**
* Parse the incoming string with a target field type of String (a protobuf string).
*
* @throws ParseExcpetion if the incoming string does not look like it is a valid string
*/
String asCompatibleString(String string);
/**
* Parse the incoming string with a target field type of ByteString (a protobuf binary).
*
* @throws ParseExcpetion if the incoming string does not look like it is a valid byte string
*/
ByteString asCompatibleBytes(String string);
/**
* Parse the incoming string with a target field type of ByteString (a protobuf Message). This byte string will then
* be merged into a builder for the corresponding message type.
*
* @throws ParseExcpetion if the incoming string cannot be used to generate the message
*/
ByteString asCompatibleMessageBytes(String string);
} | mit |
nurrochim/Project-E-Commerce-Pizza | eCommerPizza Versi 2/app/src/main/java/com/ecommerce/ecommerpizzas/models/menu/MenuModel.java | 127 | package com.ecommerce.ecommerpizzas.models.menu;
import okhttp3.Request;
public interface MenuModel {
Request build();
}
| mit |
AddstarMC/Minigames | Regions/src/main/java/au/com/mineauz/minigamesregions/NodeToolMode.java | 6314 | package au.com.mineauz.minigamesregions;
import au.com.mineauz.minigames.MinigameMessageType;
import au.com.mineauz.minigames.objects.MinigamePlayer;
import au.com.mineauz.minigames.MinigameUtils;
import au.com.mineauz.minigames.menu.*;
import au.com.mineauz.minigames.minigame.Minigame;
import au.com.mineauz.minigames.minigame.Team;
import au.com.mineauz.minigames.tool.MinigameTool;
import au.com.mineauz.minigames.tool.ToolMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import java.util.ArrayList;
import java.util.List;
public class NodeToolMode implements ToolMode {
@Override
public String getName() {
return "NODE";
}
@Override
public String getDisplayName() {
return "Node Creation";
}
@Override
public String getDescription() {
return "Creates a node where;you are standing;on right click";
}
@Override
public Material getIcon() {
return Material.STONE_BUTTON;
}
@Override
public void onSetMode(final MinigamePlayer player, MinigameTool tool) {
tool.addSetting("Node", "None");
final Menu m = new Menu(2, "Node Selection", player);
if(player.isInMenu()){
m.addItem(new MenuItemPage("Back",MenuUtility.getBackMaterial(), player.getMenu()), m.getSize() - 9);
}
final MinigameTool ftool = tool;
m.addItem(new MenuItemString("Node Name", Material.PAPER, new Callback<String>() {
@Override
public void setValue(String value) {
ftool.changeSetting("Node", value);
}
@Override
public String getValue() {
return ftool.getSetting("Node");
}
}));
if (tool.getMinigame() != null) {
// Node selection menu
RegionModule module = RegionModule.getMinigameModule(tool.getMinigame());
Menu nodeMenu = new Menu(6, "Nodes", player);
List<MenuItem> items = new ArrayList<>();
for(final Node node : module.getNodes()){
MenuItemCustom item = new MenuItemCustom(node.getName(), Material.STONE_BUTTON);
// Set the node and go back to the main menu
item.setClick(object -> {
ftool.changeSetting("Node", node.getName());
m.displayMenu(player);
return object;
});
items.add(item);
}
nodeMenu.addItems(items);
nodeMenu.addItem(new MenuItemPage("Back",MenuUtility.getBackMaterial(), m), nodeMenu.getSize() - 9);
m.addItem(new MenuItemPage("Edit Node", Material.STONE_BUTTON, nodeMenu));
}
m.displayMenu(player);
}
@Override
public void onUnsetMode(MinigamePlayer player, MinigameTool tool) {
tool.removeSetting("Node");
}
@Override
public void onLeftClick(MinigamePlayer player, Minigame minigame, Team team, PlayerInteractEvent event) {
if (event.getClickedBlock() != null) {
RegionModule mod = RegionModule.getMinigameModule(minigame);
String name = MinigameUtils.getMinigameTool(player).getSetting("Node");
Location loc = event.getClickedBlock().getLocation().add(0.5, 0.5, 0.5);
Node node = mod.getNode(name);
if (node == null) {
node = new Node(name, loc);
mod.addNode(name, node);
player.sendInfoMessage("Added new node to " + minigame + " called " + name);
} else {
node.setLocation(loc);
player.sendInfoMessage("Edited node " + name + " in " + minigame);
Main.getPlugin().getDisplayManager().update(node);
}
}
}
@Override
public void onRightClick(MinigamePlayer player, Minigame minigame, Team team, PlayerInteractEvent event) {
RegionModule mod = RegionModule.getMinigameModule(minigame);
String name = MinigameUtils.getMinigameTool(player).getSetting("Node");
Node node = mod.getNode(name);
if (node == null) {
node = new Node(name, player.getLocation());
mod.addNode(name, node);
player.sendInfoMessage("Added new node to " + minigame + " called " + name);
} else {
node.setLocation(player.getLocation());
player.sendInfoMessage("Edited node " + name + " in " + minigame);
Main.getPlugin().getDisplayManager().update(node);
}
}
@Override
public void onEntityLeftClick(MinigamePlayer player, Minigame minigame, Team team, EntityDamageByEntityEvent event) {
}
@Override
public void onEntityRightClick(MinigamePlayer player, Minigame minigame, Team team, PlayerInteractEntityEvent event) {
}
@Override
public void select(MinigamePlayer player, Minigame minigame, Team team) {
RegionModule mod = RegionModule.getMinigameModule(minigame);
String name = MinigameUtils.getMinigameTool(player).getSetting("Node");
if(mod.hasNode(name)){
Main.getPlugin().getDisplayManager().show(mod.getNode(name), player);
player.sendInfoMessage("Selected node '" + name + "' visually.");
}
else{
player.sendMessage("No node exists by the name '" + name + "'", MinigameMessageType.ERROR);
}
}
@Override
public void deselect(MinigamePlayer player, Minigame minigame, Team team) {
RegionModule mod = RegionModule.getMinigameModule(minigame);
String name = MinigameUtils.getMinigameTool(player).getSetting("Node");
if(mod.hasNode(name)){
Main.getPlugin().getDisplayManager().hide(mod.getNode(name), player);
player.sendInfoMessage("Deselected node '" + name + "'");
}
else{
player.sendMessage("No node exists by the name '" + name + "'", MinigameMessageType.ERROR);
}
}
}
| mit |
Wmedya/alu-client-java | src/main/java/com/wmedya/payu/client/PayuClient.java | 9865 | package com.wmedya.payu.client;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.wmedya.payu.client.model.Billing;
import com.wmedya.payu.client.model.Card;
import com.wmedya.payu.client.model.Delivery;
import com.wmedya.payu.client.model.MerchantConfig;
import com.wmedya.payu.client.model.MerchantPlatform;
import com.wmedya.payu.client.model.Order;
import com.wmedya.payu.client.model.Product;
import com.wmedya.payu.client.model.TokenOrder;
import com.wmedya.payu.client.model.User;
import com.wmedya.payu.client.util.HashUtils;
import com.wmedya.payu.client.util.StringUtils;
public class PayuClient implements Serializable {
private static final long serialVersionUID = 1L;
private Logger logger = Logger.getLogger(PayuClient.class);
private MerchantConfig config;
private Map<MerchantPlatform, String> platformUrls = new HashMap<MerchantPlatform, String>();
private Map<MerchantPlatform, String> tokenUrls = new HashMap<MerchantPlatform, String>();
private HttpClient client = new DefaultHttpClient();
private ObjectMapper objectMapper = new ObjectMapper();
private XmlMapper xmlMapper = new XmlMapper();
private Order order;
private Card card;
private User user;
private TokenOrder tokenOrder;
public PayuClient(MerchantConfig config) {
this.config = config;
platformUrls.put(MerchantPlatform.TR, "https://secure.payu.com.tr/order/alu/v3");
platformUrls.put(MerchantPlatform.HU, "https://secure.payu.hu/order/alu/v3");
platformUrls.put(MerchantPlatform.RO, "https://secure.payu.ro/order/alu/v3");
platformUrls.put(MerchantPlatform.RU, "https://secure.payu.ru/order/alu/v3");
platformUrls.put(MerchantPlatform.UA, "https://secure.payu.ua/order/alu/v3");
tokenUrls.put(MerchantPlatform.TR, "https://secure.payu.com.tr/order/tokens/");
tokenUrls.put(MerchantPlatform.HU, "https://secure.payu.com.hu/order/tokens/");
tokenUrls.put(MerchantPlatform.RO, "https://secure.payu.com.ro/order/tokens/");
tokenUrls.put(MerchantPlatform.RU, "https://secure.payu.com.ru/order/tokens/");
tokenUrls.put(MerchantPlatform.UA, "https://secure.payu.com.ua/order/tokens/");
}
public PayuResponse pay() {
if (order == null) {
throw new RuntimeException("order must not be null");
}
if (card == null) {
throw new RuntimeException("card must not be null");
}
if (user == null) {
throw new RuntimeException("user must not be null");
}
return pay(order, card, user);
}
public PayuResponse pay(Order order, Card card, User user) {
this.order = order;
this.card = card;
this.user = user;
String url = platformUrls.get(config.getPlatform());
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> params = getParams();
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
postParams.add(new BasicNameValuePair(key, params.get(key)));
}
PayuResponse payuResponse = null;
try {
logger.debug("executing http post request...");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post);
logger.debug("Response Code : " + response.getStatusLine().getStatusCode());
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.debug("Response as string:");
logger.debug(result);
payuResponse = xmlMapper.readValue(result, PayuResponse.class);
payuResponse.setRaw(result);
} catch (Exception e) {
logger.error(e);
}
return payuResponse;
}
public TokenPaymentResponse pay(TokenOrder tokenOrder) {
this.tokenOrder = tokenOrder;
String url = tokenUrls.get(config.getPlatform());
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> params = getTokenPaymentParams();
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
postParams.add(new BasicNameValuePair(key, params.get(key)));
}
TokenPaymentResponse payuResponse = null;
try {
logger.debug("executing http post request...");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post);
logger.debug("Response Code : " + response.getStatusLine().getStatusCode());
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.debug("Response as string:");
logger.debug(result);
payuResponse = objectMapper.readValue(result, TokenPaymentResponse.class);
payuResponse.setRaw(result);
} catch (Exception e) {
logger.error(e);
}
return payuResponse;
}
public Map<String, String> getTokenPaymentParams() {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("MERCHANT", config.getCode());
if (tokenOrder != null) {
LinkedHashMap map = objectMapper.convertValue(tokenOrder, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
params.put((String) key, convertToString(value));
}
}
}
Map<String, String> copyParams = new LinkedHashMap<>();
copyParams.putAll(params);
copyParams.put("SIGN", HashUtils.calculateHash(config.getSecret(), params));
logger.debug("total parameters...");
logger.debug(copyParams);
return copyParams;
}
public Map<String, String> getParams() {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("MERCHANT", config.getCode());
LinkedHashMap map = null;
if (order != null) {
map = objectMapper.convertValue(order, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
params.put((String) key, convertToString(value));
}
}
for (Product product : order.getProducts()) {
map = objectMapper.convertValue(product, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
String valueString = convertToString(value);
String keyString = addIndexToKey((String) key, order.getProducts().indexOf(product));
params.put(keyString, valueString);
}
}
}
Billing billing = order.getBilling();
if (billing != null) {
map = objectMapper.convertValue(billing, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
String valueString = convertToString(value);
params.put((String) key, valueString);
}
}
}
Delivery delivery = order.getDelivery();
if (delivery != null) {
map = objectMapper.convertValue(delivery, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
String valueString = convertToString(value);
params.put((String) key, valueString);
}
}
}
}
if (card != null) {
map = objectMapper.convertValue(card, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
String valueString = convertToString(value);
params.put((String) key, valueString);
}
}
}
if (user != null) {
map = objectMapper.convertValue(user, LinkedHashMap.class);
for (Object key : map.keySet()) {
Object value = map.get(key);
if (value != null) {
String valueString = convertToString(value);
params.put((String) key, valueString);
}
}
}
Map<String, String> copyParams = new LinkedHashMap<>();
copyParams.putAll(params);
copyParams.put("ORDER_HASH", HashUtils.calculateHash(config.getSecret(), params));
logger.debug("total parameters...");
logger.debug(copyParams);
return copyParams;
}
/**
* Checks the response coming from Payu is valid
*
* @param payuResponse
* @return
*/
public boolean checkResponseHash(PayuResponse payuResponse) {
LinkedHashMap checkMap = objectMapper.convertValue(payuResponse, LinkedHashMap.class);
String hash = (String) checkMap.get("HASH");
if (hash != null && hash.trim().length() > 0) {
checkMap.remove("URL_3DS");
checkMap.remove("HASH");
logger.debug("Response Hash Check:");
logger.debug(checkMap);
String calculatedHash = HashUtils.calculateHash(config.getSecret(), checkMap);
return calculatedHash.contentEquals(hash);
}
return false;
}
private String addIndexToKey(String key, int index) {
String indexedKey = key;
if (key.endsWith("[]")) {
indexedKey = key.replace("[]", "[" + index + "]");
}
return indexedKey;
}
private String convertToString(Object value) {
Object cast;
try {
cast = (Number) value;
if (cast instanceof Double) {
return formatDouble((double) cast);
}
} catch (Exception e) {
cast = (String) value;
}
return StringUtils.sanitizeString(cast.toString());
}
private String formatDouble(double d) {
if (d == (long) d)
return String.format("%d", (long) d);
else
return String.format("%s", d);
}
public void setOrder(Order order) {
this.order = order;
}
public void setCard(Card card) {
this.card = card;
}
public void setUser(User user) {
this.user = user;
}
}
| mit |
Localizr/Localizr | app/models/eventmedia/EventList.java | 1552 | package models.eventmedia;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.Gson;
import models.geo.Location;
public class EventList {
private ArrayList<Event> eventlist;
public EventList(){
eventlist = new ArrayList<Event>();
}
public String toString(){
String string = "";
for(Event e: eventlist){
string = string + "EVENTS: " + e.getTitle() + "\n";
}
return string;
}
public String getJSON(){
Gson gson = new Gson();
return gson.toJson(this);
}
public int size(){
return eventlist.size();
}
public void add(Event e){
eventlist.add(e);
}
public ArrayList<Event> get() {
return eventlist;
}
public ArrayList<String> getAllAddresses(){
ArrayList<String> addresses = new ArrayList<String>();
for(Event e: eventlist){
addresses.add(e.getAddress());
}
return addresses;
}
public HashMap<String,String> getAddressHashmap(){
HashMap<String,String> events = new HashMap<String,String>();
for(Event e: eventlist){
events.put(e.getTitle(),e.getAddress());
}
return events;
}
public ArrayList<Location> getAddressArrayList(){
ArrayList<Location> events = new ArrayList<Location>();
for(Event e: eventlist){
Location l = new Location();
l.setName(e.getTitle());
events.add(l);
}
return events;
}
}
| mit |
elBukkit/MagicPlugin | Magic/src/main/java/com/elmakers/mine/bukkit/requirements/TimeRequirement.java | 2227 | package com.elmakers.mine.bukkit.requirements;
import java.util.logging.Logger;
import org.bukkit.configuration.ConfigurationSection;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
class TimeRequirement extends RangedRequirement {
public TimeRequirement(String value, Logger logger) {
try {
if (value.startsWith("<")) {
if (value.startsWith("<=")) {
max = (double)ConfigurationUtils.parseTime(value.substring(2), logger, "time requirement");
inclusive = true;
} else {
max = (double)ConfigurationUtils.parseTime(value.substring(1), logger, "time requirement");
}
} else if (value.startsWith(">")) {
if (value.startsWith(">=")) {
min = (double)ConfigurationUtils.parseTime(value.substring(2), logger, "time requirement");
inclusive = true;
} else {
min = (double)ConfigurationUtils.parseTime(value.substring(1), logger, "time requirement");
}
} else if (value.startsWith("=")) {
this.value = (double)ConfigurationUtils.parseTime(value.substring(1), logger, "time requirement");
} else {
// Default to >= which is what we normally mean
min = (double)ConfigurationUtils.parseTime(value, logger, "time requirement");
this.inclusive = true;
}
} catch (Exception ignore) {
}
}
public TimeRequirement(ConfigurationSection configuration, Logger logger) {
if (configuration.contains("min")) {
min = (double)ConfigurationUtils.parseTime(configuration.getString("min"), logger, "time requirement");
}
if (configuration.contains("max")) {
max = (double)ConfigurationUtils.parseTime(configuration.getString("max"), logger, "time requirement");
}
if (configuration.contains("value")) {
value = (double)ConfigurationUtils.parseTime(configuration.getString("value"), logger, "time requirement");
}
inclusive = configuration.getBoolean("inclusive");
}
}
| mit |
digitalheir/java-rechtspraak-library | deprecated/crf/main/java/deprecated/org/crf/utilities/DoubleArrayWrapper.java | 908 | package deprecated.org.crf.utilities;
import java.util.Arrays;
/**
* Wraps double[] with {@link #equals(Object)} and {@link #hashCode()}.
*
* @author Asher Stern
* Date: Nov 13, 2014
*
*/
public class DoubleArrayWrapper
{
private final double[] array;
public DoubleArrayWrapper(double[] array)
{
super();
this.array = array;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(array);
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DoubleArrayWrapper other = (DoubleArrayWrapper) obj;
if (!Arrays.equals(array, other.array))
return false;
return true;
}
@Override
public String toString()
{
return StringUtilities.arrayOfDoubleToString(array);
}
}
| mit |
lathspell/java_test | java_test_spring_rest/src/main/java/de/lathspell/test/rest/GreetingController.java | 2596 | package de.lathspell.test.rest;
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Spring REST Controller.
*
* The @RestController annotation includes @Controller which is a specialization of @Component and @ResponseBody which tells Spring that the return
* value of every method should be converted into an HTTP Response.
*
*/
@RestController
public class GreetingController {
/**
* Default Mapper.
*
* Without parameters this is the default mapper for all HTTP verbs
* (GET, PUT, POST, etc.) and all URLs that have no more-specific mapping.
*/
@RequestMapping
public String hello1(String name) {
return "Hello1 " + name;
}
/**
* Mapping with fine tuning.
*/
@RequestMapping(path = "/hello2", method = GET, produces = TEXT_PLAIN_VALUE)
public String hello2(String name) {
return "Hello2 " + name;
}
/**
* Mapping using the new annotation name.
*/
@GetMapping(path = "/hello3", produces = TEXT_PLAIN_VALUE)
public String hello3(String name) {
return "Hello3 " + name;
}
/**
* Only matches if this header is set in the request.
*
* (apart from that it works for every URL as no "path" is specified)
*
* <pre>
* $ curl -H 'X-Override: true' 'http://localhost:8090/java_test_spring_rest/whatever?name=Tim'
* HelloX Tim
* </pre>
*/
@RequestMapping(method = GET, headers = "X-Override=true")
public String helloX(@RequestParam("name") String name) {
return "HelloX " + name;
}
/**
* HTTP POST example.
*
* - the @RequestBody is mandatory!
*
* <pre>
* $ curl -d '{"name":"Tim"}' -H 'Content-Type: application/json' -X POST 'http://localhost:8090/java_test_spring_rest/uppercase?name=foo'
* {"NAME":"TIM"}
* </pre>
*
*/
@PostMapping(path = "uppercase", consumes = TEXT_PLAIN_VALUE)
public String uppercase(@RequestBody String input) {
Assert.notNull(input, "Body darf nicht NULL sein!");
return input.toUpperCase();
}
}
| cc0-1.0 |
Aatik/UltimateCompass | app/src/main/java/ara/kuet/musta/MaghribFragment.java | 7718 | package ara.kuet.musta;
import android.app.TimePickerDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.kuet.musta.R;
public class MaghribFragment extends Fragment implements TimePickerDialog.OnTimeSetListener {
SharedPreferences spmaster;
SharedPreferences.Editor editor;
Button update;
TextView clock;
Spinner mode,engage,release;
String tclock;
int hour,minute;
int define_hour = 18;
int define_minute = 2;
int define_engage = 5;
int define_release = 15+5;
public MaghribFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.maghrib_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
spmaster = getActivity().getSharedPreferences("mysp",0);
editor = spmaster.edit();
update = (Button) view.findViewById(R.id.but_maghrib_update);
clock = (TextView) view.findViewById(R.id.tv_maghrib_clock);
clock.setText(spmaster.getString("maghrib_clock",clockMaker(define_hour,define_minute)));
mode = (Spinner) view.findViewById(R.id.spinner_maghrib_pmode);
engage = (Spinner) view.findViewById(R.id.spinner_maghrib_eggage);
release = (Spinner) view.findViewById(R.id.spinner_maghrib_release);
LoadSpinner();
Button_update();
}
private void Button_update() {
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
hour = spmaster.getInt("maghrib_hour",define_hour);
minute = spmaster.getInt("maghrib_minute",define_minute);
bundle.putInt("hour", hour);
bundle.putInt("minute", minute);
TimePickerDialogFragment dialog = new TimePickerDialogFragment(MaghribFragment.this);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "Dialog");
}
});
}
private void LoadSpinner() {
ArrayAdapter adapter1 = ArrayAdapter.createFromResource(getActivity(),R.array.phone_mode,android.R.layout.simple_list_item_checked);
adapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
mode.setAdapter(adapter1);
mode.setSelection(spmaster.getInt("maghrib_phone_mode",0));
mode.setOnItemSelectedListener(new modeMaghribSpinnerItemListener());
ArrayAdapter adapter2 = ArrayAdapter.createFromResource(getActivity(),R.array.maghrib_before_time,android.R.layout.simple_list_item_checked);
adapter2.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
engage.setAdapter(adapter2);
engage.setSelection(spmaster.getInt("maghrib_engage_poss",0));
engage.setOnItemSelectedListener(new engageMaghribSpinnerItemListener());
ArrayAdapter adapter3 = ArrayAdapter.createFromResource(getActivity(),R.array.maghrib_release_time,android.R.layout.simple_list_item_checked);
adapter3.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
release.setAdapter(adapter3);
release.setSelection(spmaster.getInt("maghrib_release_poss",0));
release.setOnItemSelectedListener(new releaseMaghribSpinnerItemListener());
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
editor.putInt("maghrib_hour",hourOfDay);
editor.putInt("maghrib_minute",minute);
String nclock = clockMaker(hourOfDay,minute);
editor.putString("maghrib_clock",nclock);
clock.setText(nclock);
editor.apply();
engage_release_actualTime();
}
public String clockMaker (int hourOfDay,int minute)
{
if(hourOfDay>=12)
{
tclock = pad(hourOfDay-12) + ":" + pad(minute)+" PM";
}
else {
tclock = pad(hourOfDay) + ":" + pad(minute)+" AM";
}
return tclock;
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public class modeMaghribSpinnerItemListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
editor.putInt("maghrib_phone_mode",position);
editor.apply();
}
@Override
public void onNothingSelected(AdapterView parent) {
}
}
public class engageMaghribSpinnerItemListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
editor.putInt("maghrib_engage_poss",position);
editor.putInt("maghrib_engage_minute",position+5);
editor.apply();
engage_release_actualTime();
}
@Override
public void onNothingSelected(AdapterView parent) {
}
}
public class releaseMaghribSpinnerItemListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView parent, View view, int position, long id) {
//int a = position+20;
editor.putInt("maghrib_release_poss",position);
editor.putInt("maghrib_release_minute",position+20);
editor.apply();
engage_release_actualTime();
}
@Override
public void onNothingSelected(AdapterView parent) {
}
}
private void engage_release_actualTime() {
int engage_actual_minute,release_actual_minute;
int hour = spmaster.getInt("maghrib_hour",define_hour);
int minute = spmaster.getInt("maghrib_minute",define_minute);
int engage_minute = spmaster.getInt("maghrib_engage_minute",define_engage);
int release_minute = spmaster.getInt("maghrib_release_minute",define_release);
engage_actual_minute = minute - engage_minute;
if(engage_actual_minute < 0)
{
hour--;
engage_actual_minute = 60 + engage_actual_minute;
}
editor.putInt("maghrib_engage_actual_hour",hour);
editor.putInt("maghrib_engage_actual_minute",engage_actual_minute);
//Toast.makeText(getActivity(), clockMaker(hour,engage_actual_minute), Toast.LENGTH_LONG).show();
release_actual_minute = minute + release_minute;
if(release_actual_minute >= 60 )
{
release_actual_minute = release_actual_minute - 60;
hour++;
}
editor.putInt("maghrib_release_actual_hour",hour);
editor.putInt("maghrib_release_actual_minute",release_actual_minute);
editor.apply();
//Toast.makeText(getActivity(),clockMaker(spmaster.getInt("maghrib_release_actual_hour",0),spmaster.getInt("maghrib_release_actual_minute",0)),Toast.LENGTH_LONG).show();
}
}
| cc0-1.0 |
teste-sw/distribuicao_de_disciplinas | src/br/edu/ifrn/suap/academico/entidades/Curso.java | 184 | package br.edu.ifrn.suap.academico.entidades;
import java.util.Set;
public class Curso {
public String codigo;
public String titulo;
public Set<Disciplina> disciplinas;
}
| cc0-1.0 |
niuqg/controller | opendaylight/md-sal/model/model-flow-base/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/table/types/rev131026/table/feature/prop/type/table/feature/prop/type/WildcardsBuilder.java | 6865 | package org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type;
import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.wildcards.WildcardSetfield;
import java.util.Map;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import java.util.HashMap;
import java.util.Collections;
public class WildcardsBuilder {
private WildcardSetfield _wildcardSetfield;
private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>> augmentation = new HashMap<>();
public WildcardsBuilder() {
}
public WildcardSetfield getWildcardSetfield() {
return _wildcardSetfield;
}
@SuppressWarnings("unchecked")
public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>> E getAugmentation(Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
public WildcardsBuilder setWildcardSetfield(WildcardSetfield value) {
this._wildcardSetfield = value;
return this;
}
public WildcardsBuilder addAugmentation(Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>> augmentationType, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards> augmentation) {
this.augmentation.put(augmentationType, augmentation);
return this;
}
public Wildcards build() {
return new WildcardsImpl(this);
}
private static final class WildcardsImpl implements Wildcards {
public Class<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards> getImplementedInterface() {
return org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards.class;
}
private final WildcardSetfield _wildcardSetfield;
private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>> augmentation;
private WildcardsImpl(WildcardsBuilder builder) {
this._wildcardSetfield = builder.getWildcardSetfield();
switch (builder.augmentation.size()) {
case 0:
this.augmentation = Collections.emptyMap();
break;
case 1:
final Map.Entry<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>> e = builder.augmentation.entrySet().iterator().next();
this.augmentation = Collections.<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>>singletonMap(e.getKey(), e.getValue());
break;
default :
this.augmentation = new HashMap<>(builder.augmentation);
}
}
@Override
public WildcardSetfield getWildcardSetfield() {
return _wildcardSetfield;
}
@SuppressWarnings("unchecked")
@Override
public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.Wildcards>> E getAugmentation(Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_wildcardSetfield == null) ? 0 : _wildcardSetfield.hashCode());
result = prime * result + ((augmentation == null) ? 0 : augmentation.hashCode());
return result;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WildcardsImpl other = (WildcardsImpl) obj;
if (_wildcardSetfield == null) {
if (other._wildcardSetfield != null) {
return false;
}
} else if(!_wildcardSetfield.equals(other._wildcardSetfield)) {
return false;
}
if (augmentation == null) {
if (other.augmentation != null) {
return false;
}
} else if(!augmentation.equals(other.augmentation)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Wildcards [");
boolean first = true;
if (_wildcardSetfield != null) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append("_wildcardSetfield=");
builder.append(_wildcardSetfield);
}
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append("augmentation=");
builder.append(augmentation.values());
return builder.append(']').toString();
}
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/factories/NamespaceResolverWithPrefixes.java | 750 | package org.eclipse.persistence.internal.sessions.factories;
import org.eclipse.persistence.oxm.NamespaceResolver;
public class NamespaceResolverWithPrefixes extends NamespaceResolver {
protected String primaryPrefix = null;
protected String secondaryPrefix = null;
public void putPrimary(String ns1, String primaryNamespace) {
this.primaryPrefix = ns1;
put(ns1, primaryNamespace);
}
public String getPrimaryPrefix() {
return primaryPrefix;
}
public void putSecondary(String ns1, String secondaryNamespace) {
this.secondaryPrefix = ns1;
put(ns1, secondaryNamespace);
}
public String getSecondaryPrefix() {
return secondaryPrefix;
}
}
| epl-1.0 |
fellipealeixo/dsc-2015-2 | SisTCCs/src/br/edu/ifrn/sistcc/daos/SubmissaoDAOImp.java | 2121 | package br.edu.ifrn.sistcc.daos;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import br.edu.ifrn.sistcc.entidades.EstadoSubmissao;
import br.edu.ifrn.sistcc.entidades.Submissao;
@Stateless
public class SubmissaoDAOImp implements SubmissaoDAO {
@PersistenceContext(unitName="sistcc")
private EntityManager em;
@SuppressWarnings("unchecked")
@Override
public List<Submissao> getTodasSubmissoes() {
Query query = em.createNamedQuery("listarSubmissoes");
return query.getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<Submissao> getSubmisoesAtivas() {
Query query = em.createNamedQuery("submissoesAtivas");
query.setParameter("arquivadas", EstadoSubmissao.ARQUIVADO);
return query.getResultList();
}
@Override
public Submissao getSubmissao(int idSubmissao) {
return em.find(Submissao.class, idSubmissao);
}
@SuppressWarnings("unchecked")
@Override
public List<Submissao> submissoesPorEvento(int idEvento) {
Query query = em.createNamedQuery("subimissoesPorEvento");
query.setParameter("id", idEvento);
return query.getResultList();
}
@Override
public List<Submissao> submissoesPorAvaliador(int idAvaliador) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Submissao> submissoesAtivasPorAvaliador(int idAvaliador) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Submissao> submissoesPorUsuario(int idUsuario) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ExtratoSubmissao> quantidadeSubmissoesPorEvento() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean insereSubmissao(Submissao submissao) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean atualizaSubmissao(Submissao submissao) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean removeSubmissao(int idSubmissao) {
// TODO Auto-generated method stub
return false;
}
}
| epl-1.0 |
forge/javaee-descriptors | api/src/main/java/org/jboss/shrinkwrap/descriptor/api/ejbjar32/package-info.java | 141 | /**
* Provides the interfaces and enumeration types as defined in the schema
*/
package org.jboss.shrinkwrap.descriptor.api.ejbjar32;
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/advanced/concurrency/TransitionRunner1.java | 1921 | package org.eclipse.persistence.testing.tests.jpa.advanced.concurrency;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;
import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;
import org.eclipse.persistence.testing.models.jpa.advanced.ConcurrencyB;
import org.eclipse.persistence.testing.models.jpa.advanced.ConcurrencyC;
public class TransitionRunner1 implements Runnable {
protected ConcurrencyB concB;
protected ConcurrencyC concC;
protected EntityManagerFactory emf;
protected Object toWaitOn;
public TransitionRunner1(Object toWaitOn, ConcurrencyB concB, ConcurrencyC concC, EntityManagerFactory emf) {
this.concB = concB;
this.concC = concC;
this.emf = emf;
this.toWaitOn = toWaitOn;
}
public void run() {
EntityManager em = emf.createEntityManager();
ConcurrencyB b = em.find(ConcurrencyB.class, concB.getId());
ConcurrencyC c = em.find(ConcurrencyC.class, concC.getId());
c.setName(System.currentTimeMillis() + "_C");
b.setName(System.currentTimeMillis() + "_B");
UnitOfWorkImpl uow = ((EntityManagerImpl) em).getActivePersistenceContext(null);
try {
synchronized (toWaitOn) {
toWaitOn.wait(120000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uow.issueSQLbeforeCompletion(true);
try {
synchronized (toWaitOn) {
toWaitOn.notifyAll();
toWaitOn.wait(6000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uow.release();
}
}
| epl-1.0 |
rondiplomatico/texlipse | source/net/sourceforge/texlipse/builder/ExternalProgram.java | 7866 | /*
* $Id$
*
* Copyright (c) 2004-2005 by the TeXlapse Team.
* 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
*/
package net.sourceforge.texlipse.builder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Properties;
import net.sourceforge.texlipse.PathUtils;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.properties.TexlipseProperties;
/**
* Helper methods to run an external program.
*
* @author Kimmo Karlsson
* @author Boris von Loesch
*/
public class ExternalProgram {
// the command to run
private String[] command;
// the directory to the command in
private File dir;
// the process that executes the command
private Process process;
// output messages to this console
private String consoleOutput;
/**
* Creates a new command runner.
*/
public ExternalProgram() {
this.command = null;
this.dir = null;
this.process = null;
this.consoleOutput = null;
}
/**
* Resets the command runner.
*
* @param command command to run
* @param dir directory to run the command in
*/
public void setup(String[] command, File dir, String console) {
this.command = command;
this.dir = dir;
this.process = null;
this.consoleOutput = console;
}
/**
* Force termination of the running process.
*/
public void stop() {
if (process != null) {
process.destroy();
// can't null the process here, because run()-method of this class is still executing
//process = null;
}
}
/**
* Reads the contents of a stream.
*
* @param is the stream
* @return the contents of the stream as a String
*/
protected String readOutput(InputStream is) {
StringWriter store = new StringWriter();
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
store.write(line + '\n');
if (consoleOutput != null) {
BuilderRegistry.printToConsole(consoleOutput + "> " + line);
}
}
} catch (IOException e) {
}
store.flush();
return store.getBuffer().toString();
}
/**
* Runs the external program as a process and waits
* for the process to finish execution.
*
* @param queryMessage text which will trigger the query dialog
* @return the text produced to standard output by the process
* @throws Exception
*/
public String run(String[] queryMessage) throws Exception {
return run(true, queryMessage);
}
/**
* Runs the external program as a process and waits
* for the process to finish execution.
*
* @return the text produced to standard output by the process
* @throws Exception
*/
public String run() throws Exception {
return run(true, null);
}
/**
* Runs the external program as a process and waits
* for the process to finish execution.
*
* @param wait if true, this method will block until
* the process has finished execution
* @return the text produced to standard output by the process
* @throws IOException
*/
protected String run(boolean wait, String[] queryMessage) throws IOException {
String output = null;
String errorOutput = null;
if ((command != null) && (dir != null)) {
StringBuffer commandSB = new StringBuffer();
for (int i = 0; i < command.length; i++) {
commandSB.append(command[i]);
commandSB.append(" ");
}
BuilderRegistry.printToConsole("running: " + commandSB.toString());
Runtime rt = Runtime.getRuntime();
// Add builder program path to environmet variables.
// This is needed at least on Mac OS X, where Eclipse overwrites
// the "path" environment variable, and xelatex needs its directory in the path.
Properties envProp = PathUtils.getEnv();
int index = command[0].lastIndexOf(File.separatorChar);
if (index > 0) {
String commandPath = command[0].substring(0, index);
String key = PathUtils.findPathKey(envProp);
envProp.setProperty(key, envProp.getProperty(key) + File.pathSeparatorChar + commandPath);
}
String[] env = PathUtils.mergeEnvFromPrefs(envProp, TexlipseProperties.BUILD_ENV_SETTINGS);
process = rt.exec(command, env, dir);
} else {
throw new IllegalStateException();
}
final StringBuffer thErrorOutput = new StringBuffer();
final StringBuffer thOutput = new StringBuffer();
// scan the standard output stream
final OutputScanner scanner = new OutputScanner(process.getInputStream(),
process.getOutputStream(), queryMessage, consoleOutput);
// scan also the standard error stream
final OutputScanner errorScanner = new OutputScanner(process.getErrorStream(),
process.getOutputStream(), queryMessage, consoleOutput);
final Thread errorThread = new Thread() {
public void run() {
if (errorScanner.scanOutput()) {
thErrorOutput.append(errorScanner.getText());
}
};
};
final Thread outputThread = new Thread() {
public void run() {
if (scanner.scanOutput()) {
thOutput.append(scanner.getText());
} else {
// Abort by user: Abort build, clear all output
process.destroy();
try {
errorThread.join();
} catch (InterruptedException e) {
// Should not happen
TexlipsePlugin.log("Output scanner interrupted", e);
}
thOutput.setLength(0);
thErrorOutput.setLength(0);
}
};
};
outputThread.start();
errorThread.start();
try {
// Wait until stream read has finished
errorThread.join();
outputThread.join();
} catch (InterruptedException e) {
TexlipsePlugin.log("Output scanner interrupted", e);
// Should not happen
}
output = thOutput.toString();
errorOutput = thErrorOutput.toString();
if (wait) {
// the process status code is not useful here
//int code =
try {
process.waitFor();
} catch (InterruptedException e) {
//Should not happen
TexlipsePlugin.log("Process interrupted", e);
}
}
process = null;
// combine the error output with normal output
// to collect information from for example makeindex
if (errorOutput.length() > 0) {
output += "\n" + errorOutput;
}
return output;
}
}
| epl-1.0 |
TMJesso/JavaSource | Exam2/src/geoMetricShapes/ThreeDimension.java | 1341 | package geoMetricShapes;
/** three dimension - set up for creating the volume of an object
*
* @author Theral Jessop<br>
* Mar 25, 2015<br>
* ThreeDimension.java<br>
*
*/
public abstract class ThreeDimension extends Shape {
double dimension1;
double dimension2;
double dimension3;
/** three dimension constructor
*
* @param dim1
* @param dim2
* @param dim3
* @param color
* @param point
*/
public ThreeDimension(double dim1, double dim2, double dim3, String color, Point point) {
super(color, point);
this.dimension1 = dim1;
this.dimension2 = dim2;
this.dimension3 = dim3;
}
/** abstract method for area
*
* @return
*/
abstract public double getArea();
/** abstract method for volume
*
* @return
*/
abstract public double getVolume();
// get
/** get Dimension 1
*
* @return dimension1
*/
public double getDimension1() {
return this.dimension1;
}
/** get Dimension 2
*
* @return dimension2
*/
public double getDimension2() {
return this.dimension2;
}
// set
/** set Dimension 1
*
* @param dimension1
*/
public void setDimension1(double dimension1) {
this.dimension1 = dimension1;
}
/** set Dimension 2
*
* @param dimension2
*/
public void setDimension2(double dimension2) {
this.dimension2 = dimension2;
}
}
| epl-1.0 |
kgibm/open-liberty | dev/fattest.simplicity/src/componenttest/custom/junit/runner/FATRunner.java | 41386 | /*******************************************************************************
* Copyright (c) 2011, 2021 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 componenttest.custom.junit.runner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.ClassRule;
import org.junit.internal.AssumptionViolatedException;
import org.junit.runner.manipulation.Filter;
import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import com.ibm.websphere.simplicity.Machine;
import com.ibm.websphere.simplicity.RemoteFile;
import com.ibm.websphere.simplicity.config.HttpEndpoint;
import com.ibm.websphere.simplicity.config.IncludeElement;
import com.ibm.websphere.simplicity.config.ServerConfiguration;
import com.ibm.websphere.simplicity.log.Log;
import componenttest.annotation.AllowedFFDC;
import componenttest.annotation.ExpectedFFDC;
import componenttest.annotation.Server;
import componenttest.annotation.processor.TestServletProcessor;
import componenttest.exception.TopologyException;
import componenttest.logging.ffdc.IgnoredFFDCs;
import componenttest.logging.ffdc.IgnoredFFDCs.IgnoredFFDC;
import componenttest.rules.repeater.EE9PackageReplacementHelper;
import componenttest.rules.repeater.JakartaEE9Action;
import componenttest.topology.impl.LibertyServer;
import componenttest.topology.impl.LibertyServerFactory;
import componenttest.topology.impl.LibertyServerWrapper;
import junit.framework.AssertionFailedError;
public class FATRunner extends BlockJUnit4ClassRunner {
private static final Class<?> c = FATRunner.class;
// Used to reduce timeouts to a sensible level when FATs are running locally
public static final boolean FAT_TEST_LOCALRUN = Boolean.getBoolean("fat.test.localrun") && !Boolean.parseBoolean(System.getenv("CI"));
private static final int MAX_FFDC_LINES = 1000;
private static final boolean DISABLE_FFDC_CHECKING = Boolean.getBoolean("disable.ffdc.checking");
private static final boolean ENABLE_TMP_DIR_CHECKING = Boolean.getBoolean("enable.tmpdir.checking");
private static final long TMP_DIR_SIZE_THRESHOLD = 20 * 1024; // 20k
//list of filters to apply
private static final Filter[] testFiltersToApply = new Filter[] {
new TestModeFilter(),
new TestNameFilter(),
new FeatureFilter(),
new SystemPropertyFilter(),
new JavaLevelFilter()
};
private static EE9PackageReplacementHelper ee9Helper;
private static final Set<String> classesUsingFATRunner = new HashSet<String>();
static {
Log.info(c, "<clinit>", "Is this FAT running locally? fat.test.localrun=" + FAT_TEST_LOCALRUN);
Log.info(c, "<clinit>", "Using filters " + Arrays.toString(testFiltersToApply));
}
public static void requireFATRunner(String className) {
if (!classesUsingFATRunner.contains(className))
throw new IllegalStateException("The class " + className + " is attempting to use functionality " +
"that requires @RunWith(FATRunner.class) to be specified at the " +
"class level.");
}
@Override
protected String testName(FrameworkMethod method) {
String testName = super.testName(method);
if (RepeatTestFilter.isAnyRepeatActionActive()) {
testName = testName + RepeatTestFilter.getRepeatActionsAsString();
}
return testName;
}
private boolean hasTests = true;
class FFDCInfo {
int count;
final String ffdcFile;
final Machine machine;
String ffdcHeader;
FFDCInfo(Machine machine, String file, int count) {
this.machine = machine;
this.ffdcFile = file;
this.count = count;
}
FFDCInfo(FFDCInfo copy, int newCount) {
this(copy.machine, copy.ffdcFile, newCount);
}
@Override
public String toString() {
return "[count=" + count + ", file=" + ffdcFile + ", machine=" + machine + "]";
}
}
public FATRunner(Class<?> tc) throws Exception {
super(tc);
classesUsingFATRunner.add(tc.getName());
try {
//filter any tests, using our list of filters
filter(new CompoundFilter(testFiltersToApply));
} catch (NoTestsRemainException e) {
//swallow this exception, because we might have Test classes that contain only tests that
// run in a mode we aren't currently in log a warning so we know
Log.warning(this.getClass(), "All tests were filtered out for class " + getTestClass().getName());
//set the flag so we can shortcut and avoid wasting time on @BeforeClass etc for stuff we aren't going to run any tests for
hasTests = false;
}
}
/*
* We only get one chance to add a child, because the runner determines what tests to run using getFilteredChildren(),
* and that method caches the results of getChildren().
*/
@Override
public List<FrameworkMethod> getChildren() {
List<FrameworkMethod> unfilteredChildren = super.getChildren();
List<FrameworkMethod> servletTests = TestServletProcessor.getServletTests(getTestClass());
if (servletTests != null && servletTests.size() > 0) {
unfilteredChildren.addAll(servletTests);
}
return unfilteredChildren;
}
@Override
public void run(RunNotifier notifier) {
if (hasTests) {
injectLibertyServers();
super.run(notifier);
}
}
/**
* Intercepting and over-riding at this point seems to be the cleanest way
* of generating a test failure and having it assigned to the right test method.
* A TestRule would be more elegant, but we seem to have to annotate
* it to each Test class, which defeats the point.
*/
@Override
public Statement methodBlock(final FrameworkMethod method) {
final Statement superStatement = super.methodBlock(method);
Statement statement = new Statement() {
@Override
public void evaluate() throws Throwable {
if (!RepeatTestFilter.shouldRun(method)) {
throw new AssumptionViolatedException("Test skipped for current RepeatAction");
}
Map<String, Long> tmpDirFilesBeforeTest = createDirectorySnapshot("/tmp");
try {
Log.info(c, "evaluate", "entering " + getTestClass().getName() + "." + method.getName());
Map<String, FFDCInfo> ffdcBeforeTest = retrieveFFDCCounts();
superStatement.evaluate();
// If we got to here without error, do a final check that
// any FFDCs were expected
Map<String, FFDCInfo> ffdcAfterTest = retrieveFFDCCounts();
Map<String, FFDCInfo> unexpectedFFDCs = filterOutPreexistingFFDCs(ffdcBeforeTest, ffdcAfterTest);
ArrayList<String> errors = new ArrayList<String>();
List<String> expectedFFDCs = getExpectedFFDCAnnotationFromTest(method);
// check for expectedFFDCs
for (String ffdcException : expectedFFDCs) {
FFDCInfo info = unexpectedFFDCs.remove(ffdcException);
if (info == null) {
errors.add("An FFDC reporting " + ffdcException + " was expected but none was found.");
}
}
Set<String> allowedFFDCs = getAllowedFFDCAnnotationFromTest(method);
// remove allowedFFDCs
for (String ffdcException : allowedFFDCs) {
if (ffdcException.equals(AllowedFFDC.ALL_FFDC))
unexpectedFFDCs.clear();
else
unexpectedFFDCs.remove(ffdcException);
}
for (FFDCInfo ffdcInfo : unexpectedFFDCs.values()) {
ffdcInfo.ffdcHeader = getFFDCHeader(new RemoteFile(ffdcInfo.machine, ffdcInfo.ffdcFile));
}
for (IgnoredFFDC ffdcToIgnore : IgnoredFFDCs.FFDCs) {
FFDCInfo ffdcInfo = unexpectedFFDCs.get(ffdcToIgnore.exception);
if (ffdcInfo != null && ffdcToIgnore.ignore(ffdcInfo.ffdcHeader)) {
unexpectedFFDCs.remove(ffdcToIgnore.exception);
}
}
// anything remaining is an error
for (Map.Entry<String, FFDCInfo> unexpected : unexpectedFFDCs.entrySet()) {
FFDCInfo ffdcInfo = unexpected.getValue();
int count = ffdcInfo.count;
if (count > 0) {
String error = "Unexpected FFDC reporting " + unexpected.getKey() + " was found (count = " + count + ")";
if (ffdcInfo.ffdcFile != null) {
error += ": " + ffdcInfo.ffdcFile + "\n" + ffdcInfo.ffdcHeader;
}
errors.add(error);
}
}
if (errors.size() > 0) {
blowup(errors.toString());
}
} catch (Throwable t) {
if (t instanceof AssumptionViolatedException) {
Log.info(c, "evaluate", "assumption violated: " + t);
} else {
Log.error(c, "evaluate", t);
if (t instanceof MultipleFailureException) {
Log.info(c, "evaluate", "Multiple failure");
MultipleFailureException e = (MultipleFailureException) t;
for (Throwable t2 : e.getFailures()) {
Log.error(c, "evaluate", t2, "Specific failure:");
}
}
}
throw newThrowableWithTimeStamp(t);
} finally {
Map<String, Long> tmpDirFilesAfterTest = createDirectorySnapshot("/tmp");
compareDirectorySnapshots("/tmp", tmpDirFilesBeforeTest, tmpDirFilesAfterTest);
Log.info(c, "evaluate", "exiting " + getTestClass().getName() + "." + method.getName());
}
}
};
return statement;
}
private static Throwable newThrowableWithTimeStamp(Throwable orig) throws Throwable {
// Create a new throwable that includes the current timestamp to help with the
// investigation of test failures. We want to create the same type of exception
// as the original in order to distinguish between a test failure (AssertionFailedError)
// and an error (RuntimeException, IOException, etc.).
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss:SSS");
String newMsg = sdf.format(new Date()) + " " + orig.getMessage();
Throwable newThrowable;
try {
Constructor<? extends Throwable> ctor = orig.getClass().getDeclaredConstructor(String.class);
ctor.setAccessible(true);
newThrowable = ctor.newInstance(newMsg);
newThrowable.setStackTrace(orig.getStackTrace());
} catch (Throwable t) {
newThrowable = new Throwable(newMsg, orig);
}
return newThrowable;
}
private static void blowup(String string) {
if (!!!DISABLE_FFDC_CHECKING) {
throw new AssertionFailedError(string);
}
}
/**
* Run at the end of the whole test. Tidy up and check for any FFDCs which were produced by the cleanup.
*/
@Override
public Statement classBlock(RunNotifier notifier) {
final Statement superStatement = super.classBlock(notifier);
Statement statement = new Statement() {
@Override
public void evaluate() throws Throwable {
if (!RepeatTestFilter.shouldRun(getTestClass().getJavaClass())) {
return;
}
try {
superStatement.evaluate();
} finally {
String ffdcHeader = null;
// This won't detect (and never did) FFDCs generated during class initialization - oh well!
ArrayList<String> ffdcAfterTest = retrieveFFDCLogs();
//Now force the post test tidy
LibertyServerFactory.tidyAllKnownServers(getTestClassNameForAssociatedServers());
ArrayList<String> ffdcAfterTidying = retrieveFFDCLogs();
// Get any FFDCs we care about before recovering the servers
List<String> unexpectedFFDCs = filterOutPreexistingFFDCs(ffdcAfterTest, ffdcAfterTidying);
// Any new FFDC after the tests run is bad - fail, including the message from the first one
if (unexpectedFFDCs.size() > 0) {
// Sort to pick up the chronologically first FFDC.
Collections.sort(unexpectedFFDCs);
ffdcHeader = findFFDCAndGetHeader(unexpectedFFDCs.get(0));
}
//Now recover the servers
LibertyServerFactory.recoverAllServers(getTestClassNameForAssociatedServers());
// Now that we're all done, throw any assertion failures for FFDCs we spotted earlier
if (ffdcHeader != null) {
blowup("A problem was detected during post-test tidy up. New FFDC file is generated. Please check the log directory. The beginning of the FFDC file is:\n"
+ ffdcHeader);
}
LogPolice.checkUsedTrace();
}
}
};
return statement;
}
private String getTestClassNameForAssociatedServers() {
//Some tests had to do things differently from all the others (I'm looking at you CDI!)
//So we should check for class rule fields and see if any of those classes have our
//special workaround annotation, and if it does, we should use the name of that class
//instead of the test class name that we would normally use.
String testClassName = getTestClass().getName();
final List<FrameworkField> classRuleFields = getTestClass().getAnnotatedFields(ClassRule.class);
for (FrameworkField ff : classRuleFields) {
Class<?> c = ff.getType();
if (c.isAnnotationPresent(LibertyServerWrapper.class))
testClassName = c.getName();
}
return testClassName;
}
/**
* Creates a new list which includes all the strings in the after list which
* are not in the before list.
*/
private List<String> filterOutPreexistingFFDCs(List<String> before, List<String> after) {
// The after list is modified in this method so create a copy
List<String> filtered = new ArrayList<String>(after);
// Filter out pre-existing FFDCs
filtered.removeAll(before);
return filtered;
}
/**
* Given a Map of FFDCs that occur before and after a test has run, return a map of the FFDCs that are unique to after-test map
*/
private Map<String, FFDCInfo> filterOutPreexistingFFDCs(Map<String, FFDCInfo> ffdcBeforeTest, Map<String, FFDCInfo> ffdcAfterTest) {
HashMap<String, FFDCInfo> filtered = new HashMap<String, FFDCInfo>(ffdcAfterTest.size());
for (Map.Entry<String, FFDCInfo> afterEntry : ffdcAfterTest.entrySet()) {
FFDCInfo beforeInfo = ffdcBeforeTest.get(afterEntry.getKey());
String exeptionKey = afterEntry.getKey();
exeptionKey = exeptionKey.substring(0, exeptionKey.indexOf(":"));
// if the FFDC exception matches, and its header is valid, the current FFDC has previosuly occurred
if (beforeInfo != null) {
int newVal = afterEntry.getValue().count - beforeInfo.count;
if (newVal != 0) {
FFDCInfo filteredInfo = new FFDCInfo(afterEntry.getValue(), newVal);
filtered.put(exeptionKey, filteredInfo);
}
} else {
filtered.put(exeptionKey, afterEntry.getValue());
}
}
return filtered;
}
private String findFFDCAndGetHeader(String ffdcFileName) {
// Find the FFDC file with the right name
Iterator<LibertyServer> it = getRunningLibertyServers().iterator();
// We'll probably only have to check one server
while (it.hasNext()) {
try {
LibertyServer server = it.next();
RemoteFile ffdcLogFile = server.getFFDCLogFile(ffdcFileName);
// Assume no two servers have FFDC logs with the same name
return getFFDCHeader(ffdcLogFile);
} catch (FileNotFoundException e) {
// This is fine - it just means the file didn't exist on this server
} catch (Exception e) {
Log.warning(this.getClass(), "Difficulties encountered searching for exceptions in FFDC logs: " + e);
return "[Could not read file contents because of unexpected exception: " + e + "]";
}
}
// We really should never get to this code since we just found the FFDC file
return "[Could not find FFDC file " + ffdcFileName + "]";
}
private String getFFDCHeader(RemoteFile ffdcLogFile) throws Exception {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(ffdcLogFile.openForReading()));
StringBuilder lines = new StringBuilder();
int numLines = 1;
for (String line; (line = reader.readLine()) != null; numLines++) {
if (line.isEmpty()) {
// FFDC incident reports put a blank line between
// the exception stack trace and the introspection.
break;
}
if (numLines > MAX_FFDC_LINES) {
lines.append("...").append('\n');
break;
}
lines.append('>').append(line).append('\n');
}
return lines.toString();
} catch (Exception e) {
Log.error(this.getClass(), "Could not read " + ffdcLogFile, e);
return "[Could not read " + ffdcLogFile + ": " + e + "]";
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Fail silently
}
}
}
}
private Collection<LibertyServer> getRunningLibertyServers() {
return LibertyServerFactory.getKnownLibertyServers(getTestClassNameForAssociatedServers());
}
/**
* Returns a map of FFDCs applicable to the current server. The map keys are in the format of
* <exception>:<ffdcFilePath>, and the map values are FFDCInfo objects. Keeping keys in this format
* allows us to keep track of FFDCs that share the same exception across multiple servers.
*/
private Map<String, FFDCInfo> retrieveFFDCCounts() {
HashMap<String, FFDCInfo> ffdcPrimaryInfo = new LinkedHashMap<String, FFDCInfo>();
try {
for (LibertyServer server : getRunningLibertyServers()) {
// If the server has the FFDC checking flag set to false, skip it.
if (server.getFFDCChecking() == false) {
Log.info(c, "retrieveFFDCCounts", "FFDC log collection for server: " + server.getServerName() + " is skipped. FFDC Checking is disabled for this server.");
continue;
}
int readAttempts = 0;
boolean retry = true;
while (retry && readAttempts++ <= 5) {
try {
ArrayList<String> summaries = server.listFFDCSummaryFiles(server.getServerName());
if (summaries.size() > 0) {
Collections.sort(summaries);
String lastSummary = summaries.get(summaries.size() - 1);
// Copy ffdcInfo so any partial updates can be discarded if there is a failure
HashMap<String, FFDCInfo> ffdcServerInfo;
if ((ffdcServerInfo = parseSummary(server.getFFDCSummaryFile(lastSummary))) != null) {
//merge returned map from server with primary map
for (Map.Entry<String, FFDCInfo> entry : ffdcServerInfo.entrySet()) {
FFDCInfo oldInfo = ffdcPrimaryInfo.get(entry.getKey());
String file = entry.getValue().ffdcFile;
if (oldInfo != null) {
// Add the counts if the primary map already had a value for that exception key.
oldInfo.count += entry.getValue().count;
ffdcPrimaryInfo.put(entry.getKey() + ":" + file, oldInfo);
} else {
ffdcPrimaryInfo.put(entry.getKey() + ":" + file, entry.getValue());
}
}
retry = false;
} else {
Log.info(c, "retrieveFFDCCounts", "Read incomplete FFDC summary file, readAttempts = " + readAttempts);
//returned null, file is truncated
retry = true;
//wait a bit and retry
Thread.sleep(500);
}
}
} catch (TopologyException e) {
//ignore the exception as log directory doesn't exist and no FFDC log
retry = false;
} catch (Exception e) {
Log.info(c, "retrieveFFDCCounts", "Exception parsing FFDC summary");
Log.error(c, "retrieveFFDCCounts", e);
retry = false;
}
}
// Only bother logging if a failure was previously logged
if (readAttempts > 1 && !retry) {
Log.info(c, "retrieveFFDCCounts", "Retry Successful");
} else if (retry) {
//retry failed 5 times
Log.info(c, "retrieveFFDCCounts", "Retry Unsuccessful");
}
}
} catch (Exception e) {
//Exception obtaining Liberty servers
Log.error(c, "retrieveFFDCCounts", e);
}
return ffdcPrimaryInfo;
}
// FFDC summary file format:
// """
//
// Index Count Time of first Occurrence Time of last Occurrence Exception SourceId ProbeId
// ------+------+---------------------------+---------------------------+---------------------------
// 0 2 4/11/13 2:25:30:312 BST 4/11/13 2:25:30:312 BST java.lang.ClassNotFoundException com.ibm.ws.config.internal.xml.validator.XMLConfigValidatorFactory 112
// - /test/jazz_build/jbe_rheinfelden/jazz/buildsystem/buildengine/eclipse/build/build.image/wlp/usr/servers/com.ibm.ws.config.validator/logs/ffdc/ffdc_13.04.11_02.25.30.0.log
// - /test/jazz_build/jbe_rheinfelden/jazz/buildsystem/buildengine/eclipse/build/build.image/wlp/usr/servers/com.ibm.ws.config.validator/logs/ffdc/ffdc_13.04.11_02.25.30.0.log
// 1 1 4/11/13 2:25:31:959 BST 4/11/13 2:25:31:959 BST java.lang.NullPointerException com.ibm.ws.threading.internal.Worker 446
// ------+------+---------------------------+---------------------------+---------------------------
// """
private HashMap<String, FFDCInfo> parseSummary(RemoteFile summaryFile) throws Exception {
HashMap<String, FFDCInfo> ffdcInfo = new LinkedHashMap<String, FFDCInfo>();
if (summaryFile.exists()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(summaryFile.openForReading()));
String line = null;
try {
// parse exception_summary
reader.readLine(); // empty line
reader.readLine(); // header line
reader.readLine(); // --- line
Machine machine = summaryFile.getMachine();
int count = 0;
String exception = "";
line = reader.readLine();
//truncated file
if (line == null) {
return null;
}
while (!(line.startsWith("---"))) {
String[] parts = line.trim().split("\\s+");
if (parts.length > 9) {
// 0 1 4/11/13 2:25:30:312 BST 4/11/13 2:25:30:312 BST java.lang.ClassNotFoundException com.ibm.ws.config.internal.xml.validator.XMLConfigValidatorFactory 112
count = Integer.parseInt(parts[1]);
exception = parts[8];
} else if (parts.length > 1 && parts[0].equals("-")) {
String ffdcFile = parts[1];
FFDCInfo oldInfo = ffdcInfo.get(exception);
if (oldInfo != null) {
oldInfo.count += count;
} else {
ffdcInfo.put(exception, new FFDCInfo(machine, ffdcFile, count));
}
} else {
Log.warning(this.getClass(), "Failed to match FFDC line: " + line);
}
line = reader.readLine();
//truncated file
if (line == null) {
return null;
}
}
} catch (Exception e) {
// Something went wrong parsing, return null so caller tries again
Log.info(this.getClass(), "retrieveFFDCCounts", "Exception parsing FFDC summary");
Log.error(this.getClass(), "retrieveFFDCCounts", e);
return null;
} finally {
reader.close();
}
}
return ffdcInfo;
}
private ArrayList<String> retrieveFFDCLogs() {
ArrayList<String> ffdcList = new ArrayList<String>();
try {
Iterator<LibertyServer> iterator = getRunningLibertyServers().iterator();
while (iterator.hasNext()) {
try {
ffdcList = LibertyServerFactory.retrieveFFDCFile(iterator.next());
} catch (TopologyException e) {
} catch (Exception e) {
Log.error(c, "retrieveFFDCLogs", e);
}
}
} catch (Exception e) {
Log.error(c, "retrieveFFDCLogs", e);
}
return ffdcList;
}
public List<String> getExpectedFFDCAnnotationFromTest(FrameworkMethod m) {
ArrayList<String> annotationListPerClass = new ArrayList<String>();
ExpectedFFDC[] ffdcs = m.getMethod().getAnnotationsByType(ExpectedFFDC.class);
for (ExpectedFFDC ffdc : ffdcs) {
if (ffdc != null) {
String[] exceptionClasses = ffdc.value();
if (JakartaEE9Action.isActive()) {
String[] jakarta9ReplacementExceptionClasses = new String[exceptionClasses.length];
System.arraycopy(exceptionClasses, 0, jakarta9ReplacementExceptionClasses, 0, exceptionClasses.length);
int index = 0;
for (String exceptionClass : exceptionClasses) {
if (ee9Helper == null) {
ee9Helper = new EE9PackageReplacementHelper();
}
jakarta9ReplacementExceptionClasses[index++] = ee9Helper.replacePackages(exceptionClass);
}
exceptionClasses = jakarta9ReplacementExceptionClasses;
}
if (RepeatTestFilter.isAnyRepeatActionActive()) {
for (String repeatAction : ffdc.repeatAction()) {
if (repeatAction.equals(ExpectedFFDC.ALL_REPEAT_ACTIONS) || RepeatTestFilter.isRepeatActionActive(repeatAction)) {
for (String exceptionClass : exceptionClasses) {
annotationListPerClass.add(exceptionClass);
}
}
}
} else {
for (String exceptionClass : exceptionClasses) {
annotationListPerClass.add(exceptionClass);
}
}
}
}
return annotationListPerClass;
}
private Set<String> getAllowedFFDCAnnotationFromTest(FrameworkMethod m) {
Set<String> annotationListPerClass = new HashSet<String>();
// Method
AllowedFFDC[] allowedffdcs = m.getMethod().getAnnotationsByType(AllowedFFDC.class);
Set<AllowedFFDC> ffdcs = new HashSet<AllowedFFDC>(Arrays.asList(allowedffdcs));
// Declaring Class
Class<?> declaringClass = m.getMethod().getDeclaringClass();
allowedffdcs = declaringClass.getAnnotationsByType(AllowedFFDC.class);
ffdcs.addAll(Arrays.asList(allowedffdcs));
// Test Class
Class<?> testClass = getTestClass().getJavaClass();
if (!declaringClass.equals(testClass)) {
allowedffdcs = testClass.getAnnotationsByType(AllowedFFDC.class);
ffdcs.addAll(Arrays.asList(allowedffdcs));
}
for (AllowedFFDC ffdc : ffdcs) {
if (ffdc != null) {
String[] exceptionClasses = ffdc.value();
if (JakartaEE9Action.isActive()) {
String[] jakarta9ReplacementExceptionClasses = new String[exceptionClasses.length];
System.arraycopy(exceptionClasses, 0, jakarta9ReplacementExceptionClasses, 0, exceptionClasses.length);
int index = 0;
for (String exceptionClass : exceptionClasses) {
if (ee9Helper == null) {
ee9Helper = new EE9PackageReplacementHelper();
}
jakarta9ReplacementExceptionClasses[index++] = ee9Helper.replacePackages(exceptionClass);
}
exceptionClasses = jakarta9ReplacementExceptionClasses;
}
if (RepeatTestFilter.isAnyRepeatActionActive()) {
for (String repeatAction : ffdc.repeatAction()) {
if (repeatAction.equals(AllowedFFDC.ALL_REPEAT_ACTIONS) || RepeatTestFilter.isRepeatActionActive(repeatAction)) {
for (String exceptionClass : exceptionClasses) {
annotationListPerClass.add(exceptionClass);
}
}
}
} else {
for (String exceptionClass : exceptionClasses) {
annotationListPerClass.add(exceptionClass);
}
}
}
}
return annotationListPerClass;
}
private void injectLibertyServers() {
String method = "injectLibertyServers";
List<FrameworkField> servers = getTestClass().getAnnotatedFields(Server.class);
for (FrameworkField frameworkField : servers) {
Field serverField = frameworkField.getField();
if (!frameworkField.isStatic())
throw new RuntimeException("Annotated field '" + serverField.getName() + "' must be static.");
if (!frameworkField.isPublic())
throw new RuntimeException("Annotated field '" + serverField.getName() + "' must be public.");
if (!LibertyServer.class.isAssignableFrom(serverField.getType()))
throw new RuntimeException("Annotated field '" + serverField.getName() + "' must be of type or subtype of " + LibertyServer.class.getCanonicalName());
Server anno = serverField.getAnnotation(Server.class);
String serverName = anno.value();
Class<?> testClass = getTestClass().getJavaClass();
try {
LibertyServer serv = LibertyServerFactory.getLibertyServer(serverName, testClass);
// Set the HTTP and IIOP ports for the LibertyServer instance
if (serv.getHttpDefaultPort() == 0) {
// Note that this case block only applies to running a FAT locally without Ant.
// Any builds using Ant to invoke JUnit will bypass this block completely.
ServerConfiguration config = serv.getServerConfiguration();
HttpEndpoint http = config.getHttpEndpoints().getById("defaultHttpEndpoint");
IncludeElement include = config.getIncludes().getBy("location", "../fatTestPorts.xml");
if (http != null) {
Log.info(c, method, "Using ports from <httpEndpoint> element in " + serverName + " server.xml");
// If there is an <httpEndpoint> element in the server config, use those ports
serv.setHttpDefaultPort(Integer.parseInt(http.getHttpPort()));
serv.setHttpDefaultSecurePort(Integer.parseInt(http.getHttpsPort()));
} else if (include != null) {
Log.info(c, method, "Using BVT HTTP port defaults in fatTestPorts.xml for " + serverName);
serv.setHttpDefaultPort(8010);
serv.setHttpDefaultSecurePort(8020);
serv.setHttpSecondaryPort(8030);
serv.setHttpSecondarySecurePort(8040);
} else {
Log.info(c, method, "No http endpoint. Using defaultInstance config for " + serverName);
serv.setHttpDefaultPort(9080);
serv.setHttpDefaultSecurePort(9443);
}
}
if (serv.getIiopDefaultPort() == 0) {
// Note that this case block only applies to running a FAT locally without Ant.
// Any builds using Ant to invoke JUnit will bypass this block completely.
serv.setIiopDefaultPort(2809);
}
serv.setConsoleLogName(testClass.getSimpleName() + ".log");
serverField.set(testClass, serv);
Log.info(c, method, "Injected LibertyServer " + serv.getServerName() + " to class " + testClass.getCanonicalName());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static Map<String, Long> createDirectorySnapshot(String path) {
// this check can be expensive on machines with lots of content in /tmp, skip unless needed
if (!ENABLE_TMP_DIR_CHECKING) {
return null;
}
Map<String, Long> snapshot = new HashMap<String, Long>();
File dir = new File(path);
File[] childFiles = dir.listFiles(); // will be null if dir is not really a directory
if (childFiles != null) {
for (File f : childFiles) {
String fileName = f.getAbsolutePath();
if (f.isDirectory()) {
snapshot.putAll(createDirectorySnapshot(fileName));
} else {
snapshot.put(fileName, f.length());
}
}
}
return snapshot;
}
private static void compareDirectorySnapshots(String path, Map<String, Long> before, Map<String, Long> after) {
if (!ENABLE_TMP_DIR_CHECKING)
return;
final String method = "compareDirectorySnapshots";
if (before.isEmpty() || after.isEmpty()) {
Log.info(c, method, "Unable to calculate directories for " + path);
return;
}
long sizeDiff = 0;
// remove all files that were previously there - adding/subtracting any changes to file sizes in between.
for (Map.Entry<String, Long> entry : before.entrySet()) {
String fileName = entry.getKey();
Long afterFileSize = after.remove(fileName);
if (afterFileSize != null) {
Long beforeFileSize = entry.getValue();
if (beforeFileSize != null) {
long difference = afterFileSize - beforeFileSize;
sizeDiff += difference;
if (difference > 0) {
Log.info(c, method, fileName + " grew by " + difference + " bytes.");
} else if (difference < 0) {
// using debug here, because we'll rarely care when a file takes up _less_ space
Log.debug(c, method + " " + fileName + " shrank by " + difference + " bytes.");
}
}
}
}
// Now the after map should only contain files that were created during this test class's execution.
for (Map.Entry<String, Long> entry : after.entrySet()) {
Long size = entry.getValue();
if (size != null) {
sizeDiff += size;
}
Log.info(c, method, "New file found during test class execution: + " + entry.getKey() + " size: " + size + " bytes.");
}
// While it is possible that a file was deleted during the test class execution, this is probably pretty rare,
// so we will not consider that possibility when determining whether the test exceeded the file size threshold.
if (ENABLE_TMP_DIR_CHECKING && sizeDiff > TMP_DIR_SIZE_THRESHOLD) {
throw new AssertionFailedError("This test class left too much garbage in the " + path + " directory. Total difference in size between start and finish is " + sizeDiff
+ " bytes");
}
}
@Override
protected void collectInitializationErrors(List<Throwable> errors) {
// Override this method to allow test classes to only declare @Test methods
// via the @TestServlet(s) annotation. Otherwise JUnit will throw an
// initialization exception because there are no tests to run
super.collectInitializationErrors(errors);
if (errors.size() > 0) {
List<Throwable> remove = new ArrayList<Throwable>();
for (Throwable error : errors) {
if ("No runnable methods".equals(error.getMessage()))
remove.add(error);
}
errors.removeAll(remove);
}
}
}
| epl-1.0 |
polarsys/eplmp | eplmp-server/eplmp-server-ejb/src/main/java/org/polarsys/eplmp/server/dao/LayerDAO.java | 1834 | /*******************************************************************************
* Copyright (c) 2017-2019 DocDoku.
* 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:
* DocDoku - initial API and implementation
*******************************************************************************/
package org.polarsys.eplmp.server.dao;
import org.polarsys.eplmp.core.exceptions.LayerNotFoundException;
import org.polarsys.eplmp.core.product.ConfigurationItemKey;
import org.polarsys.eplmp.core.product.Layer;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.List;
@RequestScoped
public class LayerDAO {
@Inject
private EntityManager em;
public LayerDAO() {
}
public List<Layer> findAllLayers(ConfigurationItemKey pKey) {
TypedQuery<Layer> query = em.createNamedQuery("Layer.findLayersByConfigurationItem", Layer.class);
query.setParameter("workspaceId", pKey.getWorkspace());
query.setParameter("configurationItemId", pKey.getId());
return query.getResultList();
}
public Layer loadLayer(int pId) throws LayerNotFoundException {
Layer layer = em.find(Layer.class, pId);
if (layer == null) {
throw new LayerNotFoundException(pId);
} else {
return layer;
}
}
public void createLayer(Layer pLayer) {
em.persist(pLayer);
em.flush();
}
public void deleteLayer(Layer layer) {
em.remove(layer);
em.flush();
}
}
| epl-1.0 |