hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
111f8cfc7b41333ac88c8d22f29250235f5aeeef | 2,547 | package com.github.correa.finalreality.model.character.player;
import com.github.correa.finalreality.controller.handlers.IEventHandler;
import com.github.correa.finalreality.model.character.AbstractCharacter;
import com.github.correa.finalreality.model.character.ICharacter;
import com.github.correa.finalreality.model.weapon.IWeapon;
import org.jetbrains.annotations.NotNull;
import java.beans.PropertyChangeSupport;
import java.util.concurrent.BlockingQueue;
/**
* A class that holds all the information of a single character of the game.
*
* @author Ignacio Slater Muñoz.
* @author Benjamín Correa Karstulovic.
*/
public abstract class AbstractPlayerCharacter extends AbstractCharacter implements IPlayerCharacter {
private IWeapon equippedWeapon;
private final PropertyChangeSupport playerDeathNotification =
new PropertyChangeSupport(this);
/**
* Creates a new player character.
* @param turnsQueue
* the queue with the characters waiting for their turn.
* @param name
* the player character's name.
* @param maxHitPoints
* the player character's maximum hit points.
* @param defensePoints
* the player character's defense points.
*/
public AbstractPlayerCharacter(
@NotNull BlockingQueue<ICharacter> turnsQueue, @NotNull String name,
int maxHitPoints, int defensePoints) {
super(turnsQueue, name, maxHitPoints, defensePoints);
this.equippedWeapon = null;
}
@Override
public int getAttack() {
if (equippedWeapon == null) {
return 0;
}
else {
return this.getEquippedWeapon().getDamage();
}
}
@Override
public abstract void equip(IWeapon weapon);
@Override
public void unequip(){
this.equippedWeapon = null;
}
/**
* Equips the weapon if the character is alive.
*/
public void equippedBy (IWeapon weapon) {
if (this.isAlive()){
this.equippedWeapon = weapon;
}
}
@Override
public IWeapon getEquippedWeapon() {
return equippedWeapon;
}
@Override
public int getWeight() {
if (getEquippedWeapon() != null) {
return this.equippedWeapon.getWeight();
}
return 0;
}
@Override
public void addPlayerDeathListener(IEventHandler playerDeathHandler) {
playerDeathNotification.addPropertyChangeListener(
playerDeathHandler);
}
@Override
public void setHitPoints(int hitPoints) {
super.setHitPoints(hitPoints);
if (hitPoints <= 0) {
playerDeathNotification.firePropertyChange(
"PLAYER_DEATH", null, this);
}
}
}
| 25.989796 | 101 | 0.720063 |
3572b84aea11cb68d9e25cd10560a22014e6c9a2 | 3,491 | package okio;
import java.io.EOFException;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
public final class InflaterSource implements Source {
private int bufferBytesHeldByInflater;
private boolean closed;
private final Inflater inflater;
private final BufferedSource source;
public InflaterSource(Source source, Inflater inflater) {
this(Okio.buffer(source), inflater);
}
InflaterSource(BufferedSource source, Inflater inflater) {
if (source == null) {
throw new IllegalArgumentException("source == null");
} else if (inflater == null) {
throw new IllegalArgumentException("inflater == null");
} else {
this.source = source;
this.inflater = inflater;
}
}
public long read(Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) {
throw new IllegalArgumentException("byteCount < 0: " + byteCount);
} else if (this.closed) {
throw new IllegalStateException("closed");
} else if (byteCount == 0) {
return 0;
} else {
boolean sourceExhausted;
do {
sourceExhausted = refill();
try {
Segment tail = sink.writableSegment(1);
int bytesInflated = this.inflater.inflate(tail.data, tail.limit, 8192 - tail.limit);
if (bytesInflated > 0) {
tail.limit += bytesInflated;
sink.size += (long) bytesInflated;
return (long) bytesInflated;
} else if (this.inflater.finished() || this.inflater.needsDictionary()) {
releaseInflatedBytes();
if (tail.pos == tail.limit) {
sink.head = tail.pop();
SegmentPool.recycle(tail);
}
return -1;
}
} catch (DataFormatException e) {
throw new IOException(e);
}
} while (!sourceExhausted);
throw new EOFException("source exhausted prematurely");
}
}
public boolean refill() throws IOException {
if (!this.inflater.needsInput()) {
return false;
}
releaseInflatedBytes();
if (this.inflater.getRemaining() != 0) {
throw new IllegalStateException("?");
} else if (this.source.exhausted()) {
return true;
} else {
Segment head = this.source.buffer().head;
this.bufferBytesHeldByInflater = head.limit - head.pos;
this.inflater.setInput(head.data, head.pos, this.bufferBytesHeldByInflater);
return false;
}
}
private void releaseInflatedBytes() throws IOException {
if (this.bufferBytesHeldByInflater != 0) {
int toRelease = this.bufferBytesHeldByInflater - this.inflater.getRemaining();
this.bufferBytesHeldByInflater -= toRelease;
this.source.skip((long) toRelease);
}
}
public Timeout timeout() {
return this.source.timeout();
}
public void close() throws IOException {
if (!this.closed) {
this.inflater.end();
this.closed = true;
this.source.close();
}
}
}
| 34.91 | 104 | 0.547408 |
68a92a290b8d48905661c035303f76fcb39ab9c5 | 43,790 | /*
* 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 gui;
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
import library.Library;
/**
*
* @author haadfida
*/
public class ClerkHome extends javax.swing.JFrame {
/**
* Creates new form Home
*/
public static Library lms;
public static String userdisp;
public static String userid;
public ClerkHome(Library lms,String display,String userid) {
initComponents();
setColor(btn_home);
resetColor(new JPanel[]{btn_BorrowerView});
this.lms=lms;
jLabelUserName.setText(display);
String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
jcurrentDate.setText(date);
this.lms=lms;
userdisp=display;
this.userid=userid;
}
/**
* 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() {
side_panel = new javax.swing.JPanel();
btn_BorrowerView = new javax.swing.JPanel();
jPanel11 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
btn_home = new javax.swing.JPanel();
jPanel12 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
ComboUser = new javax.swing.JComboBox<>();
jTextSearch = new javax.swing.JTextField();
jLabel21 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel6 = new javax.swing.JLabel();
jLabelUserName = new javax.swing.JLabel();
button_exit = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
button1 = new java.awt.Button();
jcurrentDate = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
btn_AddBorrower = new java.awt.Button();
btn_IssueItem = new java.awt.Button();
btn_ReturnItem = new java.awt.Button();
btn_UpdateBorrower = new java.awt.Button();
btn_LoanHistory = new java.awt.Button();
jLabel7 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
btn_RenewItem = new java.awt.Button();
jLabel20 = new javax.swing.JLabel();
btn_Dues = new java.awt.Button();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setUndecorated(true);
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
formMouseDragged(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
side_panel.setBackground(new java.awt.Color(23, 35, 51));
side_panel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btn_BorrowerView.setBackground(new java.awt.Color(23, 35, 51));
btn_BorrowerView.setPreferredSize(new java.awt.Dimension(170, 114));
btn_BorrowerView.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
btn_BorrowerViewMousePressed(evt);
}
});
jPanel11.setPreferredSize(new java.awt.Dimension(5, 53));
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 5, Short.MAX_VALUE)
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 60, Short.MAX_VALUE)
);
jLabel10.setFont(new java.awt.Font("Times New Roman", 0, 20)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("Borrower");
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/eye.png"))); // NOI18N
javax.swing.GroupLayout btn_BorrowerViewLayout = new javax.swing.GroupLayout(btn_BorrowerView);
btn_BorrowerView.setLayout(btn_BorrowerViewLayout);
btn_BorrowerViewLayout.setHorizontalGroup(
btn_BorrowerViewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_BorrowerViewLayout.createSequentialGroup()
.addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
.addComponent(jLabel10)
.addGap(18, 18, 18))
);
btn_BorrowerViewLayout.setVerticalGroup(
btn_BorrowerViewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, btn_BorrowerViewLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(btn_BorrowerViewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, btn_BorrowerViewLayout.createSequentialGroup()
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, btn_BorrowerViewLayout.createSequentialGroup()
.addComponent(jLabel8)
.addContainerGap())))
);
side_panel.add(btn_BorrowerView, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 200, -1, 60));
btn_home.setBackground(new java.awt.Color(41, 57, 80));
btn_home.setPreferredSize(new java.awt.Dimension(170, 114));
btn_home.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
btn_homeMousePressed(evt);
}
});
jPanel12.setPreferredSize(new java.awt.Dimension(5, 53));
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 5, Short.MAX_VALUE)
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 60, Short.MAX_VALUE)
);
jLabel12.setFont(new java.awt.Font("Times New Roman", 0, 20)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setText("Home");
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/Library-icon.png"))); // NOI18N
javax.swing.GroupLayout btn_homeLayout = new javax.swing.GroupLayout(btn_home);
btn_home.setLayout(btn_homeLayout);
btn_homeLayout.setHorizontalGroup(
btn_homeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(btn_homeLayout.createSequentialGroup()
.addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jLabel12)
.addGap(0, 47, Short.MAX_VALUE))
);
btn_homeLayout.setVerticalGroup(
btn_homeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
.addGroup(btn_homeLayout.createSequentialGroup()
.addContainerGap()
.addGroup(btn_homeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addGroup(btn_homeLayout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel12)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
side_panel.add(btn_home, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, -1, 60));
getContentPane().add(side_panel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 170, 850));
jPanel2.setBackground(new java.awt.Color(70, 120, 197));
ComboUser.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "title", "author", "subject" }));
ComboUser.setToolTipText("");
ComboUser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ComboUserActionPerformed(evt);
}
});
jTextSearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextSearchActionPerformed(evt);
}
});
jLabel21.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/research.png"))); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(479, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(174, 174, 174))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(ComboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel21)
.addGap(163, 163, 163))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(27, 27, 27)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ComboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jLabel21))
.addContainerGap(25, Short.MAX_VALUE))
);
getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 0, 1070, 80));
jPanel3.setBackground(new java.awt.Color(70, 120, 197));
jPanel4.setBackground(new java.awt.Color(120, 168, 252));
jPanel5.setBackground(new java.awt.Color(84, 127, 206));
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabelUserName.setFont(new java.awt.Font("Lucida Grande", 0, 48)); // NOI18N
jLabelUserName.setForeground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator1)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(43, 43, 43)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 234, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(46, 46, 46)
.addComponent(jLabel4)))
.addGap(18, 18, 18))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(46, 46, 46)
.addComponent(jLabelUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jLabelUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel1))
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(115, Short.MAX_VALUE))
);
button_exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/back-2.png"))); // NOI18N
button_exit.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
button_exitMousePressed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(button_exit, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(button_exit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel8.setBackground(new java.awt.Color(84, 127, 206));
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 459, Short.MAX_VALUE)
);
button1.setBackground(new java.awt.Color(70, 120, 197));
button1.setFont(new java.awt.Font("Sinhala MN", 1, 18)); // NOI18N
button1.setForeground(new java.awt.Color(255, 255, 255));
button1.setLabel("Refresh Date");
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
});
jcurrentDate.setFont(new java.awt.Font("Times New Roman", 0, 24)); // NOI18N
jcurrentDate.setForeground(new java.awt.Color(255, 255, 255));
jcurrentDate.setText("Jan 2019");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(jcurrentDate, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(218, 218, 218)
.addComponent(jcurrentDate)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(534, 534, 534)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 70, 360, 780));
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel7.setBackground(new java.awt.Color(240, 246, 246));
btn_AddBorrower.setActionCommand("d");
btn_AddBorrower.setBackground(new java.awt.Color(70, 120, 197));
btn_AddBorrower.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_AddBorrower.setForeground(new java.awt.Color(255, 255, 255));
btn_AddBorrower.setLabel("Add Borrower");
btn_AddBorrower.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_AddBorrowerActionPerformed(evt);
}
});
btn_IssueItem.setActionCommand("d");
btn_IssueItem.setBackground(new java.awt.Color(70, 120, 197));
btn_IssueItem.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_IssueItem.setForeground(new java.awt.Color(255, 255, 255));
btn_IssueItem.setLabel("Issue Item");
btn_IssueItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_IssueItemActionPerformed(evt);
}
});
btn_ReturnItem.setActionCommand("d");
btn_ReturnItem.setBackground(new java.awt.Color(70, 120, 197));
btn_ReturnItem.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_ReturnItem.setForeground(new java.awt.Color(255, 255, 255));
btn_ReturnItem.setLabel("Return Item");
btn_ReturnItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_ReturnItemActionPerformed(evt);
}
});
btn_UpdateBorrower.setActionCommand("d");
btn_UpdateBorrower.setBackground(new java.awt.Color(70, 120, 197));
btn_UpdateBorrower.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_UpdateBorrower.setForeground(new java.awt.Color(255, 255, 255));
btn_UpdateBorrower.setLabel("Update Borrower");
btn_UpdateBorrower.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_UpdateBorrowerActionPerformed(evt);
}
});
btn_LoanHistory.setActionCommand("d");
btn_LoanHistory.setBackground(new java.awt.Color(70, 120, 197));
btn_LoanHistory.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_LoanHistory.setForeground(new java.awt.Color(255, 255, 255));
btn_LoanHistory.setLabel("Loan History");
btn_LoanHistory.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_LoanHistoryActionPerformed(evt);
}
});
jLabel7.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/add-user-button.png"))); // NOI18N
jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/update.png"))); // NOI18N
jLabel16.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/library-2.png"))); // NOI18N
jLabel17.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel17.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/online-learning.png"))); // NOI18N
jLabel18.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel18.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/scholarship.png"))); // NOI18N
jLabel19.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel19.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/bank.png"))); // NOI18N
btn_RenewItem.setActionCommand("d");
btn_RenewItem.setBackground(new java.awt.Color(70, 120, 197));
btn_RenewItem.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_RenewItem.setForeground(new java.awt.Color(255, 255, 255));
btn_RenewItem.setLabel("Renew Item");
btn_RenewItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_RenewItemActionPerformed(evt);
}
});
jLabel20.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel20.setIcon(new javax.swing.ImageIcon(getClass().getResource("/LBMS/images/research-2.png"))); // NOI18N
btn_Dues.setActionCommand("d");
btn_Dues.setBackground(new java.awt.Color(70, 120, 197));
btn_Dues.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
btn_Dues.setForeground(new java.awt.Color(255, 255, 255));
btn_Dues.setLabel("Fine Payment");
btn_Dues.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_DuesActionPerformed(evt);
}
});
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(85, 85, 85)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19)
.addComponent(jLabel18)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel16)
.addComponent(jLabel17)
.addComponent(jLabel11)
.addComponent(jLabel7))))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel20)
.addGap(6, 6, 6)))
.addGap(69, 69, 69)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_LoanHistory, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_IssueItem, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_ReturnItem, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_RenewItem, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_Dues, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_UpdateBorrower, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_AddBorrower, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(352, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(btn_AddBorrower, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addComponent(btn_UpdateBorrower, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(63, 63, 63)
.addComponent(btn_IssueItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40))
.addGroup(jPanel7Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(44, 44, 44)
.addComponent(jLabel11)
.addGap(34, 34, 34)
.addComponent(jLabel16)
.addGap(32, 32, 32)))
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btn_ReturnItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_RenewItem, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(51, 51, 51)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_Dues, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel19, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(52, 52, 52)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btn_LoanHistory, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(19, 19, 19))
);
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, 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()
.addGap(42, 42, 42)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(58, Short.MAX_VALUE))
);
getContentPane().add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 80, 710, 770));
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_homeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_homeMousePressed
// TODO add your handling code here:
setColor(btn_home);
resetColor(new JPanel[]{btn_BorrowerView});
}//GEN-LAST:event_btn_homeMousePressed
private void btn_BorrowerViewMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_BorrowerViewMousePressed
// TODO add your handling code here:
BorrowerHome b=new BorrowerHome(lms,userdisp,userid);
b.setVisible(true);
}//GEN-LAST:event_btn_BorrowerViewMousePressed
private void button_exitMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button_exitMousePressed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_button_exitMousePressed
private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
// TODO add your handling code here:
int x=evt.getXOnScreen();
int y=evt.getYOnScreen();
this.setLocation(x-xx,y-xy);
}//GEN-LAST:event_formMouseDragged
int xx,xy;
private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
// TODO add your handling code here:
xx=evt.getX();
xy=evt.getY();
}//GEN-LAST:event_formMousePressed
private void btn_AddBorrowerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_AddBorrowerActionPerformed
// TODO add your handling code here:
ClerkAddBorrower c= new ClerkAddBorrower(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_AddBorrowerActionPerformed
private void btn_IssueItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_IssueItemActionPerformed
ClerkIssueItem c= new ClerkIssueItem(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_IssueItemActionPerformed
private void btn_ReturnItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ReturnItemActionPerformed
ClerkReturnItem c= new ClerkReturnItem(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_ReturnItemActionPerformed
private void btn_UpdateBorrowerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_UpdateBorrowerActionPerformed
ClerkEditBorrower c= new ClerkEditBorrower(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_UpdateBorrowerActionPerformed
private void btn_LoanHistoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_LoanHistoryActionPerformed
ClerkLoanHistory c= new ClerkLoanHistory(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_LoanHistoryActionPerformed
private void btn_RenewItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_RenewItemActionPerformed
ClerkRenewItem c= new ClerkRenewItem(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_RenewItemActionPerformed
int selected;
private void ComboUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ComboUserActionPerformed
// TODO add your handling code here:
// "Borrower", "Clerk", "Librarian"
if(ComboUser.getSelectedItem().equals("title")){
// JOptionPane.showMessageDialog(null,"Borrower Selected");
selected=1;
}
else if(ComboUser.getSelectedItem().equals("author"))
{
selected=2;
}
else if(ComboUser.getSelectedItem().equals("subject"))
{
selected=3;
}
}//GEN-LAST:event_ComboUserActionPerformed
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
jcurrentDate.setText(date);
}//GEN-LAST:event_button1ActionPerformed
private void jTextSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextSearchActionPerformed
String Search= jTextSearch.getText().toString();
switch (selected) {
case 1:
{
SearchItemTitle s = new SearchItemTitle(lms,Search,userid);
s.setVisible(true);
break;
}
case 2:
{
SearchItemAuthor s = new SearchItemAuthor(lms,Search,userid);
s.setVisible(true);
break;
}
case 3:
{
SearchItemSubject s = new SearchItemSubject(lms,Search,userid);
s.setVisible(true);
break;
}
default:
SearchItemTitle s = new SearchItemTitle(lms,Search,userid);
s.setVisible(true);
break;
}
}//GEN-LAST:event_jTextSearchActionPerformed
private void btn_DuesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_DuesActionPerformed
ClerkDues c= new ClerkDues(lms,userdisp,userid);
c.setVisible(true);
}//GEN-LAST:event_btn_DuesActionPerformed
/**
* @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 ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ClerkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ClerkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ClerkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ClerkHome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClerkHome(lms,userdisp,userid).setVisible(true);
}
});
}
private void setColor(JPanel panel)
{
panel.setBackground(new Color(41,57,80));
}
private void resetColor(JPanel[] panel)
{
for(int i=0; i<panel.length;i++){
panel[i].setBackground(new Color(23,35,51));
}
// for(int i=0; i<indicators.length;i++){
// indicators[i].setOpaque(false);
// }
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> ComboUser;
private java.awt.Button btn_AddBorrower;
private javax.swing.JPanel btn_BorrowerView;
private java.awt.Button btn_Dues;
private java.awt.Button btn_IssueItem;
private java.awt.Button btn_LoanHistory;
private java.awt.Button btn_RenewItem;
private java.awt.Button btn_ReturnItem;
private java.awt.Button btn_UpdateBorrower;
private javax.swing.JPanel btn_home;
private java.awt.Button button1;
private javax.swing.JLabel button_exit;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel jLabelUserName;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
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.JSeparator jSeparator1;
private javax.swing.JTextField jTextSearch;
private javax.swing.JLabel jcurrentDate;
private javax.swing.JPanel side_panel;
// End of variables declaration//GEN-END:variables
}
| 53.014528 | 212 | 0.661612 |
39ecb130a8a9018c8d1e28dddea16b6f8d5b2d43 | 7,741 | package org.bukkit.entity;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.minecart.CommandMinecart;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.SpawnerMinecart;
import org.bukkit.entity.minecart.RideableMinecart;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.entity.minecart.PoweredMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.inventory.ItemStack;
import org.bukkit.Location;
import org.bukkit.World;
public enum EntityType {
// These strings MUST match the strings in nms.EntityTypes and are case sensitive.
/**
* An item resting on the ground.
* <p>
* Spawn with {@link World#dropItem(Location, ItemStack)} or {@link
* World#dropItemNaturally(Location, ItemStack)}
*/
DROPPED_ITEM("Item", Item.class, 1, false),
/**
* An experience orb.
*/
EXPERIENCE_ORB("XPOrb", ExperienceOrb.class, 2),
/**
* A leash attached to a fencepost.
*/
LEASH_HITCH("LeashKnot", LeashHitch.class, 8),
/**
* A painting on a wall.
*/
PAINTING("Painting", Painting.class, 9),
/**
* An arrow projectile; may get stuck in the ground.
*/
ARROW("Arrow", Arrow.class, 10),
/**
* A flying snowball.
*/
SNOWBALL("Snowball", Snowball.class, 11),
/**
* A flying large fireball, as thrown by a Ghast for example.
*/
FIREBALL("Fireball", LargeFireball.class, 12),
/**
* A flying small fireball, such as thrown by a Blaze or player.
*/
SMALL_FIREBALL("SmallFireball", SmallFireball.class, 13),
/**
* A flying ender pearl.
*/
ENDER_PEARL("ThrownEnderpearl", EnderPearl.class, 14),
/**
* An ender eye signal.
*/
ENDER_SIGNAL("EyeOfEnderSignal", EnderSignal.class, 15),
/**
* A flying experience bottle.
*/
THROWN_EXP_BOTTLE("ThrownExpBottle", ThrownExpBottle.class, 17),
/**
* An item frame on a wall.
*/
ITEM_FRAME("ItemFrame", ItemFrame.class, 18),
/**
* A flying wither skull projectile.
*/
WITHER_SKULL("WitherSkull", WitherSkull.class, 19),
/**
* Primed TNT that is about to explode.
*/
PRIMED_TNT("PrimedTnt", TNTPrimed.class, 20),
/**
* A block that is going to or is about to fall.
*/
FALLING_BLOCK("FallingSand", FallingBlock.class, 21, false),
FIREWORK("FireworksRocketEntity", Firework.class, 22, false),
/**
* @see CommandMinecart
*/
MINECART_COMMAND("MinecartCommandBlock", CommandMinecart.class, 40),
/**
* A placed boat.
*/
BOAT("Boat", Boat.class, 41),
/**
* @see RideableMinecart
*/
MINECART("MinecartRideable", RideableMinecart.class, 42),
/**
* @see StorageMinecart
*/
MINECART_CHEST("MinecartChest", StorageMinecart.class, 43),
/**
* @see PoweredMinecart
*/
MINECART_FURNACE("MinecartFurnace", PoweredMinecart.class, 44),
/**
* @see ExplosiveMinecart
*/
MINECART_TNT("MinecartTNT", ExplosiveMinecart.class, 45),
/**
* @see HopperMinecart
*/
MINECART_HOPPER("MinecartHopper", HopperMinecart.class, 46),
/**
* @see SpawnerMinecart
*/
MINECART_MOB_SPAWNER("MinecartMobSpawner", SpawnerMinecart.class, 47),
CREEPER("Creeper", Creeper.class, 50),
SKELETON("Skeleton", Skeleton.class, 51),
SPIDER("Spider", Spider.class, 52),
GIANT("Giant", Giant.class, 53),
ZOMBIE("Zombie", Zombie.class, 54),
SLIME("Slime", Slime.class, 55),
GHAST("Ghast", Ghast.class, 56),
PIG_ZOMBIE("PigZombie", PigZombie.class, 57),
ENDERMAN("Enderman", Enderman.class, 58),
CAVE_SPIDER("CaveSpider", CaveSpider.class, 59),
SILVERFISH("Silverfish", Silverfish.class, 60),
BLAZE("Blaze", Blaze.class, 61),
MAGMA_CUBE("LavaSlime", MagmaCube.class, 62),
ENDER_DRAGON("EnderDragon", EnderDragon.class, 63),
WITHER("WitherBoss", Wither.class, 64),
BAT("Bat", Bat.class, 65),
WITCH("Witch", Witch.class, 66),
PIG("Pig", Pig.class, 90),
SHEEP("Sheep", Sheep.class, 91),
COW("Cow", Cow.class, 92),
CHICKEN("Chicken", Chicken.class, 93),
SQUID("Squid", Squid.class, 94),
WOLF("Wolf", Wolf.class, 95),
MUSHROOM_COW("MushroomCow", MushroomCow.class, 96),
SNOWMAN("SnowMan", Snowman.class, 97),
OCELOT("Ozelot", Ocelot.class, 98),
IRON_GOLEM("VillagerGolem", IronGolem.class, 99),
HORSE("EntityHorse", Horse.class, 100),
VILLAGER("Villager", Villager.class, 120),
ENDER_CRYSTAL("EnderCrystal", EnderCrystal.class, 200),
// These don't have an entity ID in nms.EntityTypes.
/**
* A flying splash potion.
*/
SPLASH_POTION(null, ThrownPotion.class, -1, false),
/**
* A flying chicken egg.
*/
EGG(null, Egg.class, -1, false),
/**
* A fishing line and bobber.
*/
FISHING_HOOK(null, Fish.class, -1, false),
/**
* A bolt of lightning.
* <p>
* Spawn with {@link World#strikeLightning(Location)}.
*/
LIGHTNING(null, LightningStrike.class, -1, false),
WEATHER(null, Weather.class, -1, false),
PLAYER(null, Player.class, -1, false),
COMPLEX_PART(null, ComplexEntityPart.class, -1, false),
/**
* An unknown entity without an Entity Class
*/
UNKNOWN(null, null, -1, false);
private String name;
private Class<? extends Entity> clazz;
private short typeId;
private boolean independent, living;
private static final Map<String, EntityType> NAME_MAP = new HashMap<String, EntityType>();
private static final Map<Short, EntityType> ID_MAP = new HashMap<Short, EntityType>();
static {
for (EntityType type : values()) {
if (type.name != null) {
NAME_MAP.put(type.name.toLowerCase(), type);
}
if (type.typeId > 0) {
ID_MAP.put(type.typeId, type);
}
}
}
private EntityType(String name, Class<? extends Entity> clazz, int typeId) {
this(name, clazz, typeId, true);
}
private EntityType(String name, Class<? extends Entity> clazz, int typeId, boolean independent) {
this.name = name;
this.clazz = clazz;
this.typeId = (short) typeId;
this.independent = independent;
if (clazz != null) {
this.living = LivingEntity.class.isAssignableFrom(clazz);
}
}
/**
*
* @deprecated Magic value
*/
@Deprecated
public String getName() {
return name;
}
public Class<? extends Entity> getEntityClass() {
return clazz;
}
/**
*
* @deprecated Magic value
*/
@Deprecated
public short getTypeId() {
return typeId;
}
/**
*
* @deprecated Magic value
*/
@Deprecated
public static EntityType fromName(String name) {
if (name == null) {
return null;
}
return NAME_MAP.get(name.toLowerCase());
}
/**
*
* @deprecated Magic value
*/
@Deprecated
public static EntityType fromId(int id) {
if (id > Short.MAX_VALUE) {
return null;
}
return ID_MAP.get((short) id);
}
/**
* Some entities cannot be spawned using {@link
* World#spawnEntity(Location, EntityType)} or {@link
* World#spawn(Location, Class)}, usually because they require additional
* information in order to spawn.
*
* @return False if the entity type cannot be spawned
*/
public boolean isSpawnable() {
return independent;
}
public boolean isAlive() {
return living;
}
}
| 28.884328 | 101 | 0.614908 |
0ee098ff296486059a9c22f7ec74362c6e7c3213 | 8,716 | /*
* #%L
* ImgLib2: a general-purpose, multidimensional image processing library.
* %%
* Copyright (C) 2009 - 2021 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld,
* John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke,
* Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner,
* Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert,
* Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin,
* Jean-Yves Tinevez and Michael Zinsmaier.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imglib2.loops;
import net.imglib2.Cursor;
import net.imglib2.loops.LoopBuilder.FiveConsumer;
import net.imglib2.loops.LoopBuilder.FourConsumer;
import net.imglib2.loops.LoopBuilder.SixConsumer;
import net.imglib2.loops.LoopBuilder.TriConsumer;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.LongConsumer;
/**
* A package-private utility class that's used by {@link LoopBuilder}.
*
* @see FastCursorLoops#createLoop(Object, List)
*/
public final class FastCursorLoops
{
private FastCursorLoops()
{
// prevent from instantiation
}
private static final List< ClassCopyProvider< LongConsumer > > factories = Arrays.asList(
new ClassCopyProvider<>( OneCursorLoop.class, LongConsumer.class ),
new ClassCopyProvider<>( TwoCursorLoop.class, LongConsumer.class ),
new ClassCopyProvider<>( ThreeCursorLoop.class, LongConsumer.class ),
new ClassCopyProvider<>( FourCursorLoop.class, LongConsumer.class ),
new ClassCopyProvider<>( FiveCursorLoop.class, LongConsumer.class ),
new ClassCopyProvider<>( SixCursorLoop.class, LongConsumer.class ) );
/**
* For example.: Given a BiConsumer and two Cursors:
* <pre>
* {@code
*
* BiConsumer<A, B> biConsumer = ... ;
* Cursor<A> cursorA = ... ;
* Cursor<B> cursorB = ... ;
* }
* </pre>
* This method
* {@code createLoop(biConsumer, Arrays.asList(cursorA, cursorB))}
* will return a LongConsumer that is functionally equivalent to:
* <pre>
* {@code
*
* LongConsumer loop = n -> {
* for ( long i = 0; i < n; i++ )
* biConsumer.accept( cursorA.next(), cursorB.next() );
* };
* }
* </pre>
* The returned {@link LongConsumer} is created in a way, that it can be
* gracefully optimised by the Java just-in-time compiler.
*
* @param action This must be an instance of {@link Consumer},
* {@link BiConsumer}, {@link TriConsumer}, {@link FourConsumer},
* {@link FiveConsumer} or {@link SixConsumer}.
* @param cursors A list of {@link Cursor}, the size of the list must fit
* given action.
* @throws IllegalArgumentException if the number of cursor does not fit the given consumer.
*/
public static LongConsumer createLoop( final Object action, final List< ? extends Cursor< ? > > cursors )
{
final Object[] arguments = ListUtils.concatAsArray( action, cursors );
ClassCopyProvider< LongConsumer > factory = factories.get( cursors.size() - 1 );
final List< Class< ? > > key = ListUtils.map( Object::getClass, arguments );
return factory.newInstanceForKey( key, arguments );
}
public static class OneCursorLoop< A > implements LongConsumer
{
private final Consumer< A > action;
private final Cursor< A > cursorA;
public OneCursorLoop( final Consumer< A > action, final Cursor< A > cursorA )
{
this.action = action;
this.cursorA = cursorA;
}
@Override
public void accept( long n )
{
while ( --n >= 0 )
action.accept( cursorA.next() );
}
}
public static class TwoCursorLoop< A, B > implements LongConsumer
{
private final BiConsumer< A, B > action;
private final Cursor< A > cursorA;
private final Cursor< B > cursorB;
public TwoCursorLoop( final BiConsumer< A, B > action, final Cursor< A > cursorA, final Cursor< B > cursorB )
{
this.action = action;
this.cursorA = cursorA;
this.cursorB = cursorB;
}
@Override
public void accept( long n )
{
while ( --n >= 0 )
action.accept( cursorA.next(), cursorB.next() );
}
}
public static class ThreeCursorLoop< A, B, C > implements LongConsumer
{
private final TriConsumer< A, B, C > action;
private final Cursor< A > cursorA;
private final Cursor< B > cursorB;
private final Cursor< C > cursorC;
public ThreeCursorLoop( final TriConsumer< A, B, C > action, final Cursor< A > cursorA, final Cursor< B > cursorB, final Cursor< C > cursorC )
{
this.action = action;
this.cursorA = cursorA;
this.cursorB = cursorB;
this.cursorC = cursorC;
}
@Override
public void accept( long n )
{
while ( --n >= 0 )
action.accept( cursorA.next(), cursorB.next(), cursorC.next() );
}
}
public static class FourCursorLoop< A, B, C, D > implements LongConsumer
{
private final FourConsumer< A, B, C, D > action;
private final Cursor< A > cursorA;
private final Cursor< B > cursorB;
private final Cursor< C > cursorC;
private final Cursor< D > cursorD;
public FourCursorLoop( final FourConsumer< A, B, C, D > action, final Cursor< A > cursorA, final Cursor< B > cursorB, final Cursor< C > cursorC, final Cursor< D > cursorD )
{
this.action = action;
this.cursorA = cursorA;
this.cursorB = cursorB;
this.cursorC = cursorC;
this.cursorD = cursorD;
}
@Override
public void accept( long n )
{
while ( --n >= 0 )
action.accept( cursorA.next(), cursorB.next(), cursorC.next(), cursorD.next() );
}
}
public static class FiveCursorLoop< A, B, C, D, E > implements LongConsumer
{
private final FiveConsumer< A, B, C, D, E > action;
private final Cursor< A > cursorA;
private final Cursor< B > cursorB;
private final Cursor< C > cursorC;
private final Cursor< D > cursorD;
private final Cursor< E > cursorE;
public FiveCursorLoop( final FiveConsumer< A, B, C, D, E > action, final Cursor< A > cursorA, final Cursor< B > cursorB, final Cursor< C > cursorC, final Cursor< D > cursorD, Cursor< E > cursorE )
{
this.action = action;
this.cursorA = cursorA;
this.cursorB = cursorB;
this.cursorC = cursorC;
this.cursorD = cursorD;
this.cursorE = cursorE;
}
@Override
public void accept( long n )
{
while ( --n >= 0 )
action.accept( cursorA.next(), cursorB.next(), cursorC.next(), cursorD.next(), cursorE.next() );
}
}
public static class SixCursorLoop< A, B, C, D, E, F > implements LongConsumer
{
private final SixConsumer< A, B, C, D, E, F > action;
private final Cursor< A > cursorA;
private final Cursor< B > cursorB;
private final Cursor< C > cursorC;
private final Cursor< D > cursorD;
private final Cursor< E > cursorE;
private final Cursor< F > cursorF;
public SixCursorLoop( final SixConsumer< A, B, C, D, E, F > action, final Cursor< A > cursorA, final Cursor< B > cursorB, final Cursor< C > cursorC, final Cursor< D > cursorD, final Cursor< E > cursorE, final Cursor< F > cursorF )
{
this.action = action;
this.cursorA = cursorA;
this.cursorB = cursorB;
this.cursorC = cursorC;
this.cursorD = cursorD;
this.cursorE = cursorE;
this.cursorF = cursorF;
}
@Override
public void accept( long n )
{
while ( --n >= 0 )
action.accept( cursorA.next(), cursorB.next(), cursorC.next(), cursorD.next(), cursorE.next(), cursorF.next() );
}
}
}
| 31.128571 | 232 | 0.689307 |
54f110f19a42ce9bbef9f3236fbef9f56e50e150 | 13,282 | /*
* 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 setoperations;
import java.awt.geom.Point2D;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import java.util.Random;
/**
*
* @author jethro
*/
public class GUI extends javax.swing.JFrame {
/**
* Creates new form GUI
*/
public GUI() {
initComponents();
}
/**
* 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() {
pointsButton = new javax.swing.JButton();
pointCountField = new javax.swing.JTextField();
drawPanel1 = new setoperations.drawPanel();
intsButton = new javax.swing.JButton();
divideButton = new javax.swing.JButton();
markButton = new javax.swing.JButton();
intersectButton = new javax.swing.JButton();
unionButton = new javax.swing.JButton();
differenceButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pointsButton.setText("Points");
pointsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pointsButtonActionPerformed(evt);
}
});
pointCountField.setText("10");
javax.swing.GroupLayout drawPanel1Layout = new javax.swing.GroupLayout(drawPanel1);
drawPanel1.setLayout(drawPanel1Layout);
drawPanel1Layout.setHorizontalGroup(
drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 719, Short.MAX_VALUE)
);
drawPanel1Layout.setVerticalGroup(
drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
intsButton.setText("Intersections");
intsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
intsButtonActionPerformed(evt);
}
});
divideButton.setText("Divide");
divideButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divideButtonActionPerformed(evt);
}
});
markButton.setText("Mark");
markButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
markButtonActionPerformed(evt);
}
});
intersectButton.setText("Intersect");
intersectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
intersectButtonActionPerformed(evt);
}
});
unionButton.setText("Union");
unionButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
unionButtonActionPerformed(evt);
}
});
differenceButton.setText("Difference");
differenceButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
differenceButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(pointCountField, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 47, Short.MAX_VALUE))
.addComponent(pointsButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(intsButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(divideButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(markButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(intersectButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(unionButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(differenceButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(drawPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(pointCountField, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(pointsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(intsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(divideButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(markButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(unionButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(intersectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(differenceButton, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(272, Short.MAX_VALUE))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void pointsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pointsButtonActionPerformed
int npoints = Integer.parseInt(pointCountField.getText());
drawPanel1.polyA = new Polygon(generateStar(npoints));
drawPanel1.polyB = new Polygon(generateStar(npoints));
drawPanel1.repaint();
}//GEN-LAST:event_pointsButtonActionPerformed
private void intsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_intsButtonActionPerformed
drawPanel1.intersec = Algorithms.allIntersections(drawPanel1.polyA,drawPanel1.polyB);
drawPanel1.repaint();
}//GEN-LAST:event_intsButtonActionPerformed
private void divideButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_divideButtonActionPerformed
drawPanel1.polyA = Algorithms.divideAll(drawPanel1.polyA, drawPanel1.intersec);
drawPanel1.polyB = Algorithms.divideAll(drawPanel1.polyB, drawPanel1.intersec);
drawPanel1.repaint();
}//GEN-LAST:event_divideButtonActionPerformed
private void markButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_markButtonActionPerformed
Algorithms.setInside(drawPanel1.polyA, drawPanel1.polyB);
drawPanel1.repaint();
}//GEN-LAST:event_markButtonActionPerformed
private void intersectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_intersectButtonActionPerformed
drawPanel1.polyOut = Algorithms.polyIntersect(drawPanel1.polyA, drawPanel1.polyB);
drawPanel1.repaint();
}//GEN-LAST:event_intersectButtonActionPerformed
private void unionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unionButtonActionPerformed
drawPanel1.polyOut = Algorithms.polyUnion(drawPanel1.polyA, drawPanel1.polyB);
drawPanel1.repaint();
}//GEN-LAST:event_unionButtonActionPerformed
private void differenceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_differenceButtonActionPerformed
drawPanel1.polyOut = Algorithms.polyDiff(drawPanel1.polyA, drawPanel1.polyB);
drawPanel1.repaint();
}//GEN-LAST:event_differenceButtonActionPerformed
public Point2D[] generateStar(int size){
Point2D [] points;
points = new Point2D[size];
Random rnd;
rnd = new Random();
for (int i=0;i<size;i++){
double rand = (2*Math.PI/size)*(-i);
double x = (cos(rand)/2)*rnd.nextDouble() + 0.5;
double y = (sin(rand)/2)*rnd.nextDouble() + 0.5;
points[i] = new Point2D.Double(x,y);
}
return points;
}
/**
* @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 ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton differenceButton;
private javax.swing.JButton divideButton;
private setoperations.drawPanel drawPanel1;
private javax.swing.JButton intersectButton;
private javax.swing.JButton intsButton;
private javax.swing.JButton markButton;
private javax.swing.JTextField pointCountField;
private javax.swing.JButton pointsButton;
private javax.swing.JButton unionButton;
// End of variables declaration//GEN-END:variables
}
| 51.281853 | 187 | 0.677383 |
8f9ff34a29b8a0103cb33cea17b37706a3d6acaa | 359 | package pruefungsvorbereitung;
public class VCE2014ExamCQuestion034 {
public static void main(String[] args) {
try {
// some code here
int b = 0;
int a = 1/b;
} catch (NullPointerException e1) {
System.out.print("a");
} catch (Exception e2) {
System.out.print("b");
} finally {
System.out.print("c");
}
}
}
| 17.95 | 42 | 0.593315 |
7af03be0bb7d2ba47329bdcaf7627906496be1fd | 4,971 | package com.yhy.flow.engine.persist;
import com.yhy.flow.db.service.FlowDfnEventService;
import com.yhy.flow.db.service.FlowDfnProcessService;
import com.yhy.flow.db.service.FlowXmlProcessService;
import com.yhy.flow.engine.model.event.StartEventNode;
import com.yhy.flow.engine.parser.XMLParser;
import com.yhy.flow.model.ems.EventType;
import com.yhy.flow.model.entity.dfn.DfnEvent;
import com.yhy.flow.model.entity.dfn.DfnProcess;
import com.yhy.flow.model.entity.xml.XMLProcess;
import com.yhy.jakit.core.internal.Lists;
import com.yhy.jakit.core.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
/**
* Created on 2021-10-12 10:22
*
* @author 颜洪毅
* @version 1.0.0
* @since 1.0.0
*/
@Slf4j
public class ProcessPersist extends Abstract {
private final XMLParser parser;
private final FlowXmlProcessService xmlProcessRepository;
private final FlowDfnProcessService dfnProcessRepository;
private final FlowDfnEventService dfnEventRepository;
private ProcessPersist(XMLParser parser) {
super(parser.getEngine());
this.parser = parser;
xmlProcessRepository = context.beanOf(FlowXmlProcessService.class);
dfnProcessRepository = context.beanOf(FlowDfnProcessService.class);
dfnEventRepository = context.beanOf(FlowDfnEventService.class);
}
public static ProcessPersist create(XMLParser parser) {
return new ProcessPersist(parser);
}
public void persist() {
String name = parser.getName();
// 1、更新下 xml 数据库记录
persistXMLProcess(name, parser.getXml());
// 2、保存流程定义信息
String processId = persistProcess();
// 3、保存开始事件定义
persistStartEvent(processId);
}
private void persistStartEvent(String processId) {
StartEventNode node = parser.getStartEvent();
List<DfnEvent> byNameAndProcess = dfnEventRepository.listByNameAndProcessIdAndType(node.getName(), processId, EventType.Start);
if (CollectionUtils.isNotEmpty(byNameAndProcess)) {
// 已存在,更新
// 每个流程定义里,只能有一个开始事件
if (byNameAndProcess.size() > 1) {
throw new IllegalStateException("There is duplicate startEvent nodes in process '" + processId + "' named '" + parser.getName() + "'.");
}
DfnEvent event = byNameAndProcess.get(0);
event.setLabel(node.getLabel());
event.setCallback(node.getCallback());
event.beforeUpdate(context.currentUser());
dfnEventRepository.updateByName(event);
} else {
// 创建
DfnEvent event = new DfnEvent();
event.setName(node.getName());
event.setLabel(node.getLabel());
event.setProcessId(processId);
event.setType(EventType.Start);
event.setCallback(node.getCallback());
event.beforeCreate(context.currentUser());
dfnEventRepository.create(event);
byNameAndProcess = Lists.of(event);
}
// 清除多余的数据,如历史记录
// 先查出关联了该流程的,再把不叫这个名字的删了
List<DfnEvent> byProcess = dfnEventRepository.listByProcessIdAndType(processId, EventType.Start);
List<DfnEvent> shouldDeleteList = Lists.difference(byProcess, byNameAndProcess, (dfnEvent, dfnEvent2) -> dfnEvent.getId().equals(dfnEvent2.getId()));
if (CollectionUtils.isNotEmpty(shouldDeleteList)) {
dfnEventRepository.deleteBatch(shouldDeleteList);
}
}
public String persistProcess() {
String name = parser.getName();
String version = parser.getVersion();
String description = parser.getDescription();
DfnProcess process = dfnProcessRepository.getByName(name);
if (null != process) {
// 存在,更新
process.setVersion(version);
process.setDescription(description);
process.beforeUpdate(context.currentUser());
process = dfnProcessRepository.updateByName(process);
} else {
// 创建
process = new DfnProcess();
process.setName(name);
process.setVersion(version);
process.setDescription(description);
process.beforeCreate(context.currentUser());
process = dfnProcessRepository.create(process);
}
return process.getId();
}
private void persistXMLProcess(String name, String xml) {
XMLProcess process = xmlProcessRepository.getByName(name);
if (null != process) {
// 已存在,更新
process.setXml(xml);
process.beforeUpdate(context.currentUser());
xmlProcessRepository.updateByName(process);
} else {
// 不存在,新增
process = new XMLProcess();
process.setName(name);
process.setXml(xml);
process.beforeCreate(context.currentUser());
xmlProcessRepository.create(process);
}
}
}
| 36.284672 | 157 | 0.651378 |
326dbc9000c32a080c2203f82341f52368391297 | 6,045 | package com.vailsys.persephony.api.conference;
import static com.vailsys.persephony.json.PersyGson.gson;
import java.util.HashMap;
import com.vailsys.persephony.api.PersyCommon;
import com.vailsys.persephony.api.PersyJSONException;
import com.google.gson.JsonSyntaxException;
/**
* This class represents a Persephony Conference instance. Conference objects are created
* by the SDK whenever a conference instance would be returned by the API; these
* primarily come from a {@link com.vailsys.persephony.api.conference.ConferencesRequester}
* inside a {@link com.vailsys.persephony.api.PersyClient} instance.<br>
* <br>
* Conferences are immutable and intended only to be used to read information
* returned from the API in a language accessible way.
*
* @see com.vailsys.persephony.api.conference.ConferencesRequester
* @see com.vailsys.persephony.api.PersyClient
*/
public class Conference extends PersyCommon {
/**
* The conferenceId for this conference instance.
*/
private String conferenceId;
/**
* The accountId of the account that created this conference.
*/
private String accountId;
/**
* The alias for this conference.
*/
private String alias;
/**
* This represents the current playBeep of this conference.
* @see com.vailsys.persephony.api.conference.PlayBeep
*/
private PlayBeep playBeep;
/**
* Whether this conference is being recorded.
*/
private Boolean record;
/**
* This represents the current status or state of this conference.
* @see com.vailsys.persephony.api.conference.ConferenceStatus
*/
private ConferenceStatus status;
/**
* The url Persephony checks for actions to perform to calls in this conference while waiting for it to start.
*/
private String waitUrl;
/**
* The url Persephony sends updates to when the conference changes states.
*/
private String statusCallBackUrl;
/**
* The list of subresources for this conference. Includes participants
* and/or recordings associated with this conference.
*/
private HashMap<String, String> subresourceUris;
/**
* Converts the provided JSON string into a Conference object.
*
* @param json A JSON string representing a Persephony Conference instance.
*
* @return A Conference object equivalent to the JSON string passed in.
* @throws PersyJSONException when the JSON is invalid.
*/
public static Conference fromJson (String json) throws PersyJSONException {
try {
return gson.fromJson(json, Conference.class);
}
catch(JsonSyntaxException jse) {
throw new PersyJSONException(jse);
}
}
/**
* Retrieve the conferenceId for this conference from the object.
*
* @return The conferenceId for this conference.
*/
public String getConferenceId() {
return this.conferenceId;
}
/**
* Retrieve the accountId for this conference from the object.
*
* @return The accountId for this conference.
*/
public String getAccountId() {
return this.accountId;
}
/**
* Retrieve the alias for this conference from the object.
*
* @return The alias for this conference.
*/
public String getAlias() {
return this.alias;
}
/**
* Retrieve the playBeep for this conference from the object.
*
* @return The playBeep for this conference.
*/
public PlayBeep getPlayBeep() {
return this.playBeep;
}
/**
* Retrieve the record for this conference from the object.
*
* @return The record for this conference.
*/
public Boolean getRecord() {
return this.record;
}
/**
* Retrieve the status for this conference from the object.
*
* @return The status for this conference.
*/
public ConferenceStatus getStatus() {
return this.status;
}
/**
* Retrieve the wait url for this conference from the object.
*
* @return The wait url for this conference.
*/
public String getWaitUrl() {
return this.waitUrl;
}
/**
* Retrieve the status callback url for this conference from the object.
*
* @return The status callback url for this conference.
*/
public String getStatusCallBackUrl() {
return this.statusCallBackUrl;
}
/**
* Retrieve the subresourceUris for this conference from the object.
*
* @return The subresourceUris for this conference.
*/
public HashMap<String, String> getSubresourceUris() {
return this.subresourceUris;
}
/**
* Check if this conference equals another. This is done by comparing all fields in the conference for equality.
*
* @param that The Conference object for comparison.
* @return {@code true} if conferences are equal, {@code false} otherwise.
*/
public boolean equals(Conference that){
boolean result = super.equals(that);
if(this.conferenceId != null){
result = result && that.conferenceId.equals(this.conferenceId);
} else {
result = result && that.conferenceId == null;
}
if(this.accountId != null){
result = result && that.accountId.equals(this.accountId);
} else {
result = result && that.accountId == null;
}
if(this.alias != null){
result = result && that.alias.equals(this.alias);
} else {
result = result && that.alias== null;
}
if(this.playBeep != null){
result = result && that.playBeep.equals(this.playBeep);
} else {
result = result && that.playBeep == null;
}
if(this.record != null){
result = result && that.record.equals(this.record);
} else {
result = result && that.record == null;
}
if(this.status != null){
result = result && that.status.equals(this.status);
} else {
result = result && that.status == null;
}
if(this.waitUrl != null){
result = result && that.waitUrl.equals(this.waitUrl);
} else {
result = result && that.waitUrl == null;
}
if(this.statusCallBackUrl != null){
result = result && that.statusCallBackUrl.equals(this.statusCallBackUrl);
} else {
result = result && that.statusCallBackUrl == null;
}
if(this.subresourceUris != null){
result = result && that.subresourceUris.equals(this.subresourceUris);
} else {
result = result && that.subresourceUris == null;
}
return result;
}
}
| 26.39738 | 113 | 0.706038 |
b114d229f60ec96de58eebdf63c4444a3e6f28f1 | 12,591 | package com.tomaskostadinov.weatherapp.helper;
import android.content.Intent;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.Toast;
import com.tomaskostadinov.weatherapp.R;
import com.tomaskostadinov.weatherapp.activity.MainActivity;
import com.tomaskostadinov.weatherapp.adapter.ForecastOverviewAdapter;
import com.tomaskostadinov.weatherapp.model.Day;
import com.tomaskostadinov.weatherapp.model.Place;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by Tomas on 17.05.2015.
*/
public class WeatherHelper {
private NotificationHelper nh;
private Double kelvin = 272.15;
private String city = "lol";
private String description, formattedDater, tomorrow_desc;
private Integer weatherid, sunrise, sunset, humidity, tomorrowweatherid;
private Double temperature_max, speed, pressure, tomorrow_temp;
private static Integer istat = R.drawable.ic_sunny;
public ArrayList<Day> items;
public ForecastOverviewAdapter adapter;
public void setCity(String in){
city = in;
}
public void setDescription(String in){
description = in;
}
public void setWeatherId(Integer in){
weatherid = in;
}
public void setTomorrowWeatherId(Integer in){
tomorrowweatherid = in;
}
public void setSunrise(Integer in){
sunrise = in;
}
public void setSunset(Integer in){
sunset = in;
}
public void setTemperature_max(Double in){
temperature_max = in;
}
public void setHumidity(Integer in){
humidity = in;
}
public void setPressure(Double in){
pressure = in;
}
public void setSpeed(Double in){
speed = in;
}
public void setTomorrowTemp(Double in){
tomorrow_temp = in;
}
public void setTomorrowDesc(String in){
tomorrow_desc = in;
}
public String getCity(){
return city;
}
public String getDescription(){
return description;
}
public Integer getWeatherId(){
return weatherid;
}
public Integer getTomorrowWeatherId(){
return tomorrowweatherid;
}
public Integer getSunrise(){
return sunrise;
}
public Integer getSunset(){
return sunset;
}
public Double getTemperature_max(){
return temperature_max;
}
public Integer getHumidity(){
return humidity;
}
public Double getPressure(){
return pressure;
}
public Double getSpeed(){
return speed;
}
public Double getTomorrow_temp(){
return tomorrow_temp;
}
public String getTomorrow_desc(){
return tomorrow_desc;
}
/**
*man
* @param in json input
*/
public void ParseData(String in){
try {
JSONObject reader = new JSONObject(in);
JSONObject city = reader.getJSONObject("city");
setCity(city.getString("name"));
JSONArray list = reader.getJSONArray("list");
JSONObject JSONList = list.getJSONObject(0);
JSONArray weather = JSONList.getJSONArray("weather");
JSONObject JSONWeather = weather.getJSONObject(0);
setDescription(JSONWeather.getString("description"));
setWeatherId(JSONWeather.getInt("id"));
//JSONObject sys = reader.getJSONObject("sys");
String country = city.getString("country");
//setSunrise(sys.getInt("sunrise"));
//setSunset(sys.getInt("sunset"));
JSONObject temp = JSONList.getJSONObject("temp");
//Integer temperature_min = main.getInt("temp_min");
setTemperature_max(temp.getDouble("morn"));
setHumidity(JSONList.getInt("humidity"));
setPressure(JSONList.getDouble("pressure"));
//JSONObject wind = reader.getJSONObject("wind");
setSpeed(JSONList.getDouble("speed"));
//temperature_min = Math.round(temperature_min) - kelvin;
setTemperature_max(temperature_max);
JSONObject tomorrowJSONList = list.getJSONObject(1);
JSONObject tomorrowtemp = tomorrowJSONList.getJSONObject("temp");
setTomorrowTemp(tomorrowtemp.getDouble("day"));
JSONArray tomorrowweather = tomorrowJSONList.getJSONArray("weather");
JSONObject tomorrowJSONWeather = tomorrowweather.getJSONObject(0);
setTomorrowWeatherId(tomorrowJSONWeather.getInt("id"));
setTomorrowDesc(tomorrowJSONWeather.getString("description"));
items = new ArrayList<>();
for (int i = 0; i < list.length(); i++) {
JSONObject forJSONList = list.getJSONObject(i);
JSONArray forWeather = forJSONList.getJSONArray("weather");
JSONObject forJSONWeather = forWeather.getJSONObject(0);
JSONObject fortemp = forJSONList.getJSONObject("temp");
Log.i("RecyclerView", "JSON Parsing Nr." + i);
items.add(new Day(forJSONList.getInt("dt"), fortemp.getDouble("max"), fortemp.getDouble("min"), forJSONList.getDouble("pressure"), forJSONList.getInt("humidity"), forJSONWeather.getInt("id"), forJSONWeather.getString("description"), forJSONList.getDouble("speed")));
Log.i("RecyclerView", "Added items Nr" + i);
adapter.notifyItemInserted(0);
Log.i("RecyclerView", "notifyItemInserted Nr." + i);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("JSON Parsing", e.toString());
}
}
public void ParseDataSingle(String in){
try {
JSONObject reader = new JSONObject(in);
JSONObject city = reader.getJSONObject("city");
setCity(city.getString("name"));
JSONArray list = reader.getJSONArray("list");
JSONObject JSONList = list.getJSONObject(0);
JSONArray weather = JSONList.getJSONArray("weather");
JSONObject JSONWeather = weather.getJSONObject(0);
setDescription(JSONWeather.getString("description"));
setWeatherId(JSONWeather.getInt("id"));
//JSONObject sys = reader.getJSONObject("sys");
String country = city.getString("country");
//setSunrise(sys.getInt("sunrise"));
//setSunset(sys.getInt("sunset"));
JSONObject temp = JSONList.getJSONObject("temp");
//Integer temperature_min = main.getInt("temp_min");
setTemperature_max(temp.getDouble("morn"));
setHumidity(JSONList.getInt("humidity"));
setPressure(JSONList.getDouble("pressure"));
//JSONObject wind = reader.getJSONObject("wind");
setSpeed(JSONList.getDouble("speed"));
//temperature_min = Math.round(temperature_min) - kelvin;
setTemperature_max(temperature_max);
JSONObject tomorrowJSONList = list.getJSONObject(1);
JSONObject tomorrowtemp = tomorrowJSONList.getJSONObject("temp");
setTomorrowTemp(tomorrowtemp.getDouble("day"));
JSONArray tomorrowweather = tomorrowJSONList.getJSONArray("weather");
JSONObject tomorrowJSONWeather = tomorrowweather.getJSONObject(0);
setTomorrowWeatherId(tomorrowJSONWeather.getInt("id"));
setTomorrowDesc(tomorrowJSONWeather.getString("description"));
} catch (Exception e) {
e.printStackTrace();
Log.e("JSON Parsing", e.toString());
}
}
public ArrayList<Day> getDays() {
return items;
}
/**
*
* @param ID the weather id
* @return Integer weather drawable
*/
public Integer convertWeather(Integer ID){
switch (ID){
case 200:
case 201:
case 202:
case 210:
case 211:
case 212:
case 221:
case 230:
case 231:
case 232:
istat = R.drawable.ic_rain;
break;
case 300:
case 301:
case 302:
case 310:
case 311:
case 312:
case 313:
case 314:
case 321:
istat = R.drawable.ic_rain;
break;
case 500:
case 501:
case 502:
case 503:
case 504:
case 511:
case 520:
case 521:
case 522:
case 531:
istat = R.drawable.ic_rain;
break;
case 600:
case 601:
case 602:
case 611:
case 612:
case 615:
case 616:
case 620:
case 621:
case 622:
istat = R.drawable.ic_rain;
//stat = R.drawable.ic_snow;
break;
case 700:
case 711:
case 721:
case 731:
case 741:
case 751:
case 761:
case 762:
case 771:
case 781:
istat = R.drawable.ic_cloud;
break;
case 800:
istat = R.drawable.ic_sunny;
break;
case 801:
case 802:
istat = R.drawable.ic_cloudy;
break;
case 803:
case 804:
istat = R.drawable.ic_cloud;
break;
case 900:
case 901:
case 902:
case 903:
case 904:
case 905:
case 906:
istat = R.drawable.ic_cloud;
break;
default:
istat = R.drawable.ic_sunny;
break;
}
return istat;
}
public static Integer convertWeatherToColor(Integer ID){
switch (ID){
case 200:
case 201:
case 202:
case 210:
case 211:
case 212:
case 221:
case 230:
case 231:
case 232:
istat = R.color.rainyWeather;
break;
case 300:
case 301:
case 302:
case 310:
case 311:
case 312:
case 313:
case 314:
case 321:
istat = R.color.badWeather;
break;
case 500:
case 501:
case 502:
case 503:
case 504:
case 511:
case 520:
case 521:
case 522:
case 531:
istat = R.color.rainyWeather;
break;
case 600:
case 601:
case 602:
case 611:
case 612:
case 615:
case 616:
case 620:
case 621:
case 622:
istat = R.color.badWeather;
break;
case 700:
case 711:
case 721:
case 731:
case 741:
case 751:
case 761:
case 762:
case 771:
case 781:
istat = R.color.warningWeather;
break;
case 800:
istat = R.color.sunnyWeather;
break;
case 801:
istat = R.color.sunnyWeather;
break;
case 802:
istat = R.color.goodWeather;
break;
case 803:
case 804:
istat = R.color.goodWeather;
break;
case 900:
case 901:
case 902:
case 903:
case 904:
case 905:
case 906:
istat = R.color.warningWeather;
break;
default:
istat = R.color.sunnyWeather;
break;
}
return istat;
}
/**
*
* @param Time unix timestamp
* @return SimpleDateFormat
*/
public String convertTime(Integer Time){
formattedDater = DateUtils.getRelativeTimeSpanString(Time, System.currentTimeMillis(), 0).toString();
return formattedDater;
}
} | 28.486425 | 282 | 0.534112 |
f3cbf3e0981fa1348492f1e931e2ea52fa695981 | 3,168 |
package io.slingr.endpoints.afip.fev1.dif.afip.gov.ar;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for PtoVenta complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PtoVenta">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Nro" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="EmisionTipo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Bloqueado" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="FchBaja" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PtoVenta", propOrder = {
"nro",
"emisionTipo",
"bloqueado",
"fchBaja"
})
public class PtoVenta {
@XmlElement(name = "Nro")
protected int nro;
@XmlElement(name = "EmisionTipo")
protected String emisionTipo;
@XmlElement(name = "Bloqueado")
protected String bloqueado;
@XmlElement(name = "FchBaja")
protected String fchBaja;
/**
* Gets the value of the nro property.
*
*/
public int getNro() {
return nro;
}
/**
* Sets the value of the nro property.
*
*/
public void setNro(int value) {
this.nro = value;
}
/**
* Gets the value of the emisionTipo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEmisionTipo() {
return emisionTipo;
}
/**
* Sets the value of the emisionTipo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEmisionTipo(String value) {
this.emisionTipo = value;
}
/**
* Gets the value of the bloqueado property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBloqueado() {
return bloqueado;
}
/**
* Sets the value of the bloqueado property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBloqueado(String value) {
this.bloqueado = value;
}
/**
* Gets the value of the fchBaja property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFchBaja() {
return fchBaja;
}
/**
* Sets the value of the fchBaja property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFchBaja(String value) {
this.fchBaja = value;
}
}
| 22.791367 | 105 | 0.565657 |
571e2cadd72b957ff45a520940bfe523f87c557d | 3,011 | package adf.app;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Logger;
public class AppManifestAttributes {
private static final Logger logger = Logger.getLogger(AppManifestAttributes.class.getName());
private static final String APP_VERSION_KEY = "Application-Version";
private static final String APP_BUILD_DATE_KEY = "Built-Date";
private static String APPLICATION_ATTRIBUTE_NOT_INITIALIZED = "Not Initialized";
private static String APPLICATION_VERSION_DEVELOPMENT = "Development";
private static String BUILD_DATE_NOT_DEFINED = "Not defined";
private static Manifest manifest;
private static Attributes attributes;
private static boolean initialized;
public static final void initialize() {
assert !initialized : "Application Manifest already initialized";
try {
String className = AppManifestAttributes.class.getName();
className = className.replace(".", "/") + ".class";
URL resourceURL = AppManifestAttributes.class.getClassLoader().getResource(className);
URLConnection openConnection = resourceURL.openConnection();
if (!(openConnection instanceof JarURLConnection)) {
logger.severe("Application started not from Jar. Manifest not retrieved.");
return;
}
if (openConnection instanceof JarURLConnection) {
JarURLConnection jarConnection = (JarURLConnection) openConnection;
manifest = jarConnection.getManifest();
if (manifest == null) {
logger.severe("Application Manifest not retrieved.");
return;
}
attributes = manifest.getMainAttributes();
if (attributes == null) {
logger.severe("Application Manifest Attributes not retrieved.");
return;
}
logger.severe("Application Manifest retrieved: " + manifest);
initialized = true;
}
} catch (Throwable e) {
logger.severe("Cannot read Application Manifest.");
}
}
public static final String getAppVersion() {
if (!initialized) {
return APPLICATION_VERSION_DEVELOPMENT;
}
String appVersion = attributes.getValue(APP_VERSION_KEY);
appVersion = (appVersion != null && !appVersion.isEmpty()) ? appVersion : APPLICATION_ATTRIBUTE_NOT_INITIALIZED;
return appVersion;
}
public static final String getAppBuiltDate() {
if (!initialized) {
return BUILD_DATE_NOT_DEFINED;
}
String buildDate = attributes.getValue(APP_BUILD_DATE_KEY);
buildDate = (buildDate != null && !buildDate.isEmpty()) ? buildDate : APPLICATION_ATTRIBUTE_NOT_INITIALIZED;
return buildDate;
}
}
| 38.602564 | 120 | 0.647293 |
4d49da02e037e9deeb7a5936d41f0a1128c2850d | 1,383 | package blockchain.chain;
import blockchain.data.Passport;
import blockchain.exceptions.TransactionsSizeException;
import blockchain.transactions.Transaction;
import org.junit.jupiter.api.Test;
import testutils.ParentTest;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BlockchainTest extends ParentTest {
@Test
void getPassportTest() {
Passport passport = blockchain.getPassport("1");
assertNotNull(passport, "Passport should be returned");
assertEquals(dataProvider.getPassportWithVisaData(), passport, "Last passport modification " +
"was not returned");
}
@Test
void mineBlockTest() throws TransactionsSizeException {
List<Transaction> transactionList = new ArrayList<>();
transactionList.add(dataProvider.getDefaultTransaction());
int blockchainOldSize = blockchain.getBlockchain().size();
blockchain.mineBlock(transactionList);
assertEquals(blockchainOldSize + 1, blockchain.getBlockchain().size(),
"Blockchain size should increase");
}
@Test
void isChainValid() {
assertTrue(blockchain.isChainValid(), "Blockchain should be valid");
}
} | 33.731707 | 102 | 0.730296 |
df444b194848cef84ff1d4c904a9ff9f0c510c8a | 21,122 | package com.runabove;
import static org.junit.Assert.assertNotNull;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import com.runabove.api.AccountManager;
import com.runabove.api.AuthManager;
import com.runabove.api.ContainerManager;
import com.runabove.api.FlavorManager;
import com.runabove.api.ImageManager;
import com.runabove.api.InstanceManager;
import com.runabove.api.RegionManager;
import com.runabove.api.RunAboveBuilder;
import com.runabove.api.RunAboveConfig;
import com.runabove.api.RunAboveManager;
import com.runabove.api.SSHKeyManager;
import com.runabove.error.LoggerErrorHandler;
import com.runabove.model.account.Account;
import com.runabove.model.account.Balance;
import com.runabove.model.account.CurrentUsage;
import com.runabove.model.auth.AccessRule;
import com.runabove.model.auth.Credential;
import com.runabove.model.auth.CredentialParams;
import com.runabove.model.auth.DefaultCredentialParams;
import com.runabove.model.billing.BillingBandwidthInstanceDetails;
import com.runabove.model.billing.BillingInstanceDetails;
import com.runabove.model.billing.BillingProjectDetails;
import com.runabove.model.billing.BillingProjectUse;
import com.runabove.model.image.Image;
import com.runabove.model.image.ImageDetail;
import com.runabove.model.instance.Flavor;
import com.runabove.model.instance.Instance;
import com.runabove.model.instance.InstanceAlter;
import com.runabove.model.instance.InstanceDetail;
import com.runabove.model.instance.InstanceIP;
import com.runabove.model.instance.InstanceQuota;
import com.runabove.model.instance.InstanceVNC;
import com.runabove.model.ssh.SSHKeyPair;
import com.runabove.model.ssh.SSHKeyPairDetail;
import com.runabove.model.storage.Catalog;
import com.runabove.model.storage.Endpoint;
import com.runabove.model.storage.StorageContainer;
import com.runabove.model.storage.StorageContainerCreate;
import com.runabove.model.storage.StorageContainerDetail;
import com.runabove.model.storage.StorageContainerObject;
import com.runabove.model.token.Domain;
import com.runabove.model.token.OpenstackToken;
import com.runabove.model.token.Role;
import com.runabove.model.token.Token;
import com.runabove.model.token.TokenProject;
import com.runabove.model.token.User;
/*
* Copyright (c) 2014, OVH
* 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.
* Except as contained in this notice, the name of OVH and or its trademarks
* (and among others RunAbove) shall not be used in advertising or otherwise to
* promote the sale, use or other dealings in this Software without prior
* written authorization from OVH.
* Unit test for run above api
*
*
*/
/**
* The Class ApiTest.
*/
public class ApiTest extends AbstractPojoTester {
/** The Constant LOG. */
private static final Logger LOG = LoggerFactory.getLogger(ApiTest.class);
/**
* Test generic builder.
*/
@Test
public void testGenericBuilder() {
// create a runabove auth api
AuthManager runAboveAuth = new RunAboveBuilder(getConfig()).createAuthManager();
assertNotNull(runAboveAuth);
// create a runabove api
RunAboveManager runAbove = new RunAboveBuilder(getConfig()).createManager(new MockClient());
assertNotNull(runAbove);
}
/**
* Test auth.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testAuth() throws IOException {
// create a runabove auth api
AuthManager runAboveAuth = new RunAboveBuilder(getConfig()).createAuthManager(new MockAuthClient());
assertNotNull(runAboveAuth);
// everything is merged into a credential params so retrofit can autoconvert it into json (see jake wharton SO answer about it)
Credential creds = runAboveAuth.credential(new DefaultCredentialParams());
// we can get the consumer key
assertNotNull(creds);
assertNotNull(creds.getConsumerKey());
}
/**
* Test login and me.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testLoginAndMe() throws IOException {
// create a runabove api
RunAboveManager runAboveApi = new RunAboveBuilder(getConfig()).createManager(new MockClient());
assertNotNull(runAboveApi);
// get my account
Account account = runAboveApi.me();
assertNotNull(account);
assertNotNull(account.getEmail());
LOG.info("Account getEmail=" + account.getEmail());
LOG.info("Account getAccountIdentifier=" + account.getAccountIdentifier());
LOG.info("Account getName=" + account.getName());
LOG.info("Account getFirstname=" + account.getFirstname());
LOG.info("Account getCellNumber=" + account.getCellNumber());
LOG.info("Account getAddress=" + account.getAddress());
LOG.info("Account getPostalCode=" + account.getPostalCode());
LOG.info("Account getCity=" + account.getCity());
LOG.info("Account getArea=" + account.getArea());
LOG.info("Account getCountry=" + account.getCountry());
}
/**
* Test projects.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testProjects() throws IOException {
RunAboveManager runAboveApi = login();
String[] projects = runAboveApi.project();
assertNotNull(projects);
for (int i = 0; i < projects.length; i++) {
LOG.info("PROJECTS " + projects[i]);
}
}
/**
* Test token.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testToken() throws IOException {
RunAboveManager runAboveApi = login();
// request a token for openstack swift from the api (this can also directly asked to keystone)
Token toekn = runAboveApi.token();
assertNotNull(toekn);
LOG.info("XAUTH TOEKN = " + toekn.getXAuthToken());
List<Catalog> catalogues = toekn.getToken().getCatalog();
assertNotNull(catalogues);
for (Catalog catalog : catalogues) {
if ("object-store".equals(catalog.getType())) {
for (Endpoint ep : catalog.getEndpoints()) {
LOG.info("Store id " + ep.getId());
LOG.info("Store interface " + ep.getInterface());
LOG.info("Store region " + ep.getRegion());
LOG.info("Store url " + ep.getUrl());
}
}
}
}
/**
* Test create instance.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testCreateInstance() throws IOException {
RunAboveManager runAboveApi = login();
InstanceDetail instanceDetail = new InstanceDetail();
// get a flavor
Flavor[] flavors = runAboveApi.getFlavor();
instanceDetail.setFlavor(flavors[0]);
// get a region
String[] regions = runAboveApi.getRegions();
instanceDetail.setRegion(regions[0]);
// get an image
Image[] imgs = runAboveApi.getImages();
instanceDetail.setImage(imgs[0]);
// create an instance
InstanceDetail resultInstance = runAboveApi.createInstance(instanceDetail);
// list all the instances
Instance[] listInstances = runAboveApi.getInstances();
assertNotNull(listInstances);
for (Instance instance : listInstances) {
LOG.info("instance id " + instance.getInstanceId());
LOG.info("instance name " + instance.getName());
}
runAboveApi.deleteInstance(resultInstance.getInstanceId(), new Callback<Void>() {
public void failure(RetrofitError arg0) {
LOG.info("instance deletion failed");
}
public void success(Void arg0, Response arg1) {
LOG.info("instance deletion successful");
}
});
}
/**
* Test images.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testImages() throws IOException {
RunAboveManager runAboveApi = login();
// get all available images
Image[] imgs = runAboveApi.getImages();
assertNotNull(imgs);
for (Image image : imgs) {
LOG.info("image id " + image.getId());
LOG.info("image name " + image.getName());
LOG.info("image region " + image.getRegion());
}
}
/**
* Test image detail.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testImageDetail() throws IOException {
RunAboveManager runAboveApi = login();
// get all available images
Image[] imgs = runAboveApi.getImages();
assertNotNull(imgs);
for (Image image : imgs) {
ImageDetail imageDetail = runAboveApi.getImage(image.getId());
LOG.info("imageDetail id " + imageDetail.getId());
LOG.info("imageDetail name " + imageDetail.getName());
LOG.info("imageDetail region " + imageDetail.getRegion());
LOG.info("imageDetail creation date " + imageDetail.getCreationDate());
LOG.info("imageDetail mindisk " + imageDetail.getMinDisk());
LOG.info("imageDetail minram " + imageDetail.getMinRam());
LOG.info("imageDetail status " + imageDetail.getStatus());
}
}
/**
* Test instances.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testInstances() throws IOException {
RunAboveManager runAboveApi = login();
String[] regions = runAboveApi.getRegions();
assertNotNull(regions);
String firstRegion = regions[0];
assertNotNull(firstRegion);
// get instance quota
InstanceQuota instanceQuota = runAboveApi.getInstanceQuota(firstRegion);
LOG.info("InstanceQuota getCores " + instanceQuota.getCores());
LOG.info("InstanceQuota getInstances " + instanceQuota.getInstances());
LOG.info("InstanceQuota getKeypairs " + instanceQuota.getKeypairs());
LOG.info("InstanceQuota getRam " + instanceQuota.getRam());
LOG.info("InstanceQuota getSecurityGroups " + instanceQuota.getSecurityGroups());
// get all available instances
Instance[] instances = runAboveApi.getInstances();
assertNotNull(instances);
for (Instance instance : instances) {
LOG.info("instance getCreated " + instance.getCreated());
LOG.info("instance getFlavorId " + instance.getFlavorId());
LOG.info("instance getImageId " + instance.getImageId());
LOG.info("instance getInstanceId " + instance.getInstanceId());
LOG.info("instance getIp " + instance.getIp());
LOG.info("instance getName " + instance.getName());
LOG.info("instance getRegion " + instance.getRegion());
LOG.info("instance getStatus " + instance.getStatus());
Instance instanceDetail = runAboveApi.getInstance(instance.getInstanceId());
assertNotNull(instanceDetail);
LOG.info("instanceDetail getInstanceId " + instanceDetail.getInstanceId());
InstanceVNC instanceVNC = runAboveApi.getInstanceVNC(instance.getInstanceId());
assertNotNull(instanceVNC);
LOG.info("instanceVNC getType " + instanceVNC.getType());
LOG.info("instanceVNC getUrl " + instanceVNC.getUrl());
}
}
/**
* Test regions.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testRegions() throws IOException {
RunAboveManager runAboveApi = login();
// get all available regions
String[] regions = runAboveApi.getRegions();
assertNotNull(regions);
for (String string : regions) {
LOG.info("Regions " + string);
}
}
/**
* Test balance usage.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testBalanceUsage() throws IOException {
RunAboveManager runAboveApi = login();
// get all available billing info
BillingProjectUse[] uses = runAboveApi.getUsage(true, "2014-04-19", null, "2014-04-19");
assertNotNull(uses);
for (BillingProjectUse billingProjectUse : uses) {
LOG.info("BillingProjectUse project id " + billingProjectUse.getProjectId());
LOG.info("BillingProjectUse region " + billingProjectUse.getRegion());
for (BillingProjectDetails details : billingProjectUse.getDetails()) {
LOG.info("Details getBandwidthInstance " + details.getBandwidthInstance());
LOG.info("Details " + details.getBandwidthStorage());
LOG.info("Details " + details.getBandwidthStorageDetails());
LOG.info("Details " + details.getFrom());
LOG.info("Details " + details.getInstance());
LOG.info("Details " + details.getStorage());
LOG.info("Details " + details.getStorageDetails());
LOG.info("Details " + details.getTo());
for (BillingBandwidthInstanceDetails bwdetail : details.getBandwidthInstanceDetails()) {
LOG.info("Detaisl BW Id " + bwdetail.getId());
LOG.info("Detaisl BW Quantity " + bwdetail.getQuantity());
}
}
}
Balance balance = runAboveApi.getBalance();
assertNotNull(balance);
LOG.info("balance " + balance.getCreditLeft());
if (balance.getCurrentUsages() != null) {
for (CurrentUsage usage : balance.getCurrentUsages()) {
LOG.info("balance usage " + usage.getProjectId());
LOG.info("balance usage " + usage.getCurrentTotal());
}
}
}
// ssh
/**
* Test ssh.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testSSH() throws IOException {
RunAboveManager runAboveApi = login();
SSHKeyPair[] sshKeyPair = runAboveApi.getSSHKeyPairs();
assertNotNull(sshKeyPair);
for (SSHKeyPair ssh : sshKeyPair) {
LOG.info("SSHKeyPair getFingerPrint " + ssh.getFingerPrint());
LOG.info("SSHKeyPair getName " + ssh.getName());
LOG.info("SSHKeyPair getPublicKey " + ssh.getPublicKey());
LOG.info("SSHKeyPair getRegion " + ssh.getRegion());
}
}
// storage
/**
* Test storage get.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testStorageGet() throws IOException {
RunAboveManager runAboveApi = login();
// get all available files in a storage container
StorageContainer[] containers = runAboveApi.getStoreContainers();
assertNotNull(containers);
for (StorageContainer storageContainer : containers) {
LOG.info("StorageContainer getContainerName " + storageContainer.getName());
LOG.info("StorageContainer getRegion " + storageContainer.getRegion());
LOG.info("StorageContainer getStored " + storageContainer.getStored());
LOG.info("StorageContainer getPublic " + storageContainer.getPublic());
LOG.info("StorageContainer getRegion " + storageContainer.getRegion());
LOG.info("StorageContainer getTotalFiles " + storageContainer.getTotalObjects());
StorageContainerDetail detail = runAboveApi.getStoreContainerDetail(storageContainer.getName(), 10, storageContainer.getRegion(), null);
assertNotNull(detail);
if (detail.getFiles() != null) {
for (StorageContainerObject file : detail.getFiles()) {
LOG.info("StorageContainerFile getContentType " + file.getContentType());
LOG.info("StorageContainerFile getLastModified " + file.getLastModified());
LOG.info("StorageContainerFile getName " + file.getName());
LOG.info("StorageContainerFile getSize " + file.getSize());
}
}
}
}
/**
* Test storage create.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testStorageCreate() throws IOException {
RunAboveManager runAboveApi = login();
StorageContainerCreate storageContainer = new StorageContainerCreate();
storageContainer.setContainerName("dummy");
storageContainer.setContainerRegion("BHS-1");
StorageContainerDetail containerDetail = runAboveApi.createStorageContainer(storageContainer);
assertNotNull(containerDetail);
LOG.info("containerDetail " + containerDetail.getName());
}
/**
* Test flavor.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testFlavor() throws IOException {
RunAboveManager runAboveApi = login();
// get all available instances
Flavor[] falvors = runAboveApi.getFlavor();
assertNotNull(falvors);
for (Flavor flavor : falvors) {
LOG.info("Flavor getDisk " + flavor.getDisk());
LOG.info("Flavor getId " + flavor.getId());
LOG.info("Flavor getName " + flavor.getName());
LOG.info("Flavor getRam " + flavor.getRam());
LOG.info("Flavor getRegion " + flavor.getRegion());
LOG.info("Flavor getVcpus " + flavor.getVcpus());
}
}
/**
* Test project.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testProject() throws IOException {
RunAboveManager runAboveApi = login();
String[] projects = runAboveApi.project();
assertNotNull(projects);
for (String project : projects) {
LOG.info("Project " + project);
}
}
/**
* Test builder.
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Test
public void testBuilder() throws IOException {
AccountManager acm = new RunAboveBuilder(getConfig()).createAccountManager(new MockClient());
assertNotNull(acm);
ContainerManager cm = new RunAboveBuilder(getConfig()).createContainerManager(new MockClient());
assertNotNull(cm);
FlavorManager flm = new RunAboveBuilder(getConfig()).createFlavorManager(new MockClient());
assertNotNull(flm);
ImageManager imm = new RunAboveBuilder(getConfig()).createImageManager(new MockClient());
assertNotNull(imm);
InstanceManager ism = new RunAboveBuilder(getConfig()).createInstanceManager(new MockClient());
assertNotNull(ism);
RegionManager rem = new RunAboveBuilder(getConfig()).createRegionManager(new MockClient());
assertNotNull(rem);
SSHKeyManager sshm = new RunAboveBuilder(getConfig()).createSSHKeyManager(new MockClient());
assertNotNull(sshm);
}
/**
* Login.
*
* @return the run above manager
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private RunAboveManager login() throws IOException {
// to switch from mockup client to real client, just uncomment this line and comment the one below
// return new RunAboveBuilder(getConfig()).createManager(consummerKey);
return new RunAboveBuilder(getConfig()).createManager(new MockClient());
}
/**
* Gets the config.
*
* @return the config
*/
private RunAboveConfig getConfig() {
return new RunAboveConfig().setErrorHandlder(new LoggerErrorHandler()).setApplicationKey("").setApplicationSecret("");
}
/**
* Test pojo.
* @throws IntrospectionException
* @throws InstantiationException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
@Test
public void testPojo() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, IntrospectionException {
// this is to ensure that pojo with complex getters and setters logic do work properly (if applicable)
// and increase test coverage to maximum value
// objects should be used properly in normal tests before entering the pojo phase test
// instance
testPojo(InstanceDetail.class);
testPojo(InstanceAlter.class);
testPojo(Instance.class);
testPojo(Flavor.class);
testPojo(InstanceIP.class);
testPojo(InstanceQuota.class);
testPojo(InstanceVNC.class);
// account
testPojo(Account.class);
testPojo(Balance.class);
testPojo(CurrentUsage.class);
// auth
testPojo(AccessRule.class);
testPojo(Credential.class);
testPojo(CredentialParams.class);
testPojo(DefaultCredentialParams.class);
// billing
testPojo(BillingBandwidthInstanceDetails.class);
testPojo(BillingInstanceDetails.class);
testPojo(BillingProjectDetails.class);
testPojo(BillingProjectUse.class);
// ssh
testPojo(SSHKeyPair.class);
testPojo(SSHKeyPairDetail.class);
// storage
testPojo(Catalog.class);
testPojo(Endpoint.class);
testPojo(StorageContainerCreate.class);
testPojo(StorageContainer.class);
testPojo(StorageContainerDetail.class);
testPojo(StorageContainerObject.class);
// token
testPojo(Domain.class);
testPojo(OpenstackToken.class);
testPojo(Role.class);
testPojo(Token.class);
testPojo(TokenProject.class);
testPojo(User.class);
}
}
| 32.495385 | 156 | 0.725878 |
c36a307f55f9462f4bb9ed694e77fd106bf3c80c | 984 | /* Java implementation of Shell Sort*/
public class Shell_Sort
{
public void sort(int input[]) // Function implementing Insertion Sort
{
int n = input.length, temp, j;
for (int gap = n / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < n; i++) // Gapped insertion sort
{
temp = input[i];
for (j = i; j >= gap && input[j - gap] > temp; j = j - gap)
input[j] = input[j - gap];
input[j] = temp;
}
}
}
public static void main(String[] args)
{
int input[] = {5, 6, 8, 4, 6, 5, 3, 3, 2, 7, 8, 45, 85, 96}; //Input array
shellSort ob = new shellSort();
ob.sort(input);
System.out.print("Output : ");
for (int i = 0; i < input.length; ++i) // Printing Sorted array
System.out.print(input[i] + " ");
}
}
/*
Output : 2 3 3 4 5 5 6 6 7 8 8 45 85 96
*/
| 22.883721 | 82 | 0.447154 |
007de9646932b7354023a56c1afc58ae883b299e | 3,070 | /*
* Copyright 2015-present Facebook, Inc.
*
* 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.
*/
// Copyright 2014 Google Inc. 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://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.facebook.buck.query;
import com.facebook.buck.core.model.QueryTarget;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.facebook.buck.query.QueryEnvironment.Argument;
import com.facebook.buck.query.QueryEnvironment.ArgumentType;
import com.facebook.buck.query.QueryEnvironment.QueryFunction;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.util.Set;
import org.immutables.value.Value;
/** A query expression for user-defined query functions. */
@Value.Immutable(prehash = true, builder = false, copy = false)
@BuckStyleValue
public abstract class FunctionExpression<NODE_TYPE> extends QueryExpression<NODE_TYPE> {
@Value.Auxiliary
public abstract QueryFunction<?, NODE_TYPE> getFunction();
// Use the function's class for equals/hashcode.
@Value.Derived
Class<?> getFunctionClass() {
return getFunction().getClass();
}
public abstract ImmutableList<Argument<NODE_TYPE>> getArgs();
@Override
@SuppressWarnings("unchecked")
<OUTPUT_TYPE extends QueryTarget> Set<OUTPUT_TYPE> eval(
QueryEvaluator<NODE_TYPE> evaluator, QueryEnvironment<NODE_TYPE> env) throws QueryException {
return ((QueryFunction<OUTPUT_TYPE, NODE_TYPE>) getFunction()).eval(evaluator, env, getArgs());
}
@Override
public void traverse(QueryExpression.Visitor<NODE_TYPE> visitor) {
if (visitor.visit(this) == VisitResult.CONTINUE) {
for (Argument<NODE_TYPE> arg : getArgs()) {
if (arg.getType() == ArgumentType.EXPRESSION) {
arg.getExpression().traverse(visitor);
}
}
}
}
@Override
public String toString() {
return getFunction().getName()
+ "("
+ Joiner.on(", ").join(Iterables.transform(getArgs(), Object::toString))
+ ")";
}
}
| 36.117647 | 99 | 0.735179 |
a4c1ca3e370ad3b99ff3e8a0e2498772b01eeefb | 1,796 | package com.braintreepayments.api.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.braintreepayments.api.annotations.Beta;
import com.google.gson.annotations.SerializedName;
/**
* A class to contain 3D Secure information about the current
* {@link com.braintreepayments.api.models.Card}
*/
@Beta
public class ThreeDSecureInfo implements Parcelable {
@SerializedName("liabilityShifted") private boolean mLiabilityShifted;
@SerializedName("liabilityShiftPossible") private boolean mLiabilityShiftPossible;
public ThreeDSecureInfo() {}
/**
* @return If the 3D Secure liability shift has occurred for the current
* {@link com.braintreepayments.api.models.Card}
*/
public boolean isLiabilityShifted() {
return mLiabilityShifted;
}
/**
* @return If the 3D Secure liability shift is possible for the current
* {@link com.braintreepayments.api.models.Card}
*/
public boolean isLiabilityShiftPossible() {
return mLiabilityShiftPossible;
}
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeByte(mLiabilityShifted ? (byte) 1 : (byte) 0);
dest.writeByte(mLiabilityShiftPossible ? (byte) 1 : (byte) 0);
}
private ThreeDSecureInfo(Parcel in) {
mLiabilityShifted = in.readByte() != 0;
mLiabilityShiftPossible = in.readByte() != 0;
}
public static final Creator<ThreeDSecureInfo> CREATOR = new Creator<ThreeDSecureInfo>() {
public ThreeDSecureInfo createFromParcel(Parcel source) {
return new ThreeDSecureInfo(source);
}
public ThreeDSecureInfo[] newArray(int size) {return new ThreeDSecureInfo[size];}
};
}
| 29.933333 | 93 | 0.700445 |
9b9838dd3bd2032d25945638882b6539df70ec20 | 934 | package g2001_2100.s2012_sum_of_beauty_in_the_array;
// #Medium #Array #2022_05_24_Time_10_ms_(44.69%)_Space_98.1_MB_(18.43%)
public class Solution {
public int sumOfBeauties(int[] nums) {
int[] maxArr = new int[nums.length];
maxArr[0] = nums[0];
for (int i = 1; i < nums.length - 1; i++) {
maxArr[i] = Math.max(maxArr[i - 1], nums[i]);
}
int[] minArr = new int[nums.length];
minArr[nums.length - 1] = nums[nums.length - 1];
for (int i = nums.length - 2; i >= 0; i--) {
minArr[i] = Math.min(minArr[i + 1], nums[i]);
}
int sum = 0;
for (int i = 1; i < nums.length - 1; i++) {
if (nums[i] > maxArr[i - 1] && nums[i] < minArr[i + 1]) {
sum += 2;
} else if (nums[i] > nums[i - 1] && nums[i] < nums[i + 1]) {
sum += 1;
}
}
return sum;
}
}
| 31.133333 | 72 | 0.474304 |
0cf6d4130168fed877a25a135c8bd3f10f5e9b15 | 312 | package de.claudioaltamura.java.functional.bestpractices;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class BarTest {
@Test
void test() {
Bar<String, String> fn = str -> str + "fb";
assertThat(fn.apply(fn.defaultMethod())).isEqualTo("defaultfb");
}
} | 19.5 | 66 | 0.727564 |
54a20356e66855765d0c91391c226f9b23a520d1 | 6,473 | package com.phoenixnap.oss.ramlplugin.raml2code.rules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Set;
import org.hamcrest.MatcherAssert;
import org.hamcrest.text.IsEqualCompressingWhiteSpace;
import org.jsonschema2pojo.AnnotationStyle;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.phoenixnap.oss.ramlplugin.raml2code.data.ApiActionMetadata;
import com.phoenixnap.oss.ramlplugin.raml2code.data.ApiResourceMetadata;
import com.phoenixnap.oss.ramlplugin.raml2code.exception.InvalidRamlResourceException;
import com.phoenixnap.oss.ramlplugin.raml2code.helpers.RamlParser;
import com.phoenixnap.oss.ramlplugin.raml2code.plugin.TestConfig;
import com.phoenixnap.oss.ramlplugin.raml2code.raml.RamlRoot;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.writer.SingleStreamCodeWriter;
/**
* @author armin.weisser
* @since 0.4.1
*/
public abstract class AbstractRuleTestBase {
public static final boolean VISUALISE_CODE = false;
public static final String RESOURCE_BASE = "ramls/";
public static final String VALIDATOR_BASE = "validations/";
public static final String LINE_END = System.getProperty("line.separator");
public static RamlRoot RAML;
protected static final Logger logger = LoggerFactory.getLogger(AbstractRuleTestBase.class);
protected JCodeModel jCodeModel;
protected RamlParser defaultRamlParser;
protected Rule<JCodeModel, JDefinedClass, ApiResourceMetadata> rule;
private ApiResourceMetadata controllerMetadata;
public AbstractRuleTestBase() {
defaultRamlParser = new RamlParser("/api");
}
/**
* add GSON at the end of the name if correspond
* @param fileName
* @return
*/
public static String getFileAnnotationDiscriminator(String fileName){
if ( TestConfig.isGSONAnnotationStyle() )
fileName += "GSON";
return fileName;
}
@BeforeClass
public static void initRaml() throws InvalidRamlResourceException {
TestConfig.resetConfig();
if ( System.getProperty("isGSON") != null && System.getProperty("isGSON").toLowerCase().equals("true"))
TestConfig.setAnnotationStyle(AnnotationStyle.GSON);
RAML = RamlLoader.loadRamlFromFile(RESOURCE_BASE + "test-single-controller.raml");
}
@Before
public void setupModel() {
jCodeModel = new JCodeModel();
}
protected void initControllerMetadata(RamlParser par) {
controllerMetadata = par.extractControllers(jCodeModel, RAML).iterator().next();
}
protected ApiResourceMetadata getControllerMetadata() {
if (controllerMetadata == null) {
initControllerMetadata(defaultRamlParser);
}
return controllerMetadata;
}
protected Set<ApiResourceMetadata> getAllControllersMetadata() {
return defaultRamlParser.extractControllers(jCodeModel, RAML);
}
protected ApiActionMetadata getEndpointMetadata() {
return getEndpointMetadata(1);
}
protected ApiActionMetadata getEndpointMetadata(int number) {
return getControllerMetadata().getApiCalls().stream().skip(number - 1).findFirst().get();
}
protected String serializeModel() {
return serializeModel(jCodeModel);
}
protected String serializeModel(JCodeModel jCodeModel) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
jCodeModel.build(new SingleStreamCodeWriter(bos));
} catch (IOException e) {
assertThat(e.getMessage(), is(nullValue()));
}
return bos.toString();
}
@After
public void printCode() {
if (VISUALISE_CODE) {
logger.debug(serializeModel());
}
}
protected void verifyGeneratedCode(String name) throws Exception {
verifyGeneratedCode(name, serializeModel());
}
protected void verifyGeneratedCode(String name, String generatedCode) throws Exception {
String removedSerialVersionUID = removeSerialVersionUID(generatedCode);
String fileName = VALIDATOR_BASE + name + ".java.txt";
logger.debug("comparing to file " + fileName);
String expectedCode = getTextFromFile(fileName);
try {
MatcherAssert.assertThat(name + " is not generated correctly.", removedSerialVersionUID,
new IsEqualIgnoringLeadingAndEndingWhiteSpaces(expectedCode));
} catch (AssertionError e) {
// We let assertEquals fail here instead, because better IDE support
// for multi line string diff.
assertEquals(expectedCode, removedSerialVersionUID);
}
}
protected String getTextFromFile(String resourcePath) throws Exception {
URI uri = getUri(resourcePath);
return new String(Files.readAllBytes(Paths.get(uri)), StandardCharsets.UTF_8);
}
protected URI getUri(String resourcePath) throws URISyntaxException {
URL resource = getClass().getClassLoader().getResource(resourcePath);
return resource.toURI();
}
public static class IsEqualIgnoringLeadingAndEndingWhiteSpaces extends IsEqualCompressingWhiteSpace {
public IsEqualIgnoringLeadingAndEndingWhiteSpaces(String string) {
super(string);
}
@Override
public String stripSpaces(String toBeStripped) {
String result = "";
BufferedReader bufReader = new BufferedReader(new StringReader(toBeStripped));
String line;
try {
while ((line = bufReader.readLine()) != null) {
result += super.stripSpaces(line);
}
} catch (IOException e) {
return e.getMessage();
}
return result;
}
}
protected String removeSerialVersionUID(String serializedModel) throws IOException {
BufferedReader bufReader = new BufferedReader(new StringReader(serializedModel));
StringWriter stringWriter = new StringWriter();
BufferedWriter bufWriter = new BufferedWriter(stringWriter);
String line = null;
while ((line = bufReader.readLine()) != null) {
if (!line.contains("serialVersionUID = ")) {
bufWriter.write(line + LINE_END);
}
}
bufWriter.flush();
bufWriter.close();
return stringWriter.toString();
}
public static void loadRaml(String ramlFileName) {
RAML = RamlLoader.loadRamlFromFile(RESOURCE_BASE + ramlFileName);
}
}
| 30.971292 | 106 | 0.774602 |
f848a43d8a942e26e6487e0940ac40bbba4ce688 | 3,734 | package com.santosediego.dscatalog.services;
import java.util.Optional;
import javax.persistence.EntityNotFoundException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.santosediego.dscatalog.dto.RoleDTO;
import com.santosediego.dscatalog.dto.UserDTO;
import com.santosediego.dscatalog.dto.UserInsertDTO;
import com.santosediego.dscatalog.dto.UserUpdateDTO;
import com.santosediego.dscatalog.entities.Role;
import com.santosediego.dscatalog.entities.User;
import com.santosediego.dscatalog.repositories.RoleRepository;
import com.santosediego.dscatalog.repositories.UserRepository;
import com.santosediego.dscatalog.services.exceptions.DatabaseException;
import com.santosediego.dscatalog.services.exceptions.ResourceNotFoundException;
@Service
public class UserService implements UserDetailsService {
private static Logger logger = org.slf4j.LoggerFactory.getLogger(UserService.class);
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserRepository repository;
@Autowired
private RoleRepository roleRepository;
@Transactional(readOnly = true)
public Page<UserDTO> findAllPaged(PageRequest pageRequest) {
Page<User> list = repository.findAll(pageRequest);
return list.map(x -> new UserDTO(x));
}
@Transactional(readOnly = true)
public UserDTO findById(Long id) {
Optional<User> obj = repository.findById(id);
User entity = obj.orElseThrow(() -> new ResourceNotFoundException("Entity not found"));
return new UserDTO(entity);
}
@Transactional
public UserDTO insert(UserInsertDTO dto) {
User entity = new User();
copyDtoToEntity(dto, entity);
entity.setPassword(passwordEncoder.encode(dto.getPassword()));
entity = repository.save(entity);
return new UserDTO(entity);
}
@Transactional
public UserDTO update(Long id, UserUpdateDTO dto) {
try {
User entity = repository.getOne(id);
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new UserDTO(entity);
} catch (EntityNotFoundException e) {
throw new ResourceNotFoundException("Id not found " + id);
}
}
public void delete(Long id) {
try {
repository.deleteById(id);
} catch (EmptyResultDataAccessException e) {
throw new ResourceNotFoundException("Id not found " + id);
} catch (DataIntegrityViolationException e) {
throw new DatabaseException("Integrity violation");
}
}
private void copyDtoToEntity(UserDTO dto, User entity) {
entity.setFirstName(dto.getFirstName());
entity.setLastName(dto.getLastName());
entity.setEmail(dto.getEmail());
entity.getRoles().clear();
for (RoleDTO roleDTO : dto.getRoles()) {
Role role = roleRepository.getOne(roleDTO.getId());
entity.getRoles().add(role);
}
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = repository.findByEmail(username);
if(user == null) {
logger.error("User not found " + username);
throw new UsernameNotFoundException("Email no found");
}
logger.info("User found " + username);
return user;
}
} | 31.91453 | 90 | 0.788163 |
8b0d2d1b3fda60fc323667672ecf270eb53d0c18 | 13,167 | package net.minecraft.client.renderer.entity;
import org.vivecraft.render.PlayerModelController;
import org.vivecraft.render.PlayerModelController.RotInfo;
import org.vivecraft.utils.Quaternion;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.player.AbstractClientPlayerEntity;
import net.minecraft.client.renderer.entity.layers.ArrowLayer;
import net.minecraft.client.renderer.entity.layers.BipedArmorLayer;
import net.minecraft.client.renderer.entity.layers.CapeLayer;
import net.minecraft.client.renderer.entity.layers.Deadmau5HeadLayer;
import net.minecraft.client.renderer.entity.layers.ElytraLayer;
import net.minecraft.client.renderer.entity.layers.HeadLayer;
import net.minecraft.client.renderer.entity.layers.HeldItemLayer;
import net.minecraft.client.renderer.entity.layers.ParrotVariantLayer;
import net.minecraft.client.renderer.entity.layers.SpinAttackEffectLayer;
import net.minecraft.client.renderer.entity.model.BipedModel;
import net.minecraft.client.renderer.entity.model.PlayerModel;
import net.minecraft.client.renderer.entity.model.VRArmorModel;
import net.minecraft.client.renderer.entity.model.VRPlayerModel;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerModelPart;
import net.minecraft.item.CrossbowItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.UseAction;
import net.minecraft.scoreboard.Score;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.util.Hand;
import net.minecraft.util.HandSide;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
public class VRPlayerRenderer extends LivingRenderer<AbstractClientPlayerEntity, VRPlayerModel<AbstractClientPlayerEntity>>
{
public VRPlayerRenderer(EntityRendererManager p_i3452_1_)
{
this(p_i3452_1_, false);
}
public VRPlayerRenderer(EntityRendererManager p_i3453_1_, boolean p_i3453_2_)
{
super(p_i3453_1_, new VRPlayerModel<>(0.0F, p_i3453_2_), 0.5F);
BipedArmorLayer layer = new BipedArmorLayer<>(this, new VRArmorModel(0.5F), new VRArmorModel(1.0F));
this.addLayer(layer);
((VRPlayerModel)this.entityModel).armor = layer;
this.addLayer(new HeldItemLayer<>(this));
this.addLayer(new ArrowLayer<>(this));
// this.addLayer(new Deadmau5HeadLayer(this));
// this.addLayer(new CapeLayer(this));
this.addLayer(new HeadLayer<>(this));
this.addLayer(new ElytraLayer<>(this));
// this.addLayer(new ParrotVariantLayer<>(this));
// this.addLayer(new SpinAttackEffectLayer<>(this));
}
public void doRender(AbstractClientPlayerEntity entity, double x, double y, double z, float entityYaw, float partialTicks)
{
if (!entity.isUser() || this.renderManager.info.getRenderViewEntity() == entity)
{
double d0 = y;
if (entity.shouldRenderSneaking())
{
d0 = y - 0.125D;
}
if(entity.isUser()){
Vec3d offset=new Vec3d(0,0,0);
float yaw= Minecraft.getInstance().vrPlayer.vrdata_world_render.hmd.getYaw();
offset = new Quaternion(0,-yaw,0).multiply(offset);
x+=offset.x;
y+=offset.y;
z+=offset.z;
}
this.setModelVisibilities(entity);
GlStateManager.setProfile(GlStateManager.Profile.PLAYER_SKIN);
super.doRender(entity, x, d0, z, entityYaw, partialTicks);
GlStateManager.unsetProfile(GlStateManager.Profile.PLAYER_SKIN);
}
}
@Override
public float prepareScale(AbstractClientPlayerEntity entitylivingbaseIn, float partialTicks)
{
GlStateManager.enableRescaleNormal();
GlStateManager.scalef(-1.0F, -1.0F, 1.0F);
this.preRenderCallback(entitylivingbaseIn, partialTicks);
float f = 0.0625F;
PlayerModelController.RotInfo rotInfo = PlayerModelController.getInstance().getRotationsForPlayer(((PlayerEntity)entitylivingbaseIn).getUniqueID());
if(rotInfo != null) {
// f *= rotInfo.heightScale;
GlStateManager.translatef(0.0F, -1.501F *rotInfo.heightScale , 0.0F); //keep?
return f;
} else {
//magical mystical bullshit
GlStateManager.translatef(0.0F, -1.501F, 0.0F);
return f;
}
}
private void setModelVisibilities(AbstractClientPlayerEntity clientPlayer)
{
VRPlayerModel<AbstractClientPlayerEntity> playermodel = this.getEntityModel();
if (clientPlayer.isSpectator())
{
playermodel.setVisible(false);
playermodel.bipedHead.showModel = true;
playermodel.bipedHeadwear.showModel = true;
}
else
{
ItemStack itemstack = clientPlayer.getHeldItemMainhand();
ItemStack itemstack1 = clientPlayer.getHeldItemOffhand();
playermodel.setVisible(true);
playermodel.bipedHeadwear.showModel = clientPlayer.isWearing(PlayerModelPart.HAT);
playermodel.bipedBodyWear.showModel = clientPlayer.isWearing(PlayerModelPart.JACKET);
playermodel.bipedLeftLegwear.showModel = clientPlayer.isWearing(PlayerModelPart.LEFT_PANTS_LEG);
playermodel.bipedRightLegwear.showModel = clientPlayer.isWearing(PlayerModelPart.RIGHT_PANTS_LEG);
playermodel.bipedLeftArmwear.showModel = clientPlayer.isWearing(PlayerModelPart.LEFT_SLEEVE);
playermodel.bipedRightArmwear.showModel = clientPlayer.isWearing(PlayerModelPart.RIGHT_SLEEVE);
playermodel.isSneak = clientPlayer.shouldRenderSneaking();
BipedModel.ArmPose bipedmodel$armpose = this.func_217766_a(clientPlayer, itemstack, itemstack1, Hand.MAIN_HAND);
BipedModel.ArmPose bipedmodel$armpose1 = this.func_217766_a(clientPlayer, itemstack, itemstack1, Hand.OFF_HAND);
if (clientPlayer.getPrimaryHand() == HandSide.RIGHT)
{
playermodel.rightArmPose = bipedmodel$armpose;
playermodel.leftArmPose = bipedmodel$armpose1;
}
else
{
playermodel.rightArmPose = bipedmodel$armpose1;
playermodel.leftArmPose = bipedmodel$armpose;
}
}
}
private BipedModel.ArmPose func_217766_a(AbstractClientPlayerEntity p_217766_1_, ItemStack p_217766_2_, ItemStack p_217766_3_, Hand p_217766_4_)
{
BipedModel.ArmPose bipedmodel$armpose = BipedModel.ArmPose.EMPTY;
ItemStack itemstack = p_217766_4_ == Hand.MAIN_HAND ? p_217766_2_ : p_217766_3_;
if (!itemstack.isEmpty())
{
bipedmodel$armpose = BipedModel.ArmPose.ITEM;
if (p_217766_1_.getItemInUseCount() > 0)
{
UseAction useaction = itemstack.getUseAction();
if (useaction == UseAction.BLOCK)
{
bipedmodel$armpose = BipedModel.ArmPose.BLOCK;
}
else if (useaction == UseAction.BOW)
{
bipedmodel$armpose = BipedModel.ArmPose.BOW_AND_ARROW;
}
else if (useaction == UseAction.SPEAR)
{
bipedmodel$armpose = BipedModel.ArmPose.THROW_SPEAR;
}
else if (useaction == UseAction.CROSSBOW && p_217766_4_ == p_217766_1_.getActiveHand())
{
bipedmodel$armpose = BipedModel.ArmPose.CROSSBOW_CHARGE;
}
}
else
{
boolean flag3 = p_217766_2_.getItem() == Items.CROSSBOW;
boolean flag = CrossbowItem.isCharged(p_217766_2_);
boolean flag1 = p_217766_3_.getItem() == Items.CROSSBOW;
boolean flag2 = CrossbowItem.isCharged(p_217766_3_);
if (flag3 && flag)
{
bipedmodel$armpose = BipedModel.ArmPose.CROSSBOW_HOLD;
}
if (flag1 && flag2 && p_217766_2_.getItem().getUseAction(p_217766_2_) == UseAction.NONE)
{
bipedmodel$armpose = BipedModel.ArmPose.CROSSBOW_HOLD;
}
}
}
return bipedmodel$armpose;
}
public ResourceLocation getEntityTexture(AbstractClientPlayerEntity entity)
{
return entity.getLocationSkin();
}
protected void preRenderCallback(AbstractClientPlayerEntity entitylivingbaseIn, float partialTickTime)
{
float f = 0.9375F;
GlStateManager.scalef(0.9375F, 0.9375F, 0.9375F);
}
protected void renderEntityName(AbstractClientPlayerEntity entityIn, double x, double y, double z, String name, double distanceSq)
{
if (distanceSq < 100.0D)
{
Scoreboard scoreboard = entityIn.getWorldScoreboard();
ScoreObjective scoreobjective = scoreboard.getObjectiveInDisplaySlot(2);
if (scoreobjective != null)
{
Score score = scoreboard.getOrCreateScore(entityIn.getScoreboardName(), scoreobjective);
this.renderLivingLabel(entityIn, score.getScorePoints() + " " + scoreobjective.getDisplayName().getFormattedText(), x, y, z, 64);
y += (double)(9.0F * 1.15F * 0.025F);
}
}
super.renderEntityName(entityIn, x, y, z, name, distanceSq);
}
public void renderRightArm(AbstractClientPlayerEntity clientPlayer)
{
float f = 1.0F;
GlStateManager.color3f(1.0F, 1.0F, 1.0F);
float f1 = 0.0625F;
VRPlayerModel<AbstractClientPlayerEntity> playermodel = this.getEntityModel();
this.setModelVisibilities(clientPlayer);
GlStateManager.enableBlend();
playermodel.swingProgress = 0.0F;
playermodel.isSneak = false;
playermodel.swimAnimation = 0.0F;
playermodel.setRotationAngles(clientPlayer, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F);
playermodel.bipedRightArm.rotateAngleX = 0.0F;
playermodel.bipedRightArm.render(0.0625F);
playermodel.bipedRightArmwear.rotateAngleX = 0.0F;
playermodel.bipedRightArmwear.render(0.0625F);
GlStateManager.disableBlend();
}
public void renderLeftArm(AbstractClientPlayerEntity clientPlayer)
{
float f = 1.0F;
GlStateManager.color3f(1.0F, 1.0F, 1.0F);
float f1 = 0.0625F;
VRPlayerModel<AbstractClientPlayerEntity> playermodel = this.getEntityModel();
this.setModelVisibilities(clientPlayer);
GlStateManager.enableBlend();
playermodel.isSneak = false;
playermodel.swingProgress = 0.0F;
playermodel.swimAnimation = 0.0F;
playermodel.setRotationAngles(clientPlayer, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F);
playermodel.bipedLeftArm.rotateAngleX = 0.0F;
playermodel.bipedLeftArm.render(0.0625F);
playermodel.bipedLeftArmwear.rotateAngleX = 0.0F;
playermodel.bipedLeftArmwear.render(0.0625F);
GlStateManager.disableBlend();
}
protected void applyRotations(AbstractClientPlayerEntity entityLiving, float ageInTicks, float rotationYaw, float partialTicks)
{
float f = entityLiving.getSwimAnimation(partialTicks);
if (entityLiving.isElytraFlying())
{
super.applyRotations(entityLiving, ageInTicks, rotationYaw, partialTicks);
float f1 = (float)entityLiving.getTicksElytraFlying() + partialTicks;
float f2 = MathHelper.clamp(f1 * f1 / 100.0F, 0.0F, 1.0F);
if (!entityLiving.isSpinAttacking())
{
GlStateManager.rotatef(f2 * (-90.0F - entityLiving.rotationPitch), 1.0F, 0.0F, 0.0F);
}
Vec3d vec3d = entityLiving.getLook(partialTicks);
Vec3d vec3d1 = entityLiving.getMotion();
double d0 = Entity.func_213296_b(vec3d1);
double d1 = Entity.func_213296_b(vec3d);
if (d0 > 0.0D && d1 > 0.0D)
{
double d2 = (vec3d1.x * vec3d.x + vec3d1.z * vec3d.z) / (Math.sqrt(d0) * Math.sqrt(d1));
double d3 = vec3d1.x * vec3d.z - vec3d1.z * vec3d.x;
GlStateManager.rotatef((float)(Math.signum(d3) * Math.acos(d2)) * 180.0F / (float)Math.PI, 0.0F, 1.0F, 0.0F);
}
}
else if (f > 0.0F)
{
super.applyRotations(entityLiving, ageInTicks, rotationYaw, partialTicks);
float f3 = entityLiving.isInWater() ? -90.0F - entityLiving.rotationPitch : -90.0F;
float f4 = MathHelper.lerp(f, 0.0F, f3);
GlStateManager.rotatef(f4, 1.0F, 0.0F, 0.0F);
if (entityLiving.func_213314_bj())
{
GlStateManager.translatef(0.0F, -1.0F, 0.3F);
}
}
else
{
super.applyRotations(entityLiving, ageInTicks, rotationYaw, partialTicks);
}
}
}
| 42.337621 | 153 | 0.656414 |
dc2aadb4b517989e6b17d591aabaf5791c470238 | 6,489 | /*
* Copyright 1999-2017 Alibaba Group.
*
* 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.alibaba.p3c.pmd.lang.java.rule.oop;
import java.util.List;
import com.alibaba.p3c.pmd.lang.java.rule.AbstractAliRule;
import com.alibaba.p3c.pmd.lang.java.rule.util.NodeUtils;
import com.alibaba.p3c.pmd.lang.java.util.StringAndCharConstants;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTName;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
import net.sourceforge.pmd.lang.java.ast.AbstractJavaNode;
import net.sourceforge.pmd.lang.java.ast.Token;
import org.jaxen.JaxenException;
/**
* [Mandatory] Since NullPointerException can possibly be thrown while calling the equals method of Object,
* equals should be invoked by a constant or an object that is definitely not null.
*
* @author zenghou.fw
* @date 2016/11/29
*/
public class EqualsAvoidNullRule extends AbstractAliRule {
private static final String XPATH = "//PrimaryExpression[" + "(PrimaryPrefix[Name[(ends-with(@Image, '.equals'))]]|"
+ "PrimarySuffix[@Image='equals'])"
+ "[(../PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression/PrimaryPrefix) and "
+ "( count(../PrimarySuffix/Arguments/ArgumentList/Expression) = 1 )]]"
+ "[not(ancestor::Expression/ConditionalAndExpression//EqualityExpression[@Image='!=']//NullLiteral)]"
+ "[not(ancestor::Expression/ConditionalOrExpression//EqualityExpression[@Image='==']//NullLiteral)]";
private static final String INVOCATION_PREFIX_XPATH
= "PrimarySuffix/Arguments/ArgumentList/Expression/PrimaryExpression[not(PrimarySuffix)]/PrimaryPrefix";
private static final String METHOD_EQUALS = "equals";
@Override
public Object visit(ASTCompilationUnit node, Object data) {
try {
List<Node> equalsInvocations = node.findChildNodesWithXPath(XPATH);
if (equalsInvocations == null || equalsInvocations.isEmpty()) {
return super.visit(node, data);
}
for (Node invocation : equalsInvocations) {
// https://github.com/alibaba/p3c/issues/471
if (callerIsLiteral(invocation)) {
return super.visit(node, data);
}
// if arguments of equals is complicate expression, skip the check
List<? extends Node> simpleExpressions = invocation.findChildNodesWithXPath(INVOCATION_PREFIX_XPATH);
if (simpleExpressions == null || simpleExpressions.isEmpty()) {
return super.visit(node, data);
}
ASTPrimaryPrefix right = (ASTPrimaryPrefix)simpleExpressions.get(0);
if (right.getFirstChildOfType(ASTLiteral.class) != null) {
ASTLiteral literal = right.getFirstChildOfType(ASTLiteral.class);
if (literal.isStringLiteral()) {
// other literals has no equals method, can not be flipped
addRuleViolation(data, invocation);
}
} else {
ASTName name = right.getFirstChildOfType(ASTName.class);
// TODO works only in current compilation file, by crossing files will be null
boolean nameInvalid = name == null || name.getNameDeclaration() == null
|| name.getNameDeclaration().getNode() == null;
if (nameInvalid) {
return super.visit(node, data);
}
Node nameNode = name.getNameDeclaration().getNode();
if ((nameNode instanceof ASTVariableDeclaratorId) && (nameNode.getNthParent(
2) instanceof ASTFieldDeclaration)) {
ASTFieldDeclaration field = (ASTFieldDeclaration)nameNode.getNthParent(2);
if (NodeUtils.isConstant(field)) {
addRuleViolation(data, invocation);
}
}
}
}
} catch (JaxenException e) {
throw new RuntimeException("XPath expression " + XPATH + " failed: " + e.getLocalizedMessage(), e);
}
return super.visit(node, data);
}
private boolean callerIsLiteral(Node equalsInvocation) {
if (equalsInvocation instanceof ASTPrimaryExpression) {
ASTPrimaryPrefix caller = equalsInvocation.getFirstChildOfType(ASTPrimaryPrefix.class);
return caller != null && caller.getFirstChildOfType(ASTLiteral.class) != null;
}
return false;
}
private String getInvocationName(AbstractJavaNode javaNode) {
Token token = (Token)javaNode.jjtGetFirstToken();
StringBuilder sb = new StringBuilder(token.image).append(token.image);
while (token.next != null && token.next.image != null && !METHOD_EQUALS.equals(token.next.image)) {
token = token.next;
sb.append(token.image);
}
if (sb.charAt(sb.length() - 1) == StringAndCharConstants.DOT) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
private void addRuleViolation(Object data, Node invocation) {
if (invocation instanceof AbstractJavaNode) {
AbstractJavaNode javaNode = (AbstractJavaNode)invocation;
addViolationWithMessage(data, invocation, "java.oop.EqualsAvoidNullRule.violation.msg",
new Object[] {getInvocationName(javaNode)});
} else {
addViolation(data, invocation);
}
}
}
| 47.021739 | 120 | 0.646479 |
3e0af96876ed12d35df7e00bee260db44d24f1ef | 720 | package com.larksuite.appframework.sdk.core.protocol.client.calendar;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.larksuite.appframework.sdk.core.protocol.BaseResponse;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@Data
public class AttendeesResponse extends BaseResponse {
private List<Data> data;
@Getter
@Setter
@ToString
public static class Data {
@JsonProperty("open_id")
private String openId;
@JsonProperty("employee_id")
private String employeeId;
@JsonProperty("display_name")
private String displayName;
private Boolean optional;
}
}
| 21.176471 | 69 | 0.720833 |
7c1e6683dc40a6c37db5cf14aa7eeb450ad07f92 | 9,938 | /**
*
* Copyright the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.advisoryapps.smackx.bytestreams.socks5;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import org.junit.Test;
/**
* Test for Socks5Proxy class.
*
* @author Henning Staib
*/
public class Socks5ProxyTest {
private static final String loopbackAddress = InetAddress.getLoopbackAddress().getHostAddress();
/**
* The SOCKS5 proxy should be a quasi singleton used by all XMPP connections.
*/
@Test
public void shouldBeAQuasiSingleton() {
Socks5Proxy proxy1 = Socks5Proxy.getSocks5Proxy();
Socks5Proxy proxy2 = Socks5Proxy.getSocks5Proxy();
assertNotNull(proxy1);
assertNotNull(proxy2);
assertSame(proxy1, proxy2);
}
/**
* The SOCKS5 proxy should use a free port above the one configured.
*
* @throws Exception should not happen
*/
@Test
public void shouldUseFreePortOnNegativeValues() throws Exception {
Socks5Proxy proxy = new Socks5Proxy();
assertFalse(proxy.isRunning());
try (ServerSocket serverSocket = new ServerSocket(0)) {
proxy.setLocalSocks5ProxyPort(-serverSocket.getLocalPort());
proxy.start();
assertTrue(proxy.isRunning());
assertTrue(proxy.getPort() > serverSocket.getLocalPort());
} finally {
proxy.stop();
}
}
/**
* When inserting new network addresses to the proxy the order should remain in the order they
* were inserted.
*
* @throws UnknownHostException
*/
@Test
public void shouldPreserveAddressOrderOnInsertions() throws UnknownHostException {
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
LinkedHashSet<InetAddress> addresses = new LinkedHashSet<>(proxy.getLocalAddresses());
for (int i = 1 ; i <= 3; i++) {
addresses.add(InetAddress.getByName(Integer.toString(i)));
}
for (InetAddress address : addresses) {
proxy.addLocalAddress(address);
}
List<InetAddress> localAddresses = proxy.getLocalAddresses();
Iterator<InetAddress> iterator = addresses.iterator();
for (int i = 0; i < addresses.size(); i++) {
assertEquals(iterator.next(), localAddresses.get(i));
}
}
/**
* When replacing network addresses of the proxy the order should remain in the order if the
* given list.
*
* @throws UnknownHostException
*/
@Test
public void shouldPreserveAddressOrderOnReplace() throws UnknownHostException {
Socks5Proxy proxy = Socks5Proxy.getSocks5Proxy();
List<InetAddress> addresses = new ArrayList<>(proxy.getLocalAddresses());
addresses.add(InetAddress.getByName("1"));
addresses.add(InetAddress.getByName("2"));
addresses.add(InetAddress.getByName("3"));
proxy.replaceLocalAddresses(addresses);
List<InetAddress> localAddresses = proxy.getLocalAddresses();
for (int i = 0; i < addresses.size(); i++) {
assertEquals(addresses.get(i), localAddresses.get(i));
}
}
/**
* If the SOCKS5 proxy accepts a connection that is not a SOCKS5 connection it should close the
* corresponding socket.
*
* @throws Exception should not happen
*/
@Test
public void shouldCloseSocketIfNoSocks5Request() throws Exception {
Socks5Proxy proxy = new Socks5Proxy();
proxy.start();
try (Socket socket = new Socket(loopbackAddress, proxy.getPort())) {
OutputStream out = socket.getOutputStream();
out.write(new byte[] { 1, 2, 3 });
int res;
try {
res = socket.getInputStream().read();
} catch (SocketException e) {
res = -1;
}
assertEquals(-1, res);
} finally {
proxy.stop();
}
}
/**
* The SOCKS5 proxy should reply with an error message if no supported authentication methods
* are given in the SOCKS5 request.
*
* @throws Exception should not happen
*/
@Test
public void shouldRespondWithErrorIfNoSupportedAuthenticationMethod() throws Exception {
Socks5Proxy proxy = new Socks5Proxy();
proxy.start();
try (Socket socket = new Socket(loopbackAddress, proxy.getPort())) {
OutputStream out = socket.getOutputStream();
// request username/password-authentication
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x02 });
InputStream in = socket.getInputStream();
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0xFF, (byte) in.read());
assertEquals(-1, in.read());
} finally {
proxy.stop();
}
}
/**
* The SOCKS5 proxy should respond with an error message if the client is not allowed to connect
* with the proxy.
*
* @throws Exception should not happen
*/
@Test
public void shouldRespondWithErrorIfConnectionIsNotAllowed() throws Exception {
Socks5Proxy proxy = new Socks5Proxy();
proxy.start();
try (Socket socket = new Socket(loopbackAddress, proxy.getPort())) {
OutputStream out = socket.getOutputStream();
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x00 });
InputStream in = socket.getInputStream();
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
// send valid SOCKS5 message
out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0xAA,
(byte) 0x00, (byte) 0x00 });
// verify error message
assertEquals((byte) 0x05, (byte) in.read());
assertFalse((byte) 0x00 == (byte) in.read()); // something other than 0 == success
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x03, (byte) in.read());
assertEquals((byte) 0x01, (byte) in.read());
assertEquals((byte) 0xAA, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
assertEquals(-1, in.read());
} finally {
proxy.stop();
}
}
/**
* A Client should successfully establish a connection to the SOCKS5 proxy.
*
* @throws Exception should not happen
*/
@Test
public void shouldSuccessfullyEstablishConnection() throws Exception {
Socks5Proxy proxy = new Socks5Proxy();
proxy.start();
try {
assertTrue(proxy.isRunning());
String digest = new String(new byte[] { (byte) 0xAA }, StandardCharsets.UTF_8);
// add digest to allow connection
proxy.addTransfer(digest);
@SuppressWarnings("resource")
Socket socket = new Socket(loopbackAddress, proxy.getPort());
OutputStream out = socket.getOutputStream();
out.write(new byte[] { (byte) 0x05, (byte) 0x01, (byte) 0x00 });
InputStream in = socket.getInputStream();
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
// send valid SOCKS5 message
out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x01, (byte) 0xAA,
(byte) 0x00, (byte) 0x00 });
// verify response
assertEquals((byte) 0x05, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read()); // success
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x03, (byte) in.read());
assertEquals((byte) 0x01, (byte) in.read());
assertEquals((byte) 0xAA, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
assertEquals((byte) 0x00, (byte) in.read());
Socket remoteSocket = proxy.getSocket(digest);
try {
// remove digest
proxy.removeTransfer(digest);
// test stream
OutputStream remoteOut = remoteSocket.getOutputStream();
byte[] data = new byte[] { 1, 2, 3, 4, 5 };
remoteOut.write(data);
remoteOut.flush();
for (int i = 0; i < data.length; i++) {
assertEquals(data[i], in.read());
}
} finally {
remoteSocket.close();
}
assertEquals(-1, in.read());
} finally {
proxy.stop();
}
}
}
| 33.348993 | 112 | 0.600221 |
7c16a66691ed265bb8830bfa0515cafec61f64f7 | 85 | package ontoplay.models.ontologyModel;
public enum XsdType {
String, Integer
}
| 12.142857 | 38 | 0.752941 |
04809293e02f58a8fc2134c0ed9735e3b38c4463 | 2,831 | package com.guiigos.androidhelpers.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.guiigos.androidhelpers.R;
import com.guiigos.androidhelpers.dao.AlunoDao;
import com.guiigos.androidhelpers.helper.FormularioHelper;
import com.guiigos.androidhelpers.model.Aluno;
public class FormularioActivity
extends AppCompatActivity
implements View.OnClickListener {
private FormularioHelper fh;
private AlunoDao ad;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formulario);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fh = new FormularioHelper(this);
ad = new AlunoDao(this);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(intent.hasExtra("aluno")){
Aluno aluno = (Aluno)bundle.getSerializable("aluno");
fh.PreencheAluno(aluno);
}
if(intent.hasExtra("telefone")){
String celular = bundle.getString("telefone", "");
String corpo = bundle.getString("corpo", "");
Aluno aluno = new Aluno();
aluno.setNome(corpo);
aluno.setTelefone(celular);
Log.d("SMS_receiver", "Chegou - " + celular + " - " + corpo);
fh.PreencheAluno(aluno);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.fab:
Toast.makeText(this, "Botão gravar.", Toast.LENGTH_SHORT).show();
Aluno aluno = fh.PegaAluno();
if(aluno.getId() != 0) ad.alterar(aluno);
else ad.insere(aluno);
metodoVoltar();
break;
case R.id.fab_voltar:
Snackbar.make(v, "Botão voltar.", Snackbar.LENGTH_SHORT).setAction("Action", null).show();
metodoVoltar();
break;
}
}
@Override
public void onBackPressed() {
Snackbar.make(toolbar, "Utilize o botão voltar!", Snackbar.LENGTH_SHORT).setAction("Action", null).show();
}
@Override
protected void onDestroy() {
ad.close();
super.onDestroy();
}
public void metodoVoltar(){
Intent itVoltar = new Intent(FormularioActivity.this, MainActivity.class);
startActivity(itVoltar);
finish();
}
}
| 29.489583 | 115 | 0.599082 |
035d8c24fe9d34b1c728135223eda18b34a9e95b | 1,695 | /*
* Copyright 2015-2018 Canoo Engineering AG.
*
* 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.canoo.dp.impl.server.gc;
import com.canoo.platform.remoting.ObservableList;
import com.canoo.platform.remoting.RemotingBean;
import org.apiguardian.api.API;
import static org.apiguardian.api.API.Status.INTERNAL;
/**
* A {@link Reference} that is defined by a {@link ObservableList}.
* Example for such a reference: Dolphin bean A contains a {@link ObservableList} that contains dolphin bean B
* For more information see {@link Reference} and {@link RemotingBean}
*/
@API(since = "0.x", status = INTERNAL)
public class ListReference extends Reference {
private ObservableList list;
/**
* Constructor
* @param parent the dolphin bean that contains the {@link ObservableList}
* @param list the list
* @param child the dolphin bean that is part of the list
*/
public ListReference(Instance parent, ObservableList list, Instance child) {
super(parent, child);
this.list = list;
}
/**
* Returns the list
* @return the list
*/
public ObservableList getList() {
return list;
}
}
| 31.981132 | 110 | 0.707375 |
6322f5f8492f68422a0f8b866ee6d6738ea31ecf | 352 | package org.firstinspires.ftc.robotcontroller.internal.WebInterface.JsonPackets;
import java.util.HashMap;
public class VariablesPacket {
int opcode = 3;
public String[] numVarNames;
public Double[] numVars;
public String[] boolVarsNames;
public Boolean[] boolVars;
public String[] strVarNames;
public String[] strVars;
}
| 25.142857 | 80 | 0.735795 |
9e27467f87f7383d5a9e6e1e3b1798d518f7152f | 422 | package com.webkreator.qlue.example_app.pages.packageRouter.subfolder;
import com.webkreator.qlue.Page;
import com.webkreator.qlue.view.View;
import java.io.IOException;
public class index extends Page {
@Override
public View onGet() throws IOException {
context.response.setContentType("text/plain");
context.response.getWriter().write("packageRouter/subfolder");
return null;
}
}
| 24.823529 | 70 | 0.732227 |
dfb38fb2466c8d45c39b54b74ea5c8089cfb0167 | 2,909 | /*
* Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package vm.mlvm.share.jdi;
import java.util.List;
import vm.mlvm.share.jpda.StratumInfo;
import com.sun.jdi.request.BreakpointRequest;
public class BreakpointInfo {
public static enum Type {
/** set breakpoint via BreakpointRequest */
EXPLICIT,
/**
* don't set JDI breakpoint, verify that we can reach the location
* via stepping
*/
IMPLICIT
};
// Initial information
public Type type = Type.EXPLICIT;
public String className = "";
public final String methodName;
public int methodLine = 0;
/** Breakpoint stratum (JSR-045). null == default stratum */
public StratumInfo stratumInfo = null;
/**
* How many times this breakpoint should be hit. null == any number of
* hits
*/
public Integer requiredHits = null;
/** How many steps do via StepRequest after reaching the breakpoint */
public int stepsToTrace = 0;
/** Conditional breakpoints should not be enabled by default */
public final boolean isConditional;
/** Sub-breakpoints */
public List<BreakpointInfo> subBreakpoints = null;
// Fields below are filled in by debugger
public long bci = -1;
public BreakpointRequest bpReq = null;
public int hits = 0;
public BreakpointInfo(String methodName) {
this(methodName, false);
}
public BreakpointInfo(String methodName, boolean isConditional) {
this.methodName = methodName;
this.isConditional = isConditional;
}
public boolean isHit() {
if (requiredHits == null) {
return hits > 0;
} else {
return hits == requiredHits;
}
}
@Override
public String toString() {
return className + "." + methodName + ":" + methodLine + "[bci=" + bci + ",bp=" + bpReq + "]";
}
}
| 30.621053 | 102 | 0.668615 |
0f394541dd4ea869cddc3eef05956ba6f9ce1dea | 4,326 | //
// This file is auto-generated. Please don't modify it!
//
package org.opencv.xfeatures2d;
import org.opencv.core.Mat;
import org.opencv.features2d.Feature2D;
import org.opencv.xfeatures2d.DAISY;
// C++: class DAISY
//javadoc: DAISY
public class DAISY extends Feature2D {
protected DAISY(long addr) { super(addr); }
// internal usage only
public static DAISY __fromPtr__(long addr) { return new DAISY(addr); }
// C++: enum NormalizationType
public static final int
NRM_NONE = 100,
NRM_PARTIAL = 101,
NRM_FULL = 102,
NRM_SIFT = 103;
//
// C++: static Ptr_DAISY cv::xfeatures2d::DAISY::create(float radius = 15, int q_radius = 3, int q_theta = 8, int q_hist = 8, DAISY_NormalizationType norm = DAISY::NRM_NONE, Mat H = Mat(), bool interpolation = true, bool use_orientation = false)
//
//javadoc: DAISY::create(radius, q_radius, q_theta, q_hist, H, interpolation, use_orientation)
public static DAISY create(float radius, int q_radius, int q_theta, int q_hist, Mat H, boolean interpolation, boolean use_orientation)
{
DAISY retVal = DAISY.__fromPtr__(create_0(radius, q_radius, q_theta, q_hist, H.nativeObj, interpolation, use_orientation));
return retVal;
}
//javadoc: DAISY::create(radius, q_radius, q_theta, q_hist, H, interpolation)
public static DAISY create(float radius, int q_radius, int q_theta, int q_hist, Mat H, boolean interpolation)
{
DAISY retVal = DAISY.__fromPtr__(create_1(radius, q_radius, q_theta, q_hist, H.nativeObj, interpolation));
return retVal;
}
//javadoc: DAISY::create(radius, q_radius, q_theta, q_hist, H)
public static DAISY create(float radius, int q_radius, int q_theta, int q_hist, Mat H)
{
DAISY retVal = DAISY.__fromPtr__(create_2(radius, q_radius, q_theta, q_hist, H.nativeObj));
return retVal;
}
//javadoc: DAISY::create(radius, q_radius, q_theta, q_hist)
public static DAISY create(float radius, int q_radius, int q_theta, int q_hist)
{
DAISY retVal = DAISY.__fromPtr__(create_3(radius, q_radius, q_theta, q_hist));
return retVal;
}
//javadoc: DAISY::create(radius, q_radius, q_theta)
public static DAISY create(float radius, int q_radius, int q_theta)
{
DAISY retVal = DAISY.__fromPtr__(create_5(radius, q_radius, q_theta));
return retVal;
}
//javadoc: DAISY::create(radius, q_radius)
public static DAISY create(float radius, int q_radius)
{
DAISY retVal = DAISY.__fromPtr__(create_6(radius, q_radius));
return retVal;
}
//javadoc: DAISY::create(radius)
public static DAISY create(float radius)
{
DAISY retVal = DAISY.__fromPtr__(create_7(radius));
return retVal;
}
//javadoc: DAISY::create()
public static DAISY create()
{
DAISY retVal = DAISY.__fromPtr__(create_8());
return retVal;
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: static Ptr_DAISY cv::xfeatures2d::DAISY::create(float radius = 15, int q_radius = 3, int q_theta = 8, int q_hist = 8, DAISY_NormalizationType norm = DAISY::NRM_NONE, Mat H = Mat(), bool interpolation = true, bool use_orientation = false)
private static native long create_0(float radius, int q_radius, int q_theta, int q_hist, long H_nativeObj, boolean interpolation, boolean use_orientation);
private static native long create_1(float radius, int q_radius, int q_theta, int q_hist, long H_nativeObj, boolean interpolation);
private static native long create_2(float radius, int q_radius, int q_theta, int q_hist, long H_nativeObj);
private static native long create_3(float radius, int q_radius, int q_theta, int q_hist);
private static native long create_5(float radius, int q_radius, int q_theta);
private static native long create_6(float radius, int q_radius);
private static native long create_7(float radius);
private static native long create_8();
// native support for java finalize()
private static native void delete(long nativeObj);
}
| 34.333333 | 249 | 0.668054 |
1185cc43d77f377b98c1426b4db305bfb5726911 | 908 | package io.schinzel.basicutils.state;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.experimental.Accessors;
/**
* The purpose of this class is to optionally add a unit to a property.
*/
@Accessors(prefix = "m")
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class PropUnit {
private StateBuilder mStateBuilder;
private String mKey;
private String mValAsString;
private Object mValAsObject;
/**
* Adds a unit to a property.
*
* @param unit The unit to add.
* @return A builder for the property.
*/
public PropertyBuilder unit(String unit) {
return new PropertyBuilder(mStateBuilder, mKey, mValAsString, mValAsObject, unit);
}
/**
* Builds the property.
*
* @return The state builder
*/
public StateBuilder buildProp() {
return this.unit("").buildProp();
}
}
| 21.619048 | 90 | 0.670705 |
a651454818d81cdee7e4f55c5c32b896ab917289 | 1,685 | /*
* Copyright 2016 incode.org
*
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.incode.module.document.dom.impl.types;
import java.util.List;
import javax.inject.Inject;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.Mixin;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.incode.module.document.dom.impl.docs.DocumentTemplate;
import org.incode.module.document.dom.impl.docs.DocumentTemplateRepository;
@Mixin
public class DocumentType_currentTemplates {
//region > constructor
private final DocumentType documentType;
public DocumentType_currentTemplates(final DocumentType documentType) {
this.documentType = documentType;
}
//endregion
@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(contributed = Contributed.AS_ASSOCIATION)
public List<DocumentTemplate> $$() {
return documentTemplateRepository.findByType(documentType);
}
@Inject
DocumentTemplateRepository documentTemplateRepository;
}
| 30.089286 | 75 | 0.758457 |
d150358ee414f31bddc86833886c4e6d625fae23 | 675 | package com.leyou.common.exception;
import lombok.Getter;
/**
* @author Leslie Arnoald
*/
@Getter
public class LyException extends RuntimeException {
/**
* 异常状态码信息
*/
private int status;
public LyException(int status) {
this.status = status;
}
public LyException(int status, String message) {
super(message);
this.status = status;
}
//Throwable是所有异常的顶级父类
public LyException(int status, String message, Throwable cause) {
super(message, cause);
this.status = status;
}
public LyException(int status, Throwable cause) {
super(cause);
this.status = status;
}
} | 19.852941 | 69 | 0.623704 |
ae8fa2bed5dbacfdf5de08da48abe5364247d800 | 3,847 | package com.github.mforoni.jspreadsheet;
import java.util.Date;
import javax.annotation.Nullable;
import org.joda.time.DateTime;
/**
* @author Foroni Marco
*/
abstract class AbstractSheet implements Sheet {
@Override
public int getLastRow() {
int rowIndex = getRows();
for (; rowIndex > 0; rowIndex--) {
final int lastColumn = getLastColumn(rowIndex - 1);
if (lastColumn != 0) {
return rowIndex;
}
}
return 0;
}
@Override
public Object[] getRow(final int rowIndex, final int fromColumn, final int toColumn) {
final int size = toColumn - fromColumn + 1;
final Object[] values = new Object[size];
for (int c = 0; c < size; c++) {
values[c] = getObject(rowIndex, c + fromColumn);
}
return values;
}
@Override
public Object[] getRow(final int rowIndex) {
return getRow(rowIndex, 0, getColumns() - 1);
}
@Override
public void setAutoSize() {
setAutoSize(0, getColumns());
}
@Override
public void setObject(final int rowIndex, final int columnIndex, @Nullable final Object value) {
setObject(rowIndex, columnIndex, value, null);
}
@Override
public void setObject(final int rowIndex, final int columnIndex, @Nullable final Object value,
@Nullable final SSCellFormat cellFormat) {
if (value != null) {
if (value instanceof String) {
setString(rowIndex, columnIndex, (String) value, cellFormat);
} else if (value instanceof Number) {
setDouble(rowIndex, columnIndex, ((Number) value).doubleValue(), cellFormat);
} else if (value instanceof Date) {
setDate(rowIndex, columnIndex, (Date) value, cellFormat);
} else if (value instanceof DateTime) {
final DateTime dateTime = (DateTime) value;
setDate(rowIndex, columnIndex, dateTime.toDate(), cellFormat);
} else if (value instanceof Boolean) {
setBoolean(rowIndex, columnIndex, (Boolean) value, cellFormat);
} else {
throw new IllegalStateException(
String.format("Unable to set value having Type %s: case not handled.",
value.getClass().getSimpleName()));
}
}
}
@Override
public void setString(final int rowIndex, final int columnIndex, final String value) {
setString(rowIndex, columnIndex, value, null);
}
@Override
public void setDouble(final int rowIndex, final int columnIndex, final Double value) {
setDouble(rowIndex, columnIndex, value, null);
}
@Override
public void setDate(final int rowIndex, final int columnIndex, final Date value) {
setDate(rowIndex, columnIndex, value, null);
}
@Override
public void setBoolean(final int rowIndex, final int columnIndex, final Boolean value) {
setBoolean(rowIndex, columnIndex, value, null);
}
@Override
public void add(final int rowIndex, final int columnIndex, @Nullable final Double value) {
if (value != null) {
final Double d = getDouble(rowIndex, columnIndex);
final double sum = d != null ? d + value : value;
setDouble(rowIndex, columnIndex, sum);
}
}
@Override
public void setRow(final int rowIndex, final Object[] values) {
setRow(rowIndex, 0, values);
}
@Override
public void setRow(final int rowIndex, final Object[] values, final SSCellFormat cellFormat) {
setRow(rowIndex, 0, values, cellFormat);
}
@Override
public void setRow(final int rowIndex, final int columnOffset, final Object[] values) {
for (int c = 0; c < values.length; c++) {
setObject(rowIndex, columnOffset + c, values[c]);
}
}
@Override
public void setRow(final int rowIndex, final int columnOffset, final Object[] values,
final SSCellFormat cellFormat) {
for (int c = 0; c < values.length; c++) {
setObject(rowIndex, columnOffset + c, values[c], cellFormat);
}
}
}
| 30.776 | 98 | 0.667013 |
5b0a60c0e287da512b441ec2616e3b3d5ec60ee9 | 8,702 | /*
* Copyright 2013-2018 featherrun
*
* 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 running.database;
import running.core.Logger;
import running.core.Running;
import running.util.StringUtils;
import running.util.ZipUtils;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 数据库结构
*/
public class Struct {
protected Table[] tables = null;
public Table[] getTables() {
return tables;
}
public Table getTableByName(String name) {
for (Table t : tables) {
if (t.getName().equals(name)) {
return t;
}
}
return null;
}
public Map<String, List<Map<String, Object>>> toData() {
Map<String, List<Map<String, Object>>> dataMap = new HashMap<>();
for (Table t : tables) {
dataMap.put(t.getName(), t.toData());
}
return dataMap;
}
/**
* 从db.zip加载
* @param file
*/
public void load(String file) {
final ZipUtils zipUtils = Running.get(ZipUtils.class);
Map<String, String> textMap = zipUtils.read(file);
loadStruct(textMap);
loadValues(textMap);
}
protected void loadStruct(Map<String, String> textMap) {
List<Table> list = new ArrayList<>();
for (Map.Entry<String, String> entry : textMap.entrySet()) {
String name = entry.getKey();
if (name.contains(".sql")) {
Table t = new Table();
t.parseSql(entry.getValue());
list.add(t);
}
}
tables = list.toArray(new Table[list.size()]);
}
protected void loadValues(Map<String, String> textMap) {
for (Table t : tables) {
String name = t.getTableName() + ".txt";
if (textMap.containsKey(name)) {
t.parseData(textMap.get(name));
}
}
}
/**
* 从数据库加载
* @param db
*/
public void load(SimpleDb db) {
loadStruct(db);
loadValues(db);
}
public void loadStruct(SimpleDb db) {
Collection<String> tableNames = db.getStringList("SHOW TABLES");
List<Table> list = new ArrayList<>();
for (String tableName : tableNames) {
List<String[]> createSql = db.getStringArrayList("SHOW CREATE TABLE " + tableName);
String text = createSql.get(0)[1] + ";";
Table t = new Table();
t.parseSql(text);
list.add(t);
}
tables = list.toArray(new Table[list.size()]);
}
public void loadValues(SimpleDb db) {
if (tables == null) {
return;
}
for (Table t : tables) {
List<String[]> list = db.getStringArrayList("SELECT * FROM " + t.getTableName());
t.values = list.toArray(new String[list.size()][]);
}
}
/**
* 数据表
*/
public static class Table {
static final Pattern p1 = Pattern.compile("CREATE TABLE `([A-Za-z0-9_]+)` \\((.+)\\)([^;]+);");
static final Pattern p2 = Pattern.compile("`([A-Za-z0-9_]+)` ([a-z\\(\\)0-9]+).+COMMENT '(.+)'");
static final Pattern p3 = Pattern.compile("`([A-Za-z0-9_]+)` ([a-z\\(\\)0-9]+)");
static final Pattern p4 = Pattern.compile("PRIMARY KEY \\(`([A-Za-z0-9_]+)`\\)");
static final Pattern p5 = Pattern.compile("COMMENT='(.+)'");
public static final String s_col = "\t#\t";
public static final String s_row = "\n-\n";
public static final String s_row_win = "\r\n-\r\n";
protected String sql;
protected String tableName;
protected String tableComment;
protected Field[] fields;
protected String[][] values;
protected int fieldCount;
protected String primaryKey;
protected String primary;
protected String name;
public String getSql() {
return sql;
}
public String getTableName() {
return tableName;
}
public String getTableComment() {
return tableComment;
}
public String getPrimaryKey() {
return primaryKey;
}
public String getPrimary() {
return primary;
}
public String getName() {
return name;
}
public Field[] getFields() {
return fields;
}
public String[][] getValues() {
return values;
}
public List<Map<String, Object>> toData() {
List<Map<String, Object>> list = new ArrayList<>();
if (values != null) {
for (String[] line : values) {
Map<String, Object> map = new HashMap<>();
list.add(map);
int i = 0;
for (String val : line) {
Field f = fields[i];
i++;
if (f == null) break;
map.put(f.getName(), f.getValue(val));
}
}
}
return list;
}
/**
* 解析CREATE TABLE结构
*
* @param sql
*/
public void parseSql(String sql) {
this.sql = sql;
final StringUtils stringUtils = Running.get(StringUtils.class);
sql = sql.replaceAll("\\r\\n", "");
sql = sql.replaceAll("\\n", "");
Matcher m1 = p1.matcher(sql);
if (m1.find()) {
tableName = m1.group(1);
name = stringUtils.normalize(tableName, true);
tableComment = m1.group(3);
Matcher m5 = p5.matcher(tableComment);
if (m5.find()) {
tableComment = m5.group(1);
}
String fieldStr = m1.group(2);
String[] fieldArr = fieldStr.split(",");
fields = new Field[fieldArr.length];
fieldCount = 0;
for (String field : fieldArr) {
if (field.contains("KEY")) {
Matcher m4 = p4.matcher(field);
if (m4.find()) {
primaryKey = m4.group(1);
primary = stringUtils.normalize(primaryKey, false);
}
} else {
Field f = null;
Matcher m2 = p2.matcher(field);
if (m2.find()) {
f = new Field();
f.fieldName = m2.group(1);
f.fieldType = m2.group(2);
f.fieldComment = m2.group(3);
} else {
Matcher m3 = p3.matcher(field);
if (m3.find()) {
f = new Field();
f.fieldName = m3.group(1);
f.fieldType = m3.group(2);
}
}
if (f != null) {
f.name = stringUtils.normalize(f.fieldName, false);
fields[fieldCount] = f;
fieldCount++;
}
}
}
if (primaryKey == null) {
primaryKey = fields[0].fieldName;
primary = stringUtils.normalize(primaryKey, false);
final Logger logger = Running.getLogger(getClass());
logger.warn(tableName + ": unable to find the primary key, use `" + primaryKey + "` instead.");
}
}
}
/**
* 解析数据
*
* @param text
*/
public void parseData(String text) {
if (text.isEmpty())
return;
String[] lines = text.contains(s_row_win) ? text.split(s_row_win) : text.split(s_row);
values = new String[lines.length][];
int i = 0;
for (String line : lines) {
values[i] = line.split(s_col);
i++;
}
//如果解析的数据长度和字段长度不符,给以提示
if (values.length > 1 && values[1].length != fieldCount) {
final Logger logger = Running.getLogger(getClass());
logger.warn("DATA-FIELD COUNT DIFFERENT: " + tableName + " " + values[1].length + " " + fieldCount);
}
}
}
/**
* 数据字段
*/
public static class Field {
protected String fieldName;
protected String fieldType;
protected String fieldComment;
protected String name;
protected String type;
public String getFieldName() {
return fieldName;
}
public String getFieldType() {
return fieldType;
}
public String getFieldComment() {
return fieldComment;
}
public String getName() {
return name;
}
public String getType() {
if (type == null) {
String t = fieldType.toLowerCase();
int index = t.indexOf("(");
if (index != -1) {
t = t.substring(0, index);
}
switch (t) {
case "tinyint":
if (fieldType.charAt(index + 1) == '3') {
return "short";
}
type = "byte";
break;
case "smallint":
type = "short";
break;
case "mediumint":
case "int":
type = "int";
break;
case "bigint":
type = "long";
break;
case "float":
case "double":
type = "double";
break;
case "bit":
type = "boolean";
break;
default:
type = "String";
break;
}
}
return type;
}
public Object getValue(String s) {
String t = getType();
switch (t) {
case "byte":
return s == null ? (byte) 0 : Byte.parseByte(s);
case "short":
return s == null ? (short) 0 : Short.parseShort(s);
case "int":
return s == null ? 0 : Integer.parseInt(s);
case "long":
return s == null ? 0 : Long.parseLong(s);
case "double":
return s == null ? 0d : Double.parseDouble(s);
default:
return s.intern();
}
}
}
}
| 23.392473 | 104 | 0.602275 |
a3d428182aad5145dfbc8a8359ecd856ddf4458e | 1,628 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.fhwa.c2cri.ntcip2306v109.messaging;
/**
* The Class NTCIP2306MessageValidationException provides a mechanism to indicate that an exception is specifically related to the validation of an NTCIP 2306 message.
*
* @author TransCore ITS, LLC
* Last Updated: 1/8/2014
*/
public class NTCIP2306MessageValidationException extends Exception {
/** The message. */
private String message = null;
/**
* Instantiates a new NTCIP2306 message validation exception.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*/
public NTCIP2306MessageValidationException() {
super();
}
/**
* Instantiates a new NTCIP2306 message validation exception.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param message the message
*/
public NTCIP2306MessageValidationException(String message) {
super(message);
this.message = message;
}
/**
* Instantiates a new NTCIP2306 message validation exception.
*
* Pre-Conditions: N/A
* Post-Conditions: N/A
*
* @param cause the cause
*/
public NTCIP2306MessageValidationException(Throwable cause) {
super(cause);
}
/* (non-Javadoc)
* @see java.lang.Throwable#toString()
*/
@Override
public String toString() {
return message;
}
/* (non-Javadoc)
* @see java.lang.Throwable#getMessage()
*/
@Override
public String getMessage() {
return message;
}
}
| 23.257143 | 167 | 0.632064 |
886f5f2c3ad4cc0e99390f3663c170b1c63071ce | 2,463 | package osm5.ns.yang.nfvo.netslice.instantiation.parameters.rev181128.netslice_vld_params;
import java.lang.Override;
import java.lang.String;
import javax.annotation.Nullable;
import org.opendaylight.yangtools.yang.binding.Augmentable;
import org.opendaylight.yangtools.yang.binding.ChildOf;
import org.opendaylight.yangtools.yang.binding.Identifiable;
import org.opendaylight.yangtools.yang.common.QName;
import osm5.ns.yang.ietf.inet.types.rev130715.IpAddress;
import osm5.ns.yang.nfvo.netslice.instantiation.parameters.rev181128.$YangModuleInfoImpl;
import osm5.ns.yang.nfvo.netslice.instantiation.parameters.rev181128.NetsliceVldParams;
/**
*
* <p>
* This class represents the following YANG schema fragment defined in module <b>netslice-instantiation-parameters</b>
* <pre>
* list nss-connection-point-ref {
* key "nss-ref nsd-connection-point-ref";
* leaf nss-ref {
* type leafref {
* path /nst:nst/nst:netslice-subnet/nst:id;
* }
* }
* leaf nsd-connection-point-ref {
* type leafref {
* path /nsd:nsd-catalog/nsd:nsd/nsd:connection-point/nsd:name;
* }
* }
* leaf ip-address {
* type inet:ip-address;
* }
* }
* </pre>The schema path to identify an instance is
* <i>netslice-instantiation-parameters/netslice_vld_params/nss-connection-point-ref</i>
*
* <p>To create instances of this class use {@link NssConnectionPointRefBuilder}.
* @see NssConnectionPointRefBuilder
* @see NssConnectionPointRefKey
*
*/
public interface NssConnectionPointRef
extends
ChildOf<NetsliceVldParams>,
Augmentable<NssConnectionPointRef>,
Identifiable<NssConnectionPointRefKey>
{
public static final QName QNAME = $YangModuleInfoImpl.qnameOf("nss-connection-point-ref");
/**
* Reference to slice subnet
*
*
*
* @return <code>java.lang.String</code> <code>nssRef</code>, or <code>null</code> if not present
*/
@Nullable
String getNssRef();
/**
* @return <code>java.lang.String</code> <code>nsdConnectionPointRef</code>, or <code>null</code> if not present
*/
@Nullable
String getNsdConnectionPointRef();
/**
* @return <code>org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress</code> <code>ipAddress</code>, or <code>null</code> if not present
*/
@Nullable
IpAddress getIpAddress();
@Override
NssConnectionPointRefKey key();
}
| 30.036585 | 180 | 0.709298 |
4f123956b64d73ecc844d68d24011979318000e8 | 12,635 | package Frontera.Produccion;
import Frontera.Usuarios.*;
import Frontera.FramePrincipal;
import com.easycoffee.ImgTabla;
import com.easycoffee.Plaga;
import com.easycoffee.Usuario;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
/**
*
* @author Diego Felipe Lopez Avila
*/
public class Plagas extends javax.swing.JPanel {
private int cedula;
ArrayList<Plaga> plagas= FramePrincipal.getSistem().getAdmin().getFinca().getPlagas();
private void PropiedadesTabla(){
tabla.setFont(new java.awt.Font("Sitka Banner", 1, 18));
tabla.setDefaultRenderer(Object.class, new ImgTabla());
String titulos[] = {"Nombre","Foto","Descripción","Tratamiento"};
DefaultTableModel model = new DefaultTableModel(null,titulos);
for(int i=0; i<plagas.size();i++){
ImageIcon imagen = plagas.get(i).getImagen();
model.addRow(new Object[]{plagas.get(i).getNombrePlaga(),
new JLabel(new ImageIcon(imagen.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH))),
plagas.get(i).getDescripcionPlaga(),
plagas.get(i).getTratamientoPlaga()
});
}
tabla.setRowHeight(100);
tabla.setModel(model);
TableColumn columna = tabla.getColumn("Foto");
columna.setPreferredWidth(100);
columna = tabla.getColumn("Nombre");
columna.setPreferredWidth(90);
columna = tabla.getColumn("Descripción");
columna.setPreferredWidth(300);
columna = tabla.getColumn("Tratamiento");
columna.setPreferredWidth(300);
}
public Plagas(int cedula) {
initComponents();
PropiedadesTabla();
this.cedula = cedula;
tabla.setFont(new java.awt.Font("Sitka Banner", 1, 18));
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
nLotesL = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tabla = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
añadir = new javax.swing.JToggleButton();
jLabel1 = new javax.swing.JLabel();
buscar = new javax.swing.JToggleButton();
nombre = new javax.swing.JTextField();
recargar = new javax.swing.JToggleButton();
setMaximumSize(new java.awt.Dimension(900, 376));
setMinimumSize(new java.awt.Dimension(900, 376));
setPreferredSize(new java.awt.Dimension(900, 376));
nLotesL.setFont(new java.awt.Font("Sitka Banner", 1, 18)); // NOI18N
nLotesL.setForeground(new java.awt.Color(255, 255, 255));
tabla.setBackground(new java.awt.Color(102, 102, 102));
tabla.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
tabla.setFont(new java.awt.Font("Sitka Banner", 0, 18)); // NOI18N
tabla.setForeground(new java.awt.Color(0, 0, 0));
tabla.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tabla.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
tabla.setEnabled(false);
tabla.setGridColor(new java.awt.Color(204, 204, 204));
tabla.setMaximumSize(new java.awt.Dimension(2147483647, 2147483647));
tabla.setMinimumSize(new java.awt.Dimension(100, 100));
tabla.setRowHeight(100);
tabla.setRowMargin(3);
tabla.setSelectionBackground(new java.awt.Color(153, 153, 153));
tabla.setSelectionForeground(new java.awt.Color(0, 0, 0));
tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
tabla.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tablaMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tabla);
jButton1.setBackground(new java.awt.Color(102, 0, 0));
jButton1.setFont(new java.awt.Font("Sitka Banner", 1, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 255, 255));
jButton1.setText("Recargar");
jButton1.setBorder(javax.swing.BorderFactory.createEtchedBorder(java.awt.Color.white, null));
añadir.setBackground(new java.awt.Color(102, 0, 0));
añadir.setFont(new java.awt.Font("Sitka Banner", 0, 14)); // NOI18N
añadir.setForeground(new java.awt.Color(255, 255, 255));
añadir.setText("Añadir plaga");
añadir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
añadirActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Sitka Banner", 1, 14)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Nombre de plaga:");
buscar.setBackground(new java.awt.Color(102, 0, 0));
buscar.setFont(new java.awt.Font("Sitka Banner", 0, 14)); // NOI18N
buscar.setForeground(new java.awt.Color(255, 255, 255));
buscar.setText("Buscar");
buscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buscarActionPerformed(evt);
}
});
nombre.setBackground(new java.awt.Color(255, 255, 255));
nombre.setFont(new java.awt.Font("Sitka Banner", 0, 14)); // NOI18N
nombre.setForeground(new java.awt.Color(0, 0, 0));
recargar.setBackground(new java.awt.Color(102, 0, 0));
recargar.setFont(new java.awt.Font("Sitka Banner", 0, 14)); // NOI18N
recargar.setForeground(new java.awt.Color(255, 255, 255));
recargar.setText("Recargar");
recargar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
recargarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(387, 387, 387)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(añadir, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(recargar, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(buscar)
.addGap(176, 176, 176)
.addComponent(nLotesL, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 874, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(nLotesL, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(añadir, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(recargar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(769, 769, 769)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void añadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_añadirActionPerformed
FramePrincipal.cambiarPanel376(new CrearPlaga(cedula));
}//GEN-LAST:event_añadirActionPerformed
private void buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarActionPerformed
if(!nombre.getText().equals("")){
tabla.setDefaultRenderer(Object.class, new ImgTabla());
String titulos[] = {"Nombre","Foto","Descripción","Tratamiento"};
DefaultTableModel model = new DefaultTableModel(null,titulos);
for(int i=0; i<plagas.size();i++){
if(plagas.get(i).getNombrePlaga().toUpperCase().contains(nombre.getText().toUpperCase())){
ImageIcon imagen = plagas.get(i).getImagen();
model.addRow(new Object[]{plagas.get(i).getNombrePlaga(),
new JLabel(new ImageIcon(imagen.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH))),
plagas.get(i).getDescripcionPlaga(),
plagas.get(i).getTratamientoPlaga()
});
}
}
tabla.setRowHeight(100);
tabla.setModel(model);
TableColumn columna = tabla.getColumn("Foto");
columna.setPreferredWidth(100);
columna = tabla.getColumn("Nombre");
columna.setPreferredWidth(90);
columna = tabla.getColumn("Descripción");
columna.setPreferredWidth(300);
columna = tabla.getColumn("Tratamiento");
columna.setPreferredWidth(300);
}else{
JOptionPane.showMessageDialog(null, "No ingresó el nombre de la plaga.");
}
}//GEN-LAST:event_buscarActionPerformed
private void recargarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recargarActionPerformed
PropiedadesTabla();
}//GEN-LAST:event_recargarActionPerformed
private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
}//GEN-LAST:event_tablaMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton añadir;
private javax.swing.JToggleButton buscar;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel nLotesL;
private javax.swing.JTextField nombre;
private javax.swing.JToggleButton recargar;
private javax.swing.JTable tabla;
// End of variables declaration//GEN-END:variables
}
| 46.113139 | 167 | 0.640522 |
f82abd2cc1425bbf11c688e0b86faf558593adfd | 2,629 | /*
* 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.aliyuncs.ens.model.v20171110;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
/**
* @author auto create
* @version
*/
public class DescribeEnsRegionIdResourceRequest extends RpcAcsRequest<DescribeEnsRegionIdResourceResponse> {
private String isp;
private String startTime;
private Integer pageNumber;
private String orderByParams;
private String pageSize;
private String endTime;
public DescribeEnsRegionIdResourceRequest() {
super("Ens", "2017-11-10", "DescribeEnsRegionIdResource", "ens");
setMethod(MethodType.POST);
}
public String getIsp() {
return this.isp;
}
public void setIsp(String isp) {
this.isp = isp;
if(isp != null){
putQueryParameter("Isp", isp);
}
}
public String getStartTime() {
return this.startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
if(startTime != null){
putQueryParameter("StartTime", startTime);
}
}
public Integer getPageNumber() {
return this.pageNumber;
}
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
if(pageNumber != null){
putQueryParameter("PageNumber", pageNumber.toString());
}
}
public String getOrderByParams() {
return this.orderByParams;
}
public void setOrderByParams(String orderByParams) {
this.orderByParams = orderByParams;
if(orderByParams != null){
putQueryParameter("OrderByParams", orderByParams);
}
}
public String getPageSize() {
return this.pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
if(pageSize != null){
putQueryParameter("PageSize", pageSize);
}
}
public String getEndTime() {
return this.endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
if(endTime != null){
putQueryParameter("EndTime", endTime);
}
}
@Override
public Class<DescribeEnsRegionIdResourceResponse> getResponseClass() {
return DescribeEnsRegionIdResourceResponse.class;
}
}
| 22.86087 | 108 | 0.713199 |
e1b8ded6735c2aa9c211df2a6eb38f2e4d2cff61 | 7,313 | /*
* Copyright (c) 2022 Eben Howard, Tommy Ettinger, and contributors
*
* 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 squidpony.squidgrid.mapping;
import squidpony.ArrayTools;
import squidpony.squidgrid.Radius;
import squidpony.squidmath.BathtubDistribution;
import squidpony.squidmath.FastNoise;
import squidpony.squidmath.GWTRNG;
import squidpony.squidmath.GreasedRegion;
import squidpony.squidmath.IRNG;
/**
* Map generator that produces erratic, non-artificial-looking areas that could be cave complexes. This works by
* generating a region of continuous noise and two distant points in it, progressively using larger
* portions of the noise until it connects the points. The algorithm was discovered by tann, a libGDX user and noise
* aficionado, and it works a little more cleanly than the old approach this class used.
* <br>
* Initially created by Tommy Ettinger on 4/18/2016, reworked a few times, now mostly tann's work.
*/
public class OrganicMapGenerator implements IDungeonGenerator {
public char[][] map;
public int[][] environment;
public GreasedRegion floors;
public IRNG rng;
protected int width, height;
public double noiseMin, noiseMax;
protected FastNoise noise;
public OrganicMapGenerator()
{
this(0.55, 0.65, 80, 30, new GWTRNG());
}
public OrganicMapGenerator(int width, int height)
{
this(0.55, 0.65, width, height, new GWTRNG());
}
public OrganicMapGenerator(int width, int height, IRNG rng)
{
this(0.55, 0.65, width, height, rng);
}
public OrganicMapGenerator(double noiseMin, double noiseMax, int width, int height, IRNG rng)
{
this.rng = rng;
this.width = Math.max(3, width);
this.height = Math.max(3, height);
this.noiseMin = Math.min(0.9, Math.max(-1.0, noiseMin - 0.1));
this.noiseMax = Math.min(1.0, Math.max(noiseMin + 0.05, noiseMax + 0.1));
map = new char[this.width][this.height];
environment = new int[this.width][this.height];
floors = new GreasedRegion(width, height);
noise = new FastNoise(1, 0.375f, FastNoise.HONEY_FRACTAL, 2);
}
/**
* Generate a map as a 2D char array using the width and height specified in the constructor.
* Should produce an organic, cave-like map.
* @return a 2D char array for the map that should be organic-looking.
*/
@Override
public char[][] generate() {
noise.setSeed(rng.nextInt());
double[][] noiseMap = new double[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
noiseMap[x][y] = noise.getConfiguredNoise(x, y);
}
}
int w2 = width - 2, h2 = height - 2;
int startX = (int) (BathtubDistribution.instance.nextDouble(rng) * w2) + 1;
int endX = (int) (BathtubDistribution.instance.nextDouble(rng) * w2) + 1;
int startY = (int) (BathtubDistribution.instance.nextDouble(rng) * h2) + 1;
int endY = (int) (BathtubDistribution.instance.nextDouble(rng) * h2) + 1;
while (Radius.CIRCLE.radius(startX, startY, endX, endY) * 3 < width + height){
startX = (int) (BathtubDistribution.instance.nextDouble(rng) * w2) + 1;
endX = (int) (BathtubDistribution.instance.nextDouble(rng) * w2) + 1;
startY = (int) (BathtubDistribution.instance.nextDouble(rng) * h2) + 1;
endY = (int) (BathtubDistribution.instance.nextDouble(rng) * h2) + 1;
}
GreasedRegion region = new GreasedRegion(width, height), linking;
for (int i = 1; i <= 25; i++) {
noiseMax = 0.04 * i;
floors.refill(noiseMap, -noiseMax, noiseMax);
if(floors.contains(startX, startY) && floors.contains(endX, endY) &&
region.empty().insert(startX, startY).flood(floors, width * height).contains(endX, endY))
break;
}
floors.intoChars(map, '.', '#');
ArrayTools.fill(environment, DungeonUtility.UNTOUCHED);
floors.writeIntsInto(environment, DungeonUtility.CAVE_FLOOR);
region.remake(floors).fringe8way().writeIntsInto(environment, DungeonUtility.CAVE_WALL);
int upperY = height - 1;
int upperX = width - 1;
for (int i = 0; i < width; i++) {
map[i][0] = '#';
map[i][upperY] = '#';
environment[i][0] = DungeonUtility.UNTOUCHED;
environment[i][upperY] = DungeonUtility.UNTOUCHED;
}
for (int i = 0; i < height; i++) {
map[0][i] = '#';
map[upperX][i] = '#';
environment[0][i] = DungeonUtility.UNTOUCHED;
environment[upperX][i] = DungeonUtility.UNTOUCHED;
}
return map;
}
/**
* Gets a 2D array of int constants, each representing a type of environment corresponding to a static field of
* MixedGenerator. This array will have the same size as the last char 2D array produced by generate(); the value
* of this method if called before generate() is undefined, but probably will be a 2D array of all 0 (UNTOUCHED).
* <ul>
* <li>MixedGenerator.UNTOUCHED, equal to 0, is used for any cells that aren't near a floor.</li>
* <li>MixedGenerator.ROOM_FLOOR, equal to 1, is used for floor cells inside wide room areas.</li>
* <li>MixedGenerator.ROOM_WALL, equal to 2, is used for wall cells around wide room areas.</li>
* <li>MixedGenerator.CAVE_FLOOR, equal to 3, is used for floor cells inside rough cave areas.</li>
* <li>MixedGenerator.CAVE_WALL, equal to 4, is used for wall cells around rough cave areas.</li>
* <li>MixedGenerator.CORRIDOR_FLOOR, equal to 5, is used for floor cells inside narrow corridor areas.</li>
* <li>MixedGenerator.CORRIDOR_WALL, equal to 6, is used for wall cells around narrow corridor areas.</li>
* </ul>
* @return a 2D int array where each element is an environment type constant in MixedGenerator
*/
public int[][] getEnvironment()
{
return environment;
}
@Override
public char[][] getDungeon() {
return map;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public double getNoiseMin() {
return noiseMin;
}
public void setNoiseMin(double noiseMin) {
this.noiseMin = noiseMin;
}
public double getNoiseMax() {
return noiseMax;
}
public void setNoiseMax(double noiseMax) {
this.noiseMax = noiseMax;
}
}
| 40.181319 | 117 | 0.637221 |
d6a6143d77a15d0a4e38408dad529afb5ad94fd2 | 117 | package com.eastwood.demo.router;
public class SerializableObject {
public int data;
public String name;
} | 14.625 | 33 | 0.735043 |
68601d937a096ec6a42d98f24eae6027b7b4cfeb | 3,737 | package com.greymass.esr.models;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.greymass.esr.ESRException;
import com.greymass.esr.interfaces.IRequest;
import com.greymass.esr.util.JSONUtil;
import java.util.List;
import java.util.Map;
import static com.greymass.esr.models.Identity.IDENTITY;
public class Action implements IRequest {
public static final String VARIANT_TYPE = "action";
private final String ACCOUNT = "account";
private final String NAME = "name";
private final String AUTHORIZATION = "authorization";
private final String DATA = "data";
private AccountName gAccount;
private ActionName gName;
private List<PermissionLevel> gAuthorization = Lists.newArrayList();
private ActionData gData;
public Action() {
}
public Action(JsonObject obj) throws ESRException {
gAccount = new AccountName(obj.get(ACCOUNT).getAsString());
gName = new ActionName(obj.get(NAME).getAsString());
gAuthorization = getPermissionsFromJsonArray(obj.getAsJsonArray(AUTHORIZATION));
if (obj.get(DATA).isJsonObject())
gData = new ActionData(obj.getAsJsonObject(DATA));
else
gData = new ActionData(obj.get(DATA).getAsString());
}
private List<PermissionLevel> getPermissionsFromJsonArray(JsonArray array) throws ESRException {
List<PermissionLevel> permissionLevels = Lists.newArrayList();
for (JsonElement el : array) {
if (!(el instanceof JsonObject))
throw new ESRException("Permission was not an object");
permissionLevels.add(new PermissionLevel((JsonObject) el));
}
return permissionLevels;
}
public boolean isIdentity() {
return gAccount != null && "".equals(gAccount.getName()) &&
gName != null && IDENTITY.equals(gName.getName());
}
public AccountName getAccount() {
return gAccount;
}
public void setAccount(AccountName account) {
gAccount = account;
}
public ActionName getName() {
return gName;
}
public void setName(ActionName name) {
gName = name;
}
public List<PermissionLevel> getAuthorization() {
return gAuthorization;
}
public String getAuthorizationJSON() {
List<Map<String, String>> toEncode = Lists.newArrayList();
for (PermissionLevel level : gAuthorization)
toEncode.add(level.toMap());
return JSONUtil.stringify(toEncode);
}
public void addAuthorization(PermissionLevel authorization) {
gAuthorization.add(authorization);
}
public ActionData getData() {
return gData;
}
public void setData(ActionData data) {
gData = data;
}
public Map<String, Object> toMap() {
Map<String, Object> result = Maps.newHashMap();
result.put(ACCOUNT, gAccount.getName());
result.put(NAME, gName.getName());
List<Map<String, String>> auths = Lists.newArrayList();
for (PermissionLevel permissionLevel : gAuthorization)
auths.add(permissionLevel.toMap());
result.put(AUTHORIZATION, auths);
result.put(DATA, gData.isPacked() ? gData.getPackedData() : gData.getData());
return result;
}
@Override
public List<Action> getRawActions() {
return Lists.newArrayList(this);
}
@Override
public List<Object> toVariant() {
List<Object> variant = Lists.newArrayList();
variant.add(VARIANT_TYPE);
variant.add(toMap());
return variant;
}
}
| 29.65873 | 100 | 0.660423 |
ee4ea3a9b661b861899a6a902a12ac43ab42b32b | 6,681 | /*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package com.microsoft.azure.sdk.iot.provisioning.service.auth;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import static org.apache.commons.codec.binary.Base64.decodeBase64;
import static org.apache.commons.codec.binary.Base64.encodeBase64String;
/**
* Grants device access to an Provisioning for the specified amount of time.
*/
public final class ProvisioningSasToken
{
private static final long TOKEN_VALID_SECS = 365*24*60*60;
private static final long ONE_SECOND_IN_MILLISECONDS = 1000;
/**
* The SAS token format. The parameters to be interpolated are, in order:
* the signature
* the resource URI
* the expiry time
* the key name
* Example: {@code SharedAccessSignature sr=DEVICEPROVISIONINGSERVICEURI&sig=SIGNATURE&se=EXPIRY&skn=SHAREDACCESSKEYNAME}
*/
private static final String TOKEN_FORMAT = "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s";
/* The URI for a connection to an Provisioning */
private final String resourceUri;
/* The value of the SharedAccessKey */
private final String keyValue;
/* The time, as a UNIX timestamp, before which the token is valid. */
private final long expiryTime;
/* The value of SharedAccessKeyName */
private final String keyName;
/* The SAS token that grants access. */
private final String token;
/**
* Constructor. Generates a SAS token that grants access to an Provisioning for
* the specified amount of time. (1 year specified in TOKEN_VALID_SECS)
*
* @param provisioningConnectionString Connection string object containing the connection parameters
* @throws IllegalArgumentException if the provided provisioning connection string is null
*/
public ProvisioningSasToken(ProvisioningConnectionString provisioningConnectionString) throws IllegalArgumentException
{
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_001: [The constructor shall throw IllegalArgumentException if the input object is null]
if (provisioningConnectionString == null)
{
throw new IllegalArgumentException("provisioningConnectionString is null");
}
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)]
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
this.resourceUri = provisioningConnectionString.getHostName();
this.keyValue = provisioningConnectionString.getSharedAccessKey();
this.keyName = provisioningConnectionString.getSharedAccessKeyName();
this.expiryTime = buildExpiresOn();
this.token = buildToken();
}
/**
* Helper function to build the token string
*
* @return Valid token string
*/
private String buildToken()
{
String targetUri;
try
{
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
targetUri = URLEncoder.encode(this.resourceUri.toLowerCase(), StandardCharsets.UTF_8.name());
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)]
String toSign = targetUri + "\n" + this.expiryTime;
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Get an hmac_sha1 key from the raw key bytes
byte[] keyBytes = decodeBase64(this.keyValue.getBytes(StandardCharsets.UTF_8));
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
// Get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(toSign.getBytes(StandardCharsets.UTF_8));
// Convert raw bytes to Hex
String signature = URLEncoder.encode(encodeBase64String(rawHmac), StandardCharsets.UTF_8.name());
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
return String.format(TOKEN_FORMAT, targetUri, signature, this.expiryTime, this.keyName);
}
catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e)
{
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_007: [The constructor shall throw Exception if building the token failed]
throw new RuntimeException(e);
}
}
/**
* Helper function to calculate token expiry
*
* @return Seconds from now to expiry
*/
private long buildExpiresOn()
{
long expiresOnDate = System.currentTimeMillis();
expiresOnDate += TOKEN_VALID_SECS * ONE_SECOND_IN_MILLISECONDS;
return expiresOnDate / ONE_SECOND_IN_MILLISECONDS;
}
/**
* Returns the string representation of the SAS token.
*
* @return The string representation of the SAS token.
*/
@Override
public String toString()
{
// Codes_SRS_PROVISIONING_SERVICE_SASTOKEN_12_008: [The constructor shall return with the generated token]
return this.token;
}
}
| 48.064748 | 230 | 0.72115 |
4d2656ee91c4f6caa0ddc5a5b7e3920948f0dc3b | 5,412 | package com.igeeksky.xtool.core.nlp;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
/**
* @author Patrick.Lau
* @since 0.0.4 2021-11-12
*/
@SuppressWarnings("unchecked")
public class LinkedNode<V> extends Node<V> {
protected LinkedNode<V> next;
public LinkedNode(char c) {
super(c);
}
public LinkedNode(char c, V value, int size, Node<V>[] table) {
super(c, value, size, table);
}
public void setNext(LinkedNode<V> next) {
this.next = next;
}
@Override
public Node<V> find(char c) {
LinkedNode<V> node = this;
while (node != null) {
if (node.c == c) {
return node;
}
node = node.next;
}
return null;
}
@Override
protected List<Node<V>> findAll() {
List<Node<V>> nodes = new LinkedList<>();
LinkedNode<V> node = this;
while (node != null) {
nodes.add(node);
node = node.next;
}
return nodes;
}
@Override
public Node<V> insert(Node<V> parent, int index, char c, NodeConvertor<? extends Node<V>, ? extends TreeNode<V>> convertor) {
// 遍历首节点及其后继节点:如果char值相同,返回该节点;如果char值不同,将新节点添加到链表末尾(超过阈值则转换成AVL树再插入新节点)
int count = 1;
LinkedNode<V> next = this;
while (true) {
if (c == next.c) {
return next;
}
count++;
if (next.next == null) {
if (count >= TrieConstants.TO_TREE_NODE_THRESHOLD) {
// 转换成Avl树,并插入新节点
Node<V> head = ((NodeConvertor<LinkedNode<V>, ? extends TreeNode<V>>) convertor).toTreeNode(this);
return head.insert(parent, index, c, convertor);
}
parent.increment();
LinkedNode<V> node = new LinkedNode<>(c);
next.setNext(node);
return node;
}
next = next.next;
}
}
@Override
public Node<V> delete(BaseNode<V> delete, NodeConvertor<? extends Node<V>, ? extends TreeNode<V>> convertor) {
LinkedNode<V> del = (LinkedNode<V>) delete;
if (this.c == del.c) {
LinkedNode<V> head = this.next;
this.next = null;
return head;
}
LinkedNode<V> node = this;
while (node.next != null) {
if (node.next.c == del.c) {
del = node.next;
node.next = del.next;
del.next = null;
break;
}
node = node.next;
}
return this;
}
@Override
public void split(Node<V>[] newTab, int oldCap, int oldIndex, NodeConvertor<? extends Node<V>, ? extends TreeNode<V>> convertor) {
if (this.next == null) {
newTab[this.c & newTab.length - 1] = this;
return;
}
LinkedNode<V> head = this, loHead = null, loTail = null, hiHead = null, hiTail = null;
for (LinkedNode<V> node = head, next; node != null; node = next) {
next = node.next;
if ((node.c & oldCap) == 0) {
if (loTail == null) {
loHead = node;
} else {
loTail.next = node;
}
loTail = node;
} else {
if (hiTail == null) {
hiHead = node;
} else {
hiTail.next = node;
}
hiTail = node;
}
}
if (loHead != null) {
newTab[oldIndex] = loHead;
loTail.next = null;
}
if (hiHead != null) {
newTab[oldIndex + oldCap] = hiHead;
hiTail.next = null;
}
}
@Override
public Node<V> join(Node<V> old, NodeConvertor<? extends Node<V>, ? extends TreeNode<V>> convertor) {
if (!(old instanceof LinkedNode)) {
return old.join(this, convertor);
}
int count = 1;
LinkedNode<V> head = this, tail = this;
while (tail.next != null) {
++count;
tail = tail.next;
}
LinkedNode<V> node = (LinkedNode<V>) old;
while (node != null) {
++count;
tail.next = node;
tail = node;
node = node.next;
}
if (count >= TrieConstants.TO_TREE_NODE_THRESHOLD) {
return ((NodeConvertor<LinkedNode<V>, ? extends TreeNode<V>>) convertor).toTreeNode(head);
}
return head;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof LinkedNode)) {
return false;
}
if (!super.equals(o)) {
return false;
}
LinkedNode<?> that = (LinkedNode<?>) o;
return Objects.equals(next, that.next);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (next != null ? next.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "{\"c\":\"" + c + "\"" +
(null != value ? (", \"value\":" + value) : "") +
(null != next ? (", \"next\":" + next) : "") +
'}';
}
} | 28.787234 | 134 | 0.472469 |
b94a50b3f6e45e8458c5516335f147b76ff4546a | 7,357 | package carbon.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewParent;
import carbon.R;
import carbon.drawable.EdgeEffect;
/**
* Created by Marcin on 2015-02-28.
*/
public class ScrollView extends android.widget.ScrollView {
private final int mTouchSlop;
int glowColor;
EdgeEffect edgeGlowTop;
EdgeEffect edgeGlowBottom;
private boolean drag = true;
private float prevY;
private int overscrollMode;
public static final int OVER_SCROLL_ALWAYS = 0;
public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
public static final int OVER_SCROLL_NEVER = 2;
public ScrollView(Context context) {
this(context, null);
}
public ScrollView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.scrollViewStyle);
}
public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ScrollView, defStyleAttr, 0);
glowColor = a.getColor(R.styleable.ScrollView_carbon_glowColor, 0);
a.recycle();
}
private int getScrollRange() {
int scrollRange = 0;
if (getChildCount() > 0) {
View child = getChildAt(0);
scrollRange = Math.max(0,
child.getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop()));
}
return scrollRange;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (edgeGlowTop != null) {
final int scrollY = getScrollY();
if (!edgeGlowTop.isFinished()) {
final int restoreCount = canvas.save();
final int width = getWidth() - getPaddingLeft() - getPaddingRight();
canvas.translate(getPaddingLeft(), Math.min(0, scrollY));
edgeGlowTop.setSize(width, getHeight());
if (edgeGlowTop.draw(canvas)) {
postInvalidate();
}
canvas.restoreToCount(restoreCount);
}
if (!edgeGlowBottom.isFinished()) {
final int restoreCount = canvas.save();
final int width = getWidth() - getPaddingLeft() - getPaddingRight();
final int height = getHeight();
canvas.translate(-width + getPaddingLeft(),
Math.max(getScrollRange(), scrollY) + height);
canvas.rotate(180, width, 0);
edgeGlowBottom.setSize(width, height);
if (edgeGlowBottom.draw(canvas)) {
postInvalidate();
}
canvas.restoreToCount(restoreCount);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean result = super.onTouchEvent(ev);
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
float deltaY = prevY - ev.getY();
if (!drag && Math.abs(deltaY) > mTouchSlop) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
drag = true;
if (deltaY > 0) {
deltaY -= mTouchSlop;
} else {
deltaY += mTouchSlop;
}
}
if (drag) {
final int oldY = getScrollY();
final int range = getScrollRange();
boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
(overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
if (canOverscroll) {
float pulledToY = oldY + deltaY;
if (pulledToY < 0) {
edgeGlowTop.onPull(deltaY / getHeight(), ev.getX() / getWidth());
if (!edgeGlowBottom.isFinished())
edgeGlowBottom.onRelease();
} else if (pulledToY > range) {
edgeGlowBottom.onPull(deltaY / getHeight(), 1.f - ev.getX() / getWidth());
if (!edgeGlowTop.isFinished())
edgeGlowTop.onRelease();
}
if (edgeGlowTop != null && (!edgeGlowTop.isFinished() || !edgeGlowBottom.isFinished()))
postInvalidate();
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (drag)
endDrag();
break;
}
prevY = ev.getY();
return result;
}
/* @Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
final int range = getScrollRange();
final boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
(overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
if (canOverscroll) {
if (y < 0 && oldY >= 0) {
edgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity());
} else if (y > range && oldY <= range) {
edgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity());
}
}
}
if (!awakenScrollBars()) {
// Keep on drawing until the animation has finished.
postInvalidate();
}
}
}*/
private void endDrag() {
drag = false;
if (edgeGlowTop != null) {
edgeGlowTop.onRelease();
edgeGlowBottom.onRelease();
}
}
@Override
public void setOverScrollMode(int mode) {
if (mode != OVER_SCROLL_NEVER) {
if (edgeGlowTop == null) {
Context context = getContext();
edgeGlowTop = new EdgeEffect(context);
edgeGlowTop.setColor(glowColor);
edgeGlowBottom = new EdgeEffect(context);
edgeGlowBottom.setColor(glowColor);
}
} else {
edgeGlowTop = null;
edgeGlowBottom = null;
}
super.setOverScrollMode(OVER_SCROLL_NEVER);
this.overscrollMode = mode;
}
public int getGlowColor() {
return glowColor;
}
public void setGlowColor(int glowColor) {
this.glowColor = glowColor;
}
}
| 34.867299 | 111 | 0.528748 |
140134cbfc4ba66fadd682608d39f6997d9603ad | 2,715 | package de.consol.labs.h2c;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;
@WebServlet("test")
public class TestServlet extends HttpServlet {
// Mapped to https://localhost:8443/h2c/test
// The size of the returned text can be increased with a URL parameter, like
// https://localhost:8443/hello-world/api/hello-world?size=123
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (session.getAttribute("counter") == null) {
session.setAttribute("counter", new AtomicInteger(0));
}
int reqNr = ((AtomicInteger) session.getAttribute("counter")).incrementAndGet();
PrintWriter writer = resp.getWriter();
writer.write("Hello, World!\n");
writer.write("Btw, this is request number " + reqNr + ".\n");
int size = readSize(req);
if (size > 0) {
writer.write("Here are " + size + " 'a' characters\n");
for (int i = 1; i <= size; i++) {
writer.write("a");
if (i % 80 == 0) {
writer.write("\n");
}
}
}
writer.close();
}
private int readSize(HttpServletRequest request) {
if (request.getParameterMap().containsKey("size")) {
return Integer.parseInt(request.getParameter("size"));
}
return 0;
}
// Mapped to https://localhost:8443/h2c/test
@Override
protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
int i = 0;
while (req.getReader().read() != -1) {
i++;
}
PrintWriter writer = resp.getWriter();
writer.write("Received put request with " + i + " characters payload.\n");
writer.close();
}
// Mapped to https://localhost:8443/h2c/test
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
int i = 0;
while (req.getReader().read() != -1) {
i++;
}
PrintWriter writer = resp.getWriter();
writer.write("Received post request with " + i + " characters payload.\n");
writer.close();
}
}
| 36.689189 | 126 | 0.627993 |
b4b8c5323f8734ba0ac413ac1f17c77cbb6f44b0 | 1,057 | package ru.otus;
import ru.otus.annotations.Log;
public class MyClassImpl implements MyClassInterface {
@Log
@Override
public void secureAccess() {
System.out.println("Method secureAccess with annotation and overloading");
}
@Override
public void secureAccess(String param) {
System.out.println("Method secureAccess without annotation, param:" + param);
}
@Log
@Override
public void secureAccess(String param1, String param2) {
System.out.println("Method secureAccess with annotation, param:" + param1 + " and " + param2);
}
@Override
public void methodWithoutAnnotation(int param) {
System.out.println("Method without annotations and one parameter: " + param);
}
@Log
@Override
public void methodWithAnnotationAndTwoParameters(int param1, int param2) {
System.out.println("Method with annotation and two parameters: " + param1 + " and " + param2);
}
@Override
public String toString() {
return "MyClassImpl{}";
}
}
| 25.780488 | 102 | 0.666982 |
31fb269448083e69288e0d47099adf158ae4ff51 | 346 | package edu.cibertec.votoelectronico.domain.complex.transformer;
import java.util.List;
import org.hibernate.transform.ResultTransformer;
@FunctionalInterface
public interface ListResultTransformer extends ResultTransformer {
@SuppressWarnings("rawtypes")
@Override
default List transformList(List collection) {
return collection;
}
}
| 20.352941 | 66 | 0.820809 |
d812eab736102338310b904158d112a50af9c950 | 2,903 | /*
* Copyright 2018 Google Inc.
*
* 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.gwtproject.uibinder.processor.elementparsers;
import java.util.HashMap;
import java.util.Map;
import org.gwtproject.uibinder.processor.UiBinderWriter;
import org.gwtproject.uibinder.processor.XMLAttribute;
import org.gwtproject.uibinder.processor.XMLElement;
import org.gwtproject.uibinder.processor.ext.UnableToCompleteException;
/**
* Assigns computed values to element attributes, e.g. styleName={resources.style.pretty}, which
* will become something like myWidget.setStyleName(resources.style().pretty()) in the generated
* code.
*/
class ComputedAttributeInterpreter implements XMLElement.Interpreter<String> {
interface Delegate {
String getAttributeToken(XMLAttribute attribute) throws UnableToCompleteException;
}
class DefaultDelegate implements Delegate {
public String getAttributeToken(XMLAttribute attribute) throws UnableToCompleteException {
return writer.tokenForStringExpression(
attribute.getElement(), attribute.consumeStringValue());
}
}
private final UiBinderWriter writer;
private final Delegate delegate;
ComputedAttributeInterpreter(UiBinderWriter writer) {
this.writer = writer;
this.delegate = new DefaultDelegate();
}
ComputedAttributeInterpreter(UiBinderWriter writer, Delegate delegate) {
this.delegate = delegate;
this.writer = writer;
}
public String interpretElement(XMLElement elem) throws UnableToCompleteException {
Map<String, String> attNameToToken = new HashMap<String, String>();
for (int i = elem.getAttributeCount() - 1; i >= 0; i--) {
XMLAttribute att = elem.getAttribute(i);
if (att.hasComputedValue()) {
String attToken = delegate.getAttributeToken(att);
attNameToToken.put(att.getName(), attToken);
} else {
/*
* No computed value, but make sure that any {{ madness gets escaped.
* TODO(rjrjr) Move this to XMLElement RSN
*/
String n = att.getName();
String v = att.consumeRawValue().replace("\\{", "{");
elem.setAttribute(n, v);
}
}
for (Map.Entry<String, String> attr : attNameToToken.entrySet()) {
elem.setAttribute(attr.getKey(), attr.getValue());
}
// Return null because we don't want to replace the dom element
return null;
}
}
| 33.755814 | 96 | 0.721667 |
449e84dc255fb5d6034cbb937c38dcb12f43d5b6 | 4,283 | package com.example.praveenp.logitechtestapp.Activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.praveenp.logitechtestapp.R;
import com.example.praveenp.logitechtestapp.adapter.DeviceAdapter;
import com.example.praveenp.logitechtestapp.dao.Country;
import com.example.praveenp.logitechtestapp.dao.DeviceConfig;
import com.example.praveenp.logitechtestapp.dao.Language;
import com.example.praveenp.logitechtestapp.listeners.CountrySelectionListener;
import java.util.ArrayList;
import java.util.List;
public class DeviceListActivity extends Activity implements DeviceListView, CountrySelectionListener {
private ProgressDialog mProgressDialog ;
private DeviceListPresenter mPresenter;
private ListView mListView;
private DeviceAdapter mAdapter;
private List<Country> mCountryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
initView();
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Please Wait....");
mPresenter = new DeviceListPresenter();
mPresenter.attachView(this);
mPresenter.requestDeviceData();
}
private void initView(){
mListView = (ListView) findViewById(R.id.devices_list);
mListView.setEmptyView(findViewById(R.id.emptyview));
mAdapter = new DeviceAdapter(this,new ArrayList());
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int postion, long l) {
Country country = mCountryList.get(postion);
Intent i = new Intent(DeviceListActivity.this,DetailsActivity.class);
i.putExtra("COUNTRY_NAME",country.getName());
i.putExtra("COUNTRY_FLAG",country.getFlag());
StringBuffer lngStr = new StringBuffer();
for (Language language : country.getLanguages()){
lngStr.append(", "+language.getName());
}
i.putExtra("COUNTRY_LANG", lngStr.toString());
i.putExtra("COUNTRY_CALLING_CODE", country.getCallingCodes().get(0));
startActivity(i);
}
});
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
hideProgress();
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void showProgress() {
if (mProgressDialog != null && !isFinishing()) {
mProgressDialog.show();
}
}
@Override
public void hideProgress() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(isProgressDialogShowing()){
mProgressDialog.dismiss();
}
}
});
}
@Override
public Activity getActivity() {
return this;
}
public boolean isProgressDialogShowing() {
if (mProgressDialog != null) {
return mProgressDialog.isShowing();
}
return false;
}
@Override
public void updateDeviceInfo(final List<Country> configList) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mCountryList = configList;
mAdapter.updateDeviceInfo(mCountryList);
mAdapter.notifyDataSetChanged();
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onCountrySelect(Country country) {
}
}
| 29.951049 | 103 | 0.620593 |
59bf8e7412fe9dbdda770ed4a69e371feada0f26 | 1,292 | package com.xh.aop.commom.aspectj;
import com.xh.aop.commom.enums.EmError;
import com.xh.aop.commom.exception.BusinessException;
import com.xh.aop.commom.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @Name AccessLimitExceptionAspect
* @Description 使用aop处理异常请求
* @Author wen
* @Date 2019-07-11
*/
@Slf4j
//@Component
//@Aspect
public class AccessLimitExceptionAspect{
private Exception e;
//切入点
@Pointcut("@annotation(com.xh.aop.commom.annotation.AccessLimit)")
private void bountyHunterPointcut() {
}
/**
* 拦截web层异常,记录异常日志,并返回友好信息到前端
* @param e 异常对象
*/
@AfterThrowing(pointcut = "bountyHunterPointcut()", throwing = "e")
public void handleThrowing(JoinPoint joinPoint, Exception e) {
this.e = e;
log.error("发现异常!方法:" + joinPoint.getSignature().getName() + "--->异常", e);
//这里输入友好性信息
if (e instanceof BusinessException) {
ResponseUtil.writer((BusinessException)e);
} else {
ResponseUtil.writer(EmError.UNKNOWN_ERROR);
}
}
}
| 26.367347 | 81 | 0.694272 |
1f238b3e1683479a2abbbf3990122c8864ab2cbd | 5,664 | package com.reyzeny.twist;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.Source;
import com.jpardogo.android.googleprogressbar.library.GoogleProgressBar;
import com.mifmif.common.regex.Main;
import java.util.HashMap;
import java.util.Map;
public class Profile extends AppCompatActivity {
EditText edtUsername, edtFirstname, edtLastname, edtKeyRetrievalPassword;
AppCompatButton btnSave;
GoogleProgressBar pgbar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initComponents();
}
private void initComponents() {
edtUsername = findViewById(R.id.edit_text_profile_username);
edtFirstname = findViewById(R.id.edit_text_profile_firstname);
edtLastname = findViewById(R.id.edit_text_profile_lastname);
edtKeyRetrievalPassword = findViewById(R.id.edit_text_profile_key_retrieval_password);
btnSave = findViewById(R.id.button_profile_save);
pgbar = findViewById(R.id.profile_progressbar);
pgbar.setVisibility(View.GONE);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = edtUsername.getText().toString().toLowerCase();
String firstname = edtFirstname.getText().toString().toLowerCase();
String lastname = edtLastname.getText().toString().toLowerCase();
String key_retrieval_password = edtKeyRetrievalPassword.getText().toString().toLowerCase();
validateAndSaveInformation(username, firstname, lastname, key_retrieval_password);
}
});
}
private void validateAndSaveInformation(String username, String firstname, String lastname, String key_retrieval_password) {
if (inputsValidated(username, firstname, lastname, key_retrieval_password)) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
pgbar.setVisibility(View.VISIBLE);
db.collection(Constant.FIREBASE_USER_PROFILE_COLLECTION).whereEqualTo(Constant.USERNAME, username).get(Source.SERVER).addOnCompleteListener(Profile.this, new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.getResult()==null || task.getResult().getDocuments().isEmpty()) {
saveUserDetails(db, username, firstname, lastname, key_retrieval_password);
return;
}
showUserExists();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
}
});
}
}
private boolean inputsValidated(String username, String firstname, String lastname, String key_retrieval_password) {
if (username.isEmpty()){
edtUsername.setError("Enter a username");
return false;
}
if (firstname.isEmpty()){
edtFirstname.setError("Enter first name");
return false;
}
if (lastname.isEmpty()){
edtLastname.setError("Enter last name");
return false;
}
if (key_retrieval_password.isEmpty()){
edtKeyRetrievalPassword.setError("Enter password");
return false;
}
return true;
}
private void showUserExists() {
Snackbar.make(edtUsername, "Username already exists!", Snackbar.LENGTH_LONG).show();
pgbar.setVisibility(View.GONE);
}
private void saveUserDetails(FirebaseFirestore db, String username, String firstname, String lastname, String key_retrieval_password) {
Map<String, String> profile = new HashMap<>();
profile.put(Constant.USERNAME, username);
profile.put(Constant.FIRST_NAME, firstname);
profile.put(Constant.LAST_NAME, lastname);
profile.put(Constant.KEY_RETRIEVAL_PASSWORD, key_retrieval_password);
db.collection(Constant.FIREBASE_USER_PROFILE_COLLECTION).document(LocalData.getUserId(this))
.set(profile)
.addOnSuccessListener(documentReference -> {
LocalData.setUserName(Profile.this, username);
LocalData.setFirstName(Profile.this, firstname);
LocalData.setLastName(Profile.this, lastname);
LocalData.setUserSetupDone(Profile.this, true);
pgbar.setVisibility(View.GONE);
showMain();
});
}
private void showMain() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
| 42.268657 | 207 | 0.663489 |
53d24009d80854375eacd971c545a1f210432f3a | 2,857 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.airavata.registry.core.entities.appcatalog;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "GATEWAY_GROUPS")
public class GatewayGroupsEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "GATEWAY_ID")
private String gatewayId;
@Column(name = "ADMINS_GROUP_ID")
private String adminsGroupId;
@Column(name = "READ_ONLY_ADMINS_GROUP_ID")
private String readOnlyAdminsGroupId;
@Column(name = "DEFAULT_GATEWAY_USERS_GROUP_ID")
private String defaultGatewayUsersGroupId;
protected GatewayGroupsEntity() {
}
public GatewayGroupsEntity(String gatewayId) {
this.gatewayId = gatewayId;
}
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
public String getAdminsGroupId() {
return adminsGroupId;
}
public void setAdminsGroupId(String adminsGroupId) {
this.adminsGroupId = adminsGroupId;
}
public String getReadOnlyAdminsGroupId() {
return readOnlyAdminsGroupId;
}
public void setReadOnlyAdminsGroupId(String readOnlyAdminsGroupId) {
this.readOnlyAdminsGroupId = readOnlyAdminsGroupId;
}
public String getDefaultGatewayUsersGroupId() {
return defaultGatewayUsersGroupId;
}
public void setDefaultGatewayUsersGroupId(String defaultGatewayUsersGroupId) {
this.defaultGatewayUsersGroupId = defaultGatewayUsersGroupId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GatewayGroupsEntity)) return false;
GatewayGroupsEntity that = (GatewayGroupsEntity) o;
return gatewayId.equals(that.gatewayId);
}
@Override
public int hashCode() {
return gatewayId.hashCode();
}
}
| 28.009804 | 82 | 0.719286 |
43d9e3d4eb8b568f19c87191862f24acc89504e1 | 919 | package com.invoicing.manage.test;
import com.snailf.config.CodeGenerator;
public class TestCodeMaker {
// 数据库地址
private static String ip = "localhost";
// 数据库端口号
private static String port = "3306";
// 数据库用户名
private static String userName = "root";
// 数据库密码
private static String password = "123456";
// 数据库名称
private static String dbName = "jxc_db";
// 要生成代码的表名
private static String tableName = "system_authority_tb";
// 基础包名
private static String basePackage = "com.invoicing";
// 业务包名
private static String servicePackage = "manage";
// 项目名称
// private static String projectName = "helloword";
// private static String projectName = "code-generator";
//包路径 com.invoicing.manage.comment.aspect
public static void main(String[] args) {
CodeGenerator code = new CodeGenerator(ip, port, userName, password, dbName, tableName, basePackage,
servicePackage);
code.run();
}
}
| 23.564103 | 102 | 0.720348 |
4b0c58589eab806ba8c302345625fb272ebdf50c | 1,263 | package org.launchcode.liftoffrecipetracker.models;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Beverage extends AbstractEntityName {
//Class Variables
@ManyToMany(mappedBy = "beverages")
private final List<Recipe> recipes = new ArrayList<>();
@ManyToOne
private User user;
@NotBlank(message = "Please include a description of your beverage.")
@NotNull
@Size(max=500)
@FullTextField
private String description;
//Constructors
public Beverage() {
}
//Getters and Setters
public List<Recipe> getRecipes() {
return recipes;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| 21.40678 | 84 | 0.702296 |
8f2ef9cb339e8420daeec0e50aec00b997f40d7a | 15,118 | package org.filteredpush.akka.actors;
import akka.actor.*;
import akka.japi.Creator;
import akka.routing.RoundRobinPool;
import org.filteredpush.kuration.services.GeoLocate3;
import org.filteredpush.kuration.interfaces.IGeoRefValidationService;
import akka.routing.Broadcast;
import org.filteredpush.kuration.util.CountryLookup;
import org.filteredpush.kuration.util.CurationStatus;
import org.filteredpush.kuration.util.SpecimenRecord;
import org.filteredpush.kuration.util.CurationComment;
import org.filteredpush.kuration.util.CurationCommentType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.filteredpush.akka.data.Token;
import org.filteredpush.akka.data.TokenWithProv;
public class GEORefValidator extends UntypedActor {
private final ActorRef listener;
private final ActorRef workerRouter;
public GEORefValidator(final String service, final boolean useCache, final double certainty, final ActorRef listener) {
this.listener = listener;
workerRouter = getContext().actorOf(new RoundRobinPool(4).props(GEORefValidatorInvocation.props(service, useCache, certainty, listener)),
"workerRouter");
getContext().watch(workerRouter);
}
public GEORefValidator(final String service, final boolean useCache, final double certainty, final int instances, final ActorRef listener) {
this.listener = listener;
workerRouter = getContext().actorOf(new RoundRobinPool(instances).props(GEORefValidatorInvocation.props(service, useCache, certainty, listener)),
"workerRouter");
getContext().watch(workerRouter);
}
public void onReceive(Object message) {
if (message instanceof Token) {
if (!getSender().equals(getSelf())) {
workerRouter.tell(message, getSelf());
} else {
listener.tell(message, getSelf());
}
} else if (message instanceof Broadcast) {
workerRouter.tell(new Broadcast(((Broadcast) message).message()), getSender());
} else if (message instanceof Terminated) {
if (((Terminated) message).getActor().equals(workerRouter))
this.getContext().stop(getSelf());
} else {
unhandled(message);
}
/*
//pass through the original token
if (message instanceof TokenWithProv) {
if (((TokenWithProv) message).getActorCreated().equals("MongoDBReader")) {
listener.tell(message, getSelf());
}
}
*/
}
@Override
public void postStop() {
System.out.println("Stopped GeoRefValidator");
listener.tell(new Broadcast(PoisonPill.getInstance()), getSelf());
}
public final static double DEFAULT_CERTAINTY = 20; // km distance within which to accept two points as similar.
}
class GEORefValidatorInvocation extends UntypedActor {
private boolean useCache;
private final ActorRef listener;
private String serviceClassQN;
private IGeoRefValidationService geoRefValidationService;
private double certainty; //the unit is km
private int invoc;
private final Random rand;
private GEORefValidatorInvocation(final String service, final boolean useCache, final double certainty, final ActorRef listener) {
this.serviceClassQN = service;
this.useCache = useCache;
this.certainty = certainty;
this.listener = listener;
this.rand = new Random();
//resolve service
try {
geoRefValidationService = (IGeoRefValidationService)Class.forName(service).newInstance();
geoRefValidationService.setUseCache(useCache);
} catch (InstantiationException e) {
geoRefValidationService = new GeoLocate3();
geoRefValidationService.setUseCache(useCache);
e.printStackTrace();
} catch (IllegalAccessException e) {
geoRefValidationService = new GeoLocate3();
geoRefValidationService.setUseCache(useCache);
e.printStackTrace();
} catch (ClassNotFoundException e) {
geoRefValidationService = new GeoLocate3();
geoRefValidationService.setUseCache(useCache);
e.printStackTrace();
}
}
public static Props props(final String service, final boolean useCache, final double certainty, final ActorRef listener) {
return Props.create(new Creator<GEORefValidatorInvocation>() {
private static final long serialVersionUID = 1L;
@Override
public GEORefValidatorInvocation create() throws Exception {
return new GEORefValidatorInvocation(service, useCache, certainty, listener);
}
});
}
public String getName() {
return "GEORefValidator";
}
public void onReceive(Object message) {
long start = System.currentTimeMillis();
invoc = rand.nextInt();
if (message instanceof TokenWithProv) {
/*Prov.log().printf("datadep\t%s\t%d\t%s\t%d\t%d\t%d\n",
((TokenWithProv) message).getActorCreated(),
((TokenWithProv) message).getInvocCreated(),
this.getClass().getSimpleName(),
invoc,
((TokenWithProv) message).getTimeCreated(),
System.currentTimeMillis()); */
}
if (message instanceof Token) {
if (((Token) message).getData() instanceof SpecimenRecord) {
SpecimenRecord record = (SpecimenRecord) ((Token) message).getData();
//System.err.println("georefstart#"+record.get("oaiid").toString() + "#" + System.currentTimeMillis());
Map<String,String> fields = new HashMap<String,String>();
for (String key : record.keySet()) {
fields.put(key,record.get(key));
}
// TODO: We need an actor to examine country names and country codes
// able to fill in one when the other is missing, and able to identify conflicts.
//if missing, let it run, handle the error in service
String country = record.get("country");
String countryCode = record.get("countryCode");
// Special case handling for GBIF Benin data set which largely lacks the country name.
if (country==null || country.trim().length()==0) {
if (countryCode!=null) {
country = CountryLookup.lookupCountry(countryCode);
}
}
String stateProvince = record.get("stateProvince");
String county = record.get("county");
String locality = record.get("locality");
String waterBody = record.get("waterBody");
String verbatimDepth = record.get("verbatimDepth");
/*
//get the needed information from the input SpecimenRecord
String country = record.get("country");
if(country == null){
CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY,"country is missing in the input",getName());
constructOutput(fields,curationComment);
Prov.log().printf("invocation\t%s\t%d\t%d\t%d\n", this.getClass().getSimpleName(), invoc, start, System.currentTimeMillis());
return;
}
String stateProvince = record.get("stateProvince");
if(stateProvince == null){
CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY,"stateProvinceLabel is missing in the input",getName());
constructOutput(fields, curationComment);
Prov.log().printf("invocation\t%s\t%d\t%d\t%d\n", this.getClass().getSimpleName(), invoc, start, System.currentTimeMillis());
return;
}
String county = record.get("county");
if (county == null){
CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY,"countyLabel is missing in the input",getName());
constructOutput(fields, curationComment);
Prov.log().printf("invocation\t%s\t%d\t%d\t%d\n", this.getClass().getSimpleName(), invoc, start, System.currentTimeMillis());
return;
}
String locality = record.get("locality");
if(locality == null){
CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY,"localityLabel is missing in the input",getName());
constructOutput(fields, curationComment);
Prov.log().printf("invocation\t%s\t%d\t%d\t%d\n", this.getClass().getSimpleName(), invoc, start, System.currentTimeMillis());
return;
}
*/
int isCoordinateMissing = 0;
String latitudeToken = record.get("decimalLatitude");
double latitude = -1;
if (latitudeToken != null && !latitudeToken.isEmpty()){
//if(!(latitudeToken instanceof ScalarToken)){
// CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY,"latitudeLabel of the input is not of scalar type.",getName());
// constructOutput(fields, curationComment);
// return;
//}
try{
latitude = Double.valueOf(latitudeToken);
}catch (Exception e){
System.out.println("latitude token has issue: |" + latitudeToken + "|");
}
}else{
isCoordinateMissing++;
}
String longitudeToken = record.get("decimalLongitude");
double longitude = -1;
if (longitudeToken != null && !longitudeToken.isEmpty()) {
//if(!(longitudeToken instanceof ScalarToken)){
//CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY,"longitudeLabel of the input is not of scalar type.",getName());
//constructOutput(fields, curationComment);
//return;
//}
try{
longitude = Double.valueOf(longitudeToken);
}catch (Exception e){
System.out.println("longitude token has issue: |" + latitudeToken + "|");
}
} else {
isCoordinateMissing++;
}
//invoke the service to parse the locality and return the coordinates
//isCoordinateMissing == 2 means both longitude and latitude are missing
if(isCoordinateMissing == 2){
//geoRefValidationService.validateGeoRef(country, stateProvince, county, locality,null,null,certainty);
CurationCommentType curationComment = CurationComment.construct(CurationComment.UNABLE_DETERMINE_VALIDITY, "Both longitude and latitude are missing in the incoming SpecimenRecord", null);
constructOutput(new SpecimenRecord(fields),curationComment);
return;
}else{
geoRefValidationService.validateGeoRef(country, stateProvince, county, waterBody, verbatimDepth, locality,String.valueOf(latitude),String.valueOf(longitude),certainty);
}
CurationStatus curationStatus = geoRefValidationService.getCurationStatus();
if(curationStatus == CurationComment.CURATED || curationStatus == CurationComment.FILLED_IN){
String originalLat = fields.get(SpecimenRecord.dwc_decimalLatitude);
String originalLng = fields.get(SpecimenRecord.dwc_decimalLongitude);
String newLat = String.valueOf(geoRefValidationService.getCorrectedLatitude());
String newLng = String.valueOf(geoRefValidationService.getCorrectedLongitude());
if(originalLat != null && originalLat.length() != 0 && !originalLat.equals(newLat)){
fields.put(SpecimenRecord.Original_Latitude_Label, originalLat);
fields.put(SpecimenRecord.dwc_decimalLatitude, newLat);
}
if(originalLng != null && originalLng.length() != 0 && !originalLng.equals(newLng)){
fields.put(SpecimenRecord.Original_Longitude_Label, originalLng);
fields.put(SpecimenRecord.dwc_decimalLongitude, newLng);
}
}
//output
//System.out.println("curationStatus = " + curationStatus.toString());
//System.out.println("curationComment = " + curationComment.toString());
CurationCommentType curationComment = CurationComment.construct(curationStatus,geoRefValidationService.getComment(),geoRefValidationService.getServiceName());
constructOutput(fields, curationComment);
for (List l : geoRefValidationService.getLog()) {
//Prov.log().printf("service\t%s\t%d\t%s\t%d\t%d\t%s\t%s\n", this.getClass().getSimpleName(), invoc, (String)l.get(0), (Long)l.get(1), (Long)l.get(2),l.get(3),curationStatus.toString());
}
}
//Prov.log().printf("invocation\t%s\t%d\t%d\t%d\n", this.getClass().getSimpleName(), invoc, start, System.currentTimeMillis());
}
}
private void constructOutput(Map<String, String> result, CurationCommentType comment) {
if (comment != null) {
result.put(SpecimenRecord.geoRef_Status_Label,comment.getStatus());
} else {
result.put(SpecimenRecord.geoRef_Status_Label,CurationComment.CORRECT.toString());
}
result.put(SpecimenRecord.geoRef_Comment_Label,comment.getDetails());
result.put(SpecimenRecord.geoRef_Source_Label,comment.getSource());
SpecimenRecord r = new SpecimenRecord(result);
Token token = new TokenWithProv<SpecimenRecord>(r,getName(),invoc);
//System.err.println("georefend#"+result.get("oaiid").toString() + "#" + System.currentTimeMillis());
listener.tell(token,getContext().parent());
}
}
| 50.902357 | 207 | 0.601799 |
392469309f272b4df16b9c65d429f97469274f1a | 242 | package scloud.rxjava;
import org.junit.jupiter.api.Test;
public class CompletableHelloTest {
@Test
public void test() {
CompletableHello completableHello = new CompletableHello();
completableHello.hello();
}
}
| 18.615385 | 67 | 0.694215 |
99b74e19a90eb18431b975fc140de0c9fd82f42a | 4,599 | package com.cscao.apps.mobirnn.model;
import static com.cscao.apps.mobirnn.helper.DataUtil.alter2Dto1D;
import android.content.Context;
import com.cscao.apps.mobirnn.helper.DataUtil;
import com.cscao.apps.mobirnn.helper.Matrix;
import java.util.Arrays;
/**
* Created by qqcao on 5/11/17Thursday.
*
* LSTM model on CPU
*/
class CpuModel extends AbstractModel {
private float[][] mWIn;
private float[][] mWOut;
private float[][][] mWeights;
private ModelMode mMode;
CpuModel(Context context, int layerSize, int hiddenUnits, ModelMode mode) {
super(context, layerSize, hiddenUnits);
mMode = mode;
transformParams();
}
private void transformParams() {
mWIn = new float[mInputDim][mHiddenUnits];
for (int i = 0; i < mInputDim; i++) {
System.arraycopy(super.mWIn, i * mHiddenUnits, mWIn[i], 0, mHiddenUnits);
}
mWOut = new float[mHiddenUnits][mOutputDim];
for (int i = 0; i < mHiddenUnits; i++) {
System.arraycopy(super.mWOut, i * mOutputDim, mWOut[i], 0, mOutputDim);
}
mWeights = new float[mLayerSize][mHiddenUnits * 2][mHiddenUnits * 4];
for (int k = 0; k < mLayerSize; k++) {
for (int i = 0; i < mHiddenUnits * 2; i++) {
System.arraycopy(super.mRnnWeights[k], i * mHiddenUnits * 4, mWeights[k][i], 0,
mHiddenUnits * 4);
}
}
}
private float[][] calcCellOneStep(float[] in_, float[] c_, float[] h_, int layer) {
// concat in_ and h_ and do xw_plu_b
float[] concat = Matrix.concat(in_, h_);
float[] linearResult = Matrix.vecAddVec(Matrix.vecMulMat(concat, mWeights[layer]),
mRnnBiases[layer]);
float[] i = Matrix.split(linearResult, 4, 0);
float[] j = Matrix.split(linearResult, 4, 1);
float[] f = Matrix.split(linearResult, 4, 2);
float[] o = Matrix.split(linearResult, 4, 3);
int size = c_.length;
for (int k = 0; k < size; k++) {
c_[k] = c_[k] * DataUtil.sigmoid(f[k] + 1) + DataUtil.sigmoid(i[k]) * DataUtil.tanh(
j[k]);
h_[k] = DataUtil.tanh(c_[k]) * DataUtil.sigmoid(o[k]);
}
float[][] state = new float[2][];
state[0] = c_;
state[1] = h_;
return state;
}
@Override
protected int predictLabel(float[] x) {
switch (mMode) {
case CPU:
return predictJavaCpu(x);
case Native:
return predictNativeCpu(x);
case Eigen:
return predictEigenCpu(x);
default:
return predictJavaCpu(x);
}
}
private int predictJavaCpu(float[] input) {
float[][] x = new float[mTimeSteps][mInputDim];
for (int i = 0; i < mTimeSteps; i++) {
System.arraycopy(input, i * mInputDim, x[i], 0, mInputDim);
}
x = DataUtil.relu(Matrix.addVec(Matrix.multiply(x, mWIn), mBIn));
float[] c = new float[mHiddenUnits];
float[] h = new float[mHiddenUnits];
for (int j = 0; j < mLayerSize; j++) {
Arrays.fill(c, 0);
Arrays.fill(h, 0);
for (float[] aX : x) {
float[][] state = calcCellOneStep(aX, c, h, j);
c = state[0];
h = state[1];
System.arraycopy(h, 0, aX, 0, mHiddenUnits);
}
}
float[] outProb = Matrix.vecAddVec(Matrix.vecMulMat(h, mWOut), mBOut);
return DataUtil.argmax(outProb) + 1;
}
private int predictNativeCpu(float[] x) {
return predictNative(x, mLayerSize, mTimeSteps, mHiddenUnits, mInputDim, mOutputDim,
super.mWIn, mBIn, super.mWOut, mBOut, alter2Dto1D(super.mRnnWeights),
alter2Dto1D(mRnnBiases));
}
private int predictEigenCpu(float[] x) {
return predictNativeEigen(x,
new int[]{mLayerSize, mTimeSteps, mHiddenUnits, mInputDim, mOutputDim}, super.mWIn,
mBIn, super.mWOut, mBOut, alter2Dto1D(super.mRnnWeights), alter2Dto1D(mRnnBiases));
}
private native int predictNativeEigen(float[] input, int[] config, float[] wIn, float[] bIn,
float[] wOut, float[] bOut, float[] weights, float[] biases);
private native int predictNative(float[] input, int layer_size,
int time_steps, int hidden_unites, int in_dim, int out_dim, float[] wIn, float[] bIn,
float[] wOut, float[] bOut, float[] weights, float[] biases);
}
| 34.066667 | 99 | 0.56795 |
c759dfe978ed3adf1a1aaac9750dc5779f4e149c | 11,825 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.jdbc;
import org.apache.drill.categories.JdbcStorageTest;
import org.apache.drill.common.logical.security.PlainCredentialsProvider;
import org.apache.drill.common.logical.StoragePluginConfig.AuthMode;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.physical.rowSet.DirectRowSet;
import org.apache.drill.exec.physical.rowSet.RowSet;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.shaded.guava.com.google.common.collect.ImmutableMap;
import org.apache.drill.test.ClusterFixture;
import org.apache.drill.test.ClusterTest;
import org.apache.drill.test.rowSet.RowSetUtilities;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.testcontainers.containers.MSSQLServerContainer;
import java.math.BigDecimal;
import java.util.TimeZone;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* JDBC storage plugin tests against MSSQL. Note that there is no mssql container
* available on aarch64 so these tests must be disabled on that arch.
*/
@Category(JdbcStorageTest.class)
public class TestJdbcPluginWithMSSQL extends ClusterTest {
private static MSSQLServerContainer jdbcContainer;
@BeforeClass
public static void initMSSQL() throws Exception {
Assume.assumeTrue(System.getProperty("os.arch").matches("(amd64|x86_64)"));
startCluster(ClusterFixture.builder(dirTestWatcher));
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
jdbcContainer = new MSSQLServerContainer<>()
.withPassword("B!llyG0atGruff") // must meet mssql's complexity requirements
.withInitScript("mssql-test-data.ms.sql")
.withUrlParam("trustServerCertificate", "true")
.acceptLicense();
jdbcContainer.start();
Map<String, String> credentials = ImmutableMap.<String, String>builder()
.put("username", jdbcContainer.getUsername())
.put("password", jdbcContainer.getPassword())
.build();
PlainCredentialsProvider credentialsProvider = new PlainCredentialsProvider(credentials);
// To test for unimplemented Connection::getSchema (DRILL-8227), we use the jTDS driver
// in this class. The jTDS driver is only at JDBC v3 and so does not support isValid.
// To satisfy Hikari we must therefore specify a connection test query.
Map<String, Object> sourceParms = ImmutableMap.<String, Object>builder()
.put("connectionTestQuery", "select 1")
.build();
JdbcStorageConfig jdbcStorageConfig = new JdbcStorageConfig(
"net.sourceforge.jtds.jdbc.Driver",
jdbcContainer.getJdbcUrl().replaceFirst("jdbc:", "jdbc:jtds:"), // mangle the reported URL for jTDS
null,
null,
true,
false,
sourceParms,
credentialsProvider,
AuthMode.SHARED_USER.name(),
100000
);
jdbcStorageConfig.setEnabled(true);
cluster.defineStoragePlugin("mssql", jdbcStorageConfig);
}
@AfterClass
public static void stopMSSQL() {
if (jdbcContainer != null) {
jdbcContainer.stop();
}
}
@Test
public void validateResult() throws Exception {
String sql = "SELECT person_id, first_name, last_name, address, city, state, zip, " +
"json, bigint_field, smallint_field, decimal_field, bit_field, " +
"double_field, float_field, datetime_field " +
"FROM mssql.dbo.person ORDER BY person_id";
DirectRowSet results = queryBuilder().sql(sql).rowSet();
TupleMetadata expectedSchema = new SchemaBuilder()
.addNullable("person_id", MinorType.INT, 10)
.addNullable("first_name", MinorType.VARCHAR, 38)
.addNullable("last_name", MinorType.VARCHAR, 38)
.addNullable("address", MinorType.VARCHAR, 38)
.addNullable("city", MinorType.VARCHAR, 38)
.addNullable("state", MinorType.VARCHAR, 2)
.addNullable("zip", MinorType.INT, 10)
.addNullable("json", MinorType.VARCHAR, 38)
.addNullable("bigint_field", MinorType.BIGINT, 19)
.addNullable("smallint_field", MinorType.INT, 5)
.addNullable("decimal_field", MinorType.VARDECIMAL, 15, 2)
.addNullable("bit_field", MinorType.BIT, 1)
.addNullable("double_field", MinorType.FLOAT8, 15)
.addNullable("float_field", MinorType.FLOAT8, 15)
// TODO: these two types are mapped to VARCHARS instead of date/time types
//.addNullable("date_field", MinorType.VARCHAR, 10)
//.addNullable("datetime2_field", MinorType.TIMESTAMP, 23, 3)
.addNullable("datetime_field", MinorType.TIMESTAMP, 23, 3)
.buildSchema();
RowSet expected = client.rowSetBuilder(expectedSchema)
.addRow(1, "first_name_1", "last_name_1", "1401 John F Kennedy Blvd",
"Philadelphia", "PA", 19107, "{ a : 5, b : 6 }", 123456789L, 1,
new BigDecimal("123.32"), 1, 1.0, 1.1,
1330520401000L)
.addRow(2, "first_name_2", "last_name_2", "One Ferry Building",
"San Francisco", "CA", 94111, "{ z : [ 1, 2, 3 ] }", 45456767L, 3,
null, 0, 3.0, 3.1,
1319974461000L)
.addRow(3, "first_name_3", "last_name_3", "176 Bowery",
"New York", "NY", 10012, "{ [ a, b, c ] }", 123090L, -3,
null, 1, 5.0, 5.1,
1442936770000L)
.addRow(4, null, null, null, null, null, null, null, null, null,
null, null, null, null, null)
.build();
RowSetUtilities.verify(expected, results);
}
@Test
public void pushDownJoin() throws Exception {
String query = "select x.person_id from (select person_id from mssql.dbo.person) x "
+ "join (select person_id from mssql.dbo.person) y on x.person_id = y.person_id";
queryBuilder()
.sql(query)
.planMatcher()
.exclude("Join")
.match();
}
@Test
public void pushDownJoinAndFilterPushDown() throws Exception {
String query = "select * from " +
"mssql.dbo.person e " +
"INNER JOIN " +
"mssql.dbo.person s " +
"ON e.first_name = s.first_name " +
"WHERE e.last_name > 'hello'";
queryBuilder()
.sql(query)
.planMatcher()
.exclude("Join", "Filter")
.match();
}
@Test
public void testPhysicalPlanSubmission() throws Exception {
String query = "select * from mssql.dbo.person";
String plan = queryBuilder().sql(query).explainJson();
assertEquals(4, queryBuilder().physical(plan).run().recordCount());
}
@Test
public void emptyOutput() {
String query = "select * from mssql.dbo.person e limit 0";
testBuilder()
.sqlQuery(query)
.expectsEmptyResultSet();
}
@Test
public void testExpressionsWithoutAlias() throws Exception {
String sql = "select count(*), 1+1+2+3+5+8+13+21+34, (1+sqrt(5))/2\n" +
"from mssql.dbo.person";
DirectRowSet results = queryBuilder().sql(sql).rowSet();
TupleMetadata expectedSchema = new SchemaBuilder()
.addNullable("EXPR$0", MinorType.INT, 10)
.addNullable("EXPR$1", MinorType.INT, 10)
.addNullable("EXPR$2", MinorType.FLOAT8, 15)
.build();
RowSet expected = client.rowSetBuilder(expectedSchema)
.addRow(4L, 88L, 1.618033988749895)
.build();
RowSetUtilities.verify(expected, results);
}
@Test
public void testExpressionsWithoutAliasesPermutations() throws Exception {
String query = "select EXPR$1, EXPR$0, EXPR$2\n" +
"from (select 1+1+2+3+5+8+13+21+34, (1+sqrt(5))/2, count(*) from mssql.dbo.person)";
testBuilder()
.sqlQuery(query)
.unOrdered()
.baselineColumns("EXPR$1", "EXPR$0", "EXPR$2")
.baselineValues(1.618033988749895, 88, 4)
.go();
}
@Test
public void testExpressionsWithAliases() throws Exception {
String query = "SELECT person_id AS ID, 1+1+2+3+5+8+13+21+34 as FIBONACCI_SUM, (1+sqrt(5))/2 as golden_ratio\n" +
"FROM mssql.dbo.person limit 2";
testBuilder()
.sqlQuery(query)
.unOrdered()
.baselineColumns("ID", "FIBONACCI_SUM", "golden_ratio")
.baselineValues(1, 88, 1.618033988749895)
.baselineValues(2, 88, 1.618033988749895)
.go();
}
@Test
public void testJoinStar() throws Exception {
String query = "select * from (select person_id from mssql.dbo.person) t1 join " +
"(select person_id from mssql.dbo.person) t2 on t1.person_id = t2.person_id";
testBuilder()
.sqlQuery(query)
.unOrdered()
.baselineColumns("person_id", "person_id0")
.baselineValues(1, 1)
.baselineValues(2, 2)
.baselineValues(3, 3)
.baselineValues(4, 4)
.go();
}
@Test
public void testSemiJoin() throws Exception {
String query =
"select person_id from mssql.dbo.person t1\n" +
"where exists (" +
"select person_id from mssql.dbo.person\n" +
"where t1.person_id = person_id)";
testBuilder()
.sqlQuery(query)
.unOrdered()
.baselineColumns("person_id")
.baselineValuesForSingleColumn(1, 2, 3, 4)
.go();
}
@Test
public void testInformationSchemaViews() throws Exception {
String query = "select * from information_schema.`views`";
run(query);
}
@Test
public void testJdbcTableTypes() throws Exception {
String query = "select distinct table_type from information_schema.`tables` " +
"where table_schema like 'mssql%'";
testBuilder()
.sqlQuery(query)
.unOrdered()
.baselineColumns("table_type")
.baselineValuesForSingleColumn("TABLE", "VIEW")
.go();
}
// DRILL-8090
@Test
public void testLimitPushDown() throws Exception {
String query = "select person_id, first_name, last_name from mssql.dbo.person limit 100";
queryBuilder()
.sql(query)
.planMatcher()
.include("Jdbc\\(.*SELECT TOP \\(100\\)")
.exclude("Limit\\(")
.match();
}
@Test
public void testLimitPushDownWithOrderBy() throws Exception {
String query = "select person_id from mssql.dbo.person order by first_name limit 100";
queryBuilder()
.sql(query)
.planMatcher()
.include("Jdbc\\(.*SELECT TOP \\(100\\).*ORDER BY.*\"first_name\"")
.exclude("Limit\\(")
.match();
}
@Test
@Ignore
// TODO: Enable once the push down logic has been clarified.
public void testLimitPushDownWithOffset() throws Exception {
String query = "select person_id, first_name from mssql.dbo.person limit 100 offset 10";
queryBuilder()
.sql(query)
.planMatcher()
.include("Jdbc\\(.*SELECT TOP \\(110\\)")
.include("Limit\\(")
.match();
}
@Test
public void testLimitPushDownWithConvertFromJson() throws Exception {
String query = "select convert_fromJSON(first_name)['ppid'] from mssql.dbo.person LIMIT 100";
queryBuilder()
.sql(query)
.planMatcher()
.include("Jdbc\\(.*SELECT TOP \\(100\\)")
.exclude("Limit\\(")
.match();
}
}
| 34.475219 | 117 | 0.675349 |
f1c8392cd0fa4c53e0da15c36467ec313421b084 | 4,884 | package com.vdcodeassociate.simpleregistrationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static com.vdcodeassociate.simpleregistrationapp.R.*;
public class DashboardActivity extends AppCompatActivity {
LinearLayout linearLayout,profileButton;
private FirebaseAuth firebaseAuth;
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_dashboard);
firebaseAuth = FirebaseAuth.getInstance();
linearLayout = findViewById(R.id.linearLayoutDashBoard);
profileButton = findViewById(R.id.CardLinearLayout1);
Toolbar toolbar = findViewById(R.id.DashboardToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Dashboard");
checkEmailVerification();
profileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(DashboardActivity.this,MyProfileActivity.class);
startActivity(intent);
}
});
//dialog
dialog = new Dialog(DashboardActivity.this);
dialog.setContentView(R.layout.email_verification_dialog);
dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.dialog_background_drawable));
dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
Button sendButton = dialog.findViewById(R.id.sendEmailButton);
TextView skipButton = dialog.findViewById(R.id.SkipTextView2);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmailVerification();
dialog.dismiss();
}
});
skipButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
private void checkEmailVerification(){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser != null){
if(!firebaseUser.isEmailVerified()){
Snackbar.make(linearLayout,"Email not verified!",Snackbar.LENGTH_LONG)
.setAction("Click to verify", new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
}).setActionTextColor(getResources().getColor(color.custom_red))
.show();
}
}
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser != null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Verification mail sent!Re-login after verify...",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext()," Verification mail hasn't been sent!..!......",Toast.LENGTH_SHORT).show();
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case id.logout_user:
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(),SignINActivity.class);
startActivity(intent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
} | 36.177778 | 140 | 0.638411 |
3275e275c8c29d2be53c9fd60663fa85f82f3cdb | 3,443 | /*
* Copyright 2013 University of Glasgow.
*
* 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 broadwick.abc;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
/**
* This class runs an approximate Bayesian computation, sampling from the posterior.
*/
public class ApproxBayesianComp {
/**
* Create an ABC instance. The created instance will be ready to run a calculation using the default controller and
* distance measure, these will need to be set if custom ones are required.
* @param observedData the observed data from which the distance will be calculated.
* @param model the model that generates the data.
* @param priors the sampler objec that samples from the priors.
* @param sensitivity the distance cutoff, distance greater than this value will be ignored.
*/
public ApproxBayesianComp(final AbcNamedQuantity observedData, final AbcModel model,
final AbcPriorsSampler priors, final double sensitivity) {
this.posteriors = new LinkedHashMap<>();
this.observedData = observedData;
this.model = model;
this.priors = priors;
this.epsilon = sensitivity;
numSamplesTaken = 0;
}
/**
* Run the ABC algorithm.
*/
public final void run() {
while (controller.goOn(this)) {
final AbcNamedQuantity parameters = priors.sample();
numSamplesTaken++;
final AbcNamedQuantity generatedData = model.run(parameters);
if (distance.calculate(generatedData, observedData) < epsilon) {
save(parameters);
}
}
}
/**
* Save the sample taken from the prior as it meets the criteria set for being a posterior sample.
* @param prior the sampled values from the prior.
*/
private void save(final AbcNamedQuantity prior) {
if (posteriors.isEmpty()) {
for (Map.Entry<String, Double> entry : prior.getParameters().entrySet()) {
final LinkedList<Double> vals = new LinkedList<>();
vals.add(entry.getValue());
posteriors.put(entry.getKey(), vals);
}
} else {
for (Map.Entry<String, Double> entry : prior.getParameters().entrySet()) {
posteriors.get(entry.getKey()).add(entry.getValue());
}
}
}
@Setter
private AbcController controller = new AbcMaxNumStepController();
@Setter
private AbcDistance distance = new AbcAbsDistance();
private AbcModel model;
private AbcPriorsSampler priors;
@Getter
private Map<String, LinkedList<Double>> posteriors;
private AbcNamedQuantity observedData;
private double epsilon;
@Getter
@SuppressWarnings("PMD.UnusedPrivateField")
private int numSamplesTaken;
}
| 35.864583 | 119 | 0.661632 |
e6db073399d1c4b0e74c27950274fd2037d95fec | 366 | package com.github.mybatis.generator.gonggongwenjian;
/**
* 前后端交互携带的请求头
*
* @version : RequestHeadConstant.java 2020年12月09日 15:49
*/
public class RequestHeadConstant {
/**
* 登录Token COOKIE名称
*/
public static final String DMS_NAME_TOKEN = "TOKEN";
/**
* 登录user COOKIE名称
*/
public static final String DMS_NAME_USER = "USER";
}
| 20.333333 | 56 | 0.666667 |
085fe3e12474b024afe661aa428f2e4b7afa57d2 | 1,024 | package cap12.pag273;
import javax.swing.*;
import java.awt.*;
public class SimpleAnimation {
int x = 70;
int y = 70;
public static void main(String[] args) {
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);
for (int i = 0; i < 130; i++) {
x++;
y++;
drawPanel.repaint();
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
} // fecha o método go()
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
} // fecha classe interna
} // fecha classe externa
| 21.333333 | 61 | 0.53418 |
6e3d3daecac697fced9bd102d13c9e10e3d19419 | 5,800 | package com.tlongdev.bktf.adapter;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.tlongdev.bktf.BptfApplication;
import com.tlongdev.bktf.R;
import com.tlongdev.bktf.data.DatabaseContract.ItemSchemaEntry;
import com.tlongdev.bktf.data.DatabaseContract.PriceEntry;
import com.tlongdev.bktf.model.Item;
import com.tlongdev.bktf.model.Price;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Adapter for the recycler view in the recents fragment.
*/
public class RecentsAdapter extends CursorRecyclerViewAdapter<RecentsAdapter.ViewHolder> {
@Inject Context mContext;
private OnMoreListener mListener;
public RecentsAdapter(BptfApplication application) {
super(application, null);
application.getAdapterComponent().inject(this);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_recents, parent, false);
return new ViewHolder(v);
}
@SuppressWarnings("WrongConstant")
@Override
public void onBindViewHolder(ViewHolder holder, Cursor cursor) {
Price price = new Price();
price.setValue(cursor.getDouble(cursor.getColumnIndex(PriceEntry.COLUMN_PRICE)));
price.setHighValue(cursor.getDouble(cursor.getColumnIndex(PriceEntry.COLUMN_PRICE_HIGH)));
price.setDifference(cursor.getDouble(cursor.getColumnIndex(PriceEntry.COLUMN_DIFFERENCE)));
price.setCurrency(cursor.getString(cursor.getColumnIndex(PriceEntry.COLUMN_CURRENCY)));
price.setRawValue(cursor.getDouble(cursor.getColumnIndex("raw_price")));
//Get all the data from the cursor
final Item item = new Item();
item.setDefindex(cursor.getInt(cursor.getColumnIndex(PriceEntry.COLUMN_DEFINDEX)));
item.setName(cursor.getString(cursor.getColumnIndex(ItemSchemaEntry.COLUMN_ITEM_NAME)));
item.setImage(cursor.getString(cursor.getColumnIndex(ItemSchemaEntry.COLUMN_IMAGE)));
item.setQuality(cursor.getInt(cursor.getColumnIndex(PriceEntry.COLUMN_ITEM_QUALITY)));
item.setTradable(cursor.getInt(cursor.getColumnIndex(PriceEntry.COLUMN_ITEM_TRADABLE)) == 1);
item.setCraftable(cursor.getInt(cursor.getColumnIndex(PriceEntry.COLUMN_ITEM_CRAFTABLE)) == 1);
item.setAustralium(cursor.getInt(cursor.getColumnIndex(PriceEntry.COLUMN_AUSTRALIUM)) == 1);
item.setPriceIndex(cursor.getInt(cursor.getColumnIndex(PriceEntry.COLUMN_PRICE_INDEX)));
item.setPrice(price);
holder.name.setSelected(false);
holder.root.setOnClickListener(v -> {
holder.name.setSelected(false);
holder.name.setSelected(true);
});
holder.more.setOnClickListener(v -> {
if (mListener != null) {
mListener.onMoreClicked(v, item);
}
});
holder.name.setText(item.getFormattedName(mContext, false));
//Set the change indicator of the item
holder.difference.setTextColor(item.getPrice().getDifferenceColor());
holder.difference.setText(item.getPrice().getFormattedDifference(mContext));
holder.icon.setImageDrawable(null);
holder.quality.setBackgroundColor(item.getColor(mContext, true));
if (!item.isTradable()) {
if (!item.isCraftable()) {
holder.quality.setImageResource(R.drawable.uncraft_untrad);
} else {
holder.quality.setImageResource(R.drawable.untrad);
}
} else if (!item.isCraftable()) {
holder.quality.setImageResource(R.drawable.uncraft);
} else {
holder.quality.setImageResource(0);
}
//Set the item icon
Glide.with(mContext)
.load(item.getIconUrl(mContext))
.transition(DrawableTransitionOptions.withCrossFade())
.into(holder.icon);
if (item.getPriceIndex() != 0 && item.canHaveEffects()) {
Glide.with(mContext)
.load(item.getEffectUrl())
.transition(DrawableTransitionOptions.withCrossFade())
.into(holder.effect);
} else {
Glide.with(mContext).clear(holder.effect);
holder.effect.setImageDrawable(null);
}
try {
//Properly format the price
holder.price.setText(item.getPrice().getFormattedPrice(mContext));
} catch (Throwable t) {
t.printStackTrace();
}
}
public void setListener(OnMoreListener listener) {
mListener = listener;
}
/**
* The view holder.
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
final View root;
@BindView(R.id.more) View more;
@BindView(R.id.icon) ImageView icon;
@BindView(R.id.effect) ImageView effect;
@BindView(R.id.quality) ImageView quality;
@BindView(R.id.name) TextView name;
@BindView(R.id.price) TextView price;
@BindView(R.id.difference) TextView difference;
public ViewHolder(View view) {
super(view);
root = view;
ButterKnife.bind(this, view);
}
}
public interface OnMoreListener {
void onMoreClicked(View view, Item item);
}
} | 37.179487 | 103 | 0.674828 |
6bf161e300f10108a7c8f8e9c6edece543520c3f | 1,822 | package voss.multilayernms.inventory.nmscore.model.creator;
import jp.iiga.nmt.core.model.MetaData;
import jp.iiga.nmt.core.model.PhysicalLink;
import naef.dto.LinkDto;
import naef.dto.ip.IpSubnetDto;
import voss.multilayernms.inventory.config.NmsCoreLinkConfiguration;
import voss.multilayernms.inventory.nmscore.rendering.LinkRenderingUtil;
import voss.multilayernms.inventory.renderer.L2LinkRenderer;
import voss.multilayernms.inventory.renderer.LinkRenderer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class LinkModelCreator {
public static PhysicalLink createModel(IpSubnetDto link, String inventoryId) throws IOException {
PhysicalLink model = new PhysicalLink();
Map<String, Object> properties = new HashMap<String, Object>();
for (String key : NmsCoreLinkConfiguration.getInstance().getPropertyFields()) {
properties.put(key, LinkRenderingUtil.rendering(link, key));
}
MetaData data = new MetaData();
data.setProperties(properties);
model.setMetaData(data);
model.setId(inventoryId);
model.setText(LinkRenderer.getName(link));
return model;
}
public static PhysicalLink createModel(LinkDto link, String inventoryId) throws IOException {
PhysicalLink model = new PhysicalLink();
Map<String, Object> properties = new HashMap<String, Object>();
for (String key : NmsCoreLinkConfiguration.getInstance().getPropertyFields()) {
properties.put(key, LinkRenderingUtil.rendering(link, key));
}
MetaData data = new MetaData();
data.setProperties(properties);
model.setMetaData(data);
model.setId(inventoryId);
model.setText(L2LinkRenderer.getName(link));
return model;
}
} | 35.038462 | 101 | 0.719539 |
3839fe2662977d4d56fd777280c05934e2c934d1 | 1,092 | package com.es.projector.net;
import com.es.projector.common.Constants;
import com.es.projector.net.rmi.ShareService;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.regex.Pattern;
public class Client {
public static Client client;
private Client() {}
public static Client init() {
if (Client.client == null) {
Client.client = new Client();
}
return Client.client;
}
public ShareService connect(String projectorId) throws NotBoundException, RemoteException {
String networkAddress = NetworkSession.instance().getHostFromSessionId(projectorId);
System.setProperty("java.rmi.server.hostname", networkAddress);
String[] sessionData = projectorId.split(Pattern.quote("-"));
Registry registry = LocateRegistry.getRegistry(networkAddress);
return (ShareService) registry
.lookup(String.format(Constants.Stream.RMI_REGISTRY, networkAddress, sessionData[1]));
}
}
| 32.117647 | 102 | 0.714286 |
371b5a265be5fb9a8d1c51bc3e24c0f919fe20f0 | 1,773 | /**
* Copyright (C), 2015-2020,
* FileName: XinXiJiaoHuZhuTiPage
* Author: 呵呵哒
* Date: 2020/6/20 16:14
* Description:
*/
package org.springblade.anbiao.zhengfu.page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springblade.common.BasePage;
/**
* @创建人 hyp
* @创建时间 2020/6/20
* @描述
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "ZhengFuBaoJingTongJiJieSuanPage对象", description = "ZhengFuBaoJingTongJiJieSuanPage对象")
public class ZhengFuBaoJingTongJiJieSuanPage<T> extends BasePage<T> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "deptId")
private String deptId;
@ApiModelProperty(value = "deptName")
private String deptName;
@ApiModelProperty(value = "开始时间", required = true)
private String begintime;
@ApiModelProperty(value = "结束时间", required = true)
private String endtime;
@ApiModelProperty(value = "xiaJiDeptId")
private String xiaJiDeptId;
@ApiModelProperty(value = "是否处理('',未处理,已处理)")
private String shifouchuli;
@ApiModelProperty(value = "是否申诉('',未申诉,已申诉)")
private String shifoushenshu;
@ApiModelProperty(value = "车辆牌照")
private String cheliangpaizhao;
@ApiModelProperty(value = "营运类型")
private String shiyongxingzhi;
@ApiModelProperty(value = "报警类型")
private String alarmtype;
@ApiModelProperty(value = "排序字段")
private String orderColumns;
@ApiModelProperty(value = "区分地区、企业报警排名")
private String leiXing;
@ApiModelProperty(value = "政府ID ")
private String zhengfuid;
@ApiModelProperty(value = "省ID ")
private String province;
@ApiModelProperty(value = "市ID ")
private String city;
@ApiModelProperty(value = "县ID ")
private String country;
}
| 23.025974 | 105 | 0.747885 |
3795b77164b405a8d711212235cf973dabcd716b | 3,633 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.spring.sample.cosmos.multi.database.multiple.account;
import com.azure.cosmos.models.PartitionKey;
import com.azure.spring.data.cosmos.core.CosmosTemplate;
import com.azure.spring.data.cosmos.core.ReactiveCosmosTemplate;
import com.azure.spring.data.cosmos.repository.support.CosmosEntityInformation;
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.cosmos.CosmosUser;
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.cosmos.CosmosUserRepository;
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.mysql.MysqlUser;
import com.azure.spring.sample.cosmos.multi.database.multiple.account.repository.mysql.MysqlUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@SpringBootApplication
public class MultiDatabaseApplication implements CommandLineRunner {
@Autowired
private CosmosUserRepository cosmosUserRepository;
@Autowired
private MysqlUserRepository mysqlUserRepository;
@Autowired
@Qualifier("secondaryDatabaseTemplate")
private CosmosTemplate secondaryDatabaseTemplate;
@Autowired
@Qualifier("primaryDatabaseTemplate")
private ReactiveCosmosTemplate primaryDatabaseTemplate;
private final CosmosUser cosmosUser = new CosmosUser("1024", "[email protected]", "1k", "Mars");
private static CosmosEntityInformation<CosmosUser, String> userInfo = new CosmosEntityInformation<>(CosmosUser.class);
public static void main(String[] args) {
SpringApplication.run(MultiDatabaseApplication.class, args);
}
public void run(String... var1) throws Exception {
CosmosUser cosmosUserGet = primaryDatabaseTemplate.findById(cosmosUser.getId(), cosmosUser.getClass()).block();
// Same to this.cosmosUserRepository.findById(cosmosUser.getId()).block();
MysqlUser mysqlUser = new MysqlUser(cosmosUserGet.getId(), cosmosUserGet.getEmail(), cosmosUserGet.getName(), cosmosUserGet.getAddress());
mysqlUserRepository.save(mysqlUser);
mysqlUserRepository.findAll().forEach(System.out::println);
CosmosUser secondaryCosmosUserGet = secondaryDatabaseTemplate.findById(CosmosUser.class.getSimpleName(), cosmosUser.getId(), CosmosUser.class);
System.out.println(secondaryCosmosUserGet);
}
@PostConstruct
public void setup() {
primaryDatabaseTemplate.createContainerIfNotExists(userInfo).block();
primaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName())).block();
// Same to this.cosmosUserRepository.save(user).block();
secondaryDatabaseTemplate.createContainerIfNotExists(userInfo);
secondaryDatabaseTemplate.insert(CosmosUser.class.getSimpleName(), cosmosUser, new PartitionKey(cosmosUser.getName()));
}
@PreDestroy
public void cleanup() {
primaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName(), CosmosUser.class).block();
// Same to this.cosmosUserRepository.deleteAll().block();
secondaryDatabaseTemplate.deleteAll(CosmosUser.class.getSimpleName() , CosmosUser.class);
mysqlUserRepository.deleteAll();
}
}
| 47.802632 | 151 | 0.785301 |
acfb2a095f7e1f578b3c9635566f5f9dc8db491f | 5,139 | package ch.idsia.agents.controllers;
import ch.idsia.benchmark.mario.engine.LevelScene;
import ch.idsia.benchmark.mario.engine.SimulatorOptions;
import ch.idsia.benchmark.mario.engine.SimulatorOptions.ReceptiveFieldMode;
import ch.idsia.benchmark.mario.engine.VisualizationComponent;
import ch.idsia.benchmark.mario.engine.input.MarioCheaterKeyboard;
import ch.idsia.benchmark.mario.engine.input.MarioInput;
import ch.idsia.benchmark.mario.engine.input.MarioKey;
import ch.idsia.benchmark.mario.environments.IEnvironment;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* Splits {@link #actionSelection()} into {@link #actionSelectionAI()} done by AGENT
* and {@link #actionSelectionKeyboard()} done by {@link #keyboard}.
*
* @author Jakub 'Jimmy' Gemrot, [email protected]
*/
public class MarioHijackAIBase extends MarioAIBase implements KeyListener, IMarioDebugDraw {
protected MarioCheaterKeyboard keyboard = new MarioCheaterKeyboard();
protected boolean hijacked = false;
@Override
public final MarioInput actionSelection() {
if (hijacked) return actionSelectionKeyboard();
return actionSelectionAI();
}
public MarioInput actionSelectionAI() {
return action;
}
public MarioInput actionSelectionKeyboard() {
return keyboard.getInput();
}
@Override
public void debugDraw(VisualizationComponent vis, LevelScene level, IEnvironment env, Graphics g) {
if (hijacked) {
MarioInput ai = actionSelectionAI();
if (ai != null) {
String msg = "AGENT KEYS: ";
boolean first = true;
for (MarioKey pressedKey : ai.getPressed()) {
if (first) first = false;
else msg += " ";
msg += pressedKey.getDebug();
}
VisualizationComponent.drawStringDropShadow(g, msg, 0, 8, 6);
}
}
}
@Override
public void keyTyped(KeyEvent e) {
keyboard.keyTyped(e);
}
public void keyPressed(KeyEvent e) {
toggleKey(e, true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e, false);
}
protected void toggleKey(KeyEvent e, boolean isPressed) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_H:
if (isPressed) hijacked = !hijacked;
return;
// CHEATS!
case KeyEvent.VK_D:
if (isPressed) SimulatorOptions.gameViewerTick();
return;
case KeyEvent.VK_V:
if (isPressed) SimulatorOptions.isVisualization = !SimulatorOptions.isVisualization;
return;
case KeyEvent.VK_O:
if (isPressed) {
SimulatorOptions.areFrozenCreatures = !SimulatorOptions.areFrozenCreatures;
}
return;
case KeyEvent.VK_L:
if (isPressed) SimulatorOptions.areLabels = !SimulatorOptions.areLabels;
return;
case KeyEvent.VK_C:
if (isPressed) SimulatorOptions.isCameraCenteredOnMario = !SimulatorOptions.isCameraCenteredOnMario;
return;
case 61:
if (isPressed) {
++SimulatorOptions.FPS;
SimulatorOptions.FPS = (SimulatorOptions.FPS > SimulatorOptions.MaxFPS ? SimulatorOptions.MaxFPS : SimulatorOptions.FPS);
SimulatorOptions.AdjustMarioVisualComponentFPS();
}
return;
case 45:
if (isPressed) {
--SimulatorOptions.FPS;
SimulatorOptions.FPS = (SimulatorOptions.FPS < 1 ? 1 : SimulatorOptions.FPS);
SimulatorOptions.AdjustMarioVisualComponentFPS();
}
return;
case KeyEvent.VK_G:
if (isPressed) {
SimulatorOptions.receptiveFieldMode = ReceptiveFieldMode.getForCode(SimulatorOptions.receptiveFieldMode.getCode() + 1);
}
return;
case KeyEvent.VK_P:
case KeyEvent.VK_SPACE:
if (isPressed) {
SimulatorOptions.isGameplayStopped = !SimulatorOptions.isGameplayStopped;
}
return;
case KeyEvent.VK_F:
if (isPressed) {
SimulatorOptions.isFly = !SimulatorOptions.isFly;
}
return;
case KeyEvent.VK_Z:
if (isPressed) {
SimulatorOptions.changeScale2x();
}
return;
case KeyEvent.VK_R:
if (isPressed) {
SimulatorOptions.isRecording = !SimulatorOptions.isRecording;
}
return;
}
// NOT HANDLED YET
// => ask keyboard
if (isPressed) keyboard.keyPressed(e);
else keyboard.keyReleased(e);
}
}
| 35.19863 | 141 | 0.579296 |
12bb1e052c91594e734f0ba0329c9ebc4662a565 | 11,914 | package com.rtbhouse.utils.avro;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import org.apache.avro.Schema;
import org.apache.avro.SchemaNormalization;
import org.apache.avro.io.parsing.Symbol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
public abstract class FastDeserializerGeneratorBase<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(FastDeserializerGeneratorBase.class);
public static final String GENERATED_PACKAGE_NAME = "com.rtbhouse.utils.avro.deserialization.generated";
public static final String GENERATED_SOURCES_PATH = "/com/rtbhouse/utils/avro/deserialization/generated/";
protected JCodeModel codeModel;
protected JDefinedClass deserializerClass;
protected final Schema writer;
protected final Schema reader;
private File destination;
private ClassLoader classLoader;
private String compileClassPath;
FastDeserializerGeneratorBase(Schema writer, Schema reader, File destination, ClassLoader classLoader,
String compileClassPath) {
this.writer = writer;
this.reader = reader;
this.destination = destination;
this.classLoader = classLoader;
this.compileClassPath = compileClassPath;
codeModel = new JCodeModel();
}
public abstract FastDeserializer<T> generateDeserializer();
@SuppressWarnings("unchecked")
protected Class<FastDeserializer<T>> compileClass(final String className) throws IOException,
ClassNotFoundException {
final OutputStream infoLoggingStream = LoggingOutputStream.infoLoggingStream(LOGGER);
final OutputStream errorLoggingStream = LoggingOutputStream.errorLoggingStream(LOGGER);
codeModel.build(destination, new PrintStream(infoLoggingStream));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new FastDeserializerGeneratorException("no system java compiler is available");
}
int compileResult;
if (compileClassPath != null) {
compileResult = compiler.run(
null,
infoLoggingStream,
errorLoggingStream,
"-cp",
compileClassPath,
destination.getAbsolutePath() + GENERATED_SOURCES_PATH + className + ".java"
);
} else {
compileResult = compiler.run(
null,
infoLoggingStream,
errorLoggingStream,
destination.getAbsolutePath() + GENERATED_SOURCES_PATH + className + ".java");
}
if (compileResult != 0) {
throw new FastDeserializerGeneratorException("unable to compile: " + className);
}
return (Class<FastDeserializer<T>>) classLoader.loadClass(GENERATED_PACKAGE_NAME + "."
+ className);
}
protected ListIterator<Symbol> actionIterator(FieldAction action) {
ListIterator<Symbol> actionIterator = null;
if (action.getSymbolIterator() != null) {
actionIterator = action.getSymbolIterator();
} else if (action.getSymbol().production != null) {
actionIterator = Lists.newArrayList(reverseSymbolArray(action.getSymbol().production))
.listIterator();
} else {
actionIterator = Collections.emptyListIterator();
}
while (actionIterator.hasNext()) {
Symbol symbol = actionIterator.next();
if (symbol instanceof Symbol.ErrorAction) {
throw new FastDeserializerGeneratorException(((Symbol.ErrorAction) symbol).msg);
}
if (symbol instanceof Symbol.FieldOrderAction) {
break;
}
}
return actionIterator;
}
protected void forwardToExpectedDefault(ListIterator<Symbol> symbolIterator) {
Symbol symbol;
while (symbolIterator.hasNext()) {
symbol = symbolIterator.next();
if (symbol instanceof Symbol.ErrorAction) {
throw new FastDeserializerGeneratorException(((Symbol.ErrorAction) symbol).msg);
}
if (symbol instanceof Symbol.DefaultStartAction) {
return;
}
}
throw new FastDeserializerGeneratorException("DefaultStartAction symbol expected!");
}
protected FieldAction seekFieldAction(boolean shouldReadCurrent, Schema.Field field,
ListIterator<Symbol> symbolIterator) {
Schema.Type type = field.schema().getType();
if (!shouldReadCurrent) {
return FieldAction.fromValues(type, false, EMPTY_SYMBOL);
}
boolean shouldRead = true;
Symbol fieldSymbol = END_SYMBOL;
if (Schema.Type.RECORD.equals(type)) {
if (symbolIterator.hasNext()) {
fieldSymbol = symbolIterator.next();
if (fieldSymbol instanceof Symbol.SkipAction) {
return FieldAction.fromValues(type, false, fieldSymbol);
} else {
symbolIterator.previous();
}
}
return FieldAction.fromValues(type, true, symbolIterator);
}
while (symbolIterator.hasNext()) {
Symbol symbol = symbolIterator.next();
if (symbol instanceof Symbol.ErrorAction) {
throw new FastDeserializerGeneratorException(((Symbol.ErrorAction) symbol).msg);
}
if (symbol instanceof Symbol.SkipAction) {
shouldRead = false;
fieldSymbol = symbol;
break;
}
if (symbol instanceof Symbol.WriterUnionAction) {
if (symbolIterator.hasNext()) {
symbol = symbolIterator.next();
if (symbol instanceof Symbol.Alternative) {
shouldRead = true;
fieldSymbol = symbol;
break;
}
}
}
if (symbol.kind == Symbol.Kind.TERMINAL) {
shouldRead = true;
if (symbolIterator.hasNext()) {
symbol = symbolIterator.next();
if (symbol instanceof Symbol.Repeater) {
fieldSymbol = symbol;
} else {
fieldSymbol = symbolIterator.previous();
}
} else if (!symbolIterator.hasNext() && getSymbolPrintName(symbol) != null) {
fieldSymbol = symbol;
}
break;
}
}
return FieldAction.fromValues(type, shouldRead, fieldSymbol);
}
protected static final class FieldAction {
private Schema.Type type;
private boolean shouldRead;
private Symbol symbol;
private ListIterator<Symbol> symbolIterator;
private FieldAction(Schema.Type type, boolean shouldRead, Symbol symbol) {
this.type = type;
this.shouldRead = shouldRead;
this.symbol = symbol;
}
private FieldAction(Schema.Type type, boolean shouldRead, ListIterator<Symbol> symbolIterator) {
this.type = type;
this.shouldRead = shouldRead;
this.symbolIterator = symbolIterator;
}
public Schema.Type getType() {
return type;
}
public boolean getShouldRead() {
return shouldRead;
}
public Symbol getSymbol() {
return symbol;
}
public ListIterator<Symbol> getSymbolIterator() {
return symbolIterator;
}
public static FieldAction fromValues(Schema.Type type, boolean read, Symbol symbol) {
return new FieldAction(type, read, symbol);
}
public static FieldAction fromValues(Schema.Type type, boolean read, ListIterator<Symbol> symbolIterator) {
return new FieldAction(type, read, symbolIterator);
}
}
protected static final Symbol EMPTY_SYMBOL = new Symbol(Symbol.Kind.TERMINAL, new Symbol[] {}) {
};
protected static final Symbol END_SYMBOL = new Symbol(Symbol.Kind.TERMINAL, new Symbol[] {}) {
};
protected static Symbol[] reverseSymbolArray(Symbol[] symbols) {
Symbol[] reversedSymbols = new Symbol[symbols.length];
for (int i = 0; i < symbols.length; i++) {
reversedSymbols[symbols.length - i - 1] = symbols[i];
}
return reversedSymbols;
}
public static String getClassName(Schema writerSchema, Schema readerSchema, String description) {
Integer writerSchemaId = Math.abs(getSchemaId(writerSchema));
Integer readerSchemaId = Math.abs(getSchemaId(readerSchema));
if (Schema.Type.RECORD.equals(readerSchema.getType())) {
return readerSchema.getName() + description + "Deserializer"
+ writerSchemaId + "_" + readerSchemaId;
} else if (Schema.Type.ARRAY.equals(readerSchema.getType())) {
return "Array" + description + "Deserializer"
+ writerSchemaId + "_" + readerSchemaId;
} else if (Schema.Type.MAP.equals(readerSchema.getType())) {
return "Map" + description + "Deserializer"
+ writerSchemaId + "_" + readerSchemaId;
}
throw new FastDeserializerGeneratorException("Unsupported return type: " + readerSchema.getType());
}
protected static String getVariableName(String name) {
return name + nextRandomInt();
}
protected static String getSymbolPrintName(Symbol symbol) {
String printName;
try {
Field field = symbol.getClass().getDeclaredField("printName");
field.setAccessible(true);
printName = (String) field.get(symbol);
field.setAccessible(false);
} catch (ReflectiveOperationException e) {
throw new FastDeserializerGeneratorException(e);
}
return printName;
}
private static final Map<Schema, Integer> SCHEMA_IDS_CACHE = new ConcurrentHashMap<>();
private static final HashFunction HASH_FUNCTION = Hashing.murmur3_128();
public static int getSchemaId(Schema schema) {
Integer schemaId = SCHEMA_IDS_CACHE.get(schema);
if (schemaId == null) {
String schemaString = SchemaNormalization.toParsingForm(schema);
schemaId = HASH_FUNCTION.hashString(schemaString, Charsets.UTF_8).asInt();
SCHEMA_IDS_CACHE.put(schema, schemaId);
}
return schemaId;
}
protected static int nextRandomInt() {
return Math.abs(ThreadLocalRandom.current().nextInt());
}
protected static void assignBlockToBody(Object codeContainer, JBlock body) {
try {
Field field = codeContainer.getClass().getDeclaredField("body");
field.setAccessible(true);
field.set(codeContainer, body);
field.setAccessible(false);
} catch (ReflectiveOperationException e) {
throw new FastDeserializerGeneratorException(e);
}
}
}
| 35.777778 | 115 | 0.620027 |
e7b1914d6c5c6d760f92824d82f40b0d7586511d | 2,977 |
/**
* Copyright (c) 2020 Nathin-Dolphin.
*
* This file is part of the utility library and is under the MIT License.
*/
package source.utility;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
* <p>
* <b>No Known Issues.</b>
*
* @author Nathin Wascher
* @version v1.0.1 - November 20, 2020
*/
public final class Misc {
private Misc() {
}
/**
* Capitalizes the inputted string.
*
* @param input The string to capitalize
* @return The capitalized string
* @throws StringIndexOutOfBoundsException if the {@code beginIndex} is
* negative, or {@code endIndex} is
* larger than the length of this
* {@code String} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public static String capitalize(String input) throws StringIndexOutOfBoundsException {
String tempString;
tempString = input.substring(0, 1).toUpperCase();
tempString = tempString.concat(input.substring(1, input.length()));
return tempString;
}
/**
* Set the x and y position of the {@code GridBagConstraint}.
*
* @param gbc {@code GridBagConstraint}
* @param gridX {@code GridBagConstraint.gridx} value
* @param gridY {@code GridBagConstraint.gridy} value
* @return The {@code GridBagConstraint} with the new grid position
*/
public static GridBagConstraints setGBC(GridBagConstraints gbc, int gridX, int gridY) {
gbc.gridx = gridX;
gbc.gridy = gridY;
return gbc;
}
/**
*
*/
public static ImageIcon findImageIcon() {
java.net.URL imageURL = Misc.class.getResource("Pokeball.png");
if (imageURL != null) {
return new ImageIcon(imageURL, "Pokeball");
} else {
System.out.println("Couldn't find file: Pokeball.png");
return null;
}
}
/**
*
* @param parentComponent
* @param contents
*/
public static void showInfoBox(Component parentComponent, String title, ArrayList<String> contents) {
String message = "";
for (String s : contents) {
message = message + s;
}
JOptionPane.showMessageDialog(parentComponent, message, title, JOptionPane.INFORMATION_MESSAGE);
}
/**
*
* @param parentComponent
* @param warningMessage
*/
public static void warningBox(Component parentComponent, String warningMessage) {
JOptionPane.showConfirmDialog(parentComponent, "WARNING: " + warningMessage, "WARNING MESSAGE!",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
}
}
| 29.77 | 105 | 0.590863 |
41381ac8a8bf363b034922f05080005e39836b4e | 4,736 | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.jenkinsci.plugins.jx.pipelines.arguments;
import hudson.Extension;
import io.jenkins.functions.Argument;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.jx.pipelines.StepExtension;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import java.util.ArrayList;
import java.util.List;
/**
*/
public class PromoteArtifactsArguments extends JXPipelinesArguments<PromoteArtifactsArguments> {
private static final long serialVersionUID = 1L;
@Argument
private String project = "";
@Argument
private String version = "";
@Argument
private List<String> repoIds = new ArrayList<>();
@Argument
private String containerName = "maven";
@Argument
private boolean helmPush;
@Argument
private boolean updateNextDevelopmentVersion;
@Argument
private String updateNextDevelopmentVersionArguments = "";
private StepExtension stepExtension;
@DataBoundConstructor
public PromoteArtifactsArguments() {
}
public PromoteArtifactsArguments(String project, String version) {
this.project = project;
this.version = version;
}
public PromoteArtifactsArguments(String project, String version, List<String> repoIds) {
this.project = project;
this.version = version;
this.repoIds = repoIds;
}
public PromoteArtifactsArguments(String project, String version, List<String> repoIds, String containerName, boolean helmPush, boolean updateNextDevelopmentVersion, String updateNextDevelopmentVersionArguments, StepExtension stepExtension) {
this.project = project;
this.version = version;
this.repoIds = repoIds;
this.containerName = containerName;
this.helmPush = helmPush;
this.updateNextDevelopmentVersion = updateNextDevelopmentVersion;
this.updateNextDevelopmentVersionArguments = updateNextDevelopmentVersionArguments;
this.stepExtension = stepExtension;
}
public String getProject() {
return project;
}
@DataBoundSetter
public void setProject(String project) {
this.project = project;
}
public String getVersion() {
return version;
}
@DataBoundSetter
public void setVersion(String version) {
this.version = version;
}
public List<String> getRepoIds() {
return repoIds;
}
@DataBoundSetter
public void setRepoIds(List<String> repoIds) {
this.repoIds = repoIds;
}
public String getContainerName() {
return containerName;
}
@DataBoundSetter
public void setContainerName(String containerName) {
this.containerName = containerName;
}
public boolean isHelmPush() {
return helmPush;
}
@DataBoundSetter
public void setHelmPush(boolean helmPush) {
this.helmPush = helmPush;
}
public boolean isUpdateNextDevelopmentVersion() {
return updateNextDevelopmentVersion;
}
@DataBoundSetter
public void setUpdateNextDevelopmentVersion(boolean updateNextDevelopmentVersion) {
this.updateNextDevelopmentVersion = updateNextDevelopmentVersion;
}
public String getUpdateNextDevelopmentVersionArguments() {
return updateNextDevelopmentVersionArguments;
}
@DataBoundSetter
public void setUpdateNextDevelopmentVersionArguments(String updateNextDevelopmentVersionArguments) {
this.updateNextDevelopmentVersionArguments = updateNextDevelopmentVersionArguments;
}
public StepExtension getStepExtension() {
return stepExtension;
}
@DataBoundSetter
public void setStepExtension(StepExtension stepExtension) {
this.stepExtension = stepExtension;
}
@Extension @Symbol("promoteArtifacts")
public static class DescriptorImpl extends JXPipelinesArgumentsDescriptor<PromoteArtifactsArguments> {
}
}
| 30.753247 | 245 | 0.725718 |
b287ba41efd98cf8240cbaa855679040be8ff4f7 | 520 | package com.bedatadriven.finance.freeagent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import java.util.List;
public class ListUserResponse extends GenericJson {
@Key
private List<FreeAgentUser> users;
public ListUserResponse() {
}
public ListUserResponse(List<FreeAgentUser> users) {
this.users = users;
}
public List<FreeAgentUser> getUsers() {
return users;
}
public void setUsers(List<FreeAgentUser> users) {
this.users = users;
}
}
| 18.571429 | 54 | 0.728846 |
c336a0324d38db7fa21e36aa97b3bfa51af72b6f | 119 | package algo;
/**
* Created by Tikitoo on 2015/12/21.
*/
public interface Sorter {
void sort(CharSequence s);
}
| 13.222222 | 36 | 0.663866 |
5c252f6cd83256dc9560f5cd69c8873b5d717a11 | 3,242 | package com.github.valfirst.slf4jtest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Test;
class TestMDCAdapterTests {
private TestMDCAdapter testMDCAdapter = new TestMDCAdapter();
private String key = "key";
private String value = "value";
@Test
void putGetRemoveLoop() {
assertNull(testMDCAdapter.get(key));
testMDCAdapter.put(key, value);
assertEquals(value, testMDCAdapter.get(key));
testMDCAdapter.remove(key);
assertNull(testMDCAdapter.get(key));
}
@Test
void getCopyOfContextMap() {
testMDCAdapter.put(key, value);
assertEquals(Collections.singletonMap(key, value), testMDCAdapter.getCopyOfContextMap());
}
@Test
void getCopyOfContextMapIsCopy() {
testMDCAdapter.put(key, value);
Map actual = testMDCAdapter.getCopyOfContextMap();
testMDCAdapter.clear();
assertEquals(Collections.singletonMap(key, value), actual);
}
@Test
void clear() {
testMDCAdapter.put(key, value);
testMDCAdapter.clear();
assertEquals(Collections.emptyMap(), testMDCAdapter.getCopyOfContextMap());
}
@Test
void setContextMapSetsCopy() {
Map<String, String> newValues = new HashMap<>();
newValues.put(key, value);
testMDCAdapter.setContextMap(newValues);
Map<String, String> expected = new HashMap<>(newValues);
newValues.clear();
assertEquals(expected, testMDCAdapter.getCopyOfContextMap());
}
@Test
void testMdcAdapterIsThreadLocal() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(2);
final Map<String, String> results = new HashMap<>();
Thread thread1 =
new Thread(
() -> {
testMDCAdapter.put(key, "value1");
latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
results.put("thread1", testMDCAdapter.get(key));
});
Thread thread2 =
new Thread(
() -> {
testMDCAdapter.put(key, "value2");
latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
results.put("thread2", testMDCAdapter.get(key));
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertEquals("value1", results.get("thread1"));
assertEquals("value2", results.get("thread2"));
}
}
| 34.489362 | 97 | 0.550278 |
5cd9af011a97b55b3b47616ffcc98fd9e7e95c9a | 316 | package de.egga;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class ThingTest {
@Test
void it_should_call_for_action() {
Thing thing = new Thing();
String value = thing.callForAction();
assertThat(value).isEqualTo("Done.");
}
}
| 19.75 | 57 | 0.670886 |
09343f702bbb0914ec1f56aa888fe217d7435704 | 2,767 | /*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to [email protected]
*/
package dan200.computercraft.server.proxy;
import dan200.computercraft.ComputerCraft;
import dan200.computercraft.shared.computer.blocks.TileComputer;
import dan200.computercraft.shared.computer.core.ComputerFamily;
import dan200.computercraft.shared.computer.core.IComputer;
import dan200.computercraft.shared.network.ComputerCraftPacket;
import dan200.computercraft.shared.peripheral.diskdrive.TileDiskDrive;
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
import dan200.computercraft.shared.proxy.ComputerCraftProxyCommon;
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import java.io.File;
public class ComputerCraftProxyServer extends ComputerCraftProxyCommon
{
public ComputerCraftProxyServer()
{
}
// IComputerCraftProxy implementation
@Override
public void init()
{
super.init();
}
@Override
public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle )
{
return null;
}
@Override
public boolean isClient()
{
return false;
}
@Override
public boolean getGlobalCursorBlink()
{
return false;
}
@Override
public long getRenderFrame()
{
return 0;
}
@Override
public Object getFixedWidthFontRenderer()
{
return null;
}
@Override
public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive )
{
return null;
}
@Override
public Object getComputerGUI( TileComputer computer )
{
return null;
}
@Override
public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer )
{
return null;
}
@Override
public Object getPrintoutGUI( EntityPlayer player, EnumHand hand )
{
return null;
}
@Override
public Object getPocketComputerGUI( EntityPlayer player, EnumHand hand )
{
return null;
}
@Override
public Object getComputerGUI( IComputer computer, int width, int height, ComputerFamily family )
{
return null;
}
@Override
public File getWorldDir( World world )
{
return DimensionManager.getWorld( 0 ).getSaveHandler().getWorldDirectory();
}
}
| 24.27193 | 100 | 0.712685 |
889deb211f8e9fa03d74b0a7107affdd40e91cfd | 221 | package com.itextpdf.text.pdf;
public interface HyphenationEvent {
String getHyphenSymbol();
String getHyphenatedWordPost();
String getHyphenatedWordPre(String str, BaseFont baseFont, float f, float f2);
}
| 22.1 | 82 | 0.760181 |
7576daf83f26fcdc1ae494aabdb55ae59ed40c4d | 27,133 | package no.petroware.logio.json;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonValue;
import no.petroware.logio.util.Formatter;
import no.petroware.logio.util.ISO8601DateParser;
import no.petroware.logio.util.Util;
/**
* Class for writing JSON Well Log Format files to disk.
* <p>
* Typical usage:
*
* <pre>
* JsonLog log = new JsonLog();
* :
*
* // Write to file, human readable with 2 space indentation
* JsonWriter writer = new JsonWriter(new File("path/to/file.json"), true, 2);
* writer.write(log);
* writer.close();
* </pre>
*
* If there is to much data to keep in memory, it is possible to write in a
* <em>streaming</em> manner by adding curve data and appending the output
* file alternately, see {@link #append}.
* <p>
* Note that the pretty print mode of this writer will behave different than
* a standard JSON writer in that it always writes curve data arrays horizontally,
* with each curve vertically aligned.
*
* @author <a href="mailto:[email protected]">Petroware AS</a>
*/
public final class JsonWriter
implements Closeable
{
/** Platform independent new-line string. */
private static String NEWLINE = System.getProperty("line.separator");
/** The physical disk file to write. */
private final File file_;
/** The output stream to write. */
private final OutputStream outputStream_;
/** True to write in human readable pretty format, false to write dense. */
private final boolean isPretty_;
/**
* The new line token according to pretty print mode. Either NEWLINE or "".
* Cached for efficiency.
*/
private final String newline_;
/**
* Spacing between tokens according to pretty print mode. Either " " or "".
* Cached for efficiency.
*/
private final String spacing_;
/** Current indentation according to pretty print mode. */
private final Indentation indentation_;
/** The writer instance. */
private Writer writer_;
/** Indicate if the last written JSON file contains data or not. */
private boolean hasData_;
/**
* Class for holding a space indentation as used at the beginning
* of the line when writing in pretty print mode to disk file.
*
* @author <a href="mailto:[email protected]">Petroware AS</a>
*/
private final static class Indentation
{
/** Number of characters for the indentation. [0,>. */
private final int unit_;
/** The actual indentation string. */
private final String indent_;
/**
* Create an indentation instance of the specified unit,
* and an initial indentation.
*
* @param unit Number of characters per indentation. [0,>.
* @param indentation Current indentation. Non-null.
*/
private Indentation(int unit, String indentation)
{
assert unit >= 0 : "Invalid unit: " + unit;
assert indentation != null : "indentation cannot be null";
unit_ = unit;
indent_ = indentation;
}
/**
* Create a new indentation instance indented one level to the right.
*
* @return The requested indentation instance. Never null.
*/
private Indentation push()
{
int indentation = indent_.length() + unit_;
return new Indentation(unit_, Util.getSpaces(indentation));
}
/**
* Create a new indentation instance indented one level to the left.
*
* @return The requested indentation instance. Never null.
*/
private Indentation pop()
{
int indentation = Math.max(0, indent_.length() - unit_);
return new Indentation(unit_, Util.getSpaces(indentation));
}
/** {@inheritDoc} */
@Override
public String toString()
{
return indent_;
}
}
/**
* Create a JSON Well Log Format writer instance.
*
* @param outputStream Stream to write. Non-null.
* @param isPretty True to write in human readable pretty format, false
* to write as dense as possible.
* @param indentation The white space indentation used in pretty print mode. [0,>.
* If isPretty is false, this setting has no effect.
* @throws IllegalArgumentException If outputStream is null or indentation is out of bounds.
*/
public JsonWriter(OutputStream outputStream, boolean isPretty, int indentation)
{
if (outputStream == null)
throw new IllegalArgumentException("outputStream cannot be null");
if (isPretty && indentation < 0)
throw new IllegalArgumentException("Invalid indentation: " + indentation);
file_ = null;
outputStream_ = outputStream;
isPretty_ = isPretty;
newline_ = isPretty_ ? NEWLINE : "";
spacing_ = isPretty_ ? " " : "";
indentation_ = new Indentation(isPretty ? indentation : 0, "");
}
/**
* Create a JSON Well Log Format writer instance.
*
* @param file Disk file to write to. Non-null.
* @param isPretty True to write in human readable pretty format, false
* to write as dense as possible.
* @param indentation The white space indentation used in pretty print mode. [0,>.
* If isPretty is false, this setting has no effect.
* @throws IllegalArgumentException If file is null or indentation is out of bounds.
*/
public JsonWriter(File file, boolean isPretty, int indentation)
{
if (file == null)
throw new IllegalArgumentException("file cannot be null");
if (isPretty && indentation < 0)
throw new IllegalArgumentException("Invalid indentation: " + indentation);
file_ = file;
outputStream_ = null;
isPretty_ = isPretty;
newline_ = isPretty_ ? NEWLINE : "";
spacing_ = isPretty_ ? " " : "";
indentation_ = new Indentation(isPretty ? indentation : 0, "");
}
/**
* Create a JSON Well Log Format writer producing pretty content with
* standard indentation.
*
* @param file Disk file to write to. Non-null.
* @throws IllegalArgumentException If file is null.
*/
public JsonWriter(File file)
{
this(file, true, 2);
}
/**
* Get the specified string token as a quoted text suitable for writing to
* a JSON disk file, i.e. "null" if null, or properly escaped if non-null.
*
* @param value Value to get as text. May be null.
* @return The value as a JSON text. Never null.
*/
private static String getQuotedText(String value)
{
return value != null ? JsonUtil.encode(value) : "null";
}
/**
* Compute the width of the widest element of the column of the specified curve.
*
* @param curve Curve to compute column width of. Non-null.
* @param formatter Curve data formatter. Null if N/A for the specified curve.
* @return Width of widest element of the curve. [0,>.
*/
private static int computeColumnWidth(JsonCurve curve, Formatter formatter)
{
assert curve != null : "curve cannot be null";
int columnWidth = 0;
Class<?> valueType = curve.getValueType();
for (int index = 0; index < curve.getNValues(); index++) {
for (int dimension = 0; dimension < curve.getNDimensions(); dimension++) {
Object value = curve.getValue(dimension, index);
String text;
if (value == null)
text = "null";
else if (valueType == Date.class)
text = "2018-10-10T12:20:00Z"; // Template
else if (formatter != null)
text = formatter.format(Util.getAsDouble(value));
else if (valueType == String.class)
text = getQuotedText(value.toString());
else // Boolean and Integers
text = value.toString();
if (text.length() > columnWidth)
columnWidth = text.length();
}
}
return columnWidth;
}
/**
* Get the specified data value as text, according to the specified value type,
* the curve formatter, the curve width and the general rules for the JSON format.
*
* @param value Curve value to get as text. May be null, in case "null" is returned.
* @param valueType Java value type of the curve of the value. Non-null.
* @param formatter Curve formatter. Specified for floating point values only, null otherwise,
* @param width Total with set aside for the values of this column. [0,>.
* @return The JSON token to be written to file. Never null.
*/
private String getText(Object value, Class<?> valueType, Formatter formatter, int width)
{
assert valueType != null : "valueType cannot be null";
assert width >= 0 : "Invalid width: " + width;
String text = null;
if (value == null)
text = "null";
else if (valueType == Date.class)
text = '\"' + ISO8601DateParser.toString((Date) value) + '\"';
else if (valueType == Boolean.class)
text = value.toString();
else if (formatter != null)
text = formatter.format(Util.getAsDouble(value));
else if (Number.class.isAssignableFrom(valueType))
text = value.toString();
else if (valueType == String.class)
text = getQuotedText(value.toString());
else
assert false : "Unrecognized valueType: " + valueType;
String padding = isPretty_ ? Util.getSpaces(width - text.length()) : "";
return padding + text;
}
/**
* Write the specified JSON value to the current writer.
*
* @param jsonValue Value to write. Non-null.
* @param indentation The current indentation level. Non-null.
*/
private void writeValue(JsonValue jsonValue, Indentation indentation)
throws IOException
{
assert jsonValue != null : "jsonValue cannot be null";
assert indentation != null : "indentation cannot b3 null";
switch (jsonValue.getValueType()) {
case ARRAY :
writeArray((JsonArray) jsonValue, indentation);
break;
case OBJECT :
writeObject((JsonObject) jsonValue, indentation);
break;
case NUMBER :
writer_.write(jsonValue.toString());
break;
case STRING :
writer_.write(getQuotedText(((JsonString) jsonValue).getString()));
break;
case FALSE :
writer_.write("false");
break;
case TRUE :
writer_.write("true");
break;
case NULL :
writer_.write("null");
break;
default :
assert false : "Unrecognized value type: " + jsonValue.getValueType();
}
}
/**
* Write the specified JSON object to the current writer.
*
* @param jsonObject Object to write. Non-null.
* @param indentation The current indentation level. Non-null.
*/
private void writeObject(JsonObject jsonObject, Indentation indentation)
throws IOException
{
assert jsonObject != null : "jsonObject cannot be null";
assert indentation != null : "indentation cannot be null";
writer_.write('{');
boolean isFirst = true;
for (Map.Entry<String,JsonValue> entry : jsonObject.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
if (!isFirst)
writer_.write(',');
writer_.write(newline_);
writer_.write(indentation.push().toString());
writer_.write('\"');
writer_.write(key);
writer_.write('\"');
writer_.write(':');
writer_.write(spacing_);
writeValue(value, indentation.push());
isFirst = false;
}
if (!jsonObject.isEmpty()) {
writer_.write(newline_);
writer_.write(indentation.toString());
}
writer_.write("}");
}
/**
* Write the specified JSON array to the current writer.
*
* @param jsonArray Array to write. Non-null.
* @param indentation The current indentation level. Non-null.
*/
private void writeArray(JsonArray jsonArray, Indentation indentation)
throws IOException
{
assert jsonArray != null : "jsonArray cannot be null";
assert indentation != null : "indentation cannot be null";
boolean isHorizontal = !JsonUtil.containsObjects(jsonArray);
writer_.write('[');
boolean isFirst = true;
for (JsonValue jsonValue : jsonArray) {
if (!isFirst) {
writer_.write(",");
if (isHorizontal)
writer_.write(spacing_);
}
if (!isHorizontal) {
writer_.write(newline_);
writer_.write(indentation.push().toString());
}
writeValue(jsonValue, indentation.push());
isFirst = false;
}
if (!jsonArray.isEmpty() && !isHorizontal) {
writer_.write(newline_);
writer_.write(indentation.toString());
}
writer_.write(']');
}
/**
* Write the speicfied JSON Well Logg Format header object to the current writer.
* <p>
* This method is equal the writeHeader method apart from its special handling
* of the specific keys startIndex, endIndex and step so that these gets identical
* formatting as the index curve of the log.
*
* @param header The JSON Well Log Format header object. Non-null.
* @param indentation The current indentation level. Non-null.
* @param log The log of this header. Non-null.
*/
private void writeHeaderObject(JsonObject header, Indentation indentation, JsonLog log)
throws IOException
{
assert header != null : "header cannot be null";
assert indentation != null : "indentation cannot be null";
assert log != null : "log cannot be null";
JsonCurve indexCurve = log.getNCurves() > 0 ? log.getCurves().get(0) : null;
Formatter indexCurveFormatter = indexCurve != null ? log.createFormatter(indexCurve, true) : null;
writer_.write('{');
boolean isFirst = true;
for (Map.Entry<String,JsonValue> entry : header.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
if (!isFirst)
writer_.write(',');
writer_.write(newline_);
writer_.write(indentation.push().toString());
writer_.write('\"');
writer_.write(key);
writer_.write('\"');
writer_.write(':');
writer_.write(spacing_);
//
// Special handling of startIndex, endIndex and step so that
// they get the same formatting as the index curve data.
//
if (indexCurveFormatter != null && (key.equals("startIndex") || key.equals("endIndex") || key.equals("step"))) {
double v = Util.getAsDouble(JsonUtil.getValue(value));
String text = Double.isFinite(v) ? indexCurveFormatter.format(v) : "null";
writer_.write(text);
}
else {
writeValue(value, indentation.push());
}
isFirst = false;
}
if (!header.isEmpty()) {
writer_.write(newline_);
writer_.write(indentation.toString());
}
writer_.write("}");
}
/**
* Write the curve data of the specified JSON log to the stream
* of this writer.
*
* @param log Log to write curve data of. Non-null.
* @throws IOException If the write operation fails for some reason.
*/
private void writeData(JsonLog log)
throws IOException
{
assert log != null : "log cannot be null";
Indentation indentation = indentation_.push().push().push();
List<JsonCurve> curves = log.getCurves();
// Create formatters for each curve
Map<JsonCurve,Formatter> formatters = new HashMap<>();
for (int curveNo = 0; curveNo < log.getNCurves(); curveNo++) {
JsonCurve curve = curves.get(curveNo);
formatters.put(curve, log.createFormatter(curve, curveNo == 0));
}
// Compute column width for each data column
Map<JsonCurve,Integer> columnWidths = new HashMap<>();
for (JsonCurve curve : curves)
columnWidths.put(curve, computeColumnWidth(curve, formatters.get(curve)));
for (int index = 0; index < log.getNValues(); index++) {
for (int curveNo = 0; curveNo < log.getNCurves(); curveNo++) {
JsonCurve curve = curves.get(curveNo);
Class<?> valueType = curve.getValueType();
int nDimensions = curve.getNDimensions();
int width = columnWidths.get(curve);
Formatter formatter = formatters.get(curve);
if (curveNo == 0) {
writer_.write(indentation.toString());
writer_.write('[');
}
if (nDimensions > 1) {
if (curveNo > 0) {
writer_.write(',');
writer_.write(spacing_);
}
writer_.write('[');
for (int dimension = 0; dimension < nDimensions; dimension ++) {
Object value = curve.getValue(dimension, index);
String text = getText(value, valueType, formatter, width);
if (dimension > 0) {
writer_.write(',');
writer_.write(spacing_);
}
writer_.write(text);
}
writer_.write(']');
}
else {
Object value = curve.getValue(0, index);
String text = getText(value, valueType, formatter, width);
if (curveNo > 0) {
writer_.write(',');
writer_.write(spacing_);
}
writer_.write(text);
}
}
writer_.write(']');
if (index < log.getNValues() - 1) {
writer_.write(',');
writer_.write(newline_);
}
}
}
/**
* Write the specified log instances to this writer.
* Multiple logs can be written in sequence to the same stream.
* Additional data can be appended to the last one by {@link #append}.
* When writing is done, close the writer with {@link #close}.
*
* @param log Log to write. Non-null.
* @throws IllegalArgumentException If log is null.
* @throws IOException If the write operation fails for some reason.
*/
public void write(JsonLog log)
throws IOException
{
if (log == null)
throw new IllegalArgumentException("log cannot be null");
boolean isFirstLog = writer_ == null;
// Create the writer on first write operation
if (isFirstLog) {
OutputStream outputStream = file_ != null ? new FileOutputStream(file_) : outputStream_;
writer_ = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer_.write('[');
writer_.write(newline_);
}
// If this is an additional log, close the previous and make ready for a new
else {
writer_.write(newline_);
writer_.write(indentation_.push().push().toString());
writer_.write(']');
writer_.write(newline_);
writer_.write(indentation_.push().toString());
writer_.write("},");
writer_.write(newline_);
}
Indentation indentation = indentation_.push();
writer_.write(indentation.toString());
writer_.write('{');
writer_.write(newline_);
indentation = indentation.push();
//
// "header"
//
writer_.write(indentation.toString());
writer_.write("\"header\":");
writer_.write(spacing_);
writeHeaderObject(log.getHeader(), indentation, log);
writer_.write(',');
//
// "curves"
//
writer_.write(newline_);
writer_.write(indentation.toString());
writer_.write("\"curves\": [");
boolean isFirstCurve = true;
List<JsonCurve> curves = log.getCurves();
for (JsonCurve curve : curves) {
if (!isFirstCurve)
writer_.write(',');
writer_.write(newline_);
indentation = indentation.push();
writer_.write(indentation.toString());
writer_.write('{');
writer_.write(newline_);
indentation = indentation.push();
// Name
writer_.write(indentation.toString());
writer_.write("\"name\":");
writer_.write(spacing_);
writer_.write(getQuotedText(curve.getName()));
writer_.write(',');
writer_.write(newline_);
// Description
writer_.write(indentation.toString());
writer_.write("\"description\":");
writer_.write(spacing_);
writer_.write(getQuotedText(curve.getDescription()));
writer_.write(',');
writer_.write(newline_);
// Quantity
writer_.write(indentation.toString());
writer_.write("\"quantity\":");
writer_.write(spacing_);
writer_.write(getQuotedText(curve.getQuantity()));
writer_.write(',');
writer_.write(newline_);
// Unit
writer_.write(indentation.toString());
writer_.write("\"unit\":");
writer_.write(spacing_);
writer_.write(getQuotedText(curve.getUnit()));
writer_.write(',');
writer_.write(newline_);
// Value type
writer_.write(indentation.toString());
writer_.write("\"valueType\":");
writer_.write(spacing_);
writer_.write(getQuotedText(JsonValueType.get(curve.getValueType()).toString()));
writer_.write(',');
writer_.write(newline_);
// Dimension
writer_.write(indentation.toString());
writer_.write("\"dimensions\":");
writer_.write(spacing_);
writer_.write("" + curve.getNDimensions());
writer_.write(newline_);
indentation = indentation.pop();
writer_.write(indentation.toString());
writer_.write('}');
indentation = indentation.pop();
isFirstCurve = false;
}
writer_.write(newline_);
writer_.write(indentation.toString());
writer_.write(']');
writer_.write(',');
//
// "data"
//
writer_.write(newline_);
writer_.write(indentation.toString());
writer_.write("\"data\": [");
writer_.write(newline_);
writeData(log);
hasData_ = log.getNValues() > 0;
}
/**
* Append the curve data of the specified log to this writer.
* <p>
* This feature can be used to <em>stream</em> data to a JSON
* destination. By repeatedly clearing and populating the log
* curves with new data there is no need for the client to
* keep the full volume in memory at any point in time.
* <p>
* <b>NOTE:</b> This method should be called after the
* JSON Well Log Format metadata has been written (see {@link #write}),
* and the JSON log must be compatible with this.
* <p>
* When writing is done, close the stream with {@link #close}.
*
* @param log Log to append to stream. Non-null.
* @throws IllegalArgumentException If log is null.
* @throws IllegalStateException If the writer is not open for writing.
* @throws IOException If the write operation fails for some reason.
*/
public void append(JsonLog log)
throws IOException
{
if (log == null)
throw new IllegalArgumentException("log cannot be null");
if (writer_ == null)
throw new IllegalStateException("Writer is not open");
if (hasData_) {
writer_.write(',');
writer_.write(newline_);
}
writer_.write(indentation_.toString());
writeData(log);
if (!hasData_ && log.getNValues() > 0)
hasData_ = true;
}
/**
* Append the final brackets to the JSON Well Log Format stream and
* close the writer.
*/
@Override
public void close()
throws IOException
{
// Nothing to do if the writer was never opened
if (writer_ == null)
return;
// Complete the data array
writer_.write(newline_);
writer_.write(indentation_.push().push().toString());
writer_.write(']');
writer_.write(newline_);
// Complete the log object
writer_.write(indentation_.push().toString());
writer_.write('}');
writer_.write(newline_);
// Complete the logs array
writer_.write(']');
writer_.write(newline_);
writer_.close();
writer_ = null;
}
/**
* Convenience method for returning a string representation of the specified logs.
*
* @param logs Logs to write. Non-null.
* @param isPretty True to write in human readable pretty format, false
* to write as dense as possible.
* @param indentation The white space indentation used in pretty print mode. [0,>.
* If isPretty is false, this setting has no effect.
* @return The requested string. Never null.
* @throws IllegalArgumentException If logs is null or indentation is out of bounds.
*/
public static String toString(List<JsonLog> logs, boolean isPretty, int indentation)
{
if (logs == null)
throw new IllegalArgumentException("logs cannot be null");
if (indentation < 0)
throw new IllegalArgumentException("invalid indentation: " + indentation);
ByteArrayOutputStream stringStream = new ByteArrayOutputStream();
JsonWriter writer = new JsonWriter(stringStream, isPretty, indentation);
String string = "";
try {
for (JsonLog log : logs)
writer.write(log);
}
catch (IOException exception) {
// Since we are writing to memory (ByteArrayOutputStream) we don't really
// expect an IOException so if we get one anyway, we are in serious trouble
throw new RuntimeException("Unable to write", exception);
}
finally {
try {
writer.close();
string = new String(stringStream.toByteArray(), "UTF-8");
}
catch (IOException exception) {
// Again: This will never happen.
throw new RuntimeException("Unable to write", exception);
}
}
return string;
}
/**
* Convenience method for returning a string representation of the specified log.
*
* @param log Log to write. Non-null.
* @param isPretty True to write in human readable pretty format, false
* to write as dense as possible.
* @param indentation The white space indentation used in pretty print mode. [0,>.
* If isPretty is false, this setting has no effect.
* @return The requested string. Never null.
* @throws IllegalArgumentException If log is null or indentation is out of bounds.
*/
public static String toString(JsonLog log, boolean isPretty, int indentation)
{
if (log == null)
throw new IllegalArgumentException("log cannot be null");
if (indentation < 0)
throw new IllegalArgumentException("invalid indentation: " + indentation);
List<JsonLog> logs = new ArrayList<>();
logs.add(log);
return toString(logs, isPretty, indentation);
}
/**
* Convenience method for returning a pretty printed string representation
* of the specified log.
*
* @param log Log to write. Non-null.
* @return The requested string. Never null.
* @throws IllegalArgumentException If log is null.
*/
public static String toString(JsonLog log)
{
if (log == null)
throw new IllegalArgumentException("log cannot be null");
return toString(log, true, 2);
}
}
| 30.316201 | 118 | 0.635573 |
01eff85b4fb504c21a6465d4e4428f954e195739 | 6,989 | package org.jetbrains.research.refactorinsight.pullrequests;
import com.intellij.diff.util.FileEditorBase;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.Gray;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBLoadingPanel;
import com.intellij.ui.components.JBLoadingPanelListener;
import com.intellij.ui.components.JBViewport;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.vcs.log.VcsFullCommitDetails;
import com.intellij.vcs.log.VcsLogProvider;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.impl.VcsProjectLog;
import com.intellij.vcs.log.util.VcsLogUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.research.refactorinsight.RefactorInsightBundle;
import org.jetbrains.research.refactorinsight.data.RefactoringEntry;
import org.jetbrains.research.refactorinsight.data.RefactoringInfo;
import org.jetbrains.research.refactorinsight.services.MiningService;
import org.jetbrains.research.refactorinsight.ui.tree.Node;
import org.jetbrains.research.refactorinsight.ui.tree.TreeUtils;
import org.jetbrains.research.refactorinsight.ui.tree.renderers.MainCellRenderer;
import org.jetbrains.research.refactorinsight.ui.windows.DiffWindow;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* Shows a list of discovered refactorings in opened Pull Request.
*/
public class PRFileEditor extends FileEditorBase {
private final PRVirtualFile file;
private final Project project;
private final JScrollPane panel;
private JBLoadingPanel loadingPanel;
private final ConcurrentHashMap<String, VcsFullCommitDetails> commitsDetails = new ConcurrentHashMap<>();
/**
* Creates a new editor.
*
* @param project current project.
* @param prVirtualFile virtual file.
*/
public PRFileEditor(Project project, PRVirtualFile prVirtualFile) {
this.file = prVirtualFile;
this.project = project;
this.panel = new JScrollPane();
createLoadingPanel();
collectCommitsDetails();
}
@Override
public @NotNull
JComponent getComponent() {
return loadingPanel;
}
private void collectCommitsDetails() {
ProgressManager.getInstance().run(new Task.Modal(
project, "", true) {
List<? extends VcsFullCommitDetails> details = new ArrayList<>();
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
loadingPanel.startLoading();
VcsLogData vcsLogData = VcsProjectLog.getInstance(project).getLogManager().getDataManager();
VirtualFile root = vcsLogData.getRoots().iterator().next();
VcsLogProvider vcsLogProvider = VcsProjectLog.getInstance(project).getDataManager().getLogProvider(root);
try {
details = VcsLogUtil.getDetails(vcsLogProvider, root, file.getCommitsIds());
} catch (VcsException e) {
e.printStackTrace();
}
saveCommitsDetails(details);
}
@Override
public void onFinished() {
calculateRefactorings();
}
});
}
private void saveCommitsDetails(List<? extends VcsFullCommitDetails> vcsFullCommitDetails) {
if (!vcsFullCommitDetails.isEmpty()) {
for (VcsFullCommitDetails data : vcsFullCommitDetails) {
commitsDetails.put(data.getId().asString(), data);
}
}
}
/**
* Creates a loading panel that is shown during the refactoring detection.
*/
private void createLoadingPanel() {
loadingPanel = new JBLoadingPanel(new BorderLayout(), this);
loadingPanel.addListener(new JBLoadingPanelListener.Adapter() {
@Override
public void onLoadingFinish() {
panel.updateUI();
loadingPanel.updateUI();
}
});
loadingPanel.add(panel);
}
private void calculateRefactorings() {
MiningService.getInstance(project).mineAtCommitFromPR(new ArrayList<>(commitsDetails.values()),
project, this);
}
/**
* Builds a panel to show the discovered refactorings in opened Pull Request.
*/
public void buildComponent() {
panel.setAutoscrolls(true);
JBViewport viewport = new JBViewport();
viewport.setAutoscrolls(true);
MiningService miner = MiningService.getInstance(project);
List<RefactoringInfo> refactoringsFromAllCommits = new ArrayList<>();
for (String commitId : file.getCommitsIds()) {
RefactoringEntry entry = miner.get(commitId);
if (entry != null) {
refactoringsFromAllCommits.addAll(entry.getRefactorings());
}
}
// Check if all commits don't have refactorings
if (refactoringsFromAllCommits.isEmpty()) {
final JBLabel component =
new JBLabel(RefactorInsightBundle.message("no.ref"), SwingConstants.CENTER);
component.setForeground(Gray._105);
viewport.setView(component);
} else {
Tree tree = TreeUtils.buildTree(refactoringsFromAllCommits);
tree.setCellRenderer(new MainCellRenderer());
tree.setAutoscrolls(true);
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent ev) {
if (ev.getClickCount() == 2) {
TreePath path = tree.getPathForLocation(ev.getX(), ev.getY());
if (path == null) {
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node.isLeaf()) {
RefactoringInfo info = ((Node) node.getUserObject()).getInfo();
final Collection<Change> changes = Optional.ofNullable(commitsDetails.get(info.getCommitId()))
.map(VcsFullCommitDetails::getChanges).orElse(new ArrayList<>());
if (changes.size() != 0) {
DiffWindow.showDiff(changes, info, project, info.getEntry().getRefactorings());
}
}
}
}
});
viewport.setView(tree);
}
panel.setViewport(viewport);
loadingPanel.stopLoading();
loadingPanel.add(panel);
}
@Override
public @Nullable
JComponent getPreferredFocusedComponent() {
return panel;
}
@Override
public @NotNull
String getName() {
return "RefactorInsight";
}
@Override
public @Nullable
VirtualFile getFile() {
return file;
}
}
| 34.259804 | 113 | 0.716555 |
d10ae8172fbab2b248d86da7e08ebd0855a4f75f | 1,340 | package com.intershop.oms.test.servicehandler.transmissionservice.v1_1.mapping;
import java.util.List;
import org.mapstruct.AfterMapping;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;
import com.intershop.oms.rest.transmission.v1_1.model.ReceiverType;
import com.intershop.oms.test.businessobject.transmission.OMSReceiverType;
@Mapper
public interface ReceiverTypeMapper
{
ReceiverTypeMapper INSTANCE = Mappers.getMapper(ReceiverTypeMapper.class);
OMSReceiverType fromApiReceiverType(ReceiverType ReceiverType);
@InheritInverseConfiguration
public abstract ReceiverType toApiReceiverType(OMSReceiverType omsReceiverType);
@AfterMapping
public default void fromApiReceiverTypeList(final List<ReceiverType> receiverTypes, @MappingTarget final List<OMSReceiverType> omsReceiverTypes)
{
receiverTypes.stream().forEach(receiverType -> omsReceiverTypes.add(fromApiReceiverType(receiverType)));
}
@AfterMapping
public default void toApiReceiverTypeList(final List<OMSReceiverType> omsReceiverTypes, @MappingTarget final List<ReceiverType> receiverTypes)
{
omsReceiverTypes.stream().forEach(omsReceiverType -> receiverTypes.add(toApiReceiverType(omsReceiverType)));
}
} | 38.285714 | 148 | 0.814925 |
ed465bd4dabc3510b1f6d9a80716aca7f53607c0 | 974 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: com/api/igdb/igdbproto.proto
package proto;
public interface MultiQueryResultArrayOrBuilder extends
// @@protoc_insertion_point(interface_extends:proto.MultiQueryResultArray)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .proto.MultiQueryResult result = 1;</code>
*/
java.util.List<proto.MultiQueryResult>
getResultList();
/**
* <code>repeated .proto.MultiQueryResult result = 1;</code>
*/
proto.MultiQueryResult getResult(int index);
/**
* <code>repeated .proto.MultiQueryResult result = 1;</code>
*/
int getResultCount();
/**
* <code>repeated .proto.MultiQueryResult result = 1;</code>
*/
java.util.List<? extends proto.MultiQueryResultOrBuilder>
getResultOrBuilderList();
/**
* <code>repeated .proto.MultiQueryResult result = 1;</code>
*/
proto.MultiQueryResultOrBuilder getResultOrBuilder(
int index);
}
| 28.647059 | 78 | 0.703285 |
b729b0f3c8d156cb2f0784bfd31a03fe1b6636de | 2,760 | package com.benstone.tankgame.EntitySystems;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.EntitySystem;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.math.Vector2;
import com.benstone.tankgame.Components.*;
import com.benstone.tankgame.Utils.EntityMapper;
/**
* Created by Ben on 1/12/2016.
*/
public class B2DTankChassisMovementSystem extends EntitySystem
{
private ImmutableArray<Entity> entities = null;
@Override
public void addedToEngine(Engine engine) {
super.addedToEngine(engine);
// Get all entities in the engine with a Render and Position Component
entities = engine.getEntitiesFor(Family.all(B2DBodyComponent.class).all(B2DTankChassisMovementComponent.class).get());
}
@Override
public void update(float deltaTime)
{
super.update(deltaTime);
if (entities != null)
{
for (int i = 0; i < entities.size(); i++)
{
// Get the playerEntity at index i
Entity entity = entities.get(i);
// Get the Components component from the playerEntity
B2DTankChassisMovementComponent b2dmc = EntityMapper.B2D_TANK_CHASSIS_MOVEMENT_COMPONENT_MAPPER.get(entity);
B2DBodyComponent b2dbc = EntityMapper.B2D_BODY_COMPONENT_MAPPER.get(entity);
// Reset values so we don't move when nothing is pressed
int traverseDir = 0;
int forwardAndBackwardDir = 0;
// Should I move to left
if(b2dmc.traverseLeft)
{
traverseDir += 1;
}
// Should I move to right
if(b2dmc.traverseRight)
{
traverseDir -= 1;
}
// Should I move up
if(b2dmc.moveForward)
{
forwardAndBackwardDir += 1;
}
// Should I move down
if(b2dmc.moveBackwards)
{
forwardAndBackwardDir -= 1;
}
// Get the world coordinates of a vector given the local coordinates.
Vector2 velocityDirection = b2dbc.body.getWorldVector(new Vector2(0, 1));
Vector2 linearVelocity = velocityDirection.scl(forwardAndBackwardDir * b2dmc.forwardAndBackwardSpeed);
// Update Body Position
b2dbc.body.setLinearVelocity(linearVelocity);
b2dbc.body.setAngularVelocity(traverseDir * b2dmc.traverseSpeed);
}
}
}
}
| 32.857143 | 126 | 0.590942 |
c65dc7f92be7b0d800137935e586eae98cf8fa8b | 1,321 | package com._4point.aem.formsfeeder.core.api;
import java.util.Optional;
public interface AemConfig {
public enum Protocol {
HTTP("http"), HTTPS("https");
private final String protocolString;
private Protocol(String protocolString) {
this.protocolString = protocolString;
}
public final String toProtocolString() {
return protocolString;
}
public static final Optional<Protocol> from(String string) {
for (Protocol value : Protocol.values()) {
if (value.protocolString.equalsIgnoreCase(string)) {
return Optional.of(value);
}
}
return Optional.empty();
}
};
public enum AemServerType {
JEE,
OSGI;
public static Optional<AemServerType> from(String typeString) {
if (typeString != null && !typeString.isEmpty()) {
for (AemServerType st : values()) {
if (typeString.equalsIgnoreCase(st.name())) {
return Optional.of(st);
}
}
}
return Optional.empty();
}
}
public String host();
public int port();
public String username();
public String secret();
public Protocol protocol();
public AemServerType serverType();
default public String url() {
return protocol().toProtocolString() + "://" + host() + (port() != 80 ? ":" + port() : "") + "/";
}
}
| 23.589286 | 100 | 0.627555 |
b57429c4591c84c2cdecc083f70fbafbb9a974d7 | 1,966 | package org.recap.model.jpa;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.CascadeType;
import javax.persistence.ManyToOne;
import javax.persistence.FetchType;
import javax.persistence.JoinTable;
import java.util.Date;
import java.util.List;
/**
* Created by dharmendrag on 29/11/16.
*/
@Entity
@Table(name="user_t",schema="recap",catalog="")
@AttributeOverride(name = "id", column = @Column(name = "user_id"))
@Getter
@Setter
public class UsersEntity extends AbstractEntity<Integer>{
@Column(name="login_id")
private String loginId;
@Column(name="user_institution")
private Integer institutionId;
@Column(name="user_description")
private String userDescription;
@Column(name="user_emailid")
private String emailId;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATED_DATE")
private Date createdDate;
@Column(name = "CREATED_BY")
private String createdBy;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "LAST_UPDATED_DATE")
private Date lastUpdatedDate;
@Column(name = "LAST_UPDATED_BY")
private String lastUpdatedBy;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name="user_role_t", joinColumns = {
@JoinColumn(name="user_id",referencedColumnName = "user_id")},
inverseJoinColumns = {
@JoinColumn(name="role_id",referencedColumnName = "role_id")
})
private List<RoleEntity> userRole;
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "user_institution", insertable = false, updatable = false)
private InstitutionEntity institutionEntity;
}
| 27.305556 | 81 | 0.731434 |
75f9a404fcc59431b574a4d7ebb9052f0ad88972 | 1,864 | package com.divide2.team.controller;
import com.divide2.core.data.del.SingleStringId;
import com.divide2.team.model.Attention;
import com.divide2.team.service.AttentionService;
import com.divide2.core.data.resp.Messager;
import com.divide2.core.er.Responser;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* @author bvvy
* @date 2019/1/23
*/
@RestController
@RequestMapping("/v1/attention")
public class AttentionController {
private final AttentionService attentionService;
public AttentionController(AttentionService attentionService) {
this.attentionService = attentionService;
}
@PostMapping
@ApiOperation("添加")
public ResponseEntity<Messager> add(@Valid @RequestBody Attention attention, BindingResult br) {
attentionService.add(attention);
return Responser.created();
}
@PatchMapping
@ApiOperation("修改")
public ResponseEntity<Messager> update(@Valid @RequestBody Attention update, BindingResult br) {
Attention attention = attentionService.get(update.getId());
attention.setContent(update.getContent());
attentionService.update(attention);
return Responser.updated();
}
@DeleteMapping
@ApiOperation("删除")
public ResponseEntity<Messager> delete(@Valid @RequestBody SingleStringId id, BindingResult br) {
attentionService.delete(id.getId());
return Responser.deleted();
}
@GetMapping("/all")
@ApiOperation("全部")
public ResponseEntity<List<Attention>> get(@PathVariable Integer id) {
List<Attention> attentions = attentionService.findAll();
return Responser.ok(attentions);
}
}
| 30.557377 | 101 | 0.733906 |
5bdccd943e2d4184106a68bf1dd3090e45feac9e | 422 | package me.roybailey.springboot.jpa.domain;
import lombok.*;
import javax.persistence.*;
import java.math.BigDecimal;
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version
private Long version;
private String name;
private String description;
private BigDecimal price;
}
| 16.230769 | 55 | 0.739336 |
8a382bc9bf448828c2ad89feebbe5b18890c5001 | 5,685 | /*
* Copyright 2021 The Android Open Source Project
*
* 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 androidx.camera.core.impl;
import static android.media.MediaRecorder.VideoEncoder.DEFAULT;
import static android.media.MediaRecorder.VideoEncoder.H263;
import static android.media.MediaRecorder.VideoEncoder.H264;
import static android.media.MediaRecorder.VideoEncoder.HEVC;
import static android.media.MediaRecorder.VideoEncoder.MPEG_4_SP;
import static android.media.MediaRecorder.VideoEncoder.VP8;
import android.media.CamcorderProfile;
import android.media.MediaFormat;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.google.auto.value.AutoValue;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* CamcorderProfileProxy defines the get methods that is mapping to the fields of
* {@link CamcorderProfile}.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@AutoValue
public abstract class CamcorderProfileProxy {
@Retention(RetentionPolicy.SOURCE)
@IntDef({H263, H264, HEVC, VP8, MPEG_4_SP, DEFAULT})
@interface VideoEncoder {
}
/** Creates a CamcorderProfileProxy instance. */
@NonNull
public static CamcorderProfileProxy create(int duration,
int quality,
int fileFormat,
@VideoEncoder int videoCodec,
int videoBitRate,
int videoFrameRate,
int videoFrameWidth,
int videoFrameHeight,
int audioCodec,
int audioBitRate,
int audioSampleRate,
int audioChannels) {
return new AutoValue_CamcorderProfileProxy(
duration,
quality,
fileFormat,
videoCodec,
videoBitRate,
videoFrameRate,
videoFrameWidth,
videoFrameHeight,
audioCodec,
audioBitRate,
audioSampleRate,
audioChannels
);
}
/** Creates a CamcorderProfileProxy instance from {@link CamcorderProfile}. */
@NonNull
public static CamcorderProfileProxy fromCamcorderProfile(
@NonNull CamcorderProfile camcorderProfile) {
return new AutoValue_CamcorderProfileProxy(
camcorderProfile.duration,
camcorderProfile.quality,
camcorderProfile.fileFormat,
camcorderProfile.videoCodec,
camcorderProfile.videoBitRate,
camcorderProfile.videoFrameRate,
camcorderProfile.videoFrameWidth,
camcorderProfile.videoFrameHeight,
camcorderProfile.audioCodec,
camcorderProfile.audioBitRate,
camcorderProfile.audioSampleRate,
camcorderProfile.audioChannels
);
}
/** @see CamcorderProfile#duration */
public abstract int getDuration();
/** @see CamcorderProfile#quality */
public abstract int getQuality();
/** @see CamcorderProfile#fileFormat */
public abstract int getFileFormat();
/** @see CamcorderProfile#videoCodec */
@VideoEncoder
public abstract int getVideoCodec();
/** @see CamcorderProfile#videoBitRate */
public abstract int getVideoBitRate();
/** @see CamcorderProfile#videoFrameRate */
public abstract int getVideoFrameRate();
/** @see CamcorderProfile#videoFrameWidth */
public abstract int getVideoFrameWidth();
/** @see CamcorderProfile#videoFrameHeight */
public abstract int getVideoFrameHeight();
/** @see CamcorderProfile#audioCodec */
public abstract int getAudioCodec();
/** @see CamcorderProfile#audioBitRate */
public abstract int getAudioBitRate();
/** @see CamcorderProfile#audioSampleRate */
public abstract int getAudioSampleRate();
/** @see CamcorderProfile#audioChannels */
public abstract int getAudioChannels();
/**
* Returns a mime-type string for the video codec type returned by {@link #getVideoCodec()}.
*
* @return A mime-type string or {@code null} if the codec type is
* {@link android.media.MediaRecorder.VideoEncoder#DEFAULT}, as this type is under-defined
* and cannot be resolved to a specific mime type without more information.
*/
@Nullable
public String getVideoCodecMimeType() {
// Mime-type definitions taken from
// frameworks/av/media/libstagefright/foundation/MediaDefs.cpp
switch (getVideoCodec()) {
case H263:
return MediaFormat.MIMETYPE_VIDEO_H263;
case H264:
return MediaFormat.MIMETYPE_VIDEO_AVC;
case HEVC:
return MediaFormat.MIMETYPE_VIDEO_HEVC;
case VP8:
return MediaFormat.MIMETYPE_VIDEO_VP8;
case MPEG_4_SP:
return MediaFormat.MIMETYPE_VIDEO_MPEG4;
case DEFAULT:
break;
}
return null;
}
}
| 33.839286 | 96 | 0.667546 |
3082e7661acc9b6b7ea7e6878fcb22a0b1663ca2 | 526 | package com.github.dakusui.jcunit8.tests.validation.testresources;
import com.github.dakusui.jcunit8.factorspace.Parameter;
import com.github.dakusui.jcunit8.runners.junit4.JCUnit8;
import com.github.dakusui.jcunit8.runners.junit4.annotations.ParameterSource;
import org.junit.runner.RunWith;
import static java.util.Arrays.asList;
@RunWith(JCUnit8.class)
public class NoTestMethod {
@ParameterSource
public Parameter.Simple.Factory<Integer> a() {
return Parameter.Simple.Factory.of(asList(-1, 0, 1, 2, 4));
}
}
| 29.222222 | 77 | 0.792776 |
863ae2e4f770f90e2d498f1cc76f98e9f77c1e7f | 5,245 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.client.sys;
import com.haulmont.cuba.core.app.PersistenceManagerService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Client-side caching proxy for the <code>PersistenceManagerService</code>.
* <p>
* Caches the PersistenceManager information for the whole life time of the client application.
* The web-client's <code>Caching</code> MBean contains a method to clear this cache.
* </p>
*/
@Component(PersistenceManagerClient.NAME)
@Primary
public class PersistenceManagerClient implements PersistenceManagerService {
public static final String NAME = "cuba_PersistenceManagerClient";
protected static class CacheEntry {
Boolean useLazyCollection;
Boolean useLookupScreen;
Integer fetchUI;
Integer maxFetchUI;
}
protected static class DbmsCacheEntry {
boolean supportsLobSortingAndFiltering;
boolean emulateEqualsByLike;
}
protected Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
protected Map<String, DbmsCacheEntry> dbmsCache = new ConcurrentHashMap<>();
protected volatile String dbmsType;
protected volatile String dbmsVersion;
protected volatile String uniqueConstraintViolationPattern;
protected volatile Boolean defaultNullSorting;
@Inject
protected PersistenceManagerService service;
protected CacheEntry getCacheEntry(String entityName) {
CacheEntry cacheEntry = cache.get(entityName);
if (cacheEntry == null) {
cacheEntry = new CacheEntry();
cache.put(entityName, cacheEntry);
}
return cacheEntry;
}
@Override
public boolean useLazyCollection(String entityName) {
CacheEntry cacheEntry = getCacheEntry(entityName);
if (cacheEntry.useLazyCollection == null) {
cacheEntry.useLazyCollection = service.useLazyCollection(entityName);
}
return cacheEntry.useLazyCollection;
}
@Override
public boolean useLookupScreen(String entityName) {
CacheEntry cacheEntry = getCacheEntry(entityName);
if (cacheEntry.useLookupScreen == null) {
cacheEntry.useLookupScreen = service.useLookupScreen(entityName);
}
return cacheEntry.useLookupScreen;
}
@Override
public int getFetchUI(String entityName) {
CacheEntry cacheEntry = getCacheEntry(entityName);
if (cacheEntry.fetchUI == null) {
cacheEntry.fetchUI = service.getFetchUI(entityName);
}
return cacheEntry.fetchUI;
}
@Override
public int getMaxFetchUI(String entityName) {
CacheEntry cacheEntry = getCacheEntry(entityName);
if (cacheEntry.maxFetchUI == null) {
cacheEntry.maxFetchUI = service.getMaxFetchUI(entityName);
}
return cacheEntry.maxFetchUI;
}
@Override
public String getDbmsType() {
if (dbmsType == null)
dbmsType = service.getDbmsType();
return dbmsType;
}
@Override
public String getDbmsVersion() {
if (dbmsVersion == null)
dbmsVersion = service.getDbmsVersion();
return dbmsVersion;
}
@Override
public String getUniqueConstraintViolationPattern() {
if (uniqueConstraintViolationPattern == null)
uniqueConstraintViolationPattern = service.getUniqueConstraintViolationPattern();
return uniqueConstraintViolationPattern;
}
@Override
public boolean isNullsLastSorting() {
if (defaultNullSorting == null)
defaultNullSorting = service.isNullsLastSorting();
return defaultNullSorting;
}
@Override
public boolean supportsLobSortingAndFiltering(String storeName) {
return storeName == null || getDbmsCacheEntry(storeName).supportsLobSortingAndFiltering;
}
@Override
public boolean emulateEqualsByLike(String storeName) {
return storeName == null || getDbmsCacheEntry(storeName).emulateEqualsByLike;
}
protected DbmsCacheEntry getDbmsCacheEntry(String storeName) {
return dbmsCache.computeIfAbsent(storeName, s -> {
DbmsCacheEntry cacheEntry = new DbmsCacheEntry();
cacheEntry.supportsLobSortingAndFiltering = service.supportsLobSortingAndFiltering(s);
cacheEntry.emulateEqualsByLike = service.emulateEqualsByLike(s);
return cacheEntry;
});
}
public void clearCache() {
cache.clear();
}
} | 32.987421 | 98 | 0.699905 |
ba369e0aaa5165f2a44f13b10f994cfd963ef9f6 | 3,019 |
package nesne.proje;
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
import org.junit.*;
public class TestSubscriptionPlan {
ServiceProvider gsm_provider1=new GSMProvider("GSM Provider-1");
ServiceProvider cable_provider1=new CableProvider("Cable Provider-1");
SubscriptionPlan sub_plan1=new SubscriptionPlan("Subscription Plan-1");
SubscriptionPlan sub_plan2=new SubscriptionPlan("Subscription Plan-2",gsm_provider1);
SubscriptionPlan sub_plan3=new SubscriptionPlan("Subscription Plan-3");
SubscriptionPlan sub_plan4=new SubscriptionPlan("Subscription Plan-4",cable_provider1);
@Test
public void TestGetName(){
String expect1="Subscription Plan-1";
String expect2="Subscription Plan-2";
String expect3="Subscription Plan-3";
String expect4="Subscription Plan-4";
assertEquals(expect1,sub_plan1.getName());
assertEquals(expect2,sub_plan2.getName());
assertEquals(expect3,sub_plan3.getName());
assertEquals(expect4,sub_plan4.getName());
}
@Test
public void TestSetName(){
sub_plan1.setName("Subscription Plan-01");
sub_plan2.setName("Subscription Plan-02");
sub_plan3.setName("Subscription Plan-03");
sub_plan4.setName("Subscription Plan-04");
String expect1="Subscription Plan-01";
String expect2="Subscription Plan-02";
String expect3="Subscription Plan-03";
String expect4="Subscription Plan-04";
assertEquals(expect1,sub_plan1.getName());
assertEquals(expect2,sub_plan2.getName());
assertEquals(expect3,sub_plan3.getName());
assertEquals(expect4,sub_plan4.getName());
}
@Test
public void TestGetServiceProvider(){
ServiceProvider expect1=null;
ServiceProvider expect2=gsm_provider1;
ServiceProvider expect3=null;
ServiceProvider expect4=cable_provider1;
assertEquals(expect1,sub_plan1.getServiceProvider());
assertEquals(expect2,sub_plan2.getServiceProvider());
assertEquals(expect3,sub_plan3.getServiceProvider());
assertEquals(expect4,sub_plan4.getServiceProvider());
}
@Test
public void TestSetServiceProvider(){
sub_plan1.setServiceProvider(gsm_provider1);
sub_plan2.setServiceProvider(cable_provider1);
sub_plan3.setServiceProvider(cable_provider1);
sub_plan4.setServiceProvider(gsm_provider1);
ServiceProvider expect1=gsm_provider1;
ServiceProvider expect2=cable_provider1;
ServiceProvider expect3=cable_provider1;
ServiceProvider expect4=gsm_provider1;
assertEquals(expect1,sub_plan1.getServiceProvider());
assertEquals(expect2,sub_plan2.getServiceProvider());
assertEquals(expect3,sub_plan3.getServiceProvider());
assertEquals(expect4,sub_plan4.getServiceProvider());
}
}
| 39.723684 | 92 | 0.692945 |
2b8eb5b8b77899fd41d23df98800a8c4ba265a88 | 3,366 | package com.baidu.aip.face;
public class AddUserReply {
/**
* result : {"face_token":"c9d2bfcccaebdc41693826361d530d40","location":{"top":19.95,"left":25.13,"rotation":0,"width":45,"height":49}}
* log_id : 2579996545651
* error_msg : SUCCESS
* cached : 0
* error_code : 0
* timestamp : 1578643572
*/
private ResultBean result;
private long log_id;
private String error_msg;
private int cached;
private int error_code;
private int timestamp;
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public long getLog_id() {
return log_id;
}
public void setLog_id(long log_id) {
this.log_id = log_id;
}
public String getError_msg() {
return error_msg;
}
public void setError_msg(String error_msg) {
this.error_msg = error_msg;
}
public int getCached() {
return cached;
}
public void setCached(int cached) {
this.cached = cached;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public int getTimestamp() {
return timestamp;
}
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
public static class ResultBean {
/**
* face_token : c9d2bfcccaebdc41693826361d530d40
* location : {"top":19.95,"left":25.13,"rotation":0,"width":45,"height":49}
*/
private String face_token;
private LocationBean location;
public String getFace_token() {
return face_token;
}
public void setFace_token(String face_token) {
this.face_token = face_token;
}
public LocationBean getLocation() {
return location;
}
public void setLocation(LocationBean location) {
this.location = location;
}
public static class LocationBean {
/**
* top : 19.95
* left : 25.13
* rotation : 0
* width : 45
* height : 49
*/
private double top;
private double left;
private int rotation;
private int width;
private int height;
public double getTop() {
return top;
}
public void setTop(double top) {
this.top = top;
}
public double getLeft() {
return left;
}
public void setLeft(double left) {
this.left = left;
}
public int getRotation() {
return rotation;
}
public void setRotation(int rotation) {
this.rotation = rotation;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
}
}
| 22.144737 | 139 | 0.516043 |
b98965e90ec4a5de1b543417870809c71e3a8195 | 456 | module aion.boot {
requires aion.crypto;
requires aion.apiserver;
requires aion.zero.impl;
requires aion.log;
requires aion.evtmgr;
requires aion.mcf;
requires slf4j.api;
requires aion.p2p;
requires aion.fastvm;
requires aion.txpool.impl;
requires libnzmq;
uses org.aion.evtmgr.EventMgrModule;
uses org.aion.log.AionLoggerFactory;
requires aion.vm;
requires aion.util;
exports org.aion;
}
| 20.727273 | 40 | 0.686404 |
b5c06ad93e5553ec58132f56eb831c0e178fe08a | 3,692 | package io.pazuzu.registry.config;
import io.pazuzu.registry.properties.PazuzuRegistryProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.web.cors.CorsUtils;
import io.pazuzu.registry.oauth2.ClientIdAuthorityGrantingAuthenticationExtractor;
import io.pazuzu.registry.security.Roles;
import org.zalando.stups.oauth2.spring.security.expression.ExtendedOAuth2WebSecurityExpressionHandler;
import org.zalando.stups.oauth2.spring.server.DefaultTokenInfoRequestExecutor;
import org.zalando.stups.oauth2.spring.server.ExecutorWrappers;
import org.zalando.stups.oauth2.spring.server.TokenInfoResourceServerTokenServices;
import org.zalando.stups.tokens.config.AccessTokensBeanProperties;
@Profile({"production", "oauth"})
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(jsr250Enabled = true)
@EnableConfigurationProperties(PazuzuRegistryProperties.class)
public class OAuthConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private AccessTokensBeanProperties accessTokensBeanProperties;
@Autowired
private PazuzuRegistryProperties registryProperties;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// here is the important part for stups-expression-handler
resources.expressionHandler(new ExtendedOAuth2WebSecurityExpressionHandler());
}
@Override
public void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.httpBasic()
.disable()
.anonymous()
.and()
.requestMatchers()
.antMatchers("/api/**")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers("/api/health").permitAll()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/**").permitAll()
//FIXME: disabled oauth
.anyRequest().permitAll();
// @formatter:on
}
@Bean
public ResourceServerTokenServices customResourceTokenServices() {
return new TokenInfoResourceServerTokenServices("pazuzu-registry",
new ClientIdAuthorityGrantingAuthenticationExtractor(registryProperties.getAdmins(), Roles.ADMIN),
ExecutorWrappers
.wrap(new DefaultTokenInfoRequestExecutor(
accessTokensBeanProperties.getTokenInfoUri().toString())));
}
}
| 46.734177 | 114 | 0.750813 |
d080c0bc0d76969ce6c257b10f3ecead19633a96 | 156,142 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package pasalab.dfs.perf.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-03-12")
public class MasterService {
public interface Iface {
public boolean slave_canRun(int taskId, String nodeName) throws SlaveNotRegisterException, org.apache.thrift.TException;
public void slave_finish(int taskId, String nodeName, boolean successFinish) throws SlaveNotRegisterException, org.apache.thrift.TException;
public void slave_ready(int taskId, String nodeName, boolean successSetup) throws SlaveNotRegisterException, org.apache.thrift.TException;
public boolean slave_register(int taskId, String nodeName, String cleanupDir) throws SlaveAlreadyRegisterException, org.apache.thrift.TException;
}
public interface AsyncIface {
public void slave_canRun(int taskId, String nodeName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
public void slave_finish(int taskId, String nodeName, boolean successFinish, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
public void slave_ready(int taskId, String nodeName, boolean successSetup, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
public void slave_register(int taskId, String nodeName, String cleanupDir, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public boolean slave_canRun(int taskId, String nodeName) throws SlaveNotRegisterException, org.apache.thrift.TException
{
send_slave_canRun(taskId, nodeName);
return recv_slave_canRun();
}
public void send_slave_canRun(int taskId, String nodeName) throws org.apache.thrift.TException
{
slave_canRun_args args = new slave_canRun_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
sendBase("slave_canRun", args);
}
public boolean recv_slave_canRun() throws SlaveNotRegisterException, org.apache.thrift.TException
{
slave_canRun_result result = new slave_canRun_result();
receiveBase(result, "slave_canRun");
if (result.isSetSuccess()) {
return result.success;
}
if (result.e != null) {
throw result.e;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "slave_canRun failed: unknown result");
}
public void slave_finish(int taskId, String nodeName, boolean successFinish) throws SlaveNotRegisterException, org.apache.thrift.TException
{
send_slave_finish(taskId, nodeName, successFinish);
recv_slave_finish();
}
public void send_slave_finish(int taskId, String nodeName, boolean successFinish) throws org.apache.thrift.TException
{
slave_finish_args args = new slave_finish_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.setSuccessFinish(successFinish);
sendBase("slave_finish", args);
}
public void recv_slave_finish() throws SlaveNotRegisterException, org.apache.thrift.TException
{
slave_finish_result result = new slave_finish_result();
receiveBase(result, "slave_finish");
if (result.e != null) {
throw result.e;
}
return;
}
public void slave_ready(int taskId, String nodeName, boolean successSetup) throws SlaveNotRegisterException, org.apache.thrift.TException
{
send_slave_ready(taskId, nodeName, successSetup);
recv_slave_ready();
}
public void send_slave_ready(int taskId, String nodeName, boolean successSetup) throws org.apache.thrift.TException
{
slave_ready_args args = new slave_ready_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.setSuccessSetup(successSetup);
sendBase("slave_ready", args);
}
public void recv_slave_ready() throws SlaveNotRegisterException, org.apache.thrift.TException
{
slave_ready_result result = new slave_ready_result();
receiveBase(result, "slave_ready");
if (result.e != null) {
throw result.e;
}
return;
}
public boolean slave_register(int taskId, String nodeName, String cleanupDir) throws SlaveAlreadyRegisterException, org.apache.thrift.TException
{
send_slave_register(taskId, nodeName, cleanupDir);
return recv_slave_register();
}
public void send_slave_register(int taskId, String nodeName, String cleanupDir) throws org.apache.thrift.TException
{
slave_register_args args = new slave_register_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.setCleanupDir(cleanupDir);
sendBase("slave_register", args);
}
public boolean recv_slave_register() throws SlaveAlreadyRegisterException, org.apache.thrift.TException
{
slave_register_result result = new slave_register_result();
receiveBase(result, "slave_register");
if (result.isSetSuccess()) {
return result.success;
}
if (result.e != null) {
throw result.e;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "slave_register failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void slave_canRun(int taskId, String nodeName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
slave_canRun_call method_call = new slave_canRun_call(taskId, nodeName, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class slave_canRun_call extends org.apache.thrift.async.TAsyncMethodCall {
private int taskId;
private String nodeName;
public slave_canRun_call(int taskId, String nodeName, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.taskId = taskId;
this.nodeName = nodeName;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("slave_canRun", org.apache.thrift.protocol.TMessageType.CALL, 0));
slave_canRun_args args = new slave_canRun_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.write(prot);
prot.writeMessageEnd();
}
public boolean getResult() throws SlaveNotRegisterException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_slave_canRun();
}
}
public void slave_finish(int taskId, String nodeName, boolean successFinish, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
slave_finish_call method_call = new slave_finish_call(taskId, nodeName, successFinish, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class slave_finish_call extends org.apache.thrift.async.TAsyncMethodCall {
private int taskId;
private String nodeName;
private boolean successFinish;
public slave_finish_call(int taskId, String nodeName, boolean successFinish, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.taskId = taskId;
this.nodeName = nodeName;
this.successFinish = successFinish;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("slave_finish", org.apache.thrift.protocol.TMessageType.CALL, 0));
slave_finish_args args = new slave_finish_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.setSuccessFinish(successFinish);
args.write(prot);
prot.writeMessageEnd();
}
public void getResult() throws SlaveNotRegisterException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
(new Client(prot)).recv_slave_finish();
}
}
public void slave_ready(int taskId, String nodeName, boolean successSetup, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
slave_ready_call method_call = new slave_ready_call(taskId, nodeName, successSetup, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class slave_ready_call extends org.apache.thrift.async.TAsyncMethodCall {
private int taskId;
private String nodeName;
private boolean successSetup;
public slave_ready_call(int taskId, String nodeName, boolean successSetup, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.taskId = taskId;
this.nodeName = nodeName;
this.successSetup = successSetup;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("slave_ready", org.apache.thrift.protocol.TMessageType.CALL, 0));
slave_ready_args args = new slave_ready_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.setSuccessSetup(successSetup);
args.write(prot);
prot.writeMessageEnd();
}
public void getResult() throws SlaveNotRegisterException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
(new Client(prot)).recv_slave_ready();
}
}
public void slave_register(int taskId, String nodeName, String cleanupDir, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
slave_register_call method_call = new slave_register_call(taskId, nodeName, cleanupDir, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class slave_register_call extends org.apache.thrift.async.TAsyncMethodCall {
private int taskId;
private String nodeName;
private String cleanupDir;
public slave_register_call(int taskId, String nodeName, String cleanupDir, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.taskId = taskId;
this.nodeName = nodeName;
this.cleanupDir = cleanupDir;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("slave_register", org.apache.thrift.protocol.TMessageType.CALL, 0));
slave_register_args args = new slave_register_args();
args.setTaskId(taskId);
args.setNodeName(nodeName);
args.setCleanupDir(cleanupDir);
args.write(prot);
prot.writeMessageEnd();
}
public boolean getResult() throws SlaveAlreadyRegisterException, org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_slave_register();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("slave_canRun", new slave_canRun());
processMap.put("slave_finish", new slave_finish());
processMap.put("slave_ready", new slave_ready());
processMap.put("slave_register", new slave_register());
return processMap;
}
public static class slave_canRun<I extends Iface> extends org.apache.thrift.ProcessFunction<I, slave_canRun_args> {
public slave_canRun() {
super("slave_canRun");
}
public slave_canRun_args getEmptyArgsInstance() {
return new slave_canRun_args();
}
protected boolean isOneway() {
return false;
}
public slave_canRun_result getResult(I iface, slave_canRun_args args) throws org.apache.thrift.TException {
slave_canRun_result result = new slave_canRun_result();
try {
result.success = iface.slave_canRun(args.taskId, args.nodeName);
result.setSuccessIsSet(true);
} catch (SlaveNotRegisterException e) {
result.e = e;
}
return result;
}
}
public static class slave_finish<I extends Iface> extends org.apache.thrift.ProcessFunction<I, slave_finish_args> {
public slave_finish() {
super("slave_finish");
}
public slave_finish_args getEmptyArgsInstance() {
return new slave_finish_args();
}
protected boolean isOneway() {
return false;
}
public slave_finish_result getResult(I iface, slave_finish_args args) throws org.apache.thrift.TException {
slave_finish_result result = new slave_finish_result();
try {
iface.slave_finish(args.taskId, args.nodeName, args.successFinish);
} catch (SlaveNotRegisterException e) {
result.e = e;
}
return result;
}
}
public static class slave_ready<I extends Iface> extends org.apache.thrift.ProcessFunction<I, slave_ready_args> {
public slave_ready() {
super("slave_ready");
}
public slave_ready_args getEmptyArgsInstance() {
return new slave_ready_args();
}
protected boolean isOneway() {
return false;
}
public slave_ready_result getResult(I iface, slave_ready_args args) throws org.apache.thrift.TException {
slave_ready_result result = new slave_ready_result();
try {
iface.slave_ready(args.taskId, args.nodeName, args.successSetup);
} catch (SlaveNotRegisterException e) {
result.e = e;
}
return result;
}
}
public static class slave_register<I extends Iface> extends org.apache.thrift.ProcessFunction<I, slave_register_args> {
public slave_register() {
super("slave_register");
}
public slave_register_args getEmptyArgsInstance() {
return new slave_register_args();
}
protected boolean isOneway() {
return false;
}
public slave_register_result getResult(I iface, slave_register_args args) throws org.apache.thrift.TException {
slave_register_result result = new slave_register_result();
try {
result.success = iface.slave_register(args.taskId, args.nodeName, args.cleanupDir);
result.setSuccessIsSet(true);
} catch (SlaveAlreadyRegisterException e) {
result.e = e;
}
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("slave_canRun", new slave_canRun());
processMap.put("slave_finish", new slave_finish());
processMap.put("slave_ready", new slave_ready());
processMap.put("slave_register", new slave_register());
return processMap;
}
public static class slave_canRun<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, slave_canRun_args, Boolean> {
public slave_canRun() {
super("slave_canRun");
}
public slave_canRun_args getEmptyArgsInstance() {
return new slave_canRun_args();
}
public AsyncMethodCallback<Boolean> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<Boolean>() {
public void onComplete(Boolean o) {
slave_canRun_result result = new slave_canRun_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
slave_canRun_result result = new slave_canRun_result();
if (e instanceof SlaveNotRegisterException) {
result.e = (SlaveNotRegisterException) e;
result.setEIsSet(true);
msg = result;
}
else
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, slave_canRun_args args, org.apache.thrift.async.AsyncMethodCallback<Boolean> resultHandler) throws TException {
iface.slave_canRun(args.taskId, args.nodeName,resultHandler);
}
}
public static class slave_finish<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, slave_finish_args, Void> {
public slave_finish() {
super("slave_finish");
}
public slave_finish_args getEmptyArgsInstance() {
return new slave_finish_args();
}
public AsyncMethodCallback<Void> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<Void>() {
public void onComplete(Void o) {
slave_finish_result result = new slave_finish_result();
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
slave_finish_result result = new slave_finish_result();
if (e instanceof SlaveNotRegisterException) {
result.e = (SlaveNotRegisterException) e;
result.setEIsSet(true);
msg = result;
}
else
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, slave_finish_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws TException {
iface.slave_finish(args.taskId, args.nodeName, args.successFinish,resultHandler);
}
}
public static class slave_ready<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, slave_ready_args, Void> {
public slave_ready() {
super("slave_ready");
}
public slave_ready_args getEmptyArgsInstance() {
return new slave_ready_args();
}
public AsyncMethodCallback<Void> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<Void>() {
public void onComplete(Void o) {
slave_ready_result result = new slave_ready_result();
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
slave_ready_result result = new slave_ready_result();
if (e instanceof SlaveNotRegisterException) {
result.e = (SlaveNotRegisterException) e;
result.setEIsSet(true);
msg = result;
}
else
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, slave_ready_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws TException {
iface.slave_ready(args.taskId, args.nodeName, args.successSetup,resultHandler);
}
}
public static class slave_register<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, slave_register_args, Boolean> {
public slave_register() {
super("slave_register");
}
public slave_register_args getEmptyArgsInstance() {
return new slave_register_args();
}
public AsyncMethodCallback<Boolean> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<Boolean>() {
public void onComplete(Boolean o) {
slave_register_result result = new slave_register_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
slave_register_result result = new slave_register_result();
if (e instanceof SlaveAlreadyRegisterException) {
result.e = (SlaveAlreadyRegisterException) e;
result.setEIsSet(true);
msg = result;
}
else
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, slave_register_args args, org.apache.thrift.async.AsyncMethodCallback<Boolean> resultHandler) throws TException {
iface.slave_register(args.taskId, args.nodeName, args.cleanupDir,resultHandler);
}
}
}
public static class slave_canRun_args implements org.apache.thrift.TBase<slave_canRun_args, slave_canRun_args._Fields>, java.io.Serializable, Cloneable, Comparable<slave_canRun_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_canRun_args");
private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("taskId", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField NODE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_canRun_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_canRun_argsTupleSchemeFactory());
}
private int taskId; // required
private String nodeName; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TASK_ID((short)1, "taskId"),
NODE_NAME((short)2, "nodeName");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TASK_ID
return TASK_ID;
case 2: // NODE_NAME
return NODE_NAME;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TASKID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TASK_ID, new org.apache.thrift.meta_data.FieldMetaData("taskId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.NODE_NAME, new org.apache.thrift.meta_data.FieldMetaData("nodeName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_canRun_args.class, metaDataMap);
}
public slave_canRun_args() {
}
public slave_canRun_args(
int taskId,
String nodeName)
{
this();
this.taskId = taskId;
setTaskIdIsSet(true);
this.nodeName = nodeName;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_canRun_args(slave_canRun_args other) {
__isset_bitfield = other.__isset_bitfield;
this.taskId = other.taskId;
if (other.isSetNodeName()) {
this.nodeName = other.nodeName;
}
}
public slave_canRun_args deepCopy() {
return new slave_canRun_args(this);
}
@Override
public void clear() {
setTaskIdIsSet(false);
this.taskId = 0;
this.nodeName = null;
}
public int getTaskId() {
return this.taskId;
}
public slave_canRun_args setTaskId(int taskId) {
this.taskId = taskId;
setTaskIdIsSet(true);
return this;
}
public void unsetTaskId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TASKID_ISSET_ID);
}
/** Returns true if field taskId is set (has been assigned a value) and false otherwise */
public boolean isSetTaskId() {
return EncodingUtils.testBit(__isset_bitfield, __TASKID_ISSET_ID);
}
public void setTaskIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TASKID_ISSET_ID, value);
}
public String getNodeName() {
return this.nodeName;
}
public slave_canRun_args setNodeName(String nodeName) {
this.nodeName = nodeName;
return this;
}
public void unsetNodeName() {
this.nodeName = null;
}
/** Returns true if field nodeName is set (has been assigned a value) and false otherwise */
public boolean isSetNodeName() {
return this.nodeName != null;
}
public void setNodeNameIsSet(boolean value) {
if (!value) {
this.nodeName = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TASK_ID:
if (value == null) {
unsetTaskId();
} else {
setTaskId((Integer)value);
}
break;
case NODE_NAME:
if (value == null) {
unsetNodeName();
} else {
setNodeName((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TASK_ID:
return getTaskId();
case NODE_NAME:
return getNodeName();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TASK_ID:
return isSetTaskId();
case NODE_NAME:
return isSetNodeName();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_canRun_args)
return this.equals((slave_canRun_args)that);
return false;
}
public boolean equals(slave_canRun_args that) {
if (that == null)
return false;
boolean this_present_taskId = true;
boolean that_present_taskId = true;
if (this_present_taskId || that_present_taskId) {
if (!(this_present_taskId && that_present_taskId))
return false;
if (this.taskId != that.taskId)
return false;
}
boolean this_present_nodeName = true && this.isSetNodeName();
boolean that_present_nodeName = true && that.isSetNodeName();
if (this_present_nodeName || that_present_nodeName) {
if (!(this_present_nodeName && that_present_nodeName))
return false;
if (!this.nodeName.equals(that.nodeName))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_taskId = true;
list.add(present_taskId);
if (present_taskId)
list.add(taskId);
boolean present_nodeName = true && (isSetNodeName());
list.add(present_nodeName);
if (present_nodeName)
list.add(nodeName);
return list.hashCode();
}
@Override
public int compareTo(slave_canRun_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTaskId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetNodeName()).compareTo(other.isSetNodeName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetNodeName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeName, other.nodeName);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_canRun_args(");
boolean first = true;
sb.append("taskId:");
sb.append(this.taskId);
first = false;
if (!first) sb.append(", ");
sb.append("nodeName:");
if (this.nodeName == null) {
sb.append("null");
} else {
sb.append(this.nodeName);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_canRun_argsStandardSchemeFactory implements SchemeFactory {
public slave_canRun_argsStandardScheme getScheme() {
return new slave_canRun_argsStandardScheme();
}
}
private static class slave_canRun_argsStandardScheme extends StandardScheme<slave_canRun_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_canRun_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TASK_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NODE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_canRun_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(TASK_ID_FIELD_DESC);
oprot.writeI32(struct.taskId);
oprot.writeFieldEnd();
if (struct.nodeName != null) {
oprot.writeFieldBegin(NODE_NAME_FIELD_DESC);
oprot.writeString(struct.nodeName);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_canRun_argsTupleSchemeFactory implements SchemeFactory {
public slave_canRun_argsTupleScheme getScheme() {
return new slave_canRun_argsTupleScheme();
}
}
private static class slave_canRun_argsTupleScheme extends TupleScheme<slave_canRun_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_canRun_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetTaskId()) {
optionals.set(0);
}
if (struct.isSetNodeName()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetTaskId()) {
oprot.writeI32(struct.taskId);
}
if (struct.isSetNodeName()) {
oprot.writeString(struct.nodeName);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_canRun_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
}
if (incoming.get(1)) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
}
}
}
}
public static class slave_canRun_result implements org.apache.thrift.TBase<slave_canRun_result, slave_canRun_result._Fields>, java.io.Serializable, Cloneable, Comparable<slave_canRun_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_canRun_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_canRun_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_canRun_resultTupleSchemeFactory());
}
private boolean success; // required
private SlaveNotRegisterException e; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success"),
E((short)1, "e");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
case 1: // E
return E;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_canRun_result.class, metaDataMap);
}
public slave_canRun_result() {
}
public slave_canRun_result(
boolean success,
SlaveNotRegisterException e)
{
this();
this.success = success;
setSuccessIsSet(true);
this.e = e;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_canRun_result(slave_canRun_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
if (other.isSetE()) {
this.e = new SlaveNotRegisterException(other.e);
}
}
public slave_canRun_result deepCopy() {
return new slave_canRun_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
this.e = null;
}
public boolean isSuccess() {
return this.success;
}
public slave_canRun_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
public SlaveNotRegisterException getE() {
return this.e;
}
public slave_canRun_result setE(SlaveNotRegisterException e) {
this.e = e;
return this;
}
public void unsetE() {
this.e = null;
}
/** Returns true if field e is set (has been assigned a value) and false otherwise */
public boolean isSetE() {
return this.e != null;
}
public void setEIsSet(boolean value) {
if (!value) {
this.e = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((Boolean)value);
}
break;
case E:
if (value == null) {
unsetE();
} else {
setE((SlaveNotRegisterException)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
case E:
return getE();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
case E:
return isSetE();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_canRun_result)
return this.equals((slave_canRun_result)that);
return false;
}
public boolean equals(slave_canRun_result that) {
if (that == null)
return false;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
boolean this_present_e = true && this.isSetE();
boolean that_present_e = true && that.isSetE();
if (this_present_e || that_present_e) {
if (!(this_present_e && that_present_e))
return false;
if (!this.e.equals(that.e))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_success = true;
list.add(present_success);
if (present_success)
list.add(success);
boolean present_e = true && (isSetE());
list.add(present_e);
if (present_e)
list.add(e);
return list.hashCode();
}
@Override
public int compareTo(slave_canRun_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetE()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_canRun_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
if (!first) sb.append(", ");
sb.append("e:");
if (this.e == null) {
sb.append("null");
} else {
sb.append(this.e);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_canRun_resultStandardSchemeFactory implements SchemeFactory {
public slave_canRun_resultStandardScheme getScheme() {
return new slave_canRun_resultStandardScheme();
}
}
private static class slave_canRun_resultStandardScheme extends StandardScheme<slave_canRun_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_canRun_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 1: // E
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.e = new SlaveNotRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_canRun_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
if (struct.e != null) {
oprot.writeFieldBegin(E_FIELD_DESC);
struct.e.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_canRun_resultTupleSchemeFactory implements SchemeFactory {
public slave_canRun_resultTupleScheme getScheme() {
return new slave_canRun_resultTupleScheme();
}
}
private static class slave_canRun_resultTupleScheme extends TupleScheme<slave_canRun_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_canRun_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
if (struct.isSetE()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
if (struct.isSetE()) {
struct.e.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_canRun_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
if (incoming.get(1)) {
struct.e = new SlaveNotRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
}
}
}
}
public static class slave_finish_args implements org.apache.thrift.TBase<slave_finish_args, slave_finish_args._Fields>, java.io.Serializable, Cloneable, Comparable<slave_finish_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_finish_args");
private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("taskId", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField NODE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField SUCCESS_FINISH_FIELD_DESC = new org.apache.thrift.protocol.TField("successFinish", org.apache.thrift.protocol.TType.BOOL, (short)3);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_finish_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_finish_argsTupleSchemeFactory());
}
private int taskId; // required
private String nodeName; // required
private boolean successFinish; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TASK_ID((short)1, "taskId"),
NODE_NAME((short)2, "nodeName"),
SUCCESS_FINISH((short)3, "successFinish");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TASK_ID
return TASK_ID;
case 2: // NODE_NAME
return NODE_NAME;
case 3: // SUCCESS_FINISH
return SUCCESS_FINISH;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TASKID_ISSET_ID = 0;
private static final int __SUCCESSFINISH_ISSET_ID = 1;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TASK_ID, new org.apache.thrift.meta_data.FieldMetaData("taskId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.NODE_NAME, new org.apache.thrift.meta_data.FieldMetaData("nodeName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.SUCCESS_FINISH, new org.apache.thrift.meta_data.FieldMetaData("successFinish", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_finish_args.class, metaDataMap);
}
public slave_finish_args() {
}
public slave_finish_args(
int taskId,
String nodeName,
boolean successFinish)
{
this();
this.taskId = taskId;
setTaskIdIsSet(true);
this.nodeName = nodeName;
this.successFinish = successFinish;
setSuccessFinishIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_finish_args(slave_finish_args other) {
__isset_bitfield = other.__isset_bitfield;
this.taskId = other.taskId;
if (other.isSetNodeName()) {
this.nodeName = other.nodeName;
}
this.successFinish = other.successFinish;
}
public slave_finish_args deepCopy() {
return new slave_finish_args(this);
}
@Override
public void clear() {
setTaskIdIsSet(false);
this.taskId = 0;
this.nodeName = null;
setSuccessFinishIsSet(false);
this.successFinish = false;
}
public int getTaskId() {
return this.taskId;
}
public slave_finish_args setTaskId(int taskId) {
this.taskId = taskId;
setTaskIdIsSet(true);
return this;
}
public void unsetTaskId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TASKID_ISSET_ID);
}
/** Returns true if field taskId is set (has been assigned a value) and false otherwise */
public boolean isSetTaskId() {
return EncodingUtils.testBit(__isset_bitfield, __TASKID_ISSET_ID);
}
public void setTaskIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TASKID_ISSET_ID, value);
}
public String getNodeName() {
return this.nodeName;
}
public slave_finish_args setNodeName(String nodeName) {
this.nodeName = nodeName;
return this;
}
public void unsetNodeName() {
this.nodeName = null;
}
/** Returns true if field nodeName is set (has been assigned a value) and false otherwise */
public boolean isSetNodeName() {
return this.nodeName != null;
}
public void setNodeNameIsSet(boolean value) {
if (!value) {
this.nodeName = null;
}
}
public boolean isSuccessFinish() {
return this.successFinish;
}
public slave_finish_args setSuccessFinish(boolean successFinish) {
this.successFinish = successFinish;
setSuccessFinishIsSet(true);
return this;
}
public void unsetSuccessFinish() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESSFINISH_ISSET_ID);
}
/** Returns true if field successFinish is set (has been assigned a value) and false otherwise */
public boolean isSetSuccessFinish() {
return EncodingUtils.testBit(__isset_bitfield, __SUCCESSFINISH_ISSET_ID);
}
public void setSuccessFinishIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESSFINISH_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TASK_ID:
if (value == null) {
unsetTaskId();
} else {
setTaskId((Integer)value);
}
break;
case NODE_NAME:
if (value == null) {
unsetNodeName();
} else {
setNodeName((String)value);
}
break;
case SUCCESS_FINISH:
if (value == null) {
unsetSuccessFinish();
} else {
setSuccessFinish((Boolean)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TASK_ID:
return getTaskId();
case NODE_NAME:
return getNodeName();
case SUCCESS_FINISH:
return isSuccessFinish();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TASK_ID:
return isSetTaskId();
case NODE_NAME:
return isSetNodeName();
case SUCCESS_FINISH:
return isSetSuccessFinish();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_finish_args)
return this.equals((slave_finish_args)that);
return false;
}
public boolean equals(slave_finish_args that) {
if (that == null)
return false;
boolean this_present_taskId = true;
boolean that_present_taskId = true;
if (this_present_taskId || that_present_taskId) {
if (!(this_present_taskId && that_present_taskId))
return false;
if (this.taskId != that.taskId)
return false;
}
boolean this_present_nodeName = true && this.isSetNodeName();
boolean that_present_nodeName = true && that.isSetNodeName();
if (this_present_nodeName || that_present_nodeName) {
if (!(this_present_nodeName && that_present_nodeName))
return false;
if (!this.nodeName.equals(that.nodeName))
return false;
}
boolean this_present_successFinish = true;
boolean that_present_successFinish = true;
if (this_present_successFinish || that_present_successFinish) {
if (!(this_present_successFinish && that_present_successFinish))
return false;
if (this.successFinish != that.successFinish)
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_taskId = true;
list.add(present_taskId);
if (present_taskId)
list.add(taskId);
boolean present_nodeName = true && (isSetNodeName());
list.add(present_nodeName);
if (present_nodeName)
list.add(nodeName);
boolean present_successFinish = true;
list.add(present_successFinish);
if (present_successFinish)
list.add(successFinish);
return list.hashCode();
}
@Override
public int compareTo(slave_finish_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTaskId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetNodeName()).compareTo(other.isSetNodeName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetNodeName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeName, other.nodeName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetSuccessFinish()).compareTo(other.isSetSuccessFinish());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccessFinish()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.successFinish, other.successFinish);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_finish_args(");
boolean first = true;
sb.append("taskId:");
sb.append(this.taskId);
first = false;
if (!first) sb.append(", ");
sb.append("nodeName:");
if (this.nodeName == null) {
sb.append("null");
} else {
sb.append(this.nodeName);
}
first = false;
if (!first) sb.append(", ");
sb.append("successFinish:");
sb.append(this.successFinish);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_finish_argsStandardSchemeFactory implements SchemeFactory {
public slave_finish_argsStandardScheme getScheme() {
return new slave_finish_argsStandardScheme();
}
}
private static class slave_finish_argsStandardScheme extends StandardScheme<slave_finish_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_finish_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TASK_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NODE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // SUCCESS_FINISH
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.successFinish = iprot.readBool();
struct.setSuccessFinishIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_finish_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(TASK_ID_FIELD_DESC);
oprot.writeI32(struct.taskId);
oprot.writeFieldEnd();
if (struct.nodeName != null) {
oprot.writeFieldBegin(NODE_NAME_FIELD_DESC);
oprot.writeString(struct.nodeName);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(SUCCESS_FINISH_FIELD_DESC);
oprot.writeBool(struct.successFinish);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_finish_argsTupleSchemeFactory implements SchemeFactory {
public slave_finish_argsTupleScheme getScheme() {
return new slave_finish_argsTupleScheme();
}
}
private static class slave_finish_argsTupleScheme extends TupleScheme<slave_finish_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_finish_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetTaskId()) {
optionals.set(0);
}
if (struct.isSetNodeName()) {
optionals.set(1);
}
if (struct.isSetSuccessFinish()) {
optionals.set(2);
}
oprot.writeBitSet(optionals, 3);
if (struct.isSetTaskId()) {
oprot.writeI32(struct.taskId);
}
if (struct.isSetNodeName()) {
oprot.writeString(struct.nodeName);
}
if (struct.isSetSuccessFinish()) {
oprot.writeBool(struct.successFinish);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_finish_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(3);
if (incoming.get(0)) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
}
if (incoming.get(1)) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
}
if (incoming.get(2)) {
struct.successFinish = iprot.readBool();
struct.setSuccessFinishIsSet(true);
}
}
}
}
public static class slave_finish_result implements org.apache.thrift.TBase<slave_finish_result, slave_finish_result._Fields>, java.io.Serializable, Cloneable, Comparable<slave_finish_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_finish_result");
private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_finish_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_finish_resultTupleSchemeFactory());
}
private SlaveNotRegisterException e; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
E((short)1, "e");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // E
return E;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_finish_result.class, metaDataMap);
}
public slave_finish_result() {
}
public slave_finish_result(
SlaveNotRegisterException e)
{
this();
this.e = e;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_finish_result(slave_finish_result other) {
if (other.isSetE()) {
this.e = new SlaveNotRegisterException(other.e);
}
}
public slave_finish_result deepCopy() {
return new slave_finish_result(this);
}
@Override
public void clear() {
this.e = null;
}
public SlaveNotRegisterException getE() {
return this.e;
}
public slave_finish_result setE(SlaveNotRegisterException e) {
this.e = e;
return this;
}
public void unsetE() {
this.e = null;
}
/** Returns true if field e is set (has been assigned a value) and false otherwise */
public boolean isSetE() {
return this.e != null;
}
public void setEIsSet(boolean value) {
if (!value) {
this.e = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case E:
if (value == null) {
unsetE();
} else {
setE((SlaveNotRegisterException)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case E:
return getE();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case E:
return isSetE();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_finish_result)
return this.equals((slave_finish_result)that);
return false;
}
public boolean equals(slave_finish_result that) {
if (that == null)
return false;
boolean this_present_e = true && this.isSetE();
boolean that_present_e = true && that.isSetE();
if (this_present_e || that_present_e) {
if (!(this_present_e && that_present_e))
return false;
if (!this.e.equals(that.e))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_e = true && (isSetE());
list.add(present_e);
if (present_e)
list.add(e);
return list.hashCode();
}
@Override
public int compareTo(slave_finish_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetE()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_finish_result(");
boolean first = true;
sb.append("e:");
if (this.e == null) {
sb.append("null");
} else {
sb.append(this.e);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_finish_resultStandardSchemeFactory implements SchemeFactory {
public slave_finish_resultStandardScheme getScheme() {
return new slave_finish_resultStandardScheme();
}
}
private static class slave_finish_resultStandardScheme extends StandardScheme<slave_finish_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_finish_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // E
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.e = new SlaveNotRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_finish_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.e != null) {
oprot.writeFieldBegin(E_FIELD_DESC);
struct.e.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_finish_resultTupleSchemeFactory implements SchemeFactory {
public slave_finish_resultTupleScheme getScheme() {
return new slave_finish_resultTupleScheme();
}
}
private static class slave_finish_resultTupleScheme extends TupleScheme<slave_finish_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_finish_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetE()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetE()) {
struct.e.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_finish_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.e = new SlaveNotRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
}
}
}
}
public static class slave_ready_args implements org.apache.thrift.TBase<slave_ready_args, slave_ready_args._Fields>, java.io.Serializable, Cloneable, Comparable<slave_ready_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_ready_args");
private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("taskId", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField NODE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField SUCCESS_SETUP_FIELD_DESC = new org.apache.thrift.protocol.TField("successSetup", org.apache.thrift.protocol.TType.BOOL, (short)3);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_ready_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_ready_argsTupleSchemeFactory());
}
private int taskId; // required
private String nodeName; // required
private boolean successSetup; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TASK_ID((short)1, "taskId"),
NODE_NAME((short)2, "nodeName"),
SUCCESS_SETUP((short)3, "successSetup");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TASK_ID
return TASK_ID;
case 2: // NODE_NAME
return NODE_NAME;
case 3: // SUCCESS_SETUP
return SUCCESS_SETUP;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TASKID_ISSET_ID = 0;
private static final int __SUCCESSSETUP_ISSET_ID = 1;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TASK_ID, new org.apache.thrift.meta_data.FieldMetaData("taskId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.NODE_NAME, new org.apache.thrift.meta_data.FieldMetaData("nodeName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.SUCCESS_SETUP, new org.apache.thrift.meta_data.FieldMetaData("successSetup", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_ready_args.class, metaDataMap);
}
public slave_ready_args() {
}
public slave_ready_args(
int taskId,
String nodeName,
boolean successSetup)
{
this();
this.taskId = taskId;
setTaskIdIsSet(true);
this.nodeName = nodeName;
this.successSetup = successSetup;
setSuccessSetupIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_ready_args(slave_ready_args other) {
__isset_bitfield = other.__isset_bitfield;
this.taskId = other.taskId;
if (other.isSetNodeName()) {
this.nodeName = other.nodeName;
}
this.successSetup = other.successSetup;
}
public slave_ready_args deepCopy() {
return new slave_ready_args(this);
}
@Override
public void clear() {
setTaskIdIsSet(false);
this.taskId = 0;
this.nodeName = null;
setSuccessSetupIsSet(false);
this.successSetup = false;
}
public int getTaskId() {
return this.taskId;
}
public slave_ready_args setTaskId(int taskId) {
this.taskId = taskId;
setTaskIdIsSet(true);
return this;
}
public void unsetTaskId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TASKID_ISSET_ID);
}
/** Returns true if field taskId is set (has been assigned a value) and false otherwise */
public boolean isSetTaskId() {
return EncodingUtils.testBit(__isset_bitfield, __TASKID_ISSET_ID);
}
public void setTaskIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TASKID_ISSET_ID, value);
}
public String getNodeName() {
return this.nodeName;
}
public slave_ready_args setNodeName(String nodeName) {
this.nodeName = nodeName;
return this;
}
public void unsetNodeName() {
this.nodeName = null;
}
/** Returns true if field nodeName is set (has been assigned a value) and false otherwise */
public boolean isSetNodeName() {
return this.nodeName != null;
}
public void setNodeNameIsSet(boolean value) {
if (!value) {
this.nodeName = null;
}
}
public boolean isSuccessSetup() {
return this.successSetup;
}
public slave_ready_args setSuccessSetup(boolean successSetup) {
this.successSetup = successSetup;
setSuccessSetupIsSet(true);
return this;
}
public void unsetSuccessSetup() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESSSETUP_ISSET_ID);
}
/** Returns true if field successSetup is set (has been assigned a value) and false otherwise */
public boolean isSetSuccessSetup() {
return EncodingUtils.testBit(__isset_bitfield, __SUCCESSSETUP_ISSET_ID);
}
public void setSuccessSetupIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESSSETUP_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TASK_ID:
if (value == null) {
unsetTaskId();
} else {
setTaskId((Integer)value);
}
break;
case NODE_NAME:
if (value == null) {
unsetNodeName();
} else {
setNodeName((String)value);
}
break;
case SUCCESS_SETUP:
if (value == null) {
unsetSuccessSetup();
} else {
setSuccessSetup((Boolean)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TASK_ID:
return getTaskId();
case NODE_NAME:
return getNodeName();
case SUCCESS_SETUP:
return isSuccessSetup();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TASK_ID:
return isSetTaskId();
case NODE_NAME:
return isSetNodeName();
case SUCCESS_SETUP:
return isSetSuccessSetup();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_ready_args)
return this.equals((slave_ready_args)that);
return false;
}
public boolean equals(slave_ready_args that) {
if (that == null)
return false;
boolean this_present_taskId = true;
boolean that_present_taskId = true;
if (this_present_taskId || that_present_taskId) {
if (!(this_present_taskId && that_present_taskId))
return false;
if (this.taskId != that.taskId)
return false;
}
boolean this_present_nodeName = true && this.isSetNodeName();
boolean that_present_nodeName = true && that.isSetNodeName();
if (this_present_nodeName || that_present_nodeName) {
if (!(this_present_nodeName && that_present_nodeName))
return false;
if (!this.nodeName.equals(that.nodeName))
return false;
}
boolean this_present_successSetup = true;
boolean that_present_successSetup = true;
if (this_present_successSetup || that_present_successSetup) {
if (!(this_present_successSetup && that_present_successSetup))
return false;
if (this.successSetup != that.successSetup)
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_taskId = true;
list.add(present_taskId);
if (present_taskId)
list.add(taskId);
boolean present_nodeName = true && (isSetNodeName());
list.add(present_nodeName);
if (present_nodeName)
list.add(nodeName);
boolean present_successSetup = true;
list.add(present_successSetup);
if (present_successSetup)
list.add(successSetup);
return list.hashCode();
}
@Override
public int compareTo(slave_ready_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTaskId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetNodeName()).compareTo(other.isSetNodeName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetNodeName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeName, other.nodeName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetSuccessSetup()).compareTo(other.isSetSuccessSetup());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccessSetup()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.successSetup, other.successSetup);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_ready_args(");
boolean first = true;
sb.append("taskId:");
sb.append(this.taskId);
first = false;
if (!first) sb.append(", ");
sb.append("nodeName:");
if (this.nodeName == null) {
sb.append("null");
} else {
sb.append(this.nodeName);
}
first = false;
if (!first) sb.append(", ");
sb.append("successSetup:");
sb.append(this.successSetup);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_ready_argsStandardSchemeFactory implements SchemeFactory {
public slave_ready_argsStandardScheme getScheme() {
return new slave_ready_argsStandardScheme();
}
}
private static class slave_ready_argsStandardScheme extends StandardScheme<slave_ready_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_ready_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TASK_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NODE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // SUCCESS_SETUP
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.successSetup = iprot.readBool();
struct.setSuccessSetupIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_ready_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(TASK_ID_FIELD_DESC);
oprot.writeI32(struct.taskId);
oprot.writeFieldEnd();
if (struct.nodeName != null) {
oprot.writeFieldBegin(NODE_NAME_FIELD_DESC);
oprot.writeString(struct.nodeName);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(SUCCESS_SETUP_FIELD_DESC);
oprot.writeBool(struct.successSetup);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_ready_argsTupleSchemeFactory implements SchemeFactory {
public slave_ready_argsTupleScheme getScheme() {
return new slave_ready_argsTupleScheme();
}
}
private static class slave_ready_argsTupleScheme extends TupleScheme<slave_ready_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_ready_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetTaskId()) {
optionals.set(0);
}
if (struct.isSetNodeName()) {
optionals.set(1);
}
if (struct.isSetSuccessSetup()) {
optionals.set(2);
}
oprot.writeBitSet(optionals, 3);
if (struct.isSetTaskId()) {
oprot.writeI32(struct.taskId);
}
if (struct.isSetNodeName()) {
oprot.writeString(struct.nodeName);
}
if (struct.isSetSuccessSetup()) {
oprot.writeBool(struct.successSetup);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_ready_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(3);
if (incoming.get(0)) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
}
if (incoming.get(1)) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
}
if (incoming.get(2)) {
struct.successSetup = iprot.readBool();
struct.setSuccessSetupIsSet(true);
}
}
}
}
public static class slave_ready_result implements org.apache.thrift.TBase<slave_ready_result, slave_ready_result._Fields>, java.io.Serializable, Cloneable, Comparable<slave_ready_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_ready_result");
private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_ready_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_ready_resultTupleSchemeFactory());
}
private SlaveNotRegisterException e; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
E((short)1, "e");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // E
return E;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_ready_result.class, metaDataMap);
}
public slave_ready_result() {
}
public slave_ready_result(
SlaveNotRegisterException e)
{
this();
this.e = e;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_ready_result(slave_ready_result other) {
if (other.isSetE()) {
this.e = new SlaveNotRegisterException(other.e);
}
}
public slave_ready_result deepCopy() {
return new slave_ready_result(this);
}
@Override
public void clear() {
this.e = null;
}
public SlaveNotRegisterException getE() {
return this.e;
}
public slave_ready_result setE(SlaveNotRegisterException e) {
this.e = e;
return this;
}
public void unsetE() {
this.e = null;
}
/** Returns true if field e is set (has been assigned a value) and false otherwise */
public boolean isSetE() {
return this.e != null;
}
public void setEIsSet(boolean value) {
if (!value) {
this.e = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case E:
if (value == null) {
unsetE();
} else {
setE((SlaveNotRegisterException)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case E:
return getE();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case E:
return isSetE();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_ready_result)
return this.equals((slave_ready_result)that);
return false;
}
public boolean equals(slave_ready_result that) {
if (that == null)
return false;
boolean this_present_e = true && this.isSetE();
boolean that_present_e = true && that.isSetE();
if (this_present_e || that_present_e) {
if (!(this_present_e && that_present_e))
return false;
if (!this.e.equals(that.e))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_e = true && (isSetE());
list.add(present_e);
if (present_e)
list.add(e);
return list.hashCode();
}
@Override
public int compareTo(slave_ready_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetE()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_ready_result(");
boolean first = true;
sb.append("e:");
if (this.e == null) {
sb.append("null");
} else {
sb.append(this.e);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_ready_resultStandardSchemeFactory implements SchemeFactory {
public slave_ready_resultStandardScheme getScheme() {
return new slave_ready_resultStandardScheme();
}
}
private static class slave_ready_resultStandardScheme extends StandardScheme<slave_ready_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_ready_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // E
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.e = new SlaveNotRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_ready_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.e != null) {
oprot.writeFieldBegin(E_FIELD_DESC);
struct.e.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_ready_resultTupleSchemeFactory implements SchemeFactory {
public slave_ready_resultTupleScheme getScheme() {
return new slave_ready_resultTupleScheme();
}
}
private static class slave_ready_resultTupleScheme extends TupleScheme<slave_ready_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_ready_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetE()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetE()) {
struct.e.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_ready_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.e = new SlaveNotRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
}
}
}
}
public static class slave_register_args implements org.apache.thrift.TBase<slave_register_args, slave_register_args._Fields>, java.io.Serializable, Cloneable, Comparable<slave_register_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_register_args");
private static final org.apache.thrift.protocol.TField TASK_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("taskId", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField NODE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField CLEANUP_DIR_FIELD_DESC = new org.apache.thrift.protocol.TField("cleanupDir", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_register_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_register_argsTupleSchemeFactory());
}
private int taskId; // required
private String nodeName; // required
private String cleanupDir; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TASK_ID((short)1, "taskId"),
NODE_NAME((short)2, "nodeName"),
CLEANUP_DIR((short)3, "cleanupDir");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TASK_ID
return TASK_ID;
case 2: // NODE_NAME
return NODE_NAME;
case 3: // CLEANUP_DIR
return CLEANUP_DIR;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TASKID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TASK_ID, new org.apache.thrift.meta_data.FieldMetaData("taskId", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.NODE_NAME, new org.apache.thrift.meta_data.FieldMetaData("nodeName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.CLEANUP_DIR, new org.apache.thrift.meta_data.FieldMetaData("cleanupDir", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_register_args.class, metaDataMap);
}
public slave_register_args() {
}
public slave_register_args(
int taskId,
String nodeName,
String cleanupDir)
{
this();
this.taskId = taskId;
setTaskIdIsSet(true);
this.nodeName = nodeName;
this.cleanupDir = cleanupDir;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_register_args(slave_register_args other) {
__isset_bitfield = other.__isset_bitfield;
this.taskId = other.taskId;
if (other.isSetNodeName()) {
this.nodeName = other.nodeName;
}
if (other.isSetCleanupDir()) {
this.cleanupDir = other.cleanupDir;
}
}
public slave_register_args deepCopy() {
return new slave_register_args(this);
}
@Override
public void clear() {
setTaskIdIsSet(false);
this.taskId = 0;
this.nodeName = null;
this.cleanupDir = null;
}
public int getTaskId() {
return this.taskId;
}
public slave_register_args setTaskId(int taskId) {
this.taskId = taskId;
setTaskIdIsSet(true);
return this;
}
public void unsetTaskId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TASKID_ISSET_ID);
}
/** Returns true if field taskId is set (has been assigned a value) and false otherwise */
public boolean isSetTaskId() {
return EncodingUtils.testBit(__isset_bitfield, __TASKID_ISSET_ID);
}
public void setTaskIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TASKID_ISSET_ID, value);
}
public String getNodeName() {
return this.nodeName;
}
public slave_register_args setNodeName(String nodeName) {
this.nodeName = nodeName;
return this;
}
public void unsetNodeName() {
this.nodeName = null;
}
/** Returns true if field nodeName is set (has been assigned a value) and false otherwise */
public boolean isSetNodeName() {
return this.nodeName != null;
}
public void setNodeNameIsSet(boolean value) {
if (!value) {
this.nodeName = null;
}
}
public String getCleanupDir() {
return this.cleanupDir;
}
public slave_register_args setCleanupDir(String cleanupDir) {
this.cleanupDir = cleanupDir;
return this;
}
public void unsetCleanupDir() {
this.cleanupDir = null;
}
/** Returns true if field cleanupDir is set (has been assigned a value) and false otherwise */
public boolean isSetCleanupDir() {
return this.cleanupDir != null;
}
public void setCleanupDirIsSet(boolean value) {
if (!value) {
this.cleanupDir = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TASK_ID:
if (value == null) {
unsetTaskId();
} else {
setTaskId((Integer)value);
}
break;
case NODE_NAME:
if (value == null) {
unsetNodeName();
} else {
setNodeName((String)value);
}
break;
case CLEANUP_DIR:
if (value == null) {
unsetCleanupDir();
} else {
setCleanupDir((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TASK_ID:
return getTaskId();
case NODE_NAME:
return getNodeName();
case CLEANUP_DIR:
return getCleanupDir();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TASK_ID:
return isSetTaskId();
case NODE_NAME:
return isSetNodeName();
case CLEANUP_DIR:
return isSetCleanupDir();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_register_args)
return this.equals((slave_register_args)that);
return false;
}
public boolean equals(slave_register_args that) {
if (that == null)
return false;
boolean this_present_taskId = true;
boolean that_present_taskId = true;
if (this_present_taskId || that_present_taskId) {
if (!(this_present_taskId && that_present_taskId))
return false;
if (this.taskId != that.taskId)
return false;
}
boolean this_present_nodeName = true && this.isSetNodeName();
boolean that_present_nodeName = true && that.isSetNodeName();
if (this_present_nodeName || that_present_nodeName) {
if (!(this_present_nodeName && that_present_nodeName))
return false;
if (!this.nodeName.equals(that.nodeName))
return false;
}
boolean this_present_cleanupDir = true && this.isSetCleanupDir();
boolean that_present_cleanupDir = true && that.isSetCleanupDir();
if (this_present_cleanupDir || that_present_cleanupDir) {
if (!(this_present_cleanupDir && that_present_cleanupDir))
return false;
if (!this.cleanupDir.equals(that.cleanupDir))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_taskId = true;
list.add(present_taskId);
if (present_taskId)
list.add(taskId);
boolean present_nodeName = true && (isSetNodeName());
list.add(present_nodeName);
if (present_nodeName)
list.add(nodeName);
boolean present_cleanupDir = true && (isSetCleanupDir());
list.add(present_cleanupDir);
if (present_cleanupDir)
list.add(cleanupDir);
return list.hashCode();
}
@Override
public int compareTo(slave_register_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetTaskId()).compareTo(other.isSetTaskId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTaskId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.taskId, other.taskId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetNodeName()).compareTo(other.isSetNodeName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetNodeName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeName, other.nodeName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetCleanupDir()).compareTo(other.isSetCleanupDir());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCleanupDir()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.cleanupDir, other.cleanupDir);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_register_args(");
boolean first = true;
sb.append("taskId:");
sb.append(this.taskId);
first = false;
if (!first) sb.append(", ");
sb.append("nodeName:");
if (this.nodeName == null) {
sb.append("null");
} else {
sb.append(this.nodeName);
}
first = false;
if (!first) sb.append(", ");
sb.append("cleanupDir:");
if (this.cleanupDir == null) {
sb.append("null");
} else {
sb.append(this.cleanupDir);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_register_argsStandardSchemeFactory implements SchemeFactory {
public slave_register_argsStandardScheme getScheme() {
return new slave_register_argsStandardScheme();
}
}
private static class slave_register_argsStandardScheme extends StandardScheme<slave_register_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_register_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TASK_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NODE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // CLEANUP_DIR
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.cleanupDir = iprot.readString();
struct.setCleanupDirIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_register_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(TASK_ID_FIELD_DESC);
oprot.writeI32(struct.taskId);
oprot.writeFieldEnd();
if (struct.nodeName != null) {
oprot.writeFieldBegin(NODE_NAME_FIELD_DESC);
oprot.writeString(struct.nodeName);
oprot.writeFieldEnd();
}
if (struct.cleanupDir != null) {
oprot.writeFieldBegin(CLEANUP_DIR_FIELD_DESC);
oprot.writeString(struct.cleanupDir);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_register_argsTupleSchemeFactory implements SchemeFactory {
public slave_register_argsTupleScheme getScheme() {
return new slave_register_argsTupleScheme();
}
}
private static class slave_register_argsTupleScheme extends TupleScheme<slave_register_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_register_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetTaskId()) {
optionals.set(0);
}
if (struct.isSetNodeName()) {
optionals.set(1);
}
if (struct.isSetCleanupDir()) {
optionals.set(2);
}
oprot.writeBitSet(optionals, 3);
if (struct.isSetTaskId()) {
oprot.writeI32(struct.taskId);
}
if (struct.isSetNodeName()) {
oprot.writeString(struct.nodeName);
}
if (struct.isSetCleanupDir()) {
oprot.writeString(struct.cleanupDir);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_register_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(3);
if (incoming.get(0)) {
struct.taskId = iprot.readI32();
struct.setTaskIdIsSet(true);
}
if (incoming.get(1)) {
struct.nodeName = iprot.readString();
struct.setNodeNameIsSet(true);
}
if (incoming.get(2)) {
struct.cleanupDir = iprot.readString();
struct.setCleanupDirIsSet(true);
}
}
}
}
public static class slave_register_result implements org.apache.thrift.TBase<slave_register_result, slave_register_result._Fields>, java.io.Serializable, Cloneable, Comparable<slave_register_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("slave_register_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new slave_register_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new slave_register_resultTupleSchemeFactory());
}
private boolean success; // required
private SlaveAlreadyRegisterException e; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success"),
E((short)1, "e");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
case 1: // E
return E;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(slave_register_result.class, metaDataMap);
}
public slave_register_result() {
}
public slave_register_result(
boolean success,
SlaveAlreadyRegisterException e)
{
this();
this.success = success;
setSuccessIsSet(true);
this.e = e;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public slave_register_result(slave_register_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
if (other.isSetE()) {
this.e = new SlaveAlreadyRegisterException(other.e);
}
}
public slave_register_result deepCopy() {
return new slave_register_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = false;
this.e = null;
}
public boolean isSuccess() {
return this.success;
}
public slave_register_result setSuccess(boolean success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
public SlaveAlreadyRegisterException getE() {
return this.e;
}
public slave_register_result setE(SlaveAlreadyRegisterException e) {
this.e = e;
return this;
}
public void unsetE() {
this.e = null;
}
/** Returns true if field e is set (has been assigned a value) and false otherwise */
public boolean isSetE() {
return this.e != null;
}
public void setEIsSet(boolean value) {
if (!value) {
this.e = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((Boolean)value);
}
break;
case E:
if (value == null) {
unsetE();
} else {
setE((SlaveAlreadyRegisterException)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return isSuccess();
case E:
return getE();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
case E:
return isSetE();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof slave_register_result)
return this.equals((slave_register_result)that);
return false;
}
public boolean equals(slave_register_result that) {
if (that == null)
return false;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
boolean this_present_e = true && this.isSetE();
boolean that_present_e = true && that.isSetE();
if (this_present_e || that_present_e) {
if (!(this_present_e && that_present_e))
return false;
if (!this.e.equals(that.e))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_success = true;
list.add(present_success);
if (present_success)
list.add(success);
boolean present_e = true && (isSetE());
list.add(present_e);
if (present_e)
list.add(e);
return list.hashCode();
}
@Override
public int compareTo(slave_register_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetE()).compareTo(other.isSetE());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetE()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("slave_register_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
if (!first) sb.append(", ");
sb.append("e:");
if (this.e == null) {
sb.append("null");
} else {
sb.append(this.e);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class slave_register_resultStandardSchemeFactory implements SchemeFactory {
public slave_register_resultStandardScheme getScheme() {
return new slave_register_resultStandardScheme();
}
}
private static class slave_register_resultStandardScheme extends StandardScheme<slave_register_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, slave_register_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 1: // E
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.e = new SlaveAlreadyRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, slave_register_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeBool(struct.success);
oprot.writeFieldEnd();
}
if (struct.e != null) {
oprot.writeFieldBegin(E_FIELD_DESC);
struct.e.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class slave_register_resultTupleSchemeFactory implements SchemeFactory {
public slave_register_resultTupleScheme getScheme() {
return new slave_register_resultTupleScheme();
}
}
private static class slave_register_resultTupleScheme extends TupleScheme<slave_register_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, slave_register_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
if (struct.isSetE()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetSuccess()) {
oprot.writeBool(struct.success);
}
if (struct.isSetE()) {
struct.e.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, slave_register_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.success = iprot.readBool();
struct.setSuccessIsSet(true);
}
if (incoming.get(1)) {
struct.e = new SlaveAlreadyRegisterException();
struct.e.read(iprot);
struct.setEIsSet(true);
}
}
}
}
}
| 34.347118 | 346 | 0.64727 |
62e6f8fa6e1487c3ee8829c79af47b691431788b | 31,945 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.proxy.ejb;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.ejb.EJBHome;
import javax.ejb.EJBMetaData;
import javax.ejb.EJBObject;
import javax.management.ObjectName;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.rmi.CORBA.Stub;
import javax.rmi.PortableRemoteObject;
import org.jacorb.ssl.SSLPolicyValue;
import org.jacorb.ssl.SSLPolicyValueHelper;
import org.jacorb.ssl.SSL_POLICY_TYPE;
import org.jboss.ejb.Container;
import org.jboss.ejb.EJBProxyFactory;
import org.jboss.ejb.EJBProxyFactoryContainer;
import org.jboss.ejb.EntityContainer;
import org.jboss.ejb.StatefulSessionContainer;
import org.jboss.ejb.StatelessSessionContainer;
import org.jboss.iiop.CorbaNamingService;
import org.jboss.iiop.CorbaORBService;
import org.jboss.iiop.codebase.CodebasePolicy;
import org.jboss.iiop.csiv2.CSIv2Policy;
import org.jboss.iiop.rmi.AttributeAnalysis;
import org.jboss.iiop.rmi.InterfaceAnalysis;
import org.jboss.iiop.rmi.OperationAnalysis;
import org.jboss.iiop.rmi.ir.InterfaceRepository;
import org.jboss.iiop.rmi.marshal.strategy.SkeletonStrategy;
import org.jboss.invocation.Invocation;
import org.jboss.invocation.iiop.ReferenceFactory;
import org.jboss.invocation.iiop.ServantRegistries;
import org.jboss.invocation.iiop.ServantRegistry;
import org.jboss.invocation.iiop.ServantRegistryKind;
import org.jboss.invocation.iiop.ServantWithMBeanServer;
import org.jboss.logging.Logger;
import org.jboss.metadata.EntityMetaData;
import org.jboss.metadata.InvokerProxyBindingMetaData;
import org.jboss.metadata.IorSecurityConfigMetaData;
import org.jboss.metadata.MetaData;
import org.jboss.metadata.SessionMetaData;
import org.jboss.naming.Util;
import org.jboss.system.Registry;
import org.jboss.web.WebClassLoader;
import org.omg.CORBA.Any;
import org.omg.CORBA.InterfaceDef;
import org.omg.CORBA.InterfaceDefHelper;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Policy;
import org.omg.CORBA.Repository;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.InvalidName;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.omg.PortableServer.Current;
import org.omg.PortableServer.CurrentHelper;
import org.omg.PortableServer.POA;
import org.w3c.dom.Element;
/**
* This is an IIOP "proxy factory" for <code>EJBHome</code>s and
* <code>EJBObject</code>s. Rather than creating Java proxies (as the JRMP
* proxy factory does), this factory creates CORBA IORs.
*<p>
* An <code>IORFactory</code> is associated to a given enterprise bean. It
* registers with the IIOP invoker two CORBA servants: an
* <code>EjbHomeCorbaServant</code> for the bean's
* <code>EJBHome</code> and an <code>EjbObjectCorbaServant</code> for the
* bean's <code>EJBObject</code>s.
*
* @version $Revision: 66100 $
*/
public class IORFactory
implements EJBProxyFactory
{
// Constants --------------------------------------------------------------
private static final Logger staticLogger =
Logger.getLogger(IORFactory.class);
// Attributes -------------------------------------------------------------
/**
* A reference for the ORB.
*/
private ORB orb;
/**
* This <code>IORFactory</code>'s container.
*/
private Container container;
/**
* <code>JNDI</code> name of the enterprise bean in the container.
*/
private String jndiName;
/**
* True if the <code>EJBHome</code> should be bound to a JNP/JNDI context
* in addition to being bound to a CORBA naming context.
*/
private boolean useJNPContext;
/**
* The JNP/JNDI name the <code>EJBHome</code> should be bound to.
*/
private String jnpName;
/**
* <code>EJBMetaData</code> the enterprise bean in the container.
*/
private EJBMetaDataImplIIOP ejbMetaData;
/**
* Mapping from bean methods to <code>SkeletonStrategy</code> instances.
*/
private Map beanMethodMap;
/**
* Mapping from home methods to <code>SkeletonStrategy</code> instances.
*/
private Map homeMethodMap;
/**
* CORBA repository ids of the RMI-IDL interfaces implemented by the bean
* (<code>EJBObject</code> instance).
*/
private String[] beanRepositoryIds;
/**
* CORBA repository ids of the RMI-IDL interfaces implemented by the bean's
* home (<code>EJBHome</code> instance).
*/
private String[] homeRepositoryIds;
/**
* <code>ServantRegistry</code> for the container's <code>EJBHome</code>.
*/
private ServantRegistry homeServantRegistry;
/**
* <code>ServantRegistry</code> for the container's <code>EJBObject</code>s.
*/
private ServantRegistry beanServantRegistry;
/**
* <code>ReferenceFactory</code> for the container's <code>EJBHome</code>.
*/
private ReferenceFactory homeReferenceFactory;
/**
* <code>ReferenceFactory</code> for <code>EJBObject</code>s.
*/
private ReferenceFactory beanReferenceFactory;
/**
* Thread-local <code>Current</code> object from which we get the target oid
* in an incoming IIOP request.
*/
private Current poaCurrent;
/**
* The container's <code>CodebasePolicy</code>.
*/
private Policy codebasePolicy;
/**
* The container's <code>CSIv2Policy</code>.
*/
private Policy csiv2Policy;
/**
* The container's <code>SSLPolicy</code>.
*/
private Policy sslPolicy;
/**
* The container's <code>EJBHome</code>.
*/
private EJBHome ejbHome;
/**
* Invoker metadata, which includes the invoker JMX name.
*/
private InvokerProxyBindingMetaData invokerMetaData;
/**
* A reference to the invoker, used for servant registration.
*/
private ServantRegistries servantRegistries;
/**
* The enterprise bean's interface repository implementation, or null
* if the enterprise bean does not have its own interface repository.
*/
private InterfaceRepository iri;
/**
* POA for the enterprise bean's interface repository.
*/
private POA irPoa;
/**
* This <code>IORFactory</code>'s logger. Initialized with a
* per-class logger. Once the enterprise bean's JNDI name is known, the
* per-class logger will be replaced by a per-instance logger whose name
* includes the JNDI name.
*/
private Logger logger = staticLogger;
// Implementation of the interface ContainerPlugin -------------------------
public void setContainer(Container container)
{
this.container = container;
if (container != null) {
String loggerName = IORFactory.class.getName() + '.'
+ container.getBeanMetaData().getJndiName();
logger = Logger.getLogger(loggerName);
}
}
public void create() throws Exception
{
// Get orb and irPoa references
try {
orb = (ORB)new InitialContext().lookup("java:/"
+ CorbaORBService.ORB_NAME);
}
catch (NamingException e) {
throw new Exception("Cannot lookup java:/"
+ CorbaORBService.ORB_NAME + ": " + e);
}
try {
irPoa = (POA)new InitialContext().lookup("java:/"
+ CorbaORBService.IR_POA_NAME);
}
catch (NamingException e) {
throw new Exception("Cannot lookup java:/"
+ CorbaORBService.IR_POA_NAME + ": " + e);
}
// Should create a CORBA interface repository?
Element proxyFactoryConfig = invokerMetaData.getProxyFactoryConfig();
boolean interfaceRepositorySupported =
MetaData.getOptionalChildBooleanContent(
proxyFactoryConfig, "interface-repository-supported");
if (interfaceRepositorySupported) {
// Create a CORBA interface repository for the enterprise bean
iri = new InterfaceRepository(orb, irPoa, jndiName);
// Add bean interface info to the interface repository
iri.mapClass(((EJBProxyFactoryContainer)container).getRemoteClass());
iri.mapClass(((EJBProxyFactoryContainer)container).getHomeClass());
iri.finishBuild();
logger.info("CORBA interface repository for " + jndiName + ": "
+ orb.object_to_string(iri.getReference()));
}
// Create bean method mappings for container invoker
logger.debug("Bean methods:");
InterfaceAnalysis interfaceAnalysis =
InterfaceAnalysis.getInterfaceAnalysis(
((EJBProxyFactoryContainer)container).getRemoteClass());
beanMethodMap = new HashMap();
AttributeAnalysis[] attrs = interfaceAnalysis.getAttributes();
for (int i = 0; i < attrs.length; i++) {
OperationAnalysis op = attrs[i].getAccessorAnalysis();
logger.debug(" " + op.getJavaName()
+ "\n " + op.getIDLName());
beanMethodMap.put(op.getIDLName(),
new SkeletonStrategy(op.getMethod()));
op = attrs[i].getMutatorAnalysis();
if (op != null) {
logger.debug(" " + op.getJavaName()
+ "\n " + op.getIDLName());
beanMethodMap.put(op.getIDLName(),
new SkeletonStrategy(op.getMethod()));
}
}
OperationAnalysis[] ops = interfaceAnalysis.getOperations();
for (int i = 0; i < ops.length; i++) {
logger.debug(" " + ops[i].getJavaName()
+ "\n " + ops[i].getIDLName());
beanMethodMap.put(ops[i].getIDLName(),
new SkeletonStrategy(ops[i].getMethod()));
}
// Initialize repository ids of remote interface
beanRepositoryIds = interfaceAnalysis.getAllTypeIds();
// Create home method mappings for container invoker
logger.debug("Home methods:");
interfaceAnalysis =
InterfaceAnalysis.getInterfaceAnalysis(
((EJBProxyFactoryContainer)container).getHomeClass());
homeMethodMap = new HashMap();
attrs = interfaceAnalysis.getAttributes();
for (int i = 0; i < attrs.length; i++) {
OperationAnalysis op = attrs[i].getAccessorAnalysis();
logger.debug(" " + op.getJavaName()
+ "\n " + op.getIDLName());
homeMethodMap.put(op.getIDLName(),
new SkeletonStrategy(op.getMethod()));
op = attrs[i].getMutatorAnalysis();
if (op != null) {
logger.debug(" " + op.getJavaName()
+ "\n " + op.getIDLName());
homeMethodMap.put(op.getIDLName(),
new SkeletonStrategy(op.getMethod()));
}
}
ops = interfaceAnalysis.getOperations();
for (int i = 0; i < ops.length; i++) {
logger.debug(" " + ops[i].getJavaName()
+ "\n " + ops[i].getIDLName());
homeMethodMap.put(ops[i].getIDLName(),
new SkeletonStrategy(ops[i].getMethod()));
}
// Initialize repository ids of home interface
homeRepositoryIds = interfaceAnalysis.getAllTypeIds();
// Create codebasePolicy containing the container's codebase string
logger.debug("container classloader: " + container.getClassLoader()
+ "\ncontainer parent classloader: "
+ container.getClassLoader().getParent());
WebClassLoader wcl = (WebClassLoader)container.getWebClassLoader();
String codebaseString;
if (wcl != null && (codebaseString = wcl.getCodebaseString()) != null)
{
Any codebase = orb.create_any();
codebase.insert_string(codebaseString);
codebasePolicy = orb.create_policy(CodebasePolicy.TYPE, codebase);
logger.debug("codebasePolicy: " + codebasePolicy);
}
else
{
logger.debug("Not setting codebase policy, codebase is null");
}
// Create csiv2Policy for both home and remote containing
// IorSecurityConfigMetadata
Any secPolicy = orb.create_any();
IorSecurityConfigMetaData iorSecurityConfigMetaData =
container.getBeanMetaData().getIorSecurityConfigMetaData();
secPolicy.insert_Value(iorSecurityConfigMetaData);
csiv2Policy = orb.create_policy(CSIv2Policy.TYPE, secPolicy);
// Create SSLPolicy
// (SSL_REQUIRED ensures home and remote IORs
// will have port 0 in the primary address)
boolean sslRequired = false;
if (iorSecurityConfigMetaData != null) {
IorSecurityConfigMetaData.TransportConfig tc =
iorSecurityConfigMetaData.getTransportConfig();
sslRequired =
tc.getIntegrity() ==
IorSecurityConfigMetaData.TransportConfig.INTEGRITY_REQUIRED
|| tc.getConfidentiality() ==
IorSecurityConfigMetaData.TransportConfig.CONFIDENTIALITY_REQUIRED
|| tc.getEstablishTrustInClient() ==
IorSecurityConfigMetaData.TransportConfig.ESTABLISH_TRUST_IN_CLIENT_REQUIRED;
}
Any sslPolicyValue = orb.create_any();
SSLPolicyValueHelper.insert(
sslPolicyValue,
(sslRequired) ? SSLPolicyValue.SSL_REQUIRED
: SSLPolicyValue.SSL_NOT_REQUIRED);
sslPolicy = orb.create_policy(SSL_POLICY_TYPE.value, sslPolicyValue);
logger.debug("container's SSL policy: " + sslPolicy);
// Get the POACurrent object
poaCurrent = CurrentHelper.narrow(
orb.resolve_initial_references("POACurrent"));
}
public void start() throws Exception
{
// Lookup the invoker in the object registry. This typically cannot
// be done until our start method as the invokers may need to be started
// themselves.
ObjectName oname = new ObjectName(invokerMetaData.getInvokerMBean());
servantRegistries = (ServantRegistries)Registry.lookup(oname);
if (servantRegistries == null)
throw new Exception("invoker is null: " + oname);
Policy[] policies = null;
if (codebasePolicy == null)
policies = new Policy[] { sslPolicy, csiv2Policy };
else
policies = new Policy[] { codebasePolicy, sslPolicy, csiv2Policy };
// Read POA usage model from proxy factory config.
ServantRegistryKind registryWithTransientPOA;
ServantRegistryKind registryWithPersistentPOA;
Element proxyFactoryConfig = invokerMetaData.getProxyFactoryConfig();
String poaUsageModel =
MetaData.getOptionalChildContent(proxyFactoryConfig, "poa");
if (poaUsageModel == null || poaUsageModel.equals("shared")) {
registryWithTransientPOA = ServantRegistryKind.SHARED_TRANSIENT_POA;
registryWithPersistentPOA = ServantRegistryKind.SHARED_PERSISTENT_POA;
}
else if (poaUsageModel.equals("per-servant")) {
registryWithTransientPOA =
ServantRegistryKind.TRANSIENT_POA_PER_SERVANT;
registryWithPersistentPOA =
ServantRegistryKind.PERSISTENT_POA_PER_SERVANT;
}
else {
throw new Exception("invalid poa element in proxy factory config: "
+ poaUsageModel);
}
// If there is an interface repository, then get
// the homeInterfaceDef from the IR
InterfaceDef homeInterfaceDef = null;
if (iri != null) {
Repository ir = iri.getReference();
homeInterfaceDef =
InterfaceDefHelper.narrow(ir.lookup_id(homeRepositoryIds[0]));
}
// Instantiate home servant, bind it to the servant registry, and
// create CORBA reference to the EJBHome.
homeServantRegistry =
servantRegistries.getServantRegistry(registryWithPersistentPOA);
String homeServantLoggerName =
EjbHomeCorbaServant.class.getName() + '.'+ jndiName;
ServantWithMBeanServer homeServant =
new EjbHomeCorbaServant(container.getJmxName(),
container.getClassLoader(),
homeMethodMap,
homeRepositoryIds,
homeInterfaceDef,
Logger.getLogger(homeServantLoggerName));
homeReferenceFactory = homeServantRegistry.bind(homeServantName(jndiName), homeServant, policies);
org.omg.CORBA.Object corbaRef =
homeReferenceFactory.createReference(homeRepositoryIds[0]);
ejbHome = (EJBHome)PortableRemoteObject.narrow(corbaRef, EJBHome.class);
((EjbHomeCorbaServant)homeServant).setHomeHandle(
new HomeHandleImplIIOP(ejbHome));
// Initialize beanPOA and create metadata depending on the kind of bean
if (container.getBeanMetaData() instanceof EntityMetaData) {
// This is an entity bean (lifespan: persistent)
beanServantRegistry =
servantRegistries.getServantRegistry(registryWithPersistentPOA);
Class pkClass;
EntityMetaData metaData = (EntityMetaData)container.getBeanMetaData();
String pkClassName = metaData.getPrimaryKeyClass();
try {
if (pkClassName != null)
pkClass = container.getClassLoader().loadClass(pkClassName);
else
pkClass = container.getClassLoader().loadClass(
metaData.getEjbClass()).getField(
metaData.getPrimKeyField()).getClass();
}
catch (NoSuchFieldException e) {
logger.error("Unable to identify Bean's Primary Key class! "
+ "Did you specify a primary key class and/or field? "
+ "Does that field exist?");
throw new Exception("Primary Key Problem");
}
catch (NullPointerException e) {
logger.error("Unable to identify Bean's Primary Key class! "
+ "Did you specify a primary key class and/or field? "
+ "Does that field exist?");
throw new Exception("Primary Key Problem");
}
ejbMetaData = new EJBMetaDataImplIIOP(
((EJBProxyFactoryContainer)container).getRemoteClass(),
((EJBProxyFactoryContainer)container).getHomeClass(),
pkClass,
false, // Session
false, // Stateless
ejbHome);
}
else {
// This is a session bean (lifespan: transient)
beanServantRegistry =
servantRegistries.getServantRegistry(registryWithTransientPOA);
if (((SessionMetaData)container.getBeanMetaData()).isStateless()) {
// Stateless session bean
ejbMetaData = new EJBMetaDataImplIIOP(
((EJBProxyFactoryContainer)container).getRemoteClass(),
((EJBProxyFactoryContainer)container).getHomeClass(),
null, // No PK
true, // Session
true, // Stateless
ejbHome);
}
else {
// Stateful session bean
ejbMetaData = new EJBMetaDataImplIIOP(
((EJBProxyFactoryContainer)container).getRemoteClass(),
((EJBProxyFactoryContainer)container).getHomeClass(),
null, // No PK
true, // Session
false, // Stateless
ejbHome);
}
}
// If there is an interface repository, then get
// the beanInterfaceDef from the IR
InterfaceDef beanInterfaceDef = null;
if (iri != null) {
Repository ir = iri.getReference();
beanInterfaceDef =
InterfaceDefHelper.narrow(ir.lookup_id(beanRepositoryIds[0]));
}
String beanServantLoggerName =
EjbObjectCorbaServant.class.getName() + '.'+ jndiName;
ServantWithMBeanServer beanServant =
new EjbObjectCorbaServant(container.getJmxName(),
container.getClassLoader(),
poaCurrent,
beanMethodMap,
beanRepositoryIds,
beanInterfaceDef,
Logger.getLogger(beanServantLoggerName));
beanReferenceFactory = beanServantRegistry.bind(beanServantName(jndiName), beanServant, policies);
// Just for testing
logger.info("EJBHome reference for " + jndiName + ":\n"
+ orb.object_to_string((org.omg.CORBA.Object)ejbHome));
// Get JNP usage info from proxy factory config.
useJNPContext = MetaData.getOptionalChildBooleanContent(
proxyFactoryConfig, "register-ejbs-in-jnp-context");
Context initialContext = new InitialContext();
if (useJNPContext) {
String jnpContext =
MetaData.getOptionalChildContent(proxyFactoryConfig,
"jnp-context");
if (jnpContext != null && !jnpContext.equals("")) {
jnpName = jnpContext + "/" + jndiName;
}
else {
jnpName = jndiName;
}
try {
// Bind the bean home in the JNDI initial context
Util.rebind(initialContext,
jnpName,
new Reference(
"javax.ejb.EJBHome",
new StringRefAddr("IOR",
orb.object_to_string(
(org.omg.CORBA.Object)ejbHome)),
IIOPHomeFactory.class.getName(),
null));
logger.info("Home IOR for " + container.getBeanMetaData().getEjbName()
+ " bound to " + jnpName + " in JNP naming service");
}
catch (NamingException e) {
throw new Exception("Cannot bind EJBHome in JNDI:\n" + e);
}
}
NamingContextExt corbaContext = null;
try {
// Obtain local (in-VM) CORBA naming context
corbaContext = NamingContextExtHelper.narrow((org.omg.CORBA.Object)
initialContext.lookup("java:/" +
CorbaNamingService.NAMING_NAME));
}
catch (NamingException e) {
throw new Exception("Cannot lookup java:/" +
CorbaNamingService.NAMING_NAME + ":\n" + e);
}
try {
// Register bean home in local CORBA naming context
rebind(corbaContext, jndiName, (org.omg.CORBA.Object)ejbHome);
logger.info("Home IOR for " + container.getBeanMetaData().getEjbName()
+ " bound to " + jndiName + " in CORBA naming service");
}
catch (Exception e) {
logger.error("Cannot bind EJBHome in CORBA naming service:", e);
throw new Exception("Cannot bind EJBHome in CORBA naming service:\n"
+ e);
}
}
public void stop()
{
try {
// Get initial JNP/JNDI context
Context initialContext = new InitialContext();
if (useJNPContext) {
// Unbind bean home from the JNDI initial context
try {
initialContext.unbind(jnpName);
}
catch (NamingException namingException) {
logger.error("Cannot unbind EJBHome from JNDI", namingException);
}
}
// Get local (in-VM) CORBA naming context
NamingContextExt corbaContext =
NamingContextExtHelper.narrow((org.omg.CORBA.Object)
initialContext.lookup("java:/"
+ CorbaNamingService.NAMING_NAME));
// Unregister bean home from local CORBA naming context
try {
NameComponent[] name = corbaContext.to_name(jndiName);
corbaContext.unbind(name);
}
catch (InvalidName invalidName) {
logger.error("Cannot unregister EJBHome from CORBA naming service",
invalidName);
}
catch (NotFound notFound) {
logger.error("Cannot unregister EJBHome from CORBA naming service",
notFound);
}
catch (CannotProceed cannotProceed) {
logger.error("Cannot unregister EJBHome from CORBA naming service",
cannotProceed);
}
}
catch (NamingException namingException) {
logger.error("Unexpected error in JNDI lookup", namingException);
}
// Deactivate the home servant and the bean servant
try {
homeServantRegistry.unbind(homeServantName(jndiName));
}
catch (Exception e) {
logger.error("Cannot deactivate home servant", e);
}
try {
beanServantRegistry.unbind(beanServantName(jndiName));
}
catch (Exception e) {
logger.error("Cannot deactivate bean servant", e);
}
if (iri != null) {
// Deactivate the interface repository
iri.shutdown();
}
}
public void destroy()
{
}
// Implementation of the interface EJBProxyFactory -------------------------
public void setInvokerMetaData(InvokerProxyBindingMetaData imd)
{
invokerMetaData = imd;
}
public void setInvokerBinding(String binding)
{
jndiName = binding;
}
public boolean isIdentical(Container container, Invocation mi)
{
EJBObject other = (EJBObject) mi.getArguments()[0];
if (other == null)
return false;
EJBObject me;
if (container instanceof StatelessSessionContainer)
me = (EJBObject) getStatelessSessionEJBObject();
else if (container instanceof StatefulSessionContainer)
me = (EJBObject) getStatefulSessionEJBObject(mi.getId());
else if (container instanceof EntityContainer)
me = (EJBObject) getEntityEJBObject(mi.getId());
else
return false;
Stub meStub = (Stub) me;
Stub otherStub = (Stub) other;
return meStub._is_equivalent(otherStub);
}
public EJBMetaData getEJBMetaData()
{
return ejbMetaData;
}
public Object getEJBHome()
{
return ejbHome;
}
public Object getStatelessSessionEJBObject()
{
try {
return (EJBObject)PortableRemoteObject.narrow(
beanReferenceFactory.createReference(beanRepositoryIds[0]),
EJBObject.class);
}
catch (Exception e) {
throw new RuntimeException("Unable to create reference to EJBObject\n"
+ e);
}
}
public Object getStatefulSessionEJBObject(Object id)
{
try {
return (EJBObject)PortableRemoteObject.narrow(
beanReferenceFactory.createReferenceWithId(
id,
beanRepositoryIds[0]),
EJBObject.class);
}
catch (Exception e) {
throw new RuntimeException("Unable to create reference to EJBObject\n"
+ e);
}
}
public Object getEntityEJBObject(Object id)
{
if (logger.isTraceEnabled()) {
logger.trace("getEntityEJBObject(), id class is "
+ id.getClass().getName());
}
try {
Object ejbObject = (id == null ? null :
(EJBObject)PortableRemoteObject.narrow(
beanReferenceFactory.createReferenceWithId(id, beanRepositoryIds[0]),
EJBObject.class));
return ejbObject;
}
catch (Exception e) {
throw new RuntimeException("Unable to create reference to EJBObject\n"
+ e);
}
}
public Collection getEntityCollection(Collection ids)
{
if (logger.isTraceEnabled()) {
logger.trace("entering getEntityCollection()");
}
Collection collection = new ArrayList(ids.size());
Iterator idEnum = ids.iterator();
while(idEnum.hasNext()) {
collection.add(getEntityEJBObject(idEnum.next()));
}
if (logger.isTraceEnabled()) {
logger.trace("leaving getEntityCollection()");
}
return collection;
}
// Static methods ----------------------------------------------------------
/**
* Returns the CORBA repository id of a given the RMI-IDL interface.
*/
public static String rmiRepositoryId(Class clz)
{
return "RMI:" + clz.getName() + ":0000000000000000";
}
/**
* (Re)binds an object to a name in a given CORBA naming context, creating
* any non-existent intermediate contexts along the way.
*/
public static void rebind(NamingContextExt ctx,
String strName, org.omg.CORBA.Object obj)
throws Exception
{
NameComponent[] name = ctx.to_name(strName);
NamingContext intermediateCtx = ctx;
for (int i = 0; i < name.length - 1; i++ ) {
NameComponent[] relativeName = new NameComponent[] { name[i] };
try {
intermediateCtx = NamingContextHelper.narrow(
intermediateCtx.resolve(relativeName));
}
catch (NotFound e) {
intermediateCtx = intermediateCtx.bind_new_context(relativeName);
}
}
intermediateCtx.rebind(new NameComponent[] { name[name.length - 1] },
obj);
}
/**
* Returns the name of a home servant for an EJB with the given jndiName.
* The home servant will be bound to this name in a ServantRegistry.
*/
private static String homeServantName(String jndiName)
{
return "EJBHome/" + jndiName;
}
/**
* Returns the name of a bean servant for an EJB with the given jndiName.
* The bean servant will be bound to this name in a ServantRegistry.
*/
private static String beanServantName(String jndiName)
{
return "EJBObject/" + jndiName;
}
}
| 36.218821 | 104 | 0.611802 |
273b3201134881e5ff29c76978f5233c640c2d59 | 165 | package it.reply.utils.web.ws.rest.apiencoding.encode;
public interface RestResponseEncoder {
public String encode(Object model, Class<?> modelClass);
}
| 20.625 | 58 | 0.745455 |
88048124d4bd87d88bcbe528b2d8b7bb4034b80a | 1,722 | package com.airmap.airmapsdk.models.traffic;
import com.airmap.airmapsdk.models.AirMapBaseModel;
import org.json.JSONObject;
import java.io.Serializable;
import static com.airmap.airmapsdk.util.Utils.optString;
@SuppressWarnings("unused")
public class AirMapTrafficProperties implements Serializable, AirMapBaseModel {
private String aircraftId;
private String aircraftType;
/**
* Initialize an AirMapTrafficProperties from JSON
* @param propertiesJson A JSON representation of an AirMapTrafficProperties
*/
public AirMapTrafficProperties(JSONObject propertiesJson) {
constructFromJson(propertiesJson);
}
/**
* Initialize an AirMapTrafficProperties with default values
*/
public AirMapTrafficProperties() {
}
@Override
public AirMapTrafficProperties constructFromJson(JSONObject json) {
if (json != null) {
setAircraftId(optString(json, "aircraft_id"));
setAircraftType(optString(json, "aircraft_type"));
}
return this;
}
public String getAircraftId() {
return aircraftId;
}
public AirMapTrafficProperties setAircraftId(String aircraftId) {
this.aircraftId = aircraftId;
return this;
}
public String getAircraftType() {
return aircraftType;
}
public AirMapTrafficProperties setAircraftType(String aircraftType) {
this.aircraftType = aircraftType;
return this;
}
/**
* Comparison based on Aircraft ID
*/
@Override
public boolean equals(Object o) {
return o instanceof AirMapTrafficProperties && getAircraftId().equals(((AirMapTrafficProperties) o).getAircraftId());
}
}
| 26.090909 | 125 | 0.692799 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.