answer
stringlengths 17
10.2M
|
|---|
package Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
Thread thread = new Thread(this);
private boolean first = true;
public int myWidth;
public int myHeight;
public Player player;
public World world;
public int test; //Delete this variable
public GamePanel(){
//Add a mouse Listener to the JPanel
this.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
//Add a mouseMotionListner to the JPanel
this.addMouseMotionListener(new MouseMotionListener(){
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
});
this.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
});
System.out.println("Heyo");
//Set focusable to mouseMotionListener can detect and focus on panel
this.setFocusable(true);
this.requestFocusInWindow();
//Debug
this.setName("GamePanel");
//Start the runnable thread
thread.start();
}
@Override
public void paintComponent(Graphics g){
if(first){
define();
first = false;
}
g.setColor(Color.CYAN);
g.fillRect(20, 20, 100, 100);
world.draw(g);
}
public void define(){
myWidth = getWidth();
myHeight = getHeight();
player = new Player();
world = new World(10,10);
}
public void run(){
while(true){
try {
thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package chess;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import pieces.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/**
* @author Ashish Kedia and Adarsh Mohata
*
*/
/**
* This is the Main Class of our project.
* All GUI Elements are declared, initialized and used in this class itself.
* It is inherited from the JFrame Class of Java's Swing Library.
*
*/
public class Main extends JFrame implements MouseListener
{
private static final long serialVersionUID = 1L;
//Variable Declaration
private static final int Height=700;
private static final int Width=1110;
private static Rook wr01,wr02,br01,br02;
private static Knight wk01,wk02,bk01,bk02;
private static Bishop wb01,wb02,bb01,bb02;
private static Pawn wp[],bp[];
private static Queen wq,bq;
private static King wk,bk;
private Cell c,previous;
private int chance=0;
private Cell boardState[][];
private ArrayList<Cell> destinationlist = new ArrayList<Cell>();
private Player White=null,Black=null;
private JPanel board=new JPanel(new GridLayout(8,8));
private JPanel wdetails=new JPanel(new GridLayout(3,3));
private JPanel bdetails=new JPanel(new GridLayout(3,3));
private JPanel wcombopanel=new JPanel();
private JPanel bcombopanel=new JPanel();
private JPanel controlPanel,WhitePlayer,BlackPlayer,temp,displayTime,showPlayer,time;
private JSplitPane split;
private JLabel label,mov;
private static JLabel CHNC;
private Time timer;
public static Main Mainboard;
private boolean selected=false,end=false;
private Container content;
private ArrayList<Player> wplayer,bplayer;
private ArrayList<String> Wnames=new ArrayList<String>();
private ArrayList<String> Bnames=new ArrayList<String>();
private JComboBox<String> wcombo,bcombo;
private String wname=null,bname=null,winner=null;
static String move;
private Player tempPlayer;
private JScrollPane wscroll,bscroll;
private String[] WNames={},BNames={};
private JSlider timeSlider;
private BufferedImage image;
private Button start,wselect,bselect,WNewPlayer,BNewPlayer;
public static int timeRemaining=60;
public static void main(String[] args){
//variable initialization
wr01=new Rook("WR01","White_Rook.png",0);
wr02=new Rook("WR02","White_Rook.png",0);
br01=new Rook("BR01","Black_Rook.png",1);
br02=new Rook("BR02","Black_Rook.png",1);
wk01=new Knight("WK01","White_Knight.png",0);
wk02=new Knight("WK02","White_Knight.png",0);
bk01=new Knight("BK01","Black_Knight.png",1);
bk02=new Knight("BK02","Black_Knight.png",1);
wb01=new Bishop("WB01","White_Bishop.png",0);
wb02=new Bishop("WB02","White_Bishop.png",0);
bb01=new Bishop("BB01","Black_Bishop.png",1);
bb02=new Bishop("BB02","Black_Bishop.png",1);
wq=new Queen("WQ","White_Queen.png",0);
bq=new Queen("BQ","Black_Queen.png",1);
wk=new King("WK","White_King.png",0,7,3);
bk=new King("BK","Black_King.png",1,0,3);
wp=new Pawn[8];
bp=new Pawn[8];
for(int i=0;i<8;i++)
{
wp[i]=new Pawn("WP0"+(i+1),"White_Pawn.png",0);
bp[i]=new Pawn("BP0"+(i+1),"Black_Pawn.png",1);
}
//Setting up the board
Mainboard = new Main();
Mainboard.setVisible(true);
Mainboard.setResizable(false);
}
//Constructor
private Main()
{
timeRemaining=60;
timeSlider = new JSlider();
move="White";
wname=null;
bname=null;
winner=null;
board=new JPanel(new GridLayout(8,8));
wdetails=new JPanel(new GridLayout(3,3));
bdetails=new JPanel(new GridLayout(3,3));
bcombopanel=new JPanel();
wcombopanel=new JPanel();
Wnames=new ArrayList<String>();
Bnames=new ArrayList<String>();
board.setMinimumSize(new Dimension(800,700));
ImageIcon img = new ImageIcon(this.getClass().getResource("icon.png"));
this.setIconImage(img.getImage());
//Time Slider Details
/**timeSlider.setMinimum(1);
timeSlider.setMaximum(15);
timeSlider.setValue(1);
timeSlider.setMajorTickSpacing(2);
timeSlider.setPaintLabels(true);
timeSlider.setPaintTicks(true);
timeSlider.addChangeListener(new TimeChange());**/
setTimerSliderDetails(timeSlider);
//Fetching Details of all Players
wplayer= Player.fetch_players();
Iterator<Player> witr=wplayer.iterator();
while(witr.hasNext())
Wnames.add(witr.next().name());
bplayer= Player.fetch_players();
Iterator<Player> bitr=bplayer.iterator();
while(bitr.hasNext())
Bnames.add(bitr.next().name());
WNames=Wnames.toArray(WNames);
BNames=Bnames.toArray(BNames);
//Cell cell;
board.setBorder(BorderFactory.createLoweredBevelBorder());
//pieces.Piece P;
content=getContentPane();
setSize(Width,Height);
setTitle("Chess");
content.setBackground(Color.black);
controlPanel=new JPanel();
content.setLayout(new BorderLayout());
controlPanel.setLayout(new GridLayout(3,3));
controlPanel.setBorder(BorderFactory.createTitledBorder(null, "Statistics", TitledBorder.TOP,TitledBorder.CENTER, new Font("Lucida Calligraphy",Font.PLAIN,20), Color.ORANGE));
//Defining the Player Box in Control Panel
WhitePlayer=new JPanel();
WhitePlayer.setBorder(BorderFactory.createTitledBorder(null, "White Player", TitledBorder.TOP,TitledBorder.CENTER, new Font("times new roman",Font.BOLD,18), Color.RED));
WhitePlayer.setLayout(new BorderLayout());
BlackPlayer=new JPanel();
BlackPlayer.setBorder(BorderFactory.createTitledBorder(null, "Black Player", TitledBorder.TOP,TitledBorder.CENTER, new Font("times new roman",Font.BOLD,18), Color.BLUE));
BlackPlayer.setLayout(new BorderLayout());
JPanel whitestats=new JPanel(new GridLayout(3,3));
JPanel blackstats=new JPanel(new GridLayout(3,3));
wcombo=new JComboBox<String>(WNames);
bcombo=new JComboBox<String>(BNames);
wscroll=new JScrollPane(wcombo);
bscroll=new JScrollPane(bcombo);
wcombopanel.setLayout(new FlowLayout());
bcombopanel.setLayout(new FlowLayout());
wselect=new Button("Select");
bselect=new Button("Select");
wselect.addActionListener(new SelectHandler(0));
bselect.addActionListener(new SelectHandler(1));
WNewPlayer=new Button("New Player");
BNewPlayer=new Button("New Player");
WNewPlayer.addActionListener(new Handler(0));
BNewPlayer.addActionListener(new Handler(1));
wcombopanel.add(wscroll);
wcombopanel.add(wselect);
wcombopanel.add(WNewPlayer);
bcombopanel.add(bscroll);
bcombopanel.add(bselect);
bcombopanel.add(BNewPlayer);
WhitePlayer.add(wcombopanel,BorderLayout.NORTH);
BlackPlayer.add(bcombopanel,BorderLayout.NORTH);
whitestats.add(new JLabel("Name :"));
whitestats.add(new JLabel("Played :"));
whitestats.add(new JLabel("Won :"));
blackstats.add(new JLabel("Name :"));
blackstats.add(new JLabel("Played :"));
blackstats.add(new JLabel("Won :"));
WhitePlayer.add(whitestats,BorderLayout.WEST);
BlackPlayer.add(blackstats,BorderLayout.WEST);
controlPanel.add(WhitePlayer);
controlPanel.add(BlackPlayer);
//Defining all the Cells
defineAllCells();
/**boardState=new Cell[8][8];
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{
P=null;
if(i==0&&j==0)
P=br01;
else if(i==0&&j==7)
P=br02;
else if(i==7&&j==0)
P=wr01;
else if(i==7&&j==7)
P=wr02;
else if(i==0&&j==1)
P=bk01;
else if (i==0&&j==6)
P=bk02;
else if(i==7&&j==1)
P=wk01;
else if (i==7&&j==6)
P=wk02;
else if(i==0&&j==2)
P=bb01;
else if (i==0&&j==5)
P=bb02;
else if(i==7&&j==2)
P=wb01;
else if(i==7&&j==5)
P=wb02;
else if(i==0&&j==3)
P=bk;
else if(i==0&&j==4)
P=bq;
else if(i==7&&j==3)
P=wk;
else if(i==7&&j==4)
P=wq;
else if(i==1)
P=bp[j];
else if(i==6)
P=wp[j];
cell=new Cell(i,j,P);
cell.addMouseListener(this);
board.add(cell);
boardState[i][j]=cell;
}**/
showPlayer=new JPanel(new FlowLayout());
showPlayer.add(timeSlider);
JLabel setTime=new JLabel("Set Timer(in mins):");
start=new Button("Start");
start.setBackground(Color.black);
start.setForeground(Color.white);
start.addActionListener(new START());
start.setPreferredSize(new Dimension(120,40));
setTime.setFont(new Font("Arial",Font.BOLD,16));
label = new JLabel("Time Starts now", JLabel.CENTER);
label.setFont(new Font("SERIF", Font.BOLD, 30));
displayTime=new JPanel(new FlowLayout());
time=new JPanel(new GridLayout(3,3));
time.add(setTime);
time.add(showPlayer);
displayTime.add(start);
time.add(displayTime);
controlPanel.add(time);
board.setMinimumSize(new Dimension(800,700));
//The Left Layout When Game is inactive
temp=new JPanel(){
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
try {
image = ImageIO.read(this.getClass().getResource("clash.jpg"));
} catch (IOException ex) {
System.out.println("not found");
}
g.drawImage(image, 0, 0, null);
}
};
temp.setMinimumSize(new Dimension(800,700));
controlPanel.setMinimumSize(new Dimension(285,700));
split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,temp, controlPanel);
content.add(split);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//A function used to define all cells
public void defineAllCells(){
pieces.Piece P;
Cell cell;
boardState=new Cell[8][8];
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{
P=null;
if(i==0&&j==0)
P=br01;
else if(i==0&&j==7)
P=br02;
else if(i==7&&j==0)
P=wr01;
else if(i==7&&j==7)
P=wr02;
else if(i==0&&j==1)
P=bk01;
else if (i==0&&j==6)
P=bk02;
else if(i==7&&j==1)
P=wk01;
else if (i==7&&j==6)
P=wk02;
else if(i==0&&j==2)
P=bb01;
else if (i==0&&j==5)
P=bb02;
else if(i==7&&j==2)
P=wb01;
else if(i==7&&j==5)
P=wb02;
else if(i==0&&j==3)
P=bk;
else if(i==0&&j==4)
P=bq;
else if(i==7&&j==3)
P=wk;
else if(i==7&&j==4)
P=wq;
else if(i==1)
P=bp[j];
else if(i==6)
P=wp[j];
cell=new Cell(i,j,P);
cell.addMouseListener(this);
board.add(cell);
boardState[i][j]=cell;
}
}
//A function to set time slider details
public void setTimerSliderDetails(JSlider timeSlider){
timeSlider.setMinimum(1);
timeSlider.setMaximum(15);
timeSlider.setValue(1);
timeSlider.setMajorTickSpacing(2);
timeSlider.setPaintLabels(true);
timeSlider.setPaintTicks(true);
timeSlider.addChangeListener(new TimeChange());
}
// A function to change the chance from White Player to Black Player or vice verse
// It is made public because it is to be accessed in the Time Class
public void changechance()
{
if (boardState[getKing(chance).getx()][getKing(chance).gety()].ischeck())
{
chance^=1;
gameend();
}
if(destinationlist.isEmpty()==false)
cleandestinations(destinationlist);
if(previous!=null)
previous.deselect();
previous=null;
chance^=1;
if(!end && timer!=null)
{
timer.reset();
timer.start();
showPlayer.remove(CHNC);
if(Main.move=="White")
Main.move="Black";
else
Main.move="White";
CHNC.setText(Main.move);
showPlayer.add(CHNC);
}
}
//A function to retrieve the Black King or White King
private King getKing(int color)
{
if (color==0)
return wk;
else
return bk;
}
//A function to clean the highlights of possible destination cells
private void cleandestinations(ArrayList<Cell> destlist) //Function to clear the last move's destinations
{
ListIterator<Cell> it = destlist.listIterator();
while(it.hasNext())
it.next().removepossibledestination();
}
//A function that indicates the possible moves by highlighting the Cells
private void highlightdestinations(ArrayList<Cell> destlist)
{
ListIterator<Cell> it = destlist.listIterator();
while(it.hasNext())
it.next().setpossibledestination();
}
//Function to check if the king will be in danger if the given move is made
private boolean willkingbeindanger(Cell fromcell,Cell tocell)
{
Cell newboardstate[][] = new Cell[8][8];
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{ try { newboardstate[i][j] = new Cell(boardState[i][j]);} catch (CloneNotSupportedException e){e.printStackTrace(); System.out.println("There is a problem with cloning !!"); }}
if(newboardstate[tocell.x][tocell.y].getpiece()!=null)
newboardstate[tocell.x][tocell.y].removePiece();
newboardstate[tocell.x][tocell.y].setPiece(newboardstate[fromcell.x][fromcell.y].getpiece());
if(newboardstate[tocell.x][tocell.y].getpiece() instanceof King)
{
((King)(newboardstate[tocell.x][tocell.y].getpiece())).setx(tocell.x);
((King)(newboardstate[tocell.x][tocell.y].getpiece())).sety(tocell.y);
}
newboardstate[fromcell.x][fromcell.y].removePiece();
if (((King)(newboardstate[getKing(chance).getx()][getKing(chance).gety()].getpiece())).isindanger(newboardstate)==true)
return true;
else
return false;
}
//A function to eliminate the possible moves that will put the King in danger
private ArrayList<Cell> filterdestination (ArrayList<Cell> destlist, Cell fromcell)
{
ArrayList<Cell> newlist = new ArrayList<Cell>();
Cell newboardstate[][] = new Cell[8][8];
ListIterator<Cell> it = destlist.listIterator();
int x,y;
while (it.hasNext())
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{ try { newboardstate[i][j] = new Cell(boardState[i][j]);} catch (CloneNotSupportedException e){e.printStackTrace();}}
Cell tempc = it.next();
if(newboardstate[tempc.x][tempc.y].getpiece()!=null)
newboardstate[tempc.x][tempc.y].removePiece();
newboardstate[tempc.x][tempc.y].setPiece(newboardstate[fromcell.x][fromcell.y].getpiece());
x=getKing(chance).getx();
y=getKing(chance).gety();
if(newboardstate[fromcell.x][fromcell.y].getpiece() instanceof King)
{
((King)(newboardstate[tempc.x][tempc.y].getpiece())).setx(tempc.x);
((King)(newboardstate[tempc.x][tempc.y].getpiece())).sety(tempc.y);
x=tempc.x;
y=tempc.y;
}
newboardstate[fromcell.x][fromcell.y].removePiece();
if ((((King)(newboardstate[x][y].getpiece())).isindanger(newboardstate)==false))
newlist.add(tempc);
}
return newlist;
}
//A Function to filter the possible moves when the king of the current player is under Check
private ArrayList<Cell> incheckfilter (ArrayList<Cell> destlist, Cell fromcell, int color)
{
ArrayList<Cell> newlist = new ArrayList<Cell>();
Cell newboardstate[][] = new Cell[8][8];
ListIterator<Cell> it = destlist.listIterator();
int x,y;
while (it.hasNext())
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
{ try { newboardstate[i][j] = new Cell(boardState[i][j]);} catch (CloneNotSupportedException e){e.printStackTrace();}}
Cell tempc = it.next();
if(newboardstate[tempc.x][tempc.y].getpiece()!=null)
newboardstate[tempc.x][tempc.y].removePiece();
newboardstate[tempc.x][tempc.y].setPiece(newboardstate[fromcell.x][fromcell.y].getpiece());
x=getKing(color).getx();
y=getKing(color).gety();
if(newboardstate[tempc.x][tempc.y].getpiece() instanceof King)
{
((King)(newboardstate[tempc.x][tempc.y].getpiece())).setx(tempc.x);
((King)(newboardstate[tempc.x][tempc.y].getpiece())).sety(tempc.y);
x=tempc.x;
y=tempc.y;
}
newboardstate[fromcell.x][fromcell.y].removePiece();
if ((((King)(newboardstate[x][y].getpiece())).isindanger(newboardstate)==false))
newlist.add(tempc);
}
return newlist;
}
//A function to check if the King is check-mate. The Game Ends if this function returns true.
public boolean checkmate(int color)
{
ArrayList<Cell> dlist = new ArrayList<Cell>();
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if (boardState[i][j].getpiece()!=null && boardState[i][j].getpiece().getcolor()==color)
{
dlist.clear();
dlist=boardState[i][j].getpiece().move(boardState, i, j);
dlist=incheckfilter(dlist,boardState[i][j],color);
if(dlist.size()!=0)
return false;
}
}
}
return true;
}
@SuppressWarnings("deprecation")
private void gameend()
{
cleandestinations(destinationlist);
displayTime.disable();
timer.countdownTimer.stop();
if(previous!=null)
previous.removePiece();
if(chance==0)
{ White.updateGamesWon();
White.Update_Player();
winner=White.name();
}
else
{
Black.updateGamesWon();
Black.Update_Player();
winner=Black.name();
}
JOptionPane.showMessageDialog(board,"Checkmate!!!\n"+winner+" wins");
WhitePlayer.remove(wdetails);
BlackPlayer.remove(bdetails);
displayTime.remove(label);
displayTime.add(start);
showPlayer.remove(mov);
showPlayer.remove(CHNC);
showPlayer.revalidate();
showPlayer.add(timeSlider);
split.remove(board);
split.add(temp);
WNewPlayer.enable();
BNewPlayer.enable();
wselect.enable();
bselect.enable();
end=true;
Mainboard.disable();
Mainboard.dispose();
Mainboard = new Main();
Mainboard.setVisible(true);
Mainboard.setResizable(false);
}
//These are the abstract function of the parent class. Only relevant method here is the On-Click Fuction
//which is called when the user clicks on a particular cell
@Override
public void mouseClicked(MouseEvent arg0){
// TODO Auto-generated method stub
c=(Cell)arg0.getSource();
if (previous==null)
{
if(c.getpiece()!=null)
{
if(c.getpiece().getcolor()!=chance)
return;
c.select();
previous=c;
destinationlist.clear();
destinationlist=c.getpiece().move(boardState, c.x, c.y);
if(c.getpiece() instanceof King)
destinationlist=filterdestination(destinationlist,c);
else
{
if(boardState[getKing(chance).getx()][getKing(chance).gety()].ischeck())
destinationlist = new ArrayList<Cell>(filterdestination(destinationlist,c));
else if(destinationlist.isEmpty()==false && willkingbeindanger(c,destinationlist.get(0)))
destinationlist.clear();
}
highlightdestinations(destinationlist);
}
}
else
{
if(c.x==previous.x && c.y==previous.y)
{
c.deselect();
cleandestinations(destinationlist);
destinationlist.clear();
previous=null;
}
else if(c.getpiece()==null||previous.getpiece().getcolor()!=c.getpiece().getcolor())
{
if(c.ispossibledestination())
{
if(c.getpiece()!=null)
c.removePiece();
c.setPiece(previous.getpiece());
if (previous.ischeck())
previous.removecheck();
previous.removePiece();
if(getKing(chance^1).isindanger(boardState))
{
boardState[getKing(chance^1).getx()][getKing(chance^1).gety()].setcheck();
if (checkmate(getKing(chance^1).getcolor()))
{
previous.deselect();
if(previous.getpiece()!=null)
previous.removePiece();
gameend();
}
}
if(getKing(chance).isindanger(boardState)==false)
boardState[getKing(chance).getx()][getKing(chance).gety()].removecheck();
if(c.getpiece() instanceof King)
{
((King)c.getpiece()).setx(c.x);
((King)c.getpiece()).sety(c.y);
}
changechance();
if(!end)
{
timer.reset();
timer.start();
}
}
if(previous!=null)
{
previous.deselect();
previous=null;
}
cleandestinations(destinationlist);
destinationlist.clear();
}
else if(previous.getpiece().getcolor()==c.getpiece().getcolor())
{
previous.deselect();
cleandestinations(destinationlist);
destinationlist.clear();
c.select();
previous=c;
destinationlist=c.getpiece().move(boardState, c.x, c.y);
if(c.getpiece() instanceof King)
destinationlist=filterdestination(destinationlist,c);
else
{
if(boardState[getKing(chance).getx()][getKing(chance).gety()].ischeck())
destinationlist = new ArrayList<Cell>(filterdestination(destinationlist,c));
else if(destinationlist.isEmpty()==false && willkingbeindanger(c,destinationlist.get(0)))
destinationlist.clear();
}
highlightdestinations(destinationlist);
}
}
if(c.getpiece()!=null && c.getpiece() instanceof King)
{
((King)c.getpiece()).setx(c.x);
((King)c.getpiece()).sety(c.y);
}
}
//Other Irrelevant abstract function. Only the Click Event is captured.
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
class START implements ActionListener
{
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(White==null||Black==null)
{JOptionPane.showMessageDialog(controlPanel, "Fill in the details");
return;}
White.updateGamesPlayed();
White.Update_Player();
Black.updateGamesPlayed();
Black.Update_Player();
WNewPlayer.disable();
BNewPlayer.disable();
wselect.disable();
bselect.disable();
split.remove(temp);
split.add(board);
showPlayer.remove(timeSlider);
mov=new JLabel("Move:");
mov.setFont(new Font("Comic Sans MS",Font.PLAIN,20));
mov.setForeground(Color.red);
showPlayer.add(mov);
CHNC=new JLabel(move);
CHNC.setFont(new Font("Comic Sans MS",Font.BOLD,20));
CHNC.setForeground(Color.blue);
showPlayer.add(CHNC);
displayTime.remove(start);
displayTime.add(label);
timer=new Time(label);
timer.start();
}
}
class TimeChange implements ChangeListener
{
@Override
public void stateChanged(ChangeEvent arg0)
{
timeRemaining=timeSlider.getValue()*60;
}
}
class SelectHandler implements ActionListener
{
private int color;
SelectHandler(int i)
{
color=i;
}
@Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
tempPlayer=null;
String n=(color==0)?wname:bname;
JComboBox<String> jc=(color==0)?wcombo:bcombo;
JComboBox<String> ojc=(color==0)?bcombo:wcombo;
ArrayList<Player> pl=(color==0)?wplayer:bplayer;
//ArrayList<Player> otherPlayer=(color==0)?bplayer:wplayer;
ArrayList<Player> opl=Player.fetch_players();
if(opl.isEmpty())
return;
JPanel det=(color==0)?wdetails:bdetails;
JPanel PL=(color==0)?WhitePlayer:BlackPlayer;
if(selected==true)
det.removeAll();
n=(String)jc.getSelectedItem();
Iterator<Player> it=pl.iterator();
Iterator<Player> oit=opl.iterator();
while(it.hasNext())
{
Player p=it.next();
if(p.name().equals(n))
{tempPlayer=p;
break;}
}
while(oit.hasNext())
{
Player p=oit.next();
if(p.name().equals(n))
{opl.remove(p);
break;}
}
if(tempPlayer==null)
return;
if(color==0)
White=tempPlayer;
else
Black=tempPlayer;
bplayer=opl;
ojc.removeAllItems();
for (Player s:opl)
ojc.addItem(s.name());
det.add(new JLabel(" "+tempPlayer.name()));
det.add(new JLabel(" "+tempPlayer.gamesplayed()));
det.add(new JLabel(" "+tempPlayer.gameswon()));
PL.revalidate();
PL.repaint();
PL.add(det);
selected=true;
}
}
class Handler implements ActionListener{
private int color;
Handler(int i)
{
color=i;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String n=(color==0)?wname:bname;
JPanel j=(color==0)?WhitePlayer:BlackPlayer;
ArrayList<Player> N=Player.fetch_players();
Iterator<Player> it=N.iterator();
JPanel det=(color==0)?wdetails:bdetails;
n=JOptionPane.showInputDialog(j,"Enter your name");
if(n!=null)
{
while(it.hasNext())
{
if(it.next().name().equals(n))
{JOptionPane.showMessageDialog(j,"Player exists");
return;}
}
if(n.length()!=0)
{Player tem=new Player(n);
tem.Update_Player();
if(color==0)
White=tem;
else
Black=tem;
}
else return;
}
else
return;
det.removeAll();
det.add(new JLabel(" "+n));
det.add(new JLabel(" 0"));
det.add(new JLabel(" 0"));
j.revalidate();
j.repaint();
j.add(det);
selected=true;
}
}
}
|
package org.jfree.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Stroke;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.annotations.XYTextAnnotation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.PeriodAxis;
import org.jfree.chart.axis.PeriodAxisLabelInfo;
import org.jfree.chart.axis.SubCategoryAxis;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.Block;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.LabelBlock;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.CombinedDomainCategoryPlot;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.CombinedRangeCategoryPlot;
import org.jfree.chart.plot.CombinedRangeXYPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.FastScatterPlot;
import org.jfree.chart.plot.MeterPlot;
import org.jfree.chart.plot.MultiplePiePlot;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PolarPlot;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.plot.ThermometerPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.renderer.category.BarPainter;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.LineRenderer3D;
import org.jfree.chart.renderer.category.MinMaxCategoryRenderer;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.chart.renderer.xy.GradientXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.title.CompositeTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.PaintScaleLegend;
import org.jfree.chart.title.TextTitle;
import org.jfree.chart.title.Title;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleInsets;
import org.jfree.chart.util.SerialUtilities;
/**
* A default implementation of the {@link ChartTheme} interface. This
* implementation just collects a whole bunch of chart attributes and mimics
* the manual process of applying each attribute to the right sub-object
* within the JFreeChart instance. It's not elegant code, but it works.
*
* @since 1.0.11
*/
public class StandardChartTheme implements ChartTheme, Cloneable,
PublicCloneable, Serializable {
/** The name of this theme. */
private String name;
/**
* The largest font size. Use for the main chart title.
*/
private Font extraLargeFont;
/**
* A large font. Used for subtitles.
*/
private Font largeFont;
/**
* The regular font size. Used for axis tick labels, legend items etc.
*/
private Font regularFont;
/**
* The small font size.
*/
private Font smallFont;
/** The paint used to display the main chart title. */
private transient Paint titlePaint;
/** The paint used to display subtitles. */
private transient Paint subtitlePaint;
/** The background paint for the chart. */
private transient Paint chartBackgroundPaint;
/** The legend background paint. */
private transient Paint legendBackgroundPaint;
/** The legend item paint. */
private transient Paint legendItemPaint;
/** The drawing supplier. */
private DrawingSupplier drawingSupplier;
/** The background paint for the plot. */
private transient Paint plotBackgroundPaint;
/** The plot outline paint. */
private transient Paint plotOutlinePaint;
/** The label link style for pie charts. */
private PieLabelLinkStyle labelLinkStyle;
/** The label link paint for pie charts. */
private transient Paint labelLinkPaint;
/** The domain grid line paint. */
private transient Paint domainGridlinePaint;
/** The range grid line paint. */
private transient Paint rangeGridlinePaint;
/**
* The baseline paint (used for domain and range zero baselines)
*
* @since 1.0.13
*/
private transient Paint baselinePaint;
/** The crosshair paint. */
private transient Paint crosshairPaint;
/** The axis offsets. */
private RectangleInsets axisOffset;
/** The axis label paint. */
private transient Paint axisLabelPaint;
/** The tick label paint. */
private transient Paint tickLabelPaint;
/** The item label paint. */
private transient Paint itemLabelPaint;
/**
* A flag that controls whether or not shadows are visible (for example,
* in a bar renderer).
*/
private boolean shadowVisible;
/** The shadow paint. */
private transient Paint shadowPaint;
/** The bar painter. */
private BarPainter barPainter;
/** The XY bar painter. */
private XYBarPainter xyBarPainter;
/** The thermometer paint. */
private transient Paint thermometerPaint;
/**
* The paint used to fill the interior of the 'walls' in the background
* of a plot with a 3D effect. Applied to BarRenderer3D.
*/
private transient Paint wallPaint;
/** The error indicator paint for the {@link StatisticalBarRenderer}. */
private transient Paint errorIndicatorPaint;
/** The grid band paint for a {@link SymbolAxis}. */
private transient Paint gridBandPaint = SymbolAxis.DEFAULT_GRID_BAND_PAINT;
/** The grid band alternate paint for a {@link SymbolAxis}. */
private transient Paint gridBandAlternatePaint
= SymbolAxis.DEFAULT_GRID_BAND_ALTERNATE_PAINT;
/**
* Creates and returns the default 'JFree' chart theme.
*
* @return A chart theme.
*/
public static ChartTheme createJFreeTheme() {
return new StandardChartTheme("JFree");
}
/**
* Creates and returns a theme called "Darkness". In this theme, the
* charts have a black background.
*
* @return The "Darkness" theme.
*/
public static ChartTheme createDarknessTheme() {
StandardChartTheme theme = new StandardChartTheme("Darkness");
theme.titlePaint = Color.white;
theme.subtitlePaint = Color.white;
theme.legendBackgroundPaint = Color.black;
theme.legendItemPaint = Color.white;
theme.chartBackgroundPaint = Color.black;
theme.plotBackgroundPaint = Color.black;
theme.plotOutlinePaint = Color.yellow;
theme.baselinePaint = Color.white;
theme.crosshairPaint = Color.red;
theme.labelLinkPaint = Color.lightGray;
theme.tickLabelPaint = Color.white;
theme.axisLabelPaint = Color.white;
theme.shadowPaint = Color.darkGray;
theme.itemLabelPaint = Color.white;
theme.drawingSupplier = new DefaultDrawingSupplier(
new Paint[] {Color.decode("0xFFFF00"),
Color.decode("0x0036CC"), Color.decode("0xFF0000"),
Color.decode("0xFFFF7F"), Color.decode("0x6681CC"),
Color.decode("0xFF7F7F"), Color.decode("0xFFFFBF"),
Color.decode("0x99A6CC"), Color.decode("0xFFBFBF"),
Color.decode("0xA9A938"), Color.decode("0x2D4587")},
new Paint[] {Color.decode("0xFFFF00"),
Color.decode("0x0036CC")},
new Stroke[] {new BasicStroke(2.0f)},
new Stroke[] {new BasicStroke(0.5f)},
DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
theme.wallPaint = Color.darkGray;
theme.errorIndicatorPaint = Color.lightGray;
theme.gridBandPaint = new Color(255, 255, 255, 20);
theme.gridBandAlternatePaint = new Color(255, 255, 255, 40);
return theme;
}
/**
* Creates and returns a {@link ChartTheme} that doesn't apply any changes
* to the JFreeChart defaults. This produces the "legacy" look for
* JFreeChart.
*
* @return A legacy theme.
*/
public static ChartTheme createLegacyTheme() {
StandardChartTheme theme = new StandardChartTheme("Legacy") {
public void apply(JFreeChart chart) {
// do nothing at all
}
};
return theme;
}
/**
* Creates a new default instance.
*
* @param name the name of the theme (<code>null</code> not permitted).
*/
public StandardChartTheme(String name) {
if (name == null) {
throw new IllegalArgumentException("Null 'name' argument.");
}
this.name = name;
this.extraLargeFont = new Font("Tahoma", Font.BOLD, 20);
this.largeFont = new Font("Tahoma", Font.BOLD, 14);
this.regularFont = new Font("Tahoma", Font.PLAIN, 12);
this.smallFont = new Font("Tahoma", Font.PLAIN, 10);
this.titlePaint = Color.black;
this.subtitlePaint = Color.black;
this.legendBackgroundPaint = Color.white;
this.legendItemPaint = Color.darkGray;
this.chartBackgroundPaint = Color.white;
this.drawingSupplier = new DefaultDrawingSupplier();
this.plotBackgroundPaint = Color.lightGray;
this.plotOutlinePaint = Color.black;
this.labelLinkPaint = Color.black;
this.labelLinkStyle = PieLabelLinkStyle.CUBIC_CURVE;
this.axisOffset = new RectangleInsets(4, 4, 4, 4);
this.domainGridlinePaint = Color.white;
this.rangeGridlinePaint = Color.white;
this.crosshairPaint = Color.blue;
this.axisLabelPaint = Color.darkGray;
this.tickLabelPaint = Color.darkGray;
this.barPainter = new GradientBarPainter();
this.xyBarPainter = new GradientXYBarPainter();
this.shadowVisible = true;
this.shadowPaint = Color.gray;
this.itemLabelPaint = Color.black;
this.thermometerPaint = Color.white;
this.wallPaint = BarRenderer3D.DEFAULT_WALL_PAINT;
this.errorIndicatorPaint = Color.black;
}
/**
* Returns the largest font for this theme.
*
* @return The largest font for this theme.
*
* @see #setExtraLargeFont(Font)
*/
public Font getExtraLargeFont() {
return this.extraLargeFont;
}
/**
* Sets the largest font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getExtraLargeFont()
*/
public void setExtraLargeFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.extraLargeFont = font;
}
/**
* Returns the large font for this theme.
*
* @return The large font (never <code>null</code>).
*
* @see #setLargeFont(Font)
*/
public Font getLargeFont() {
return this.largeFont;
}
/**
* Sets the large font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getLargeFont()
*/
public void setLargeFont(Font font) {
this.largeFont = font;
}
/**
* Returns the regular font.
*
* @return The regular font (never <code>null</code>).
*
* @see #setRegularFont(Font)
*/
public Font getRegularFont() {
return this.regularFont;
}
/**
* Sets the regular font for this theme.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getRegularFont()
*/
public void setRegularFont(Font font) {
this.regularFont = font;
}
/**
* Returns the title paint.
*
* @return The title paint (never <code>null</code>).
*
* @see #setTitlePaint(Paint)
*/
public Paint getTitlePaint() {
return this.titlePaint;
}
/**
* Sets the title paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTitlePaint()
*/
public void setTitlePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.titlePaint = paint;
}
/**
* Returns the subtitle paint.
*
* @return The subtitle paint (never <code>null</code>).
*
* @see #setSubtitlePaint(Paint)
*/
public Paint getSubtitlePaint() {
return this.subtitlePaint;
}
/**
* Sets the subtitle paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getSubtitlePaint()
*/
public void setSubtitlePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.subtitlePaint = paint;
}
/**
* Returns the chart background paint.
*
* @return The chart background paint (never <code>null</code>).
*
* @see #setChartBackgroundPaint(Paint)
*/
public Paint getChartBackgroundPaint() {
return this.chartBackgroundPaint;
}
/**
* Sets the chart background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getChartBackgroundPaint()
*/
public void setChartBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.chartBackgroundPaint = paint;
}
/**
* Returns the legend background paint.
*
* @return The legend background paint (never <code>null</code>).
*
* @see #setLegendBackgroundPaint(Paint)
*/
public Paint getLegendBackgroundPaint() {
return this.legendBackgroundPaint;
}
/**
* Sets the legend background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendBackgroundPaint()
*/
public void setLegendBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendBackgroundPaint = paint;
}
/**
* Returns the legend item paint.
*
* @return The legend item paint (never <code>null</code>).
*
* @see #setLegendItemPaint(Paint)
*/
public Paint getLegendItemPaint() {
return this.legendItemPaint;
}
/**
* Sets the legend item paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLegendItemPaint()
*/
public void setLegendItemPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.legendItemPaint = paint;
}
/**
* Returns the plot background paint.
*
* @return The plot background paint (never <code>null</code>).
*
* @see #setPlotBackgroundPaint(Paint)
*/
public Paint getPlotBackgroundPaint() {
return this.plotBackgroundPaint;
}
/**
* Sets the plot background paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotBackgroundPaint()
*/
public void setPlotBackgroundPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.plotBackgroundPaint = paint;
}
/**
* Returns the plot outline paint.
*
* @return The plot outline paint (never <code>null</code>).
*
* @see #setPlotOutlinePaint(Paint)
*/
public Paint getPlotOutlinePaint() {
return this.plotOutlinePaint;
}
/**
* Sets the plot outline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPlotOutlinePaint()
*/
public void setPlotOutlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.plotOutlinePaint = paint;
}
/**
* Returns the label link style for pie charts.
*
* @return The label link style (never <code>null</code>).
*
* @see #setLabelLinkStyle(PieLabelLinkStyle)
*/
public PieLabelLinkStyle getLabelLinkStyle() {
return this.labelLinkStyle;
}
/**
* Sets the label link style for pie charts.
*
* @param style the style (<code>null</code> not permitted).
*
* @see #getLabelLinkStyle()
*/
public void setLabelLinkStyle(PieLabelLinkStyle style) {
if (style == null) {
throw new IllegalArgumentException("Null 'style' argument.");
}
this.labelLinkStyle = style;
}
/**
* Returns the label link paint for pie charts.
*
* @return The label link paint (never <code>null</code>).
*
* @see #setLabelLinkPaint(Paint)
*/
public Paint getLabelLinkPaint() {
return this.labelLinkPaint;
}
/**
* Sets the label link paint for pie charts.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getLabelLinkPaint()
*/
public void setLabelLinkPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.labelLinkPaint = paint;
}
/**
* Returns the domain grid line paint.
*
* @return The domain grid line paint (never <code>null<code>).
*
* @see #setDomainGridlinePaint(Paint)
*/
public Paint getDomainGridlinePaint() {
return this.domainGridlinePaint;
}
/**
* Sets the domain grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getDomainGridlinePaint()
*/
public void setDomainGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainGridlinePaint = paint;
}
/**
* Returns the range grid line paint.
*
* @return The range grid line paint (never <code>null</code>).
*
* @see #setRangeGridlinePaint(Paint)
*/
public Paint getRangeGridlinePaint() {
return this.rangeGridlinePaint;
}
/**
* Sets the range grid line paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeGridlinePaint()
*/
public void setRangeGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeGridlinePaint = paint;
}
/**
* Returns the baseline paint.
*
* @return The baseline paint.
*
* @since 1.0.13
*/
public Paint getBaselinePaint() {
return this.baselinePaint;
}
/**
* Sets the baseline paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.13
*/
public void setBaselinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.baselinePaint = paint;
}
/**
* Returns the crosshair paint.
*
* @return The crosshair paint.
*/
public Paint getCrosshairPaint() {
return this.crosshairPaint;
}
/**
* Sets the crosshair paint.
*
* @param paint the paint (<code>null</code> not permitted).
*/
public void setCrosshairPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.crosshairPaint = paint;
}
/**
* Returns the axis offsets.
*
* @return The axis offsets (never <code>null</code>).
*
* @see #setAxisOffset(RectangleInsets)
*/
public RectangleInsets getAxisOffset() {
return this.axisOffset;
}
/**
* Sets the axis offset.
*
* @param offset the offset (<code>null</code> not permitted).
*
* @see #getAxisOffset()
*/
public void setAxisOffset(RectangleInsets offset) {
if (offset == null) {
throw new IllegalArgumentException("Null 'offset' argument.");
}
this.axisOffset = offset;
}
/**
* Returns the axis label paint.
*
* @return The axis label paint (never <code>null</code>).
*
* @see #setAxisLabelPaint(Paint)
*/
public Paint getAxisLabelPaint() {
return this.axisLabelPaint;
}
/**
* Sets the axis label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getAxisLabelPaint()
*/
public void setAxisLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.axisLabelPaint = paint;
}
/**
* Returns the tick label paint.
*
* @return The tick label paint (never <code>null</code>).
*
* @see #setTickLabelPaint(Paint)
*/
public Paint getTickLabelPaint() {
return this.tickLabelPaint;
}
/**
* Sets the tick label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getTickLabelPaint()
*/
public void setTickLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.tickLabelPaint = paint;
}
/**
* Returns the item label paint.
*
* @return The item label paint (never <code>null</code>).
*
* @see #setItemLabelPaint(Paint)
*/
public Paint getItemLabelPaint() {
return this.itemLabelPaint;
}
/**
* Sets the item label paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getItemLabelPaint()
*/
public void setItemLabelPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.itemLabelPaint = paint;
}
/**
* Returns the shadow visibility flag.
*
* @return The shadow visibility flag.
*
* @see #setShadowVisible(boolean)
*/
public boolean isShadowVisible() {
return this.shadowVisible;
}
/**
* Sets the shadow visibility flag.
*
* @param visible the flag.
*
* @see #isShadowVisible()
*/
public void setShadowVisible(boolean visible) {
this.shadowVisible = visible;
}
/**
* Returns the shadow paint.
*
* @return The shadow paint (never <code>null</code>).
*
* @see #setShadowPaint(Paint)
*/
public Paint getShadowPaint() {
return this.shadowPaint;
}
/**
* Sets the shadow paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getShadowPaint()
*/
public void setShadowPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.shadowPaint = paint;
}
/**
* Returns the bar painter.
*
* @return The bar painter (never <code>null</code>).
*
* @see #setBarPainter(BarPainter)
*/
public BarPainter getBarPainter() {
return this.barPainter;
}
/**
* Sets the bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getBarPainter()
*/
public void setBarPainter(BarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.barPainter = painter;
}
/**
* Returns the XY bar painter.
*
* @return The XY bar painter (never <code>null</code>).
*
* @see #setXYBarPainter(XYBarPainter)
*/
public XYBarPainter getXYBarPainter() {
return this.xyBarPainter;
}
/**
* Sets the XY bar painter.
*
* @param painter the painter (<code>null</code> not permitted).
*
* @see #getXYBarPainter()
*/
public void setXYBarPainter(XYBarPainter painter) {
if (painter == null) {
throw new IllegalArgumentException("Null 'painter' argument.");
}
this.xyBarPainter = painter;
}
/**
* Returns the thermometer paint.
*
* @return The thermometer paint (never <code>null</code>).
*
* @see #setThermometerPaint(Paint)
*/
public Paint getThermometerPaint() {
return this.thermometerPaint;
}
/**
* Sets the thermometer paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getThermometerPaint()
*/
public void setThermometerPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.thermometerPaint = paint;
}
/**
* Returns the wall paint for charts with a 3D effect.
*
* @return The wall paint (never <code>null</code>).
*
* @see #setWallPaint(Paint)
*/
public Paint getWallPaint() {
return this.wallPaint;
}
/**
* Sets the wall paint for charts with a 3D effect.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getWallPaint()
*/
public void setWallPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.wallPaint = paint;
}
/**
* Returns the error indicator paint.
*
* @return The error indicator paint (never <code>null</code>).
*
* @see #setErrorIndicatorPaint(Paint)
*/
public Paint getErrorIndicatorPaint() {
return this.errorIndicatorPaint;
}
/**
* Sets the error indicator paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getErrorIndicatorPaint()
*/
public void setErrorIndicatorPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.errorIndicatorPaint = paint;
}
/**
* Returns the grid band paint.
*
* @return The grid band paint (never <code>null</code>).
*
* @see #setGridBandPaint(Paint)
*/
public Paint getGridBandPaint() {
return this.gridBandPaint;
}
/**
* Sets the grid band paint.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandPaint()
*/
public void setGridBandPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandPaint = paint;
}
/**
* Returns the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @return The paint (never <code>null</code>).
*
* @see #setGridBandAlternatePaint(Paint)
*/
public Paint getGridBandAlternatePaint() {
return this.gridBandAlternatePaint;
}
/**
* Sets the grid band alternate paint (used for a {@link SymbolAxis}).
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandAlternatePaint()
*/
public void setGridBandAlternatePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.gridBandAlternatePaint = paint;
}
/**
* Returns the name of this theme.
*
* @return The name of this theme.
*/
public String getName() {
return this.name;
}
/**
* Returns a clone of the drawing supplier for this theme.
*
* @return A clone of the drawing supplier.
*/
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
if (this.drawingSupplier instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.drawingSupplier;
try {
result = (DrawingSupplier) pc.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
return result;
}
/**
* Sets the drawing supplier for this theme.
*
* @param supplier the supplier (<code>null</code> not permitted).
*
* @see #getDrawingSupplier()
*/
public void setDrawingSupplier(DrawingSupplier supplier) {
if (supplier == null) {
throw new IllegalArgumentException("Null 'supplier' argument.");
}
this.drawingSupplier = supplier;
}
/**
* Applies this theme to the supplied chart.
*
* @param chart the chart (<code>null</code> not permitted).
*/
public void apply(JFreeChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Null 'chart' argument.");
}
TextTitle title = chart.getTitle();
if (title != null) {
title.setFont(this.extraLargeFont);
title.setPaint(this.titlePaint);
}
int subtitleCount = chart.getSubtitleCount();
for (int i = 0; i < subtitleCount; i++) {
applyToTitle(chart.getSubtitle(i));
}
chart.setBackgroundPaint(this.chartBackgroundPaint);
// now process the plot if there is one
Plot plot = chart.getPlot();
if (plot != null) {
applyToPlot(plot);
}
}
/**
* Applies the attributes of this theme to the specified title.
*
* @param title the title.
*/
protected void applyToTitle(Title title) {
if (title instanceof TextTitle) {
TextTitle tt = (TextTitle) title;
tt.setFont(this.largeFont);
tt.setPaint(this.subtitlePaint);
}
else if (title instanceof LegendTitle) {
LegendTitle lt = (LegendTitle) title;
if (lt.getBackgroundPaint() != null) {
lt.setBackgroundPaint(this.legendBackgroundPaint);
}
lt.setItemFont(this.regularFont);
lt.setItemPaint(this.legendItemPaint);
if (lt.getWrapper() != null) {
applyToBlockContainer(lt.getWrapper());
}
}
else if (title instanceof PaintScaleLegend) {
PaintScaleLegend psl = (PaintScaleLegend) title;
psl.setBackgroundPaint(this.legendBackgroundPaint);
ValueAxis axis = psl.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
else if (title instanceof CompositeTitle) {
CompositeTitle ct = (CompositeTitle) title;
BlockContainer bc = ct.getContainer();
List blocks = bc.getBlocks();
Iterator iterator = blocks.iterator();
while (iterator.hasNext()) {
Block b = (Block) iterator.next();
if (b instanceof Title) {
applyToTitle((Title) b);
}
}
}
}
/**
* Applies the attributes of this theme to the specified container.
*
* @param bc a block container (<code>null</code> not permitted).
*/
protected void applyToBlockContainer(BlockContainer bc) {
Iterator iterator = bc.getBlocks().iterator();
while (iterator.hasNext()) {
Block b = (Block) iterator.next();
applyToBlock(b);
}
}
/**
* Applies the attributes of this theme to the specified block.
*
* @param b the block.
*/
protected void applyToBlock(Block b) {
if (b instanceof Title) {
applyToTitle((Title) b);
}
else if (b instanceof LabelBlock) {
LabelBlock lb = (LabelBlock) b;
lb.setFont(this.regularFont);
lb.setPaint(this.legendItemPaint);
}
}
/**
* Applies the attributes of this theme to a plot.
*
* @param plot the plot (<code>null</code>).
*/
protected void applyToPlot(Plot plot) {
if (plot == null) {
throw new IllegalArgumentException("Null 'plot' argument.");
}
if (plot.getDrawingSupplier() != null) {
plot.setDrawingSupplier(getDrawingSupplier());
}
if (plot.getBackgroundPaint() != null) {
plot.setBackgroundPaint(this.plotBackgroundPaint);
}
plot.setOutlinePaint(this.plotOutlinePaint);
// now handle specific plot types (and yes, I know this is some
// really ugly code that has to be manually updated any time a new
// plot type is added - I should have written something much cooler,
// but I didn't and neither did anyone else).
if (plot instanceof PiePlot) {
applyToPiePlot((PiePlot) plot);
}
else if (plot instanceof MultiplePiePlot) {
applyToMultiplePiePlot((MultiplePiePlot) plot);
}
else if (plot instanceof CategoryPlot) {
applyToCategoryPlot((CategoryPlot) plot);
}
else if (plot instanceof XYPlot) {
applyToXYPlot((XYPlot) plot);
}
else if (plot instanceof FastScatterPlot) {
applyToFastScatterPlot((FastScatterPlot) plot);
}
else if (plot instanceof MeterPlot) {
applyToMeterPlot((MeterPlot) plot);
}
else if (plot instanceof ThermometerPlot) {
applyToThermometerPlot((ThermometerPlot) plot);
}
else if (plot instanceof SpiderWebPlot) {
applyToSpiderWebPlot((SpiderWebPlot) plot);
}
else if (plot instanceof PolarPlot) {
applyToPolarPlot((PolarPlot) plot);
}
}
/**
* Applies the attributes of this theme to a {@link PiePlot} instance.
* This method also clears any set values for the section paint, outline
* etc, so that the theme's {@link DrawingSupplier} will be used.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPiePlot(PiePlot plot) {
plot.setLabelLinkPaint(this.labelLinkPaint);
plot.setLabelLinkStyle(this.labelLinkStyle);
plot.setLabelFont(this.regularFont);
// clear the section attributes so that the theme's DrawingSupplier
// will be used
if (plot.getAutoPopulateSectionPaint()) {
plot.clearSectionPaints(false);
}
if (plot.getAutoPopulateSectionOutlinePaint()) {
plot.clearSectionOutlinePaints(false);
}
if (plot.getAutoPopulateSectionOutlineStroke()) {
plot.clearSectionOutlineStrokes(false);
}
}
/**
* Applies the attributes of this theme to a {@link MultiplePiePlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMultiplePiePlot(MultiplePiePlot plot) {
apply(plot.getPieChart());
}
/**
* Applies the attributes of this theme to a {@link CategoryPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToCategoryPlot(CategoryPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
plot.setRangeZeroBaselinePaint(this.baselinePaint);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
CategoryAxis axis = plot.getDomainAxis(i);
if (axis != null) {
applyToCategoryAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
CategoryItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToCategoryItemRenderer(r);
}
}
if (plot instanceof CombinedDomainCategoryPlot) {
CombinedDomainCategoryPlot cp = (CombinedDomainCategoryPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
CategoryPlot subplot = (CategoryPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeCategoryPlot) {
CombinedRangeCategoryPlot cp = (CombinedRangeCategoryPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
CategoryPlot subplot = (CategoryPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link XYPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToXYPlot(XYPlot plot) {
plot.setAxisOffset(this.axisOffset);
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
plot.setDomainCrosshairPaint(this.crosshairPaint);
plot.setRangeCrosshairPaint(this.crosshairPaint);
// process all domain axes
int domainAxisCount = plot.getDomainAxisCount();
for (int i = 0; i < domainAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getDomainAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all range axes
int rangeAxisCount = plot.getRangeAxisCount();
for (int i = 0; i < rangeAxisCount; i++) {
ValueAxis axis = (ValueAxis) plot.getRangeAxis(i);
if (axis != null) {
applyToValueAxis(axis);
}
}
// process all renderers
int rendererCount = plot.getRendererCount();
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer r = plot.getRenderer(i);
if (r != null) {
applyToXYItemRenderer(r);
}
}
// process all annotations
Iterator iter = plot.getAnnotations().iterator();
while (iter.hasNext()) {
XYAnnotation a = (XYAnnotation) iter.next();
applyToXYAnnotation(a);
}
if (plot instanceof CombinedDomainXYPlot) {
CombinedDomainXYPlot cp = (CombinedDomainXYPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
XYPlot subplot = (XYPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
if (plot instanceof CombinedRangeXYPlot) {
CombinedRangeXYPlot cp = (CombinedRangeXYPlot) plot;
Iterator iterator = cp.getSubplots().iterator();
while (iterator.hasNext()) {
XYPlot subplot = (XYPlot) iterator.next();
if (subplot != null) {
applyToPlot(subplot);
}
}
}
}
/**
* Applies the attributes of this theme to a {@link FastScatterPlot}.
* @param plot
*/
protected void applyToFastScatterPlot(FastScatterPlot plot) {
plot.setDomainGridlinePaint(this.domainGridlinePaint);
plot.setRangeGridlinePaint(this.rangeGridlinePaint);
ValueAxis xAxis = plot.getDomainAxis();
if (xAxis != null) {
applyToValueAxis(xAxis);
}
ValueAxis yAxis = plot.getRangeAxis();
if (yAxis != null) {
applyToValueAxis(yAxis);
}
}
/**
* Applies the attributes of this theme to a {@link PolarPlot}. This
* method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToPolarPlot(PolarPlot plot) {
plot.setAngleLabelFont(this.regularFont);
plot.setAngleLabelPaint(this.tickLabelPaint);
plot.setAngleGridlinePaint(this.domainGridlinePaint);
plot.setRadiusGridlinePaint(this.rangeGridlinePaint);
ValueAxis axis = plot.getAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes of this theme to a {@link SpiderWebPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToSpiderWebPlot(SpiderWebPlot plot) {
plot.setLabelFont(this.regularFont);
plot.setLabelPaint(this.axisLabelPaint);
plot.setAxisLinePaint(this.axisLabelPaint);
}
/**
* Applies the attributes of this theme to a {@link MeterPlot}.
*
* @param plot the plot (<code>null</code> not permitted).
*/
protected void applyToMeterPlot(MeterPlot plot) {
plot.setDialBackgroundPaint(this.plotBackgroundPaint);
plot.setValueFont(this.largeFont);
plot.setValuePaint(this.axisLabelPaint);
plot.setDialOutlinePaint(this.plotOutlinePaint);
plot.setNeedlePaint(this.thermometerPaint);
plot.setTickLabelFont(this.regularFont);
plot.setTickLabelPaint(this.tickLabelPaint);
}
/**
* Applies the attributes for this theme to a {@link ThermometerPlot}.
* This method is called from the {@link #applyToPlot(Plot)} method.
*
* @param plot the plot.
*/
protected void applyToThermometerPlot(ThermometerPlot plot) {
plot.setValueFont(this.largeFont);
plot.setThermometerPaint(this.thermometerPaint);
ValueAxis axis = plot.getRangeAxis();
if (axis != null) {
applyToValueAxis(axis);
}
}
/**
* Applies the attributes for this theme to a {@link CategoryAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToCategoryAxis(CategoryAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SubCategoryAxis) {
SubCategoryAxis sca = (SubCategoryAxis) axis;
sca.setSubLabelFont(this.regularFont);
sca.setSubLabelPaint(this.tickLabelPaint);
}
}
/**
* Applies the attributes for this theme to a {@link ValueAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToValueAxis(ValueAxis axis) {
axis.setLabelFont(this.largeFont);
axis.setLabelPaint(this.axisLabelPaint);
axis.setTickLabelFont(this.regularFont);
axis.setTickLabelPaint(this.tickLabelPaint);
if (axis instanceof SymbolAxis) {
applyToSymbolAxis((SymbolAxis) axis);
}
if (axis instanceof PeriodAxis) {
applyToPeriodAxis((PeriodAxis) axis);
}
}
/**
* Applies the attributes for this theme to a {@link SymbolAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToSymbolAxis(SymbolAxis axis) {
axis.setGridBandPaint(this.gridBandPaint);
axis.setGridBandAlternatePaint(this.gridBandAlternatePaint);
}
/**
* Applies the attributes for this theme to a {@link PeriodAxis}.
*
* @param axis the axis (<code>null</code> not permitted).
*/
protected void applyToPeriodAxis(PeriodAxis axis) {
PeriodAxisLabelInfo[] info = axis.getLabelInfo();
for (int i = 0; i < info.length; i++) {
PeriodAxisLabelInfo e = info[i];
PeriodAxisLabelInfo n = new PeriodAxisLabelInfo(e.getPeriodClass(),
e.getDateFormat(), e.getPadding(), this.regularFont,
this.tickLabelPaint, e.getDrawDividers(),
e.getDividerStroke(), e.getDividerPaint());
info[i] = n;
}
axis.setLabelInfo(info);
}
/**
* Applies the attributes for this theme to an {@link AbstractRenderer}.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToAbstractRenderer(AbstractRenderer renderer) {
if (renderer.getAutoPopulateSeriesPaint()) {
renderer.clearSeriesPaints(false);
}
if (renderer.getAutoPopulateSeriesStroke()) {
renderer.clearSeriesStrokes(false);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToCategoryItemRenderer(CategoryItemRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException("Null 'renderer' argument.");
}
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setBaseItemLabelFont(this.regularFont);
renderer.setBaseItemLabelPaint(this.itemLabelPaint);
// now we handle some special cases - yes, UGLY code alert!
// BarRenderer
if (renderer instanceof BarRenderer) {
BarRenderer br = (BarRenderer) renderer;
br.setBarPainter(this.barPainter);
br.setShadowVisible(this.shadowVisible);
br.setShadowPaint(this.shadowPaint);
}
// BarRenderer3D
if (renderer instanceof BarRenderer3D) {
BarRenderer3D br3d = (BarRenderer3D) renderer;
br3d.setWallPaint(this.wallPaint);
}
// LineRenderer3D
if (renderer instanceof LineRenderer3D) {
LineRenderer3D lr3d = (LineRenderer3D) renderer;
lr3d.setWallPaint(this.wallPaint);
}
// StatisticalBarRenderer
if (renderer instanceof StatisticalBarRenderer) {
StatisticalBarRenderer sbr = (StatisticalBarRenderer) renderer;
sbr.setErrorIndicatorPaint(this.errorIndicatorPaint);
}
// MinMaxCategoryRenderer
if (renderer instanceof MinMaxCategoryRenderer) {
MinMaxCategoryRenderer mmcr = (MinMaxCategoryRenderer) renderer;
mmcr.setGroupPaint(this.errorIndicatorPaint);
}
}
/**
* Applies the settings of this theme to the specified renderer.
*
* @param renderer the renderer (<code>null</code> not permitted).
*/
protected void applyToXYItemRenderer(XYItemRenderer renderer) {
if (renderer == null) {
throw new IllegalArgumentException("Null 'renderer' argument.");
}
if (renderer instanceof AbstractRenderer) {
applyToAbstractRenderer((AbstractRenderer) renderer);
}
renderer.setBaseItemLabelFont(this.regularFont);
renderer.setBaseItemLabelPaint(this.itemLabelPaint);
if (renderer instanceof XYBarRenderer) {
XYBarRenderer br = (XYBarRenderer) renderer;
br.setBarPainter(this.xyBarPainter);
br.setShadowVisible(this.shadowVisible);
}
}
/**
* Applies the settings of this theme to the specified annotation.
*
* @param annotation the annotation.
*/
protected void applyToXYAnnotation(XYAnnotation annotation) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
if (annotation instanceof XYTextAnnotation) {
XYTextAnnotation xyta = (XYTextAnnotation) annotation;
xyta.setFont(this.smallFont);
xyta.setPaint(this.itemLabelPaint);
}
}
/**
* Tests this theme for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StandardChartTheme)) {
return false;
}
StandardChartTheme that = (StandardChartTheme) obj;
if (!this.name.equals(that.name)) {
return false;
}
if (!this.extraLargeFont.equals(that.extraLargeFont)) {
return false;
}
if (!this.largeFont.equals(that.largeFont)) {
return false;
}
if (!this.regularFont.equals(that.regularFont)) {
return false;
}
if (!this.smallFont.equals(that.smallFont)) {
return false;
}
if (!PaintUtilities.equal(this.titlePaint, that.titlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.subtitlePaint, that.subtitlePaint)) {
return false;
}
if (!PaintUtilities.equal(this.chartBackgroundPaint,
that.chartBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendBackgroundPaint,
that.legendBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.legendItemPaint, that.legendItemPaint)) {
return false;
}
if (!this.drawingSupplier.equals(that.drawingSupplier)) {
return false;
}
if (!PaintUtilities.equal(this.plotBackgroundPaint,
that.plotBackgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.plotOutlinePaint,
that.plotOutlinePaint)) {
return false;
}
if (!this.labelLinkStyle.equals(that.labelLinkStyle)) {
return false;
}
if (!PaintUtilities.equal(this.labelLinkPaint, that.labelLinkPaint)) {
return false;
}
if (!PaintUtilities.equal(this.domainGridlinePaint,
that.domainGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.rangeGridlinePaint,
that.rangeGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.crosshairPaint, that.crosshairPaint)) {
return false;
}
if (!this.axisOffset.equals(that.axisOffset)) {
return false;
}
if (!PaintUtilities.equal(this.axisLabelPaint, that.axisLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.tickLabelPaint, that.tickLabelPaint)) {
return false;
}
if (!PaintUtilities.equal(this.itemLabelPaint, that.itemLabelPaint)) {
return false;
}
if (this.shadowVisible != that.shadowVisible) {
return false;
}
if (!PaintUtilities.equal(this.shadowPaint, that.shadowPaint)) {
return false;
}
if (!this.barPainter.equals(that.barPainter)) {
return false;
}
if (!this.xyBarPainter.equals(that.xyBarPainter)) {
return false;
}
if (!PaintUtilities.equal(this.thermometerPaint,
that.thermometerPaint)) {
return false;
}
if (!PaintUtilities.equal(this.wallPaint, that.wallPaint)) {
return false;
}
if (!PaintUtilities.equal(this.errorIndicatorPaint,
that.errorIndicatorPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandPaint, that.gridBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandAlternatePaint,
that.gridBandAlternatePaint)) {
return false;
}
return true;
}
/**
* Returns a clone of this theme.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the theme cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.titlePaint, stream);
SerialUtilities.writePaint(this.subtitlePaint, stream);
SerialUtilities.writePaint(this.chartBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendBackgroundPaint, stream);
SerialUtilities.writePaint(this.legendItemPaint, stream);
SerialUtilities.writePaint(this.plotBackgroundPaint, stream);
SerialUtilities.writePaint(this.plotOutlinePaint, stream);
SerialUtilities.writePaint(this.labelLinkPaint, stream);
SerialUtilities.writePaint(this.baselinePaint, stream);
SerialUtilities.writePaint(this.domainGridlinePaint, stream);
SerialUtilities.writePaint(this.rangeGridlinePaint, stream);
SerialUtilities.writePaint(this.crosshairPaint, stream);
SerialUtilities.writePaint(this.axisLabelPaint, stream);
SerialUtilities.writePaint(this.tickLabelPaint, stream);
SerialUtilities.writePaint(this.itemLabelPaint, stream);
SerialUtilities.writePaint(this.shadowPaint, stream);
SerialUtilities.writePaint(this.thermometerPaint, stream);
SerialUtilities.writePaint(this.wallPaint, stream);
SerialUtilities.writePaint(this.errorIndicatorPaint, stream);
SerialUtilities.writePaint(this.gridBandPaint, stream);
SerialUtilities.writePaint(this.gridBandAlternatePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream (<code>null</code> not permitted).
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.titlePaint = SerialUtilities.readPaint(stream);
this.subtitlePaint = SerialUtilities.readPaint(stream);
this.chartBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendBackgroundPaint = SerialUtilities.readPaint(stream);
this.legendItemPaint = SerialUtilities.readPaint(stream);
this.plotBackgroundPaint = SerialUtilities.readPaint(stream);
this.plotOutlinePaint = SerialUtilities.readPaint(stream);
this.labelLinkPaint = SerialUtilities.readPaint(stream);
this.baselinePaint = SerialUtilities.readPaint(stream);
this.domainGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeGridlinePaint = SerialUtilities.readPaint(stream);
this.crosshairPaint = SerialUtilities.readPaint(stream);
this.axisLabelPaint = SerialUtilities.readPaint(stream);
this.tickLabelPaint = SerialUtilities.readPaint(stream);
this.itemLabelPaint = SerialUtilities.readPaint(stream);
this.shadowPaint = SerialUtilities.readPaint(stream);
this.thermometerPaint = SerialUtilities.readPaint(stream);
this.wallPaint = SerialUtilities.readPaint(stream);
this.errorIndicatorPaint = SerialUtilities.readPaint(stream);
this.gridBandPaint = SerialUtilities.readPaint(stream);
this.gridBandAlternatePaint = SerialUtilities.readPaint(stream);
}
}
|
package org.jfree.chart.text;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.text.AttributedString;
import java.text.BreakIterator;
import org.jfree.chart.util.ObjectUtilities;
/**
* Some utility methods for working with text.
*/
public class TextUtilities {
/**
* A flag that controls whether or not the rotated string workaround is
* used.
*/
private static boolean useDrawRotatedStringWorkaround;
/**
* A flag that controls whether the FontMetrics.getStringBounds() method
* is used or a workaround is applied.
*/
private static boolean useFontMetricsGetStringBounds;
static {
boolean isJava14 = ObjectUtilities.isJDK14();
useDrawRotatedStringWorkaround = (isJava14 == false);
useFontMetricsGetStringBounds = (isJava14 == true);
}
/**
* Private constructor prevents object creation.
*/
private TextUtilities() {
}
/**
* Creates a {@link TextBlock} from a <code>String</code>. Line breaks
* are added where the <code>String</code> contains '\n' characters.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint) {
if (text == null) {
throw new IllegalArgumentException("Null 'text' argument.");
}
TextBlock result = new TextBlock();
String input = text;
boolean moreInputToProcess = (text.length() > 0);
int start = 0;
while (moreInputToProcess) {
int index = input.indexOf("\n");
if (index > start) {
String line = input.substring(start, index);
if (index < input.length() - 1) {
result.addLine(line, font, paint);
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else if (index == start) {
if (index < input.length() - 1) {
input = input.substring(index + 1);
}
else {
moreInputToProcess = false;
}
}
else {
result.addLine(input, font, paint);
moreInputToProcess = false;
}
}
return result;
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the <code>maxWidth</code> value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, TextMeasurer measurer) {
return createTextBlock(text, font, paint, maxWidth, Integer.MAX_VALUE,
measurer);
}
/**
* Creates a new text block from the given string, breaking the
* text into lines so that the <code>maxWidth</code> value is
* respected.
*
* @param text the text.
* @param font the font.
* @param paint the paint.
* @param maxWidth the maximum width for each line.
* @param maxLines the maximum number of lines.
* @param measurer the text measurer.
*
* @return A text block.
*/
public static TextBlock createTextBlock(String text, Font font,
Paint paint, float maxWidth, int maxLines, TextMeasurer measurer) {
TextBlock result = new TextBlock();
BreakIterator iterator = BreakIterator.getLineInstance();
iterator.setText(text);
int current = 0;
int lines = 0;
int length = text.length();
while (current < length && lines < maxLines) {
int next = nextLineBreak(text, current, maxWidth, iterator,
measurer);
if (next == BreakIterator.DONE) {
result.addLine(text.substring(current), font, paint);
return result;
}
result.addLine(text.substring(current, next), font, paint);
lines++;
current = next;
while (current < text.length()&& text.charAt(current) == '\n') {
current++;
}
}
if (current < length) {
TextLine lastLine = result.getLastLine();
TextFragment lastFragment = lastLine.getLastTextFragment();
String oldStr = lastFragment.getText();
String newStr = "...";
if (oldStr.length() > 3) {
newStr = oldStr.substring(0, oldStr.length() - 3) + "...";
}
lastLine.removeFragment(lastFragment);
TextFragment newFragment = new TextFragment(newStr,
lastFragment.getFont(), lastFragment.getPaint());
lastLine.addFragment(newFragment);
}
return result;
}
/**
* Returns the character index of the next line break.
*
* @param text the text.
* @param start the start index.
* @param width the target display width.
* @param iterator the word break iterator.
* @param measurer the text measurer.
*
* @return The index of the next line break.
*/
private static int nextLineBreak(String text, int start,
float width, BreakIterator iterator, TextMeasurer measurer) {
// this method is (loosely) based on code in JFreeReport's
// TextParagraph class
int current = start;
int end;
float x = 0.0f;
boolean firstWord = true;
int newline = text.indexOf('\n', start);
if (newline < 0) {
newline = Integer.MAX_VALUE;
}
while (((end = iterator.next()) != BreakIterator.DONE)) {
x += measurer.getStringWidth(text, current, end);
if (x > width) {
if (firstWord) {
while (measurer.getStringWidth(text, start, end) > width) {
end
if (end <= start) {
return end;
}
}
return end;
}
else {
end = iterator.previous();
return end;
}
}
else {
if (end > newline) {
return newline;
}
}
// we found at least one word that fits ...
firstWord = false;
current = end;
}
return BreakIterator.DONE;
}
/**
* Returns the bounds for the specified text.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics context (not <code>null</code>).
* @param fm the font metrics (not <code>null</code>).
*
* @return The text bounds (<code>null</code> if the <code>text</code>
* argument is <code>null</code>).
*/
public static Rectangle2D getTextBounds(String text, Graphics2D g2,
FontMetrics fm) {
final Rectangle2D bounds;
if (TextUtilities.useFontMetricsGetStringBounds) {
bounds = fm.getStringBounds(text, g2);
// getStringBounds() can return incorrect height for some Unicode
// characters...see bug parade 6183356, let's replace it with
// something correct
LineMetrics lm = fm.getFont().getLineMetrics(text,
g2.getFontRenderContext());
bounds.setRect(bounds.getX(), bounds.getY(), bounds.getWidth(),
lm.getHeight());
}
else {
double width = fm.stringWidth(text);
double height = fm.getHeight();
bounds = new Rectangle2D.Double(0.0, -fm.getAscent(), width,
height);
}
return bounds;
}
/**
* Draws a string such that the specified anchor point is aligned to the
* given (x, y) location.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x coordinate (Java 2D).
* @param y the y coordinate (Java 2D).
* @param anchor the anchor location.
*
* @return The text bounds (adjusted for the text position).
*/
public static Rectangle2D drawAlignedString(String text,
Graphics2D g2, float x, float y, TextAnchor anchor) {
Rectangle2D textBounds = new Rectangle2D.Double();
float[] adjust = deriveTextBoundsAnchorOffsets(g2, text, anchor,
textBounds);
// adjust text bounds to match string position
textBounds.setRect(x + adjust[0], y + adjust[1] + adjust[2],
textBounds.getWidth(), textBounds.getHeight());
g2.drawString(text, x + adjust[0], y + adjust[1]);
return textBounds;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not <code>null</code>).
* @param text the text.
* @param anchor the anchor point.
* @param textBounds the text bounds (if not <code>null</code>, this
* object will be updated by this method to match the
* string bounds).
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor, Rectangle2D textBounds) {
float[] result = new float[3];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
result[2] = -ascent;
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor == TextAnchor.TOP_CENTER
|| anchor == TextAnchor.CENTER
|| anchor == TextAnchor.BOTTOM_CENTER
|| anchor == TextAnchor.BASELINE_CENTER
|| anchor == TextAnchor.HALF_ASCENT_CENTER) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor == TextAnchor.TOP_RIGHT
|| anchor == TextAnchor.CENTER_RIGHT
|| anchor == TextAnchor.BOTTOM_RIGHT
|| anchor == TextAnchor.BASELINE_RIGHT
|| anchor == TextAnchor.HALF_ASCENT_RIGHT) {
xAdj = (float) -bounds.getWidth();
}
if (anchor == TextAnchor.TOP_LEFT
|| anchor == TextAnchor.TOP_CENTER
|| anchor == TextAnchor.TOP_RIGHT) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor == TextAnchor.HALF_ASCENT_LEFT
|| anchor == TextAnchor.HALF_ASCENT_CENTER
|| anchor == TextAnchor.HALF_ASCENT_RIGHT) {
yAdj = halfAscent;
}
else if (anchor == TextAnchor.CENTER_LEFT
|| anchor == TextAnchor.CENTER
|| anchor == TextAnchor.CENTER_RIGHT) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor == TextAnchor.BASELINE_LEFT
|| anchor == TextAnchor.BASELINE_CENTER
|| anchor == TextAnchor.BASELINE_RIGHT) {
yAdj = 0.0f;
}
else if (anchor == TextAnchor.BOTTOM_LEFT
|| anchor == TextAnchor.BOTTOM_CENTER
|| anchor == TextAnchor.BOTTOM_RIGHT) {
yAdj = -metrics.getDescent() - metrics.getLeading();
}
if (textBounds != null) {
textBounds.setRect(bounds);
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Sets the flag that controls whether or not a workaround is used for
* drawing rotated strings. The related bug is on Sun's bug parade
* (id 4312117) and the workaround involves using a <code>TextLayout</code>
* instance to draw the text instead of calling the
* <code>drawString()</code> method in the <code>Graphics2D</code> class.
*
* @param use the new flag value.
*/
public static void setUseDrawRotatedStringWorkaround(boolean use) {
useDrawRotatedStringWorkaround = use;
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param angle the angle of the (clockwise) rotation (in radians).
* @param x the x-coordinate.
* @param y the y-coordinate.
*/
public static void drawRotatedString(String text, Graphics2D g2,
double angle, float x, float y) {
drawRotatedString(text, g2, x, y, angle, x, y);
}
/**
* A utility method for drawing rotated text.
* <P>
* A common rotation is -Math.PI/2 which draws text 'vertically' (with the
* top of the characters on the left).
*
* @param text the text.
* @param g2 the graphics device.
* @param textX the x-coordinate for the text (before rotation).
* @param textY the y-coordinate for the text (before rotation).
* @param angle the angle of the (clockwise) rotation (in radians).
* @param rotateX the point about which the text is rotated.
* @param rotateY the point about which the text is rotated.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float textX, float textY, double angle,
float rotateX, float rotateY) {
if ((text == null) || (text.equals(""))) {
return;
}
AffineTransform saved = g2.getTransform();
// apply the rotation...
AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY);
g2.transform(rotate);
if (useDrawRotatedStringWorkaround) {
// workaround for JDC bug ID 4312117 and others...
TextLayout tl = new TextLayout(text, g2.getFont(),
g2.getFontRenderContext());
tl.draw(g2, textX, textY);
}
else {
AttributedString as = new AttributedString(text,
g2.getFont().getAttributes());
g2.drawString(as.getIterator(), textX, textY);
}
g2.setTransform(saved);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle.
* @param rotationX the x-coordinate for the rotation anchor point.
* @param rotationY the y-coordinate for the rotation anchor point.
*/
public static void drawRotatedString(String text, Graphics2D g2, float x,
float y, TextAnchor textAnchor, double angle, float rotationX,
float rotationY) {
if (text == null || text.equals("")) {
return;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1], angle,
rotationX, rotationY);
}
/**
* Draws a string that is aligned by one anchor point and rotated about
* another anchor point.
*
* @param text the text.
* @param g2 the graphics device.
* @param x the x-coordinate for positioning the text.
* @param y the y-coordinate for positioning the text.
* @param textAnchor the text anchor.
* @param angle the rotation angle (in radians).
* @param rotationAnchor the rotation anchor.
*/
public static void drawRotatedString(String text, Graphics2D g2,
float x, float y, TextAnchor textAnchor,
double angle, TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
drawRotatedString(text, g2, x + textAdj[0], y + textAdj[1],
angle, x + textAdj[0] + rotateAdj[0],
y + textAdj[1] + rotateAdj[1]);
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics device.
* @param x the x coordinate for the anchor point.
* @param y the y coordinate for the anchor point.
* @param textAnchor the text anchor.
* @param angle the angle.
* @param rotationAnchor the rotation anchor.
*
* @return The bounds (possibly <code>null</code>).
*/
public static Shape calculateRotatedStringBounds(String text,
Graphics2D g2, float x, float y,
TextAnchor textAnchor, double angle,
TextAnchor rotationAnchor) {
if (text == null || text.equals("")) {
return null;
}
float[] textAdj = deriveTextBoundsAnchorOffsets(g2, text, textAnchor);
float[] rotateAdj = deriveRotationAnchorOffsets(g2, text,
rotationAnchor);
Shape result = calculateRotatedStringBounds(text, g2,
x + textAdj[0], y + textAdj[1], angle,
x + textAdj[0] + rotateAdj[0], y + textAdj[1] + rotateAdj[1]);
return result;
}
/**
* A utility method that calculates the anchor offsets for a string.
* Normally, the (x, y) coordinate for drawing text is a point on the
* baseline at the left of the text string. If you add these offsets to
* (x, y) and draw the string, then the anchor point should coincide with
* the (x, y) point.
*
* @param g2 the graphics device (not <code>null</code>).
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveTextBoundsAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
Font f = g2.getFont();
FontMetrics fm = g2.getFontMetrics(f);
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
LineMetrics metrics = f.getLineMetrics(text, frc);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor == TextAnchor.TOP_CENTER
|| anchor == TextAnchor.CENTER
|| anchor == TextAnchor.BOTTOM_CENTER
|| anchor == TextAnchor.BASELINE_CENTER
|| anchor == TextAnchor.HALF_ASCENT_CENTER) {
xAdj = (float) -bounds.getWidth() / 2.0f;
}
else if (anchor == TextAnchor.TOP_RIGHT
|| anchor == TextAnchor.CENTER_RIGHT
|| anchor == TextAnchor.BOTTOM_RIGHT
|| anchor == TextAnchor.BASELINE_RIGHT
|| anchor == TextAnchor.HALF_ASCENT_RIGHT) {
xAdj = (float) -bounds.getWidth();
}
if (anchor == TextAnchor.TOP_LEFT
|| anchor == TextAnchor.TOP_CENTER
|| anchor == TextAnchor.TOP_RIGHT) {
yAdj = -descent - leading + (float) bounds.getHeight();
}
else if (anchor == TextAnchor.HALF_ASCENT_LEFT
|| anchor == TextAnchor.HALF_ASCENT_CENTER
|| anchor == TextAnchor.HALF_ASCENT_RIGHT) {
yAdj = halfAscent;
}
else if (anchor == TextAnchor.CENTER_LEFT
|| anchor == TextAnchor.CENTER
|| anchor == TextAnchor.CENTER_RIGHT) {
yAdj = -descent - leading + (float) (bounds.getHeight() / 2.0);
}
else if (anchor == TextAnchor.BASELINE_LEFT
|| anchor == TextAnchor.BASELINE_CENTER
|| anchor == TextAnchor.BASELINE_RIGHT) {
yAdj = 0.0f;
}
else if (anchor == TextAnchor.BOTTOM_LEFT
|| anchor == TextAnchor.BOTTOM_CENTER
|| anchor == TextAnchor.BOTTOM_RIGHT) {
yAdj = -metrics.getDescent() - metrics.getLeading();
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* A utility method that calculates the rotation anchor offsets for a
* string. These offsets are relative to the text starting coordinate
* (BASELINE_LEFT).
*
* @param g2 the graphics device.
* @param text the text.
* @param anchor the anchor point.
*
* @return The offsets.
*/
private static float[] deriveRotationAnchorOffsets(Graphics2D g2,
String text, TextAnchor anchor) {
float[] result = new float[2];
FontRenderContext frc = g2.getFontRenderContext();
LineMetrics metrics = g2.getFont().getLineMetrics(text, frc);
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
float ascent = metrics.getAscent();
float halfAscent = ascent / 2.0f;
float descent = metrics.getDescent();
float leading = metrics.getLeading();
float xAdj = 0.0f;
float yAdj = 0.0f;
if (anchor == TextAnchor.TOP_LEFT
|| anchor == TextAnchor.CENTER_LEFT
|| anchor == TextAnchor.BOTTOM_LEFT
|| anchor == TextAnchor.BASELINE_LEFT
|| anchor == TextAnchor.HALF_ASCENT_LEFT) {
xAdj = 0.0f;
}
else if (anchor == TextAnchor.TOP_CENTER
|| anchor == TextAnchor.CENTER
|| anchor == TextAnchor.BOTTOM_CENTER
|| anchor == TextAnchor.BASELINE_CENTER
|| anchor == TextAnchor.HALF_ASCENT_CENTER) {
xAdj = (float) bounds.getWidth() / 2.0f;
}
else if (anchor == TextAnchor.TOP_RIGHT
|| anchor == TextAnchor.CENTER_RIGHT
|| anchor == TextAnchor.BOTTOM_RIGHT
|| anchor == TextAnchor.BASELINE_RIGHT
|| anchor == TextAnchor.HALF_ASCENT_RIGHT) {
xAdj = (float) bounds.getWidth();
}
if (anchor == TextAnchor.TOP_LEFT
|| anchor == TextAnchor.TOP_CENTER
|| anchor == TextAnchor.TOP_RIGHT) {
yAdj = descent + leading - (float) bounds.getHeight();
}
else if (anchor == TextAnchor.CENTER_LEFT
|| anchor == TextAnchor.CENTER
|| anchor == TextAnchor.CENTER_RIGHT) {
yAdj = descent + leading - (float) (bounds.getHeight() / 2.0);
}
else if (anchor == TextAnchor.HALF_ASCENT_LEFT
|| anchor == TextAnchor.HALF_ASCENT_CENTER
|| anchor == TextAnchor.HALF_ASCENT_RIGHT) {
yAdj = -halfAscent;
}
else if (anchor == TextAnchor.BASELINE_LEFT
|| anchor == TextAnchor.BASELINE_CENTER
|| anchor == TextAnchor.BASELINE_RIGHT) {
yAdj = 0.0f;
}
else if (anchor == TextAnchor.BOTTOM_LEFT
|| anchor == TextAnchor.BOTTOM_CENTER
|| anchor == TextAnchor.BOTTOM_RIGHT) {
yAdj = metrics.getDescent() + metrics.getLeading();
}
result[0] = xAdj;
result[1] = yAdj;
return result;
}
/**
* Returns a shape that represents the bounds of the string after the
* specified rotation has been applied.
*
* @param text the text (<code>null</code> permitted).
* @param g2 the graphics device.
* @param textX the x coordinate for the text.
* @param textY the y coordinate for the text.
* @param angle the angle.
* @param rotateX the x coordinate for the rotation point.
* @param rotateY the y coordinate for the rotation point.
*
* @return The bounds (<code>null</code> if <code>text</code> is
* </code>null</code> or has zero length).
*/
public static Shape calculateRotatedStringBounds(String text,
Graphics2D g2, float textX, float textY,
double angle, float rotateX, float rotateY) {
if ((text == null) || (text.equals(""))) {
return null;
}
FontMetrics fm = g2.getFontMetrics();
Rectangle2D bounds = TextUtilities.getTextBounds(text, g2, fm);
AffineTransform translate = AffineTransform.getTranslateInstance(
textX, textY);
Shape translatedBounds = translate.createTransformedShape(bounds);
AffineTransform rotate = AffineTransform.getRotateInstance(
angle, rotateX, rotateY);
Shape result = rotate.createTransformedShape(translatedBounds);
return result;
}
/**
* Returns the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @return A boolean.
*/
public static boolean getUseFontMetricsGetStringBounds() {
return useFontMetricsGetStringBounds;
}
/**
* Sets the flag that controls whether the FontMetrics.getStringBounds()
* method is used or not. If you are having trouble with label alignment
* or positioning, try changing the value of this flag.
*
* @param use the flag.
*/
public static void setUseFontMetricsGetStringBounds(final boolean use) {
useFontMetricsGetStringBounds = use;
}
/**
* Returns the current value of the
* <code>useDrawRotatedStringWorkaround</code> flag.
*
* @return A boolean.
*/
public static boolean isUseDrawRotatedStringWorkaround() {
return useDrawRotatedStringWorkaround;
}
}
|
package dk.aau.sw402F15.Compiler;
import dk.aau.sw402F15.Rewriter.ASTSimplify;
import dk.aau.sw402F15.CodeGenerator.CodeGenerator;
import dk.aau.sw402F15.Exception.CompilerArgument.InvalidArgumentException;
import dk.aau.sw402F15.Exception.CompilerArgument.MissingArgumentException;
import dk.aau.sw402F15.Exception.CompilerException;
import dk.aau.sw402F15.Exception.RuntimeCompilerException;
import dk.aau.sw402F15.FunctionChecker.FunctionChecker;
import dk.aau.sw402F15.Preprocessor.Preprocessor;
import dk.aau.sw402F15.PrettyPrinter;
import dk.aau.sw402F15.ScopeChecker.ScopeChecker;
import dk.aau.sw402F15.TypeChecker.TypeChecker;
import dk.aau.sw402F15.parser.lexer.Lexer;
import dk.aau.sw402F15.parser.lexer.LexerException;
import dk.aau.sw402F15.parser.node.Start;
import dk.aau.sw402F15.parser.parser.Parser;
import dk.aau.sw402F15.parser.parser.ParserException;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Compiler {
public void compile(String args[]) {
// Init compilerArgs
CompilerArgs compilerArgs;
try {
compilerArgs = new CompilerArgs(args);
}
catch (RuntimeCompilerException e) {
e.printError("");
return;
}
try {
compile(compilerArgs);
} catch (FileNotFoundException e) {
System.err.println("Error: File was not found");
} catch (ParserException e) {
e.printStackTrace();
} catch (LexerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (CompilerException e) {
// Flush stdout
System.out.flush();
if (compilerArgs.verbose()) e.printStackTrace();
try {
e.printError(getCode(compilerArgs));
} catch (FileNotFoundException e1) {
// Should not happen because we read file in compile method - this method is only occuring when an error in the compile method has occured.
e1.printStackTrace();
}
}
}
private void compile(CompilerArgs compilerArgs) throws IOException, LexerException, CompilerException, ParserException {
compile(getReader(compilerArgs), compilerArgs);
}
private void compile(Reader reader, CompilerArgs compilerArgs) throws LexerException, CompilerException, ParserException, IOException {
compile(reader, compilerArgs.prettyPrint(), compilerArgs.verbose());
}
private void compile(Reader reader, boolean prettyPrint, boolean verbose) throws ParserException, IOException, LexerException, CompilerException {
try {
// Save starttime
long startTime = System.nanoTime();
// Parse tree
if (verbose) System.out.println("Parsing code");
// Init lexer
PushbackReader pushbackReader = new PushbackReader(reader, 1024);
Lexer lexer = verbose ? new PrintLexer(pushbackReader) : new Lexer(pushbackReader);
// Init parser
Parser parser = new Parser(lexer);
Start tree = parser.parse();
// Running pretty print
if (prettyPrint) {
if (verbose) System.out.println("Running prettyprinter before transformations");
tree.apply(new PrettyPrinter());
}
// Simplifying the AST for easier codegen
if (verbose) System.out.println("Simplifying AST");
tree.apply(new ASTSimplify());
// Apply preprocessor
if (verbose) System.out.println("Running preprocessor");
Preprocessor preprocessor = new Preprocessor();
tree.apply(preprocessor);
// Check if run and init function exists
if (verbose) System.out.println("Checking init and run functions");
FunctionChecker.checkFunctions(preprocessor.getScope());
// Apply scopechecker
if (verbose) System.out.println("Running scopechecker");
ScopeChecker checker = new ScopeChecker(preprocessor.getScope());
tree.apply(checker);
// Applying typechecker
if (verbose) System.out.println("Running typechecker");
TypeChecker typeChecker = new TypeChecker(checker.getSymbolTable());
tree.apply(typeChecker);
// Print tree
if (prettyPrint) {
if (verbose) System.out.println("Running prettyprinter");
tree.apply(new PrettyPrinter());
}
// Apply codegenerator
if (verbose) System.out.println("Running codegenerator");
tree.apply(new CodeGenerator(typeChecker.getScope()));
// Print output for total time taken
long endTime = System.nanoTime() - startTime;
System.out.println("Compilation done");
System.out.print("Took: ");
if (endTime / (1000 * 1000) < 1000) {
System.out.println(((System.nanoTime() - startTime) / (1000 * 1000)) + "ms");
} else {
System.out.println(((System.nanoTime() - startTime) / (1000 * 1000 * 1000)) + "s");
}
} catch (RuntimeCompilerException e) {
throw new CompilerException(e);
}
}
private String getCode(CompilerArgs compilerArgs) throws FileNotFoundException {
String file = "";
for (String f : compilerArgs.file()) {
FileReader fr = new FileReader(f);
Scanner scanner = new Scanner(fr);
while (scanner.hasNext())
{
file += scanner.nextLine() + "\n";
}
}
return file;
}
private Reader getReader(CompilerArgs compilerArgs) throws FileNotFoundException {
String file = getCode(compilerArgs);
if (compilerArgs.verbose()) System.out.println(file);
return new StringReader(file);
}
private class CompilerArgs {
private boolean mPrettyPrint = false;
private boolean mVerbose;
private boolean mStd;
private List<String> mFiles;
public CompilerArgs(String[] args) {
this.mFiles = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
if (args[i].equals("--ast")) {
this.mPrettyPrint = true;
} else if (args[i].equals("--verbose")) {
this.mVerbose = true;
} else if (args[i].equals("--std")) {
this.mStd = true;
} else if (args[i].equals("-file")) {
this.mFiles.add(args[++i]);
} else {
// Check if file exists
File file = new File(args[i]);
if (file.exists() && !file.isDirectory()) {
mFiles.add(args[i]);
} else {
throw new InvalidArgumentException(args[i]);
}
}
}
if (this.mFiles.size() == 0) {
throw new MissingArgumentException("File is missing");
}
// Add stdlib
if (std()) {
this.mFiles.add(0, "stdlib.ppp");
}
}
public boolean prettyPrint() {
return mPrettyPrint;
}
public boolean verbose() {
return mVerbose;
}
public boolean std() { return mStd; }
public List<String> file() {
return mFiles;
}
}
}
|
package tools.concurrency;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import javax.management.openmbean.CompositeData;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.sun.management.GarbageCollectionNotificationInfo;
import som.VM;
import som.interpreter.actors.Actor;
import som.interpreter.actors.EventualMessage;
import som.interpreter.actors.EventualMessage.PromiseMessage;
import som.interpreter.actors.SFarReference;
import som.interpreter.actors.SPromise;
import som.interpreter.actors.SPromise.SResolver;
import som.primitives.TimerPrim;
import som.primitives.processes.ChannelPrimitives.TracingProcess;
import som.vm.ObjectSystem;
import som.vm.VmSettings;
import som.vmobjects.SAbstractObject;
import som.vmobjects.SClass;
import som.vmobjects.SSymbol;
import tools.ObjectBuffer;
import tools.TraceData;
import tools.debugger.FrontendConnector;
public class ActorExecutionTrace {
static final int BUFFER_SIZE = 4096 * 1024;
private static final int BUFFER_POOL_SIZE = VmSettings.NUM_THREADS * 4;
private static final int MESSAGE_SIZE = 44; // max message size without parameters
private static final int PARAM_SIZE = 9; // max size for one parameter
private static final int TRACE_TIMEOUT = 500;
private static final int POLL_TIMEOUT = 10;
private static final List<java.lang.management.GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
private static final ArrayBlockingQueue<ByteBuffer> emptyBuffers = new ArrayBlockingQueue<ByteBuffer>(BUFFER_POOL_SIZE);
private static final ArrayBlockingQueue<ByteBuffer> fullBuffers = new ArrayBlockingQueue<ByteBuffer>(BUFFER_POOL_SIZE);
// contains symbols that need to be written to file/sent to debugger,
// e.g. actor type, message type
private static final ArrayList<SSymbol> symbolsToWrite = new ArrayList<>();
private static FrontendConnector front = null;
private static long collectedMemory = 0;
private static TraceWorkerThread workerThread = new TraceWorkerThread();
private static final byte messageEventId;
static {
if (VmSettings.MEMORY_TRACING) {
setUpGCMonitoring();
}
if (VmSettings.ACTOR_TRACING) {
for (int i = 0; i < BUFFER_POOL_SIZE; i++) {
emptyBuffers.add(ByteBuffer.allocate(BUFFER_SIZE));
}
}
byte eventid = TraceData.MESSAGE_BASE;
if (VmSettings.MESSAGE_TIMESTAMPS) {
eventid |= TraceData.TIMESTAMP_BIT;
}
if (VmSettings.MESSAGE_PARAMETERS) {
eventid |= TraceData.PARAMETER_BIT;
}
messageEventId = eventid;
}
private static long getTotal(final Map<String, MemoryUsage> map) {
return map.entrySet().stream().
mapToLong(usage -> usage.getValue().getUsed()).sum();
}
public static void setUpGCMonitoring() {
for (java.lang.management.GarbageCollectorMXBean bean : gcbeans) {
NotificationEmitter emitter = (NotificationEmitter) bean;
NotificationListener listener = new NotificationListener() {
@Override
public void handleNotification(final Notification notification, final Object handback) {
if (GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) {
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(
(CompositeData) notification.getUserData());
long after = getTotal(info.getGcInfo().getMemoryUsageAfterGc());
long before = getTotal(info.getGcInfo().getMemoryUsageBeforeGc());
collectedMemory += before - after;
}
}
};
emitter.addNotificationListener(listener, null, null);
}
}
public static void reportPeakMemoryUsage() {
List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
long totalHeap = 0;
long totalNonHeap = 0;
long gcTime = 0;
for (MemoryPoolMXBean memoryPoolMXBean : pools) {
long peakUsed = memoryPoolMXBean.getPeakUsage().getUsed();
if (memoryPoolMXBean.getType() == MemoryType.HEAP) {
totalHeap += peakUsed;
} else if (memoryPoolMXBean.getType() == MemoryType.NON_HEAP) {
totalNonHeap += peakUsed;
}
}
for (GarbageCollectorMXBean garbageCollectorMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
gcTime += garbageCollectorMXBean.getCollectionTime();
}
VM.println("[Memstat] Heap: " + totalHeap + "B\tNonHeap: " + totalNonHeap + "B\tCollected: " + collectedMemory + "B\tGC-Time: " + gcTime + "ms");
}
@TruffleBoundary
public static synchronized void swapBuffer(final TracingActivityThread t) throws IllegalStateException {
returnBuffer(t.getThreadLocalBuffer());
try {
t.setThreadLocalBuffer(emptyBuffers.take().put(Events.Thread.id).put((byte) t.getPoolIndex()).putLong(System.currentTimeMillis()));
} catch (InterruptedException e) {
throw new IllegalStateException("Failed to acquire a new Buffer!");
}
}
@TruffleBoundary
public static synchronized void returnBuffer(final ByteBuffer b) {
if (b == null) {
return;
}
b.limit(b.position());
b.rewind();
fullBuffers.add(b);
}
protected enum Events {
ActorCreation(TraceParser.ACTOR_CREATION, 19),
PromiseCreation(TraceParser.PROMISE_CREATION, 17),
PromiseResolution(TraceParser.PROMISE_RESOLUTION, 28),
PromiseChained(TraceParser.PROMISE_CHAINED, 17),
Mailbox(TraceParser.MAILBOX, 21),
// at the beginning of buffer, allows to track what was created/executed
// on which thread, really cheap solution, timestamp?
Thread(TraceParser.THREAD, 9),
// for memory events another buffer is needed
// (the gc callback is on Thread[Service Thread,9,system])
MailboxContd(TraceParser.MAILBOX_CONTD, 23),
BasicMessage(TraceParser.BASIC_MESSAGE, 7),
PromiseMessage(TraceParser.PROMISE_MESSAGE, 7),
ProcessCreation(TraceParser.PROCESS_CREATION, 19),
ProcessCompletion(TraceParser.PROCESS_COMPLETION, 9);
private final byte id;
private final int size;
Events(final byte id, final int size) {
this.id = id;
this.size = size;
}
};
protected enum ParamTypes {
False,
True,
Long,
Double,
Promise,
Resolver,
Object,
String;
byte id() {
return (byte) this.ordinal();
}
}
public static void recordMainActor(final Actor mainActor,
final ObjectSystem objectSystem) {
if (!VmSettings.ACTOR_TRACING) {
return;
}
// don't take buffer from queue, just get reference for briefly
// adding main actor info
ByteBuffer b = emptyBuffers.element();
b.put(Events.ActorCreation.id);
b.putLong(mainActor.getId()); // id of the created actor
b.putLong(0); // causal message
b.putShort(objectSystem.getPlatformClass().getName().getSymbolId());
// start worker thread for trace processing
workerThread.start();
}
public static void actorCreation(final SFarReference actor) {
if (!VmSettings.ACTOR_TRACING) {
return;
}
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.ActorCreation.size) {
swapBuffer(t);
}
final Object value = actor.getValue();
assert value instanceof SClass;
final SClass actorClass = (SClass) value;
ByteBuffer b = t.getThreadLocalBuffer();
assert b.order() == ByteOrder.BIG_ENDIAN;
b.put(Events.ActorCreation.id);
b.putLong(actor.getActor().getId()); // id of the created actor
b.putLong(t.getCurrentMessageId()); // causal message
b.putShort(actorClass.getName().getSymbolId());
}
public static void processCreation(final TracingProcess proc) {
assert VmSettings.ACTOR_TRACING;
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.ProcessCreation.size) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.ProcessCreation.id);
b.putLong(proc.getId());
b.putLong(t.getCurrentMessageId()); // causal message
b.putShort(proc.getProcObject().getSOMClass().getName().getSymbolId());
}
public static void processCompletion(final TracingProcess proc) {
assert VmSettings.ACTOR_TRACING;
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.ProcessCompletion.size) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.ProcessCompletion.id);
b.putLong(proc.getId());
}
public static void promiseCreation(final long promiseId) {
if (!VmSettings.ACTOR_TRACING) {
return;
}
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.PromiseCreation.size) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.PromiseCreation.id);
b.putLong(promiseId); // id of the created promise
b.putLong(t.getCurrentMessageId()); // causal message
}
public static void promiseResolution(final long promiseId, final Object value) {
if (!VmSettings.ACTOR_TRACING) {
return;
}
Thread current = Thread.currentThread();
if (TimerPrim.isTimerThread(current)) {
return;
}
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.PromiseResolution.size) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.PromiseResolution.id);
b.putLong(promiseId); // id of the promise
b.putLong(t.getCurrentMessageId()); // resolving message
writeParameter(value, b);
t.resolvedPromises++;
}
public static void promiseChained(final long parent, final long child) {
if (!VmSettings.ACTOR_TRACING) {
return;
}
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.PromiseChained.size) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.PromiseChained.id);
b.putLong(parent); // id of the parent
b.putLong(child); // id of the chained promise
t.resolvedPromises++;
}
public static void mailboxExecuted(final EventualMessage m,
final ObjectBuffer<EventualMessage> moreCurrent, final long baseMessageId, final int mailboxNo, final long sendTS,
final ObjectBuffer<Long> moreSendTS, final long[] execTS, final Actor actor) {
if (!VmSettings.ACTOR_TRACING) {
return;
}
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.Mailbox.size + 100 * 50) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.Mailbox.id);
b.putLong(baseMessageId); // base id for messages
b.putInt(mailboxNo);
b.putLong(actor.getId()); // receiver of the messages
int idx = 0;
if (b.remaining() < (MESSAGE_SIZE + m.getArgs().length * PARAM_SIZE)) {
swapBuffer(t);
b = t.getThreadLocalBuffer();
b.put(Events.MailboxContd.id);
b.putLong(baseMessageId);
b.putInt(mailboxNo);
b.putLong(actor.getId()); // receiver of the messages
b.putInt(idx);
}
writeBasicMessage(m, b);
if (VmSettings.MESSAGE_TIMESTAMPS) {
b.putLong(execTS[0]);
b.putLong(sendTS);
}
if (VmSettings.MESSAGE_PARAMETERS) {
writeParameters(m.getArgs(), b);
}
idx++;
if (moreCurrent != null) {
Iterator<Long> it = null;
if (VmSettings.MESSAGE_TIMESTAMPS) {
assert moreSendTS != null && moreCurrent.size() == moreSendTS.size();
it = moreSendTS.iterator();
}
for (EventualMessage em : moreCurrent) {
if (b.remaining() < (MESSAGE_SIZE + em.getArgs().length * PARAM_SIZE)) {
swapBuffer(t);
b = t.getThreadLocalBuffer();
b.put(Events.MailboxContd.id);
b.putLong(baseMessageId);
b.putInt(mailboxNo);
b.putLong(actor.getId()); // receiver of the messages
b.putInt(idx);
}
writeBasicMessage(em, b);
if (VmSettings.MESSAGE_TIMESTAMPS) {
b.putLong(execTS[idx]);
b.putLong(it.next());
}
if (VmSettings.MESSAGE_PARAMETERS) {
writeParameters(em.getArgs(), b);
}
idx++;
}
}
}
private static void writeBasicMessage(final EventualMessage em, final ByteBuffer b) {
if (em instanceof PromiseMessage && VmSettings.PROMISE_CREATION) {
b.put((byte) (messageEventId | TraceData.PROMISE_BIT));
b.putLong(((PromiseMessage) em).getPromise().getPromiseId());
} else {
b.put(messageEventId);
}
b.putLong(em.getSender().getId()); // sender
b.putLong(em.getCausalMessageId());
b.putShort(em.getSelector().getSymbolId());
}
private static void writeParameters(final Object[] params, final ByteBuffer b) {
b.put((byte) (params.length - 1)); // num paramaters
for (int i = 1; i < params.length; i++) {
// will need a 8 plus 1 byte for most parameter,
// boolean just use two identifiers.
if (params[i] instanceof SFarReference) {
Object o = ((SFarReference) params[i]).getValue();
writeParameter(o, b);
} else {
writeParameter(params[i], b);
}
}
}
private static void writeParameter(final Object param, final ByteBuffer b) {
if (param instanceof SPromise) {
b.put(ParamTypes.Promise.id());
b.putLong(((SPromise) param).getPromiseId());
} else if (param instanceof SResolver) {
b.put(ParamTypes.Resolver.id());
b.putLong(((SResolver) param).getPromise().getPromiseId());
} else if (param instanceof SAbstractObject) {
b.put(ParamTypes.Object.id());
b.putShort(((SAbstractObject) param).getSOMClass().getName().getSymbolId());
} else {
if (param instanceof Long) {
b.put(ParamTypes.Long.id());
b.putLong((Long) param);
} else if (param instanceof Double) {
b.put(ParamTypes.Double.id());
b.putDouble((Double) param);
} else if (param instanceof Boolean) {
if ((Boolean) param) {
b.put(ParamTypes.True.id());
} else {
b.put(ParamTypes.False.id());
}
} else if (param instanceof String) {
b.put(ParamTypes.String.id());
} else {
throw new RuntimeException("unexpected parameter type");
}
// TODO add case for null/nil/exception,
// ask ctorresl about what type is used for the error handling stuff
}
}
/**
* @param fc The FrontendConnector used to send data to the debugger.
*/
public static void setFrontEnd(final FrontendConnector fc) {
front = fc;
}
public static void logSymbol(final SSymbol symbol) {
synchronized (symbolsToWrite) {
symbolsToWrite.add(symbol);
}
}
public static void waitForTrace() {
workerThread.cont = false;
try {
workerThread.join(TRACE_TIMEOUT);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private static class TraceWorkerThread extends Thread {
protected boolean cont = true;
@Override
public void run() {
File f = new File(VmSettings.TRACE_FILE + ".trace");
File sf = new File(VmSettings.TRACE_FILE + ".sym");
f.getParentFile().mkdirs();
if (!VmSettings.DISABLE_TRACE_FILE) {
try (FileOutputStream fos = new FileOutputStream(f);
FileOutputStream sfos = new FileOutputStream(sf);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sfos))) {
while (cont || ActorExecutionTrace.fullBuffers.size() > 0) {
ByteBuffer b;
try {
b = ActorExecutionTrace.fullBuffers.poll(POLL_TIMEOUT, TimeUnit.MILLISECONDS);
if (b == null) {
continue;
}
} catch (InterruptedException e) {
continue;
}
synchronized (symbolsToWrite) {
if (front != null) {
front.sendSymbols(ActorExecutionTrace.symbolsToWrite);
}
for (SSymbol s : symbolsToWrite) {
bw.write(s.getSymbolId() + ":" + s.getString());
bw.newLine();
}
bw.flush();
ActorExecutionTrace.symbolsToWrite.clear();
}
fos.getChannel().write(b);
fos.flush();
b.rewind();
if (front != null) {
front.sendTracingData(b);
}
b.clear();
ActorExecutionTrace.emptyBuffers.add(b);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
while (cont || ActorExecutionTrace.fullBuffers.size() > 0) {
ByteBuffer b;
try {
b = ActorExecutionTrace.fullBuffers.poll(POLL_TIMEOUT, TimeUnit.MILLISECONDS);
if (b == null) {
continue;
}
} catch (InterruptedException e) {
continue;
}
synchronized (symbolsToWrite) {
if (front != null) {
front.sendSymbols(ActorExecutionTrace.symbolsToWrite);
}
ActorExecutionTrace.symbolsToWrite.clear();
}
if (front != null) {
front.sendTracingData(b);
}
b.clear();
ActorExecutionTrace.emptyBuffers.add(b);
}
}
}
}
public static void mailboxExecutedReplay(final Queue<EventualMessage> todo,
final long baseMessageId, final int mailboxNo, final Actor actor) {
Thread current = Thread.currentThread();
assert current instanceof TracingActivityThread;
TracingActivityThread t = (TracingActivityThread) current;
if (t.getThreadLocalBuffer().remaining() < Events.Mailbox.size + 100 * 50) {
swapBuffer(t);
}
ByteBuffer b = t.getThreadLocalBuffer();
b.put(Events.Mailbox.id);
b.putLong(baseMessageId); // base id for messages
b.putInt(mailboxNo);
b.putLong(actor.getId()); // receiver of the messages
int idx = 0;
if (todo != null) {
for (EventualMessage em : todo) {
if (b.remaining() < (MESSAGE_SIZE + em.getArgs().length * PARAM_SIZE)) {
swapBuffer(t);
b = t.getThreadLocalBuffer();
b.put(Events.MailboxContd.id);
b.putLong(baseMessageId);
b.putLong(actor.getId()); // receiver of the messages
b.putInt(idx);
}
writeBasicMessage(em, b);
if (VmSettings.MESSAGE_PARAMETERS) {
writeParameters(em.getArgs(), b);
}
idx++;
}
}
}
}
|
package com.dmdirc;
import com.dmdirc.commandparser.parsers.ServerCommandParser;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.parser.common.CallbackNotFoundException;
import com.dmdirc.parser.interfaces.Parser;
import com.dmdirc.parser.interfaces.callbacks.DataInListener;
import com.dmdirc.parser.interfaces.callbacks.DataOutListener;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.core.components.WindowComponent;
import com.dmdirc.ui.input.TabCompleter;
import java.util.Arrays;
import java.util.Date;
/**
* Handles the raw window (which shows the user raw data being sent and
* received to/from the server).
*/
public final class Raw extends WritableFrameContainer
implements DataInListener, DataOutListener {
/** The server object that's being monitored. */
private Server server;
/**
* Creates a new instance of Raw.
*
* @param newServer the server to monitor
*/
public Raw(final Server newServer) {
super("raw", "Raw", "(Raw log)", newServer.getConfigManager(),
new ServerCommandParser(newServer.getConfigManager()),
Arrays.asList(WindowComponent.TEXTAREA.getIdentifier(),
WindowComponent.INPUTFIELD.getIdentifier()));
this.server = newServer;
getCommandParser().setOwner(server);
WindowManager.getWindowManager().addWindow(server, this);
}
/**
* Registers the data callbacks for this raw window.
*/
public void registerCallbacks() {
try {
server.getParser().getCallbackManager().addCallback(DataInListener.class, this);
server.getParser().getCallbackManager().addCallback(DataOutListener.class, this);
} catch (CallbackNotFoundException ex) {
Logger.appError(ErrorLevel.HIGH, "Unable to register raw callbacks", ex);
}
}
/** {@inheritDoc} */
@Override
public void windowClosing() {
// 2: Remove any callbacks or listeners
if (server.getParser() != null) {
server.getParser().getCallbackManager().delAllCallback(this);
}
// 3: Trigger any actions neccessary
// 4: Trigger action for the window closing
// 5: Inform any parents that the window is closing
server.delRaw();
}
/** {@inheritDoc} */
@Override
public void windowClosed() {
// 7: Remove any references to the window and parents
server = null;
}
/** {@inheritDoc} */
@Override
public void onDataIn(final Parser parser, final Date date, final String data) {
addLine("rawIn", data);
}
/** {@inheritDoc} */
@Override
public void onDataOut(final Parser parser, final Date date, final String data,
final boolean fromParser) {
addLine("rawOut", data);
}
/** {@inheritDoc} */
@Override
public Server getServer() {
return server;
}
/** {@inheritDoc} */
@Override
public void sendLine(final String line) {
server.sendLine(line);
}
/** {@inheritDoc} */
@Override
public int getMaxLineLength() {
return server.getMaxLineLength();
}
/** {@inheritDoc} */
@Override
public TabCompleter getTabCompleter() {
return server.getTabCompleter();
}
}
|
package water.util;
import static water.util.RandomUtils.getRNG;
import water.*;
import water.H2O.H2OCallback;
import water.H2O.H2OCountedCompleter;
import water.fvec.*;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class MRUtils {
/**
* Sample rows from a frame.
* Can be unlucky for small sampling fractions - will continue calling itself until at least 1 row is returned.
* @param fr Input frame
* @param rows Approximate number of rows to sample (across all chunks)
* @param seed Seed for RNG
* @return Sampled frame
*/
public static Frame sampleFrame(Frame fr, final long rows, final long seed) {
if (fr == null) return null;
final float fraction = rows > 0 ? (float)rows / fr.numRows() : 1.f;
if (fraction >= 1.f) return fr;
Key newKey = fr._key != null ? Key.make(fr._key.toString() + (fr._key.toString().contains("temporary") ? ".sample." : ".temporary.sample.") + PrettyPrint.formatPct(fraction).replace(" ","")) : null;
Frame r = new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
final Random rng = getRNG(seed + cs[0].cidx());
int count = 0;
for (int r = 0; r < cs[0]._len; r++)
if (rng.nextFloat() < fraction || (count == 0 && r == cs[0]._len-1) ) {
count++;
for (int i = 0; i < ncs.length; i++) {
ncs[i].addNum(cs[i].atd(r));
}
}
}
}.doAll(fr.numCols(), fr).outputFrame(newKey, fr.names(), fr.domains());
if (r.numRows() == 0) {
Log.warn("You asked for " + rows + " rows (out of " + fr.numRows() + "), but you got none (seed=" + seed + ").");
Log.warn("Let's try again. You've gotta ask yourself a question: \"Do I feel lucky?\"");
return sampleFrame(fr, rows, seed+1);
}
return r;
}
/**
* Row-wise shuffle of a frame (only shuffles rows inside of each chunk)
* @param fr Input frame
* @return Shuffled frame
*/
public static Frame shuffleFramePerChunk(Frame fr, final long seed) {
return new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
long[] idx = new long[cs[0]._len];
for (int r=0; r<idx.length; ++r) idx[r] = r;
ArrayUtils.shuffleArray(idx, seed);
for (long anIdx : idx) {
for (int i = 0; i < ncs.length; i++) {
ncs[i].addNum(cs[i].atd((int) anIdx));
}
}
}
}.doAll(fr.numCols(), fr).outputFrame(fr.names(), fr.domains());
}
public static class ClassDist extends ClassDistHelper {
public ClassDist(final Vec label) { super(label.domain().length); }
public ClassDist(int n) { super(n); }
public final long[] dist() { return _ys; }
public final double[] rel_dist() {
double[] rel = new double[_ys.length];
for (int i=0; i<_ys.length; ++i) rel[i] = (float)_ys[i];
final double sum = ArrayUtils.sum(rel);
assert(sum != 0.);
ArrayUtils.div(rel, sum);
return rel;
}
}
private static class ClassDistHelper extends MRTask<ClassDist> {
private ClassDistHelper(int nclass) { _nclass = nclass; }
final int _nclass;
protected long[] _ys;
@Override public void map(Chunk ys) {
_ys = new long[_nclass];
for( int i=0; i<ys._len; i++ )
if( !ys.isNA(i) )
_ys[(int)ys.at8(i)]++;
}
@Override public void reduce( ClassDist that ) { ArrayUtils.add(_ys,that._ys); }
}
/**
* Stratified sampling for classifiers
* @param fr Input frame
* @param label Label vector (must be enum)
* @param sampling_ratios Optional: array containing the requested sampling ratios per class (in order of domains), will be overwritten if it contains all 0s
* @param maxrows Maximum number of rows in the returned frame
* @param seed RNG seed for sampling
* @param allowOversampling Allow oversampling of minority classes
* @param verbose Whether to print verbose info
* @return Sampled frame, with approximately the same number of samples from each class (or given by the requested sampling ratios)
*/
public static Frame sampleFrameStratified(final Frame fr, Vec label, float[] sampling_ratios, long maxrows, final long seed, final boolean allowOversampling, final boolean verbose) {
if (fr == null) return null;
assert(label.isEnum());
assert(maxrows >= label.domain().length);
long[] dist = new ClassDist(label).doAll(label).dist();
assert(dist.length > 0);
Log.info("Doing stratified sampling for data set containing " + fr.numRows() + " rows from " + dist.length + " classes. Oversampling: " + (allowOversampling ? "on" : "off"));
if (verbose)
for (int i=0; i<dist.length;++i)
Log.info("Class " + label.factor(i) + ": count: " + dist[i] + " prior: " + (float)dist[i]/fr.numRows());
// create sampling_ratios for class balance with max. maxrows rows (fill
// existing array if not null). Make a defensive copy.
sampling_ratios = sampling_ratios == null ? new float[dist.length] : sampling_ratios.clone();
assert sampling_ratios.length == dist.length;
if( ArrayUtils.minValue(sampling_ratios) == 0 && ArrayUtils.maxValue(sampling_ratios) == 0 ) {
// compute sampling ratios to achieve class balance
for (int i=0; i<dist.length;++i)
sampling_ratios[i] = ((float)fr.numRows() / label.domain().length) / dist[i]; // prior^-1 / num_classes
final float inv_scale = ArrayUtils.minValue(sampling_ratios); //majority class has lowest required oversampling factor to achieve balance
if (!Float.isNaN(inv_scale) && !Float.isInfinite(inv_scale))
ArrayUtils.div(sampling_ratios, inv_scale); //want sampling_ratio 1.0 for majority class (no downsampling)
}
if (!allowOversampling)
for (int i=0; i<sampling_ratios.length; ++i)
sampling_ratios[i] = Math.min(1.0f, sampling_ratios[i]);
// given these sampling ratios, and the original class distribution, this is the expected number of resulting rows
float numrows = 0;
for (int i=0; i<sampling_ratios.length; ++i)
numrows += sampling_ratios[i] * dist[i];
final long actualnumrows = Math.min(maxrows, Math.round(numrows)); //cap #rows at maxrows
assert(actualnumrows >= 0); //can have no matching rows in case of sparse data where we had to fill in a makeZero() vector
Log.info("Stratified sampling to a total of " + String.format("%,d", actualnumrows) + " rows" + (actualnumrows < numrows ? " (limited by max_after_balance_size).":"."));
if (actualnumrows != numrows) {
ArrayUtils.mult(sampling_ratios, (float)actualnumrows/numrows); //adjust the sampling_ratios by the global rescaling factor
if (verbose)
Log.info("Downsampling majority class by " + (float)actualnumrows/numrows
+ " to limit number of rows to " + String.format("%,d", maxrows));
}
for (int i=0;i<label.domain().length;++i) {
Log.info("Class '" + label.domain()[i] + "' sampling ratio: " + sampling_ratios[i]);
}
return sampleFrameStratified(fr, label, sampling_ratios, seed, verbose);
}
/**
* Stratified sampling
* @param fr Input frame
* @param label Label vector (from the input frame)
* @param sampling_ratios Given sampling ratios for each class, in order of domains
* @param seed RNG seed
* @param debug Whether to print debug info
* @return Stratified frame
*/
public static Frame sampleFrameStratified(final Frame fr, Vec label, final float[] sampling_ratios, final long seed, final boolean debug) {
return sampleFrameStratified(fr, label, sampling_ratios, seed, debug, 0);
}
// internal version with repeat counter
// currently hardcoded to do up to 10 tries to get a row from each class, which can be impossible for certain wrong sampling ratios
private static Frame sampleFrameStratified(final Frame fr, Vec label, final float[] sampling_ratios, final long seed, final boolean debug, int count) {
if (fr == null) return null;
assert(label.isEnum());
assert(sampling_ratios != null && sampling_ratios.length == label.domain().length);
final int labelidx = fr.find(label); //which column is the label?
assert(labelidx >= 0);
final boolean poisson = false; //beta feature
Frame r = new MRTask() {
@Override
public void map(Chunk[] cs, NewChunk[] ncs) {
final Random rng = getRNG(seed + cs[0].cidx());
for (int r = 0; r < cs[0]._len; r++) {
if (cs[labelidx].isNA(r)) continue; //skip missing labels
final int label = (int)cs[labelidx].at8(r);
assert(sampling_ratios.length > label && label >= 0);
int sampling_reps;
if (poisson) {
throw H2O.unimpl();
// sampling_reps = ArrayUtils.getPoisson(sampling_ratios[label], rng);
} else {
final float remainder = sampling_ratios[label] - (int)sampling_ratios[label];
sampling_reps = (int)sampling_ratios[label] + (rng.nextFloat() < remainder ? 1 : 0);
}
for (int i = 0; i < ncs.length; i++) {
for (int j = 0; j < sampling_reps; ++j) {
ncs[i].addNum(cs[i].atd(r));
}
}
}
}
}.doAll(fr.numCols(), fr).outputFrame(fr.names(), fr.domains());
// Confirm the validity of the distribution
long[] dist = new ClassDist(r.vecs()[labelidx]).doAll(r.vecs()[labelidx]).dist();
// if there are no training labels in the test set, then there is no point in sampling the test set
if (dist == null) return fr;
if (debug) {
long sumdist = ArrayUtils.sum(dist);
Log.info("After stratified sampling: " + sumdist + " rows.");
for (int i=0; i<dist.length;++i) {
Log.info("Class " + r.vecs()[labelidx].factor(i) + ": count: " + dist[i]
+ " sampling ratio: " + sampling_ratios[i] + " actual relative frequency: " + (float)dist[i] / sumdist * dist.length);
}
}
// Re-try if we didn't get at least one example from each class
if (ArrayUtils.minValue(dist) == 0 && count < 10) {
Log.info("Re-doing stratified sampling because not all classes were represented (unlucky draw).");
r.delete();
return sampleFrameStratified(fr, label, sampling_ratios, seed+1, debug, ++count);
}
// shuffle intra-chunk
Frame shuffled = shuffleFramePerChunk(r, seed+0x580FF13);
r.delete();
return shuffled;
}
public static class ParallelTasks<T extends DTask<T>> extends H2OCountedCompleter {
public transient final T [] _tasks;
transient final public int _maxP;
transient private AtomicInteger _nextTask;
public ParallelTasks(H2OCountedCompleter cmp, T[] tsks){
this(cmp,tsks,H2O.CLOUD.size());
}
public ParallelTasks(H2OCountedCompleter cmp, T[] tsks, int maxP){
super(cmp);
_maxP = maxP;
_tasks = tsks;
addToPendingCount(_tasks.length-1);
}
private void forkDTask(int i){
int nodeId = i%H2O.CLOUD.size();
forkDTask(i,H2O.CLOUD._memary[nodeId]);
}
private void forkDTask(final int i, H2ONode n){
if(n == H2O.SELF) {
_tasks[i].setCompleter(new Callback(H2O.SELF,i));
H2O.submitTask(_tasks[i]);
} else
new RPC(n,_tasks[i]).addCompleter(this).call();
}
class Callback extends H2OCallback<H2OCountedCompleter> {
final int i;
final H2ONode n;
public Callback(H2ONode n, int i){
super(ParallelTasks.this); this.n = n; this.i = i;
}
@Override public void callback(H2OCountedCompleter cc){
Log.info("callback for task " + i);
int nextI;
if((nextI = _nextTask.getAndIncrement()) < _tasks.length) // not done yet
forkDTask(nextI, n);
}
}
@Override public void compute2(){
final int n = Math.min(_maxP, _tasks.length);
_nextTask = new AtomicInteger(n);
for(int i = 0; i < n; ++i)
forkDTask(i);
}
}
}
|
package com.facebook.react.flat;
import java.util.ArrayList;
import javax.annotation.Nullable;
import com.facebook.react.uimanager.CatalystStylesDiffMap;
/**
* Shadow node hierarchy by itself cannot display UI, it is only a representation of what UI should
* be from JavaScript perspective. StateBuilder is a helper class that can walk the shadow node tree
* and collect information that can then be passed to UI thread and applied to a hierarchy of Views
* that Android finally can display.
*/
/* package */ final class StateBuilder {
private static final int[] EMPTY_INT_ARRAY = new int[0];
private final FlatUIViewOperationQueue mOperationsQueue;
private final ElementsList<DrawCommand> mDrawCommands =
new ElementsList<>(DrawCommand.EMPTY_ARRAY);
private final ElementsList<AttachDetachListener> mAttachDetachListeners =
new ElementsList<>(AttachDetachListener.EMPTY_ARRAY);
private final ElementsList<NodeRegion> mNodeRegions =
new ElementsList<>(NodeRegion.EMPTY_ARRAY);
private final ElementsList<FlatShadowNode> mNativeChildren =
new ElementsList<>(FlatShadowNode.EMPTY_ARRAY);
private final ArrayList<FlatShadowNode> mViewsToDetachAllChildrenFrom = new ArrayList<>();
private final ArrayList<FlatShadowNode> mViewsToDetach = new ArrayList<>();
private final ArrayList<FlatShadowNode> mViewsToUpdateBounds = new ArrayList<>();
private @Nullable FlatUIViewOperationQueue.DetachAllChildrenFromViews mDetachAllChildrenFromViews;
/* package */ StateBuilder(FlatUIViewOperationQueue operationsQueue) {
mOperationsQueue = operationsQueue;
}
/**
* Given a root of the laid-out shadow node hierarchy, walks the tree and generates an array of
* DrawCommands that will then mount in UI thread to a root FlatViewGroup so that it can draw.
*/
/* package */ void applyUpdates(FlatShadowNode node) {
int tag = node.getReactTag();
float width = node.getLayoutWidth();
float height = node.getLayoutHeight();
collectStateForMountableNode(node, tag, width, height);
float left = node.getLayoutX();
float top = node.getLayoutY();
float right = left + width;
float bottom = top + height;
updateNodeRegion(node, tag, left, top, right, bottom);
mViewsToUpdateBounds.add(node);
if (mDetachAllChildrenFromViews != null) {
int[] viewsToDetachAllChildrenFrom = collectViewTags(mViewsToDetachAllChildrenFrom);
mViewsToDetachAllChildrenFrom.clear();
mDetachAllChildrenFromViews.setViewsToDetachAllChildrenFrom(viewsToDetachAllChildrenFrom);
mDetachAllChildrenFromViews = null;
}
for (int i = 0, size = mViewsToUpdateBounds.size(); i != size; ++i) {
updateViewBounds(mViewsToUpdateBounds.get(i));
}
mViewsToUpdateBounds.clear();
}
/**
* Adds a DrawCommand for current mountable node.
*/
/* package */ void addDrawCommand(AbstractDrawCommand drawCommand) {
mDrawCommands.add(drawCommand);
}
/* package */ void addAttachDetachListener(AttachDetachListener listener) {
mAttachDetachListeners.add(listener);
}
/* package */ void ensureBackingViewIsCreated(
FlatShadowNode node,
int tag,
@Nullable CatalystStylesDiffMap styles) {
if (node.isBackingViewCreated()) {
if (styles != null) {
// if the View is already created, make sure propagate new styles.
mOperationsQueue.enqueueUpdateProperties(tag, node.getViewClass(), styles);
}
return;
}
mOperationsQueue.enqueueCreateView(node.getThemedContext(), tag, node.getViewClass(), styles);
node.signalBackingViewIsCreated();
}
private void addNodeRegion(NodeRegion nodeRegion) {
mNodeRegions.add(nodeRegion);
}
private void addNativeChild(FlatShadowNode nativeChild) {
mNativeChildren.add(nativeChild);
}
/**
* Updates boundaries of a View that a give nodes maps to.
*/
private void updateViewBounds(FlatShadowNode node) {
NodeRegion nodeRegion = node.getNodeRegion();
int viewLeft = Math.round(nodeRegion.mLeft);
int viewTop = Math.round(nodeRegion.mTop);
int viewRight = Math.round(nodeRegion.mRight);
int viewBottom = Math.round(nodeRegion.mBottom);
if (node.getViewLeft() == viewLeft && node.getViewTop() == viewTop &&
node.getViewRight() == viewRight && node.getViewBottom() == viewBottom) {
// nothing changed.
return;
}
// this will optionally measure and layout the View this node maps to.
node.setViewBounds(viewLeft, viewTop, viewRight, viewBottom);
int tag = node.getReactTag();
mOperationsQueue.enqueueUpdateViewBounds(tag, viewLeft, viewTop, viewRight, viewBottom);
}
/**
* Collects state (DrawCommands) for a given node that will mount to a View.
*/
private void collectStateForMountableNode(
FlatShadowNode node,
int tag,
float width,
float height) {
mDrawCommands.start(node.getDrawCommands());
mAttachDetachListeners.start(node.getAttachDetachListeners());
mNodeRegions.start(node.getNodeRegions());
mNativeChildren.start(node.getNativeChildren());
collectStateRecursively(node, 0, 0, width, height);
boolean shouldUpdateMountState = false;
final DrawCommand[] drawCommands = mDrawCommands.finish();
if (drawCommands != null) {
shouldUpdateMountState = true;
node.setDrawCommands(drawCommands);
}
final AttachDetachListener[] listeners = mAttachDetachListeners.finish();
if (listeners != null) {
shouldUpdateMountState = true;
node.setAttachDetachListeners(listeners);
}
final NodeRegion[] nodeRegions = mNodeRegions.finish();
if (nodeRegions != null) {
shouldUpdateMountState = true;
node.setNodeRegions(nodeRegions);
}
if (shouldUpdateMountState) {
mOperationsQueue.enqueueUpdateMountState(
tag,
drawCommands,
listeners,
nodeRegions);
}
final FlatShadowNode[] nativeChildren = mNativeChildren.finish();
if (nativeChildren != null) {
updateNativeChildren(node, tag, node.getNativeChildren(), nativeChildren);
}
}
private void updateNativeChildren(
FlatShadowNode node,
int tag,
FlatShadowNode[] oldNativeChildren,
FlatShadowNode[] newNativeChildren) {
node.setNativeChildren(newNativeChildren);
if (mDetachAllChildrenFromViews == null) {
mDetachAllChildrenFromViews = mOperationsQueue.enqueueDetachAllChildrenFromViews();
}
if (oldNativeChildren.length != 0) {
mViewsToDetachAllChildrenFrom.add(node);
}
int numViewsToAdd = newNativeChildren.length;
final int[] viewsToAdd;
if (numViewsToAdd == 0) {
viewsToAdd = EMPTY_INT_ARRAY;
} else {
viewsToAdd = new int[numViewsToAdd];
int i = 0;
for (FlatShadowNode child : newNativeChildren) {
if (child.getNativeParentTag() == tag) {
viewsToAdd[i] = -child.getReactTag();
} else {
viewsToAdd[i] = child.getReactTag();
}
// all views we add are first start detached
child.setNativeParentTag(-1);
++i;
}
}
// Populate an array of views to detach.
// These views still have their native parent set as opposed to being reset to -1
for (FlatShadowNode child : oldNativeChildren) {
if (child.getNativeParentTag() == tag) {
// View is attached to old parent and needs to be removed.
mViewsToDetach.add(child);
child.setNativeParentTag(-1);
}
}
final int[] viewsToDetach = collectViewTags(mViewsToDetach);
mViewsToDetach.clear();
// restore correct parent tag
for (FlatShadowNode child : newNativeChildren) {
child.setNativeParentTag(tag);
}
mOperationsQueue.enqueueUpdateViewGroup(tag, viewsToAdd, viewsToDetach);
}
/**
* Recursively walks node tree from a given node and collects DrawCommands.
*/
private void collectStateRecursively(
FlatShadowNode node,
float left,
float top,
float right,
float bottom) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
node.collectState(this, left, top, right, bottom);
for (int i = 0, childCount = node.getChildCount(); i != childCount; ++i) {
FlatShadowNode child = (FlatShadowNode) node.getChildAt(i);
processNodeAndCollectState(child, left, top);
}
}
/**
* Collects state and updates View boundaries for a given node tree.
*/
private void processNodeAndCollectState(
FlatShadowNode node,
float parentLeft,
float parentTop) {
int tag = node.getReactTag();
float width = node.getLayoutWidth();
float height = node.getLayoutHeight();
float left = parentLeft + node.getLayoutX();
float top = parentTop + node.getLayoutY();
float right = left + width;
float bottom = top + height;
updateNodeRegion(node, tag, left, top, right, bottom);
if (node.mountsToView()) {
ensureBackingViewIsCreated(node, tag, null);
addNativeChild(node);
mDrawCommands.add(DrawView.INSTANCE);
collectStateForMountableNode(node, tag, width, height);
mViewsToUpdateBounds.add(node);
} else {
collectStateRecursively(node, left, top, right, bottom);
addNodeRegion(node.getNodeRegion());
}
}
private static void updateNodeRegion(
FlatShadowNode node,
int tag,
float left,
float top,
float right,
float bottom) {
final NodeRegion nodeRegion = node.getNodeRegion();
if (nodeRegion.mLeft != left || nodeRegion.mTop != top ||
nodeRegion.mRight != right || nodeRegion.mBottom != bottom) {
node.setNodeRegion(new NodeRegion(left, top, right, bottom, tag));
}
}
private static int[] collectViewTags(ArrayList<FlatShadowNode> views) {
int numViews = views.size();
if (numViews == 0) {
return EMPTY_INT_ARRAY;
}
int[] viewTags = new int[numViews];
for (int i = 0; i < numViews; ++i) {
viewTags[i] = views.get(i).getReactTag();
}
return viewTags;
}
}
|
// This file is part of the Whiley-to-Java Compiler (wyjc).
// The Whiley-to-Java Compiler is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// The Whiley-to-Java Compiler is distributed in the hope that it
// You should have received a copy of the GNU General Public
package wyjc.testing.tests;
import org.junit.*;
import wyjc.testing.TestHarness;
public class ExtendedValidTests extends TestHarness {
public ExtendedValidTests() {
super("tests/ext/valid","tests/ext/valid","sysout");
}
@Test public void BoolAssign_Valid_3_RuntimeTest() { runTest("BoolAssign_Valid_3"); }
@Test public void BoolAssign_Valid_4_RuntimeTest() { runTest("BoolAssign_Valid_4"); }
@Test public void BoolRequires_Valid_1_RuntimeTest() { runTest("BoolRequires_Valid_1"); }
@Test public void ConstrainedDictionary_Valid_1_RuntimeTest() { runTest("ConstrainedDictionary_Valid_1"); }
@Test public void ConstrainedInt_Valid_1_RuntimeTest() { runTest("ConstrainedInt_Valid_1"); }
@Test public void ConstrainedInt_Valid_10_RuntimeTest() { runTest("ConstrainedInt_Valid_10"); }
@Test public void ConstrainedInt_Valid_11_RuntimeTest() { runTest("ConstrainedInt_Valid_11"); }
@Test public void ConstrainedInt_Valid_3_RuntimeTest() { runTest("ConstrainedInt_Valid_3"); }
@Test public void ConstrainedInt_Valid_4_RuntimeTest() { runTest("ConstrainedInt_Valid_4"); }
@Test public void ConstrainedInt_Valid_5_RuntimeTest() { runTest("ConstrainedInt_Valid_5"); }
@Test public void ConstrainedInt_Valid_6_RuntimeTest() { runTest("ConstrainedInt_Valid_6"); }
@Test public void ConstrainedInt_Valid_7_RuntimeTest() { runTest("ConstrainedInt_Valid_7"); }
@Test public void ConstrainedInt_Valid_8_RuntimeTest() { runTest("ConstrainedInt_Valid_8"); }
@Ignore("Known Issue") @Test public void ConstrainedInt_Valid_9_RuntimeTest() { runTest("ConstrainedInt_Valid_9"); }
@Test public void ConstrainedList_Valid_1_RuntimeTest() { runTest("ConstrainedList_Valid_1"); }
@Test public void ConstrainedList_Valid_2_RuntimeTest() { runTest("ConstrainedList_Valid_2"); }
@Test public void ConstrainedList_Valid_3_RuntimeTest() { runTest("ConstrainedList_Valid_3"); }
@Test public void ConstrainedList_Valid_4_RuntimeTest() { runTest("ConstrainedList_Valid_4"); }
@Ignore("Future Work") @Test public void ConstrainedNegation_Valid_1_RuntimeTest() { runTest("ConstrainedNegation_Valid_1"); }
@Test public void ConstrainedRecord_Valid_4_RuntimeTest() { runTest("ConstrainedRecord_Valid_4"); }
@Test public void ConstrainedRecord_Valid_5_RuntimeTest() { runTest("ConstrainedRecord_Valid_5"); }
@Test public void ConstrainedSet_Valid_1_RuntimeTest() { runTest("ConstrainedSet_Valid_1"); }
@Test public void ConstrainedSet_Valid_2_RuntimeTest() { runTest("ConstrainedSet_Valid_2"); }
@Test public void ConstrainedSet_Valid_3_RuntimeTest() { runTest("ConstrainedSet_Valid_3"); }
@Test public void ConstrainedSet_Valid_4_RuntimeTest() { runTest("ConstrainedSet_Valid_4"); }
@Test public void ConstrainedTuple_Valid_1_RuntimeTest() { runTest("ConstrainedTuple_Valid_1"); }
@Test public void Ensures_Valid_1_RuntimeTest() { runTest("Ensures_Valid_1"); }
@Test public void Ensures_Valid_2_RuntimeTest() { runTest("Ensures_Valid_2"); }
@Test public void Ensures_Valid_3_RuntimeTest() { runTest("Ensures_Valid_3"); }
@Test public void Ensures_Valid_4_RuntimeTest() { runTest("Ensures_Valid_4"); }
@Test public void Ensures_Valid_5_RuntimeTest() { runTest("Ensures_Valid_5"); }
@Test public void For_Valid_2_RuntimeTest() { runTest("For_Valid_2"); }
@Test public void For_Valid_3_RuntimeTest() { runTest("For_Valid_3"); }
@Ignore("Known Issue") @Test public void Function_Valid_11_RuntimeTest() { runTest("Function_Valid_11"); }
@Test public void Function_Valid_12_RuntimeTest() { runTest("Function_Valid_12"); }
@Test public void Function_Valid_2_RuntimeTest() { runTest("Function_Valid_2"); }
@Test public void Function_Valid_3_RuntimeTest() { runTest("Function_Valid_3"); }
@Test public void Function_Valid_4_RuntimeTest() { runTest("Function_Valid_4"); }
@Test public void Function_Valid_5_RuntimeTest() { runTest("Function_Valid_5"); }
@Test public void Function_Valid_6_RuntimeTest() { runTest("Function_Valid_6"); }
@Ignore("Known Issue") @Test public void Function_Valid_8_RuntimeTest() { runTest("Function_Valid_8"); }
@Test public void IntDefine_Valid_1_RuntimeTest() { runTest("IntDefine_Valid_1"); }
@Test public void IntDiv_Valid_1_RuntimeTest() { runTest("IntDiv_Valid_1"); }
@Test public void ListAccess_Valid_1_RuntimeTest() { runTest("ListAccess_Valid_1"); }
@Test public void ListAccess_Valid_2_RuntimeTest() { runTest("ListAccess_Valid_2"); }
@Test public void ListAppend_Valid_5_RuntimeTest() { runTest("ListAppend_Valid_5"); }
@Test public void ListAppend_Valid_6_RuntimeTest() { runTest("ListAppend_Valid_6"); }
@Test public void ListAssign_Valid_5_RuntimeTest() { runTest("ListAssign_Valid_5"); }
@Test public void ListAssign_Valid_6_RuntimeTest() { runTest("ListAssign_Valid_6"); }
@Test public void ListGenerator_Valid_1_RuntimeTest() { runTest("ListGenerator_Valid_1"); }
@Test public void ListGenerator_Valid_2_RuntimeTest() { runTest("ListGenerator_Valid_2"); }
@Test public void ListSublist_Valid_1_RuntimeTest() { runTest("ListSublist_Valid_1"); }
@Test public void Process_Valid_2_RuntimeTest() { runTest("Process_Valid_2"); }
@Test public void Quantifiers_Valid_1_RuntimeTest() { runTest("Quantifiers_Valid_1"); }
@Test public void RealDiv_Valid_1_RuntimeTest() { runTest("RealDiv_Valid_1"); }
@Test public void RealDiv_Valid_2_RuntimeTest() { runTest("RealDiv_Valid_2"); }
@Test public void RealDiv_Valid_3_RuntimeTest() { runTest("RealDiv_Valid_3"); }
@Test public void RealNeg_Valid_1_RuntimeTest() { runTest("RealNeg_Valid_1"); }
@Test public void RealSub_Valid_1_RuntimeTest() { runTest("RealSub_Valid_1"); }
@Test public void RecordAssign_Valid_1_RuntimeTest() { runTest("RecordAssign_Valid_1"); }
@Test public void RecordAssign_Valid_2_RuntimeTest() { runTest("RecordAssign_Valid_2"); }
@Test public void RecordAssign_Valid_4_RuntimeTest() { runTest("RecordAssign_Valid_4"); }
@Test public void RecordAssign_Valid_5_RuntimeTest() { runTest("RecordAssign_Valid_5"); }
@Test public void RecordDefine_Valid_1_RuntimeTest() { runTest("RecordDefine_Valid_1"); }
@Test public void RecursiveType_Valid_3_RuntimeTest() { runTest("RecursiveType_Valid_3"); }
@Test public void RecursiveType_Valid_5_RuntimeTest() { runTest("RecursiveType_Valid_5"); }
@Test public void RecursiveType_Valid_6_RuntimeTest() { runTest("RecursiveType_Valid_6"); }
@Test public void RecursiveType_Valid_8_RuntimeTest() { runTest("RecursiveType_Valid_8"); }
@Test public void RecursiveType_Valid_9_RuntimeTest() { runTest("RecursiveType_Valid_9"); }
@Test public void Requires_Valid_1_RuntimeTest() { runTest("Requires_Valid_1"); }
@Test public void SetAssign_Valid_1_RuntimeTest() { runTest("SetAssign_Valid_1"); }
@Test public void SetComprehension_Valid_6_RuntimeTest() { runTest("SetComprehension_Valid_6"); }
@Test public void SetComprehension_Valid_7_RuntimeTest() { runTest("SetComprehension_Valid_7"); }
@Test public void SetDefine_Valid_1_RuntimeTest() { runTest("SetDefine_Valid_1"); }
@Test public void SetIntersection_Valid_1_RuntimeTest() { runTest("SetIntersection_Valid_1"); }
@Test public void SetIntersection_Valid_2_RuntimeTest() { runTest("SetIntersection_Valid_2"); }
@Test public void SetIntersection_Valid_3_RuntimeTest() { runTest("SetIntersection_Valid_3"); }
@Test public void SetSubset_Valid_1_RuntimeTest() { runTest("SetSubset_Valid_1"); }
@Test public void SetSubset_Valid_2_RuntimeTest() { runTest("SetSubset_Valid_2"); }
@Test public void SetSubset_Valid_3_RuntimeTest() { runTest("SetSubset_Valid_3"); }
@Test public void SetSubset_Valid_4_RuntimeTest() { runTest("SetSubset_Valid_4"); }
@Test public void SetSubset_Valid_5_RuntimeTest() { runTest("SetSubset_Valid_5"); }
@Test public void SetSubset_Valid_6_RuntimeTest() { runTest("SetSubset_Valid_6"); }
@Test public void SetSubset_Valid_7_RuntimeTest() { runTest("SetSubset_Valid_7"); }
@Test public void SetUnion_Valid_5_RuntimeTest() { runTest("SetUnion_Valid_5"); }
@Test public void SetUnion_Valid_6_RuntimeTest() { runTest("SetUnion_Valid_6"); }
@Test public void Subtype_Valid_3_RuntimeTest() { runTest("Subtype_Valid_3"); }
@Test public void Subtype_Valid_4_RuntimeTest() { runTest("Subtype_Valid_4"); }
@Test public void Subtype_Valid_5_RuntimeTest() { runTest("Subtype_Valid_5"); }
@Test public void Subtype_Valid_6_RuntimeTest() { runTest("Subtype_Valid_6"); }
@Test public void Subtype_Valid_7_RuntimeTest() { runTest("Subtype_Valid_7"); }
@Test public void Subtype_Valid_8_RuntimeTest() { runTest("Subtype_Valid_8"); }
@Test public void Subtype_Valid_9_RuntimeTest() { runTest("Subtype_Valid_9"); }
@Test public void TypeEquals_Valid_1_RuntimeTest() { runTest("TypeEquals_Valid_1"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_10_RuntimeTest() { runTest("TypeEquals_Valid_10"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_13_RuntimeTest() { runTest("TypeEquals_Valid_13"); }
@Test public void TypeEquals_Valid_5_RuntimeTest() { runTest("TypeEquals_Valid_5"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_6_RuntimeTest() { runTest("TypeEquals_Valid_6"); }
@Test public void TypeEquals_Valid_8_RuntimeTest() { runTest("TypeEquals_Valid_8"); }
@Ignore("Known Issue") @Test public void TypeEquals_Valid_9_RuntimeTest() { runTest("TypeEquals_Valid_9"); }
@Test public void TypeEquals_Valid_14_RuntimeTest() { runTest("TypeEquals_Valid_14"); }
@Test public void UnionType_Valid_12_RuntimeTest() { runTest("UnionType_Valid_12"); }
@Test public void UnionType_Valid_4_RuntimeTest() { runTest("UnionType_Valid_4"); }
@Test public void UnionType_Valid_5_RuntimeTest() { runTest("UnionType_Valid_5"); }
@Test public void UnionType_Valid_6_RuntimeTest() { runTest("UnionType_Valid_6"); }
@Test public void UnionType_Valid_7_RuntimeTest() { runTest("UnionType_Valid_7"); }
@Test public void UnionType_Valid_8_RuntimeTest() { runTest("UnionType_Valid_8"); }
@Test public void VarDecl_Valid_2_RuntimeTest() { runTest("VarDecl_Valid_2"); }
@Test public void While_Valid_2_RuntimeTest() { runTest("While_Valid_2"); }
@Test public void While_Valid_3_RuntimeTest() { runTest("While_Valid_3"); }
@Test public void While_Valid_4_RuntimeTest() { runTest("While_Valid_4"); }
@Test public void While_Valid_5_RuntimeTest() { runTest("While_Valid_5"); }
@Test public void While_Valid_6_RuntimeTest() { runTest("While_Valid_6"); }
}
|
package homesoil;
import static com.google.common.base.Objects.*;
import com.google.common.collect.*;
import java.io.*;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
/**
* This class holds the PlayerInfo objects, keyed by name. It will generate them
* as needed.
*
* @author DanJ
*/
public final class PlayerInfoMap {
private final Map<String, PlayerInfo> infos = Maps.newHashMap();
private final Map<ChunkPosition, String> homeChunkOwners = Maps.newHashMap();
private int homeChunkOwnersGenCount = 0;
private final Random random = new Random();
public PlayerInfo get(OfflinePlayer player) {
String name = player.getName();
PlayerInfo info = infos.get(name);
if (info == null) {
Player onlinePlayer = player.getPlayer();
if (onlinePlayer == null) {
throw new IllegalStateException(String.format(
"The player '%'s has no PlayerInfo, but none can be generated because he is offline.",
name));
}
info = new PlayerInfo();
pickNewHomeChunk(onlinePlayer.getWorld(), onlinePlayer.getServer(), info);
infos.put(name, info);
}
return info;
}
/**
* This method determines whether a given player already has a PlayerInfo
* assigned, but does not actually create one; this therefore will not throw
* even if the player is actually offline.
*
* @param player The player to check.
* @return True if the player has an PlayerInfo assigned.
*/
public boolean isKnown(OfflinePlayer player) {
return infos.containsKey(player.getName());
}
/**
* This method takes a chunk away from a player. If this was his last chunk,
* we randomly assign a new home chunk.
*
* @param player The player whose home chunk is to be removed.
* @param homeChunk The chunk to remove from the player.
* @param server The server we are running on.
*/
public void removeHomeChunk(OfflinePlayer player, ChunkPosition homeChunk, Server server) {
// if player is not yet known, there is no point to resetting his home
// chunk. This will happen when he logs in!
if (isKnown(player)) {
PlayerInfo info = get(player);
if (!info.tryRemoveHomeChunk(homeChunk)) {
World world = homeChunk.getWorld(server);
pickNewHomeChunk(world, server, info);
}
}
}
/**
* This method returns a set containing each chunk that is the home for any
* player. The set is immutable and lazy allocated; a new one is allocated
* if the player infos are ever changed.
*
* @return An immutable set of chunks that are occupied by a player..
*/
public Set<ChunkPosition> getHomeChunks() {
updateHomeChunkOwnersIfNeeded();
return homeChunkOwners.keySet();
}
/**
* This obtains the name of the owner of the chunk indicated; if nobody owns
* the chunk this returns the empty string.
*
* @param position The chunk to be checked.
* @return The name of the chunk owner, or "".
*/
public String identifyChunkOwner(ChunkPosition position) {
updateHomeChunkOwnersIfNeeded();
return firstNonNull(homeChunkOwners.get(position), "");
}
/**
* This method checks the gen count to see if the home chunk owners map must
* be regenerated, and if it needs to, it regenerates that map.
*/
private void updateHomeChunkOwnersIfNeeded() {
int currentGenCount = PlayerInfo.getGenerationCount();
if (homeChunkOwnersGenCount != currentGenCount) {
homeChunkOwnersGenCount = currentGenCount;
homeChunkOwners.clear();
for (Map.Entry<String, PlayerInfo> e : infos.entrySet()) {
String playerName = e.getKey();
PlayerInfo info = e.getValue();
for (ChunkPosition homeChunk : info.getHomeChunks()) {
homeChunkOwners.put(homeChunk, playerName);
}
}
}
}
// Player Starts
/**
* This method returns the location to spawn a player. If the player cannot
* be spawned in his home chunk, this will assign a new home chunk in the
* same world for that player.
*
* @param player The player whose spawn point is needed.
* @return The location to spawn him.
*/
public Location getPlayerStart(Player player) {
return getPlayerStart(player, player.getWorld(), player.getServer());
}
public Location getPlayerStart(OfflinePlayer player, World world, Server server) {
PlayerInfo info = get(player);
if (!info.getHomeChunks().isEmpty()) {
ChunkPosition homeChunk = info.pickHomeChunk(random);
Location spawn = findPlayerStartOrNull(homeChunk, server, true);
if (spawn != null) {
return spawn;
}
}
return pickNewHomeChunk(world, server, info);
}
/**
* This method returns all the player starts that can be found; there can be
* as many as one per home chunk; if some can't be resolved anymore they
* will be omitted. If the player is not known, this method returns an empty
* list and does not assign a home chunk.
*
* @param player The player whose start locations are wanted.
* @param server The server that is running.
* @return The locations, in the order the home chunks were acquired.
*/
public List<Location> getPlayerStarts(OfflinePlayer player, Server server) {
ImmutableList.Builder<Location> b = ImmutableList.builder();
if (isKnown(player)) {
PlayerInfo info = get(player);
for (ChunkPosition homeChunk : info.getHomeChunks()) {
Location spawn = findPlayerStartOrNull(homeChunk, server, false);
if (spawn != null) {
b.add(spawn);
}
}
}
return b.build();
}
/**
* This method finds a place to put the player when he spawns. It will be at
* the center of the home chunk of this player, but its y position is the
* result of a search; we look for a non-air, non-liquid block with two air
* blocks on top.
*
* @param server The server in which the player will spawn.
* @param random The RNG used to pick the starting chunk.
* @param picky The method fails if the player would be spawned in water or
* lava.
* @return The location to spawn him; null if no suitable location could be
* found.
*/
private static Location findPlayerStartOrNull(ChunkPosition homeChunk, Server server, boolean picky) {
World world = homeChunk.getWorld(server);
int blockX = homeChunk.x * 16 + 8;
int blockZ = homeChunk.z * 16 + 8;
final int startY = 253;
// we spawn the player a bit in the air, since he falls a bit
// while the world is loading. We need enough air for him to fall
// through. 5 is as much as we can have without damaging the player on
// landing.
final int spawnHover = 4;
final int spawnSpaceNeeded = spawnHover + 1;
int airCount = 0;
//wondering if we can trust this to always be higher than land, esp. in
//amplified terrain. I've seen lots of 1.7 terrain far higher than this
//and of course amplified can go higher still, and have multiple
//airspaces above ground.
//If we're using this for snowball targets, higher is better - chris
for (int y = startY; y > 1; --y) {
Block bl = world.getBlockAt(blockX, y, blockZ);
if (bl.getType() == Material.AIR) {
airCount++;
} else if (airCount >= spawnSpaceNeeded) {
if (picky && bl.isLiquid()) {
break;
}
return new Location(world, blockX, y + spawnHover, blockZ);
} else {
break;
}
}
return null;
}
/**
* This method selects a home chunk and assigns it to the 'info' given; it
* keeps trying to do this until it finds a valid home chunk. If it cannot
* find one, it will throw an exception.
*
* @param world The world in which the home chunk should be found.
* @param server The server that contains the world.
* @param info The player info to be updated.
* @return The spawn point for the player, as a convenience.
*/
private Location pickNewHomeChunk(World world, Server server, PlayerInfo info) {
// we'll try many times to find a spawn location
// with a valid player start.
for (int limit = 0; limit < 256; ++limit) {
ChunkPosition homeChunk = getInitialChunkPosition(world);
// after a while, we'll take what we can get!
boolean picky = limit < 128;
Location spawn = findPlayerStartOrNull(homeChunk, server, picky);
if (spawn != null) {
info.setHomeChunk(homeChunk);
return spawn;
}
}
throw new RuntimeException(String.format("Unable to find any open home chunk in the world '%s'", world.getName()));
}
/**
* This method picks a position for a player that is not assigned to any
* player yet.
*
* @param world The world the player will spawn in.
*/
private ChunkPosition getInitialChunkPosition(World world) {
Set<ChunkPosition> oldHomes = getHomeChunks();
int numberOfHomeChunks = oldHomes.size();
int spawnRadiusInChunks = Math.max(1, (int) (Math.sqrt(numberOfHomeChunks) * 16));
//64 output (sixteen discrete homechunks) gives about a -1000 to 1000 maximum range
for (;;) {
int x = random.nextInt(spawnRadiusInChunks * 2) - spawnRadiusInChunks;
int z = random.nextInt(spawnRadiusInChunks * 2) - spawnRadiusInChunks;
ChunkPosition homeChunk = new ChunkPosition(x, z, world);
if (!oldHomes.contains(homeChunk)) {
return homeChunk;
}
}
}
// Loading and Saving
private int loadedGenerationCount;
/**
* This method populates the map with the contents of the player file.
*/
public void load(File source) {
MapFileMap.read(source).copyInto(infos, PlayerInfo.class);
loadedGenerationCount = PlayerInfo.getGenerationCount();
}
/**
* This method writes the player data out to the players file. We call this
* whenever anything is changed.
*/
public void save(File destination) {
MapFileMap.write(destination, infos);
loadedGenerationCount = PlayerInfo.getGenerationCount();
}
/**
* This method returns true if there might be changes to save; this checks
* the global generation count so its not entirely accurate, but it should
* never return false if there are changes to save.
*
* @return True if save() should be called.
*/
public boolean shouldSave() {
return loadedGenerationCount != PlayerInfo.getGenerationCount();
}
}
|
/*
* @author max
*/
package com.intellij.ui;
import com.intellij.util.NotNullProducer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
/**
* @author max
* @author Konstantin Bulenkov
*/
@SuppressWarnings("UseJBColor")
public class ColorUtil {
private ColorUtil() {
}
@NotNull
public static Color marker(@NotNull final String name) {
return new JBColor(() -> {
throw new AssertionError(name);
}) {
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public String toString() {
return name;
}
};
}
@NotNull
public static Color softer(@NotNull Color color) {
if (color.getBlue() > 220 && color.getRed() > 220 && color.getGreen() > 220) return color;
final float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
return Color.getHSBColor(hsb[0], 0.6f * hsb[1], hsb[2]);
}
@NotNull
public static Color darker(@NotNull Color color, int tones) {
return hackBrightness(color, tones, 1 / 1.1F);
}
@NotNull
public static Color brighter(@NotNull Color color, int tones) {
return hackBrightness(color, tones, 1.1F);
}
@NotNull
public static Color hackBrightness(@NotNull Color color, int howMuch, float hackValue) {
return hackBrightness(color.getRed(), color.getGreen(), color.getBlue(), howMuch, hackValue);
}
@NotNull
public static Color hackBrightness(int r, int g, int b, int howMuch, float hackValue) {
final float[] hsb = Color.RGBtoHSB(r, g, b, null);
float brightness = hsb[2];
for (int i = 0; i < howMuch; i++) {
brightness = Math.min(1, Math.max(0, brightness * hackValue));
if (brightness == 0 || brightness == 1) break;
}
return Color.getHSBColor(hsb[0], hsb[1], brightness);
}
@NotNull
public static Color saturate(@NotNull Color color, int tones) {
final float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
float saturation = hsb[1];
for (int i = 0; i < tones; i++) {
saturation = Math.min(1, saturation * 1.1F);
if (saturation == 1) break;
}
return Color.getHSBColor(hsb[0], saturation, hsb[2]);
}
@NotNull
public static Color desaturate(@NotNull Color color, int tones) {
final float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
float saturation = hsb[1];
for (int i = 0; i < tones; i++) {
saturation = Math.max(0, saturation / 1.1F);
if (saturation == 0) break;
}
return Color.getHSBColor(hsb[0], saturation, hsb[2]);
}
@NotNull
public static Color dimmer(@NotNull final Color color) {
NotNullProducer<Color> func = () -> {
float[] rgb = color.getRGBColorComponents(null);
float alpha = 0.80f;
float rem = 1 - alpha;
return new Color(rgb[0] * alpha + rem, rgb[1] * alpha + rem, rgb[2] * alpha + rem);
};
return wrap(color, func);
}
private static Color wrap(@NotNull Color color, NotNullProducer<Color> func) {
return color instanceof JBColor ? new JBColor(func) : func.produce();
}
private static int shift(int colorComponent, double d) {
final int n = (int)(colorComponent * d);
return n > 255 ? 255 : n < 0 ? 0 : n;
}
@NotNull
public static Color shift(@NotNull final Color c, final double d) {
NotNullProducer<Color> func = () -> new Color(shift(c.getRed(), d), shift(c.getGreen(), d), shift(c.getBlue(), d), c.getAlpha());
return wrap(c, func);
}
@NotNull
public static Color withAlpha(@NotNull Color c, double a) {
return toAlpha(c, (int)(255 * a));
}
@NotNull
static Color srcOver(@NotNull Color c, @NotNull Color b) {
float [] rgba = new float[4];
rgba = c.getRGBComponents(rgba);
float[] brgba = new float[4];
brgba = b.getRGBComponents(brgba);
float dsta = 1.0f - rgba[3];
// Applying SrcOver rule
return new Color(rgba[0]*rgba[3] + dsta*brgba[0],
rgba[1]*rgba[3] + dsta*brgba[1],
rgba[2]*rgba[3] + dsta*brgba[2], 1.0f);
}
@NotNull
public static Color withPreAlpha(@NotNull Color c, double a) {
float [] rgba = new float[4];
rgba = withAlpha(c, a).getRGBComponents(rgba);
return new Color(rgba[0]*rgba[3], rgba[1]*rgba[3], rgba[2]*rgba[3], 1.0f);
}
@NotNull
public static Color toAlpha(@Nullable Color color, final int a) {
final Color c = color == null ? Color.black : color;
NotNullProducer<Color> func = () -> new Color(c.getRed(), c.getGreen(), c.getBlue(), a);
return wrap(c, func);
}
@NotNull
public static String toHex(@NotNull final Color c) {
return toHex(c, false);
}
@NotNull
public static String toHex(@NotNull final Color c, final boolean withAlpha) {
final String R = Integer.toHexString(c.getRed());
final String G = Integer.toHexString(c.getGreen());
final String B = Integer.toHexString(c.getBlue());
final String rgbHex = (R.length() < 2 ? "0" : "") + R + (G.length() < 2 ? "0" : "") + G + (B.length() < 2 ? "0" : "") + B;
if (!withAlpha){
return rgbHex;
}
final String A = Integer.toHexString(c.getAlpha());
return rgbHex + (A.length() < 2 ? "0" : "") + A;
}
@NotNull
public static String toHtmlColor(@NotNull final Color c) {
return "
}
/**
* Return Color object from string. The following formats are allowed:
* {@code 0xA1B2C3},
* {@code #abc123},
* {@code ABC123},
* {@code ab5},
* {@code #FFF}.
*
* @param str hex string
* @return Color object
*/
@NotNull
public static Color fromHex(@NotNull String str) {
int pos = str.startsWith("#") ? 1 : str.startsWith("0x") ? 2 : 0;
int len = str.length() - pos;
if (len == 3) return new Color(fromHex1(str, pos), fromHex1(str, pos + 1), fromHex1(str, pos + 2), 255);
if (len == 4) return new Color(fromHex1(str, pos), fromHex1(str, pos + 1), fromHex1(str, pos + 2), fromHex1(str, pos + 3));
if (len == 6) return new Color(fromHex2(str, pos), fromHex2(str, pos + 2), fromHex2(str, pos + 4), 255);
if (len == 8) return new Color(fromHex2(str, pos), fromHex2(str, pos + 2), fromHex2(str, pos + 4), fromHex2(str, pos + 6));
throw new IllegalArgumentException("unsupported length:" + str);
}
private static int fromHex(@NotNull String str, int pos) {
char ch = str.charAt(pos);
if (ch >= '0' && ch <= '9') return ch - '0';
if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
throw new IllegalArgumentException("unsupported char at " + pos + ":" + str);
}
private static int fromHex1(@NotNull String str, int pos) {
return 17 * fromHex(str, pos);
}
private static int fromHex2(@NotNull String str, int pos) {
return 16 * fromHex(str, pos) + fromHex(str, pos + 1);
}
@Nullable
public static Color fromHex(@Nullable String str, @Nullable Color defaultValue) {
if (str == null) return defaultValue;
try {
return fromHex(str);
}
catch (Exception e) {
return defaultValue;
}
}
/**
* @param c color to check
* @return dark or not
*/
public static boolean isDark(@NotNull Color c) {
return ((getLuminance(c) + 0.05) / 0.05) < 4.5;
}
public static boolean areContrasting(@NotNull Color c1, @NotNull Color c2) {
return Double.compare(getContrast(c1, c2), 4.5) >= 0;
}
public static double getContrast(@NotNull Color c1, @NotNull Color c2) {
double l1 = getLuminance(c1);
double l2 = getLuminance(c2);
return (Math.max(l1, l2) + 0.05) / (Math.min(l2, l1) + 0.05);
}
public static double getLuminance(@NotNull Color color) {
return getLinearRGBComponentValue(color.getRed() / 255.0) * 0.2126 +
getLinearRGBComponentValue(color.getGreen() / 255.0) * 0.7152 +
getLinearRGBComponentValue(color.getBlue() / 255.0) * 0.0722;
}
private static double getLinearRGBComponentValue(double colorValue) {
if (colorValue <= 0.03928) return colorValue / 12.92;
return Math.pow(((colorValue + 0.055) / 1.055), 2.4);
}
@NotNull
public static Color mix(@NotNull final Color c1, @NotNull final Color c2, double balance) {
if (balance <= 0) return c1;
if (balance >= 1) return c2;
NotNullProducer<Color> func = new MixedColorProducer(c1, c2, balance);
return c1 instanceof JBColor || c2 instanceof JBColor ? new JBColor(func) : func.produce();
}
}
|
package module6;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.GeoJSONReader;
import de.fhpotsdam.unfolding.data.PointFeature;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.AbstractShapeMarker;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MultiMarker;
import de.fhpotsdam.unfolding.providers.Google;
import de.fhpotsdam.unfolding.providers.MBTilesMapProvider;
import de.fhpotsdam.unfolding.utils.MapUtils;
import parsing.ParseFeed;
import processing.core.PApplet;
public class EarthquakeCityMap extends PApplet {
// We will use member variables, instead of local variables, to store the data
// that the setUp and draw methods will need to access (as well as other methods)
// You will use many of these variables, but the only one you should need to add
// code to modify is countryQuakes, where you will store the number of earthquakes
// per country.
// You can ignore this. It's to get rid of eclipse warnings
private static final long serialVersionUID = 1L;
// IF YOU ARE WORKING OFFILINE, change the value of this variable to true
private static final boolean offline = false;
/** This is where to find the local tiles, for working without an Internet connection */
public static String mbTilesString = "blankLight-1-3.mbtiles";
//feed with magnitude 2.5+ Earthquakes
private String earthquakesURL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.atom";
// The files containing city names and info and country names and info
private String cityFile = "city-data.json";
private String countryFile = "countries.geo.json";
// The map
private UnfoldingMap map;
// Markers for each city
private List<Marker> cityMarkers;
// Markers for each earthquake
private List<Marker> quakeMarkers;
// A List of country markers
private List<Marker> countryMarkers;
// NEW IN MODULE 5
private CommonMarker lastSelected;
private CommonMarker lastClicked;
private int requestedQuakeMagnitude = 0;
public void setup() {
// (1) Initializing canvas and map tiles
size(900, 700, OPENGL);
if (offline) {
map = new UnfoldingMap(this, 200, 50, 650, 600, new MBTilesMapProvider(mbTilesString));
earthquakesURL = "2.5_week.atom"; // The same feed, but saved August 7, 2015
}
else {
map = new UnfoldingMap(this, 200, 50, 650, 600, new Google.GoogleMapProvider());
// IF YOU WANT TO TEST WITH A LOCAL FILE, uncomment the next line
//earthquakesURL = "2.5_week.atom";
}
MapUtils.createDefaultEventDispatcher(this, map);
// FOR TESTING: Set earthquakesURL to be one of the testing files by uncommenting
// one of the lines below. This will work whether you are online or offline
//earthquakesURL = "test1.atom";
//earthquakesURL = "test2.atom";
// Uncomment this line to take the quiz
//earthquakesURL = "quiz2.atom";
// (2) Reading in earthquake data and geometric properties
// STEP 1: load country features and markers
List<Feature> countries = GeoJSONReader.loadData(this, countryFile);
countryMarkers = MapUtils.createSimpleMarkers(countries);
// STEP 2: read in city data
List<Feature> cities = GeoJSONReader.loadData(this, cityFile);
cityMarkers = new ArrayList<Marker>();
for(Feature city : cities) {
cityMarkers.add(new CityMarker(city));
}
// STEP 3: read in earthquake RSS feed
List<PointFeature> earthquakes = ParseFeed.parseEarthquake(this, earthquakesURL);
quakeMarkers = new ArrayList<Marker>();
for(PointFeature feature : earthquakes) {
//check if LandQuake
if(isLand(feature)) {
quakeMarkers.add(new LandQuakeMarker(feature));
}
// OceanQuakes
else {
quakeMarkers.add(new OceanQuakeMarker(feature));
}
}
// could be used for debugging
printQuakes();
// (3) Add markers to map
// NOTE: Country markers are not added to the map. They are used
// for their geometric properties
map.addMarkers(quakeMarkers);
map.addMarkers(cityMarkers);
sortAndPrint(10);
} // End setup
public void draw() {
background(0);
map.draw();
addKey();
}
// TODO: Add the method:
private void sortAndPrint(int numToPrint)
{
Object[] quakeArray = quakeMarkers.toArray();
ArrayList<EarthquakeMarker> eQuakes = new ArrayList();
for(Marker marker : quakeMarkers)
{
eQuakes.add((EarthquakeMarker) marker);
}
Collections.sort(eQuakes);
int localNumToPrint = numToPrint;
if(localNumToPrint > eQuakes.size()) localNumToPrint = eQuakes.size();
for(int i = 0; i < localNumToPrint; i++)
{
System.out.println(eQuakes.get(i));
}
}
// and then call that method from setUp
/** Event handler that gets called automatically when the
* mouse moves.
*/
@Override
public void mouseMoved()
{
// clear the last selection
if (lastSelected != null) {
lastSelected.setSelected(false);
lastSelected = null;
}
selectMarkerIfHover(quakeMarkers);
selectMarkerIfHover(cityMarkers);
//loop();
}
// If there is a marker selected
private void selectMarkerIfHover(List<Marker> markers)
{
// Abort if there's already a marker selected
if (lastSelected != null) {
return;
}
for (Marker m : markers)
{
CommonMarker marker = (CommonMarker)m;
if (marker.isInside(map, mouseX, mouseY)) {
lastSelected = marker;
marker.setSelected(true);
return;
}
}
}
/** The event handler for mouse clicks
* It will display an earthquake and its threat circle of cities
* Or if a city is clicked, it will display all the earthquakes
* where the city is in the threat circle
*/
@Override
public void mouseClicked()
{
if (lastClicked != null) {
unhideMarkers();
lastClicked = null;
}
else if (lastClicked == null)
{
checkEarthquakesForClick();
if (lastClicked == null) {
checkCitiesForClick();
}
}
showThreshold();
}
// Helper method that will check if a city marker was clicked on
// and respond appropriately
private void checkCitiesForClick()
{
if (lastClicked != null) return;
// Loop over the earthquake markers to see if one of them is selected
for (Marker marker : cityMarkers) {
if (!marker.isHidden() && marker.isInside(map, mouseX, mouseY)) {
lastClicked = (CommonMarker)marker;
// Hide all the other earthquakes and hide
for (Marker mhide : cityMarkers) {
if (mhide != lastClicked) {
mhide.setHidden(true);
}
}
for (Marker mhide : quakeMarkers) {
EarthquakeMarker quakeMarker = (EarthquakeMarker)mhide;
if (quakeMarker.getDistanceTo(marker.getLocation())
> quakeMarker.threatCircle()) {
quakeMarker.setHidden(true);
}
}
return;
}
}
}
// Helper method that will check if an earthquake marker was clicked on
// and respond appropriately
private void checkEarthquakesForClick()
{
if (lastClicked != null) return;
// Loop over the earthquake markers to see if one of them is selected
for (Marker m : quakeMarkers) {
EarthquakeMarker marker = (EarthquakeMarker)m;
if (!marker.isHidden() && marker.isInside(map, mouseX, mouseY)) {
lastClicked = marker;
// Hide all the other earthquakes and hide
for (Marker mhide : quakeMarkers) {
if (mhide != lastClicked) {
mhide.setHidden(true);
}
}
for (Marker mhide : cityMarkers) {
if (mhide.getDistanceTo(marker.getLocation())
> marker.threatCircle()) {
mhide.setHidden(true);
}
}
return;
}
}
}
// loop over and unhide all markers
private void unhideMarkers() {
for(Marker marker : quakeMarkers) {
marker.setHidden(false);
}
for(Marker marker : cityMarkers) {
marker.setHidden(false);
}
}
// helper method to draw key in GUI
private void addKey() {
// Remember you can use Processing's graphics methods here
fill(255, 250, 240);
int xbase = 25;
int ybase = 50;
rect(xbase, ybase, 150, 250);
fill(0);
textAlign(LEFT, CENTER);
textSize(12);
text("Earthquake Key", xbase+25, ybase+25);
fill(150, 30, 30);
int tri_xbase = xbase + 35;
int tri_ybase = ybase + 50;
triangle(tri_xbase, tri_ybase-CityMarker.TRI_SIZE, tri_xbase-CityMarker.TRI_SIZE,
tri_ybase+CityMarker.TRI_SIZE, tri_xbase+CityMarker.TRI_SIZE,
tri_ybase+CityMarker.TRI_SIZE);
fill(0, 0, 0);
textAlign(LEFT, CENTER);
text("City Marker", tri_xbase + 15, tri_ybase);
text("Land Quake", xbase+50, ybase+70);
text("Ocean Quake", xbase+50, ybase+90);
text("Size ~ Magnitude", xbase+25, ybase+110);
fill(255, 255, 255);
ellipse(xbase+35,
ybase+70,
10,
10);
rect(xbase+35-5, ybase+90-5, 10, 10);
fill(color(255, 255, 0));
ellipse(xbase+35, ybase+140, 12, 12);
fill(color(0, 0, 255));
ellipse(xbase+35, ybase+160, 12, 12);
fill(color(255, 0, 0));
ellipse(xbase+35, ybase+180, 12, 12);
textAlign(LEFT, CENTER);
fill(0, 0, 0);
text("Shallow", xbase+50, ybase+140);
text("Intermediate", xbase+50, ybase+160);
text("Deep", xbase+50, ybase+180);
text("Past hour", xbase+50, ybase+200);
fill(255, 255, 255);
int centerx = xbase+35;
int centery = ybase+200;
ellipse(centerx, centery, 12, 12);
strokeWeight(2);
line(centerx-8, centery-8, centerx+8, centery+8);
line(centerx-8, centery+8, centerx+8, centery-8);
// BUTTONS
fill(100,100,100);
triangle(50, 350, 80, 330, 110, 350);
rect(55, 355, 50, 50);
triangle(50, 410, 80, 430, 110, 410);
fill(255, 0, 0);
textSize(20);
text(requestedQuakeMagnitude, 70, 375);
fill(255, 255, 255);
textSize(12);
text("Select earthquake", 40, 440);
text("magnitude threshold", 40, 455);
}
// Checks whether this quake occurred on land. If it did, it sets the
// "country" property of its PointFeature to the country where it occurred
// and returns true. Notice that the helper method isInCountry will
// set this "country" property already. Otherwise it returns false.
private boolean isLand(PointFeature earthquake) {
// IMPLEMENT THIS: loop over all countries to check if location is in any of them
// If it is, add 1 to the entry in countryQuakes corresponding to this country.
for (Marker country : countryMarkers) {
if (isInCountry(earthquake, country)) {
return true;
}
}
// not inside any country
return false;
}
// prints countries with number of earthquakes
// You will want to loop through the country markers or country features
// (either will work) and then for each country, loop through
// the quakes to count how many occurred in that country.
// Recall that the country markers have a "name" property,
// And LandQuakeMarkers have a "country" property set.
private void printQuakes() {
int totalWaterQuakes = quakeMarkers.size();
for (Marker country : countryMarkers) {
String countryName = country.getStringProperty("name");
int numQuakes = 0;
for (Marker marker : quakeMarkers)
{
EarthquakeMarker eqMarker = (EarthquakeMarker)marker;
if (eqMarker.isOnLand()) {
if (countryName.equals(eqMarker.getStringProperty("country"))) {
numQuakes++;
}
}
}
if (numQuakes > 0) {
totalWaterQuakes -= numQuakes;
System.out.println(countryName + ": " + numQuakes);
}
}
System.out.println("OCEAN QUAKES: " + totalWaterQuakes);
}
// helper method to test whether a given earthquake is in a given country
// This will also add the country property to the properties of the earthquake feature if
// it's in one of the countries.
// You should not have to modify this code
private boolean isInCountry(PointFeature earthquake, Marker country) {
// getting location of feature
Location checkLoc = earthquake.getLocation();
// some countries represented it as MultiMarker
// looping over SimplePolygonMarkers which make them up to use isInsideByLoc
if(country.getClass() == MultiMarker.class) {
// looping over markers making up MultiMarker
for(Marker marker : ((MultiMarker)country).getMarkers()) {
// checking if inside
if(((AbstractShapeMarker)marker).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
// return if is inside one
return true;
}
}
}
// check if inside country represented by SimplePolygonMarker
else if(((AbstractShapeMarker)country).isInsideByLocation(checkLoc)) {
earthquake.addProperty("country", country.getProperty("name"));
return true;
}
return false;
}
private void showThreshold()
{
if (mouseX > 50 && mouseX < 110 && mouseY > 330 && mouseY < 350)
{
requestedQuakeMagnitude++;
urgentEarthquakes();
}
if (mouseX > 50 && mouseX < 110 && mouseY < 430 && mouseY > 410)
{
if(requestedQuakeMagnitude >= 1) requestedQuakeMagnitude
urgentEarthquakes();
}
}
private void urgentEarthquakes()
{
for(Marker marker : quakeMarkers)
{
if (Float.parseFloat(marker.getProperty("magnitude").toString()) < requestedQuakeMagnitude) marker.setHidden(true);
else marker.setHidden(false);
}
}
}
|
package org.cleartk;
import org.cleartk.test.util.LicenseTestUtil;
import org.junit.Test;
public class LicenseTest {
@Test
public void testLicenseStatedInSource() throws Exception {
LicenseTestUtil.testJavaFiles("src/main/java");
}
@Test
public void testLicenseStatedInTestSource() throws Exception {
LicenseTestUtil.testJavaFiles("src/test/java");
}
}
|
package opendap.ppt;
import opendap.xml.Util;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* OpenDAPClient is an object that handles the connection to, sending requests
* to, and receiving response from a specified OpenDAP server running either
* on this machine or another machine.
* <p/>
* Requests to the OpenDAP server can be taken in different ways by the
* OpenDAPClient object.
* <UL>
* <LI>One request, ending with a semicolon.</LI>
* <LI>Multiple requests, each ending with a semicolon.</LI>
* <LI>Requests listed in a file, each request can span multiple lines in
* the file and there can be more than one request per line. Each request
* ends with a semicolon.</LI>
* <LI>Interactive mode where the user inputs requests on the command line,
* each ending with a semicolon, with multiple requests allowed per
* line.</LI>
* </UL>
* <p/>
* Response from the requests can sent to any File or OutputStream as
* specified by using the setOutput methods. If no output is specified using
* the setOutput methods thent he output is ignored.
* <p/>
* Thread safety of this object has not yet been determined.
*
* @author Patrick West <A * HREF="mailto:pwest@hao.ucar.edu">pwest@hao.ucar.edu</A>
*/
public class OPeNDAPClient {
private int commandCount;
private NewPPTClient _client = null;
private OutputStream _stream = null;
private boolean _isRunning;
private Logger log = null;
private String _id;
/**
* Creates a OpenDAPClient to handle OpenDAP requests.
* <p/>
* Sets the output of any responses from the OpenDAP server to null,
* meaning that all responses will be thrown out.
*/
public OPeNDAPClient() {
_stream = null;
_isRunning = false;
log = org.slf4j.LoggerFactory.getLogger(getClass());
commandCount = 0;
}
public String getID() {
return _id;
}
public void setID(String ID) {
_id = ID;
}
public int getCommandCount() {
return commandCount;
}
public boolean isRunning() {
return _isRunning;
}
public boolean isClosed() {
return _client.isClosed();
}
public boolean isConnected() {
return _client.isConnected();
}
public String showConnectionProperties() {
return _client.showConnectionProperties();
}
/**
* Connect the OpenDAP client to the OpenDAP server.
* <p/>
* Connects to the OpenDAP server on the specified machine listening on
* the specified port.
*
* @param hostStr The name of the host machine where the server is
* running.
* @param portVal The port on which the server on the host hostStr is
* listening for requests.
* @throws PPTException Thrown if unable to connect to the specified host
* machine given the specified port.
* @see String
* @see PPTException
*/
public void startClient(String hostStr, int portVal) throws PPTException {
_client = new NewPPTClient(hostStr, portVal);
_client.initConnection();
_isRunning = true;
}
/**
* Closes the connection to the OpeNDAP server and closes the output stream.
*
* @throws PPTException Thrown if unable to close the connection or close
* the output stream.
* machine given the specified port.
* @see OutputStream
* @see PPTException
*/
public void shutdownClient() throws PPTException {
if(_client!=null)
_client.closeConnection(true);
if (_stream != null) {
try {
_stream.close();
}
catch (IOException e) {
throw (new PPTException(e.getMessage()));
}
finally {
_isRunning = false;
}
}
_isRunning = false;
}
public int getChunkedReadBufferSize(){
return _client.getChunkReadBufferSize();
}
public void killClient() {
_client.dieNow();
}
/**
* Sends a single OpeNDAP request ending in a semicolon (;) to the
* OpeNDAP server.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param cmd The OpenDAP request, ending in a semicolon, that is sent to
* the OpenDAP server to handle.
*
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending the request
* to the server or a problem receiving the response
* from the server.
* @see String
* @see PPTException
*/
public boolean executeCommand(String cmd,
OutputStream target,
OutputStream error)
throws PPTException {
log.debug(cmd);
_client.sendRequest(cmd);
boolean success = _client.getResponse(target,error);
commandCount++;
return success;
}
/**
* Sends a single XML request document.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param request The XML request that is sent to
* the BES to handle.
*
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending the request
* to the server or a problem receiving the response
* from the server.
* @throws JDOMException if the response fails to parse.
* @see String
* @see PPTException
*/
/*
public Document sendRequest( Document request)
throws PPTException, JDOMException {
_client.sendXMLRequest(request);
Document doc = _client.getXMLResponse();
commandCount++;
return doc;
}
*/
/**
* Sends a single XML request document.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param request The XML request that is sent to
* the BES to handle.
*
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending the request
* to the server or a problem receiving the response
* from the server.
* @see String
* @see PPTException
*/
public boolean sendRequest( Document request,
OutputStream target,
OutputStream error)
throws PPTException {
_client.sendXMLRequest(request);
boolean val = _client.getResponse(target,error);
commandCount++;
return val;
}
/**
* Execute each of the commands in the cmd_list, separated by a * semicolon.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param cmd_list The list of OpenDAP requests, separated by semicolons
* and ending in a semicolon, that will be sent to the
* OpenDAP server to handle, one at a time.
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending any of the
* request to the server or a problem receiving any
* of the response
* s from the server.
* @see String
* @see PPTException
*/
public boolean executeCommands(String cmd_list,
OutputStream target,
OutputStream error)
throws PPTException {
boolean success = true;
String cmds[] = cmd_list.split(";");
for (String cmd : cmds) {
success = executeCommand(cmd + ";", target, error);
if(!success)
return success;
}
return success;
}
/**
* Sends the requests listed in the specified file to the OpenDAP server,
* each command ending with a semicolon.
* <p/>
* The requests do not have to be one per line but can span multiple
* lines and there can be more than one command per line.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param inputFile The file holding the list of OpenDAP requests, each
* ending with a semicolon, that will be sent to the
* OpenDAP server to handle.
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem opening the file to
* read, reading the requests from the file, sending
* any of the requests to the server or a problem
* receiving any of the responses from the server.
* @see File
* @see PPTException
*/
public boolean executeCommands(File inputFile,
OutputStream target,
OutputStream error) throws PPTException {
BufferedReader reader;
boolean success = true;
try {
reader = new BufferedReader(new FileReader(inputFile));
}
catch (FileNotFoundException e) {
throw (new PPTException(e.getMessage()));
}
try {
String cmd = null;
boolean done = false;
while (!done && success) {
String nextLine = reader.readLine();
if (nextLine == null) {
if (cmd != null) {
success = this.executeCommands(cmd,target,error);
}
done = true;
} else {
if (!nextLine.equals("")) {
int i = nextLine.lastIndexOf(';');
if (i == -1) {
if (cmd == null) {
cmd = nextLine;
} else {
cmd += " " + nextLine;
}
} else {
String sub = nextLine.substring(0, i);
if (cmd == null) {
cmd = sub;
} else {
cmd += " " + sub;
}
success = this.executeCommands(cmd,target,error);
if (i == nextLine.length() || i == nextLine.length() - 1) {
cmd = null;
} else {
cmd = nextLine.substring(i + 1, nextLine.length());
}
}
}
}
}
}
catch (IOException e) {
throw (new PPTException(e.getMessage()));
}
finally {
try {
reader.close();
} catch (IOException e) {
//Ignore the failure.
}
}
return success;
}
/**
* An interactive OpenDAP client that takes OpenDAP requests on the command
* line.
* <p/>
* There can be more than one command per line, but commands can NOT span
* multiple lines. The user will be prompted to enter a new OpenDAP request.
* <p/>
* OpenDAPClient:
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param out The target OutputStream for the results of the command.
* @param err The error OutputStream for errors returned by the server.
*
* @throws PPTException Thrown if there is a problem sending any of the
* requests to the server or a problem receiving any
* of the responses from the server.
* @see PPTException
*/
public void interact(OutputStream out, OutputStream err) throws PPTException {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
try {
boolean done = false;
while (!done) {
System.out.print("OPeNDAP> ");
String fromUser = stdIn.readLine();
if (fromUser != null) {
if (fromUser.compareTo("exit") == 0) {
done = true;
} else if (fromUser.compareTo("") == 0) {
//continue;
} else {
this.executeCommands(fromUser,out, err);
}
}
}
}
catch (Exception e) {
_client.closeConnection(true);
throw (new PPTException(e.getMessage(), e));
}
}
private static Options createCmdLineOptions(){
Options options = new Options();
options.addOption("r", "reps", true, "Number of times to send the command.");
options.addOption("c", "maxCmds", true, "Number of commands to send before closing the connection and open a new one.");
options.addOption("i", "besCmd", true, "Name of file containing the command.");
options.addOption("p", "port", true, "Port number of BES.");
options.addOption("h", "host", true, "Hostname of BES.");
options.addOption("o", "outFile", true, "Name of file to which to write BES output.");
options.addOption("e", "errFile", true, "Name of file to which to write BES errors.");
options.addOption("h", "help", true, "Print usage statement.");
return options;
}
private static void printUsage(PrintStream ps){
ps.println("Usage: ");
ps.println("");
ps.println(" OPeNDAPClient -i commandFileName [-r #TimesToSendCommand] [-c numberOfCommandsPerConnection] ");
ps.println("");
ps.println("Summary:");
ps.println("");
ps.println("");
ps.println("Options:");
ps.println("");
ps.println(" --besCmd Filename for the BES command");
ps.println(" --reps Number of times to send command");
ps.println(" --maxCmds Number of commands to send before closing connection and making and opening a new one");
ps.println(" --outFile File to write BES output to (defaults to stdout)");
ps.println(" --errFile File to write BES error output to (defaults to stderr)");
ps.println(" --host BES hostname (defaults to localhost)");
ps.println(" --port BES port number (defaults to 10022)");
ps.println(" --help Prints this usage information.");
ps.println("");
}
/**
*
* @param args Command line arguments as defined by createCmdLineOptions()
*/
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger("OPeNDAPClient-MAIN");
try {
Options options = createCmdLineOptions();
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
// Command File
if (cmd.hasOption("h")) {
printUsage(System.out);
return;
}
// Command File
if (!cmd.hasOption("i")) {
printUsage(System.err);
return;
}
Document cmdDoc = Util.getDocument(cmd.getOptionValue("i"));
String cmdString = new XMLOutputter(Format.getPrettyFormat()).outputString(cmdDoc);
log.info("BES command has been read and parsed.");
// Command reps
int reps = 1;
if (cmd.hasOption("r")) {
reps = Integer.parseInt(cmd.getOptionValue("r"));
}
log.info("BES command will sent "+reps+" time" + (reps>1?"s.":"."));
// Max commands per client
int maxCmds = 1;
if (cmd.hasOption("c")) {
maxCmds = Integer.parseInt(cmd.getOptionValue("c"));
}
log.info("The connection to the BES will be dropped and a new one opened after every "
+ maxCmds+" command" + (maxCmds>1?"s.":"."));
// BES output file
OutputStream besOut = System.out;
if (cmd.hasOption("o")) {
File besOutFile = new File(cmd.getOptionValue("o"));
besOut = new FileOutputStream(besOutFile);
log.info("BES output will be written to "+besOutFile.getAbsolutePath());
}
else {
log.info("BES output will be written to stdout");
}
// BES error file
OutputStream besErr = System.err;
if (cmd.hasOption("e")) {
File besErrFile = new File(cmd.getOptionValue("e"));
besErr = new FileOutputStream(besErrFile);
log.info("BES erros will be written to "+besErrFile.getAbsolutePath());
}
else {
log.info("BES output will be written to stderr");
}
// Hostname
String hostName = "localhost";
if (cmd.hasOption("h")) {
hostName = cmd.getOptionValue("h");
}
// Port Number
int portNum = 10022;
if (cmd.hasOption("p")) {
portNum = Integer.parseInt(cmd.getOptionValue("p"));
}
log.info("Using BES at "+hostName+":"+portNum);
log.info("
log.info("
log.info("Starting... \n\n\n");
OPeNDAPClient oc = new OPeNDAPClient();
oc.startClient(hostName,portNum);
for(int r=0; r<reps ;r++){
if(r>0 && r%maxCmds==0){
oc.shutdownClient();
oc = new OPeNDAPClient();
oc.startClient(hostName,portNum);
}
oc.executeCommand(cmdString,besOut,besErr);
}
}
catch(Throwable t){
log.error("OUCH! Caught "+t.getClass().getName()+" Message: "+t.getMessage());
log.error("STACK TRACE: \n"+org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t));
}
}
}
|
package org.bds.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bds.Config;
import org.bds.cluster.host.TaskResourcesAws;
import org.bds.executioner.ExecutionerCloudAws;
import org.bds.executioner.Executioners;
import org.bds.task.Task;
import org.bds.util.Gpr;
import org.bds.util.GprAws;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
import software.amazon.awssdk.services.ec2.model.Instance;
import software.amazon.awssdk.services.ec2.model.InstanceStateName;
import software.amazon.awssdk.services.ec2.model.Reservation;
/**
* Quick test cases when creating a new feature...
*
* @author pcingola
*
*/
public class TestCasesZzz extends TestCasesBase {
@Before
public void beforeEachTest() {
Config.reset();
Config.get().load();
}
/**
* Find AWS EC2 instance parameters for a given task
* @return DescribeInstancesResponse or null if not found
*/
protected DescribeInstancesResponse findAwsInstance(Task task) {
// Find instance
TaskResourcesAws resources = (TaskResourcesAws) task.getResources();
// Filter specific instances
String instanceId = task.getPid();
if (instanceId == null || instanceId.isEmpty()) return null;
// Query AWS
if (verbose) Gpr.debug("Creating 'DescribeInstancesRequest' request for task '" + task.getId() + "', hainvg instance Id '" + instanceId + "'");
Set<String> instanceIds = new HashSet<>();
instanceIds.add(instanceId);
Ec2Client ec2 = GprAws.ec2Client(resources.getRegion());
DescribeInstancesRequest request = DescribeInstancesRequest.builder().instanceIds(instanceIds).build();
DescribeInstancesResponse response = ec2.describeInstances(request);
if (verbose) Gpr.debug("AWS Instances: " + response);
return response;
}
/**
* Make sure there one (and only one) task in ExecutionerCloudAws
* Return the task or throw an error if not found
*/
protected Task findOneTaskAws() {
ExecutionerCloudAws excloud = (ExecutionerCloudAws) Executioners.getInstance().get(Executioners.ExecutionerType.AWS);
List<String> tids = excloud.getTaskIds();
assertTrue("There should be one task, found " + tids.size() + ", task Ids: " + tids, tids.size() == 1);
// Find task ID
String tid = tids.get(0);
Task task = excloud.findTask(tid);
assertNotNull("Could not find task '" + tid + "'", task);
return task;
}
/**
* Find the first instance state in an AWS EC2 'DescribeInstancesResponse'
* @param response
* @return The first instance state, throw an error if nothing is found
*/
protected InstanceStateName instanceStateName(DescribeInstancesResponse response, String instanceId) {
for (Reservation reservation : response.reservations()) {
for (Instance instance : reservation.instances()) {
if (verbose) Gpr.debug("Found instance Id '" + instance.instanceId() + "'");
if (instance.instanceId().equals(instanceId)) {
InstanceStateName s = instance.state().name();
if (verbose) Gpr.debug("Instance '" + instanceId + "' has state '" + s + "'");
return s;
}
}
}
throw new RuntimeException("Could not find any instance ID '" + instanceId + "' in state in response: " + response);
}
/**
* Task input in s3, output local file
*/
@Test
public void test34_TaskInS3OutLocal() {
runAndCheck("test/remote_34.bds", "outStr", "OK");
}
// /**
// * Execute a detached task on AWS
// * WARNIGN: This test might take several minutes to fail!
// */
// @Test
// public void test05() {
// Gpr.debug("Test");
// verbose = true;
// // Set the output file
// String bucket = awsBucketName();
// String region = awsRegion();
// String urlParen = "s3://" + bucket + "/tmp/bds/run_task_detached_05";
// String url = urlParen + "/out.txt";
// // Make sure output file is deleted before starting
// DataS3 dout = new DataS3(url, region);
// dout.delete();
// // Run the code and check how long before it completes
// Timer t = new Timer();
// runOk("test/run_task_detached_05.bds");
// // A detached task should finish immediately
// assertTrue("Detached task taking too long: Probably not detached", t.elapsedSecs() < 3);
// // Make sure the task is executed on AWS, check instance and instance states
// waitAwsTask();
// // Check that the output file exists
// assertTrue("Output file '" + dout + "' does not exists", dout.exists());
// dout.delete(); // Cleanup
/**
* Wait for a single AWS task to finish
* Check that there is one (and only one) tasks
*/
protected void waitAwsTask() {
int maxIterations = 120;
// Wait until the instance is created
Task task = findOneTaskAws();
String tid = task.getId();
waitInstanceCreate(task);
String instanceId = task.getPid();
if (verbose) Gpr.debug("Task Id '" + tid + "', has AWS EC2 instance ID '" + instanceId + "'");
// Wait until the instance terminates
for (int i = 0; i < maxIterations; i++) {
// Find instance
DescribeInstancesResponse response = findAwsInstance(task);
InstanceStateName state = instanceStateName(response, instanceId);
if (verbose) Gpr.debug("Task Id '" + tid + "', has AWS EC2 instance ID '" + instanceId + "', state '" + state + "'");
if (state == InstanceStateName.TERMINATED) {
return; // OK, we finished successfully
} else if (state == InstanceStateName.PENDING || state == InstanceStateName.RUNNING || state == InstanceStateName.SHUTTING_DOWN) {
// OK, wait until the instance terminates
} else {
throw new RuntimeException("Illegal state: Instance is in an illegal state. Task ID '', instance ID '" + instanceId + "', state '" + state + "'");
}
sleep(1);
}
throw new RuntimeException("Timeout: Too many iterations waiting for instance to finish. Task ID '', instance ID '" + instanceId + "'");
}
/**
* Wait for an instance to be created
* Note: This is based on the fact that the task's PID has the instance ID after is instace for executing a task is created
* Waits for 'maxIterations' seconds, checking every second, if not ready thow an error
*/
protected void waitInstanceCreate(Task task) {
int maxIterations = 60;
for (int i = 0; i < maxIterations; i++) {
String instanceId = task.getPid();
if (instanceId != null && !instanceId.isEmpty()) {
if (verbose) Gpr.debug("Found an instance '" + instanceId + "', for task Id '" + task.getId() + "'");
return;
}
if (verbose) Gpr.debug("Waiting for an instance, for task Id '" + task.getId() + "'");
sleep(1);
}
throw new RuntimeException("Timeout waiting for an instance: Too many iterations waiting for cloud instance for task '" + task.getId() + "'");
}
}
|
package org.eatabrick.vecna;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Security;
import java.util.Iterator;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.openpgp.PGPEncryptedDataList;
import org.spongycastle.openpgp.PGPObjectFactory;
import org.spongycastle.openpgp.PGPPrivateKey;
import org.spongycastle.openpgp.PGPPublicKeyEncryptedData;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSecretKeyRingCollection;
import org.spongycastle.openpgp.PGPUtil;
import org.spongycastle.openpgp.PGPLiteralData;
import org.spongycastle.openpgp.PGPOnePassSignatureList;
import org.spongycastle.openpgp.PGPCompressedData;
public class Vecna extends ListActivity {
private final static String TAG = "Vecna";
private PasswordEntryAdapter adapter;
private SharedPreferences settings;
private String passphrase = "";
private class ReadEntriesTask extends AsyncTask<String, Integer, Integer> {
ProgressDialog progress;
protected void onPreExecute() {
adapter.clear();
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(false);
progress = new ProgressDialog(Vecna.this);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setMessage(getString(R.string.progress_initial));
progress.setCancelable(false);
progress.setMax(6);
progress.show();
}
protected Integer doInBackground(String... string) {
PGPSecretKeyRingCollection keyring = null;
FileInputStream dataStream = null;
publishProgress(R.string.progress_keyfile);
try {
File keyFile = new File(settings.getString("key_file", ""));
FileInputStream keyStream = new FileInputStream(keyFile);
keyring = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyStream));
} catch (Exception e) {
return R.string.error_key_file_not_found;
}
publishProgress(R.string.progress_passfile);
try {
File dataFile = new File(settings.getString("passwords", ""));
dataStream = new FileInputStream(dataFile);
} catch (Exception e) {
return R.string.error_password_file_not_found;
}
try {
PGPObjectFactory factory;
publishProgress(R.string.progress_find_data);
factory = new PGPObjectFactory(PGPUtil.getDecoderStream(dataStream));
PGPEncryptedDataList dataList = null;
Object o;
while ((o = factory.nextObject()) != null) {
if (o instanceof PGPEncryptedDataList) {
dataList = (PGPEncryptedDataList) o;
break;
}
}
if (dataList == null) return R.string.error_no_data_in_file;
publishProgress(R.string.progress_find_key);
PGPSecretKey keySecret = null;
PGPPrivateKey keyPrivate = null;
PGPPublicKeyEncryptedData dataEncrypted = null;
Iterator it = dataList.getEncryptedDataObjects();
while (keyPrivate == null && it.hasNext()) {
dataEncrypted = (PGPPublicKeyEncryptedData) it.next();
keySecret = keyring.getSecretKey(dataEncrypted.getKeyID());
keyPrivate = keySecret.extractPrivateKey(string[0].toCharArray(), "BC");
}
if (keyPrivate == null) return R.string.error_secret_key_missing;
publishProgress(R.string.progress_decrypt);
factory = new PGPObjectFactory(dataEncrypted.getDataStream(keyPrivate, "BC"));
Object message = factory.nextObject();
if (message instanceof PGPCompressedData) {
PGPObjectFactory f = new PGPObjectFactory(((PGPCompressedData) message).getDataStream());
message = f.nextObject();
}
ByteArrayOutputStream dataFinal = new ByteArrayOutputStream();
if (message instanceof PGPLiteralData) {
InputStream s = ((PGPLiteralData) message).getInputStream();
int ch;
while ((ch = s.read()) >= 0) {
dataFinal.write(ch);
}
} else {
return R.string.error_encryption;
}
publishProgress(R.string.progress_parse);
String[] lines = dataFinal.toString().split("\n");
for (int i = 0; i < lines.length; ++i) {
adapter.add(new Entry(lines[i]));
}
} catch (Exception e) {
e.printStackTrace();
return R.string.error_unknown;
}
return 0;
}
protected void onProgressUpdate(Integer... messages) {
progress.setMessage(getString(messages[0]));
progress.incrementProgressBy(1);
}
protected void onPostExecute(Integer result) {
progress.dismiss();
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
if (result > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Vecna.this);
builder.setTitle(getString(R.string.error));
builder.setMessage(getString(result));
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
}
findViewById(android.R.id.list).requestFocus();
}
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
adapter = new PasswordEntryAdapter(this);
adapter.setNotifyOnChange(false);
setListAdapter(adapter);
Security.addProvider(new BouncyCastleProvider());
if (savedInstanceState != null) {
passphrase = savedInstanceState.getString("passphrase");
adapter.populate(savedInstanceState.getStringArray("entries"));
adapter.notifyDataSetChanged();
}
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, Preferences.class);
startActivityForResult(intent, 0);
return true;
case R.id.refresh:
updateEntries();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override protected void onResume() {
super.onResume();
if (adapter.getCount() == 0) updateEntries();
}
@Override protected void onListItemClick(ListView parent, View v, int pos, long id) {
final Entry entry = (Entry) adapter.getItem(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.entry, (ViewGroup) findViewById(R.id.layout_root));
((TextView) layout.findViewById(R.id.account )).setText(entry.account);
((TextView) layout.findViewById(R.id.user )).setText(entry.user);
((TextView) layout.findViewById(R.id.password)).setText(entry.password);
builder.setView(layout);
builder.setPositiveButton(R.string.show_entry_copy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(entry.password);
Toast.makeText(Vecna.this, getString(R.string.copied, entry.account), Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(R.string.show_entry_close, null);
builder.setNeutralButton(R.string.show_entry_show, null);
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override public void onShow(DialogInterface dialogInterface) {
final Button show = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
show.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
EditText password = (EditText) layout.findViewById(R.id.password);
if (show.getText().equals(getString(R.string.show_entry_show))) {
Log.d(TAG, "Show clicked");
password.setTransformationMethod(null);
show.setText(R.string.show_entry_hide);
} else {
Log.d(TAG, "Hide clicked");
password.setTransformationMethod(new PasswordTransformationMethod());
show.setText(R.string.show_entry_show);
}
}
});
}
});
dialog.show();
}
@Override public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("passphrase", passphrase);
savedInstanceState.putStringArray("entries", adapter.toStringArray());
}
private void getPassphrase() {
final EditText pass = new EditText(this);
pass.setSingleLine();
pass.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.prompt));
builder.setView(pass);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Vecna.this.passphrase = pass.getText().toString();
new ReadEntriesTask().execute(passphrase);
}
});
builder.show();
}
private void updateEntries() {
TextView empty = (TextView) findViewById(android.R.id.empty);
if (settings.getString("passwords", "").isEmpty() || settings.getString("key_file", "").isEmpty()) {
empty.setText(R.string.settings);
} else {
empty.setText(R.string.empty);
if (passphrase.isEmpty()) {
getPassphrase();
} else {
new ReadEntriesTask().execute(passphrase);
}
}
}
}
|
package org.exist.dom;
import java.io.*;
import java.util.*;
import javax.xml.stream.*;
import org.exist.Namespaces;
import org.exist.indexing.StreamListener;
import org.exist.numbering.NodeId;
import org.exist.stax.EmbeddedXMLStreamReader;
import org.exist.storage.*;
import org.exist.storage.btree.Value;
import org.exist.storage.txn.*;
import org.exist.util.*;
import org.exist.util.pool.NodePool;
import org.exist.xquery.Constants;
import org.exist.xquery.value.StringValue;
import org.w3c.dom.*;
/**
* ElementImpl.java
*
* @author Wolfgang Meier
*/
public class ElementImpl extends NamedNode implements Element {
public static final int LENGTH_ELEMENT_CHILD_COUNT = 4; //sizeof int
public static final int LENGTH_ATTRIBUTES_COUNT = 2; //sizeof short
public static final int LENGTH_NS_ID = 2; //sizeof short
public static final int LENGTH_PREFIX_LENGTH = 2; //sizeof short
private short attributes = 0;
private int children = 0;
private int position = 0;
private Map namespaceMappings = null;
private int indexType = RangeIndexSpec.NO_INDEX;
private boolean preserveWS = false;
private boolean isDirty = false;
public ElementImpl() {
super(Node.ELEMENT_NODE);
}
/**
* Constructor for the ElementImpl object
*
* @param nodeName Description of the Parameter
*/
public ElementImpl(QName nodeName) {
super(Node.ELEMENT_NODE, nodeName);
this.nodeName = nodeName;
}
public ElementImpl(ElementImpl other) {
super(other);
this.children = other.children;
this.attributes = other.attributes;
this.namespaceMappings = other.namespaceMappings;
this.indexType = other.indexType;
this.position = other.position;
}
/**
* Reset this element to its initial state.
*
*/
public void clear() {
super.clear();
attributes = 0;
children = 0;
position = 0;
namespaceMappings = null;
//TODO : reset below as well ? -pb
//indexType
//preserveWS
}
public void setIndexType(int idxType) {
this.indexType = idxType;
}
public int getIndexType() {
return indexType;
}
public boolean isDirty() {
return isDirty;
}
public void setDirty(boolean dirty) {
this.isDirty = dirty;
}
public void setPosition(int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public boolean declaresNamespacePrefixes() {
if (namespaceMappings == null)
return false;
return (namespaceMappings.size() > 0);
}
public byte[] serialize() {
if (nodeId == null)
throw new RuntimeException("nodeId = null for element: " +
getQName().getStringValue());
try {
byte[] prefixData = null;
// serialize namespace prefixes declared in this element
if (declaresNamespacePrefixes()) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bout);
out.writeShort(namespaceMappings.size());
for (Iterator i = namespaceMappings.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
out.writeUTF((String) entry.getKey());
short nsId = getBroker().getSymbols().getNSSymbol((String) entry.getValue());
out.writeShort(nsId);
}
prefixData = bout.toByteArray();
}
final short id = getBroker().getSymbols().getSymbol(this);
final boolean hasNamespace = nodeName.needsNamespaceDecl();
short nsId = 0;
if (hasNamespace)
nsId = getBroker().getSymbols().getNSSymbol(nodeName.getNamespaceURI());
final byte idSizeType = Signatures.getSizeType(id);
byte signature = (byte) ((Signatures.Elem << 0x5) | idSizeType);
int prefixLen = 0;
if (hasNamespace) {
if (nodeName.getPrefix() != null && nodeName.getPrefix().length() > 0)
prefixLen = UTF8.encoded(nodeName.getPrefix());
signature |= 0x10;
}
if (isDirty)
signature |= 0x8;
final int nodeIdLen = nodeId.size();
byte[] data =
ByteArrayPool.getByteArray(
StoredNode.LENGTH_SIGNATURE_LENGTH + LENGTH_ELEMENT_CHILD_COUNT + NodeId.LENGTH_NODE_ID_UNITS +
+ nodeIdLen + LENGTH_ATTRIBUTES_COUNT
+ Signatures.getLength(idSizeType)
+ (hasNamespace ? prefixLen + 4 : 0)
+ (prefixData != null ? prefixData.length : 0)
);
int next = 0;
data[next] = signature;
next += StoredNode.LENGTH_SIGNATURE_LENGTH;
ByteConversion.intToByte(children, data, next);
next += LENGTH_ELEMENT_CHILD_COUNT;
ByteConversion.shortToByte((short) nodeId.units(), data, next);
next += NodeId.LENGTH_NODE_ID_UNITS;
nodeId.serialize(data, next);
next += nodeIdLen;
ByteConversion.shortToByte(attributes, data, next);
next += LENGTH_ATTRIBUTES_COUNT;
Signatures.write(idSizeType, id, data, next);
next += Signatures.getLength(idSizeType);
if (hasNamespace) {
ByteConversion.shortToByte(nsId, data, next);
next += LENGTH_NS_ID;
ByteConversion.shortToByte((short) prefixLen, data, next);
next += LENGTH_PREFIX_LENGTH;
if (nodeName.getPrefix() != null && nodeName.getPrefix().length() > 0)
UTF8.encode(nodeName.getPrefix(), data, next);
next += prefixLen;
}
if (prefixData != null)
System.arraycopy(prefixData, 0, data, next, prefixData.length);
return data;
} catch (IOException e) {
return null;
}
}
public static StoredNode deserialize(byte[] data,
int start,
int len,
DocumentImpl doc,
boolean pooled) {
int end = start + len;
int pos = start;
byte idSizeType = (byte) (data[pos] & 0x03);
boolean isDirty = (data[pos] & 0x8) == 0x8;
boolean hasNamespace = (data[pos] & 0x10) == 0x10;
pos += StoredNode.LENGTH_SIGNATURE_LENGTH;
int children = ByteConversion.byteToInt(data, pos);
pos += LENGTH_ELEMENT_CHILD_COUNT;
int dlnLen = ByteConversion.byteToShort(data, pos);
pos += NodeId.LENGTH_NODE_ID_UNITS;
NodeId dln = doc.getBroker().getBrokerPool().getNodeFactory().createFromData(dlnLen, data, pos);
pos += dln.size();
short attributes = ByteConversion.byteToShort(data, pos);
pos += LENGTH_ATTRIBUTES_COUNT;
short id = (short) Signatures.read(idSizeType, data, pos);
pos += Signatures.getLength(idSizeType);
short nsId = 0;
String prefix = null;
if (hasNamespace) {
nsId = ByteConversion.byteToShort(data, pos);
pos += LENGTH_NS_ID;
int prefixLen = ByteConversion.byteToShort(data, pos);
pos += LENGTH_PREFIX_LENGTH;
if (prefixLen > 0)
prefix = UTF8.decode(data, pos, prefixLen).toString();
pos += prefixLen;
}
String name = doc.getSymbols().getName(id);
String namespace = "";
if (nsId != 0)
namespace = doc.getSymbols().getNamespace(nsId);
ElementImpl node;
if (pooled)
node = (ElementImpl) NodePool.getInstance().borrowNode(Node.ELEMENT_NODE);
// node = (ElementImpl) NodeObjectPool.getInstance().borrowNode(ElementImpl.class);
else
node = new ElementImpl();
node.setNodeId(dln);
node.nodeName = doc.getSymbols().getQName(Node.ELEMENT_NODE, namespace, name, prefix);
node.children = children;
node.attributes = attributes;
node.isDirty = isDirty;
node.setOwnerDocument(doc);
//TO UNDERSTAND : why is this code here ?
if (end > pos) {
byte[] pfxData = new byte[end - pos];
System.arraycopy(data, pos, pfxData, 0, end - pos);
ByteArrayInputStream bin = new ByteArrayInputStream(pfxData);
DataInputStream in = new DataInputStream(bin);
try {
short prefixCount = in.readShort();
for (int i = 0; i < prefixCount; i++) {
prefix = in.readUTF();
nsId = in.readShort();
node.addNamespaceMapping(prefix, doc.getSymbols().getNamespace(nsId));
}
}
catch (IOException e) {
e.printStackTrace();
}
}
return node;
}
public static QName readQName(Value value, DocumentImpl document, NodeId nodeId) {
final byte[] data = value.data();
int offset = value.start();
byte idSizeType = (byte) (data[offset] & 0x03);
boolean hasNamespace = (data[offset] & 0x10) == 0x10;
offset += StoredNode.LENGTH_SIGNATURE_LENGTH;
offset += LENGTH_ELEMENT_CHILD_COUNT;
offset += NodeId.LENGTH_NODE_ID_UNITS;
offset += nodeId.size();
offset += LENGTH_ATTRIBUTES_COUNT;
short id = (short) Signatures.read(idSizeType, data, offset);
offset += Signatures.getLength(idSizeType);
short nsId = 0;
String prefix = null;
if (hasNamespace) {
nsId = ByteConversion.byteToShort(data, offset);
offset += LENGTH_NS_ID;
int prefixLen = ByteConversion.byteToShort(data, offset);
offset += LENGTH_PREFIX_LENGTH;
if (prefixLen > 0)
prefix = UTF8.decode(data, offset, prefixLen).toString();
offset += prefixLen;
}
String name = document.getSymbols().getName(id);
String namespace = "";
if (nsId != 0)
namespace = document.getSymbols().getNamespace(nsId);
return new QName(name, namespace, prefix == null ? "" : prefix);
}
public void addNamespaceMapping(String prefix, String ns) {
if (prefix == null)
return;
if (namespaceMappings == null)
namespaceMappings = new HashMap(1);
else if (namespaceMappings.containsKey(prefix))
return;
namespaceMappings.put(prefix, ns);
}
/**
* Append a child to this node. This method does not rearrange the
* node tree and is only used internally by the parser.
*
* @param child
* @throws DOMException
*/
public void appendChildInternal(StoredNode prevNode, StoredNode child) throws DOMException {
NodeId childId;
if (prevNode == null) {
childId = getNodeId().newChild();
} else {
if (prevNode.getNodeId() == null) {
LOG.warn(getQName() + " : " + prevNode.getNodeName());
}
childId = prevNode.getNodeId().nextSibling();
}
child.setNodeId(childId);
++children;
}
/**
* @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node)
*/
public Node appendChild(Node child) throws DOMException {
TransactionManager transact = getBroker().getBrokerPool().getTransactionManager();
Txn transaction = transact.beginTransaction();
NodeListImpl nl = new NodeListImpl();
nl.add(child);
try {
appendChildren(transaction, nl, 0);
getBroker().storeXMLResource(transaction, (DocumentImpl) getOwnerDocument());
return getLastChild();
} catch (Exception e) {
transact.abort(transaction);
throw new DOMException(DOMException.INVALID_STATE_ERR, e.getMessage());
}
}
public void appendAttributes(Txn transaction, NodeList attribs) throws DOMException {
NodeList duplicateAttrs = findDupAttributes(attribs);
removeAppendAttributes(transaction, duplicateAttrs, attribs);
}
private NodeList checkForAttributes(Txn transaction, NodeList nodes) throws DOMException {
NodeListImpl attribs = null;
NodeListImpl rest = null;
for (int i = 0; i < nodes.getLength(); i++) {
Node next = nodes.item(i);
if (next.getNodeType() == Node.ATTRIBUTE_NODE) {
if (!next.getNodeName().startsWith("xmlns")) {
if (attribs == null)
attribs = new NodeListImpl();
attribs.add(next);
}
} else if (attribs != null) {
if (rest == null) rest = new NodeListImpl();
rest.add(next);
}
}
if (attribs == null)
return nodes;
appendAttributes(transaction, attribs);
return rest;
}
public void appendChildren(Txn transaction, NodeList nodes, int child) throws DOMException {
// attributes are handled differently. Call checkForAttributes to extract them.
nodes = checkForAttributes(transaction, nodes);
if (nodes == null || nodes.getLength() == 0)
return;
NodePath path = getPath();
StreamListener listener = null;
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(this, path);
getBroker().getIndexController().setMode(StreamListener.STORE);
if (reindexRoot == null) {
listener = getBroker().getIndexController().getStreamListener();
} else {
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
}
if (children == 0) {
// no children: append a new child
appendChildren(transaction, nodeId.newChild(), new NodeImplRef(this), path, nodes, listener);
} else {
if (child == 1) {
Node firstChild = getFirstChild();
insertBefore(transaction, nodes, firstChild);
}
else {
if (child > 1 && child <= children) {
NodeList cl = getChildNodes();
StoredNode last = (StoredNode) cl.item(child - 2);
insertAfter(transaction, nodes, getLastNode(last));
} else {
StoredNode last = (StoredNode) getLastChild();
appendChildren(transaction, last.getNodeId().nextSibling(),
new NodeImplRef(getLastNode(last)), path, nodes, listener);
}
}
}
getBroker().updateNode(transaction, this, false);
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
getBroker().flush();
}
/**
* Internal append.
*
* @throws DOMException
*/
protected void appendChildren(Txn transaction, NodeId newNodeId, NodeImplRef last, NodePath lastPath, NodeList nodes, StreamListener listener) throws DOMException {
if (last == null || last.getNode() == null || last.getNode().getOwnerDocument() == null)
throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "invalid node");
children += nodes.getLength();
for (int i = 0; i < nodes.getLength(); i++) {
Node child = nodes.item(i);
appendChild(transaction, newNodeId, last, lastPath, child, listener);
newNodeId = newNodeId.nextSibling();
}
}
private Node appendChild(Txn transaction, NodeId newNodeId, NodeImplRef last, NodePath lastPath, Node child, StreamListener listener)
throws DOMException {
if (last == null || last.getNode() == null)
//TODO : same test as above ? -pb
throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "invalid node");
final DocumentImpl owner = (DocumentImpl)getOwnerDocument();
switch (child.getNodeType()) {
case Node.DOCUMENT_FRAGMENT_NODE :
appendChildren(transaction, newNodeId, last, lastPath, child.getChildNodes(), listener);
return null; // TODO: implement document fragments so we can return all newly appended children
case Node.ELEMENT_NODE :
// create new element
final ElementImpl elem =
new ElementImpl(
new QName(child.getLocalName() == null ? child.getNodeName() : child.getLocalName(),
child.getNamespaceURI(),
child.getPrefix())
);
elem.setNodeId(newNodeId);
elem.setOwnerDocument(owner);
final NodeListImpl ch = new NodeListImpl();
final NamedNodeMap attribs = child.getAttributes();
for (int i = 0; i < attribs.getLength(); i++) {
Attr attr = (Attr) attribs.item(i);
if (!attr.getNodeName().startsWith("xmlns")) {
ch.add(attr);
} else {
String xmlnsDecl = attr.getNodeName();
String prefix = xmlnsDecl.length()==5 ? "" : xmlnsDecl.substring(6);
elem.addNamespaceMapping(prefix,attr.getNodeValue());
}
}
NodeList cl = child.getChildNodes();
for (int i = 0; i < cl.getLength(); i++) {
Node n = cl.item(i);
if (n.getNodeType() != Node.ATTRIBUTE_NODE)
ch.add(n);
}
elem.setChildCount(ch.getLength());
elem.setAttributes((short) (elem.getAttributesCount() + attribs.getLength()));
lastPath.addComponent(elem.getQName());
// insert the node
getBroker().insertNodeAfter(transaction, last.getNode(), elem);
getBroker().indexNode(transaction, elem, lastPath);
getBroker().getIndexController().indexNode(transaction, elem, lastPath, listener);
//getBroker().getIndexController().startElement(transaction, elem, lastPath, listener);
elem.setChildCount(0);
last.setNode(elem);
//process child nodes
elem.appendChildren(transaction, newNodeId.newChild(), last, lastPath, ch, listener);
getBroker().endElement(elem, lastPath, null);
getBroker().getIndexController().endElement(transaction, elem, lastPath, listener);
lastPath.removeLastComponent();
return elem;
case Node.TEXT_NODE :
final TextImpl text = new TextImpl(newNodeId, ((Text) child).getData());
text.setOwnerDocument(owner);
// insert the node
getBroker().insertNodeAfter(transaction, last.getNode(), text);
getBroker().indexNode(transaction, text, lastPath);
getBroker().getIndexController().indexNode(transaction, text, lastPath, listener);
//getBroker().getIndexController().characters(transaction, text, lastPath, listener);
last.setNode(text);
return text;
case Node.CDATA_SECTION_NODE :
final CDATASectionImpl cdata = new CDATASectionImpl(newNodeId, ((CDATASection) child).getData());
cdata.setOwnerDocument(owner);
// insert the node
getBroker().insertNodeAfter(transaction, last.getNode(), cdata);
getBroker().indexNode(transaction, cdata, lastPath);
last.setNode(cdata);
return cdata;
case Node.ATTRIBUTE_NODE:
Attr attr = (Attr) child;
String ns = attr.getNamespaceURI();
String prefix = (Namespaces.XML_NS.equals(ns) ? "xml" : attr.getPrefix());
String name = attr.getLocalName();
if (name == null) name = attr.getName();
QName attrName = new QName(name, ns, prefix);
final AttrImpl attrib = new AttrImpl(attrName, attr.getValue());
attrib.setNodeId(newNodeId);
attrib.setOwnerDocument(owner);
if (ns != null && attrName.compareTo(Namespaces.XML_ID_QNAME) == Constants.EQUAL) {
// an xml:id attribute. Normalize the attribute and set its type to ID
attrib.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attrib.getValue())));
attrib.setType(AttrImpl.ID);
} else
attrName.setNameType(ElementValue.ATTRIBUTE);
getBroker().insertNodeAfter(transaction, last.getNode(), attrib);
getBroker().indexNode(transaction, attrib, lastPath);
getBroker().getIndexController().indexNode(transaction, attrib, lastPath, listener);
//getBroker().getIndexController().attribute(transaction, attrib, lastPath, listener);
last.setNode(attrib);
return attrib;
case Node.COMMENT_NODE:
final CommentImpl comment = new CommentImpl(((Comment) child).getData());
comment.setNodeId(newNodeId);
comment.setOwnerDocument(owner);
// insert the node
getBroker().insertNodeAfter(transaction, last.getNode(), comment);
getBroker().indexNode(transaction, comment, lastPath);
last.setNode(comment);
return comment;
case Node.PROCESSING_INSTRUCTION_NODE:
final ProcessingInstructionImpl pi =
new ProcessingInstructionImpl(newNodeId,
((ProcessingInstruction) child).getTarget(),
((ProcessingInstruction) child).getData());
pi.setOwnerDocument(owner);
// insert the node
getBroker().insertNodeAfter(transaction, last.getNode(), pi);
getBroker().indexNode(transaction, pi, lastPath);
last.setNode(pi);
return pi;
default :
throw new DOMException(DOMException.INVALID_MODIFICATION_ERR,
"unknown node type: "
+ child.getNodeType()
+ " "
+ child.getNodeName());
}
}
public short getAttributesCount() {
return attributes;
}
/**
* Set the attributes that belong to this node.
*
* @param attribNum The new attributes value
*/
public void setAttributes(short attribNum) {
attributes = attribNum;
}
/**
* @see org.w3c.dom.Element#getAttribute(java.lang.String)
*/
public String getAttribute(String name) {
Attr attr = findAttribute(name);
return attr != null ? attr.getValue() : "";
}
/**
* @see org.w3c.dom.Element#getAttributeNS(java.lang.String, java.lang.String)
*/
public String getAttributeNS(String namespaceURI, String localName) {
Attr attr = findAttribute(new QName(localName, namespaceURI));
return attr != null ? attr.getValue() : "";
}
/**
* @see org.w3c.dom.Element#getAttributeNode(java.lang.String)
*/
public Attr getAttributeNode(String name) {
return findAttribute(name);
}
/**
* @see org.w3c.dom.Element#getAttributeNodeNS(java.lang.String, java.lang.String)
*/
public Attr getAttributeNodeNS(String namespaceURI, String localName) {
return findAttribute(new QName(localName, namespaceURI));
}
/**
* @see org.w3c.dom.Node#getAttributes()
*/
public NamedNodeMap getAttributes() {
NamedNodeMapImpl map = new NamedNodeMapImpl();
if (getAttributesCount() > 0) {
final Iterator iterator = getBroker().getNodeIterator(this);
iterator.next();
final int ccount = getChildCount();
for (int i = 0; i < ccount; i++) {
StoredNode next = (StoredNode) iterator.next();
if (next.getNodeType() != Node.ATTRIBUTE_NODE)
break;
map.setNamedItem(next);
}
}
if(declaresNamespacePrefixes()) {
for(Iterator i = namespaceMappings.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
String prefix = entry.getKey().toString();
String ns = entry.getValue().toString();
QName attrName = new QName(prefix, Namespaces.XMLNS_NS, "xmlns");
AttrImpl attr = new AttrImpl(attrName, ns);
map.setNamedItem(attr);
}
}
return map;
}
private AttrImpl findAttribute(String qname) {
final Iterator iterator = getBroker().getNodeIterator(this);
iterator.next();
return findAttribute(qname, iterator, this);
}
private AttrImpl findAttribute(String qname, Iterator iterator, StoredNode current) {
final int ccount = current.getChildCount();
StoredNode next;
for (int i = 0; i < ccount; i++) {
next = (StoredNode) iterator.next();
if (next.getNodeType() != Node.ATTRIBUTE_NODE)
break;
if (next.getNodeName().equals(qname))
return (AttrImpl) next;
}
return null;
}
private AttrImpl findAttribute(QName qname) {
final Iterator iterator = getBroker().getNodeIterator(this);
iterator.next();
return findAttribute(qname, iterator, this);
}
private AttrImpl findAttribute(QName qname, Iterator iterator, StoredNode current) {
final int ccount = current.getChildCount();
for (int i = 0; i < ccount; i++) {
StoredNode next = (StoredNode) iterator.next();
if (next.getNodeType() != Node.ATTRIBUTE_NODE)
break;
if (next.getQName().equalsSimple(qname))
return (AttrImpl) next;
}
return null;
}
/**
* Returns a list of all attribute nodes in attrs that are already present
* in the current element.
*
* @param attrs
* @return The attributes list
* @throws DOMException
*/
private NodeList findDupAttributes(NodeList attrs) throws DOMException {
NodeListImpl dupList = null;
NamedNodeMap map = getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
// Workaround: xerces sometimes returns null for getLocalName() !!!!
String localName = attr.getLocalName();
if (localName == null)
localName = attr.getNodeName();
Node duplicate = map.getNamedItemNS(attr.getNamespaceURI(), localName);
if (duplicate != null) {
if (dupList == null)
dupList = new NodeListImpl();
dupList.add(duplicate);
}
}
return dupList;
}
/**
* @see org.exist.dom.NodeImpl#getChildCount()
*/
public int getChildCount() {
return children;
}
public NodeList getChildNodes() {
final NodeListImpl childList = new NodeListImpl(1);
try {
for (EmbeddedXMLStreamReader reader = ownerDocument.getBroker().getXMLStreamReader(this, true); reader.hasNext(); ) {
int status = reader.next();
if (status != XMLStreamReader.END_ELEMENT) {
if (((NodeId) reader.getProperty(EmbeddedXMLStreamReader.PROPERTY_NODE_ID)).isChildOf(nodeId))
childList.add(reader.getNode());
}
}
} catch (IOException e) {
LOG.warn("Internal error while reading child nodes: " + e.getMessage(), e);
} catch (XMLStreamException e) {
LOG.warn("Internal error while reading child nodes: " + e.getMessage(), e);
}
// accept(new NodeVisitor() {
// public boolean visit(StoredNode node) {
// if(node.nodeId.isChildOf(nodeId))
// childList.add(node);
// return true;
return childList;
}
/**
* @see org.w3c.dom.Element#getElementsByTagName(java.lang.String)
*/
public NodeList getElementsByTagName(String tagName) {
QName qname = new QName(tagName, "", null);
return (NodeSet)((DocumentImpl)getOwnerDocument()).findElementsByTagName(this, qname);
}
/**
* @see org.w3c.dom.Element#getElementsByTagNameNS(java.lang.String, java.lang.String)
*/
public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
QName qname = new QName(localName, namespaceURI, null);
return (NodeSet)((DocumentImpl)getOwnerDocument()).findElementsByTagName(this, qname);
}
/**
* @see org.w3c.dom.Node#getFirstChild()
*/
public Node getFirstChild() {
if (!hasChildNodes() || getChildCount() == getAttributesCount())
return null;
final Iterator iterator = getBroker().getNodeIterator(this);
iterator.next();
StoredNode next;
for (int i = 0; i < getChildCount(); i++) {
next = (StoredNode) iterator.next();
if (next.getNodeType() != Node.ATTRIBUTE_NODE)
return next;
}
return null;
}
public Node getLastChild() {
if (!hasChildNodes())
return null;
Node node = null;
if (!isDirty) {
NodeId child = nodeId.getChild(children);
node = getBroker().objectWith(ownerDocument, child);
}
if (node == null) {
NodeList cl = getChildNodes();
return cl.item(cl.getLength() - 1);
}
return node;
}
/**
* @see org.w3c.dom.Element#getTagName()
*/
public String getTagName() {
return nodeName.getStringValue();
}
/**
* @see org.w3c.dom.Element#hasAttribute(java.lang.String)
*/
public boolean hasAttribute(String name) {
return findAttribute(name) != null;
}
/**
* @see org.w3c.dom.Element#hasAttributeNS(java.lang.String, java.lang.String)
*/
public boolean hasAttributeNS(String namespaceURI, String localName) {
return findAttribute(new QName(localName, namespaceURI)) != null;
}
/**
* @see org.w3c.dom.Node#hasAttributes()
*/
public boolean hasAttributes() {
return (getAttributesCount() > 0);
}
/**
* @see org.w3c.dom.Node#hasChildNodes()
*/
public boolean hasChildNodes() {
return children > 0;
}
/**
* @see org.w3c.dom.Node#getNodeValue()
*/
public String getNodeValue() /*throws DOMException*/ {
//TODO : parametrize the boolea value ?
return getBroker().getNodeValue(this, false);
//throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "getNodeValue() not implemented on class " + getClass().getName());
}
/**
* @see org.w3c.dom.Element#removeAttribute(java.lang.String)
*/
public void removeAttribute(String name) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "removeAttribute(String name) not implemented on class " + getClass().getName());
}
/**
* @see org.w3c.dom.Element#removeAttributeNS(java.lang.String, java.lang.String)
*/
public void removeAttributeNS(String namespaceURI, String name) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "removeAttributeNS(String namespaceURI, String name) not implemented on class " + getClass().getName());
}
public Attr removeAttributeNode(Attr oldAttr) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "removeAttributeNode(Attr oldAttr) not implemented on class " + getClass().getName());
}
public void setAttribute(String name, String value) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setAttribute(String name, String value) not implemented on class " + getClass().getName());
}
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setAttributeNS(String namespaceURI, String qualifiedName, String value) not implemented on class " + getClass().getName());
}
public Attr setAttributeNode(Attr newAttr) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setAttributeNode(Attr newAttr) not implemented on class " + getClass().getName());
}
public Attr setAttributeNodeNS(Attr newAttr) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setAttributeNodeNS(Attr newAttr) not implemented on class " + getClass().getName());
}
public void setChildCount(int count) {
children = count;
}
public void setNamespaceMappings(Map map) {
namespaceMappings = new HashMap(map);
String ns;
for (Iterator i = namespaceMappings.values().iterator(); i.hasNext();) {
ns = (String) i.next();
getBroker().getSymbols().getNSSymbol(ns);
}
}
public Iterator getPrefixes() {
return namespaceMappings.keySet().iterator();
}
public String getNamespaceForPrefix(String prefix) {
return (String) namespaceMappings.get(prefix);
}
public int getPrefixCount() {
return namespaceMappings.size();
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return toString(true);
}
public String toString(boolean top) {
return toString(top, new TreeSet());
}
/**
* Method toString.
*
*/
public String toString(boolean top, TreeSet namespaces) {
StringBuffer buf = new StringBuffer();
StringBuffer attributes = new StringBuffer();
StringBuffer children = new StringBuffer();
buf.append('<');
buf.append(nodeName);
//Remove false to have a verbose output
if (top && false) {
buf.append(" xmlns:exist=\""+ Namespaces.EXIST_NS + "\"");
buf.append(" exist:id=\"");
buf.append(getNodeId());
buf.append("\" exist:document=\"");
buf.append(((DocumentImpl)getOwnerDocument()).getFileURI());
buf.append("\"");
}
if (declaresNamespacePrefixes()) {
// declare namespaces used by this element
Map.Entry entry;
String namespace, prefix;
for (Iterator i = namespaceMappings.entrySet().iterator(); i.hasNext();) {
entry = (Map.Entry) i.next();
prefix = (String) entry.getKey();
namespace = (String) entry.getValue();
if (prefix.length() == 0) {
buf.append(" xmlns=\"");
//buf.append(namespace);
buf.append("...");
}
else {
buf.append(" xmlns:");
buf.append(prefix);
buf.append("=\"");
//buf.append(namespace);
buf.append("...");
}
buf.append("\" ");
namespaces.add(namespace);
}
}
if (nodeName.getNamespaceURI().length() > 0
&& (!namespaces.contains(nodeName.getNamespaceURI()))) {
buf.append(" xmlns:").append(nodeName.getPrefix()).append("=\"");
buf.append(nodeName.getNamespaceURI());
buf.append("\" ");
}
NodeList childNodes = getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
switch (child.getNodeType()) {
case Node.ATTRIBUTE_NODE:
attributes.append(' ');
attributes.append(((Attr) child).getName());
attributes.append("=\"");
attributes.append(escapeXml(child));
attributes.append("\"");
break;
case Node.ELEMENT_NODE:
children.append(((ElementImpl) child).toString(false, namespaces));
break;
default :
children.append(child.toString());
}
}
if (attributes.length() > 0)
buf.append(attributes.toString());
if (childNodes.getLength() > 0) {
buf.append(">");
buf.append(children.toString());
buf.append("</");
buf.append(nodeName);
buf.append(">");
}
else
buf.append("/>");
return buf.toString();
}
/**
* @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node)
*/
public Node insertBefore(Node newChild, Node refChild) throws DOMException {
if (refChild == null)
return appendChild(newChild);
if (!(refChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
NodeListImpl nl = new NodeListImpl();
nl.add(newChild);
TransactionManager transact = getBroker().getBrokerPool().getTransactionManager();
Txn transaction = transact.beginTransaction();
try {
insertBefore(transaction, nl, refChild);
getBroker().storeXMLResource(transaction, (DocumentImpl) getOwnerDocument());
transact.commit(transaction);
return refChild.getPreviousSibling();
} catch(TransactionException e) {
transact.abort(transaction);
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, e.getMessage());
}
}
/**
* Insert a list of nodes at the position before the reference
* child.
*/
public void insertBefore(Txn transaction, NodeList nodes, Node refChild) throws DOMException {
if (refChild == null) {
//TODO : use NodeImpl.UNKNOWN_NODE_IMPL_GID ? -pb
appendChildren(transaction, nodes, -1);
return;
}
if (!(refChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
NodePath path = getPath();
StreamListener listener = null;
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(this, path, true);
getBroker().getIndexController().setMode(StreamListener.STORE);
if (reindexRoot == null) {
listener = getBroker().getIndexController().getStreamListener();
} else {
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
}
StoredNode following = (StoredNode) refChild;
StoredNode previous = (StoredNode) following.getPreviousSibling();
if (previous == null)
appendChildren(transaction, following.getNodeId().insertBefore(),
new NodeImplRef(this), path, nodes, listener);
else {
NodeId newId = previous.getNodeId().insertNode(following.getNodeId());
appendChildren(transaction, newId, new NodeImplRef(getLastNode(previous)),
path, nodes, listener);
}
setDirty(true);
getBroker().updateNode(transaction, this, true);
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
getBroker().flush();
}
/**
* Insert a list of nodes at the position following the reference
* child.
*/
public void insertAfter(Txn transaction, NodeList nodes, Node refChild) throws DOMException {
if (refChild == null) {
//TODO : use NodeImpl.UNKNOWN_NODE_IMPL_GID ? -pb
appendChildren(null, nodes, -1);
return;
}
if (!(refChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type: ");
NodePath path = getPath();
StreamListener listener = null;
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(this, path, true);
getBroker().getIndexController().setMode(StreamListener.STORE);
if (reindexRoot == null) {
listener = getBroker().getIndexController().getStreamListener();
} else {
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
}
StoredNode previous = (StoredNode) refChild;
StoredNode following = (StoredNode) previous.getNextSibling();
NodeId newNodeId = previous.getNodeId().insertNode(following == null ? null : following.getNodeId());
appendChildren(transaction, newNodeId,
new NodeImplRef(getLastNode(previous)), path, nodes, listener);
setDirty(true);
getBroker().updateNode(transaction, this, true);
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
getBroker().flush();
}
/**
* Update the contents of this element. The passed list of nodes
* becomes the new content.
*
* @param newContent
* @throws DOMException
*/
public void update(Txn transaction, NodeList newContent) throws DOMException {
final NodePath path = getPath();
// remove old child nodes
NodeList nodes = getChildNodes();
StreamListener listener = null;
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(this, path, true);
getBroker().getIndexController().setMode(StreamListener.REMOVE_SOME_NODES);
if (reindexRoot == null) {
listener = getBroker().getIndexController().getStreamListener();
} else {
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.REMOVE_SOME_NODES);
}
// TODO: fix once range index has been moved to new architecture
StoredNode valueReindexRoot = getBroker().getValueIndex().getReindexRoot(this, path);
getBroker().getValueIndex().reindex(valueReindexRoot);
StoredNode last = this;
int i = nodes.getLength();
for (; i > 0; i
StoredNode child = (StoredNode) nodes.item(i - 1);
if (child.getNodeType() == Node.ATTRIBUTE_NODE) {
last = child;
break;
}
if (child.getNodeType() == Node.ELEMENT_NODE)
path.addComponent(child.getQName());
getBroker().removeAllNodes(transaction, child, path, listener);
if (child.getNodeType() == Node.ELEMENT_NODE)
path.removeLastComponent();
}
getBroker().getIndexController().flush();
getBroker().getIndexController().setMode(StreamListener.STORE);
getBroker().getIndexController().getStreamListener();
getBroker().endRemove(transaction);
children = i;
NodeId newNodeId = last == this ? nodeId.newChild() : last.nodeId.nextSibling();
// append new content
appendChildren(transaction, newNodeId, new NodeImplRef(last), path, newContent, listener);
getBroker().updateNode(transaction, this, false);
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
getBroker().getValueIndex().reindex(valueReindexRoot);
getBroker().flush();
}
/**
* Update a child node. This method will only update the child node
* but not its potential descendant nodes.
*
* @param oldChild
* @param newChild
* @throws DOMException
*/
public StoredNode updateChild(Txn transaction, Node oldChild, Node newChild) throws DOMException {
if (!(oldChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
if (!(newChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
StoredNode oldNode = (StoredNode) oldChild;
StoredNode newNode = (StoredNode) newChild;
if (!oldNode.nodeId.getParentId().equals(nodeId))
throw new DOMException(DOMException.NOT_FOUND_ERR,
"node is not a child of this element");
if (newNode.getNodeType() == Node.ATTRIBUTE_NODE) {
if (newNode.getQName().equalsSimple(Namespaces.XML_ID_QNAME)) {
// an xml:id attribute. Normalize the attribute and set its type to ID
AttrImpl attr = (AttrImpl) newNode;
attr.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attr.getValue())));
attr.setType(AttrImpl.ID);
}
}
StoredNode previousNode = (StoredNode) oldNode.getPreviousSibling();
if (previousNode == null)
previousNode = this;
else
previousNode = getLastNode(previousNode);
final NodePath currentPath = getPath();
final NodePath oldPath = oldNode.getPath(currentPath);
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
// check if the change affects any ancestor nodes, which then need to be reindexed later
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(oldNode, oldPath);
// Remove indexes
if (reindexRoot == null)
reindexRoot = oldNode;
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.REMOVE_SOME_NODES);
// TODO: fix once range index has been moved to new architecture
StoredNode valueReindexRoot = getBroker().getValueIndex().getReindexRoot(this, oldPath);
getBroker().getValueIndex().reindex(valueReindexRoot);
// Remove the actual node data
getBroker().removeNode(transaction, oldNode, oldPath, null);
getBroker().endRemove(transaction);
newNode.nodeId = oldNode.nodeId;
// Reinsert the new node data
getBroker().insertNodeAfter(transaction, previousNode, newNode);
final NodePath path = newNode.getPath(currentPath);
getBroker().indexNode(transaction, newNode, path);
if (newNode.getNodeType() == Node.ELEMENT_NODE)
getBroker().endElement(newNode, path, null);
getBroker().updateNode(transaction, this, true);
// Recreate indexes on ancestor nodes
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
getBroker().getValueIndex().reindex(valueReindexRoot);
getBroker().flush();
return newNode;
}
/**
* @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node)
*/
public Node removeChild(Txn transaction, Node oldChild) throws DOMException {
if (!(oldChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
final StoredNode oldNode = (StoredNode) oldChild;
if (!oldNode.nodeId.getParentId().equals(nodeId))
throw new DOMException(DOMException.NOT_FOUND_ERR,
"node is not a child of this element");
NodePath oldPath = oldNode.getPath();
StreamListener listener = null;
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(oldNode, oldPath);
getBroker().getIndexController().setMode(StreamListener.REMOVE_SOME_NODES);
if (reindexRoot == null) {
listener = getBroker().getIndexController().getStreamListener();
} else {
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.REMOVE_SOME_NODES);
}
getBroker().removeAllNodes(transaction, oldNode, oldPath, listener);
--children;
if (oldChild.getNodeType() == Node.ATTRIBUTE_NODE)
--attributes;
getBroker().endRemove(transaction);
setDirty(true);
getBroker().updateNode(transaction, this, false);
getBroker().flush();
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
return oldNode;
}
public void removeAppendAttributes(Txn transaction, NodeList removeList, NodeList appendList) {
try {
if (removeList != null) {
try {
for (int i=0; i<removeList.getLength(); i++) {
Node oldChild = removeList.item(i);
if (!(oldChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
StoredNode old = (StoredNode) oldChild;
if (!old.nodeId.isChildOf(nodeId))
throw new DOMException(DOMException.NOT_FOUND_ERR, "node " + old.nodeId.getParentId() +
" is not a child of element " + nodeId);
final NodePath oldPath = old.getPath();
// remove old custom indexes
getBroker().getIndexController().reindex(transaction, old, StreamListener.REMOVE_SOME_NODES);
getBroker().removeNode(transaction, old, oldPath, null);
children
attributes
}
} finally {
getBroker().endRemove(transaction);
}
}
NodePath path = getPath();
getBroker().getIndexController().setDocument(ownerDocument, StreamListener.STORE);
StreamListener listener = getBroker().getIndexController().getStreamListener();
if (children == 0) {
appendChildren(transaction, nodeId.newChild(),
new NodeImplRef(this), path, appendList, listener);
} else {
if (attributes == 0) {
StoredNode firstChild = (StoredNode) getFirstChild();
NodeId newNodeId = firstChild.nodeId.insertBefore();
appendChildren(transaction, newNodeId, new NodeImplRef(this), path, appendList, listener);
} else {
AttribVisitor visitor = new AttribVisitor();
accept(visitor);
NodeId firstChildId = visitor.firstChild == null ? null : visitor.firstChild.nodeId;
NodeId newNodeId = visitor.lastAttrib.nodeId.insertNode(firstChildId);
appendChildren(transaction, newNodeId, new NodeImplRef(visitor.lastAttrib),
path, appendList, listener);
}
setDirty(true);
}
attributes += appendList.getLength();
} finally {
getBroker().updateNode(transaction, this, true);
getBroker().flush();
}
}
private class AttribVisitor implements NodeVisitor {
private StoredNode lastAttrib = null;
private StoredNode firstChild = null;
public boolean visit(StoredNode node) {
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
lastAttrib = node;
} else if (node.nodeId.isChildOf(ElementImpl.this.nodeId)) {
firstChild = node;
return false;
}
return true;
}
}
/**
* Replaces the oldNode with the newChild
*
* @param transaction
* @param newChild
* @param oldChild
*
* @return The new node (this differs from the {@link org.w3c.dom.Node#replaceChild(Node, Node)} specification)
*
* @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node)
*/
public Node replaceChild(Txn transaction, Node newChild, Node oldChild) throws DOMException {
if (!(oldChild instanceof StoredNode))
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "wrong node type");
StoredNode oldNode = (StoredNode) oldChild;
if (!oldNode.nodeId.getParentId().equals(nodeId))
throw new DOMException(DOMException.NOT_FOUND_ERR,
"node is not a child of this element");
StoredNode previous = (StoredNode) oldNode.getPreviousSibling();
if (previous == null)
previous = this;
else
previous = getLastNode(previous);
NodePath oldPath = oldNode.getPath();
StreamListener listener = null;
//May help getReindexRoot() to make some useful things
getBroker().getIndexController().setDocument(ownerDocument);
StoredNode reindexRoot = getBroker().getIndexController().getReindexRoot(oldNode, oldPath);
getBroker().getIndexController().setMode(StreamListener.REMOVE_SOME_NODES);
if (reindexRoot == null) {
listener = getBroker().getIndexController().getStreamListener();
} else {
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.REMOVE_SOME_NODES);
}
getBroker().removeAllNodes(transaction, oldNode, oldPath, listener);
getBroker().endRemove(transaction);
getBroker().flush();
getBroker().getIndexController().setMode(StreamListener.STORE);
listener = getBroker().getIndexController().getStreamListener();
Node newNode = appendChild(transaction, oldNode.nodeId, new NodeImplRef(previous), getPath(), newChild, listener);
// reindex if required
final DocumentImpl owner = (DocumentImpl)getOwnerDocument();
getBroker().storeXMLResource(transaction, owner);
getBroker().updateNode(transaction, this, false);
getBroker().getIndexController().reindex(transaction, reindexRoot, StreamListener.STORE);
getBroker().flush();
//return oldChild; // method is spec'd to return the old child, even though that's probably useless in this case
return newNode; //returning the newNode is more sensible than returning the oldNode
}
private String escapeXml(Node child) {
final String str = ((Attr) child).getValue();
StringBuffer buffer = null;
String entity = null;
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
switch (ch) {
case '"':
entity = """;
break;
case '<':
entity = "<";
break;
case '>':
entity = ">";
break;
case '\'':
entity = "'";
break;
default :
entity = null;
break;
}
if (buffer == null) {
if (entity != null) {
buffer = new StringBuffer(str.length() + 20);
buffer.append(str.substring(0, i));
buffer.append(entity);
}
}
else {
if (entity == null)
buffer.append(ch);
else
buffer.append(entity);
}
}
return (buffer == null) ? str : buffer.toString();
}
public void setPreserveSpace(boolean preserveWS) {
this.preserveWS = preserveWS;
}
public boolean preserveSpace() {
return preserveWS;
}
/** ? @see org.w3c.dom.Element#getSchemaTypeInfo()
*/
public TypeInfo getSchemaTypeInfo() {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "getSchemaTypeInfo() not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Element#setIdAttribute(java.lang.String, boolean)
*/
public void setIdAttribute(String name, boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setIdAttribute(String name, boolean isId) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Element#setIdAttributeNS(java.lang.String, java.lang.String, boolean)
*/
public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setIdAttributeNS(String namespaceURI, String localName, boolean isId) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Element#setIdAttributeNode(org.w3c.dom.Attr, boolean)
*/
public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setIdAttributeNode(Attr idAttr, boolean isId) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#getBaseURI()
*/
public String getBaseURI() {
String baseURI = getAttributeNS(Namespaces.XML_NS, "base");
if ( baseURI == null) {
baseURI = "";
}
StoredNode parent = null;
Node test = getParentNode();
if (!(test instanceof DocumentImpl)) {
parent = (StoredNode) test;
}
while (parent != null && parent.getBaseURI() != null) {
if ("".equals(baseURI)) {
baseURI = parent.getBaseURI();
} else {
baseURI = parent.getBaseURI() + "/" + baseURI;
}
test = parent.getParentNode();
if (test instanceof DocumentImpl) {
return baseURI;
} else {
parent = (StoredNode) test;
}
}
if ("".equals(baseURI)) {
baseURI = getDocument().getBaseURI();
}
return baseURI;
}
/** ? @see org.w3c.dom.Node#compareDocumentPosition(org.w3c.dom.Node)
*/
public short compareDocumentPosition(Node other) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "compareDocumentPosition(Node other) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#getTextContent()
*/
public String getTextContent() throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "getTextContent() not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#setTextContent(java.lang.String)
*/
public void setTextContent(String textContent) throws DOMException {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setTextContent(String textContent) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#isSameNode(org.w3c.dom.Node)
*/
public boolean isSameNode(Node other) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "isSameNode(Node other) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#lookupPrefix(java.lang.String)
*/
public String lookupPrefix(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "lookupPrefix(String namespaceURI) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#isDefaultNamespace(java.lang.String)
*/
public boolean isDefaultNamespace(String namespaceURI) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "isDefaultNamespace(String namespaceURI) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#lookupNamespaceURI(java.lang.String)
*/
public String lookupNamespaceURI(String prefix) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "lookupNamespaceURI(String prefix) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#isEqualNode(org.w3c.dom.Node)
*/
public boolean isEqualNode(Node arg) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "isEqualNode(Node arg) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#getFeature(java.lang.String, java.lang.String)
*/
public Object getFeature(String feature, String version) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "getFeature(String feature, String version) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#setUserData(java.lang.String, java.lang.Object, org.w3c.dom.UserDataHandler)
*/
public Object setUserData(String key, Object data, UserDataHandler handler) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "setUserData(String key, Object data, UserDataHandler handler) not implemented on class " + getClass().getName());
}
/** ? @see org.w3c.dom.Node#getUserData(java.lang.String)
*/
public Object getUserData(String key) {
throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "getUserData(String key) not implemented on class " + getClass().getName());
}
public boolean accept(Iterator iterator, NodeVisitor visitor) {
if (!visitor.visit(this))
return false;
if (hasChildNodes()) {
final int ccount = getChildCount();
StoredNode next;
for (int i = 0; i < ccount; i++) {
next = (StoredNode) iterator.next();
if (!next.accept(iterator, visitor))
return false;
}
}
return true;
}
}
|
package org.exist.xquery;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.exist.Database;
import org.exist.storage.DBBroker;
import org.exist.xquery.value.Sequence;
/**
* XQuery profiling output. Profiling information is written to a
* logger. The profiler can be enabled/disabled and configured
* via an XQuery pragma or "declare option" expression. Example:
*
* <pre>declare option exist:profiling "enabled=yes verbosity=10 logger=profiler";</pre>
*
* @author wolf
*
*/
public class Profiler {
/** value for Verbosity property: basic profiling : just elapsed time */
public static int TIME = 1;
/** value for Verbosity property: For optimizations */
public static int OPTIMIZATIONS = 2;
/** For computations that will trigger further optimizations */
public static int OPTIMIZATION_FLAGS = 3;
/** Indicates the dependencies of the expression */
public static int DEPENDENCIES = 4;
/** An abstract level for viewing the expression's context sequence/item */
public static int START_SEQUENCES = 4;
/** Just returns the number of items in the sequence */
public static int ITEM_COUNT = 5;
/** For a truncated string representation of the context sequence (TODO) */
public static int SEQUENCE_PREVIEW = 6;
/** For a full representation of the context sequence (TODO) */
public static int SEQUENCE_DUMP = 8;
public static String CONFIG_PROPERTY_TRACELOG = "xquery.profiling.tracelog";
/**
* The logger where all output goes.
*/
private Logger log = Logger.getLogger("xquery.profiling");
private Stack<ProfiledExpr> stack = new Stack<ProfiledExpr>();
private final StringBuilder buf = new StringBuilder(64);
private boolean enabled = false;
private boolean logEnabled = false;
private int verbosity = 0;
private PerformanceStats stats;
private long queryStart = 0;
private Database db;
public Profiler(Database db) {
this.db = db;
this.stats = new PerformanceStats(db);
}
/**
* Configure the profiler from an XQuery pragma.
* Parameters are:
*
* <ul>
* <li><strong>enabled</strong>: yes|no.</li>
* <li><strong>logger</strong>: name of the logger to use.</li>
* <li><strong>verbosity</strong>: integer value > 0. 1 does only output function calls.</li>
* </ul>
* @param pragma
*/
public final void configure(Option pragma) {
String options[] = pragma.tokenizeContents();
String params[];
for (int i = 0; i < options.length; i++) {
params = Option.parseKeyValuePair(options[i]);
if (params != null) {
if (params[0].equals("trace")) {
stats.setEnabled(true);
} else if (params[0].equals("tracelog")) {
logEnabled = params[1].equals("yes");
} else if (params[0].equals("logger")) {
log = Logger.getLogger(params[1]);
} else if (params[0].equals("enabled")) {
enabled = params[1].equals("yes");
} else if ("verbosity".equals(params[0])) {
try {
verbosity = Integer.parseInt(params[1]);
} catch (NumberFormatException e) {
log.warn( "invalid value for verbosity: " +
"should be an integer between 0 and " +
SEQUENCE_DUMP );
}
}
}
}
if (verbosity == 0)
enabled=false;
}
/**
* Is profiling enabled?
*
* @return True if profiling is enabled
*/
public final boolean isEnabled() {
return enabled;
}
public final boolean isLogEnabled() {
DBBroker broker = db.getActiveBroker();
Boolean globalProp = (Boolean) broker.getConfiguration().getProperty(CONFIG_PROPERTY_TRACELOG);
return logEnabled || (globalProp != null && globalProp.booleanValue());
}
public final void setLogEnabled(boolean enabled) {
logEnabled = enabled;
}
public final boolean traceFunctions() {
return stats.isEnabled() || isLogEnabled();
}
/**
* @return the verbosity of the profiler.
*/
public final int verbosity() {
return verbosity;
}
public final void traceQueryStart() {
queryStart = System.currentTimeMillis();
}
public final void traceQueryEnd(XQueryContext context) {
stats.recordQuery(context.getSourceKey(), (System.currentTimeMillis() - queryStart));
}
public final void traceFunctionStart(Function function) {
if (isLogEnabled()) {
log.trace(String.format("ENTER %-25s", function.getSignature().getName()));
}
}
public final void traceFunctionEnd(Function function, long elapsed) {
if (stats.isEnabled()) {
String source;
if (function instanceof InternalFunctionCall)
source = ((InternalFunctionCall) function).getFunction().getClass().getName();
else
source = function.getContext().getSourceKey();
source = String.format("%s [%d:%d]", source, function.getLine(), function.getColumn());
stats.recordFunctionCall(function.getSignature().getName(), source, elapsed);
}
if (isLogEnabled()) {
log.trace(String.format("EXIT %-25s %10d ms", function.getSignature().getName(), elapsed));
}
}
public final void traceIndexUsage(XQueryContext context, String indexType, Expression expression, int mode, long elapsed) {
stats.recordIndexUse(expression, indexType, context.getSourceKey(), mode, elapsed);
}
private void save() {
if (db != null) {
db.getPerformanceStats().merge(stats);
}
}
/**
* Called by an expression to indicate the start of an operation.
* The profiler registers the start time.
*
* @param expr the expression.
*/
public final void start(Expression expr) {
start(expr, null);
}
/**
* Called by an expression to indicate the start of an operation.
* The profiler registers the start time.
*
* @param expr the expression.
* @param message if not null, contains an optional message to print in the log.
*/
public final void start(Expression expr, String message) {
if (!enabled)
return;
if (stack.size() == 0) {
log.debug("QUERY START");
}
buf.setLength(0);
for (int i = 0; i < stack.size(); i++)
buf.append('\t');
ProfiledExpr e = new ProfiledExpr(expr);
stack.push(e);
buf.append("START\t");
printPosition(e.expr);
buf.append(expr.toString());
log.debug(buf.toString());
if (message != null && !"".equals(message)) {
buf.setLength(0);
for (int i = 0; i < stack.size(); i++)
buf.append('\t');
buf.append("MSG\t");
buf.append(message);
buf.append("\t");
printPosition(e.expr);
buf.append(expr.toString());
log.debug(buf.toString());
}
}
/**
* Called by an expression to indicate the end of an operation.
* The profiler computes the elapsed time.
*
* @param expr the expression.
* @param message required: a message to be printed to the log.
*/
public final void end(Expression expr, String message, Sequence result) {
if (!enabled)
return;
try {
ProfiledExpr e = stack.pop();
if (e.expr != expr) {
log.warn("Error: the object passed to end() does not correspond to the expression on top of the stack.");
stack.clear();
return;
}
long elapsed = System.currentTimeMillis() - e.start;
if (message != null && !"".equals(message)) {
buf.setLength(0);
for (int i = 0; i < stack.size(); i++)
buf.append('\t');
buf.append("MSG\t");
buf.append(message);
buf.append("\t");
printPosition(e.expr);
buf.append(expr.toString());
log.debug(buf.toString());
}
if (verbosity > START_SEQUENCES) {
buf.setLength(0);
for (int i = 0; i < stack.size(); i++)
buf.append('\t');
buf.append("RESULT\t");
/* if (verbosity >= SEQUENCE_DUMP)
buf.append(result.toString());
else if (verbosity >= SEQUENCE_PREVIEW)
buf.append(sequencePreview(result));
else*/ if (verbosity >= ITEM_COUNT)
buf.append(result.getItemCount() + " item(s)");
buf.append("\t");
printPosition(e.expr);
buf.append(expr.toString());
log.debug(buf.toString());
}
if (verbosity >= TIME) {
buf.setLength(0);
for (int i = 0; i < stack.size(); i++)
buf.append('\t');
buf.append("TIME\t");
buf.append(elapsed + " ms");
buf.append("\t");
printPosition(e.expr);
buf.append(expr.toString());
log.debug(buf.toString());
}
buf.setLength(0);
for (int i = 0; i < stack.size(); i++)
buf.append('\t');
buf.append("END\t");
printPosition(e.expr);
buf.append(expr.toString());
log.debug(buf.toString());
if (stack.size() == 0) {
log.debug("QUERY END");
}
} catch (RuntimeException e) {
log.debug("Profiler: could not pop from expression stack - " + expr + " - "+ message + ". Error : "+ e.getMessage());
}
}
/**
* Print out a single profiling message for the given
* expression object.
*
*
* @param level
* @param title
* @param sequence
* @param expr
*/
public final void message(Expression expr, int level, String title, Sequence sequence) {
if (!enabled)
return;
if (level > verbosity)
return;
buf.setLength(0);
for (int i = 0; i < stack.size() - 1; i++)
buf.append('\t');
if (title != null && !"".equals(title))
buf.append(title);
else
buf.append("MSG");
buf.append("\t");
/* if (verbosity >= SEQUENCE_DUMP)
buf.append(sequence.toString());
else if (verbosity >= SEQUENCE_PREVIEW)
buf.append(sequencePreview(sequence));
else */ if (verbosity >= ITEM_COUNT)
buf.append(sequence.getItemCount() + " item(s)");
buf.append("\t");
buf.append(expr.toString());
log.debug(buf.toString());
}
public final void message(Expression expr, int level, String title, String message) {
if (!enabled)
return;
if (level > verbosity)
return;
buf.setLength(0);
for (int i = 0; i < stack.size() - 1; i++)
buf.append('\t');
if (title != null && !"".equals(title))
buf.append(title);
else
buf.append("MSG");
if (message != null && !"".equals(message)) {
buf.append("\t");
buf.append(message);
}
buf.append("\t");
printPosition(expr);
buf.append(expr.toString());
log.debug(buf.toString());
}
public void reset() {
if (stack.size() > 0)
log.debug("QUERY RESET");
stack.clear();
if (stats.isEnabled() && stats.hasData()) {
save();
stats.reset();
}
}
private void printPosition(Expression expr) {
if (expr.getLine() > -1) {
buf.append('[');
buf.append(expr.getLine());
buf.append(',');
buf.append(expr.getColumn());
buf.append("]\t");
}
else
buf.append("\t");
}
//TODO : find a way to preview "abstract" sequences
// never used locally
@SuppressWarnings("unused")
private String sequencePreview(Sequence sequence) {
StringBuilder truncation = new StringBuilder();
if (sequence.isEmpty())
truncation.append(sequence.toString());
else if (sequence.hasOne()) {
truncation.append("(");
if (sequence.itemAt(0).toString().length() > 20)
truncation.append(sequence.itemAt(0).toString().substring(0, 20)).append("... ");
else
truncation.append(sequence.itemAt(0).toString());
truncation.append(")");
} else {
truncation.append("(");
if (sequence.itemAt(0).toString().length() > 20)
truncation.append(sequence.itemAt(0).toString().substring(0, 20)).append("... ");
else
truncation.append(sequence.itemAt(0).toString());
truncation.append(", ... )");
}
return truncation.toString();
}
private final static class ProfiledExpr {
long start;
Expression expr;
private ProfiledExpr(Expression expression) {
this.expr = expression;
this.start = System.currentTimeMillis();
}
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setVerbosity(int verbosity) {
this.verbosity = verbosity;
}
}
|
// $Id: UDP.java,v 1.116 2006/07/28 15:30:21 belaban Exp $
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Message;
import org.jgroups.Global;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.BoundedList;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.*;
/**
* IP multicast transport based on UDP. Messages to the group (msg.dest == null) will
* be multicast (to all group members), whereas point-to-point messages
* (msg.dest != null) will be unicast to a single member. Uses a multicast and
* a unicast socket.<p>
* The following properties are read by the UDP protocol:
* <ul>
* <li> param mcast_addr - the multicast address to use; default is 228.8.8.8.
* <li> param mcast_port - (int) the port that the multicast is sent on; default is 7600
* <li> param ip_mcast - (boolean) flag whether to use IP multicast; default is true.
* <li> param ip_ttl - the default time-to-live for multicast packets sent out on this
* socket; default is 32.
* <li> param use_packet_handler - boolean, defaults to false.
* If set, the mcast and ucast receiver threads just put
* the datagram's payload (a byte buffer) into a queue, from where a separate thread
* will dequeue and handle them (unmarshal and pass up). This frees the receiver
* threads from having to do message unmarshalling; this time can now be spent
* receiving packets. If you have lots of retransmissions because of network
* input buffer overflow, consider setting this property to true.
* </ul>
* @author Bela Ban
*/
public class UDP extends TP implements Runnable {
/** Socket used for
* <ol>
* <li>sending unicast packets and
* <li>receiving unicast packets
* </ol>
* The address of this socket will be our local address (<tt>local_addr</tt>) */
DatagramSocket sock=null;
/**
* BoundedList<Integer> of the last 100 ports used. This is to avoid reusing a port for DatagramSocket
*/
private static volatile BoundedList last_ports_used=null;
/** Maintain a list of local ports opened by DatagramSocket. If this is 0, this option is turned off.
* If bind_port is > 0, then this option will be ignored */
int num_last_ports=100;
/** IP multicast socket for <em>receiving</em> multicast packets */
MulticastSocket mcast_recv_sock=null;
/** IP multicast socket for <em>sending</em> multicast packets */
MulticastSocket mcast_send_sock=null;
/** If we have multiple mcast send sockets, e.g. send_interfaces or send_on_all_interfaces enabled */
MulticastSocket[] mcast_send_sockets=null;
/**
* Traffic class for sending unicast and multicast datagrams.
* Valid values are (check {@link DatagramSocket#setTrafficClass(int)} ); for details):
* <UL>
* <LI><CODE>IPTOS_LOWCOST (0x02)</CODE>, <b>decimal 2</b></LI>
* <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE><, <b>decimal 4</b>/LI>
* <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE>, <b>decimal 8</b></LI>
* <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE>, <b>decimal</b> 16</LI>
* </UL>
*/
int tos=0; // valid values: 2, 4, 8, 16
/** The multicast address (mcast address and port) this member uses */
IpAddress mcast_addr=null;
/** The multicast address used for sending and receiving packets */
String mcast_addr_name="228.8.8.8";
/** The multicast port used for sending and receiving packets */
int mcast_port=7600;
/** The multicast receiver thread */
Thread mcast_receiver=null;
/** The unicast receiver thread */
UcastReceiver ucast_receiver=null;
/** Whether to enable IP multicasting. If false, multiple unicast datagram
* packets are sent rather than one multicast packet */
boolean ip_mcast=true;
/** The time-to-live (TTL) for multicast datagram packets */
int ip_ttl=64;
/** Send buffer size of the multicast datagram socket */
int mcast_send_buf_size=32000;
/** Receive buffer size of the multicast datagram socket */
int mcast_recv_buf_size=64000;
/** Send buffer size of the unicast datagram socket */
int ucast_send_buf_size=32000;
/** Receive buffer size of the unicast datagram socket */
int ucast_recv_buf_size=64000;
// private boolean null_src_addresses=true;
/**
* Creates the UDP protocol, and initializes the
* state variables, does however not start any sockets or threads.
*/
public UDP() {
}
/**
* Setup the Protocol instance acording to the configuration string.
* The following properties are read by the UDP protocol:
* <ul>
* <li> param mcast_addr - the multicast address to use default is 228.8.8.8
* <li> param mcast_port - (int) the port that the multicast is sent on default is 7600
* <li> param ip_mcast - (boolean) flag whether to use IP multicast - default is true
* <li> param ip_ttl - Set the default time-to-live for multicast packets sent out on this socket. default is 32
* </ul>
* @return true if no other properties are left.
* false if the properties still have data in them, ie ,
* properties are left over and not handled by the protocol stack
*/
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("num_last_ports");
if(str != null) {
num_last_ports=Integer.parseInt(str);
props.remove("num_last_ports");
}
str=props.getProperty("mcast_addr");
if(str != null) {
mcast_addr_name=str;
props.remove("mcast_addr");
}
str=System.getProperty("jboss.partition.udpGroup");
if(str != null)
mcast_addr_name=str;
str=props.getProperty("mcast_port");
if(str != null) {
mcast_port=Integer.parseInt(str);
props.remove("mcast_port");
}
str=System.getProperty("jboss.partition.udpPort");
if(str != null)
mcast_port=Integer.parseInt(str);
str=props.getProperty("ip_mcast");
if(str != null) {
ip_mcast=Boolean.valueOf(str).booleanValue();
props.remove("ip_mcast");
}
str=props.getProperty("ip_ttl");
if(str != null) {
ip_ttl=Integer.parseInt(str);
props.remove("ip_ttl");
}
str=props.getProperty("tos");
if(str != null) {
tos=Integer.parseInt(str);
props.remove("tos");
}
str=props.getProperty("mcast_send_buf_size");
if(str != null) {
mcast_send_buf_size=Integer.parseInt(str);
props.remove("mcast_send_buf_size");
}
str=props.getProperty("mcast_recv_buf_size");
if(str != null) {
mcast_recv_buf_size=Integer.parseInt(str);
props.remove("mcast_recv_buf_size");
}
str=props.getProperty("ucast_send_buf_size");
if(str != null) {
ucast_send_buf_size=Integer.parseInt(str);
props.remove("ucast_send_buf_size");
}
str=props.getProperty("ucast_recv_buf_size");
if(str != null) {
ucast_recv_buf_size=Integer.parseInt(str);
props.remove("ucast_recv_buf_size");
}
str=props.getProperty("null_src_addresses");
if(str != null) {
// null_src_addresses=Boolean.valueOf(str).booleanValue();
props.remove("null_src_addresses");
log.error("null_src_addresses has been deprecated, property will be ignored");
}
if(props.size() > 0) {
log.error("the following properties are not recognized: " + props);
return false;
}
return true;
}
public void run() {
DatagramPacket packet;
byte receive_buf[]=new byte[65535];
int offset, len, sender_port;
byte[] data;
InetAddress sender_addr;
Address sender;
// moved out of loop to avoid excessive object creations (bela March 8 2001)
packet=new DatagramPacket(receive_buf, receive_buf.length);
while(mcast_receiver != null && mcast_recv_sock != null) {
try {
packet.setData(receive_buf, 0, receive_buf.length);
mcast_recv_sock.receive(packet);
sender_addr=packet.getAddress();
sender_port=packet.getPort();
offset=packet.getOffset();
len=packet.getLength();
data=packet.getData();
sender=new IpAddress(sender_addr, sender_port);
if(len > receive_buf.length) {
if(log.isErrorEnabled())
log.error("size of the received packet (" + len + ") is bigger than " +
"allocated buffer (" + receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG protocol and make its frag_size lower than " + receive_buf.length);
}
receive(mcast_addr, sender, data, offset, len);
}
catch(SocketException sock_ex) {
if(trace) log.trace("multicast socket is closed, exception=" + sock_ex);
break;
}
catch(InterruptedIOException io_ex) { // thread was interrupted
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("failure in multicast receive()", ex);
Util.sleep(100); // so we don't get into 100% cpu spinning (should NEVER happen !)
}
}
if(log.isDebugEnabled()) log.debug("multicast thread terminated");
}
public String getInfo() {
StringBuffer sb=new StringBuffer();
sb.append("group_addr=").append(mcast_addr_name).append(':').append(mcast_port).append("\n");
return sb.toString();
}
public void sendToAllMembers(byte[] data, int offset, int length) throws Exception {
if(ip_mcast && mcast_addr != null) {
_send(mcast_addr.getIpAddress(), mcast_addr.getPort(), true, data, offset, length);
}
else {
ArrayList mbrs=new ArrayList(members);
IpAddress mbr;
for(Iterator it=mbrs.iterator(); it.hasNext();) {
mbr=(IpAddress)it.next();
_send(mbr.getIpAddress(), mbr.getPort(), false, data, offset, length);
}
}
}
public void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception {
_send(((IpAddress)dest).getIpAddress(), ((IpAddress)dest).getPort(), false, data, offset, length);
}
public void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast) {
msg.setDest(dest);
}
public void postUnmarshallingList(Message msg, Address dest, boolean multicast) {
msg.setDest(dest);
}
private void _send(InetAddress dest, int port, boolean mcast, byte[] data, int offset, int length) throws Exception {
DatagramPacket packet=new DatagramPacket(data, offset, length, dest, port);
try {
if(mcast) {
if(mcast_send_sock != null) {
mcast_send_sock.send(packet);
}
else {
if(mcast_send_sockets != null) {
MulticastSocket s;
for(int i=0; i < mcast_send_sockets.length; i++) {
s=mcast_send_sockets[i];
try {
s.send(packet);
}
catch(Exception e) {
log.error("failed sending packet on socket " + s);
}
}
}
else {
throw new Exception("both mcast_send_sock and mcast_send_sockets are null");
}
}
}
else {
if(sock != null)
sock.send(packet);
}
}
catch(Exception ex) {
throw new Exception("dest=" + dest + ":" + port + " (" + length + " bytes)", ex);
}
}
public String getName() {
return "UDP";
}
/**
* Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads
*/
public void start() throws Exception {
if(log.isDebugEnabled()) log.debug("creating sockets and starting threads");
try {
createSockets();
}
catch(Exception ex) {
String tmp="problem creating sockets (bind_addr=" + bind_addr +
", mcast_addr=" + mcast_addr + ")";
throw new Exception(tmp, ex);
}
super.start();
startThreads();
}
public void stop() {
if(log.isDebugEnabled()) log.debug("closing sockets and stopping threads");
stopThreads(); // will close sockets, closeSockets() is not really needed anymore, but...
closeSockets(); // ... we'll leave it in there for now (doesn't do anything if already closed)
super.stop();
}
/**
* Create UDP sender and receiver sockets. Currently there are 2 sockets
* (sending and receiving). This is due to Linux's non-BSD compatibility
* in the JDK port (see DESIGN).
*/
private void createSockets() throws Exception {
InetAddress tmp_addr;
// bind_addr not set, try to assign one by default. This is needed on Windows
// changed by bela Feb 12 2003: by default multicast sockets will be bound to all network interfaces
// CHANGED *BACK* by bela March 13 2003: binding to all interfaces did not result in a correct
// local_addr. As a matter of fact, comparison between e.g. 0.0.0.0:1234 (on hostA) and
// 0.0.0.0:1.2.3.4 (on hostB) would fail !
// if(bind_addr == null) {
// InetAddress[] interfaces=InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress());
// if(interfaces != null && interfaces.length > 0)
// bind_addr=interfaces[0];
if(bind_addr == null && !use_local_host) {
bind_addr=Util.getFirstNonLoopbackAddress();
}
if(bind_addr == null)
bind_addr=InetAddress.getLocalHost();
if(bind_addr != null)
if(log.isInfoEnabled()) log.info("sockets will use interface " + bind_addr.getHostAddress());
// 2. Create socket for receiving unicast UDP packets. The address and port
// of this socket will be our local address (local_addr)
if(bind_port > 0) {
sock=createDatagramSocketWithBindPort();
}
else {
sock=createEphemeralDatagramSocket();
}
if(tos > 0) {
try {
sock.setTrafficClass(tos);
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored", e);
}
}
if(sock == null)
throw new Exception("UDP.createSocket(): sock is null");
local_addr=new IpAddress(sock.getLocalAddress(), sock.getLocalPort());
if(additional_data != null)
((IpAddress)local_addr).setAdditionalData(additional_data);
// 3. Create socket for receiving IP multicast packets
if(ip_mcast) {
// 3a. Create mcast receiver socket
mcast_recv_sock=new MulticastSocket(mcast_port);
mcast_recv_sock.setTimeToLive(ip_ttl);
tmp_addr=InetAddress.getByName(mcast_addr_name);
mcast_addr=new IpAddress(tmp_addr, mcast_port);
if(receive_on_all_interfaces || (receive_interfaces != null && receive_interfaces.size() > 0)) {
List interfaces;
if(receive_interfaces != null)
interfaces=receive_interfaces;
else
interfaces=Util.getAllAvailableInterfaces();
bindToInterfaces(interfaces, mcast_recv_sock, mcast_addr.getIpAddress());
}
else {
if(bind_addr != null)
mcast_recv_sock.setInterface(bind_addr);
mcast_recv_sock.joinGroup(tmp_addr);
}
// 3b. Create mcast sender socket
if(send_on_all_interfaces || (send_interfaces != null && send_interfaces.size() > 0)) {
List interfaces;
NetworkInterface intf;
if(send_interfaces != null)
interfaces=send_interfaces;
else
interfaces=Util.getAllAvailableInterfaces();
mcast_send_sockets=new MulticastSocket[interfaces.size()];
int index=0;
for(Iterator it=interfaces.iterator(); it.hasNext();) {
intf=(NetworkInterface)it.next();
mcast_send_sockets[index]=new MulticastSocket();
mcast_send_sockets[index].setNetworkInterface(intf);
mcast_send_sockets[index].setTimeToLive(ip_ttl);
if(tos > 0) {
try {
mcast_send_sockets[index].setTrafficClass(tos);
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored", e);
}
}
index++;
}
}
else {
mcast_send_sock=new MulticastSocket();
mcast_send_sock.setTimeToLive(ip_ttl);
if(bind_addr != null)
mcast_send_sock.setInterface(bind_addr);
if(tos > 0) {
try {
mcast_send_sock.setTrafficClass(tos); // high throughput
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored", e);
}
}
}
}
setBufferSizes();
if(log.isInfoEnabled()) log.info("socket information:\n" + dumpSocketInfo());
}
// private void bindToAllInterfaces(MulticastSocket s, InetAddress mcastAddr) throws IOException {
// SocketAddress tmp_mcast_addr=new InetSocketAddress(mcastAddr, mcast_port);
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// // if(addr.isLoopbackAddress())
// // continue;
// s.joinGroup(tmp_mcast_addr, i);
// if(trace)
// log.trace("joined " + tmp_mcast_addr + " on interface " + i.getName() + " (" + addr + ")");
// break;
/**
*
* @param interfaces List<NetworkInterface>. Guaranteed to have no duplicates
* @param s
* @param mcastAddr
* @throws IOException
*/
private void bindToInterfaces(List interfaces, MulticastSocket s, InetAddress mcastAddr) throws IOException {
SocketAddress tmp_mcast_addr=new InetSocketAddress(mcastAddr, mcast_port);
for(Iterator it=interfaces.iterator(); it.hasNext();) {
NetworkInterface i=(NetworkInterface)it.next();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
s.joinGroup(tmp_mcast_addr, i);
if(trace)
log.trace("joined " + tmp_mcast_addr + " on " + i.getName() + " (" + addr + ")");
break;
}
}
}
/** Creates a DatagramSocket with a random port. Because in certain operating systems, ports are reused,
* we keep a list of the n last used ports, and avoid port reuse */
private DatagramSocket createEphemeralDatagramSocket() throws SocketException {
DatagramSocket tmp;
int localPort=0;
while(true) {
tmp=new DatagramSocket(localPort, bind_addr); // first time localPort is 0
if(num_last_ports <= 0)
break;
localPort=tmp.getLocalPort();
if(last_ports_used == null)
last_ports_used=new BoundedList(num_last_ports);
if(last_ports_used.contains(new Integer(localPort))) {
if(log.isDebugEnabled())
log.debug("local port " + localPort + " already seen in this session; will try to get other port");
try {tmp.close();} catch(Throwable e) {}
localPort++;
}
else {
last_ports_used.add(new Integer(localPort));
break;
}
}
return tmp;
}
/**
* Creates a DatagramSocket when bind_port > 0. Attempts to allocate the socket with port == bind_port, and
* increments until it finds a valid port, or until port_range has been exceeded
* @return DatagramSocket The newly created socket
* @throws Exception
*/
private DatagramSocket createDatagramSocketWithBindPort() throws Exception {
DatagramSocket tmp=null;
// 27-6-2003 bgooren, find available port in range (start_port, start_port+port_range)
int rcv_port=bind_port, max_port=bind_port + port_range;
while(rcv_port <= max_port) {
try {
tmp=new DatagramSocket(rcv_port, bind_addr);
break;
}
catch(SocketException bind_ex) { // Cannot listen on this port
rcv_port++;
}
catch(SecurityException sec_ex) { // Not allowed to listen on this port
rcv_port++;
}
// Cannot listen at all, throw an Exception
if(rcv_port >= max_port + 1) { // +1 due to the increment above
throw new Exception("UDP.createSockets(): cannot create a socket on any port in range " +
bind_port + '-' + (bind_port + port_range));
}
}
return tmp;
}
private String dumpSocketInfo() throws Exception {
StringBuffer sb=new StringBuffer(128);
sb.append("local_addr=").append(local_addr);
sb.append(", mcast_addr=").append(mcast_addr);
sb.append(", bind_addr=").append(bind_addr);
sb.append(", ttl=").append(ip_ttl);
if(sock != null) {
sb.append("\nsock: bound to ");
sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
sb.append(", send buffer size=").append(sock.getSendBufferSize());
}
if(mcast_recv_sock != null) {
sb.append("\nmcast_recv_sock: bound to ");
sb.append(mcast_recv_sock.getInterface().getHostAddress()).append(':').append(mcast_recv_sock.getLocalPort());
sb.append(", send buffer size=").append(mcast_recv_sock.getSendBufferSize());
sb.append(", receive buffer size=").append(mcast_recv_sock.getReceiveBufferSize());
}
if(mcast_send_sock != null) {
sb.append("\nmcast_send_sock: bound to ");
sb.append(mcast_send_sock.getInterface().getHostAddress()).append(':').append(mcast_send_sock.getLocalPort());
sb.append(", send buffer size=").append(mcast_send_sock.getSendBufferSize());
sb.append(", receive buffer size=").append(mcast_send_sock.getReceiveBufferSize());
}
if(mcast_send_sockets != null) {
sb.append("\n").append(mcast_send_sockets.length).append(" mcast send sockets:\n");
MulticastSocket s;
for(int i=0; i < mcast_send_sockets.length; i++) {
s=mcast_send_sockets[i];
sb.append(s.getInterface().getHostAddress()).append(':').append(s.getLocalPort());
sb.append(", send buffer size=").append(s.getSendBufferSize());
sb.append(", receive buffer size=").append(s.getReceiveBufferSize()).append("\n");
}
}
return sb.toString();
}
void setBufferSizes() {
if(sock != null)
setBufferSize(sock, ucast_send_buf_size, ucast_recv_buf_size);
if(mcast_recv_sock != null)
setBufferSize(mcast_recv_sock, mcast_send_buf_size, mcast_recv_buf_size);
if(mcast_send_sock != null)
setBufferSize(mcast_send_sock, mcast_send_buf_size, mcast_recv_buf_size);
if(mcast_send_sockets != null) {
for(int i=0; i < mcast_send_sockets.length; i++) {
setBufferSize(mcast_send_sockets[i], mcast_send_buf_size, mcast_recv_buf_size);
}
}
}
private void setBufferSize(DatagramSocket sock, int send_buf_size, int recv_buf_size) {
try {
sock.setSendBufferSize(send_buf_size);
}
catch(Throwable ex) {
if(warn) log.warn("failed setting send buffer size of " + send_buf_size + " in " + sock + ": " + ex);
}
try {
sock.setReceiveBufferSize(recv_buf_size);
}
catch(Throwable ex) {
if(warn) log.warn("failed setting receive buffer size of " + recv_buf_size + " in " + sock + ": " + ex);
}
}
/**
* Closed UDP unicast and multicast sockets
*/
void closeSockets() {
// 1. Close multicast socket
closeMulticastSocket();
// 2. Close socket
closeSocket();
}
void closeMulticastSocket() {
if(mcast_recv_sock != null) {
try {
if(mcast_addr != null) {
mcast_recv_sock.leaveGroup(mcast_addr.getIpAddress());
}
mcast_recv_sock.close(); // this will cause the mcast receiver thread to break out of its loop
mcast_recv_sock=null;
if(log.isDebugEnabled()) log.debug("multicast receive socket closed");
}
catch(IOException ex) {
}
mcast_addr=null;
}
if(mcast_send_sock != null) {
mcast_send_sock.close();
mcast_send_sock=null;
if(log.isDebugEnabled()) log.debug("multicast send socket closed");
}
if(mcast_send_sockets != null) {
MulticastSocket s;
for(int i=0; i < mcast_send_sockets.length; i++) {
s=mcast_send_sockets[i];
s.close();
if(log.isDebugEnabled()) log.debug("multicast send socket " + s + " closed");
}
mcast_send_sockets=null;
}
}
private void closeSocket() {
if(sock != null) {
sock.close();
sock=null;
if(log.isDebugEnabled()) log.debug("socket closed");
}
}
/**
* Starts the unicast and multicast receiver threads
*/
void startThreads() throws Exception {
if(ucast_receiver == null) {
//start the listener thread of the ucast_recv_sock
ucast_receiver=new UcastReceiver();
ucast_receiver.start();
if(log.isDebugEnabled()) log.debug("created unicast receiver thread");
}
if(ip_mcast) {
if(mcast_receiver != null) {
if(mcast_receiver.isAlive()) {
if(log.isDebugEnabled()) log.debug("did not create new multicastreceiver thread as existing " +
"multicast receiver thread is still running");
}
else
mcast_receiver=null; // will be created just below...
}
if(mcast_receiver == null) {
mcast_receiver=new Thread(Util.getGlobalThreadGroup(), this, "UDP mcast receiver");
mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ????
mcast_receiver.setDaemon(true);
mcast_receiver.start();
}
}
}
/**
* Stops unicast and multicast receiver threads
*/
void stopThreads() {
Thread tmp;
// 1. Stop the multicast receiver thread
if(mcast_receiver != null) {
if(mcast_receiver.isAlive()) {
tmp=mcast_receiver;
mcast_receiver=null;
closeMulticastSocket(); // will cause the multicast thread to terminate
tmp.interrupt();
try {
tmp.join(100);
}
catch(Exception e) {
}
tmp=null;
}
mcast_receiver=null;
}
// 2. Stop the unicast receiver thread
if(ucast_receiver != null) {
ucast_receiver.stop();
ucast_receiver=null;
}
}
protected void setThreadNames() {
super.setThreadNames();
if(channel_name != null) {
String tmp, prefix=Global.THREAD_PREFIX;
if(mcast_receiver != null) {
tmp=mcast_receiver.getName();
if(tmp != null && tmp.indexOf(prefix) == -1) {
tmp+=prefix + channel_name + ")";
mcast_receiver.setName(tmp);
}
}
if(ucast_receiver != null) {
tmp=ucast_receiver.getName();
if(tmp != null && tmp.indexOf(prefix) == -1) {
tmp+=prefix + channel_name + ")";
ucast_receiver.setName(tmp);
}
}
}
}
protected void unsetThreadNames() {
super.unsetThreadNames();
if(channel_name != null) {
String tmp, prefix=Global.THREAD_PREFIX;
int index;
tmp=mcast_receiver != null? mcast_receiver.getName() : null;
if(tmp != null) {
index=tmp.indexOf(prefix);
if(index > -1) {
tmp=tmp.substring(0, index);
mcast_receiver.setName(tmp);
}
}
tmp=ucast_receiver != null? ucast_receiver.getName() : null;
if(tmp != null) {
index=tmp.indexOf(prefix);
if(index > -1) {
tmp=tmp.substring(0, index);
ucast_receiver.setName(tmp);
}
}
}
}
protected void handleConfigEvent(HashMap map) {
boolean set_buffers=false;
super.handleConfigEvent(map);
if(map == null) return;
if(map.containsKey("send_buf_size")) {
mcast_send_buf_size=((Integer)map.get("send_buf_size")).intValue();
ucast_send_buf_size=mcast_send_buf_size;
set_buffers=true;
}
if(map.containsKey("recv_buf_size")) {
mcast_recv_buf_size=((Integer)map.get("recv_buf_size")).intValue();
ucast_recv_buf_size=mcast_recv_buf_size;
set_buffers=true;
}
if(set_buffers)
setBufferSizes();
}
public class UcastReceiver implements Runnable {
boolean running=true;
Thread thread=null;
String getName() {
return thread != null? thread.getName() : null;
}
void setName(String thread_name) {
if(thread != null)
thread.setName(thread_name);
}
public void start() {
if(thread == null) {
thread=new Thread(Util.getGlobalThreadGroup(), this, "UDP.UcastReceiverThread");
thread.setDaemon(true);
running=true;
thread.start();
}
}
public void stop() {
Thread tmp;
if(thread != null && thread.isAlive()) {
running=false;
tmp=thread;
thread=null;
closeSocket(); // this will cause the thread to break out of its loop
tmp.interrupt();
tmp=null;
}
thread=null;
}
public void run() {
DatagramPacket packet;
byte receive_buf[]=new byte[65535];
int offset, len;
byte[] data;
InetAddress sender_addr;
int sender_port;
Address sender;
// moved out of loop to avoid excessive object creations (bela March 8 2001)
packet=new DatagramPacket(receive_buf, receive_buf.length);
while(running && thread != null && sock != null) {
try {
packet.setData(receive_buf, 0, receive_buf.length);
sock.receive(packet);
sender_addr=packet.getAddress();
sender_port=packet.getPort();
offset=packet.getOffset();
len=packet.getLength();
data=packet.getData();
sender=new IpAddress(sender_addr, sender_port);
if(len > receive_buf.length) {
if(log.isErrorEnabled())
log.error("size of the received packet (" + len + ") is bigger than allocated buffer (" +
receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG protocol and make its frag_size lower than " + receive_buf.length);
}
receive(local_addr, sender, data, offset, len);
}
catch(SocketException sock_ex) {
if(log.isDebugEnabled()) log.debug("unicast receiver socket is closed, exception=" + sock_ex);
break;
}
catch(InterruptedIOException io_ex) { // thread was interrupted
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("[" + local_addr + "] failed receiving unicast packet", ex);
Util.sleep(100); // so we don't get into 100% cpu spinning (should NEVER happen !)
}
}
if(log.isDebugEnabled()) log.debug("unicast receiver thread terminated");
}
}
}
|
package org.owasp.esapi;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.owasp.esapi.ValidatorErrorList;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
public interface Validator {
boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException;
String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException, IntrusionException;
String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid date according to the specified date format.
*/
boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException;
/**
* Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a valid date as a Date. Invalid input will generate a descriptive ValidationException and store it inside of
* the errorList argument, and input that is clearly an attack will generate a descriptive IntrusionException.
*/
Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas
* on how to do HTML validation in a whitelist way, as this is an extremely difficult problem.
*/
boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException;
/**
* Returns canonicalized and validated "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas
* on how to do HTML validation in a whitelist way, as this is an extremely difficult problem.
*/
String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidatorErrorList errorList) throws ValidationException, IntrusionException;
/**
* Returns canonicalized and validated "safe" HTML. Implementors should reference the OWASP AntiSamy project for ideas
* on how to do HTML validation in a whitelist way, as this is an extremely difficult problem. Instead of
* throwing a ValidationException on error, this variant will store the exception inside of the ValidationErrorList.
*/
String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException;
/**
* Returns true if input is a valid credit card. Maxlength is mandated by valid credit card type.
*/
boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException;
/**
* Returns a canonicalized and validated credit card number as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a canonicalized and validated credit card number as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
String getValidCreditCard(String context, String input, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid directory path.
*/
boolean isValidDirectoryPath(String context, String input, boolean allowNull) throws IntrusionException;
/**
* Returns a canonicalized and validated directory path as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
String getValidDirectoryPath(String context, String input, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a canonicalized and validated directory path as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
String getValidDirectoryPath(String context, String input, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid file name.
*/
boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException;
/**
* Returns a canonicalized and validated file name as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
String getValidFileName(String context, String input, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a canonicalized and validated file name as a String. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
String getValidFileName(String context, String input, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid number.
*/
boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException;
/**
* Returns a validated number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a validated number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid integer.
*/
boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException;
/**
* Returns a validated integer as an int. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a validated integer as an int. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid double.
*/
boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException;
/**
* Returns a validated real number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a validated real number as a double. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is valid file content.
*/
boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException;
/**
* Returns validated file content as a byte array. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns validated file content as a byte array. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if a file upload has a valid name, path, and content.
*/
boolean isValidFileUpload(String context, String filepath, String filename, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException;
/**
* Validates the filepath, filename, and content of a file. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
void assertValidFileUpload(String context, String filepath, String filename, byte[] content, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Validates the filepath, filename, and content of a file. Invalid input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
void assertValidFileUpload(String context, String filepath, String filename, byte[] content, int maxBytes, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Validate the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed
* characters. See the SecurityConfiguration class for the methods to retrieve the whitelists.
*/
boolean isValidHTTPRequest() throws IntrusionException;
/**
* Validates the current HTTP request by comparing parameters, headers, and cookies to a predefined whitelist of allowed
* characters. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
void assertIsValidHTTPRequest() throws ValidationException, IntrusionException;
/**
* Returns true if input is a valid list item.
*/
boolean isValidListItem(String context, String input, List list) throws IntrusionException;
/**
* Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
String getValidListItem(String context, String input, List list) throws ValidationException, IntrusionException;
/**
* Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
String getValidListItem(String context, String input, List list, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if the parameters in the current request contain all required parameters and only optional ones in addition.
*/
boolean isValidHTTPRequestParameterSet(String context, Set required, Set optional) throws IntrusionException;
/**
* Validates that the parameters in the current request contain all required parameters and only optional ones in
* addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional) throws ValidationException, IntrusionException;
/**
* Validates that the parameters in the current request contain all required parameters and only optional ones in
* addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException on error,
* this variant will store the exception inside of the ValidationErrorList.
*/
void assertIsValidHTTPRequestParameterSet(String context, Set required, Set optional, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is valid printable ASCII characters.
*/
boolean isValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws IntrusionException;
/**
* Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
byte[] getValidPrintable(String context, byte[] input, int maxLength, boolean allowNull) throws ValidationException;
/**
* Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException on error,
* this variant will store the exception inside of the ValidationErrorList.
*/
byte[] getValidPrintable(String context, byte[] input, int maxLength, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is valid printable ASCII characters (32-126).
*/
boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException;
/**
* Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException;
/**
* Returns canonicalized and validated printable characters as a String. Invalid input will generate
* a descriptive ValidationException, and input that is clearly an attack will generate a
* descriptive IntrusionException. Instead of throwing a ValidationException on error,
* this variant will store the exception inside of the ValidationErrorList.
*/
String getValidPrintable(String context, String input, int maxLength, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Returns true if input is a valid redirect location.
*/
boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException;
/**
* Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException;
/**
* Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException. Instead of throwing a ValidationException
* on error, this variant will store the exception inside of the ValidationErrorList.
*/
String getValidRedirectLocation(String context, String input, boolean allowNull, ValidatorErrorList errorList) throws IntrusionException;
/**
* Reads from an input stream until end-of-line or a maximum number of
* characters. This method protects against the inherent denial of service
* attack in reading until the end of a line. If an attacker doesn't ever
* send a newline character, then a normal input stream reader will read
* until all memory is exhausted and the platform throws an OutOfMemoryError
* and probably terminates.
*/
String safeReadLine(InputStream inputStream, int maxLength) throws ValidationException;
}
|
/**********************************************************************************************
*
* RubotoActivity.java is generated from RubotoClass.java.erb. Any changes needed in should be
* made within the erb template or they will be lost.
*
*/
package org.ruboto;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Bundle;
import org.jruby.Ruby;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.exceptions.RaiseException;
public class RubotoActivity extends Activity
implements
android.hardware.SensorEventListener,
java.lang.Runnable,
android.view.View.OnClickListener,
android.view.View.OnFocusChangeListener,
android.view.View.OnLongClickListener,
android.view.View.OnTouchListener,
android.view.View.OnKeyListener,
android.widget.AdapterView.OnItemSelectedListener,
android.widget.AdapterView.OnItemLongClickListener,
android.widget.AdapterView.OnItemClickListener,
android.view.ViewGroup.OnHierarchyChangeListener,
android.widget.TabHost.TabContentFactory,
android.widget.TabHost.OnTabChangeListener,
android.widget.TextView.OnEditorActionListener,
android.widget.DatePicker.OnDateChangedListener,
android.widget.TimePicker.OnTimeChangedListener,
android.app.DatePickerDialog.OnDateSetListener,
android.app.TimePickerDialog.OnTimeSetListener,
android.content.DialogInterface.OnKeyListener,
android.content.DialogInterface.OnMultiChoiceClickListener,
android.content.DialogInterface.OnClickListener,
android.content.DialogInterface.OnShowListener,
android.content.DialogInterface.OnDismissListener,
android.content.DialogInterface.OnCancelListener
{
public static final int CB_ACTIVITY_RESULT = 0;
public static final int CB_APPLY_THEME_RESOURCE = 1;
public static final int CB_ATTACHED_TO_WINDOW = 2;
public static final int CB_BACK_PRESSED = 3;
public static final int CB_CHILD_TITLE_CHANGED = 4;
public static final int CB_CONFIGURATION_CHANGED = 5;
public static final int CB_CONTENT_CHANGED = 6;
public static final int CB_CREATE_CONTEXT_MENU = 7;
public static final int CB_CONTEXT_MENU_CLOSED = 8;
public static final int CB_CREATE_DESCRIPTION = 9;
public static final int CB_CREATE_DIALOG = 10;
public static final int CB_CREATE_OPTIONS_MENU = 11;
public static final int CB_CREATE_PANEL_MENU = 12;
public static final int CB_CREATE_PANEL_VIEW = 13;
public static final int CB_CREATE_THUMBNAIL = 14;
public static final int CB_CREATE_VIEW = 15;
public static final int CB_DESTROY = 16;
public static final int CB_DETACHED_FROM_WINDOW = 17;
public static final int CB_KEY_DOWN = 18;
public static final int CB_KEY_LONG_PRESS = 19;
public static final int CB_KEY_MULTIPLE = 20;
public static final int CB_KEY_UP = 21;
public static final int CB_LOW_MEMORY = 22;
public static final int CB_MENU_OPENED = 23;
public static final int CB_NEW_INTENT = 24;
public static final int CB_OPTIONS_ITEM_SELECTED = 25;
public static final int CB_OPTIONS_MENU_CLOSED = 26;
public static final int CB_PANEL_CLOSED = 27;
public static final int CB_PAUSE = 28;
public static final int CB_POST_CREATE = 29;
public static final int CB_POST_RESUME = 30;
public static final int CB_PREPARE_DIALOG = 31;
public static final int CB_PREPARE_OPTIONS_MENU = 32;
public static final int CB_PREPARE_PANEL = 33;
public static final int CB_RESTART = 34;
public static final int CB_RESTORE_INSTANCE_STATE = 35;
public static final int CB_RESUME = 36;
public static final int CB_RETAIN_NON_CONFIGURATION_INSTANCE = 37;
public static final int CB_SAVE_INSTANCE_STATE = 38;
public static final int CB_SEARCH_REQUESTED = 39;
public static final int CB_START = 40;
public static final int CB_STOP = 41;
public static final int CB_TITLE_CHANGED = 42;
public static final int CB_TOUCH_EVENT = 43;
public static final int CB_TRACKBALL_EVENT = 44;
public static final int CB_USER_INTERACTION = 45;
public static final int CB_USER_LEAVE_HINT = 46;
public static final int CB_WINDOW_ATTRIBUTES_CHANGED = 47;
public static final int CB_WINDOW_FOCUS_CHANGED = 48;
public static final int CB_ACCURACY_CHANGED = 49;
public static final int CB_SENSOR_CHANGED = 50;
public static final int CB_RUN = 51;
public static final int CB_CLICK = 52;
public static final int CB_FOCUS_CHANGE = 53;
public static final int CB_LONG_CLICK = 54;
public static final int CB_TOUCH = 55;
public static final int CB_KEY = 56;
public static final int CB_ITEM_SELECTED = 57;
public static final int CB_NOTHING_SELECTED = 58;
public static final int CB_ITEM_LONG_CLICK = 59;
public static final int CB_ITEM_CLICK = 60;
public static final int CB_CHILD_VIEW_ADDED = 61;
public static final int CB_CHILD_VIEW_REMOVED = 62;
public static final int CB_CREATE_TAB_CONTENT = 63;
public static final int CB_TAB_CHANGED = 64;
public static final int CB_EDITOR_ACTION = 65;
public static final int CB_DATE_CHANGED = 66;
public static final int CB_TIME_CHANGED = 67;
public static final int CB_DATE_SET = 68;
public static final int CB_TIME_SET = 69;
public static final int CB_DIALOG_KEY = 70;
public static final int CB_DIALOG_MULTI_CHOICE_CLICK = 71;
public static final int CB_DIALOG_CLICK = 72;
public static final int CB_SHOW = 73;
public static final int CB_DISMISS = 74;
public static final int CB_CANCEL = 75;
public static final int CB_DRAW = 76;
public static final int CB_SIZE_CHANGED = 77;
public static final int CB_LAST = 78;
private boolean[] callbackOptions = new boolean [CB_LAST];
private String remoteVariable = "";
private ProgressDialog loadingDialog;
private final Handler loadingHandler = new Handler();
private IRubyObject __this__;
private Ruby __ruby__;
public RubotoActivity setRemoteVariable(String var) {
remoteVariable = ((var == null) ? "" : (var + "."));
return this;
}
/**********************************************************************************
*
* Callback management
*/
public void requestCallback(int id) {
callbackOptions[id] = true;
}
public void removeCallback(int id) {
callbackOptions[id] = false;
}
/*
* Activity Lifecycle: onCreate
*/
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
if (getIntent().getAction() != null &&
getIntent().getAction().equals("org.ruboto.intent.action.LAUNCH_SCRIPT")) {
/* Launched from a shortcut */
Thread t = new Thread() {
public void run(){
Script.configDir(IRB.SDCARD_SCRIPTS_DIR, getFilesDir().getAbsolutePath() + "/scripts");
Script.setUpJRuby(null);
loadingHandler.post(loadingComplete);
}
};
t.start();
loadingDialog = ProgressDialog.show(this, "Launching Script", "Initializing Ruboto...", true, false);
} else {
Bundle configBundle = getIntent().getBundleExtra("RubotoActivity Config");
if (configBundle != null) {
setRemoteVariable(configBundle.getString("Remote Variable"));
if (configBundle.getBoolean("Define Remote Variable")) {
Script.defineGlobalVariable(configBundle.getString("Remote Variable"), this);
}
if (configBundle.getString("Initialize Script") != null) {
Script.execute(configBundle.getString("Initialize Script"));
}
} else {
Script.defineGlobalVariable("$activity", this);
}
__ruby__ = Script.getRuby();
__this__ = JavaUtil.convertJavaToRuby(__ruby__, this);
Script.defineGlobalVariable("$bundle", savedState);
Script.execute(remoteVariable + "on_create($bundle)");
// RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create", JavaUtil.convertJavaToRuby(__ruby__, savedState));
}
}
protected final Runnable loadingComplete = new Runnable(){
public void run(){
loadingDialog.dismiss();
__ruby__ = Script.getRuby();
__this__ = JavaUtil.convertJavaToRuby(__ruby__, RubotoActivity.this);
Script script = new Script(getIntent().getExtras().getString("org.ruboto.extra.SCRIPT_NAME"));
Script.defineGlobalVariable("$activity", RubotoActivity.this);
try {script.execute();}
catch (IOException e) {finish();}
}
};
/*********************************************************************************
*
* Ruby Generated Callback Methods
*/
/*
* android.app.Activity
*/
public void onActivityResult(int arg0, int arg1, android.content.Intent arg2) {
if (callbackOptions[CB_ACTIVITY_RESULT]) {
super.onActivityResult(arg0, arg1, arg2);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_activity_result", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onActivityResult(arg0, arg1, arg2);
}
}
public void onApplyThemeResource(android.content.res.Resources.Theme arg0, int arg1, boolean arg2) {
if (callbackOptions[CB_APPLY_THEME_RESOURCE]) {
super.onApplyThemeResource(arg0, arg1, arg2);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_apply_theme_resource", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onApplyThemeResource(arg0, arg1, arg2);
}
}
public void onAttachedToWindow() {
if (callbackOptions[CB_ATTACHED_TO_WINDOW]) {
super.onAttachedToWindow();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_attached_to_window");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onAttachedToWindow();
}
}
public void onBackPressed() {
if (callbackOptions[CB_BACK_PRESSED]) {
super.onBackPressed();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_back_pressed");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onBackPressed();
}
}
public void onChildTitleChanged(android.app.Activity arg0, java.lang.CharSequence arg1) {
if (callbackOptions[CB_CHILD_TITLE_CHANGED]) {
super.onChildTitleChanged(arg0, arg1);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_child_title_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onChildTitleChanged(arg0, arg1);
}
}
public void onConfigurationChanged(android.content.res.Configuration arg0) {
if (callbackOptions[CB_CONFIGURATION_CHANGED]) {
super.onConfigurationChanged(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_configuration_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onConfigurationChanged(arg0);
}
}
public void onContentChanged() {
if (callbackOptions[CB_CONTENT_CHANGED]) {
super.onContentChanged();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_content_changed");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onContentChanged();
}
}
public boolean onContextItemSelected(android.view.MenuItem arg0) {
if (callbackOptions[CB_CREATE_CONTEXT_MENU]) {
super.onContextItemSelected(arg0);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_context_item_selected", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onContextItemSelected(arg0);
}
}
public void onContextMenuClosed(android.view.Menu arg0) {
if (callbackOptions[CB_CONTEXT_MENU_CLOSED]) {
super.onContextMenuClosed(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_context_menu_closed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onContextMenuClosed(arg0);
}
}
public void onCreateContextMenu(android.view.ContextMenu arg0, android.view.View arg1, android.view.ContextMenu.ContextMenuInfo arg2) {
if (callbackOptions[CB_CREATE_CONTEXT_MENU]) {
super.onCreateContextMenu(arg0, arg1, arg2);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_context_menu", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onCreateContextMenu(arg0, arg1, arg2);
}
}
public java.lang.CharSequence onCreateDescription() {
if (callbackOptions[CB_CREATE_DESCRIPTION]) {
super.onCreateDescription();
try {
return (java.lang.CharSequence)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_description").toJava(java.lang.CharSequence.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return null;
}
} else {
return super.onCreateDescription();
}
}
public android.app.Dialog onCreateDialog(int arg0, android.os.Bundle arg1) {
if (callbackOptions[CB_CREATE_DIALOG]) {
super.onCreateDialog(arg0, arg1);
try {
return (android.app.Dialog)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_dialog", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(android.app.Dialog.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return null;
}
} else {
return super.onCreateDialog(arg0, arg1);
}
}
public boolean onCreateOptionsMenu(android.view.Menu arg0) {
if (callbackOptions[CB_CREATE_OPTIONS_MENU]) {
super.onCreateOptionsMenu(arg0);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_options_menu", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onCreateOptionsMenu(arg0);
}
}
public boolean onCreatePanelMenu(int arg0, android.view.Menu arg1) {
if (callbackOptions[CB_CREATE_PANEL_MENU]) {
super.onCreatePanelMenu(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_panel_menu", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onCreatePanelMenu(arg0, arg1);
}
}
public android.view.View onCreatePanelView(int arg0) {
if (callbackOptions[CB_CREATE_PANEL_VIEW]) {
super.onCreatePanelView(arg0);
try {
return (android.view.View)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_panel_view", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(android.view.View.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return null;
}
} else {
return super.onCreatePanelView(arg0);
}
}
public boolean onCreateThumbnail(android.graphics.Bitmap arg0, android.graphics.Canvas arg1) {
if (callbackOptions[CB_CREATE_THUMBNAIL]) {
super.onCreateThumbnail(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_thumbnail", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onCreateThumbnail(arg0, arg1);
}
}
public android.view.View onCreateView(java.lang.String arg0, android.content.Context arg1, android.util.AttributeSet arg2) {
if (callbackOptions[CB_CREATE_VIEW]) {
super.onCreateView(arg0, arg1, arg2);
try {
return (android.view.View)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_create_view", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2)).toJava(android.view.View.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return null;
}
} else {
return super.onCreateView(arg0, arg1, arg2);
}
}
public void onDestroy() {
if (callbackOptions[CB_DESTROY]) {
super.onDestroy();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_destroy");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onDestroy();
}
}
public void onDetachedFromWindow() {
if (callbackOptions[CB_DETACHED_FROM_WINDOW]) {
super.onDetachedFromWindow();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_detached_from_window");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onDetachedFromWindow();
}
}
public boolean onKeyDown(int arg0, android.view.KeyEvent arg1) {
if (callbackOptions[CB_KEY_DOWN]) {
super.onKeyDown(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_key_down", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onKeyDown(arg0, arg1);
}
}
public boolean onKeyLongPress(int arg0, android.view.KeyEvent arg1) {
if (callbackOptions[CB_KEY_LONG_PRESS]) {
super.onKeyLongPress(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_key_long_press", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onKeyLongPress(arg0, arg1);
}
}
public boolean onKeyMultiple(int arg0, int arg1, android.view.KeyEvent arg2) {
if (callbackOptions[CB_KEY_MULTIPLE]) {
super.onKeyMultiple(arg0, arg1, arg2);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_key_multiple", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onKeyMultiple(arg0, arg1, arg2);
}
}
public boolean onKeyUp(int arg0, android.view.KeyEvent arg1) {
if (callbackOptions[CB_KEY_UP]) {
super.onKeyUp(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_key_up", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onKeyUp(arg0, arg1);
}
}
public void onLowMemory() {
if (callbackOptions[CB_LOW_MEMORY]) {
super.onLowMemory();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_low_memory");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onLowMemory();
}
}
public boolean onMenuItemSelected(int arg0, android.view.MenuItem arg1) {
if (callbackOptions[CB_CREATE_OPTIONS_MENU]) {
super.onMenuItemSelected(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_menu_item_selected", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onMenuItemSelected(arg0, arg1);
}
}
public boolean onMenuOpened(int arg0, android.view.Menu arg1) {
if (callbackOptions[CB_MENU_OPENED]) {
super.onMenuOpened(arg0, arg1);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_menu_opened", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onMenuOpened(arg0, arg1);
}
}
public void onNewIntent(android.content.Intent arg0) {
if (callbackOptions[CB_NEW_INTENT]) {
super.onNewIntent(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_new_intent", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onNewIntent(arg0);
}
}
public boolean onOptionsItemSelected(android.view.MenuItem arg0) {
if (callbackOptions[CB_OPTIONS_ITEM_SELECTED]) {
super.onOptionsItemSelected(arg0);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_options_item_selected", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onOptionsItemSelected(arg0);
}
}
public void onOptionsMenuClosed(android.view.Menu arg0) {
if (callbackOptions[CB_OPTIONS_MENU_CLOSED]) {
super.onOptionsMenuClosed(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_options_menu_closed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onOptionsMenuClosed(arg0);
}
}
public void onPanelClosed(int arg0, android.view.Menu arg1) {
if (callbackOptions[CB_PANEL_CLOSED]) {
super.onPanelClosed(arg0, arg1);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_panel_closed", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onPanelClosed(arg0, arg1);
}
}
public void onPause() {
if (callbackOptions[CB_PAUSE]) {
super.onPause();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_pause");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onPause();
}
}
public void onPostCreate(android.os.Bundle arg0) {
if (callbackOptions[CB_POST_CREATE]) {
super.onPostCreate(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_post_create", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onPostCreate(arg0);
}
}
public void onPostResume() {
if (callbackOptions[CB_POST_RESUME]) {
super.onPostResume();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_post_resume");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onPostResume();
}
}
public void onPrepareDialog(int arg0, android.app.Dialog arg1, android.os.Bundle arg2) {
if (callbackOptions[CB_PREPARE_DIALOG]) {
super.onPrepareDialog(arg0, arg1, arg2);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_prepare_dialog", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onPrepareDialog(arg0, arg1, arg2);
}
}
public boolean onPrepareOptionsMenu(android.view.Menu arg0) {
if (callbackOptions[CB_PREPARE_OPTIONS_MENU]) {
super.onPrepareOptionsMenu(arg0);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_prepare_options_menu", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onPrepareOptionsMenu(arg0);
}
}
public boolean onPreparePanel(int arg0, android.view.View arg1, android.view.Menu arg2) {
if (callbackOptions[CB_PREPARE_PANEL]) {
super.onPreparePanel(arg0, arg1, arg2);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_prepare_panel", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onPreparePanel(arg0, arg1, arg2);
}
}
public void onRestart() {
if (callbackOptions[CB_RESTART]) {
super.onRestart();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_restart");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onRestart();
}
}
public void onRestoreInstanceState(android.os.Bundle arg0) {
if (callbackOptions[CB_RESTORE_INSTANCE_STATE]) {
super.onRestoreInstanceState(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_restore_instance_state", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onRestoreInstanceState(arg0);
}
}
public void onResume() {
if (callbackOptions[CB_RESUME]) {
super.onResume();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_resume");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onResume();
}
}
public java.lang.Object onRetainNonConfigurationInstance() {
if (callbackOptions[CB_RETAIN_NON_CONFIGURATION_INSTANCE]) {
super.onRetainNonConfigurationInstance();
try {
return (java.lang.Object)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_retain_non_configuration_instance").toJava(java.lang.Object.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return null;
}
} else {
return super.onRetainNonConfigurationInstance();
}
}
public void onSaveInstanceState(android.os.Bundle arg0) {
if (callbackOptions[CB_SAVE_INSTANCE_STATE]) {
super.onSaveInstanceState(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_save_instance_state", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onSaveInstanceState(arg0);
}
}
public boolean onSearchRequested() {
if (callbackOptions[CB_SEARCH_REQUESTED]) {
super.onSearchRequested();
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_search_requested").toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onSearchRequested();
}
}
public void onStart() {
if (callbackOptions[CB_START]) {
super.onStart();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_start");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onStart();
}
}
public void onStop() {
if (callbackOptions[CB_STOP]) {
super.onStop();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_stop");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onStop();
}
}
public void onTitleChanged(java.lang.CharSequence arg0, int arg1) {
if (callbackOptions[CB_TITLE_CHANGED]) {
super.onTitleChanged(arg0, arg1);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_title_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onTitleChanged(arg0, arg1);
}
}
public boolean onTouchEvent(android.view.MotionEvent arg0) {
if (callbackOptions[CB_TOUCH_EVENT]) {
super.onTouchEvent(arg0);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_touch_event", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onTouchEvent(arg0);
}
}
public boolean onTrackballEvent(android.view.MotionEvent arg0) {
if (callbackOptions[CB_TRACKBALL_EVENT]) {
super.onTrackballEvent(arg0);
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_trackball_event", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return super.onTrackballEvent(arg0);
}
}
public void onUserInteraction() {
if (callbackOptions[CB_USER_INTERACTION]) {
super.onUserInteraction();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_user_interaction");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onUserInteraction();
}
}
public void onUserLeaveHint() {
if (callbackOptions[CB_USER_LEAVE_HINT]) {
super.onUserLeaveHint();
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_user_leave_hint");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onUserLeaveHint();
}
}
public void onWindowAttributesChanged(android.view.WindowManager.LayoutParams arg0) {
if (callbackOptions[CB_WINDOW_ATTRIBUTES_CHANGED]) {
super.onWindowAttributesChanged(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_window_attributes_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onWindowAttributesChanged(arg0);
}
}
public void onWindowFocusChanged(boolean arg0) {
if (callbackOptions[CB_WINDOW_FOCUS_CHANGED]) {
super.onWindowFocusChanged(arg0);
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_window_focus_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
} else {
super.onWindowFocusChanged(arg0);
}
}
/*
* android.hardware.SensorEventListener
*/
public void onAccuracyChanged(android.hardware.Sensor arg0, int arg1) {
if (callbackOptions[CB_ACCURACY_CHANGED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_accuracy_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
public void onSensorChanged(android.hardware.SensorEvent arg0) {
if (callbackOptions[CB_SENSOR_CHANGED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_sensor_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* java.lang.Runnable
*/
public void run() {
if (callbackOptions[CB_RUN]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "run");
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.view.View$OnCreateContextMenuListener
*/
/*
* android.view.View$OnClickListener
*/
public void onClick(android.view.View arg0) {
if (callbackOptions[CB_CLICK]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_click", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.view.View$OnFocusChangeListener
*/
public void onFocusChange(android.view.View arg0, boolean arg1) {
if (callbackOptions[CB_FOCUS_CHANGE]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_focus_change", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.view.View$OnLongClickListener
*/
public boolean onLongClick(android.view.View arg0) {
if (callbackOptions[CB_LONG_CLICK]) {
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_long_click", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return false;
}
}
/*
* android.view.View$OnTouchListener
*/
public boolean onTouch(android.view.View arg0, android.view.MotionEvent arg1) {
if (callbackOptions[CB_TOUCH]) {
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_touch", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return false;
}
}
/*
* android.view.View$OnKeyListener
*/
public boolean onKey(android.view.View arg0, int arg1, android.view.KeyEvent arg2) {
if (callbackOptions[CB_KEY]) {
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_key", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return false;
}
}
/*
* android.widget.AdapterView$OnItemSelectedListener
*/
public void onItemSelected(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3) {
if (callbackOptions[CB_ITEM_SELECTED]) {
try {
IRubyObject[] args = {JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2), JavaUtil.convertJavaToRuby(__ruby__, arg3)};
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_item_selected", args);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
public void onNothingSelected(android.widget.AdapterView arg0) {
if (callbackOptions[CB_NOTHING_SELECTED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_nothing_selected", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.widget.AdapterView$OnItemLongClickListener
*/
public boolean onItemLongClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3) {
if (callbackOptions[CB_ITEM_LONG_CLICK]) {
try {
IRubyObject[] args = {JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2), JavaUtil.convertJavaToRuby(__ruby__, arg3)};
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_item_long_click", args).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return false;
}
}
/*
* android.widget.AdapterView$OnItemClickListener
*/
public void onItemClick(android.widget.AdapterView arg0, android.view.View arg1, int arg2, long arg3) {
if (callbackOptions[CB_ITEM_CLICK]) {
try {
IRubyObject[] args = {JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2), JavaUtil.convertJavaToRuby(__ruby__, arg3)};
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_item_click", args);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.view.ViewGroup$OnHierarchyChangeListener
*/
public void onChildViewAdded(android.view.View arg0, android.view.View arg1) {
if (callbackOptions[CB_CHILD_VIEW_ADDED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_child_view_added", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
public void onChildViewRemoved(android.view.View arg0, android.view.View arg1) {
if (callbackOptions[CB_CHILD_VIEW_REMOVED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_child_view_removed", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.widget.TabHost$TabContentFactory
*/
public android.view.View createTabContent(java.lang.String arg0) {
if (callbackOptions[CB_CREATE_TAB_CONTENT]) {
try {
return (android.view.View)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "create_tab_content", JavaUtil.convertJavaToRuby(__ruby__, arg0)).toJava(android.view.View.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return null;
}
} else {
return null;
}
}
/*
* android.widget.TabHost$OnTabChangeListener
*/
public void onTabChanged(java.lang.String arg0) {
if (callbackOptions[CB_TAB_CHANGED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_tab_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.widget.TextView$OnEditorActionListener
*/
public boolean onEditorAction(android.widget.TextView arg0, int arg1, android.view.KeyEvent arg2) {
if (callbackOptions[CB_EDITOR_ACTION]) {
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_editor_action", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return false;
}
}
/*
* android.widget.DatePicker$OnDateChangedListener
*/
public void onDateChanged(android.widget.DatePicker arg0, int arg1, int arg2, int arg3) {
if (callbackOptions[CB_DATE_CHANGED]) {
try {
IRubyObject[] args = {JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2), JavaUtil.convertJavaToRuby(__ruby__, arg3)};
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_date_changed", args);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.widget.TimePicker$OnTimeChangedListener
*/
public void onTimeChanged(android.widget.TimePicker arg0, int arg1, int arg2) {
if (callbackOptions[CB_TIME_CHANGED]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_time_changed", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.app.DatePickerDialog$OnDateSetListener
*/
public void onDateSet(android.widget.DatePicker arg0, int arg1, int arg2, int arg3) {
if (callbackOptions[CB_DATE_SET]) {
try {
IRubyObject[] args = {JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2), JavaUtil.convertJavaToRuby(__ruby__, arg3)};
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_date_set", args);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.app.TimePickerDialog$OnTimeSetListener
*/
public void onTimeSet(android.widget.TimePicker arg0, int arg1, int arg2) {
if (callbackOptions[CB_TIME_SET]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_time_set", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.content.DialogInterface$OnKeyListener
*/
public boolean onKey(android.content.DialogInterface arg0, int arg1, android.view.KeyEvent arg2) {
if (callbackOptions[CB_DIALOG_KEY]) {
try {
return (Boolean)RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_dialog_key", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2)).toJava(boolean.class);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
return false;
}
} else {
return false;
}
}
/*
* android.content.DialogInterface$OnMultiChoiceClickListener
*/
public void onClick(android.content.DialogInterface arg0, int arg1, boolean arg2) {
if (callbackOptions[CB_DIALOG_MULTI_CHOICE_CLICK]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_dialog_multi_choice_click", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.content.DialogInterface$OnClickListener
*/
public void onClick(android.content.DialogInterface arg0, int arg1) {
if (callbackOptions[CB_DIALOG_CLICK]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_dialog_click", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.content.DialogInterface$OnShowListener
*/
public void onShow(android.content.DialogInterface arg0) {
if (callbackOptions[CB_SHOW]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_show", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.content.DialogInterface$OnDismissListener
*/
public void onDismiss(android.content.DialogInterface arg0) {
if (callbackOptions[CB_DISMISS]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_dismiss", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* android.content.DialogInterface$OnCancelListener
*/
public void onCancel(android.content.DialogInterface arg0) {
if (callbackOptions[CB_CANCEL]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_cancel", JavaUtil.convertJavaToRuby(__ruby__, arg0));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
/*
* none
*/
public void onDraw(android.view.View arg0, android.graphics.Canvas arg1) {
if (callbackOptions[CB_DRAW]) {
try {
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_draw", JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1));
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
public void onSizeChanged(android.view.View arg0, int arg1, int arg2, int arg3, int arg4) {
if (callbackOptions[CB_SIZE_CHANGED]) {
try {
IRubyObject[] args = {JavaUtil.convertJavaToRuby(__ruby__, arg0), JavaUtil.convertJavaToRuby(__ruby__, arg1), JavaUtil.convertJavaToRuby(__ruby__, arg2), JavaUtil.convertJavaToRuby(__ruby__, arg3), JavaUtil.convertJavaToRuby(__ruby__, arg4)};
RuntimeHelpers.invoke(__ruby__.getCurrentContext(), __this__, "on_size_changed", args);
} catch (RaiseException re) {
re.printStackTrace(__ruby__.getErrorStream());
}
}
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package org.usfirst.frc5107;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.DriverStationLCD.Line;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Preferences;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Victor;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Chell extends SimpleRobot {
/**
* This function is called once each time the robot enters autonomous mode.
*/
//Outputs start
RobotDrive drive = new RobotDrive(1,2); //Base drive PWM 1&2
Jaguar cMotor1 = new Jaguar(3); //First gearbox motor PWM 3
Jaguar cMotor2 = new Jaguar(4); //Second gearbox motor PWM 4
Servo cameraPan = new Servo(5); //Axis camera pan PWM 5
Servo cameraTilt = new Servo(6); //Axis camera tilt PWM 6
Victor cFeed = new Victor(7); //Claw feed motor PWM 7
Victor cScrew = new Victor(8); //Leadscrew Motor PWM 8
Solenoid solenoid1 = new Solenoid(1); //Pneumatic Solenoid 1 SOLENOID 1
Solenoid solenoid2 = new Solenoid(2); //Pneumatic Solenoid 2 SOLENOID 2
//Outputs end
//Inputs start
Joystick leftStick = new Joystick(1); //Left joystick
Joystick rightStick = new Joystick(2); //Right joystick
DigitalInput clawLimit = new DigitalInput(2); //Winch limit switch DIO 2
DigitalInput screwUp = new DigitalInput(3); //Claw up limit DIO 3
DigitalInput screwDown = new DigitalInput(4); //Claw down limit DIO 4
//Inputs end
Compressor compressor = new Compressor(1,1); //Air compressor DIO 1 & RELAY 1
Preferences prefs;
double cMotorSpeed; //Claw gearbox motor speed
double cFeedSpeed; //Claw feed motor speed
double cScrewSpeed; //Claw leadscrew speed
public Chell(){
prefs.putDouble("Gearbox Speed", .25);
prefs.putDouble("Feed Motor Speed", .25);
prefs.putDouble("Claw Leadscrew Speed", .25);
}
public void autonomous() {
//Variables start
//cMotorSpeed = prefs.getDouble("GearboxSpeed", .25);
//cFeedSpeed = prefs.getDouble("FeedMotorSpeed", .25);
//cScrewSpeed = prefs.getDouble("ClawLeadscrewSpeed", .25);
//Variables end
compressor.enabled();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
drive.setSafetyEnabled(false); //TESTING PURPOSES
//Variables start
cMotorSpeed = prefs.getDouble("Gearbox Speed", .25);
cFeedSpeed = prefs.getDouble("Feed Motor Speed", .25);
cScrewSpeed = prefs.getDouble("Claw Leadscrew Speed", .25);
//Variables end
DriverStationLCD.getInstance().println(Line.kUser2, 1, "Gearbox Speed:"+cMotorSpeed);
DriverStationLCD.getInstance().println(Line.kUser3, 1, "Feed Motor Speed:"+cFeedSpeed);
DriverStationLCD.getInstance().println(Line.kUser4, 1, "Claw Leadscrew Speed:"+cScrewSpeed);
DriverStationLCD.getInstance().updateLCD();
compressor.enabled();
while(true && isOperatorControl() && isEnabled()){
System.out.println("Teleop Start");
DriverStationLCD.getInstance().println(Line.kUser1, 1, "TeleOp Start");
DriverStationLCD.getInstance().updateLCD();
drive.tankDrive(leftStick, rightStick); //Tank drive
//Gearbox motor control start
while(leftStick.getTrigger() && clawLimit.get()== false)
{
cMotor1.set(cMotorSpeed);
cMotor2.set(cMotorSpeed);
}
cMotor1.set(0);
cMotor2.set(0);
//Gearbox motor control end
//Fire code start
if(rightStick.getTrigger() && clawLimit.get() == true){
solenoid1.set(true);
solenoid2.set(false);
}
else
{
solenoid1.set(false);
solenoid2.set(true);
}
//Fire code end
//Compressor Auto start
//while(compressor.getPressureSwitchValue()==true){
// compressor.start();
//Compressor Auto end
//Claw Feed Motor start
while(leftStick.getRawButton(3)){
cFeed.set(cFeedSpeed);
}
while(leftStick.getRawButton(2)){
cFeed.set(-cFeedSpeed);
}
cFeed.set(0);
//Claw Feed Motor end
//Enter servo code here
//Claw Up and Down start
while(rightStick.getRawButton(3)&&screwUp.get()==false){
System.out.println("UP");
cScrew.set(-.25);
}
while(rightStick.getRawButton(2)&&screwDown.get()==false){
System.out.println("DOWN");
cScrew.set(.25);
//Claw Up and Down end
}
cScrew.set(0);
}
}
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
}
|
package org.webchecker.forms;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
/**
* HTML form element.
* Allows user to fill in form {@link Input}s of supported {@link Type}s
* and {@link Form#send} either by {@link Method#GET} or {@link Method#POST} method.
*
* @author Tunik
* @version 1.0
*/
public class Form {
private URL action;
private Method method;
private ArrayList<Input> inputs = new ArrayList<Input>();
/**
* Construct all inner structure of the form. Its inputs, action and method.
* Includes only inputs of known types and inputs with names!
*
* @param formElement is HTML element extracted from document
* @param location is {@link URL}
*/
public Form(Element formElement, URL location) {
setAction(location, formElement.attr("action"));
String methodstr = formElement.attr("method");
method = Method.valueOf(methodstr.equals("") ? "GET" : methodstr.toUpperCase());
Elements radioInputs = new Elements();
Input radioinput = processRadioInputs(formElement.getElementsByTag("input[type=\"radio\"]"));
if (radioinput == null) {}
else {inputs.add(radioinput);}
for (Element input : formElement.getElementsByTag("input")) {
if (!input.attr("type").equals("radio") && Type.containsType(input.attr("type"))) {
String name = input.attr("name");
Type type = Type.valueOf(input.attr("type").toUpperCase());
String value = (input.attr("value") == null) ? "" : input.attr("value");
inputs.add(new Input(name, type, value));
}else if (Type.containsType(input.attr("type"))){
radioInputs.add(input);
}
}
Input radioinputs = processRadioInputs(radioInputs);
if (radioinputs == null) {}
else {inputs.add(radioinputs);}
}
/**
* Support method for creating full path url of action.
*
* @param location is {@link URL} of file from which application download {@link Document}
* @param action is absolute or relative address. This address is one of attributes of HTML form
*/
public void setAction(URL location, String action){
try {
this.action = new URL(location, action);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* Support method for dealing with radio inputs, because of theirs possibility to have same name.
*
* @param inputs with type radio
* @return radio input which have attribute 'checked'
*/
private Input processRadioInputs(Elements inputs) {
if(inputs == null) return null;
for (Element input : inputs){
if(input.hasAttr("checked"))
return new Input(input.attr("name"), Type.RADIO, input.attr("checked"));
}
return null;
}
/**
* Returns collection of {@link Input} for user to see them and possibility of filling them.
* {@link Input} with {@code null} {@link Input#value} will not be {@link Form#send()} in request,
* on the other hand every other {@link Input} will.
* {@link Input}s are not checked for rightness of theirs values e.g. you can set {@link Input#value} for checkbox complete different,
* then it was originally there.
*
* @return collection of {@link Input} for user to see them and possibility of filling them
*/
public ArrayList<Input> getInputs() {
return inputs;
}
/**
* Gives user the possibility to fill all the {@link Input}s at once with predefined collection of pairs.
* First item in the pair represents {@link Input#name} and second one represents {@link Input#value}.
* If filled value is {@code null}, then this {@link Input} won't be {@link Form#send()}.
*
* @param inputsValues collection of pairs, where first item represents {@link Input#name} and second one represents {@link Input#value}
*/
public void fill(HashMap<String, String> inputsValues) {
for (Input input : this.inputs) {
if (inputsValues.containsKey(input.getName()))
input.setValue(inputsValues.get(input.getName()));
}
}
/**
* Send {@link Form} in current filled/part-filled/not filled state to his {@link Form#action} url address.
* Sending proceeds different depending on {@link Form#method}, which can be {@link Method#GET} or {@link Method#POST}.
* When sending fail in some way or response status code is different from 200, application wil return {@link null}
*
* @return response page in form of {@link Document}
*/
public Document send() {
HashMap<String, String> inputsMap = new HashMap<>();
inputs.forEach(input -> inputsMap.put(input.getName(), input.getValue()));
try {
Connection.Response response = Jsoup.connect(action.getPath()).data(inputsMap).method(method).execute();
if(response.statusCode() == 200)
return response.parse();
return null;
} catch (IOException e) {
return null;
}
}
/**
* Getter for {@link Form#action} {@link URL} address setup in construction of the {@link Form}.
*
* @return {@link Form#action} {@link URL} address
*/
public URL getAction() {
return action;
}
/**
* Getter for {@link Form#method} type setup in construction of the {@link Form}.
* This type could be either {@link Method#GET} or {@link Method#POST}.
*
* @return {@link Form#method} type
*/
public Method getMethod() {
return method;
}
}
|
package com.mychess.mychess;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mychess.mychess.Chess.Chess;
import com.mychess.mychess.Chess.Ubicacion;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.zip.Inflater;
public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
Servicio mService;
boolean mBound = false;
ImageView casillas[][] = new ImageView[8][8];
ImageView origen;
ImageView destino;
TextView tiempo;
Tiempo tiempoMovimiento;
TextView nombreColumnas[] = new TextView[8];
TextView numeroFila[] = new TextView[8];
int cOrigen;
int cDestino;
int fOrigen;
int fDestino;
boolean enroqueBlanco = true;
boolean enroqueNegro = true;
boolean jugadaLocal;// sirve para difenciar entre una jugada local y una remota
boolean juegoIniciado;
Chess chess;
TextView nombreUsuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inicializarCasillasBlanco();
setOnclickListener();
setDefaultColor();
juegoIniciado = false;
nombreUsuario = (TextView) findViewById(R.id.nombreUsuario);
nombreUsuario.setText(new Usuario(getApplicationContext()).getUsuario());
tiempo = (TextView) findViewById(R.id.textView18);
tiempoMovimiento = new Tiempo();
/* inicializcion del nuevo juego*/
chess = new Chess();
chess.newGame();
new SocketServidor().conectar();
new RecibirInvitacion().execute();
RecibirMovimientos recibirMovimientos = new RecibirMovimientos();
recibirMovimientos.execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!juegoIniciado)
Toast.makeText(Juego.this, "No ha iniciado un juego todavía", Toast.LENGTH_SHORT).show();
else if (jugadaLocal) {
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
Speech speech = new Speech();
speechRecognizer.setRecognitionListener(speech);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizer.startListening(intent);
} else
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, Servicio.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.juego, menu);
if (juegoIniciado)
return true;
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.jugar) {
// Handle the camera action
} else if (id == R.id.amigos) {
Intent intent = new Intent(Juego.this, Amigos.class);
startActivity(intent);
} else if (id == R.id.logout) {
DialogInterface.OnClickListener listenerOk = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new Usuario(getApplicationContext()).clear();
Intent intent = new Intent(Juego.this, Acceso.class);
startActivity(intent);
finish();
}
};
DialogInterface.OnClickListener listenerCanclar = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Mensaje");
builder.setMessage("¿Está seguro que desea salir?");
builder.setPositiveButton("Cerrar Sesión", listenerOk);
builder.setNegativeButton("Cancelar", listenerCanclar);
builder.create();
builder.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void inicializarCampos(int n) {
nombreColumnas[0] = (TextView) findViewById(R.id.columnaa);
nombreColumnas[1] = (TextView) findViewById(R.id.columnab);
nombreColumnas[2] = (TextView) findViewById(R.id.columnac);
nombreColumnas[3] = (TextView) findViewById(R.id.columnad);
nombreColumnas[4] = (TextView) findViewById(R.id.columnae);
nombreColumnas[5] = (TextView) findViewById(R.id.columnaf);
nombreColumnas[6] = (TextView) findViewById(R.id.columnag);
nombreColumnas[7] = (TextView) findViewById(R.id.columnah);
numeroFila[0] = (TextView) findViewById(R.id.fila1);
numeroFila[1] = (TextView) findViewById(R.id.fila2);
numeroFila[2] = (TextView) findViewById(R.id.fila3);
numeroFila[3] = (TextView) findViewById(R.id.fila4);
numeroFila[4] = (TextView) findViewById(R.id.fila5);
numeroFila[5] = (TextView) findViewById(R.id.fila6);
numeroFila[6] = (TextView) findViewById(R.id.fila7);
numeroFila[7] = (TextView) findViewById(R.id.fila8);
nombreColumnas[0].setText("a");
nombreColumnas[1].setText("b");
nombreColumnas[2].setText("c");
nombreColumnas[3].setText("d");
nombreColumnas[4].setText("e");
nombreColumnas[5].setText("f");
nombreColumnas[6].setText("g");
nombreColumnas[7].setText("h");
numeroFila[0].setText("1");
numeroFila[1].setText("2");
numeroFila[2].setText("3");
numeroFila[3].setText("4");
numeroFila[4].setText("5");
numeroFila[5].setText("6");
numeroFila[6].setText("7");
numeroFila[7].setText("8");
if (n == 2) {
nombreColumnas[0].setText("h");
nombreColumnas[1].setText("g");
nombreColumnas[2].setText("f");
nombreColumnas[3].setText("e");
nombreColumnas[4].setText("d");
nombreColumnas[5].setText("c");
nombreColumnas[6].setText("b");
nombreColumnas[7].setText("a");
numeroFila[0].setText("8");
numeroFila[1].setText("7");
numeroFila[2].setText("6");
numeroFila[3].setText("5");
numeroFila[4].setText("4");
numeroFila[5].setText("3");
numeroFila[6].setText("2");
numeroFila[7].setText("1");
}
}
private void inicializarCasillasBlanco() {
casillas[0][0] = (ImageView) findViewById(R.id.a8);
casillas[0][1] = (ImageView) findViewById(R.id.a7);
casillas[0][2] = (ImageView) findViewById(R.id.a6);
casillas[0][3] = (ImageView) findViewById(R.id.a5);
casillas[0][4] = (ImageView) findViewById(R.id.a4);
casillas[0][5] = (ImageView) findViewById(R.id.a3);
casillas[0][6] = (ImageView) findViewById(R.id.a2);
casillas[0][7] = (ImageView) findViewById(R.id.a1);
casillas[1][0] = (ImageView) findViewById(R.id.b8);
casillas[1][1] = (ImageView) findViewById(R.id.b7);
casillas[1][2] = (ImageView) findViewById(R.id.b6);
casillas[1][3] = (ImageView) findViewById(R.id.b5);
casillas[1][4] = (ImageView) findViewById(R.id.b4);
casillas[1][5] = (ImageView) findViewById(R.id.b3);
casillas[1][6] = (ImageView) findViewById(R.id.b2);
casillas[1][7] = (ImageView) findViewById(R.id.b1);
casillas[2][0] = (ImageView) findViewById(R.id.c8);
casillas[2][1] = (ImageView) findViewById(R.id.c7);
casillas[2][2] = (ImageView) findViewById(R.id.c6);
casillas[2][3] = (ImageView) findViewById(R.id.c5);
casillas[2][4] = (ImageView) findViewById(R.id.c4);
casillas[2][5] = (ImageView) findViewById(R.id.c3);
casillas[2][6] = (ImageView) findViewById(R.id.c2);
casillas[2][7] = (ImageView) findViewById(R.id.c1);
casillas[3][0] = (ImageView) findViewById(R.id.d8);
casillas[3][1] = (ImageView) findViewById(R.id.d7);
casillas[3][2] = (ImageView) findViewById(R.id.d6);
casillas[3][3] = (ImageView) findViewById(R.id.d5);
casillas[3][4] = (ImageView) findViewById(R.id.d4);
casillas[3][5] = (ImageView) findViewById(R.id.d3);
casillas[3][6] = (ImageView) findViewById(R.id.d2);
casillas[3][7] = (ImageView) findViewById(R.id.d1);
casillas[4][0] = (ImageView) findViewById(R.id.e8);
casillas[4][1] = (ImageView) findViewById(R.id.e7);
casillas[4][2] = (ImageView) findViewById(R.id.e6);
casillas[4][3] = (ImageView) findViewById(R.id.e5);
casillas[4][4] = (ImageView) findViewById(R.id.e4);
casillas[4][5] = (ImageView) findViewById(R.id.e3);
casillas[4][6] = (ImageView) findViewById(R.id.e2);
casillas[4][7] = (ImageView) findViewById(R.id.e1);
casillas[5][0] = (ImageView) findViewById(R.id.f8);
casillas[5][1] = (ImageView) findViewById(R.id.f7);
casillas[5][2] = (ImageView) findViewById(R.id.f6);
casillas[5][3] = (ImageView) findViewById(R.id.f5);
casillas[5][4] = (ImageView) findViewById(R.id.f4);
casillas[5][5] = (ImageView) findViewById(R.id.f3);
casillas[5][6] = (ImageView) findViewById(R.id.f2);
casillas[5][7] = (ImageView) findViewById(R.id.f1);
casillas[6][0] = (ImageView) findViewById(R.id.g8);
casillas[6][1] = (ImageView) findViewById(R.id.g7);
casillas[6][2] = (ImageView) findViewById(R.id.g6);
casillas[6][3] = (ImageView) findViewById(R.id.g5);
casillas[6][4] = (ImageView) findViewById(R.id.g4);
casillas[6][5] = (ImageView) findViewById(R.id.g3);
casillas[6][6] = (ImageView) findViewById(R.id.g2);
casillas[6][7] = (ImageView) findViewById(R.id.g1);
casillas[7][0] = (ImageView) findViewById(R.id.h8);
casillas[7][1] = (ImageView) findViewById(R.id.h7);
casillas[7][2] = (ImageView) findViewById(R.id.h6);
casillas[7][3] = (ImageView) findViewById(R.id.h5);
casillas[7][4] = (ImageView) findViewById(R.id.h4);
casillas[7][5] = (ImageView) findViewById(R.id.h3);
casillas[7][6] = (ImageView) findViewById(R.id.h2);
casillas[7][7] = (ImageView) findViewById(R.id.h1);
colocarPiezas(1);
inicializarCampos(1);
jugadaLocal = true;
}
private void inicializarCasillasNegro() {
casillas[0][0] = (ImageView) findViewById(R.id.h1);
casillas[0][1] = (ImageView) findViewById(R.id.h2);
casillas[0][2] = (ImageView) findViewById(R.id.h3);
casillas[0][3] = (ImageView) findViewById(R.id.h4);
casillas[0][4] = (ImageView) findViewById(R.id.h5);
casillas[0][5] = (ImageView) findViewById(R.id.h6);
casillas[0][6] = (ImageView) findViewById(R.id.h7);
casillas[0][7] = (ImageView) findViewById(R.id.h8);
casillas[1][0] = (ImageView) findViewById(R.id.g1);
casillas[1][1] = (ImageView) findViewById(R.id.g2);
casillas[1][2] = (ImageView) findViewById(R.id.g3);
casillas[1][3] = (ImageView) findViewById(R.id.g4);
casillas[1][4] = (ImageView) findViewById(R.id.g5);
casillas[1][5] = (ImageView) findViewById(R.id.g6);
casillas[1][6] = (ImageView) findViewById(R.id.g7);
casillas[1][7] = (ImageView) findViewById(R.id.g8);
casillas[2][0] = (ImageView) findViewById(R.id.f1);
casillas[2][1] = (ImageView) findViewById(R.id.f2);
casillas[2][2] = (ImageView) findViewById(R.id.f3);
casillas[2][3] = (ImageView) findViewById(R.id.f4);
casillas[2][4] = (ImageView) findViewById(R.id.f5);
casillas[2][5] = (ImageView) findViewById(R.id.f6);
casillas[2][6] = (ImageView) findViewById(R.id.f7);
casillas[2][7] = (ImageView) findViewById(R.id.f8);
casillas[3][0] = (ImageView) findViewById(R.id.e1);
casillas[3][1] = (ImageView) findViewById(R.id.e2);
casillas[3][2] = (ImageView) findViewById(R.id.e3);
casillas[3][3] = (ImageView) findViewById(R.id.e4);
casillas[3][4] = (ImageView) findViewById(R.id.e5);
casillas[3][5] = (ImageView) findViewById(R.id.e6);
casillas[3][6] = (ImageView) findViewById(R.id.e7);
casillas[3][7] = (ImageView) findViewById(R.id.e8);
casillas[4][0] = (ImageView) findViewById(R.id.d1);
casillas[4][1] = (ImageView) findViewById(R.id.d2);
casillas[4][2] = (ImageView) findViewById(R.id.d3);
casillas[4][3] = (ImageView) findViewById(R.id.d4);
casillas[4][4] = (ImageView) findViewById(R.id.d5);
casillas[4][5] = (ImageView) findViewById(R.id.d6);
casillas[4][6] = (ImageView) findViewById(R.id.d7);
casillas[4][7] = (ImageView) findViewById(R.id.d8);
casillas[5][0] = (ImageView) findViewById(R.id.c1);
casillas[5][1] = (ImageView) findViewById(R.id.c2);
casillas[5][2] = (ImageView) findViewById(R.id.c3);
casillas[5][3] = (ImageView) findViewById(R.id.c4);
casillas[5][4] = (ImageView) findViewById(R.id.c5);
casillas[5][5] = (ImageView) findViewById(R.id.c6);
casillas[5][6] = (ImageView) findViewById(R.id.c7);
casillas[5][7] = (ImageView) findViewById(R.id.c8);
casillas[6][0] = (ImageView) findViewById(R.id.b1);
casillas[6][1] = (ImageView) findViewById(R.id.b2);
casillas[6][2] = (ImageView) findViewById(R.id.b3);
casillas[6][3] = (ImageView) findViewById(R.id.b4);
casillas[6][4] = (ImageView) findViewById(R.id.b5);
casillas[6][5] = (ImageView) findViewById(R.id.b6);
casillas[6][6] = (ImageView) findViewById(R.id.b7);
casillas[6][7] = (ImageView) findViewById(R.id.b8);
casillas[7][0] = (ImageView) findViewById(R.id.a1);
casillas[7][1] = (ImageView) findViewById(R.id.a2);
casillas[7][2] = (ImageView) findViewById(R.id.a3);
casillas[7][3] = (ImageView) findViewById(R.id.a4);
casillas[7][4] = (ImageView) findViewById(R.id.a5);
casillas[7][5] = (ImageView) findViewById(R.id.a6);
casillas[7][6] = (ImageView) findViewById(R.id.a7);
casillas[7][7] = (ImageView) findViewById(R.id.a8);
colocarPiezas(1);
inicializarCampos(2);
jugadaLocal = false;
}
private void setDefaultColor() {
boolean dark = true;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (dark)
casillas[i][j].setBackgroundResource(R.color.casillablanca);
else
casillas[i][j].setBackgroundResource(R.color.casillnegra);
dark = !dark;
}
dark = !dark;
}
}
private void colocarPiezas(int bando) {
casillas[0][7].setImageResource(bando == 1 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[7][7].setImageResource(bando == 1 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[2][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[3][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[4][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[5][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[6][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[7][6].setImageResource(bando == 1 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][7].setImageResource(bando == 1 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[6][7].setImageResource(bando == 1 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[2][7].setImageResource(bando == 1 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[5][7].setImageResource(bando == 1 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[3][7].setImageResource(bando == 1 ? R.mipmap.alpha_wq : R.mipmap.alpha_bq);
casillas[4][7].setImageResource(bando == 1 ? R.mipmap.alpha_wk : R.mipmap.alpha_bk);
casillas[7][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][0].setImageResource(bando == 2 ? R.mipmap.alpha_wr : R.mipmap.alpha_br);
casillas[0][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[2][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[3][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[4][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[5][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[6][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[7][1].setImageResource(bando == 2 ? R.mipmap.alpha_wp : R.mipmap.alpha_bp);
casillas[1][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[6][0].setImageResource(bando == 2 ? R.mipmap.alpha_wn : R.mipmap.alpha_bn);
casillas[2][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[5][0].setImageResource(bando == 2 ? R.mipmap.alpha_wb : R.mipmap.alpha_bb);
casillas[3][0].setImageResource(bando == 2 ? R.mipmap.alpha_wq : R.mipmap.alpha_bq);
casillas[4][0].setImageResource(bando == 2 ? R.mipmap.alpha_wk : R.mipmap.alpha_bk);
}
private void setOnclickListener() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
casillas[i][j].setOnClickListener(this);
}
}
}
private int[] getPosition(int id) {
int position[] = {-1, -1};
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (id == casillas[i][j].getId()) {
position[0] = i;
position[1] = j;
return position;//si el click fue en una casilla se retorna la posicion
}
}
}
return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
}
private boolean validarCoordenadas(String coordenadas) {
final String columnas = "abcdefgh";
final String filas = "87654321";
cOrigen = columnas.indexOf(coordenadas.charAt(0));
cDestino = columnas.indexOf(coordenadas.charAt(2));
fOrigen = filas.indexOf(coordenadas.charAt(1));
fDestino = filas.indexOf(coordenadas.charAt(3));
if (cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
return false;
return true;
}
private void procesarResultados(ArrayList<String> listaCoordenadas) {
String coordenadas;
for (int i = 0; i < listaCoordenadas.size(); ++i) {
coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
if (coordenadas.length() == 4) {
if (validarCoordenadas(coordenadas)) {
validarMovimiento(coordenadas);
break;
}
}
}
}
private void enviarMovimiento(String coordendas) {
DataOutputStream out = null;
try {
out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
out.writeUTF(coordendas);
tiempoMovimiento.reiniciar();
} catch (IOException e) {
e.printStackTrace();
}
}
private void validarMovimiento(String coordenadas) {
switch (chess.mover(coordenadas.substring(0, 2), coordenadas.substring(2, 4))) {
case 2:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 3:
moverPieza(1, coordenadas);
break;
case 4:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 0:
moverPieza(2, coordenadas);
break;
}
}
private void moverPieza(int n, String coordenada) {
if (jugadaLocal) {
enviarMovimiento(crearCoordenada());
if (!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
} else {
validarCoordenadas(coordenada);
if (!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}
jugadaLocal = !jugadaLocal;
if (n == 1) {
Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show();
}
}
private boolean enroque() {
if (enroqueBlanco)
if (cOrigen == 4 && fOrigen == 7 && cDestino == 6 && fDestino == 7) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][7].setImageDrawable(casillas[7][7].getDrawable());
casillas[7][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
} else if (cOrigen == 4 && fOrigen == 7 && cDestino == 2 && fDestino == 7) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][7].setImageDrawable(casillas[0][7].getDrawable());
casillas[0][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}
if (enroqueNegro)
if (cOrigen == 4 && fOrigen == 0 && cDestino == 6 && fDestino == 0) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][0].setImageDrawable(casillas[7][0].getDrawable());
casillas[7][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
} else if (cOrigen == 4 && fOrigen == 0 && cDestino == 2 && fDestino == 0) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][0].setImageDrawable(casillas[0][0].getDrawable());
casillas[0][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}
return false;
}
private String crearCoordenada() {
String coordenada = "";
final String columnas = "abcdefgh";
final String filas = "87654321";
coordenada += columnas.charAt(cOrigen);
coordenada += filas.charAt(fOrigen);
coordenada += columnas.charAt(cDestino);
coordenada += filas.charAt(fDestino);
return coordenada;
}
@Override
public void onClick(View v) {
if (!juegoIniciado)
Toast.makeText(Juego.this, "No ha iniciado un juego todavía", Toast.LENGTH_SHORT).show();
else if (true) {
int position[] = getPosition(v.getId());
if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
if (origen == null) {
origen = casillas[position[0]][position[1]];
cOrigen = position[0];
fOrigen = position[1];
casillas[cOrigen][fOrigen].setBackgroundResource(R.color.origen);
for (Ubicacion u : chess.mostrarMovimientos(fOrigen, cOrigen)) {
casillas[u.getCol()][u.getFila()].setBackgroundResource(R.drawable.seleccion);
}
} else {
cDestino = position[0];
fDestino = position[1];
destino = casillas[cDestino][fDestino];
if (!(destino == origen)) {
validarMovimiento(crearCoordenada());
setDefaultColor();
} else
setDefaultColor();
origen = null;
}
}
} else {
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
}
class Speech implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
procesarResultados(listaPalabras);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
class Tiempo {
CountDown countDown;
public void iniciar() {
countDown = new CountDown(60000, 1000);
countDown.start();
}
public void detener() {
countDown.cancel();
}
public void reiniciar() {
tiempo.setText("60");
tiempo.setTextColor(Color.WHITE);
countDown.cancel();
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
tiempo.setText(String.valueOf(time));
if (time == 15)
tiempo.setTextColor(Color.RED);
}
@Override
public void onFinish() {
}
}
}
class RecibirMovimientos extends AsyncTask<Void, String, Boolean> {
Socket socket;
protected Boolean doInBackground(Void... params) {
socket = SocketServidor.getSocket();
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
InputStream fromServer = SocketServidor.getSocket().getInputStream();
DataInputStream in = new DataInputStream(fromServer);
publishProgress(in.readUTF());
} catch (Exception ex) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
validarMovimiento(values[0]);
Toast.makeText(Juego.this, values[0], Toast.LENGTH_SHORT).show();
tiempoMovimiento.iniciar();
}
}
class RecibirInvitacion extends AsyncTask<Void, String, Void> {
DataInputStream in;
@Override
protected Void doInBackground(Void... params) {
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
in = new DataInputStream(SocketServidor.getSocket().getInputStream());
publishProgress(in.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
DialogInterface.OnClickListener listenerOk = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
};
DialogInterface.OnClickListener listenerCanclar = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(Juego.this);
/*builder.setTitle("Alerta");
builder.setMessage(values[0]+" Te invita a jugar");*/
View v = getLayoutInflater().inflate(R.layout.invitacion,null);
TextView retador = (TextView) v.findViewById(R.id.retador);
retador.setText(values[0]);
builder.setView(v);
builder.setPositiveButton("Aceptar", listenerOk);
builder.setNegativeButton("Rechazar", listenerCanclar);
builder.create();
builder.show();
}
}
}
|
package com.t28.rxweather;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@JsonDeserialize(builder = Weather.Builder.class)
public class Weather {
private final int mCityId;
private final String mCityName;
private final String mCountryCode;
private final double mLat;
private final double mLon;
private final long mSunriseTime;
private final long mSunsetTime;
private final double mTemperature;
private final double mMinTemperature;
private final double mMaxTemperature;
private final int mHumidity;
private Weather(Builder builder) {
mCityId = builder.mCityId;
mCityName = builder.mCityName;
mCountryCode = builder.mCountryCode;
mLat = builder.mLat;
mLon = builder.mLon;
mSunriseTime = builder.mSunriseTime;
mSunsetTime = builder.mSunsetTime;
mTemperature = builder.mTemperature;
mMinTemperature = builder.mMinTemperature;
mMaxTemperature = builder.mMaxTemperature;
mHumidity = builder.mHumidity;
}
public int getCityId() {
return mCityId;
}
public String getCityName() {
return mCityName;
}
public String getCountryCode() {
return mCountryCode;
}
public double getLat() {
return mLat;
}
public double getLon() {
return mLon;
}
public long getSunriseTime() {
return mSunriseTime;
}
public long getSunsetTime() {
return mSunsetTime;
}
public double getTemperature() {
return mTemperature;
}
public double getMinTemperature() {
return mMinTemperature;
}
public double getMaxTemperature() {
return mMaxTemperature;
}
public int getHumidity() {
return mHumidity;
}
@JsonPOJOBuilder(withPrefix = "set")
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Builder {
private int mCityId;
private String mCityName;
private String mCountryCode;
private double mLat;
private double mLon;
private long mSunriseTime;
private long mSunsetTime;
private double mTemperature;
private double mMinTemperature;
private double mMaxTemperature;
private int mHumidity;
public Builder() {
}
@JsonProperty("id")
public Builder setCityId(int cityId) {
mCityId = cityId;
return this;
}
@JsonProperty("name")
public Builder setCityName(String cityName) {
mCityName = cityName;
return this;
}
public Builder setCountryCode(String countryCode) {
mCountryCode = countryCode;
return this;
}
public Builder setLat(double lat) {
mLat = lat;
return this;
}
public Builder setLon(double lon) {
mLon = lon;
return this;
}
public Builder setSunriseTime(long sunriseTime) {
mSunriseTime = sunriseTime;
return this;
}
public Builder setSunsetTime(long sunsetTime) {
mSunsetTime = sunsetTime;
return this;
}
public Builder setTemperature(double temperature) {
mTemperature = temperature;
return this;
}
public Builder setMinTemperature(double minTemperature) {
mMinTemperature = minTemperature;
return this;
}
public Builder setMaxTemperature(double maxTemperature) {
mMaxTemperature = maxTemperature;
return this;
}
public Builder setHumidity(int humidity) {
mHumidity = humidity;
return this;
}
public Weather build() {
return new Weather(this);
}
}
}
|
package pro.javacard.ant;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.FileVisitResult;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Jar;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.Environment.Variable;
import org.apache.tools.ant.types.Path;
public class JavaCard extends Task {
private static enum JC {
NONE, V212, V221, V222, V3;
@Override
public String toString() {
if (this.equals(V3))
return "v3.x";
if (this.equals(V222))
return "v2.2.2";
if (this.equals(V221))
return "v2.2.1";
if (this.equals(V212))
return "v2.1.x";
return "unknown";
}
}
private class JavaCardKit {
JC version = JC.NONE;
String path = null;
}
private String master_jckit_path = null;
private Vector<JCCap> packages = new Vector<>();
private static String hexAID(byte[] aid) {
StringBuffer hexaid = new StringBuffer();
for (byte b : aid) {
hexaid.append(String.format("0x%02X", b));
hexaid.append(":");
}
String hex = hexaid.toString();
// Cut off the final colon
return hex.substring(0, hex.length() - 1);
}
public void setJCKit(String msg) {
master_jckit_path = msg;
}
/**
* Given a path, return a meta-info object about possible JavaCard SDK in that path.
*
* @param path raw string as present in build.xml or environment, or <code>null</code>
*
* @return a {@link JavaCardKit} instance
*/
public JavaCardKit detectSDK(String path) {
JavaCardKit detected = new JavaCardKit();
if (path == null || path.trim() == "") {
return detected;
}
// Expand user
String real_path = path.replaceFirst("^~", System.getProperty("user.home"));
// Check if path is OK
if (!new File(real_path).exists()) {
log("JavaCard SDK folder " + path + " does not exist!", Project.MSG_WARN);
return detected;
}
detected.path = real_path;
// Identify jckit type
if (Paths.get(detected.path, "lib", "tools.jar").toFile().exists()) {
log("JavaCard 3.x SDK detected in " + detected.path, Project.MSG_VERBOSE);
detected.version = JC.V3;
} else if (Paths.get(detected.path, "lib", "api21.jar").toFile().exists()) {
detected.version = JC.V212;
log("JavaCard 2.1.x SDK detected in " + detected.path, Project.MSG_VERBOSE);
} else if (Paths.get(detected.path, "lib", "converter.jar").toFile().exists()) {
// Detect if 2.2.1 or 2.2.2
File api = Paths.get(detected.path, "lib", "api.jar").toFile();
try (ZipInputStream zip = new ZipInputStream(new FileInputStream(api))) {
while (true) {
ZipEntry entry = zip.getNextEntry();
if (entry == null) {
break;
}
if (entry.getName().equals("javacardx/apdu/ExtendedLength.class")) {
detected.version = JC.V222;
log("JavaCard 2.2.2 SDK detected in " + detected.path, Project.MSG_VERBOSE);
}
}
} catch (IOException e) {
log("Could not parse api.jar", Project.MSG_DEBUG);
} finally {
// Assume older SDK if jar parsing fails.
if (detected.version == JC.NONE) {
detected.version = JC.V221;
log("JavaCard 2.x SDK detected in " + detected.path, Project.MSG_VERBOSE);
}
}
} else {
log("Could not detect a JavaCard SDK in " + Paths.get(path).toAbsolutePath(), Project.MSG_WARN);
}
return detected;
}
public JCCap createCap() {
JCCap pkg = new JCCap();
packages.add(pkg);
return pkg;
}
@Override
public void execute() {
for (JCCap p : packages) {
p.execute();
}
}
public class JCApplet {
private String klass = null;
private byte[] aid = null;
public JCApplet() {
}
public void setClass(String msg) {
klass = msg;
}
public void setAID(String msg) {
try {
aid = stringToBin(msg);
if (aid.length < 5 || aid.length > 16) {
throw new BuildException("Applet AID must be between 5 and 16 bytes: " + aid.length);
}
} catch (IllegalArgumentException e) {
throw new BuildException("Not a correct applet AID: " + e.getMessage());
}
}
}
@SuppressWarnings("serial")
public class HelpingBuildException extends BuildException {
public HelpingBuildException(String msg) {
super(msg + "\n\nPLEASE READ https://github.com/martinpaljak/ant-javacard#syntax");
}
}
public class JCCap extends Task {
private JavaCardKit jckit = null;
private String classes_path = null;
private String sources_path = null;
private String package_name = null;
private byte[] package_aid = null;
private String package_version = null;
private Vector<JCApplet> raw_applets = new Vector<>();
private Vector<JCImport> raw_imports = new Vector<>();
private String output_cap = null;
private String output_exp = null;
private String output_jca = null;
private String jckit_path = null;
private boolean verify = true;
private boolean debug = false;
private List<java.nio.file.Path> temporary = new ArrayList<>();
public JCCap() {
}
public void setJCKit(String msg) {
jckit_path = msg;
}
public void setOutput(String msg) {
output_cap = msg;
}
public void setExport(String msg) {
output_exp = msg;
}
public void setJca(String msg) {
output_jca = msg;
}
public void setPackage(String msg) {
package_name = msg;
}
public void setClasses(String msg) {
classes_path = msg;
}
public void setVersion(String msg) {
package_version = msg;
}
public void setSources(String arg) {
sources_path = arg;
}
public void setVerify(boolean arg) {
verify = arg;
}
public void setDebug(boolean arg) {
debug = arg;
}
public void setAID(String msg) {
try {
package_aid = stringToBin(msg);
if (package_aid.length < 5 || package_aid.length > 16)
throw new BuildException("Package AID must be between 5 and 16 bytes: " + package_aid.length);
} catch (IllegalArgumentException e) {
throw new BuildException("Not a correct package AID: " + e.getMessage());
}
}
/** Many applets inside one package */
public JCApplet createApplet() {
JCApplet applet = new JCApplet();
raw_applets.add(applet);
return applet;
}
/** Many imports inside one package */
public JCImport createImport() {
JCImport imp = new JCImport();
raw_imports.add(imp);
return imp;
}
// Check that arguments are sufficient and do some DWIM
private void check() {
JavaCardKit env = detectSDK(System.getenv("JC_HOME"));
JavaCardKit prop = detectSDK(getProject().getProperty("jc.home"));
JavaCardKit master = detectSDK(master_jckit_path);
JavaCardKit current = detectSDK(jckit_path);
if (current.version == JC.NONE && master.version == JC.NONE && env.version == JC.NONE && prop.version == JC.NONE) {
throw new HelpingBuildException("Must specify usable JavaCard SDK path in build.xml or set JC_HOME or jc.home");
}
if (current.version == JC.NONE) {
// if master path is specified but is not usable,
// override with environment, variable, if usable
if (prop.version != JC.NONE) {
jckit = prop;
} else if (master.version == JC.NONE && env.version != JC.NONE) {
jckit = env;
} else {
jckit = master;
}
} else {
if (prop.version != JC.NONE) {
jckit = prop;
} else {
jckit = current;
}
}
// Sanity check
if (jckit == null || jckit.version == JC.NONE) {
throw new HelpingBuildException("No usable JavaCard SDK referenced");
} else {
log("INFO: using JavaCard " + jckit.version + " SDK in " + jckit.path, Project.MSG_INFO);
}
// sources or classes must be set
if (sources_path == null && classes_path == null) {
throw new HelpingBuildException("Must specify sources or classes");
}
// Check package version
if (package_version == null) {
package_version = "0.0";
} else {
if (!package_version.matches("^[0-9].[0-9]$")) {
throw new HelpingBuildException("Incorrect package version: " + package_version);
}
}
// Construct applets and fill in missing bits from package info, if
int applet_counter = 0;
// necessary
for (JCApplet a : raw_applets) {
// Keep count for automagic numbering
applet_counter = applet_counter + 1;
if (a.klass == null) {
throw new HelpingBuildException("Applet class is missing");
}
// If package name is present, must match the applet
if (package_name != null) {
if (!a.klass.contains(".")) {
a.klass = package_name + "." + a.klass;
} else if (!a.klass.startsWith(package_name)) {
throw new HelpingBuildException("Applet class " + a.klass + " is not in package " + package_name);
}
} else {
String pkgname = a.klass.substring(0, a.klass.lastIndexOf("."));
log("Setting package name to " + pkgname, Project.MSG_INFO);
package_name = pkgname;
}
// If applet AID is present, must match the package AID
if (package_aid != null) {
if (a.aid != null) {
// RID-s must match
if (!Arrays.equals(Arrays.copyOf(package_aid, 5), Arrays.copyOf(a.aid, 5))) {
throw new HelpingBuildException("Package RID does not match Applet RID");
}
} else {
// make "magic" applet AID from package_aid + counter
a.aid = Arrays.copyOf(package_aid, package_aid.length + 1);
a.aid[package_aid.length] = (byte) applet_counter;
log("INFO: generated applet AID: " + hexAID(a.aid) + " for " + a.klass, Project.MSG_INFO);
}
} else {
// if package AID is empty, just set it to the minimal from
// applet
if (a.aid != null) {
package_aid = Arrays.copyOf(a.aid, 5);
} else {
throw new HelpingBuildException("Both package AID and applet AID are missing!");
}
}
}
// Check package AID
if (package_aid == null) {
throw new HelpingBuildException("Must specify package AID");
}
// Check output file
if (output_cap == null) {
throw new HelpingBuildException("Must specify output file");
}
// Nice info
log("Building CAP with " + applet_counter + " applet" + (applet_counter > 1 ? "s" : "") + " from package " + package_name, Project.MSG_INFO);
for (JCApplet app : raw_applets) {
log(app.klass + " " + encodeHexString(app.aid), Project.MSG_INFO);
}
}
private void compile() {
Javac j = new Javac();
j.setProject(getProject());
j.setTaskName("compile");
j.setSrcdir(new Path(getProject(), sources_path));
File tmp;
if (classes_path != null) {
tmp = getProject().resolveFile(classes_path);
if (!tmp.exists()) {
tmp.mkdir();
}
} else {
// Generate temporary folder
java.nio.file.Path p = mktemp();
temporary.add(p);
tmp = p.toFile();
classes_path = tmp.getAbsolutePath();
}
j.setDestdir(tmp);
// See "Setting Java Compiler Options" in User Guide
j.setDebug(true);
if (jckit.version == JC.V212) {
j.setTarget("1.1");
j.setSource("1.1");
// Always set debug to disable "contains local variables,
// but not local variable table." messages
j.setDebug(true);
} else if (jckit.version == JC.V221) {
j.setTarget("1.2");
j.setSource("1.2");
} else {
j.setTarget("1.5");
j.setSource("1.5");
}
j.setIncludeantruntime(false);
j.createCompilerArg().setValue("-Xlint");
j.createCompilerArg().setValue("-Xlint:-options");
j.createCompilerArg().setValue("-Xlint:-serial");
j.setFailonerror(true);
j.setFork(true);
// set classpath
Path cp = j.createClasspath();
String api = null;
if (jckit.version == JC.V3) {
api = Paths.get(jckit.path, "lib", "api_classic.jar").toAbsolutePath().toString();
} else if (jckit.version == JC.V212) { // V2.1.X
api = Paths.get(jckit.path, "lib", "api21.jar").toAbsolutePath().toString();
} else { // V2.2.X
api = Paths.get(jckit.path, "lib", "api.jar").toAbsolutePath().toString();
}
cp.append(new Path(getProject(), api));
for (JCImport i : raw_imports) {
cp.append(new Path(getProject(), i.jar));
}
j.execute();
}
@Override
public void execute() {
// Convert
check();
try {
// Compile first if necessary
if (sources_path != null) {
compile();
}
// construct the Java task that executes converter
Java j = new Java(this);
// classpath to jckit bits
Path cp = j.createClasspath();
// converter
File jar = null;
if (jckit.version == JC.V3) {
jar = Paths.get(jckit.path, "lib", "tools.jar").toFile();
Path jarpath = new Path(getProject());
jarpath.setLocation(jar);
cp.append(jarpath);
} else {
// XXX: this should be with less lines ?
jar = Paths.get(jckit.path, "lib", "converter.jar").toFile();
Path jarpath = new Path(getProject());
jarpath.setLocation(jar);
cp.append(jarpath);
jar = Paths.get(jckit.path, "lib", "offcardverifier.jar").toFile();
jarpath = new Path(getProject());
jarpath.setLocation(jar);
cp.append(jarpath);
}
// Create temporary folder and add to cleanup
java.nio.file.Path p = mktemp();
temporary.add(p);
File applet_folder = p.toFile();
j.createArg().setLine("-classdir '" + classes_path + "'");
j.createArg().setLine("-d '" + applet_folder.getAbsolutePath() + "'");
ArrayList<String> exps = new ArrayList<>();
// Construct exportpath
if (jckit.version == JC.V212) {
exps.add(Paths.get(jckit.path, "api21_export_files").toString());
} else {
exps.add(Paths.get(jckit.path, "api_export_files").toString());
}
// add imports
for (JCImport imp : raw_imports) {
exps.add(Paths.get(imp.exps).toAbsolutePath().toString());
}
// XXX StringJoiner is 1.8+, we are 1.7+
StringBuilder expstringbuilder = new StringBuilder();
for (String imp : exps) {
expstringbuilder.append(File.pathSeparatorChar);
expstringbuilder.append(imp);
}
j.createArg().setLine("-exportpath '" + expstringbuilder.toString() + "'");
j.createArg().setLine("-verbose");
j.createArg().setLine("-nobanner");
if (debug) {
j.createArg().setLine("-debug");
}
if (!verify) {
j.createArg().setLine("-noverify");
}
if (jckit.version == JC.V3) {
j.createArg().setLine("-useproxyclass");
}
String outputs = "CAP";
if (output_exp != null) {
outputs += " EXP";
}
if (output_jca != null) {
outputs += " JCA";
}
j.createArg().setLine("-out " + outputs);
for (JCApplet app : raw_applets) {
j.createArg().setLine("-applet " + hexAID(app.aid) + " " + app.klass);
}
j.createArg().setLine(package_name + " " + hexAID(package_aid) + " " + package_version);
// Call converter
if (jckit.version == JC.V3) {
j.setClassname("com.sun.javacard.converter.Main");
Variable jchome = new Variable();
jchome.setKey("jc.home");
jchome.setValue(jckit.path);
j.addSysproperty(jchome);
} else {
j.setClassname("com.sun.javacard.converter.Converter");
}
j.setFailonerror(true);
j.setFork(true);
log("cmdline: " + j.getCommandLine(), Project.MSG_VERBOSE);
j.execute();
// Copy results
if (output_cap != null || output_exp != null || output_jca != null) {
// Last component of the package
String ln = package_name;
if (ln.lastIndexOf(".") != -1) {
ln = ln.substring(ln.lastIndexOf(".") + 1);
}
// JavaCard folder
java.nio.file.Path jcsrc = applet_folder.toPath().resolve(package_name.replace(".", File.separator)).resolve("javacard");
// Interesting paths inside the JC folder
java.nio.file.Path cap = jcsrc.resolve(ln + ".cap");
java.nio.file.Path exp = jcsrc.resolve(ln + ".exp");
java.nio.file.Path jca = jcsrc.resolve(ln + ".jca");
try {
if (!cap.toFile().exists()) {
throw new BuildException("Can not find CAP in " + jcsrc);
}
// Resolve output file
File opf = getProject().resolveFile(output_cap);
// Copy CAP
Files.copy(cap, opf.toPath(), StandardCopyOption.REPLACE_EXISTING);
log("CAP saved to " + opf.getAbsolutePath(), Project.MSG_INFO);
// Copy exp file
if (output_exp != null) {
setTaskName("export");
if (!exp.toFile().exists()) {
throw new BuildException("Can not find EXP in " + jcsrc);
}
// output_exp is the folder name
opf = getProject().resolveFile(output_exp);
// Get the folder under the output folder
java.nio.file.Path exp_path = opf.toPath().resolve(package_name.replace(".", File.separator)).resolve("javacard");
// Create the output folder
if (!exp_path.toFile().exists()) {
if (!exp_path.toFile().mkdirs()) {
throw new HelpingBuildException("Can not make path for EXP output: " + opf.getAbsolutePath());
}
}
// Copy output
Files.copy(exp, exp_path.resolve(exp.getFileName()), StandardCopyOption.REPLACE_EXISTING);
log("EXP saved to " + exp_path.resolve(exp.getFileName()), Project.MSG_INFO);
// Make Jar for the export
Jar jarz = new Jar();
jarz.setProject(getProject());
jarz.setTaskName("export");
jarz.setBasedir(getProject().resolveFile(classes_path));
jarz.setDestFile(opf.toPath().resolve(ln + ".jar").toFile());
jarz.execute();
}
// Copy JCA
if (output_jca != null) {
setTaskName("jca");
if (!jca.toFile().exists()) {
throw new BuildException("Can not find JCA in " + jcsrc);
}
opf = getProject().resolveFile(output_jca);
Files.copy(jca, opf.toPath(), StandardCopyOption.REPLACE_EXISTING);
log("JCA saved to " + opf.getAbsolutePath(), Project.MSG_INFO);
}
} catch (IOException e) {
e.printStackTrace();
throw new BuildException("Can not copy output CAP, EXP or JCA", e);
}
}
if (verify) {
setTaskName("verify");
// construct the Java task that executes converter
j = new Java(this);
j.setClasspath(cp);
j.setClassname("com.sun.javacard.offcardverifier.Verifier");
// Find all expfiles
final ArrayList<String> expfiles = new ArrayList<>();
try {
for (String e: exps) {
Files.walkFileTree(Paths.get(e), new SimpleFileVisitor<java.nio.file.Path>() {
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs)
throws IOException
{
if (file.toString().endsWith(".exp")) {
expfiles.add(file.toAbsolutePath().toString());
}
return FileVisitResult.CONTINUE;
}
});
}
} catch (IOException e) {
log("Could not find .exp files: " + e.getMessage(), Project.MSG_ERR);
return;
}
// Arguments to verifier
j.createArg().setLine("-nobanner");
//TODO j.createArg().setLine("-verbose");
for (String exp: expfiles) {
j.createArg().setLine(exp);
}
j.createArg().setLine(getProject().resolveFile(output_cap).toString());
j.setFailonerror(true);
j.setFork(true);
log("cmdline: " + j.getCommandLine(), Project.MSG_VERBOSE);
j.execute();
}
} finally {
// Clean temporary files.
for (java.nio.file.Path p: temporary) {
if (p.toFile().exists()) {
rmminusrf(p);
}
}
}
}
}
public class JCImport {
String exps = null;
String jar = null;
public void setExps(String msg) {
exps = msg;
}
public void setJar(String msg) {
jar = msg;
}
}
private static java.nio.file.Path mktemp() {
try {
java.nio.file.Path p = Files.createTempDirectory("jccpro");
return p;
} catch (IOException e) {
throw new RuntimeException("Can not make temporary folder", e);
}
}
private static void rmminusrf(java.nio.file.Path path) {
try {
Files.walkFileTree(path, new SimpleFileVisitor<java.nio.file.Path>() {
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException e)
throws IOException
{
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
// directory iteration failed
throw e;
}
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static final char[] LOWER_HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static String encodeHexString(final byte[] data) {
final int l = data.length;
final char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = LOWER_HEX[(0xF0 & data[i]) >>> 4];
out[j++] = LOWER_HEX[0x0F & data[i]];
}
return new String(out);
}
public static byte[] decodeHexString(String str) {
char data[] = str.toCharArray();
final int len = data.length;
if ((len & 0x01) != 0) {
throw new IllegalArgumentException("Odd number of characters: " + str);
}
final byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = Character.digit(data[j], 16) << 4;
j++;
f = f | Character.digit(data[j], 16);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
// End of copied code from commons-codec
public static byte[] stringToBin(String s) {
s = s.toLowerCase().replaceAll(" ", "").replaceAll(":", "");
s = s.replaceAll("0x", "").replaceAll("\n", "").replaceAll("\t", "");
s = s.replaceAll(";", "");
return decodeHexString(s);
}
}
|
package scuba.test.testcase.intra;
import framework.scuba.helper.AliasHelper;
public class Test {
public static void test() {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
}
// test new and assignment
public static void test1() {
A t1 = new A();
A t2 = new A();
AliasHelper.notAlias(t1, t2);
A t3 = t2;
AliasHelper.alias(t2, t3);
AliasHelper.notAlias(t1, t3);
}
// test load and store
public static void test2() {
B t1 = new B();
t1.f = new C();
B t2 = new B();
t2.f = new C();
AliasHelper.notAlias(t1.f, t2.f);
C t3 = t1.f;
C t4 = t1.f;
C t5 = t2.f;
AliasHelper.alias(t3, t4);
AliasHelper.notAlias(t4, t5);
AliasHelper.notAlias(t3, t5);
}
// test new array and assignment
public static void test3() {
A[] t1 = new A[10];
A[] t2 = new A[10];
AliasHelper.notAlias(t1, t2);
A[] t3 = t2;
AliasHelper.notAlias(t1, t3);
AliasHelper.alias(t2, t3);
}
// test multi new and assignment
public static void test4() {
A[][] t1 = new A[10][10];
A[][] t2 = new A[10][10];
AliasHelper.notAlias(t1, t2);
// we cannot test because of empty point-to sets of Chord
A[] t3 = t1[0];
A[] t4 = t2[0];
// AliasHelper.notAlias(t3, t4);
// AliasHelper.notAlias(t1, t3);
// AliasHelper.notAlias(t1, t4);
// AliasHelper.notAlias(t2, t3);
// AliasHelper.notAlias(t2, t4);
A[][] t5 = t2;
AliasHelper.alias(t2, t5);
AliasHelper.notAlias(t1, t5);
t3[0] = new A();
t4[0] = new A();
// AliasHelper.notAlias(t3[0], t4[0]);
}
// test array load and store
public static void test5() {
A[] t1 = new A[10];
A t2 = new A();
A t3 = new A();
t1[0] = t2;
t1[1] = t3;
AliasHelper.notAlias(t2, t3);
AliasHelper.alias(t1[0], t1[1]);
A t4 = t1[0];
A t5 = t1[1];
AliasHelper.alias(t4, t5);
}
// test condition
public static void test6() {
A t1 = new A();
A t2 = new A();
A t3 = null;
A t4 = null;
int i = 0;
if (i < 10) {
t3 = t1;
t4 = t2;
} else {
t3 = t2;
t4 = t1;
}
AliasHelper.alias(t3, t4);
AliasHelper.notAlias(t1, t2);
AliasHelper.alias(t1, t3);
AliasHelper.alias(t1, t4);
AliasHelper.alias(t2, t3);
AliasHelper.alias(t2, t4);
}
// test loop
public static void test7() {
A t1 = new A();
A t2 = null;
A t3 = null;
for (int i = 0; i < 10; i++) {
}
}
public static void test8() {
}
public static void test9() {
}
public static void test10() {
}
}
|
import odml.core.Reader;
import org.g_node.nix.Block;
import org.g_node.nix.Property;
import org.g_node.nix.Section;
import org.g_node.nix.Value;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Vector;
public class MetadataParser {
String metadataFile;
public MetadataParser(String metadatFile) {
this.metadataFile = metadatFile;
}
public MetadataParser() {
this.metadataFile = "metadata.xml";
}
private odml.core.Section initializeODMLReader(){
Reader reader = new Reader();
odml.core.Section rootSection=new odml.core.Section();
InputStream inputstream;
try {
inputstream = new FileInputStream(metadataFile);
rootSection = reader.load(inputstream, true);
} catch (Exception e) {
e.printStackTrace();
}
return rootSection;
}
/**
*
* This method takes in a nix file, a nix Block and a odml metadata file, parses the odml
* metadata file and creates a metadata for the Block in the Nix file.
*
* @param metadataFile : File name of the metadata.xml odml file
* @param block : Block whose metadata will be set
* @param file : HDF5 (Specifically nix) file in which this metadata will be written
*/
public void setMetadata(String metadataFile, Block block, org.g_node.nix.File file) {
java.io.File inputFile = new java.io.File(metadataFile);
try {
odml.core.Section rootSection = initializeODMLReader();
String version = rootSection.getDocumentVersion();
String date = rootSection.getDocumentDate().toString();
System.out.println("version : " + version);
System.out.println("date : " + date);
// create section and add a property
Section rootSectionMetadata = file.createSection("metadataSection", "metadata");
block.setMetadata(rootSectionMetadata);
//for parsing
Vector<odml.core.Section> sectionVector = rootSection.getSections();
if(sectionVector.size()>0){
setSection(rootSectionMetadata, sectionVector);
}
} catch (Exception e) {
System.out.println("Exception!!!!");
}
}
public void setSection(Section parentSection, Vector<odml.core.Section> sectionVector){
for (int temp = 0; temp < sectionVector.size(); temp++)
{
odml.core.Section thisSection = sectionVector.get(temp);
System.out.println("temp : " + temp + " | Current section : " + thisSection.getName());
String typeOfSection = "";
String nameOfSection = "";
Vector<odml.core.Property> propertiesList = new Vector<>();
if(thisSection.getType()!=null){
typeOfSection = thisSection.getType();
}
if(thisSection.getName()!=null){
nameOfSection = thisSection.getName();
}
// hdf5 creating subsection of metadata section (root)
Section secChild = parentSection.createSection(nameOfSection, typeOfSection);
//System.out.println("This section's sections: "+ thisSection.getSections().size());
//this is the recursive function since a section may have a section inside it, and so on.
if(thisSection.getSections()!=null && thisSection.getSections().size()>0){
setSection(secChild, thisSection.getSections());
}
if(thisSection.getProperties()!=null){
propertiesList = thisSection.getProperties();
}
setProperties(secChild, propertiesList);
}
}
public void setProperties(Section parentSec, Vector<odml.core.Property> propertiesList){
//for each child of section (for property)
if(propertiesList!=null && !propertiesList.isEmpty()){
String nameOfProperty = "";
Value valueOfProperty = new Value("");
for(int tempProperty = 0; tempProperty < propertiesList.size(); tempProperty++) {
odml.core.Property thisProperty = propertiesList.get(tempProperty);
System.out.println(" tempProperty : " + tempProperty + " | Current property : " + thisProperty.getName());
if(thisProperty.getName()!=null){
nameOfProperty = thisProperty.getName();
}
if(thisProperty.valueCount()>0){
odml.core.Value wholeValue = thisProperty.getWholeValue();
String value = thisProperty.getValue().toString();
String valueType= wholeValue.getMap().get("type").toString();
switch (valueType) {
case "datetime":
valueOfProperty.setString(value);
break;
case "int":
valueOfProperty.setInt(Integer.parseInt(value));
break;
case "float":
valueOfProperty.setDouble(Double.parseDouble(value));
break;
case "boolean":
valueOfProperty.setBoolean(Boolean.parseBoolean(value));
break;
case "string":
valueOfProperty.setString(value);
break;
case "long":
valueOfProperty.setLong(Long.parseLong(value));
break;
default:
System.out.println("ERROR. Some wrong valueType. valueType : " + valueType);
}
}
processGUINamespaces(parentSec, thisProperty);
}
Property prop = parentSec.createProperty(nameOfProperty, valueOfProperty);
}
}
// public void setGUINamespace(String nameOfGUINamespace, Boolean valueOfGUINamespace, Section guiSection){
// Value gui_required_value = new Value(valueOfGUINamespace);
// guiSection.createProperty(nameOfGUINamespace, gui_required_value);
public void processGUINamespaces(Section parentSec, odml.core.Property property){
Section guiSection = parentSec.createSection(property.getName(), "GUI:Namespace");
Boolean gui_required;
Boolean gui_editable;
int gui_order;
if(property.getGuiHelper().getRequired()!=null) {
gui_required = property.getGuiHelper().getRequired();
Value gui_required_value = new Value(gui_required);
guiSection.createProperty("gui_required", gui_required_value);
}
if(property.getGuiHelper().getEditable()!=null) {
gui_editable= property.getGuiHelper().getEditable();
Value gui_editable_value = new Value(gui_editable);
guiSection.createProperty("gui_empty", gui_editable_value);
}
if(property.getGuiHelper().getRequired()!=null) {
gui_order = property.getGuiHelper().getOrder();
Value gui_order_value = new Value(gui_order);
guiSection.createProperty("gui_empty", gui_order_value);
}
// List list = property.getGuiHelper().getGUINamespaceTags();
// for(int i=0; i<list.size(); i++){
// System.out.println("->"+list.get(i));
}
}
|
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.util.Observer;
/**
* TODO COMMENT
*
* @author connoryork (cxy1054@rit.edu)
*/
public class MusicPlayerGUI extends Application implements Observer {
private static final int DEFAULT_PADDING = 5;
private static final int DEFAULT_SPACING = 10;
private static final int DEFAULT_SLIDER_HEIGHT = 80;
private static final int DEFAULT_WINDOW_HEIGHT = 0;
private static final int DEFAULT_WINDOW_WIDTH = 0;
private static int MIN_VOLUME;
private static int MAX_VOLUME;
private MusicPlayerModel model;
/**
* Launches the GUI.
*
* @param args not used
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void init() {
Parameters params = getParameters();
this.model = new MusicPlayerModel("resources/" + params.getRaw().get(0));
MIN_VOLUME = (int) this.model.getMinVolume();
MAX_VOLUME = (int) this.model.getMaxVolume();
}
/**
* JavaFX start method. Builds and displays the GUI.
*
* @param primaryStage stage to build GUI on
* @throws Exception
*/
@Override
public void start(Stage primaryStage) throws Exception {
Scene s = new Scene(buildRoot());
primaryStage.initStyle(StageStyle.UTILITY);
primaryStage.setScene(s);
primaryStage.setResizable(false);
primaryStage.setAlwaysOnTop(true);
primaryStage.show();
Rectangle2D screen = Screen.getPrimary().getVisualBounds();
primaryStage.setX(screen.getWidth()/2);
System.out.println(screen.getHeight());
System.out.println(primaryStage.getHeight());
primaryStage.setY(screen.getHeight() - primaryStage.getHeight());
}
/**
* Builds the root node for the GUI.
*
* @return BorderPane Node
*/
private BorderPane buildRoot() {
BorderPane bp = new BorderPane();
bp.setPrefSize(350, 80);
bp.setCenter(buildCenter());
bp.setRight(buildVolumeSlider());
bp.setTop(buildMenuBar());
return bp;
}
/**
* Builds HBox and corresponding buttons.
*
* @return center buttons in a HBox
*/
private HBox buildCenter() {
HBox box = new HBox();
box.setSpacing(DEFAULT_SPACING);
box.setPadding(new Insets(DEFAULT_PADDING));
box.setAlignment(Pos.TOP_CENTER);
box.getChildren().add(buildRewind());
box.getChildren().add(buildPlayPause());
box.getChildren().add(buildNext());
return box;
}
/**
* Builds rewind button, which restarts the current song.
*
* @return rewind Button
*/
private Button buildRewind() {
Button rewind = new Button();
setImage(rewind, "rewind.png");
rewind.setOnAction(e -> this.model.rewindToStart());
return rewind;
}
/**
* Builds play button, which pauses and plays the song.
*
* @return play Button
*/
private Button buildPlayPause() {
Button play = new Button();
setImage(play, "play.png");
play.setOnAction(e -> {
if (!this.model.isRunning()) {
setImage(play, "pause.png");
this.model.start();
} else {
setImage(play, "play.png");
this.model.stop();
}
});
return play;
}
/**
* Builds next button, which skips the current song.
*
* @return next Button
*/
private Button buildNext() {
Button next = new Button();
setImage(next, "fastforward.png");
next.setOnAction(e -> {
// TODO play next song
});
return next;
}
/**
* Sets the image of the Button.
*
* @param b Button object
* @param filename filename of image
*/
private void setImage(ButtonBase b, String filename) {
Image image = new Image(getClass().getResourceAsStream("resources/" + filename));
b.setGraphic(new ImageView(image));
}
/**
* Builds a slider that controls the volume of the GUI.
*
* @return Slider which controls volume
*/
private Slider buildVolumeSlider() {
int half = (MAX_VOLUME + MIN_VOLUME)/2;
Slider slider = new Slider(half, MAX_VOLUME, (MAX_VOLUME + half)/2);
slider.setOrientation(Orientation.VERTICAL);
slider.setPadding(new Insets(DEFAULT_PADDING));
slider.setMaxHeight(DEFAULT_SLIDER_HEIGHT);
slider.valueProperty().addListener((observable, oldValue, newValue) -> {
this.model.volumeChange(newValue.doubleValue());
});
return slider;
}
private MenuBar buildMenuBar() {
MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu("File");
menuBar.getMenus().addAll(menuFile);
MenuItem choose = new MenuItem("Choose Song");
return menuBar;
}
/**
*
* @param o
* @param arg
*/
@Override
public void update(java.util.Observable o, Object arg) {
}
}
|
package config;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import lombok.Getter;
public class Options {
public Options build(final String[] args) {
new JCommander(this, args);
this.scenarioList = parseScenarioStringToList(this.getRunScenario());
return this;
}
@Getter
@Parameter(names = { "--source", "-s" })
private String source = "./ruberdriver.json";
@Getter
@Parameter(names = { "--async", "-a" })
private boolean async = false;
@Getter
@Parameter(names = { "--scenario", "-c" })
private String runScenario = "";
@Parameter(names = { "--debug", "-d" })
@Getter
private boolean debugMode = false;
@Parameter(names = { "--print", "-p" })
@Getter
private boolean printScriptSentences = false;
@Parameter(names = { "--all", "-l" })
@Getter
private boolean allScenario = false;
@Getter
private List<String> scenarioList;
public void disable_debugMode() {
this.debugMode = false;
}
public void disable_printScriptSentences() {
this.printScriptSentences = false;
}
private List<String> parseScenarioStringToList(String runScenario) {
String[] scenarios = runScenario.trim().split("\\s*,\\s*");
return Arrays.asList(scenarios);
}
@Test
public void testParse() {
List<String> actual = parseScenarioStringToList(" test, test2:3, test 4 , test 12 ,");
String[] expect = { "test", "test2:3", "test 4", "test 12" };
List<String> expect_list = Arrays.asList(expect);
Assert.assertTrue(actual.equals(expect_list));
}
}
|
package org.a0z.mpd;
import org.a0z.mpd.connection.MPDConnection;
import org.a0z.mpd.connection.MPDConnectionMonoSocket;
import org.a0z.mpd.connection.MPDConnectionMultiSocket;
import org.a0z.mpd.exception.MPDException;
import org.a0z.mpd.item.Album;
import org.a0z.mpd.item.Artist;
import org.a0z.mpd.item.Directory;
import org.a0z.mpd.item.FilesystemTreeEntry;
import org.a0z.mpd.item.Genre;
import org.a0z.mpd.item.Item;
import org.a0z.mpd.item.Music;
import org.a0z.mpd.item.PlaylistFile;
import org.a0z.mpd.item.Stream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static org.a0z.mpd.Tools.KEY;
import static org.a0z.mpd.Tools.VALUE;
/**
* MPD Server controller.
*/
public class MPD {
public static final String STREAMS_PLAYLIST = "[Radio Streams]";
private static final String TAG = "MPD";
protected final MPDPlaylist mPlaylist;
private final MPDConnection mConnection;
private final MPDConnection mIdleConnection;
private final MPDStatistics mStatistics;
private final MPDStatus mStatus;
/**
* Constructs a new MPD server controller without connection.
*/
public MPD() {
super();
mConnection = new MPDConnectionMultiSocket(5000, 2);
mIdleConnection = new MPDConnectionMonoSocket(0);
mStatistics = new MPDStatistics();
mPlaylist = new MPDPlaylist(mConnection);
mStatus = new MPDStatus();
}
/**
* Constructs a new MPD server controller.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public MPD(final InetAddress server, final int port, final String password)
throws MPDException, IOException {
this();
connect(server, port, password);
}
/**
* Constructs a new MPD server controller.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public MPD(final String server, final int port, final String password)
throws IOException, MPDException {
this();
connect(server, port, password);
}
private static MPDCommand getAlbumDetailsCommand(final Album album) {
final Artist artist = album.getArtist();
String artistCommand = null;
String artistName = null;
if (artist != null) {
artistName = artist.getName();
if (album.hasAlbumArtist()) {
artistCommand = MPDCommand.MPD_TAG_ALBUM_ARTIST;
} else {
artistCommand = MPDCommand.MPD_FIND_ARTIST;
}
}
return new MPDCommand(MPDCommand.MPD_CMD_COUNT,
MPDCommand.MPD_TAG_ALBUM, album.getName(),
artistCommand, artistName);
}
private static MPDCommand getSongsCommand(final Album album) {
final String albumName = album.getName();
final Artist artist = album.getArtist();
String artistName = null;
String artistCommand = null;
if (artist != null) {
artistName = artist.getName();
if (album.hasAlbumArtist()) {
artistCommand = MPDCommand.MPD_TAG_ALBUM_ARTIST;
} else {
artistCommand = MPDCommand.MPD_TAG_ARTIST;
}
}
return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumName,
artistCommand, artistName);
}
/*
* get raw command String for listAlbums
*/
private static MPDCommand listAlbumsCommand(final String artist, final boolean useAlbumArtist) {
String albumArtist = null;
if (useAlbumArtist) {
albumArtist = MPDCommand.MPD_TAG_ALBUM_ARTIST;
}
return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM,
albumArtist, artist);
}
/*
* get raw command String for listAllAlbumsGrouped
*/
private static MPDCommand listAllAlbumsGroupedCommand(final boolean useAlbumArtist) {
final String artistTag;
if (useAlbumArtist) {
artistTag = MPDCommand.MPD_TAG_ALBUM_ARTIST;
} else {
artistTag = MPDCommand.MPD_TAG_ARTIST;
}
return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM,
MPDCommand.MPD_CMD_GROUP, artistTag);
}
private static MPDCommand nextCommand() {
return new MPDCommand(MPDCommand.MPD_CMD_NEXT);
}
/**
* Parse the response from tag list command for album artists.
*
* @param response The album artist list response from the MPD server database.
* @param substring The substring from the response to remove.
* @param sortInsensitive Whether to sort insensitively.
* @return Returns a parsed album artist list.
*/
private static List<String> parseResponse(final Collection<String> response,
final String substring, final boolean sortInsensitive) {
final List<String> result = new ArrayList<>(response.size());
for (final String line : response) {
result.add(line.substring((substring + ": ").length()));
}
if (sortInsensitive) {
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
} else {
Collections.sort(result);
}
return result;
}
private static MPDCommand skipToPositionCommand(final int position) {
return new MPDCommand(MPDCommand.MPD_CMD_PLAY, Integer.toString(position));
}
/**
* Adds a {@code Album} item object to the playlist queue.
*
* @param album {@code Album} item object to be added to the media server playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Album album) throws IOException, MPDException {
add(album, false, false);
}
/**
* Adds a {@code Album} item object to the playlist queue.
*
* @param album {@code Album} item object to be added to the media server playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the item(s).
* @param play Whether to play the playlist queue after adding the item(s).
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Album album, final boolean replace, final boolean play)
throws IOException, MPDException {
final List<Music> songs = getSongs(album);
final CommandQueue commandQueue = MPDPlaylist.addAllCommand(songs);
add(commandQueue, replace, play);
}
/**
* Adds a {@code Artist} item object to the playlist queue.
*
* @param artist {@code Artist} item object to be added to the media server playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Artist artist) throws IOException, MPDException {
add(artist, false, false);
}
/**
* Adds a {@code Artist} item object to the playlist queue.
*
* @param artist {@code Artist} item object to be added to the media server playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the item(s).
* @param play Whether to play the playlist queue after adding the item(s).
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final Artist artist, final boolean replace, final boolean play)
throws IOException, MPDException {
final List<Music> songs = getSongs(artist);
final CommandQueue commandQueue = MPDPlaylist.addAllCommand(songs);
add(commandQueue, replace, play);
}
/**
* Add a {@code Music} or {@code Directory} item object to the playlist queue.
* {@code PlaylistFile} items are added in it's own method.
*
* @param music {@code Music} item object to be added to the media server playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the item(s).
* @param play Whether to play the playlist queue after adding the item(s).
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final FilesystemTreeEntry music, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.addCommand(music.getFullPath()));
add(commandQueue, replace, play);
}
/**
* Add a {@code Music} item object to the playlist queue.
*
* @param music {@code Music} item object to be added to the playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final FilesystemTreeEntry music) throws IOException, MPDException {
add(music, false, false);
}
/**
* Adds songs to the queue. Optionally, clears the queue prior to the addition. Optionally,
* play the added songs afterward.
*
* @param commandQueue The commandQueue that will be responsible of inserting the
* songs into the queue.
* @param replace If true, replaces the entire playlist queue with the added files.
* @param playAfterAdd If true, starts playing once added.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final CommandQueue commandQueue, final boolean replace,
final boolean playAfterAdd) throws IOException, MPDException {
int playPos = 0;
final boolean isPlaying = mStatus.isState(MPDStatus.STATE_PLAYING);
final boolean isConsume = mStatus.isConsume();
final boolean isRandom = mStatus.isRandom();
final int playlistLength = mStatus.getPlaylistLength();
/** Replace */
if (replace) {
if (isPlaying) {
if (playlistLength > 1) {
try {
commandQueue.add(0, MPDPlaylist.cropCommand(this));
} catch (final IllegalStateException ignored) {
/** Shouldn't occur, we already checked for playing. */
}
}
} else {
commandQueue.add(0, MPDPlaylist.clearCommand());
}
} else if (playAfterAdd && !isRandom) {
/** Since we didn't clear the playlist queue, we need to play the (current queue+1) */
playPos = mPlaylist.size();
}
if (replace) {
if (isPlaying) {
commandQueue.add(nextCommand());
} else if (playAfterAdd) {
commandQueue.add(skipToPositionCommand(playPos));
}
} else if (playAfterAdd) {
commandQueue.add(skipToPositionCommand(playPos));
}
/** Finally, clean up the last playing song. */
if (replace && isPlaying && !isConsume) {
commandQueue.add(MPDPlaylist.removeByIndexCommand(0));
}
commandQueue.send(mConnection);
}
/**
* Add a {@code Playlist} item object to the playlist queue.
*
* @param databasePlaylist A playlist item stored on the media server to add to the
* playlist queue.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final PlaylistFile databasePlaylist) throws IOException, MPDException {
add(databasePlaylist, false, false);
}
/**
* Add a {@code Playlist} item object to the playlist queue.
*
* @param databasePlaylist A playlist item stored on the media server to add to the
* playlist queue.
* @param replace Whether to clear the playlist queue prior to adding the
* databasePlaylist string.
* @param play Whether to play the playlist queue prior after adding the
* databasePlaylist string.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void add(final PlaylistFile databasePlaylist, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.loadCommand(databasePlaylist.getName()));
add(commandQueue, replace, play);
}
protected void addAlbumPaths(final List<Album> albums) {
if (albums != null && !albums.isEmpty()) {
for (final Album album : albums) {
try {
final List<Music> songs = getFirstTrack(album);
if (!songs.isEmpty()) {
album.setPath(songs.get(0).getPath());
}
} catch (final IOException | MPDException e) {
Log.error(TAG, "Failed to add an album path.", e);
}
}
}
}
/** TODO: This needs to be an add(Stream, ...) method. */
public void addStream(final String stream, final boolean replace, final boolean play)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
commandQueue.add(MPDPlaylist.addCommand(stream));
add(commandQueue, replace, play);
}
public void addToPlaylist(final String playlistName, final Album album)
throws IOException, MPDException {
addToPlaylist(playlistName, new ArrayList<>(getSongs(album)));
}
public void addToPlaylist(final String playlistName, final Artist artist)
throws IOException, MPDException {
addToPlaylist(playlistName, new ArrayList<>(getSongs(artist)));
}
public void addToPlaylist(final String playlistName, final Collection<Music> musicCollection)
throws IOException, MPDException {
if (null != musicCollection && !musicCollection.isEmpty()) {
final CommandQueue commandQueue = new CommandQueue();
for (final Music music : musicCollection) {
commandQueue
.add(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, music.getFullPath());
}
commandQueue.send(mConnection);
}
}
public void addToPlaylist(final String playlistName, final FilesystemTreeEntry entry)
throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName,
entry.getFullPath());
}
public void addToPlaylist(final String playlistName, final Music music)
throws IOException, MPDException {
final Collection<Music> songs = new ArrayList<>(1);
songs.add(music);
addToPlaylist(playlistName, songs);
}
/**
* Increases or decreases volume by {@code modifier} amount.
*
* @param modifier volume adjustment
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void adjustVolume(final int modifier) throws IOException, MPDException {
// calculate final volume (clip value with [0, 100])
int vol = mStatus.getVolume() + modifier;
vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, vol));
mConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Clears error message.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void clearError() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_CLEARERROR);
}
/**
* Connects to a MPD server.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public final synchronized void connect(final InetAddress server, final int port,
final String password) throws IOException, MPDException {
if (!isConnected()) {
mConnection.connect(server, port, password);
mIdleConnection.connect(server, port, password);
}
}
/**
* Connects to a MPD server.
*
* @param server server address or host name
* @param port server port
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public final void connect(final String server, final int port, final String password)
throws IOException, MPDException {
final InetAddress address = InetAddress.getByName(server);
connect(address, port, password);
}
/**
* Connects to a MPD server.
*
* @param server server address or host name and port (server:port)
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public final void connect(final String server, final String password) throws IOException,
MPDException {
int port = MPDCommand.DEFAULT_MPD_PORT;
final String host;
if (server.indexOf(':') == -1) {
host = server;
} else {
host = server.substring(0, server.lastIndexOf(':'));
port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1));
}
connect(host, port, password);
}
public void disableOutput(final int id) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id));
}
/**
* Disconnects from server.
*
* @throws IOException if an error occur while closing connection
*/
public synchronized void disconnect() throws IOException {
IOException ex = null;
if (mConnection != null && mConnection.isConnected()) {
try {
mConnection.disconnect();
} catch (final IOException e) {
ex = (ex != null) ? ex : e;// Always keep first non null
// exception
}
}
if (mIdleConnection != null && mIdleConnection.isConnected()) {
try {
mIdleConnection.disconnect();
} catch (final IOException e) {
ex = (ex != null) ? ex : e;// Always keep non null first
// exception
}
}
}
public void editSavedStream(final String url, final String name, final Integer pos)
throws IOException, MPDException {
removeSavedStream(pos);
saveStream(url, name);
}
public void enableOutput(final int id) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id));
}
/**
* Similar to {@code search},{@code find} looks for exact matches
* in the MPD database.
*
* @param type type of search. Should be one of the following constants:
* MPD_FIND_ARTIST, MPD_FIND_ALBUM
* @param locatorString case-insensitive locator locatorString. Anything that exactly
* matches {@code locatorString} will be returned in the results.
* @return a Collection of {@code Music}
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see org.a0z.mpd.item.Music
*/
public Collection<Music> find(final String type, final String locatorString)
throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_FIND, type, locatorString);
}
public List<Music> find(final String[] args) throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_FIND, args, true);
}
/*
* For all given albums, look for album artists and create as many albums as
* there are album artists, including "" The server call can be slow for long
* album lists
*/
protected void fixAlbumArtists(final List<Album> albums) {
if (albums != null && !albums.isEmpty()) {
List<String[]> albumArtists = null;
try {
albumArtists = listAlbumArtists(albums);
} catch (final IOException | MPDException e) {
Log.error(TAG, "Failed to fix album artists.", e);
}
if (albumArtists != null && albumArtists.size() == albums.size()) {
/** Split albums are rare, let it allocate as needed. */
@SuppressWarnings("CollectionWithoutInitialCapacity")
final Collection<Album> splitAlbums = new ArrayList<>();
int i = 0;
for (Album album : albums) {
final String[] aartists = albumArtists.get(i);
if (aartists.length > 0) {
Arrays.sort(aartists); // make sure "" is the first one
if (aartists[0] != null && !aartists[0]
.isEmpty()) { // one albumartist, fix this
// album
final Artist artist = new Artist(aartists[0]);
albums.set(i, album.setAlbumArtist(artist));
} // do nothing if albumartist is ""
if (aartists.length > 1) { // it's more than one album, insert
for (int n = 1; n < aartists.length; n++) {
final Album newalbum =
new Album(album.getName(), new Artist(aartists[n]), true);
splitAlbums.add(newalbum);
}
}
}
i++;
}
albums.addAll(splitAlbums);
}
}
}
protected List<Music> genericSearch(final String searchCommand, final String[] args,
final boolean sort) throws IOException, MPDException {
return Music.getMusicFromList(mConnection.sendCommand(searchCommand, args), sort);
}
protected List<Music> genericSearch(final String searchCommand, final String type,
final String strToFind) throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(searchCommand, type, strToFind);
return Music.getMusicFromList(response, true);
}
public int getAlbumCount(final Artist artist, final boolean useAlbumArtistTag)
throws IOException, MPDException {
return listAlbums(artist.getName(), useAlbumArtistTag).size();
}
public int getAlbumCount(final String artist, final boolean useAlbumArtistTag)
throws IOException, MPDException {
return listAlbums(artist, useAlbumArtistTag).size();
}
protected void getAlbumDetails(final List<Album> albums, final boolean findYear)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue(albums.size());
for (final Album album : albums) {
commandQueue.add(getAlbumDetailsCommand(album));
}
final List<String[]> response = commandQueue.sendSeparated(mConnection);
if (response.size() == albums.size()) {
for (int i = 0; i < response.size(); i++) {
final String[] list = response.get(i);
final Album a = albums.get(i);
for (final String[] pair : Tools.splitResponse(list)) {
if ("songs".equals(pair[KEY])) {
a.setSongCount(Long.parseLong(pair[VALUE]));
} else if ("playtime".equals(pair[KEY])) {
a.setDuration(Long.parseLong(pair[VALUE]));
}
}
if (findYear) {
final List<Music> songs = getFirstTrack(a);
if (null != songs && !songs.isEmpty()) {
a.setYear(songs.get(0).getDate());
a.setPath(songs.get(0).getPath());
}
}
}
}
}
public List<Album> getAlbums(final Artist artist, final boolean sortByYear,
final boolean trackCountNeeded) throws IOException, MPDException {
List<Album> albums = getAlbums(artist, sortByYear, trackCountNeeded, false);
// 1. the null artist list already contains all albums
// 2. the "unknown artist" should not list unknown album artists
if (artist != null && !artist.isUnknown()) {
albums = Item.merged(getAlbums(artist, sortByYear, trackCountNeeded, true), albums);
}
return albums;
}
public List<Album> getAlbums(final Artist artist, final boolean sortByYear,
final boolean trackCountNeeded, final boolean useAlbumArtist)
throws IOException, MPDException {
final List<Album> albums;
if (artist == null) {
albums = getAllAlbums(trackCountNeeded);
} else {
final List<String> albumNames = listAlbums(artist.getName(), useAlbumArtist);
albums = new ArrayList<>(albumNames.size());
if (!albumNames.isEmpty()) {
for (final String album : albumNames) {
albums.add(new Album(album, artist, useAlbumArtist));
}
if (!useAlbumArtist) {
fixAlbumArtists(albums);
}
// after fixing album artists
if (trackCountNeeded || sortByYear) {
getAlbumDetails(albums, sortByYear);
}
if (!sortByYear) {
addAlbumPaths(albums);
}
Collections.sort(albums);
}
}
return albums;
}
/**
* Get all albums (if there is no artist specified for filtering)
*
* @param trackCountNeeded Do we need the track count ?
* @return all Albums
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Album> getAllAlbums(final boolean trackCountNeeded)
throws IOException, MPDException {
final List<Album> albums;
// Use MPD 0.19's album grouping feature if available.
if (mConnection.isProtocolVersionSupported(0, 19)) {
albums = listAllAlbumsGrouped(false);
} else {
final List<String> albumNames = listAlbums();
if (null != albumNames && !albumNames.isEmpty()) {
albums = new ArrayList<>(albumNames.size());
for (final String album : albumNames) {
albums.add(new Album(album, null));
}
} else {
albums = Collections.emptyList();
}
}
Collections.sort(albums);
return albums;
}
public List<Artist> getArtists() throws IOException, MPDException {
return Item.merged(getArtists(true), getArtists(false));
}
public List<Artist> getArtists(final boolean useAlbumArtist) throws IOException, MPDException {
final List<String> artistNames;
final List<Artist> artists;
if (useAlbumArtist) {
artistNames = listAlbumArtists();
} else {
artistNames = listArtists(true);
}
artists = new ArrayList<>(artistNames.size());
if (!artistNames.isEmpty()) {
for (final String artist : artistNames) {
artists.add(new Artist(artist));
}
}
Collections.sort(artists);
return artists;
}
public List<Artist> getArtists(final Genre genre) throws IOException, MPDException {
return Item.merged(getArtists(genre, true), getArtists(genre, false));
}
public List<Artist> getArtists(final Genre genre, final boolean useAlbumArtist)
throws IOException, MPDException {
final List<String> artistNames;
final List<Artist> artists;
if (useAlbumArtist) {
artistNames = listAlbumArtists(genre);
} else {
artistNames = listArtists(genre.getName(), true);
}
artists = new ArrayList<>(artistNames.size());
if (!artistNames.isEmpty()) {
for (final String artist : artistNames) {
artists.add(new Artist(artist));
}
}
Collections.sort(artists);
return artists;
}
protected List<Music> getFirstTrack(final Album album) throws IOException, MPDException {
final Artist artist = album.getArtist();
final String[] args = new String[6];
if (artist == null) {
args[0] = "";
args[1] = "";
} else if (album.hasAlbumArtist()) {
args[0] = MPDCommand.MPD_TAG_ALBUM_ARTIST;
} else {
args[0] = MPDCommand.MPD_TAG_ARTIST;
}
if (artist != null) {
args[1] = artist.getName();
}
args[2] = MPDCommand.MPD_TAG_ALBUM;
args[3] = album.getName();
args[4] = "track";
args[5] = "1";
List<Music> songs = find(args);
if (null == songs || songs.isEmpty()) {
args[5] = "01";
songs = find(args);
}
if (null == songs || songs.isEmpty()) {
args[5] = "1";
songs = search(args);
}
if (null == songs || songs.isEmpty()) {
final String[] args2 = Arrays.copyOf(args, 4); // find all tracks
songs = find(args2);
}
return songs;
}
public List<Genre> getGenres() throws IOException, MPDException {
final List<String> genreNames = listGenres();
List<Genre> genres = null;
if (null != genreNames && !genreNames.isEmpty()) {
genres = new ArrayList<>(genreNames.size());
for (final String genre : genreNames) {
genres.add(new Genre(genre));
}
}
if (null != genres) {
Collections.sort(genres);
}
return genres;
}
public InetAddress getHostAddress() {
return mConnection.getHostAddress();
}
public int getHostPort() {
return mConnection.getHostPort();
}
MPDConnection getIdleConnection() {
return mIdleConnection;
}
/**
* Returns MPD server version.
*
* @return MPD Server version.
*/
public String getMpdVersion() {
final int[] version = mIdleConnection.getMPDVersion();
final StringBuilder sb = new StringBuilder(version.length);
for (int i = 0; i < version.length; i++) {
sb.append(version[i]);
if (i < version.length - 1) {
sb.append('.');
}
}
return sb.toString();
}
/**
* Returns the available outputs
*
* @return List of available outputs
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<MPDOutput> getOutputs() throws IOException, MPDException {
final List<MPDOutput> result = new LinkedList<>();
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTS);
final LinkedList<String> lineCache = new LinkedList<>();
for (final String line : response) {
if (line.startsWith(MPDOutput.CMD_ID)) {
if (!lineCache.isEmpty()) {
result.add(MPDOutput.build(lineCache));
lineCache.clear();
}
}
lineCache.add(line);
}
if (!lineCache.isEmpty()) {
result.add(MPDOutput.build(lineCache));
}
return result;
}
/**
* Retrieves {@code playlist}.
*
* @return playlist.
*/
public MPDPlaylist getPlaylist() {
return mPlaylist;
}
public List<Music> getPlaylistSongs(final String playlistName)
throws IOException, MPDException {
final String[] args = new String[1];
args[0] = playlistName;
return genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args, false);
}
/**
* Returns a list of all available playlists
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Item> getPlaylists() throws IOException, MPDException {
return getPlaylists(false);
}
/**
* Returns a list of all available playlists
*
* @param sort whether the return list should be sorted
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Item> getPlaylists(final boolean sort) throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_LISTPLAYLISTS);
final List<Item> result = new ArrayList<>(response.size());
for (final String[] pair : Tools.splitResponse(response)) {
if ("playlist".equals(pair[KEY])) {
if (null != pair[VALUE] && !STREAMS_PLAYLIST.equals(pair[VALUE])) {
result.add(new PlaylistFile(pair[VALUE]));
}
}
}
if (sort) {
Collections.sort(result);
}
return result;
}
public List<Music> getSavedStreams() throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_LISTPLAYLISTS);
List<Music> savedStreams = null;
for (final String[] pair : Tools.splitResponse(response)) {
if ("playlist".equals(pair[KEY])) {
if (STREAMS_PLAYLIST.equals(pair[VALUE])) {
final String[] args = {pair[VALUE]};
savedStreams = genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args, false);
break;
}
}
}
return savedStreams;
}
public List<Music> getSongs(final Album album) throws IOException, MPDException {
final List<Music> songs = Music.getMusicFromList
(mConnection.sendCommand(getSongsCommand(album)), true);
if (album.hasAlbumArtist()) {
// remove songs that don't have this album artist (mpd >=0.18 puts them in)
final Artist artist = album.getArtist();
String artistName = null;
if (artist != null) {
artistName = artist.getName();
}
for (int i = songs.size() - 1; i >= 0; i
final String albumArtist = songs.get(i).getAlbumArtist();
if (albumArtist != null && !albumArtist.isEmpty()
&& !albumArtist.equals(artistName)) {
songs.remove(i);
}
}
}
if (null != songs) {
Collections.sort(songs);
}
return songs;
}
public List<Music> getSongs(final Artist artist) throws IOException, MPDException {
final List<Album> albums = getAlbums(artist, false, false);
final List<Music> songs = new ArrayList<>(albums.size());
for (final Album album : albums) {
songs.addAll(getSongs(album));
}
return songs;
}
/**
* Retrieves the current statistics for the connected server.
*
* @return statistics for the connected server.
*/
public MPDStatistics getStatistics() {
return mStatistics;
}
/**
* Retrieves status of the connected server.
*
* @return status of the connected server.
*/
public MPDStatus getStatus() {
return mStatus;
}
public Sticker getStickerManager() {
return new Sticker(mConnection);
}
/*
* test whether given album is in given genre
*/
public boolean isAlbumInGenre(final Album album, final Genre genre)
throws IOException, MPDException {
final List<String> response;
final Artist artist = album.getArtist();
String artistName = null;
String artistType = null;
if (artist != null) {
artistName = artist.getName();
if (album.hasAlbumArtist()) {
artistType = MPDCommand.MPD_TAG_ALBUM_ARTIST;
} else {
artistType = MPDCommand.MPD_TAG_ARTIST;
}
}
response = mConnection.sendCommand(new MPDCommand(
MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM,
MPDCommand.MPD_TAG_ALBUM, album.getName(),
artistType, artistName,
MPDCommand.MPD_TAG_GENRE, genre.getName()));
return !response.isEmpty();
}
/**
* Checks for command validity against a list of available commands generated on connection.
*
* @param command A MPD protocol command.
* @return True if the {@code command} is available for use, false otherwise.
*/
public boolean isCommandAvailable(final String command) {
return mConnection.isCommandAvailable(command);
}
/**
* Returns true when connected and false when not connected.
*
* @return true when connected and false when not connected
*/
public boolean isConnected() {
return mIdleConnection.isConnected();
}
public List<String> listAlbumArtists() throws IOException, MPDException {
return listAlbumArtists(true);
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbumArtists(final boolean sortInsensitive)
throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG,
MPDCommand.MPD_TAG_ALBUM_ARTIST);
return parseResponse(response, "albumartist", sortInsensitive);
}
public List<String> listAlbumArtists(final Genre genre) throws IOException, MPDException {
return listAlbumArtists(genre, true);
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbumArtists(final Genre genre, final boolean sortInsensitive)
throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(
MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST,
MPDCommand.MPD_TAG_GENRE, genre.getName());
return parseResponse(response, MPDCommand.MPD_TAG_ALBUM_ARTIST, sortInsensitive);
}
public List<String[]> listAlbumArtists(final List<Album> albums)
throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue(albums.size());
final List<String[]> response;
List<String[]> albumArtists = null;
for (final Album album : albums) {
final Artist artist = album.getArtist();
String artistCommand = null;
String artistName = null;
if (artist != null) {
artistCommand = MPDCommand.MPD_TAG_ARTIST;
artistName = artist.getName();
}
commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST,
artistCommand, artistName,
MPDCommand.MPD_TAG_ALBUM, album.getName());
}
response = commandQueue.sendSeparated(mConnection);
if (response.size() == albums.size()) {
for (int i = 0; i < response.size(); i++) {
for (int j = 0; j < response.get(i).length; j++) {
response.get(i)[j] = response.get(i)[j].substring("AlbumArtist: ".length());
}
}
albumArtists = response;
} else {
Log.warning(TAG, "Response and album size differ when listing album artists.");
}
return albumArtists;
}
/**
* List all albums from database.
*
* @return {@code Collection} with all album names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbums() throws IOException, MPDException {
return listAlbums(null, false, true);
}
/**
* List all albums from database.
*
* @param useAlbumArtist use AlbumArtist instead of Artist
* @return {@code Collection} with all album names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbums(final boolean useAlbumArtist) throws IOException, MPDException {
return listAlbums(null, useAlbumArtist, true);
}
/**
* List all albums from a given artist, including an entry for songs with no
* album tag.
*
* @param artist artist to list albums
* @param useAlbumArtist use AlbumArtist instead of Artist
* @return {@code Collection} with all album names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbums(final String artist, final boolean useAlbumArtist)
throws IOException, MPDException {
return listAlbums(artist, useAlbumArtist, true);
}
/**
* List all albums from a given artist.
*
* @param artist artist to list albums
* @param useAlbumArtist use AlbumArtist instead of Artist
* @param includeUnknownAlbum include an entry for songs with no album tag
* @return {@code Collection} with all album names from the given
* artist present in database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listAlbums(final String artist, final boolean useAlbumArtist,
final boolean includeUnknownAlbum) throws IOException, MPDException {
boolean foundSongWithoutAlbum = false;
final List<String> response =
mConnection.sendCommand
(listAlbumsCommand(artist, useAlbumArtist));
final List<String> result = new ArrayList<>(response.size());
for (final String line : response) {
final String name = line.substring("Album: ".length());
if (name.isEmpty()) {
foundSongWithoutAlbum = true;
} else {
result.add(name);
}
}
// add a single blank entry to host all songs without an album set
if (includeUnknownAlbum && foundSongWithoutAlbum) {
result.add("");
}
Collections.sort(result);
return result;
}
/**
* List all albums grouped by Artist/AlbumArtist
* This method queries both Artist/AlbumArtist and tries to detect if the artist is an artist
* or an album artist. Only the AlbumArtist query will be displayed so that the list is not
* cluttered.
*
* @param includeUnknownAlbum include an entry for albums with no artists
* @return {@code Collection} with all albums present in database, with their artist.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Album> listAllAlbumsGrouped(final boolean includeUnknownAlbum)
throws IOException, MPDException {
final List<Album> artistAlbums = listAllAlbumsGrouped(false, includeUnknownAlbum);
final List<Album> albumArtistAlbums = listAllAlbumsGrouped(true, includeUnknownAlbum);
for (final Album artistAlbum : artistAlbums) {
for (final Album albumArtistAlbum : albumArtistAlbums) {
if (artistAlbum.getArtist() != null && artistAlbum
.doesNameExist(albumArtistAlbum)) {
albumArtistAlbum.setHasAlbumArtist(false);
break;
}
}
}
return albumArtistAlbums;
}
/**
* List all albums grouped by Artist/AlbumArtist
*
* @param useAlbumArtist use AlbumArtist instead of Artist
* @param includeUnknownAlbum include an entry for albums with no artists
* @return {@code Collection} with all albums present in database, with their artist.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Album> listAllAlbumsGrouped(final boolean useAlbumArtist,
final boolean includeUnknownAlbum) throws IOException, MPDException {
final String albumResponse = "Album";
final String artistResponse;
final List<String> response =
mConnection.sendCommand(listAllAlbumsGroupedCommand(useAlbumArtist));
final List<Album> result = new ArrayList<>(response.size() / 2);
Album currentAlbum = null;
if (useAlbumArtist) {
artistResponse = "AlbumArtist";
} else {
artistResponse = "Artist";
}
for (final String[] pair : Tools.splitResponse(response)) {
if (artistResponse.equals(pair[KEY])) {
// Don't make the check with the other so we don't waste time doing string
// comparisons for nothing.
if (currentAlbum != null) {
currentAlbum.setAlbumArtist(new Artist(pair[VALUE]));
}
} else if (albumResponse.equals(pair[KEY])) {
if (!pair[VALUE].isEmpty() || includeUnknownAlbum) {
currentAlbum = new Album(pair[VALUE], null);
currentAlbum.setHasAlbumArtist(useAlbumArtist);
result.add(currentAlbum);
} else {
currentAlbum = null;
}
}
}
Collections.sort(result);
return result;
}
/**
* Returns a sorted listallinfo command from the media server. Use of this command is highly
* discouraged, as it can retrieve so much information the server max_output_buffer_size may
* be exceeded, which will, in turn, truncate the output to this method.
*
* @return List of all available music information.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<Music> listAllInfo() throws IOException, MPDException {
final List<String> allInfo = mConnection.sendCommand(MPDCommand.MPD_CMD_LISTALLINFO);
return Music.getMusicFromList(allInfo, false);
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listArtists() throws IOException, MPDException {
return listArtists(true);
}
/**
* List all artist names from database.
*
* @param sortInsensitive boolean for insensitive sort when true
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listArtists(final boolean sortInsensitive)
throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG,
MPDCommand.MPD_TAG_ARTIST);
return parseResponse(response, "Artist", sortInsensitive);
}
/**
* List all album artist or artist names of all given albums from database.
*
* @return list of array of artist names for each album.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String[]> listArtists(final List<Album> albums, final boolean useAlbumArtist)
throws IOException, MPDException {
final List<String[]> result;
if (albums == null) {
result = Collections.emptyList();
} else {
final List<String[]> responses = listArtistsCommand(albums, useAlbumArtist);
result = new ArrayList<>(responses.size());
ArrayList<String> albumResult = null;
final int artistLength;
if (useAlbumArtist) {
artistLength = "AlbumArtist: ".length();
} else {
artistLength = "Artist: ".length();
}
for (final String[] response : responses) {
if (albumResult != null) {
albumResult.clear();
}
for (final String album : response) {
final String name = album.substring(artistLength);
if (albumResult == null) {
/** Give the array list an approximate size. */
albumResult = new ArrayList<>(album.length() * response.length);
}
albumResult.add(name);
}
result.add(albumResult.toArray(new String[albumResult.size()]));
}
}
return result;
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listArtists(final String genre) throws IOException, MPDException {
return listArtists(genre, true);
}
/**
* List all artist names from database.
*
* @param sortInsensitive boolean for insensitive sort when true
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listArtists(final String genre, final boolean sortInsensitive)
throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG,
MPDCommand.MPD_TAG_ARTIST, MPDCommand.MPD_TAG_GENRE, genre);
return parseResponse(response, "Artist", sortInsensitive);
}
private List<String[]> listArtistsCommand(final Iterable<Album> albums,
final boolean useAlbumArtist) throws IOException, MPDException {
final CommandQueue commandQueue = new CommandQueue();
for (final Album album : albums) {
final Artist artist = album.getArtist();
// When adding album artist to existing artist check that the artist matches
if (useAlbumArtist && artist != null && !artist.isUnknown()) {
commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST,
MPDCommand.MPD_TAG_ALBUM, album.getName(),
MPDCommand.MPD_TAG_ARTIST, artist.getName());
} else {
final String artistCommand;
if (useAlbumArtist) {
artistCommand = MPDCommand.MPD_TAG_ALBUM_ARTIST;
} else {
artistCommand = MPDCommand.MPD_TAG_ARTIST;
}
commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, artistCommand,
MPDCommand.MPD_TAG_ALBUM, album.getName());
}
}
return commandQueue.sendSeparated(mConnection);
}
/**
* List all genre names from database.
*
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listGenres() throws IOException, MPDException {
return listGenres(true);
}
/**
* List all genre names from database.
*
* @param sortInsensitive boolean for insensitive sort when true
* @return artist names from database.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public List<String> listGenres(final boolean sortInsensitive) throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG,
MPDCommand.MPD_TAG_GENRE);
return parseResponse(response, "Genre", sortInsensitive);
}
public void movePlaylistSong(final String playlistName, final int from, final int to)
throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlistName,
Integer.toString(from), Integer.toString(to));
}
/**
* Jumps to next playlist track.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void next() throws IOException, MPDException {
mConnection.sendCommand(nextCommand());
}
/**
* Pauses/Resumes music playing.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void pause() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PAUSE);
}
/**
* Starts playing music.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void play() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAY);
}
/**
* Plays previous playlist music.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void previous() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PREV);
}
/**
* Tells server to refresh database.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void refreshDatabase() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH);
}
/**
* Tells server to refresh database.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void refreshDatabase(final String folder) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH, folder);
}
public void refreshDirectory(final Directory directory) throws IOException, MPDException {
directory.refresh(mConnection);
}
public void removeFromPlaylist(final String playlistName, final Integer pos)
throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlistName,
Integer.toString(pos));
}
public void removeSavedStream(final Integer pos) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAYLIST_DEL, STREAMS_PLAYLIST,
Integer.toString(pos));
}
public void saveStream(final String url, final String name) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, STREAMS_PLAYLIST,
Stream.addStreamName(url, name));
}
/**
* Similar to {@code find},{@code search} looks for partial
* matches in the MPD database.
*
* @param type type of search. Should be one of the following constants:
* MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM,
* MPD_SEARCH_FILENAME
* @param locatorString case-insensitive locator locatorString. Anything that contains
* {@code locatorString} will be returned in the results.
* @return a Collection of {@code Music}.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see org.a0z.mpd.item.Music
*/
public List<Music> search(final String type, final String locatorString)
throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, locatorString);
}
public List<Music> search(final String[] args) throws IOException, MPDException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, args, true);
}
/**
* Seeks current music to the position.
*
* @param position song position in seconds
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void seek(final long position) throws IOException, MPDException {
seekById(mStatus.getSongId(), position);
}
/**
* Seeks music to the position.
*
* @param songId music id in playlist.
* @param position song position in seconds.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void seekById(final int songId, final long position) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId),
Long.toString(position));
}
/**
* Seeks music to the position.
*
* @param index music position in playlist.
* @param position song position in seconds.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void seekByIndex(final int index, final long position) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_SEEK, Integer.toString(index),
Long.toString(position));
}
/**
* Enabled or disable consuming.
*
* @param consume if true song consuming will be enabled, if false song
* consuming will be disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setConsume(final boolean consume) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_CONSUME, MPDCommand.booleanValue(consume));
}
/**
* Sets cross-fade.
*
* @param time cross-fade time in seconds. 0 to disable cross-fade.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setCrossFade(final int time) throws IOException, MPDException {
mConnection
.sendCommand(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time)));
}
/**
* Enabled or disable random.
*
* @param random if true random will be enabled, if false random will be
* disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setRandom(final boolean random) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_RANDOM, MPDCommand.booleanValue(random));
}
/**
* Enabled or disable repeating.
*
* @param repeat if true repeating will be enabled, if false repeating will
* be disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setRepeat(final boolean repeat) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_REPEAT, MPDCommand.booleanValue(repeat));
}
/**
* Enabled or disable single mode.
*
* @param single if true single mode will be enabled, if false single mode
* will be disabled.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setSingle(final boolean single) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_SINGLE, MPDCommand.booleanValue(single));
}
/**
* Sets volume to {@code volume}.
*
* @param volume new volume value, must be in 0-100 range.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void setVolume(final int volume) throws IOException, MPDException {
final int vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, volume));
mConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Kills server.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void shutdown() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_KILL);
}
/**
* Skip to song with specified {@code id}.
*
* @param id song id.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void skipToId(final int id) throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id));
}
/**
* Jumps to track {@code position} from playlist.
*
* @param position track number.
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see #skipToId(int)
*/
public void skipToPosition(final int position) throws IOException, MPDException {
mConnection.sendCommand(skipToPositionCommand(position));
}
/**
* Stops music playing.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
*/
public void stop() throws IOException, MPDException {
mConnection.sendCommand(MPDCommand.MPD_CMD_STOP);
}
/**
* Updates the {@link MPDStatistics} object stored in this object. Do not call this
* method directly unless you absolutely know what you are doing. If a long running application
* needs a status update, use the {@code MPDStatusMonitor} instead.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see MPDStatusMonitor
*/
public void updateStatistics() throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_STATISTICS);
mStatistics.update(response);
}
/**
* Retrieves status of the connected server. Do not call this method directly unless you
* absolutely know what you are doing. If a long running application needs a status update, use
* the {@code MPDStatusMonitor} instead.
*
* @throws IOException Thrown upon a communication error with the server.
* @throws MPDException Thrown if an error occurs as a result of command execution.
* @see MPDStatusMonitor
*/
void updateStatus() throws IOException, MPDException {
final List<String> response = mConnection.sendCommand(MPDCommand.MPD_CMD_STATUS);
if (response == null) {
Log.error(TAG, "No status response from the MPD server.");
} else {
mStatus.updateStatus(response);
}
}
}
|
package com.hida.model;
import java.security.SecureRandom;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An abstract Id generator that all potential Pid generators should extend.
*
* @author Brittany Cruz
* @author lruffin
*/
public abstract class IdGenerator {
/**
* Creates and new random number generator to aid in the production of
* non-deterministic ids.
*/
protected static final SecureRandom Rng = new SecureRandom();
/**
* LOGGER; logfile to be stored in resource folder
*/
protected static final Logger LOGGER = LoggerFactory.getLogger(IdGenerator.class);
/**
* The string that will be at the front of every id
*/
protected String Prefix;
/**
* missing javadoc
*
* @param prefix
*/
public IdGenerator(String prefix) {
this.Prefix = prefix;
}
public abstract Set<Pid> randomMint(long amount);
public abstract Set<Pid> sequentialMint(long amount);
public abstract long calculatePermutations();
public abstract void incrementPid(Pid pid);
protected abstract void assignName(Pid pid);
/**
* Checks whether or not the prefix is valid.
*
* @param prefix The string that will be at the front of every id.
* @return true if it contains numbers and letters and does not exceed 20
* characters.
*/
public final boolean isValidPrefix(String prefix) {
return prefix.matches("^[0-9a-zA-Z]*$") && prefix.length() <= 20;
}
/**
* Checks whether or not the requested amount is valid.
*
* @param amount The amount of ids requested.
* @return True if amount is non-negative.
*/
public final boolean isValidAmount(long amount) {
return amount >= 0;
}
/**
* Checks whether or not the requested root length is valid
*
* @param rootLength Designates the length of the id's root.
* @return True if rootLength is non-negative and less than or equal to 10.
*/
public final boolean isValidRootLength(long rootLength) {
return rootLength >= 0 && rootLength <= 10;
}
/**
* Checks whether or not the given charMap is valid for this minter.
*
* @param charMap The mapping used to describe range of possible characters
* at each of the id's root's digits.
* @return True if charMap only contains the characters: 'd', 'l', 'u', 'm',
* or 'e'.
*/
public final boolean isValidCharMap(String charMap) {
return charMap.matches("^[dlume]+$");
}
/* typical getter and setter methods */
public String getPrefix() {
return Prefix;
}
public void setPrefix(String Prefix) {
this.Prefix = Prefix;
}
}
|
package org.opencms.setup;
import org.opencms.configuration.CmsConfigurationManager;
import org.opencms.configuration.CmsModuleConfiguration;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsResource;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.i18n.CmsEncoder;
import org.opencms.importexport.CmsImportParameters;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsSystemInfo;
import org.opencms.main.OpenCms;
import org.opencms.module.CmsModule;
import org.opencms.module.CmsModuleVersion;
import org.opencms.module.CmsModuleXmlHandler;
import org.opencms.relations.I_CmsLinkParseable;
import org.opencms.report.CmsHtmlReport;
import org.opencms.report.CmsShellReport;
import org.opencms.report.I_CmsReport;
import org.opencms.setup.db.CmsUpdateDBThread;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.threads.CmsXmlContentRepairSettings;
import org.opencms.workplace.threads.CmsXmlContentRepairThread;
import org.opencms.xml.CmsXmlException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.servlet.jsp.JspWriter;
import org.apache.commons.logging.Log;
import com.google.common.collect.MapMaker;
/**
* A java bean as a controller for the OpenCms update wizard.<p>
*
* @since 6.0.0
*/
public class CmsUpdateBean extends CmsSetupBean {
/** name of the update folder. */
public static final String FOLDER_UPDATE = "update" + File.separatorChar;
/** replace pattern constant for the cms script. */
private static final String C_ADMIN_GROUP = "@ADMIN_GROUP@";
/** replace pattern constant for the cms script. */
private static final String C_ADMIN_PWD = "@ADMIN_PWD@";
/** replace pattern constant for the cms script. */
private static final String C_ADMIN_USER = "@ADMIN_USER@";
/** replace pattern constant for the cms script. */
private static final String C_UPDATE_PROJECT = "@UPDATE_PROJECT@";
/** replace pattern constant for the cms script. */
private static final String C_UPDATE_SITE = "@UPDATE_SITE@";
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsUpdateBean.class);
/** Static flag to indicate if all modules should be updated regardless of their version number. */
private static final boolean UPDATE_ALL_MODULES = false;
/** The new logging offset in the database update thread. */
protected int m_newLoggingDBOffset;
/** The old logging offset in the database update thread. */
protected int m_oldLoggingDBOffset;
/** The used admin user name. */
private String m_adminGroup = "_tmpUpdateGroup" + (System.currentTimeMillis() % 1000);
/** the admin user password. */
private String m_adminPwd = "admin";
/** The used admin user name. */
private String m_adminUser = "Admin";
/** The update database thread. */
private CmsUpdateDBThread m_dbUpdateThread;
/** The detected mayor version, based on DB structure. */
private int m_detectedVersion;
/** Parameter for keeping the history. */
private boolean m_keepHistory;
/** List of module to be updated. */
private List<String> m_modulesToUpdate;
/** the update project. */
private String m_updateProject = "_tmpUpdateProject" + (System.currentTimeMillis() % 1000);
/** the site for update. */
private String m_updateSite = CmsResource.VFS_FOLDER_SITES + "/default/";
/** Cache for the up-to-date module names. */
private List<String> m_uptodateModules;
/** The workplace import thread. */
private CmsUpdateThread m_workplaceUpdateThread;
/**
* Default constructor.<p>
*/
public CmsUpdateBean() {
super();
m_modulesFolder = FOLDER_UPDATE + CmsSystemInfo.FOLDER_MODULES;
m_logFile = CmsSystemInfo.FOLDER_WEBINF + CmsLog.FOLDER_LOGS + "update.log";
}
/**
* Adds the subscription driver to the properties.<p>
*/
public void addSubscriptionDriver() {
setExtProperty("driver.subscription", "db");
String dbName = getExtProperty("db.name");
String packageName = getDbPackage(dbName);
setExtProperty("db.subscription.driver", "org.opencms.db." + packageName + ".CmsSubscriptionDriver");
setExtProperty("db.subscription.pool", "opencms:default");
setExtProperty("db.subscription.sqlmanager", "org.opencms.db." + packageName + ".CmsSqlManager");
}
/**
* Compatibility check for OCEE modules.<p>
*
* @param version the opencms version
*
* @return <code>false</code> if OCEE is present but not compatible with opencms version
*/
@SuppressWarnings({"boxing"})
public boolean checkOceeVersion(String version) {
try {
Class<?> manager = Class.forName("org.opencms.ocee.base.CmsOceeManager");
Method checkVersion = manager.getMethod("checkOceeVersion", String.class);
return (Boolean)checkVersion.invoke(manager, version);
} catch (ClassNotFoundException e) {
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Creates the shared folder if possible.<p>
*
* @throws Exception if something goes wrong
*/
public void createSharedFolder() throws Exception {
String originalSiteRoot = m_cms.getRequestContext().getSiteRoot();
CmsProject originalProject = m_cms.getRequestContext().getCurrentProject();
try {
m_cms.getRequestContext().setSiteRoot("");
m_cms.getRequestContext().setCurrentProject(m_cms.createTempfileProject());
if (!m_cms.existsResource("/shared")) {
m_cms.createResource("/shared", OpenCms.getResourceManager().getResourceType("folder").getTypeId());
CmsResource shared = m_cms.readResource("/shared");
OpenCms.getPublishManager().publishProject(
m_cms,
new CmsHtmlReport(m_cms.getRequestContext().getLocale(), m_cms.getRequestContext().getSiteRoot()),
shared,
false);
OpenCms.getPublishManager().waitWhileRunning();
}
try {
m_cms.lockResourceTemporary("/shared");
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
try {
m_cms.chacc("/shared", "group", "Users", "+v+w+r+i");
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
} finally {
m_cms.getRequestContext().setSiteRoot(originalSiteRoot);
m_cms.getRequestContext().setCurrentProject(originalProject);
}
}
/**
* Returns html code to display an error.<p>
*
* @param pathPrefix to adjust the path
*
* @return html code
*/
@Override
public String displayError(String pathPrefix) {
if (pathPrefix == null) {
pathPrefix = "";
}
StringBuffer html = new StringBuffer(512);
html.append("<table border='0' cellpadding='5' cellspacing='0' style='width: 100%; height: 100%;'>");
html.append("\t<tr>");
html.append("\t\t<td style='vertical-align: middle; height: 100%;'>");
html.append(getHtmlPart("C_BLOCK_START", "Error"));
html.append("\t\t\t<table border='0' cellpadding='0' cellspacing='0' style='width: 100%;'>");
html.append("\t\t\t\t<tr>");
html.append("\t\t\t\t\t<td><img src='").append(pathPrefix).append("resources/error.png' border='0'></td>");
html.append("\t\t\t\t\t<td> </td>");
html.append("\t\t\t\t\t<td style='width: 100%;'>");
html.append("\t\t\t\t\t\tThe Alkacon OpenCms update wizard has not been started correctly!<br>");
html.append("\t\t\t\t\t\tPlease click <a href='").append(pathPrefix);
html.append("index.jsp'>here</a> to restart the wizard.");
html.append("\t\t\t\t\t</td>");
html.append("\t\t\t\t</tr>");
html.append("\t\t\t</table>");
html.append(getHtmlPart("C_BLOCK_END"));
html.append("\t\t</td>");
html.append("\t</tr>");
html.append("</table>");
return html.toString();
}
/**
* Returns the admin Pwd.<p>
*
* @return the admin Pwd
*/
public String getAdminPwd() {
return m_adminPwd;
}
/**
* Returns the admin User.<p>
*
* @return the admin User
*/
public String getAdminUser() {
return m_adminUser;
}
/**
* Returns the detected mayor version, based on DB structure.<p>
*
* @return the detected mayor version
*/
public int getDetectedVersion() {
return m_detectedVersion;
}
/**
* Returns a map of all previously installed modules.<p>
*
* @return a map of <code>[String, {@link org.opencms.module.CmsModuleVersion}]</code> objects
*
* @see org.opencms.module.CmsModuleManager#getAllInstalledModules()
*/
public Map<String, CmsModuleVersion> getInstalledModules() {
String file = CmsModuleConfiguration.DEFAULT_XML_FILE_NAME;
// /opencms/modules/module[?]
String basePath = new StringBuffer("/").append(CmsConfigurationManager.N_ROOT).append("/").append(
CmsModuleConfiguration.N_MODULES).append("/").append(CmsModuleXmlHandler.N_MODULE).append("[?]/").toString();
Map<String, CmsModuleVersion> modules = new HashMap<String, CmsModuleVersion>();
String name = "";
for (int i = 1; name != null; i++) {
if (i > 1) {
String ver = CmsModuleVersion.DEFAULT_VERSION;
try {
ver = getXmlHelper().getValue(
file,
CmsStringUtil.substitute(basePath, "?", "" + (i - 1)) + CmsModuleXmlHandler.N_VERSION);
} catch (CmsXmlException e) {
// ignore
}
modules.put(name, new CmsModuleVersion(ver));
}
try {
name = getXmlHelper().getValue(
file,
CmsStringUtil.substitute(basePath, "?", "" + i) + CmsModuleXmlHandler.N_NAME);
} catch (CmsXmlException e) {
// ignore
}
}
return modules;
}
/**
* List of modules to be updated.<p>
*
* @return a list of module names
*/
public List<String> getModulesToUpdate() {
if (m_modulesToUpdate == null) {
getUptodateModules();
}
return m_modulesToUpdate;
}
/**
* Returns the update database thread.<p>
*
* @return the update database thread
*/
public CmsUpdateDBThread getUpdateDBThread() {
return m_dbUpdateThread;
}
/**
* Returns the update Project.<p>
*
* @return the update Project
*/
public String getUpdateProject() {
return m_updateProject;
}
/**
* Returns the update site.<p>
*
* @return the update site
*/
public String getUpdateSite() {
return m_updateSite;
}
/**
* Returns the modules that does not need to be updated.<p>
*
* @return a list of module names
*/
public List<String> getUptodateModules() {
if (m_uptodateModules == null) {
m_uptodateModules = new ArrayList<String>();
m_modulesToUpdate = new ArrayList<String>();
Map<String, CmsModuleVersion> installedModules = getInstalledModules();
Map<String, CmsModule> availableModules = getAvailableModules();
Iterator<Map.Entry<String, CmsModule>> itMods = availableModules.entrySet().iterator();
while (itMods.hasNext()) {
Map.Entry<String, CmsModule> entry = itMods.next();
String name = entry.getKey();
CmsModuleVersion instVer = installedModules.get(name);
CmsModuleVersion availVer = entry.getValue().getVersion();
boolean uptodate = (!UPDATE_ALL_MODULES) && ((instVer != null) && (instVer.compareTo(availVer) >= 0));
if (uptodate) {
m_uptodateModules.add(name);
} else {
m_modulesToUpdate.add(name);
}
if (LOG.isDebugEnabled()) {
LOG.debug(name
+ " --- installed: "
+ instVer
+ " available: "
+ availVer
+ "
+ uptodate);
}
}
}
return m_uptodateModules;
}
/**
* Returns the workplace update thread.<p>
*
* @return the workplace update thread
*/
public CmsUpdateThread getWorkplaceUpdateThread() {
return m_workplaceUpdateThread;
}
/**
* @see org.opencms.setup.CmsSetupBean#htmlModules()
*/
@Override
public String htmlModules() {
StringBuffer html = new StringBuffer(1024);
Set<String> uptodate = new HashSet<String>(getUptodateModules());
Iterator<String> itModules = sortModules(getAvailableModules().values()).iterator();
boolean hasModules = false;
for (int i = 0; itModules.hasNext(); i++) {
String moduleName = itModules.next();
CmsModule module = getAvailableModules().get(moduleName);
if (UPDATE_ALL_MODULES || !uptodate.contains(moduleName)) {
html.append(htmlModule(module, i));
hasModules = true;
} else {
html.append("<input type='hidden' name='availableModules' value='");
html.append(moduleName);
html.append("'>\n");
}
}
if (!hasModules) {
html.append("\t<tr>\n");
html.append("\t\t<td style='vertical-align: middle;'>\n");
html.append(Messages.get().getBundle().key(Messages.GUI_WARNING_ALL_MODULES_UPTODATE_0));
html.append("\t\t</td>\n");
html.append("\t</tr>\n");
}
return html.toString();
}
/**
* Creates a new instance of the setup Bean.<p>
*
* @param webAppRfsPath path to the OpenCms web application
* @param servletMapping the OpenCms servlet mapping
* @param defaultWebApplication the name of the default web application
*/
@Override
public void init(String webAppRfsPath, String servletMapping, String defaultWebApplication) {
try {
super.init(webAppRfsPath, servletMapping, defaultWebApplication);
if (m_workplaceUpdateThread != null) {
if (m_workplaceUpdateThread.isAlive()) {
m_workplaceUpdateThread.kill();
}
m_workplaceUpdateThread = null;
}
if (m_dbUpdateThread != null) {
if (m_dbUpdateThread.isAlive()) {
m_dbUpdateThread.kill();
}
m_dbUpdateThread = null;
m_newLoggingOffset = 0;
m_oldLoggingOffset = 0;
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Returns the keep History parameter value.<p>
*
* @return the keep History parameter value
*/
public boolean isKeepHistory() {
return m_keepHistory;
}
/**
* Returns <code>true</code> if a DB update is needed.<p>
*
* @return <code>true</code> if a DB update is needed
*/
public boolean isNeedDbUpdate() {
return m_detectedVersion != 8;
}
/**
* Try to preload necessary classes, to avoid ugly class loader issues caused by JARs being deleted during the update.
*/
public void preload() {
//opencms.jar
preload(OpenCms.class);
//guava
preload(MapMaker.class);
}
/**
* Preloads classes from the same jar file as a given class.<p>
*
* @param cls the class for which the classes from the same jar file should be loaded
*/
public void preload(Class<?> cls) {
try {
File jar = new File(cls.getProtectionDomain().getCodeSource().getLocation().getFile());
java.util.jar.JarFile jarfile = new JarFile(jar);
try {
Enumeration<JarEntry> entries = jarfile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.endsWith(".class")) {
String className = name.replaceFirst("\\.class$", "");
className = className.replace('/', '.');
try {
Class.forName(className);
} catch (VirtualMachineError e) {
throw e;
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
} finally {
jarfile.close();
}
} catch (VirtualMachineError e) {
throw e;
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
/**
* Prepares step 1 of the update wizard.<p>
*/
public void prepareUpdateStep1() {
// nothing to do jet
}
/**
* Prepares step 1 of the update wizard.<p>
*/
public void prepareUpdateStep1b() {
if (!isInitialized()) {
return;
}
if ((m_dbUpdateThread != null) && (m_dbUpdateThread.isFinished())) {
// update is already finished, just wait for client to collect final data
return;
}
if (m_dbUpdateThread == null) {
m_dbUpdateThread = new CmsUpdateDBThread(this);
}
if (!m_dbUpdateThread.isAlive()) {
m_dbUpdateThread.start();
}
}
/**
* Generates the output for step 1 of the setup wizard.<p>
*
* @param out the JSP print stream
* @throws IOException in case errors occur while writing to "out"
*/
public void prepareUpdateStep1bOutput(JspWriter out) throws IOException {
m_oldLoggingDBOffset = m_newLoggingDBOffset;
m_newLoggingDBOffset = m_dbUpdateThread.getLoggingThread().getMessages().size();
if (isInitialized()) {
for (int i = m_oldLoggingDBOffset; i < m_newLoggingDBOffset; i++) {
String str = m_dbUpdateThread.getLoggingThread().getMessages().get(i).toString();
str = CmsEncoder.escapeWBlanks(str, CmsEncoder.ENCODING_UTF_8);
out.println("output[" + (i - m_oldLoggingDBOffset) + "] = \"" + str + "\";");
}
} else {
out.println("output[0] = 'ERROR';");
}
boolean threadFinished = m_dbUpdateThread.isFinished();
boolean allWritten = m_oldLoggingDBOffset >= m_dbUpdateThread.getLoggingThread().getMessages().size();
out.println("function initThread() {");
if (isInitialized()) {
out.print("send();");
if (threadFinished && allWritten) {
out.println("setTimeout('top.display.finish()', 1000);");
} else {
int timeout = 5000;
if (getUpdateDBThread().getLoggingThread().getMessages().size() < 20) {
timeout = 2000;
}
out.println("setTimeout('location.reload()', " + timeout + ");");
}
}
out.println("}");
}
/**
* Prepares step 5 of the update wizard.<p>
*/
public void prepareUpdateStep5() {
if (isInitialized()) {
preload();
try {
String fileName = getWebAppRfsPath() + FOLDER_UPDATE + "cmsupdate";
// read the file
FileInputStream fis = new FileInputStream(fileName + CmsConfigurationManager.POSTFIX_ORI);
String script = "";
int readChar = fis.read();
while (readChar > -1) {
script += (char)readChar;
readChar = fis.read();
}
fis.close();
// substitute macros
script = CmsStringUtil.substitute(script, C_ADMIN_USER, getAdminUser());
script = CmsStringUtil.substitute(script, C_ADMIN_PWD, getAdminPwd());
script = CmsStringUtil.substitute(script, C_UPDATE_PROJECT, getUpdateProject());
script = CmsStringUtil.substitute(script, C_UPDATE_SITE, getUpdateSite());
script = CmsStringUtil.substitute(script, C_ADMIN_GROUP, getAdminGroup());
// write the new script
FileOutputStream fos = new FileOutputStream(fileName + ".txt");
fos.write(script.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
/**
* Prepares step 5 of the update wizard.<p>
*/
public void prepareUpdateStep5b() {
if (!isInitialized()) {
return;
}
addSubscriptionDriver();
if ((m_workplaceUpdateThread != null) && (m_workplaceUpdateThread.isFinished())) {
// update is already finished, just wait for client to collect final data
return;
}
if (m_workplaceUpdateThread == null) {
m_workplaceUpdateThread = new CmsUpdateThread(this);
}
if (!m_workplaceUpdateThread.isAlive()) {
m_workplaceUpdateThread.start();
}
}
/**
* Generates the output for the update wizard.<p>
*
* @param out the JSP print stream
*
* @throws IOException in case errors occur while writing to "out"
*/
public void prepareUpdateStep5bOutput(JspWriter out) throws IOException {
if ((m_workplaceUpdateThread == null) || (m_workplaceUpdateThread.getLoggingThread() == null)) {
return;
}
m_oldLoggingOffset = m_newLoggingOffset;
m_newLoggingOffset = m_workplaceUpdateThread.getLoggingThread().getMessages().size();
if (isInitialized()) {
for (int i = m_oldLoggingOffset; i < m_newLoggingOffset; i++) {
String str = m_workplaceUpdateThread.getLoggingThread().getMessages().get(i).toString();
str = CmsEncoder.escapeWBlanks(str, CmsEncoder.ENCODING_UTF_8);
out.println("output[" + (i - m_oldLoggingOffset) + "] = \"" + str + "\";");
}
} else {
out.println("output[0] = 'ERROR';");
}
boolean threadFinished = m_workplaceUpdateThread.isFinished();
boolean allWritten = m_oldLoggingOffset >= m_workplaceUpdateThread.getLoggingThread().getMessages().size();
out.println("function initThread() {");
if (isInitialized()) {
out.print("send();");
if (threadFinished && allWritten) {
out.println("setTimeout('top.display.finish()', 500);");
} else {
int timeout = 5000;
if (getWorkplaceUpdateThread().getLoggingThread().getMessages().size() < 20) {
timeout = 1000;
}
out.println("setTimeout('location.reload()', " + timeout + ");");
}
}
out.println("}");
}
/**
* Prepares step 6 of the update wizard.<p>
*/
public void prepareUpdateStep6() {
Set<String> forced = new HashSet<String>();
forced.add("driver.subscription");
forced.add("db.subscription.driver");
forced.add("db.subscription.pool");
forced.add("db.subscription.sqlmanager");
addSubscriptionDriver();
if (isInitialized()) {
// lock the wizard for further use
lockWizard();
// save Properties to file "opencms.properties"
saveProperties(getProperties(), CmsSystemInfo.FILE_PROPERTIES, false, forced);
}
}
/**
* Sets the admin Pwd.<p>
*
* @param adminPwd the admin Pwd to set
*/
public void setAdminPwd(String adminPwd) {
m_adminPwd = adminPwd;
}
/**
* Sets the admin User.<p>
*
* @param adminUser the admin User to set
*/
public void setAdminUser(String adminUser) {
m_adminUser = adminUser;
}
/**
* Sets the detected mayor version.<p>
*
* @param detectedVersion the value to set
*/
public void setDetectedVersion(int detectedVersion) {
m_detectedVersion = detectedVersion;
}
/**
* Sets the keep History parameter value.<p>
*
* @param keepHistory the keep History parameter value to set
*/
public void setKeepHistory(boolean keepHistory) {
m_keepHistory = keepHistory;
}
/**
* Sets the update Project.<p>
*
* @param updateProject the update Project to set
*/
public void setUpdateProject(String updateProject) {
m_updateProject = updateProject;
}
/**
* Sets the update site.<p>
*
* @param site the update site to set
*/
public void setUpdateSite(String site) {
m_updateSite = site;
}
/**
* @see org.opencms.main.I_CmsShellCommands#shellExit()
*/
@Override
public void shellExit() {
System.out.println();
System.out.println();
System.out.println("The update is finished!\nThe OpenCms system used for the update will now shut down.");
}
/**
* @see org.opencms.main.I_CmsShellCommands#shellStart()
*/
@Override
public void shellStart() {
System.out.println();
System.out.println("Starting Workplace update for OpenCms!");
String[] copy = org.opencms.main.Messages.COPYRIGHT_BY_ALKACON;
for (int i = copy.length - 1; i >= 0; i
System.out.println(copy[i]);
}
System.out.println("This is OpenCms " + OpenCms.getSystemInfo().getVersionNumber());
System.out.println();
System.out.println();
}
/**
* Installed all modules that have been set using {@link #setInstallModules(String)}.<p>
*
* This method is invoked as a shell command.<p>
*
* @throws Exception if something goes wrong
*/
public void updateModulesFromUpdateBean() throws Exception {
// read here how the list of modules to be installed is passed from the setup bean to the
// setup thread, and finally to the shell process that executes the setup script:
// 1) the list with the package names of the modules to be installed is saved by setInstallModules
// 2) the setup thread gets initialized in a JSP of the setup wizard
// 3) the instance of the setup bean is passed to the setup thread by setAdditionalShellCommand
// 4) the setup bean is passed to the shell by startSetup
// 5) because the setup bean implements I_CmsShellCommands, the shell constructor can pass the shell's CmsObject back to the setup bean
// 6) thus, the setup bean can do things with the Cms
if ((m_cms != null) && (m_installModules != null)) {
I_CmsReport report = new CmsShellReport(m_cms.getRequestContext().getLocale());
Set<String> utdModules = new HashSet<String>(getUptodateModules());
for (String moduleToRemove : getModulesToDelete()) {
removeModule(moduleToRemove, report);
}
for (String name : m_installModules) {
if (!utdModules.contains(name)) {
String filename = m_moduleFilenames.get(name);
try {
updateModule(name, filename, report);
} catch (Exception e) {
// log a exception during module import, but make sure the next module is still imported
e.printStackTrace(System.err);
}
} else {
report.println(
Messages.get().container(Messages.RPT_MODULE_UPTODATE_1, name),
I_CmsReport.FORMAT_HEADLINE);
}
}
}
}
/**
* Fills the relations db tables during the update.<p>
*
* @throws Exception if something goes wrong
*/
public void updateRelations() throws Exception {
if (m_detectedVersion > 6) {
// skip if not updating from 6.x
return;
}
I_CmsReport report = new CmsShellReport(m_cms.getRequestContext().getLocale());
report.println(Messages.get().container(Messages.RPT_START_UPDATE_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE);
String storedSite = m_cms.getRequestContext().getSiteRoot();
CmsProject project = null;
try {
String projectName = "Update relations project";
try {
// try to read a (leftover) unlock project
project = m_cms.readProject(projectName);
} catch (CmsException e) {
// create a Project to unlock the resources
project = m_cms.createProject(
projectName,
projectName,
OpenCms.getDefaultUsers().getGroupAdministrators(),
OpenCms.getDefaultUsers().getGroupAdministrators(),
CmsProject.PROJECT_TYPE_TEMPORARY);
}
m_cms.getRequestContext().setSiteRoot(""); // change to the root site
m_cms.getRequestContext().setCurrentProject(project);
List<I_CmsResourceType> types = OpenCms.getResourceManager().getResourceTypes();
int n = types.size();
int m = 0;
Iterator<I_CmsResourceType> itTypes = types.iterator();
while (itTypes.hasNext()) {
I_CmsResourceType type = itTypes.next();
m++;
report.print(
org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_SUCCESSION_2,
String.valueOf(m),
String.valueOf(n)),
I_CmsReport.FORMAT_NOTE);
report.print(org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_ARGUMENT_1,
type.getTypeName()));
report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));
if (type instanceof I_CmsLinkParseable) {
try {
CmsXmlContentRepairSettings settings = new CmsXmlContentRepairSettings(m_cms);
settings.setIncludeSubFolders(true);
settings.setVfsFolder("/");
settings.setForce(true);
settings.setResourceType(type.getTypeName());
CmsXmlContentRepairThread t = new CmsXmlContentRepairThread(m_cms, settings);
t.start();
synchronized (this) {
t.join();
}
report.println(
org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
I_CmsReport.FORMAT_OK);
} catch (Exception e) {
report.println(
org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ERROR_0),
I_CmsReport.FORMAT_ERROR);
report.addError(e);
// log the error
e.printStackTrace(System.err);
}
} else {
report.println(
org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SKIPPED_0),
I_CmsReport.FORMAT_WARNING);
}
}
} finally {
try {
if (project != null) {
try {
m_cms.unlockProject(project.getUuid()); // unlock everything
OpenCms.getPublishManager().publishProject(
m_cms,
report,
OpenCms.getPublishManager().getPublishList(m_cms));
OpenCms.getPublishManager().waitWhileRunning();
} finally {
m_cms.getRequestContext().setCurrentProject(m_cms.readProject(CmsProject.ONLINE_PROJECT_ID));
}
}
} finally {
m_cms.getRequestContext().setSiteRoot(storedSite);
}
report.println(
Messages.get().container(Messages.RPT_FINISH_UPDATE_RELATIONS_0),
I_CmsReport.FORMAT_HEADLINE);
}
}
/**
* Returns the admin Group.<p>
*
* @return the admin Group
*/
protected String getAdminGroup() {
return m_adminGroup;
}
/**
* Computes a list of modules which need to be removed before updating the other modules, e.g. because of resource type
* conflicts.<p>
*
* @return the list of names of modules which need to be removed
*/
protected List<String> getModulesToDelete() {
List<String> result = new ArrayList<String>();
if (m_installModules.contains("org.opencms.ade.config")) {
// some resource types have been moved from org.opencms.ade.containerpage an org.opencms.ade.sitemap
// to org.opencms.ade.config in 8.0.3, so we need to remove the former modules to avoid a resource
// type conflict.
CmsModule containerpageModule = OpenCms.getModuleManager().getModule("org.opencms.ade.containerpage");
if (containerpageModule != null) {
String version = containerpageModule.getVersion().toString();
if ("8.0.0".equals(version)
|| "8.0.1".equals(version)
|| "8.0.2".equals(version)
|| "8.0.3".equals(version)) {
result.add("org.opencms.ade.containerpage");
result.add("org.opencms.ade.sitemap");
}
}
}
return result;
}
/**
* Removes a module.<p>
*
* @param moduleName the name of the module to remove
* @param report the report to write to
*
* @throws CmsException
*/
protected void removeModule(String moduleName, I_CmsReport report) throws CmsException {
if (OpenCms.getModuleManager().getModule(moduleName) != null) {
OpenCms.getModuleManager().deleteModule(m_cms, moduleName, true, report);
}
}
/**
* Sets the admin Group.<p>
*
* @param adminGroup the admin Group to set
*/
protected void setAdminGroup(String adminGroup) {
m_adminGroup = adminGroup;
}
/**
* Imports a module (zipfile) from the default module directory,
* creating a temporary project for this.<p>
*
* @param moduleName the name of the module to replace
* @param importFile the name of the import .zip file located in the update module directory
* @param report the shell report to write the output
*
* @throws Exception if something goes wrong
*
* @see org.opencms.importexport.CmsImportExportManager#importData(org.opencms.file.CmsObject, I_CmsReport, org.opencms.importexport.CmsImportParameters)
*/
protected void updateModule(String moduleName, String importFile, I_CmsReport report) throws Exception {
String fileName = getModuleFolder() + importFile;
report.println(
Messages.get().container(Messages.RPT_BEGIN_UPDATE_MODULE_1, moduleName),
I_CmsReport.FORMAT_HEADLINE);
removeModule(moduleName, report);
OpenCms.getPublishManager().stopPublishing();
OpenCms.getPublishManager().startPublishing();
OpenCms.getPublishManager().waitWhileRunning();
OpenCms.getImportExportManager().importData(m_cms, report, new CmsImportParameters(fileName, "/", true));
report.println(
Messages.get().container(Messages.RPT_END_UPDATE_MODULE_1, moduleName),
I_CmsReport.FORMAT_HEADLINE);
OpenCms.getPublishManager().stopPublishing();
OpenCms.getPublishManager().startPublishing();
OpenCms.getPublishManager().waitWhileRunning();
}
/**
* Gets the database package name part.<p>
*
* @param dbName the db name from the opencms.properties file
*
* @return the db package name part
*/
private String getDbPackage(String dbName) {
if (dbName.contains("mysql")) {
return "mysql";
} else if (dbName.contains("oracle")) {
return "oracle";
} else {
return dbName;
}
}
}
|
package bolts;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Represents the result of an asynchronous operation.
*
* @param <TResult> The type of the result of the task.
*/
public class Task<TResult> {
/**
* An {@link java.util.concurrent.Executor} that executes tasks in parallel.
*/
public static final Executor BACKGROUND_EXECUTOR = BoltsExecutors.background();
/**
* An {@link java.util.concurrent.Executor} that executes tasks in the current thread unless
* the stack runs too deep, at which point it will delegate to {@link Task#BACKGROUND_EXECUTOR} in
* order to trim the stack.
*/
private static final Executor IMMEDIATE_EXECUTOR = BoltsExecutors.immediate();
/**
* An {@link java.util.concurrent.Executor} that executes tasks on the UI thread.
*/
public static final Executor UI_THREAD_EXECUTOR = AndroidExecutors.uiThread();
private final Object lock = new Object();
private boolean complete;
private boolean cancelled;
private TResult result;
private Exception error;
private List<Continuation<TResult, Void>> continuations;
private Task() {
continuations = new ArrayList<Continuation<TResult, Void>>();
}
/**
* Creates a TaskCompletionSource that orchestrates a Task. This allows the creator of a task to
* be solely responsible for its completion.
*
* @return A new TaskCompletionSource.
*/
public static <TResult> TaskCompletionSource<TResult> create() {
return new TaskCompletionSource(new Task<TResult>());
}
/**
* @return {@code true} if the task completed (has a result, an error, or was cancelled.
* {@code false} otherwise.
*/
public boolean isCompleted() {
synchronized (lock) {
return complete;
}
}
/**
* @return {@code true} if the task was cancelled, {@code false} otherwise.
*/
public boolean isCancelled() {
synchronized (lock) {
return cancelled;
}
}
/**
* @return {@code true} if the task has an error, {@code false} otherwise.
*/
public boolean isFaulted() {
synchronized (lock) {
return error != null;
}
}
/**
* @return The result of the task, if set. {@code null} otherwise.
*/
public TResult getResult() {
synchronized (lock) {
return result;
}
}
/**
* @return The error for the task, if set. {@code null} otherwise.
*/
public Exception getError() {
synchronized (lock) {
return error;
}
}
/**
* Blocks until the task is complete.
*/
public void waitForCompletion() throws InterruptedException {
synchronized (lock) {
if (!isCompleted()) {
lock.wait();
}
}
}
/**
* Creates a completed task with the given value.
*/
public static <TResult> Task<TResult> forResult(TResult value) {
TaskCompletionSource<TResult> tcs = Task.create();
tcs.setResult(value);
return tcs.getTask();
}
/**
* Creates a faulted task with the given error.
*/
public static <TResult> Task<TResult> forError(Exception error) {
TaskCompletionSource<TResult> tcs = Task.create();
tcs.setError(error);
return tcs.getTask();
}
/**
* Creates a cancelled task.
*/
public static <TResult> Task<TResult> cancelled() {
TaskCompletionSource<TResult> tcs = Task.create();
tcs.setCancelled();
return tcs.getTask();
}
/**
* Makes a fluent cast of a Task's result possible, avoiding an extra continuation just to cast
* the type of the result.
*/
public <TOut> Task<TOut> cast() {
@SuppressWarnings("unchecked") Task<TOut> task = (Task<TOut>) this;
return task;
}
/**
* Turns a {@code Task<T>} into a {@code Task<Void>}, dropping any result.
*/
public Task<Void> makeVoid() {
return this.continueWithTask(new Continuation<TResult, Task<Void>>() {
@Override
public Task<Void> then(Task<TResult> task) throws Exception {
if (task.isCancelled()) {
return Task.cancelled();
}
if (task.isFaulted()) {
return Task.forError(task.getError());
}
return Task.forResult(null);
}
});
}
/**
* Invokes the callable on a background thread, returning a Task to represent the operation.
*/
public static <TResult> Task<TResult> callInBackground(Callable<TResult> callable) {
return call(callable, BACKGROUND_EXECUTOR);
}
/**
* Invokes the callable using the given executor, returning a Task to represent the operation.
*/
public static <TResult> Task<TResult> call(final Callable<TResult> callable, Executor executor) {
final TaskCompletionSource<TResult> tcs = Task.create();
executor.execute(new Runnable() {
@Override
public void run() {
try {
tcs.setResult(callable.call());
} catch (Exception e) {
tcs.setError(e);
}
}
});
return tcs.getTask();
}
/**
* Invokes the callable on the current thread, producing a Task.
*/
public static <TResult> Task<TResult> call(final Callable<TResult> callable) {
return call(callable, IMMEDIATE_EXECUTOR);
}
/**
* Creates a task that completes when all of the provided tasks are complete.
*
* @param tasks The tasks that the return value will wait for before completing.
* @return A Task that will resolve to {@code Void} when all the tasks are resolved. If a single
* task fails, it will resolve to that {@link java.lang.Exception}. If multiple tasks fail, it
* will resolve to an {@link AggregateException} of all the {@link java.lang.Exception}s.
*/
public static Task<Void> whenAll(Collection<? extends Task<?>> tasks) {
if (tasks.size() == 0) {
return Task.forResult(null);
}
final TaskCompletionSource<Void> allFinished = Task.create();
final ArrayList<Exception> causes = new ArrayList<Exception>();
final Object errorLock = new Object();
final AtomicInteger count = new AtomicInteger(tasks.size());
final AtomicBoolean isCancelled = new AtomicBoolean(false);
for (Task<?> task : tasks) {
@SuppressWarnings("unchecked") Task<Object> t = (Task<Object>) task;
t.continueWith(new Continuation<Object, Void>() {
@Override
public Void then(Task<Object> task) {
if (task.isFaulted()) {
synchronized (errorLock) {
causes.add(task.getError());
}
}
if (task.isCancelled()) {
isCancelled.set(true);
}
if (count.decrementAndGet() == 0) {
if (causes.size() != 0) {
if (causes.size() == 1) {
allFinished.setError(causes.get(0));
} else {
Throwable[] throwables = causes.toArray(new Throwable[causes.size()]);
Exception error = new AggregateException(String.format("There were %d exceptions.", causes.size()),
throwables);
allFinished.setError(error);
}
} else if (isCancelled.get()) {
allFinished.setCancelled();
} else {
allFinished.setResult(null);
}
}
return null;
}
});
}
return allFinished.getTask();
}
/**
* Continues a task with the equivalent of a Task-based while loop, where the body of the loop is
* a task continuation.
*/
public Task<Void> continueWhile(Callable<Boolean> predicate, Continuation<Void, Task<Void>> continuation) {
return continueWhile(predicate, continuation, IMMEDIATE_EXECUTOR);
}
/**
* Continues a task with the equivalent of a Task-based while loop, where the body of the loop is
* a task continuation.
*/
public Task<Void> continueWhile(final Callable<Boolean> predicate, final Continuation<Void, Task<Void>> continuation, final Executor executor) {
final Capture<Continuation<Void, Task<Void>>> predicateContinuation = new Capture<Continuation<Void, Task<Void>>>();
predicateContinuation.set(new Continuation<Void, Task<Void>>() {
@Override
public Task<Void> then(Task<Void> task) throws Exception {
if (predicate.call()) {
return Task.<Void>forResult(null).onSuccessTask(continuation, executor).onSuccessTask(predicateContinuation.get(),
executor);
}
return Task.forResult(null);
}
});
return makeVoid().continueWithTask(predicateContinuation.get(), executor);
}
/**
* Adds a continuation that will be scheduled using the executor, returning a new task that
* completes after the continuation has finished running. This allows the continuation to be
* scheduled on different thread.
*/
public <TContinuationResult> Task<TContinuationResult> continueWith(final Continuation<TResult, TContinuationResult> continuation, final Executor executor) {
boolean completed;
final TaskCompletionSource<TContinuationResult> tcs = Task.create();
synchronized (lock) {
completed = this.isCompleted();
if (!completed) {
this.continuations.add(new Continuation<TResult, Void>() {
@Override
public Void then(Task<TResult> task) {
completeImmediately(tcs, continuation, task, executor);
return null;
}
});
}
}
if (completed) {
completeImmediately(tcs, continuation, this, executor);
}
return tcs.getTask();
}
/**
* Adds a synchronous continuation to this task, returning a new task that completes after the
* continuation has finished running.
*/
public <TContinuationResult> Task<TContinuationResult> continueWith(Continuation<TResult, TContinuationResult> continuation) {
return continueWith(continuation, IMMEDIATE_EXECUTOR);
}
/**
* Adds an Task-based continuation to this task that will be scheduled using the executor,
* returning a new task that completes after the task returned by the continuation has completed.
*/
public <TContinuationResult> Task<TContinuationResult> continueWithTask(final Continuation<TResult, Task<TContinuationResult>> continuation, final Executor executor) {
boolean completed;
final TaskCompletionSource<TContinuationResult> tcs = Task.create();
synchronized (lock) {
completed = this.isCompleted();
if (!completed) {
this.continuations.add(new Continuation<TResult, Void>() {
@Override
public Void then(Task<TResult> task) {
completeAfterTask(tcs, continuation, task, executor);
return null;
}
});
}
}
if (completed) {
completeAfterTask(tcs, continuation, this, executor);
}
return tcs.getTask();
}
/**
* Adds an asynchronous continuation to this task, returning a new task that completes after the
* task returned by the continuation has completed.
*/
public <TContinuationResult> Task<TContinuationResult> continueWithTask(Continuation<TResult, Task<TContinuationResult>> continuation) {
return continueWithTask(continuation, IMMEDIATE_EXECUTOR);
}
/**
* Runs a continuation when a task completes successfully, forwarding along
* {@link java.lang.Exception} or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccess(final Continuation<TResult, TContinuationResult> continuation, Executor executor) {
return continueWithTask(new Continuation<TResult, Task<TContinuationResult>>() {
@Override
public Task<TContinuationResult> then(Task<TResult> task) {
if (task.isFaulted()) {
return Task.forError(task.getError());
} else if (task.isCancelled()) {
return Task.cancelled();
} else {
return task.continueWith(continuation);
}
}
}, executor);
}
/**
* Runs a continuation when a task completes successfully, forwarding along
* {@link java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccess(final Continuation<TResult, TContinuationResult> continuation) {
return onSuccess(continuation, IMMEDIATE_EXECUTOR);
}
/**
* Runs a continuation when a task completes successfully, forwarding along
* {@link java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(final Continuation<TResult, Task<TContinuationResult>> continuation, Executor executor) {
return continueWithTask(new Continuation<TResult, Task<TContinuationResult>>() {
@Override
public Task<TContinuationResult> then(Task<TResult> task) {
if (task.isFaulted()) {
return Task.forError(task.getError());
} else if (task.isCancelled()) {
return Task.cancelled();
} else {
return task.continueWithTask(continuation);
}
}
}, executor);
}
/**
* Runs a continuation when a task completes successfully, forwarding along
* {@link java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(final Continuation<TResult, Task<TContinuationResult>> continuation) {
return onSuccessTask(continuation, IMMEDIATE_EXECUTOR);
}
/**
* Handles the non-async (i.e. the continuation doesn't return a Task) continuation case, passing
* the results of the given Task through to the given continuation and using the results of that
* call to set the result of the TaskContinuationSource.
*
* @param tcs The TaskContinuationSource that will be orchestrated by this call.
* @param continuation The non-async continuation.
* @param task The task being completed.
* @param executor The executor to use when running the continuation (allowing the continuation to be
* scheduled on a different thread).
*/
private static <TContinuationResult, TResult> void completeImmediately(final TaskCompletionSource<TContinuationResult> tcs, final Continuation<TResult, TContinuationResult> continuation, final Task<TResult> task, Executor executor) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
TContinuationResult result = continuation.then(task);
tcs.setResult(result);
} catch (Exception e) {
tcs.setError(e);
}
}
});
}
/**
* Handles the async (i.e. the continuation does return a Task) continuation case, passing the
* results of the given Task through to the given continuation to get a new Task. The
* TaskCompletionSource's results are only set when the new Task has completed, unwrapping the
* results of the task returned by the continuation.
*
* @param tcs The TaskContinuationSource that will be orchestrated by this call.
* @param continuation The async continuation.
* @param task The task being completed.
* @param executor The executor to use when running the continuation (allowing the continuation to be
* scheduled on a different thread).
*/
private static <TContinuationResult, TResult> void completeAfterTask(final TaskCompletionSource<TContinuationResult> tcs, final Continuation<TResult, Task<TContinuationResult>> continuation, final Task<TResult> task, final Executor executor) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
Task<TContinuationResult> result = continuation.then(task);
if (result == null) {
tcs.setResult(null);
} else {
result.continueWith(new Continuation<TContinuationResult, Void>() {
@Override
public Void then(Task<TContinuationResult> task) {
if (task.isCancelled()) {
tcs.setCancelled();
} else if (task.isFaulted()) {
tcs.setError(task.getError());
} else {
tcs.setResult(task.getResult());
}
return null;
}
});
}
} catch (Exception e) {
tcs.setError(e);
}
}
});
}
private void runContinuations() {
synchronized (lock) {
for (Continuation<TResult, ?> continuation : continuations) {
try {
continuation.then(this);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
continuations = null;
}
}
/**
* Allows safe orchestration of a task's completion, preventing the consumer from prematurely
* completing the task. Essentially, it represents the producer side of a {@link Task}, providing
* access to the consumer side through the getTask() method while isolating the Task's completion
* mechanisms from the consumer.
*/
public static class TaskCompletionSource<TResult> {
private final Task<TResult> task;
private TaskCompletionSource(Task<TResult> task) {
this.task = task;
}
/**
* @return the Task associated with this TaskCompletionSource.
*/
public Task<TResult> getTask() {
return task;
}
/**
* Sets the cancelled flag on the Task if the Task hasn't already been completed.
*/
public boolean trySetCancelled() {
synchronized (task.lock) {
if (task.complete) {
return false;
}
task.complete = true;
task.cancelled = true;
task.lock.notifyAll();
task.runContinuations();
return true;
}
}
/**
* Sets the result on the Task if the Task hasn't already been completed.
*/
public boolean trySetResult(TResult result) {
synchronized (task.lock) {
if (task.complete) {
return false;
}
task.complete = true;
task.result = result;
task.lock.notifyAll();
task.runContinuations();
return true;
}
}
/**
* Sets the error on the Task if the Task hasn't already been completed.
*/
public boolean trySetError(Exception error) {
synchronized (task.lock) {
if (task.complete) {
return false;
}
task.complete = true;
task.error = error;
task.lock.notifyAll();
task.runContinuations();
return true;
}
}
/**
* Sets the cancelled flag on the task, throwing if the Task has already been completed.
*/
public void setCancelled() {
if (!trySetCancelled()) {
throw new IllegalStateException("Cannot cancel a completed task.");
}
}
/**
* Sets the result of the Task, throwing if the Task has already been completed.
*/
public void setResult(TResult result) {
if (!trySetResult(result)) {
throw new IllegalStateException("Cannot set the result of a completed task.");
}
}
/**
* Sets the error of the Task, throwing if the Task has already been completed.
*/
public void setError(Exception error) {
if (!trySetError(error)) {
throw new IllegalStateException("Cannot set the error on a completed task.");
}
}
}
}
|
package org.pentaho.di.ui.spoon;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.ObjectRevision;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.RepositoryObjectType;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.step.StepStatus;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TreeMemory;
import org.pentaho.di.ui.core.widget.TreeUtil;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.www.SlaveServerJobStatus;
import org.pentaho.di.www.SlaveServerStatus;
import org.pentaho.di.www.SlaveServerTransStatus;
import org.pentaho.di.www.SniffStepServlet;
import org.pentaho.di.www.WebResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* SpoonSlave handles the display of the slave server information in a Spoon tab.
*
* @see org.pentaho.di.spoon.Spoon
* @author Matt
* @since 12 nov 2006
*/
public class SpoonSlave extends Composite implements TabItemInterface {
private static Class<?> PKG = Spoon.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
public static final long UPDATE_TIME_VIEW = 30000L; // 30s
public static final String STRING_SLAVE_LOG_TREE_NAME = "SLAVE_LOG : ";
private Shell shell;
private Display display;
private SlaveServer slaveServer;
private Map<String, Integer> lastLineMap;
private Map<String, String> loggingMap;
private Spoon spoon;
private ColumnInfo[] colinf;
private Tree wTree;
private Text wText;
private Button wError;
private Button wStart;
private Button wPause;
private Button wStop;
private Button wRemove;
private Button wSniff;
private Button wRefresh;
private FormData fdTree, fdText, fdSash;
private boolean refreshBusy;
private SlaveServerStatus slaveServerStatus;
private Timer timer;
private TimerTask timerTask;
private TreeItem transParentItem;
private TreeItem jobParentItem;
private LogChannelInterface log;
private class TreeEntry {
String itemType; // Transformation or Job
String name;
String status;
String id;
int length;
public TreeEntry(TreeItem treeItem) {
String[] path = ConstUI.getTreeStrings(treeItem);
this.length = path.length;
if (path.length > 0) {
itemType = path[0];
}
if (path.length > 1) {
name = path[1];
}
if (path.length == 3) {
treeItem = treeItem.getParentItem();
}
status = treeItem.getText(9);
id = treeItem.getText(13);
}
boolean isTransformation() {
return itemType.equals(transParentItem.getText());
}
boolean isJob() {
return itemType.equals(jobParentItem.getText());
}
boolean isRunning() {
return Trans.STRING_RUNNING.equals(status);
}
boolean isStopped() {
return Trans.STRING_STOPPED.equals(status);
}
boolean isFinished() {
return Trans.STRING_FINISHED.equals(status);
}
boolean isPaused() {
return Trans.STRING_PAUSED.equals(status);
}
boolean isWaiting() {
return Trans.STRING_WAITING.equals(status);
}
}
public SpoonSlave(Composite parent, int style, final Spoon spoon, SlaveServer slaveServer) {
super(parent, style);
this.shell = parent.getShell();
this.display = shell.getDisplay();
this.spoon = spoon;
this.slaveServer = slaveServer;
this.log = spoon.getLog();
lastLineMap = new HashMap<String, Integer>();
loggingMap = new HashMap<String, String>();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
setLayout(formLayout);
setVisible(true);
spoon.props.setLook(this);
SashForm sash = new SashForm(this, SWT.VERTICAL);
sash.setLayout(new FillLayout());
colinf = new ColumnInfo[] { new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Stepname"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Copynr"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Read"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Written"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Input"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Output"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Updated"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Rejected"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Errors"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Active"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Time"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.Speed"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.PriorityBufferSizes"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SpoonSlave.Column.CarteObjectId"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
};
colinf[1].setAllignement(SWT.RIGHT);
colinf[2].setAllignement(SWT.RIGHT);
colinf[3].setAllignement(SWT.RIGHT);
colinf[4].setAllignement(SWT.RIGHT);
colinf[5].setAllignement(SWT.RIGHT);
colinf[6].setAllignement(SWT.RIGHT);
colinf[7].setAllignement(SWT.RIGHT);
colinf[8].setAllignement(SWT.RIGHT);
colinf[9].setAllignement(SWT.RIGHT);
colinf[10].setAllignement(SWT.RIGHT);
colinf[11].setAllignement(SWT.RIGHT);
colinf[12].setAllignement(SWT.RIGHT);
wTree = new Tree(sash, SWT.SINGLE | SWT.V_SCROLL | SWT.H_SCROLL);
wTree.setHeaderVisible(true);
TreeMemory.addTreeListener(wTree, STRING_SLAVE_LOG_TREE_NAME + slaveServer.toString());
Rectangle bounds = spoon.tabfolder.getSwtTabset().getBounds();
for (int i = 0; i < colinf.length; i++) {
ColumnInfo columnInfo = colinf[i];
TreeColumn treeColumn = new TreeColumn(wTree, columnInfo.getAllignement());
treeColumn.setText(columnInfo.getName());
treeColumn.setWidth(bounds.width / colinf.length);
}
transParentItem = new TreeItem(wTree, SWT.NONE);
transParentItem.setText(Spoon.STRING_TRANSFORMATIONS);
transParentItem.setImage(GUIResource.getInstance().getImageTransGraph());
jobParentItem = new TreeItem(wTree, SWT.NONE);
jobParentItem.setText(Spoon.STRING_JOBS);
jobParentItem.setImage(GUIResource.getInstance().getImageJobGraph());
wTree.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
enableButtons();
treeItemSelected((TreeItem) event.item);
((TreeItem) event.item).setExpanded(true);
showLog();
}
});
wTree.addTreeListener(new TreeListener() {
public void treeExpanded(TreeEvent event) {
treeItemSelected((TreeItem) event.item);
showLog();
}
public void treeCollapsed(TreeEvent arg0) {
}
});
wText = new Text(sash, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY | SWT.BORDER);
spoon.props.setLook(wText);
wText.setVisible(true);
wRefresh = new Button(this, SWT.PUSH);
wRefresh.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.Refresh"));
wRefresh.setEnabled(true);
wRefresh.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
refreshViewAndLog();
}
});
wError = new Button(this, SWT.PUSH);
wError.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.ShowErrorLines")); //$NON-NLS-1$
wError.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showErrors();
}
});
wSniff = new Button(this, SWT.PUSH);
wSniff.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.Sniff"));
wSniff.setEnabled(false);
wSniff.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
sniff();
}
});
wStart = new Button(this, SWT.PUSH);
wStart.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.Start"));
wStart.setEnabled(false);
wStart.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
start();
}
});
wPause = new Button(this, SWT.PUSH);
wPause.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.Pause"));
wPause.setEnabled(false);
wPause.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
pause();
}
});
wStop = new Button(this, SWT.PUSH);
wStop.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.Stop"));
wStop.setEnabled(false);
wStop.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
stop();
}
});
wRemove = new Button(this, SWT.PUSH);
wRemove.setText(BaseMessages.getString(PKG, "SpoonSlave.Button.Remove"));
wRemove.setEnabled(false);
wRemove.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
remove();
}
});
BaseStepDialog.positionBottomButtons(this, new Button[] { wRefresh, wSniff, wStart, wPause, wStop, wRemove, wError }, Const.MARGIN, null);
// Put tree on top
fdTree = new FormData();
fdTree.left = new FormAttachment(0, 0);
fdTree.top = new FormAttachment(0, 0);
fdTree.right = new FormAttachment(100, 0);
fdTree.bottom = new FormAttachment(100, 0);
wTree.setLayoutData(fdTree);
// Put text in the middle
fdText = new FormData();
fdText.left = new FormAttachment(0, 0);
fdText.top = new FormAttachment(0, 0);
fdText.right = new FormAttachment(100, 0);
fdText.bottom = new FormAttachment(100, 0);
wText.setLayoutData(fdText);
fdSash = new FormData();
fdSash.left = new FormAttachment(0, 0); // First one in the left top corner
fdSash.top = new FormAttachment(0, 0);
fdSash.right = new FormAttachment(100, 0);
fdSash.bottom = new FormAttachment(wRefresh, -5);
sash.setLayoutData(fdSash);
pack();
timer = new Timer("SpoonSlave: " + getMeta().getName());
timerTask = new TimerTask() {
public void run() {
if (display != null && !display.isDisposed()) {
display.asyncExec(new Runnable() {
public void run() {
refreshViewAndLog();
}
});
}
}
};
timer.schedule(timerTask, 0L, UPDATE_TIME_VIEW); // schedule to repeat a couple of times per second to get fast feedback
addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
timer.cancel();
}
});
}
public void treeItemSelected(TreeItem item) {
// load node upon expansion
if (item.getData("transStatus") != null) {
SlaveServerTransStatus transStatus = (SlaveServerTransStatus) item.getData("transStatus");
try {
log.logDetailed("Getting transformation status for [{0}] on server [{1}]", transStatus.getTransName(), SpoonSlave.this.slaveServer);
Integer lastLine = lastLineMap.get(transStatus.getId());
int lastLineNr = lastLine == null ? 0 : lastLine.intValue();
SlaveServerTransStatus ts = SpoonSlave.this.slaveServer.getTransStatus(transStatus.getTransName(), transStatus.getId(), lastLineNr);
log.logDetailed("Finished receiving transformation status for [{0}] from server [{1}]", transStatus.getTransName(), SpoonSlave.this.slaveServer);
List<StepStatus> stepStatusList = ts.getStepStatusList();
transStatus.setStepStatusList(stepStatusList);
lastLineMap.put(transStatus.getId(), ts.getLastLoggingLineNr());
String logging = loggingMap.get(transStatus.getId());
if (logging == null) {
logging = ts.getLoggingString();
} else {
logging = new StringBuffer(logging).append(ts.getLoggingString()).toString();
}
loggingMap.put(transStatus.getId(), logging);
item.removeAll();
for (int s = 0; s < stepStatusList.size(); s++) {
StepStatus stepStatus = stepStatusList.get(s);
TreeItem stepItem = new TreeItem(item, SWT.NONE);
stepItem.setText(stepStatus.getSpoonSlaveLogFields());
}
} catch (Exception e) {
transStatus.setErrorDescription("Unable to access transformation details : " + Const.CR + Const.getStackTracker(e));
}
} else if (item.getData("jobStatus") != null) {
SlaveServerJobStatus jobStatus = (SlaveServerJobStatus) item.getData("jobStatus");
try {
log.logDetailed("Getting job status for [{0}] on server [{1}]", jobStatus.getJobName(), slaveServer);
Integer lastLine = lastLineMap.get(jobStatus.getId());
int lastLineNr = lastLine == null ? 0 : lastLine.intValue();
SlaveServerJobStatus ts = slaveServer.getJobStatus(jobStatus.getJobName(), jobStatus.getId(), lastLineNr);
log.logDetailed("Finished receiving job status for [{0}] from server [{1}]", jobStatus.getJobName(), slaveServer);
lastLineMap.put(jobStatus.getId(), ts.getLastLoggingLineNr());
String logging = loggingMap.get(jobStatus.getId());
if (logging == null) {
logging = ts.getLoggingString();
} else {
logging = new StringBuffer(logging).append(ts.getLoggingString()).toString();
}
loggingMap.put(jobStatus.getId(), logging);
Result result = ts.getResult();
if (result != null) {
item.setText(2, "" + result.getNrLinesRead());
item.setText(3, "" + result.getNrLinesWritten());
item.setText(4, "" + result.getNrLinesInput());
item.setText(5, "" + result.getNrLinesOutput());
item.setText(6, "" + result.getNrLinesUpdated());
item.setText(7, "" + result.getNrLinesRejected());
item.setText(8, "" + result.getNrErrors());
}
} catch (Exception e) {
jobStatus.setErrorDescription("Unable to access transformation details : " + Const.CR + Const.getStackTracker(e));
}
}
}
protected void enableButtons() {
TreeEntry treeEntry = getTreeEntry();
boolean isTrans = treeEntry != null && treeEntry.isTransformation();
boolean isJob = treeEntry != null && treeEntry.isJob();
boolean hasId = treeEntry != null && !Const.isEmpty(treeEntry.id);
boolean isRunning = treeEntry != null && treeEntry.isRunning();
boolean isStopped = treeEntry != null && treeEntry.isStopped();
boolean isFinished = treeEntry != null && treeEntry.isFinished();
boolean isPaused = treeEntry != null && treeEntry.isPaused();
boolean isWaiting = treeEntry != null && treeEntry.isWaiting();
boolean isStep = treeEntry != null && treeEntry.length == 3;
wStart.setEnabled((isTrans || isJob) && hasId && !isRunning && (isFinished || isStopped || isWaiting));
wPause.setEnabled(isTrans && hasId && (isRunning || isPaused));
wStop.setEnabled((isTrans || isJob) && hasId && (isRunning || isPaused));
wRemove.setEnabled((isTrans || isJob) && hasId && (isFinished || isStopped || isWaiting));
wSniff.setEnabled(isTrans && hasId && isRunning && isStep);
}
protected void refreshViewAndLog() {
String[] selectionPath = null;
if (wTree.getSelectionCount() == 1) {
selectionPath = ConstUI.getTreeStrings(wTree.getSelection()[0]);
}
refreshView();
if (selectionPath != null) // Select the same one again
{
TreeItem treeItem = TreeUtil.findTreeItem(wTree, selectionPath);
if (treeItem != null) {
wTree.setSelection(treeItem);
wTree.showItem(treeItem);
treeItemSelected(treeItem);
treeItem.setExpanded(true);
}
}
showLog();
}
public boolean canBeClosed() {
// It's OK to close this at any time.
// We just have to make sure we stop the timers etc.
spoon.tabfolder.setSelected(0);
return true;
}
/**
* Someone clicks on a line: show the log or error message associated with that in the text-box
*/
public void showLog() {
TreeEntry treeEntry = getTreeEntry();
if (treeEntry == null)
return;
if (treeEntry.length <= 1)
return;
if (treeEntry.isTransformation()) {
SlaveServerTransStatus transStatus = slaveServerStatus.findTransStatus(treeEntry.name, treeEntry.id);
StringBuffer message = new StringBuffer();
String errorDescription = transStatus.getErrorDescription();
if (!Const.isEmpty(errorDescription)) {
message.append(errorDescription).append(Const.CR).append(Const.CR);
}
String logging = loggingMap.get(transStatus.getId());
if (!Const.isEmpty(logging)) {
message.append(logging).append(Const.CR);
}
wText.setText(message.toString());
wText.setSelection(wText.getText().length());
wText.showSelection();
// wText.setTopIndex(wText.getLineCount());
}
if (treeEntry.isJob()) {
// We clicked on a job line item
SlaveServerJobStatus jobStatus = slaveServerStatus.findJobStatus(treeEntry.name);
StringBuffer message = new StringBuffer();
String errorDescription = jobStatus.getErrorDescription();
if (!Const.isEmpty(errorDescription)) {
message.append(errorDescription).append(Const.CR).append(Const.CR);
}
String logging = loggingMap.get(jobStatus.getId());
if (!Const.isEmpty(logging)) {
message.append(logging).append(Const.CR);
}
wText.setText(message.toString());
wText.setSelection(wText.getText().length());
wText.showSelection();
}
}
protected void start() {
TreeEntry treeEntry = getTreeEntry();
if (treeEntry == null)
return;
if (treeEntry.isTransformation()) {
SlaveServerTransStatus transStatus = slaveServerStatus.findTransStatus(treeEntry.name, treeEntry.id);
if (transStatus != null) {
if (!transStatus.isRunning()) {
try {
WebResult webResult = slaveServer.startTransformation(treeEntry.name, transStatus.getId());
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
EnterTextDialog dialog = new EnterTextDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStartingTrans.Title"), BaseMessages.getString(
PKG, "SpoonSlave.ErrorStartingTrans.Message"), webResult.getMessage());
dialog.setReadOnly();
dialog.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStartingTrans.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorStartingTrans.Message"), e);
}
}
}
}
if (treeEntry.isJob()) {
SlaveServerJobStatus jobStatus = slaveServerStatus.findJobStatus(treeEntry.name);
if (jobStatus != null) {
if (!jobStatus.isRunning()) {
try {
WebResult webResult = slaveServer.startJob(treeEntry.name, treeEntry.id);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
EnterTextDialog dialog = new EnterTextDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStartingJob.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorStartingJob.Message"), webResult.getMessage());
dialog.setReadOnly();
dialog.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStartingJob.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorStartingJob.Message"), e);
}
}
}
}
}
private TreeEntry getTreeEntry() {
TreeItem ti[] = wTree.getSelection();
if (ti.length == 1) {
TreeEntry treeEntry = new TreeEntry(ti[0]);
if (treeEntry.length <= 1)
return null;
return treeEntry;
} else {
return null;
}
}
protected void stop() {
TreeEntry treeEntry = getTreeEntry();
if (treeEntry == null)
return;
// Transformations
if (treeEntry.isTransformation()) {
SlaveServerTransStatus transStatus = slaveServerStatus.findTransStatus(treeEntry.name, treeEntry.id);
if (transStatus != null) {
if (transStatus.isRunning() || transStatus.isPaused()) {
try {
WebResult webResult = slaveServer.stopTransformation(treeEntry.name, transStatus.getId());
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
EnterTextDialog dialog = new EnterTextDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStoppingTrans.Title"), BaseMessages.getString(
PKG, "SpoonSlave.ErrorStoppingTrans.Message"), webResult.getMessage());
dialog.setReadOnly();
dialog.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStoppingTrans.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorStoppingTrans.Message"), e);
}
}
}
}
// Jobs
if (treeEntry.isJob()) {
SlaveServerJobStatus jobStatus = slaveServerStatus.findJobStatus(treeEntry.name);
if (jobStatus != null) {
if (jobStatus.isRunning()) {
try {
WebResult webResult = slaveServer.stopJob(treeEntry.name, treeEntry.id);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
EnterTextDialog dialog = new EnterTextDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStoppingJob.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorStoppingJob.Message"), webResult.getMessage());
dialog.setReadOnly();
dialog.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorStoppingJob.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorStoppingJob.Message"), e);
}
}
}
}
}
protected void remove() {
TreeEntry treeEntry = getTreeEntry();
if (treeEntry == null)
return;
// Transformations
if (treeEntry.isTransformation()) {
SlaveServerTransStatus transStatus = slaveServerStatus.findTransStatus(treeEntry.name, treeEntry.id);
if (transStatus != null) {
if (!transStatus.isRunning() && !transStatus.isPaused() && !transStatus.isStopped()) {
try {
WebResult webResult = slaveServer.removeTransformation(treeEntry.name, transStatus.getId());
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
EnterTextDialog dialog = new EnterTextDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorRemovingTrans.Title"), BaseMessages.getString(
PKG, "SpoonSlave.ErrorRemovingTrans.Message"), webResult.getMessage());
dialog.setReadOnly();
dialog.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorRemovingTrans.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorRemovingTrans.Message"), e);
}
}
}
}
// TODO: support for jobs
}
protected void pause() {
TreeEntry treeEntry = getTreeEntry();
if (treeEntry == null)
return;
// Transformations
if (treeEntry.isTransformation()) {
try {
WebResult webResult = slaveServer.pauseResumeTransformation(treeEntry.name, treeEntry.id);
if (!webResult.getResult().equalsIgnoreCase(WebResult.STRING_OK)) {
EnterTextDialog dialog = new EnterTextDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorPausingOrResumingTrans.Title"),
BaseMessages.getString(PKG, "SpoonSlave.ErrorPausingOrResumingTrans.Message"), webResult.getMessage());
dialog.setReadOnly();
dialog.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorPausingOrResumingTrans.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorPausingOrResumingTrans.Message"), e);
}
}
}
private synchronized void refreshView() {
if (wTree.isDisposed())
return;
if (refreshBusy)
return;
refreshBusy = true;
log.logDetailed("Refresh");
transParentItem.removeAll();
jobParentItem.removeAll();
// Determine the transformations on the slave servers
try {
slaveServerStatus = slaveServer.getStatus();
} catch (Exception e) {
slaveServerStatus = new SlaveServerStatus("Error contacting server");
slaveServerStatus.setErrorDescription(Const.getStackTracker(e));
wText.setText(slaveServerStatus.getErrorDescription());
}
List<SlaveServerTransStatus> transStatusList = slaveServerStatus.getTransStatusList();
for (int i = 0; i < transStatusList.size(); i++) {
SlaveServerTransStatus transStatus = transStatusList.get(i);
TreeItem transItem = new TreeItem(transParentItem, SWT.NONE);
transItem.setText(0, transStatus.getTransName());
transItem.setText(9, transStatus.getStatusDescription());
transItem.setText(13, Const.NVL(transStatus.getId(), ""));
transItem.setImage(GUIResource.getInstance().getImageTransGraph());
transItem.setData("transStatus", transStatus);
}
for (int i = 0; i < slaveServerStatus.getJobStatusList().size(); i++) {
SlaveServerJobStatus jobStatus = slaveServerStatus.getJobStatusList().get(i);
TreeItem jobItem = new TreeItem(jobParentItem, SWT.NONE);
jobItem.setText(0, jobStatus.getJobName());
jobItem.setText(9, jobStatus.getStatusDescription());
jobItem.setText(13, Const.NVL(jobStatus.getId(), ""));
jobItem.setImage(GUIResource.getInstance().getImageJobGraph());
jobItem.setData("jobStatus", jobStatus);
}
TreeMemory.setExpandedFromMemory(wTree, STRING_SLAVE_LOG_TREE_NAME + slaveServer.toString());
TreeUtil.setOptimalWidthOnColumns(wTree);
refreshBusy = false;
}
public void showErrors() {
String all = wText.getText();
List<String> err = new ArrayList<String>();
int i = 0;
int startpos = 0;
int crlen = Const.CR.length();
while (i < all.length() - crlen) {
if (all.substring(i, i + crlen).equalsIgnoreCase(Const.CR)) {
String line = all.substring(startpos, i);
String uLine = line.toUpperCase();
if (uLine.indexOf(BaseMessages.getString(PKG, "TransLog.System.ERROR")) >= 0 || //$NON-NLS-1$
uLine.indexOf(BaseMessages.getString(PKG, "TransLog.System.EXCEPTION")) >= 0 || //$NON-NLS-1$
uLine.indexOf("ERROR") >= 0 || // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
uLine.indexOf("EXCEPTION") >= 0 // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
) {
err.add(line);
}
// New start of line
startpos = i + crlen;
}
i++;
}
String line = all.substring(startpos);
String uLine = line.toUpperCase();
if (uLine.indexOf(BaseMessages.getString(PKG, "TransLog.System.ERROR2")) >= 0 || //$NON-NLS-1$
uLine.indexOf(BaseMessages.getString(PKG, "TransLog.System.EXCEPTION2")) >= 0 || //$NON-NLS-1$
uLine.indexOf("ERROR") >= 0 || // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
uLine.indexOf("EXCEPTION") >= 0 // i18n for compatibilty to non translated steps a.s.o. //$NON-NLS-1$
) {
err.add(line);
}
if (err.size() > 0) {
String err_lines[] = new String[err.size()];
for (i = 0; i < err_lines.length; i++)
err_lines[i] = err.get(i);
EnterSelectionDialog esd = new EnterSelectionDialog(shell, err_lines,
BaseMessages.getString(PKG, "TransLog.Dialog.ErrorLines.Title"), BaseMessages.getString(PKG, "TransLog.Dialog.ErrorLines.Message")); //$NON-NLS-1$ //$NON-NLS-2$
line = esd.open();
/*
* TODO: we have multiple transformation we can go to: which one should we pick? if (line != null) { for (i = 0; i < spoon.getTransMeta().nrSteps(); i++)
* { StepMeta stepMeta = spoon.getTransMeta().getStep(i); if (line.indexOf(stepMeta.getName()) >= 0) { spoon.editStep(stepMeta.getName()); } } //
* System.out.println("Error line selected: "+line); }
*/
}
}
public String toString() {
return Spoon.APP_NAME;
}
public Object getManagedObject() {
return slaveServer;
}
public boolean hasContentChanged() {
return false;
}
public boolean applyChanges() {
return true;
}
public int showChangedWarning() {
return SWT.YES;
}
public EngineMetaInterface getMeta() {
return new EngineMetaInterface() {
public void setModifiedUser(String user) {
}
public void setModifiedDate(Date date) {
}
public void setInternalKettleVariables() {
}
public void setObjectId(ObjectId id) {
}
public void setFilename(String filename) {
}
public void setCreatedUser(String createduser) {
}
public void setCreatedDate(Date date) {
}
public void saveSharedObjects() {
}
public void nameFromFilename() {
}
public String getXML() {
return null;
}
public boolean canSave() {
return true;
}
public String getName() {
return slaveServer.getName();
}
public String getModifiedUser() {
return null;
}
public Date getModifiedDate() {
return null;
}
public String[] getFilterNames() {
return null;
}
public String[] getFilterExtensions() {
return null;
}
public String getFilename() {
return null;
}
public String getFileType() {
return null;
}
public RepositoryDirectoryInterface getRepositoryDirectory() {
return null;
}
public String getDefaultExtension() {
return null;
}
public String getCreatedUser() {
return null;
}
public Date getCreatedDate() {
return null;
}
public void clearChanged() {
}
public ObjectId getObjectId() {
return null;
}
public RepositoryObjectType getRepositoryElementType() {
return null;
}
public void setName(String name) {
}
public void setRepositoryDirectory(RepositoryDirectoryInterface repositoryDirectory) {
}
public String getDescription() {
return null;
}
public void setDescription(String description) {
}
public ObjectRevision getObjectRevision() {
return null;
}
public void setObjectRevision(ObjectRevision objectRevision) {
}
};
}
public void setControlStates() {
// TODO Auto-generated method stub
}
public boolean canHandleSave() {
return false;
}
protected void sniff() {
TreeItem ti[] = wTree.getSelection();
if (ti.length == 1) {
TreeItem treeItem = ti[0];
String[] path = ConstUI.getTreeStrings(treeItem);
// Make sure we're positioned on a step
if (path.length <= 2) {
return;
}
String name = path[1];
String step = path[2];
String copy = treeItem.getText(1);
EnterNumberDialog numberDialog = new EnterNumberDialog(shell, PropsUI.getInstance().getDefaultPreviewSize(), BaseMessages.getString(PKG,
"SpoonSlave.SniffSizeQuestion.Title"), BaseMessages.getString(PKG, "SpoonSlave.SniffSizeQuestion.Message"));
int lines = numberDialog.open();
if (lines <= 0) {
return;
}
EnterSelectionDialog selectionDialog = new EnterSelectionDialog(shell, new String[] { SniffStepServlet.TYPE_INPUT, SniffStepServlet.TYPE_OUTPUT, },
BaseMessages.getString(PKG, "SpoonSlave.SniffTypeQuestion.Title"), BaseMessages.getString(PKG, "SpoonSlave.SniffTypeQuestion.Message"));
String type = selectionDialog.open(1);
if (type == null) {
return;
}
try {
String xml = slaveServer.sniffStep(name, step, copy, lines, type);
Document doc = XMLHandler.loadXMLString(xml);
Node node = XMLHandler.getSubNode(doc, SniffStepServlet.XML_TAG);
Node metaNode = XMLHandler.getSubNode(node, RowMeta.XML_META_TAG);
RowMetaInterface rowMeta = new RowMeta(metaNode);
int nrRows = Const.toInt(XMLHandler.getTagValue(node, "nr_rows"), 0);
List<Object[]> rowBuffer = new ArrayList<Object[]>();
for (int i = 0; i < nrRows; i++) {
Node dataNode = XMLHandler.getSubNodeByNr(node, RowMeta.XML_DATA_TAG, i);
Object[] row = rowMeta.getRow(dataNode);
rowBuffer.add(row);
}
PreviewRowsDialog prd = new PreviewRowsDialog(shell, new Variables(), SWT.NONE, step, rowMeta, rowBuffer);
prd.open();
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "SpoonSlave.ErrorSniffingStep.Title"), BaseMessages.getString(PKG,
"SpoonSlave.ErrorSniffingStep.Message"), e);
}
}
}
public ChangedWarningInterface getChangedWarning() {
return null;
}
}
|
import java.io.File;
import org.testevol.domain.Version;
public class Test {
//@org.junit.Test
public void test() {
try {
Version version = new Version(new File("/home/leandro/Documents/Atlanta/workspace/testevol-web/testevol-web/tool/tmp/projects/Gson/v.1.0"));
version.setUp(new File("/home/leandro/Documents/Atlanta/workspace/testevol-web/testevol-web/tool/config"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package org.jboss.xnio;
import java.io.Closeable;
import java.io.IOException;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.net.InetSocketAddress;
import org.jboss.xnio.channels.ConnectedStreamChannel;
import org.jboss.xnio.channels.DatagramChannel;
import org.jboss.xnio.channels.StreamChannel;
import org.jboss.xnio.channels.StreamSinkChannel;
import org.jboss.xnio.channels.StreamSourceChannel;
import org.jboss.xnio.channels.TcpChannel;
import org.jboss.xnio.channels.UdpChannel;
import org.jboss.xnio.log.Logger;
import org.jboss.xnio.management.OneWayPipeConnectionMBean;
import org.jboss.xnio.management.PipeConnectionMBean;
import org.jboss.xnio.management.PipeServerMBean;
import org.jboss.xnio.management.PipeSinkServerMBean;
import org.jboss.xnio.management.PipeSourceServerMBean;
import org.jboss.xnio.management.TcpConnectionMBean;
import org.jboss.xnio.management.TcpServerMBean;
import org.jboss.xnio.management.UdpServerMBean;
import javax.management.InstanceNotFoundException;
import javax.management.JMException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.RuntimeOperationsException;
import javax.net.SocketFactory;
import javax.net.ServerSocketFactory;
/**
* The XNIO entry point class.
*
* @apiviz.landmark
*/
public abstract class Xnio implements Closeable {
private static final Logger mlog = Logger.getLogger("org.jboss.xnio.management");
static {
Logger.getLogger("org.jboss.xnio").info("XNIO Version " + Version.VERSION);
}
private static final String NIO_IMPL_PROVIDER = "nio";
private static final String PROVIDER_NAME;
private static final String MANAGEMENT_DOMAIN = "jboss.xnio";
private static final AtomicLong mbeanSequence = new AtomicLong();
private static String AGENTID_PROPNAME = "xnio.agentid";
private static String PROVIDER_PROPNAME = "xnio.provider.name";
private static final PrivilegedAction<String> GET_PROVIDER_ACTION = new GetPropertyAction(PROVIDER_PROPNAME, NIO_IMPL_PROVIDER);
private static final PrivilegedAction<String> GET_AGENTID_ACTION = new GetPropertyAction(AGENTID_PROPNAME, null);
private static final Permission SUBCLASS_PERMISSION = new RuntimePermission("xnioProvider");
static {
String providerClassName = NIO_IMPL_PROVIDER;
try {
providerClassName = AccessController.doPrivileged(GET_PROVIDER_ACTION);
} catch (Throwable t) {
// ignored
}
PROVIDER_NAME = providerClassName;
}
private final List<MBeanServer> mBeanServers = new ArrayList<MBeanServer>();
private final String name;
private final Executor executor;
/**
* Get the default handler executor.
*
* @return the executor
*/
protected Executor getExecutor() {
return executor;
}
/**
* Create an instance of the default XNIO provider. The provider name can be specified through the
* {@code xnio.provider.name} system property. Any failure to create the XNIO provider will cause an {@code java.io.IOException}
* to be thrown.
*
* @return an XNIO instance
* @throws IOException if the XNIO provider could not be created
*/
public static Xnio create() throws IOException {
return create(PROVIDER_NAME, new XnioConfiguration());
}
/**
* Create an instance of the default XNIO provider. The provider name can be specified through the
* {@code xnio.provider.name} system property. Any failure to create the XNIO provider will cause an {@code java.io.IOException}
* to be thrown.
*
* @param configuration the configuration parameters for the implementation
* @return an XNIO instance
* @throws IOException if the XNIO provider could not be created
*/
public static Xnio create(XnioConfiguration configuration) throws IOException {
return create(PROVIDER_NAME, configuration);
}
/**
* Create an instance of the named XNIO provider. Any failure to create the XNIO provider will cause an {@code java.io.IOException}
* to be thrown.
*
* @param implName the name of the implementation
* @param configuration the configuration parameters for the implementation
* @return an XNIO instance
* @throws IOException if the XNIO provider could not be created
*/
public static Xnio create(String implName, XnioConfiguration configuration) throws IOException {
for (XnioProvider xnioProvider : ServiceLoader.load(XnioProvider.class)) {
if (implName.equals(xnioProvider.getName())) {
return xnioProvider.getNewInstance(configuration);
}
}
throw new IOException("No XNIO provider named \"" + implName + "\" could be found");
}
private static final AtomicInteger xnioSequence = new AtomicInteger(1);
/**
* Construct an XNIO provider instance.
*/
protected Xnio(XnioConfiguration configuration) {
if (configuration == null) {
throw new NullPointerException("configuration is null");
}
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SUBCLASS_PERMISSION);
}
final String name = configuration.getName();
final int seq = xnioSequence.getAndIncrement();
this.name = name != null ? name : String.format("%s-%d", getClass().getName(), Integer.valueOf(seq));
final Executor executor = configuration.getExecutor();
this.executor = executor != null ? executor : IoUtils.directExecutor();
// Perform MBeanServer autodetection...
final List<MBeanServer> servers = mBeanServers;
synchronized (servers) {
final List<MBeanServer> confServers = configuration.getMBeanServers();
if (confServers != null) {
for (MBeanServer server : confServers) {
if (server == null) {
throw new NullPointerException("server in MBeanServer configuration list is null");
}
mlog.debug("Registered configured MBeanServer %s", server);
servers.add(server);
}
} else {
final String agentidpropval;
try {
agentidpropval = sm != null ? AccessController.doPrivileged(GET_AGENTID_ACTION) : System.getProperty(AGENTID_PROPNAME);
} catch (SecurityException e) {
// not allowed; leave mbean servers empty
mlog.debug("Unable to read agentid property (%s); JMX features disabled", e);
return;
}
if (agentidpropval == null || agentidpropval.length() == 0) {
final Collection<? extends MBeanServer> fullList;
try {
fullList = sm != null ? AccessController.doPrivileged(new GetMBeanServersAction(null)) : MBeanServerFactory.findMBeanServer(null);
} catch (SecurityException e) {
mlog.debug("Unable to detect installed mbean servers (%s); JMX features disabled", e);
return;
}
for (MBeanServer match : fullList) {
mlog.debug("Registered MBeanServer %s", match);
servers.add(match);
}
} else {
String[] agentids = agentidpropval.split(",");
for (String agentid : agentids) {
String properName = agentid.trim();
if (properName.length() == 0) {
continue;
}
Collection<? extends MBeanServer> matches;
try {
matches = sm != null ? AccessController.doPrivileged(new GetMBeanServersAction(properName)) : MBeanServerFactory.findMBeanServer(null);
} catch (SecurityException e) {
mlog.debug("Unable to locate any MBeanServer for ID \"%s\" (%s); skipping", properName, e);
continue;
}
if (matches == null) {
mlog.debug("Unable to locate any MBeanServer for ID \"%s\" (no matches); skipping", properName);
} else {
for (MBeanServer match : matches) {
mlog.debug("Registered MBeanServer %s for ID \"%s\"", match, properName);
servers.add(match);
}
}
}
}
}
}
}
/**
* Create a managed socket factory which uses this provider's MBean configuration to track management information.
*
* @param optionMap the option map
* @return the managed socket factory
*
* @since 2.0
*/
public SocketFactory createManagedSocketFactory(OptionMap optionMap) {
return new ManagedSocketFactory(this, optionMap);
}
/**
* Create a managed server socket factory which uses this provider's MBean configuration to track management information.
*
* @param optionMap the option map
* @return the managed server socket factory
*
* @since 2.0
*/
public ServerSocketFactory createServerSocketFactory(OptionMap optionMap) {
return new ManagedServerSocketFactory(this, optionMap);
}
/**
* Create an unbound TCP server. The given executor will be used to execute handler methods.
*
* @param executor the executor to use to execute the handlers
* @param openHandler the initial open-connection handler
* @param optionMap the initial configuration for the server
* @return the unbound TCP server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpServer createTcpServer(Executor executor, ChannelListener<? super TcpChannel> openHandler, OptionMap optionMap) {
throw new UnsupportedOperationException("TCP Server");
}
/**
* Create an unbound TCP server. The provider's default executor will be used to execute handler methods.
*
* @param openHandler the initial open-connection handler
* @param optionMap the initial configuration for the server
* @return the unbound TCP server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpServer createTcpServer(ChannelListener<? super TcpChannel> openHandler, OptionMap optionMap) {
return createTcpServer(executor, openHandler, optionMap);
}
/**
* Create a TCP connector. The given executor will be used to execute handler methods.
*
* @param executor the executor to use to execute the handlers
* @param optionMap the initial configuration for the connector
* @return the TCP connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpConnector createTcpConnector(Executor executor, OptionMap optionMap) {
return createTcpConnector(executor, null, optionMap);
}
/**
* Create a TCP connector. The provider's default executor will be used to execute handler methods.
*
* @param optionMap the initial configuration for the connector
* @return the TCP connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpConnector createTcpConnector(OptionMap optionMap) {
return createTcpConnector(executor, optionMap);
}
/**
* Create a TCP connector. The given executor will be used to execute handler methods.
*
* @param executor the executor to use to execute the handlers
* @param src the source address for connections
* @param optionMap the initial configuration for the connector
* @return the TCP connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpConnector createTcpConnector(Executor executor, InetSocketAddress src, OptionMap optionMap) {
throw new UnsupportedOperationException("TCP Connector");
}
/**
* Create a TCP connector. The provider's default executor will be used to execute handler methods.
*
* @param src the source address for connections
* @param optionMap the initial configuration for the connector
* @return the TCP connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpConnector createTcpConnector(InetSocketAddress src, OptionMap optionMap) {
return createTcpConnector(executor, src, optionMap);
}
/**
* Create an unbound UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The given executor will be used to execute handler methods.
*
* @param executor the executor to use to execute the handlers
* @param openHandler the initial open-connection handler
* @param optionMap the initial configuration for the server
*
* @return a factory that can be used to configure the new UDP server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public UdpServer createUdpServer(Executor executor, ChannelListener<? super UdpChannel> openHandler, OptionMap optionMap) {
throw new UnsupportedOperationException("UDP Server");
}
/**
* Create an unbound UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The provider's default executor will be used to execute handler methods.
*
* @param openHandler the initial open-connection handler
* @param optionMap the initial configuration for the server
*
* @return a factory that can be used to configure the new UDP server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public UdpServer createUdpServer(ChannelListener<? super UdpChannel> openHandler, OptionMap optionMap) {
return createUdpServer(executor, openHandler, optionMap);
}
/**
* Create an unbound UDP server. The UDP server can be configured to be multicast-capable; this should only be
* done if multicast is needed, since some providers have a performance penalty associated with multicast.
* The provider's default executor will be used to execute handler methods.
*
* @param optionMap the initial configuration for the server
*
* @return a factory that can be used to configure the new UDP server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public UdpServer createUdpServer(OptionMap optionMap) {
return createUdpServer(executor, IoUtils.nullChannelListener(), optionMap);
}
/**
* Create a pipe "server". The provided handler factory is used to supply handlers for the server "end" of the
* pipe. The returned channel source is used to establish connections to the server.
*
* @param executor the executor to use to execute the handlers
* @param openHandler the initial open-connection handler
*
* @return the client channel source
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public ChannelSource<? extends StreamChannel> createPipeServer(Executor executor, ChannelListener<? super StreamChannel> openHandler) {
throw new UnsupportedOperationException("Pipe Server");
}
/**
* Create a pipe "server". The provided handler factory is used to supply handlers for the server "end" of the
* pipe. The returned channel source is used to establish connections to the server. The provider's default executor will be used to
* execute handler methods.
*
* @param openHandler the initial open-connection handler
*
* @return the client channel source
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public ChannelSource<? extends StreamChannel> createPipeServer(ChannelListener<? super StreamChannel> openHandler) {
return createPipeServer(executor, openHandler);
}
/**
* Create a one-way pipe "server". The provided handler factory is used to supply handlers for the server "end" of
* the pipe. The returned channel source is used to establish connections to the server. The data flows from the
* server to the client.
*
* @param executor the executor to use to execute the handlers
* @param openHandler the initial open-connection handler
*
* @return the client channel source
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public ChannelSource<? extends StreamSourceChannel> createPipeSourceServer(Executor executor, ChannelListener<? super StreamSinkChannel> openHandler) {
throw new UnsupportedOperationException("One-way Pipe Server");
}
/**
* Create a one-way pipe "server". The provided handler factory is used to supply handlers for the server "end" of
* the pipe. The returned channel source is used to establish connections to the server. The data flows from the
* server to the client. The provider's default executor will be used to
* execute handler methods.
*
* @param openHandler the initial open-connection handler
*
* @return the client channel source
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public ChannelSource<? extends StreamSourceChannel> createPipeSourceServer(ChannelListener<? super StreamSinkChannel> openHandler) {
return createPipeSourceServer(executor, openHandler);
}
/**
* Create a one-way pipe "server". The provided handler factory is used to supply handlers for the server "end" of
* the pipe. The returned channel source is used to establish connections to the server. The data flows from the
* client to the server.
*
* @param executor the executor to use to execute the handlers
* @param openHandler the initial open-connection handler
*
* @return the client channel source
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public ChannelSource<? extends StreamSinkChannel> createPipeSinkServer(Executor executor, ChannelListener<? super StreamSourceChannel> openHandler) {
throw new UnsupportedOperationException("One-way Pipe Server");
}
/**
* Create a one-way pipe "server". The provided handler factory is used to supply handlers for the server "end" of
* the pipe. The returned channel source is used to establish connections to the server. The data flows from the
* client to the server. The provider's default executor will be used to
* execute handler methods.
*
* @param openHandler the initial open-connection handler
*
* @return the client channel source
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public ChannelSource<? extends StreamSinkChannel> createPipeSinkServer(ChannelListener<? super StreamSourceChannel> openHandler) {
return createPipeSinkServer(executor, openHandler);
}
/**
* Create a single pipe connection.
*
* @param executor the executor to use to execute the handlers
* @param leftHandler the open handler for the "left" side of the pipe
* @param rightHandler the open handler for the "right" side of the pipe
*
* @return the future connection
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public IoFuture<? extends Closeable> createPipeConnection(Executor executor, ChannelListener<? super StreamChannel> leftHandler, ChannelListener<? super StreamChannel> rightHandler) {
throw new UnsupportedOperationException("Pipe Connection");
}
/**
* Create a single pipe connection. The provider's default executor will be used to
* execute handler methods.
*
* @param leftHandler the handler for the "left" side of the pipe
* @param rightHandler the handler for the "right" side of the pipe
*
* @return the future connection
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public IoFuture<? extends Closeable> createPipeConnection(ChannelListener<? super StreamChannel> leftHandler, ChannelListener<? super StreamChannel> rightHandler) {
return createPipeConnection(executor, leftHandler, rightHandler);
}
/**
* Create a single one-way pipe connection.
*
* @param executor the executor to use to execute the handlers
* @param sourceHandler the handler for the "source" side of the pipe
* @param sinkHandler the handler for the "sink" side of the pipe
*
* @return the future connection
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public IoFuture<? extends Closeable> createOneWayPipeConnection(Executor executor, ChannelListener<? super StreamSourceChannel> sourceHandler, ChannelListener<? super StreamSinkChannel> sinkHandler) {
throw new UnsupportedOperationException("One-way Pipe Connection");
}
/**
* Create a single one-way pipe connection. The provider's default executor will be used to
* execute handler methods.
*
* @param sourceHandler the handler for the "source" side of the pipe
* @param sinkHandler the handler for the "sink" side of the pipe
*
* @return the future connection
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public IoFuture<? extends Closeable> createOneWayPipeConnection(ChannelListener<? super StreamSourceChannel> sourceHandler, ChannelListener<? super StreamSinkChannel> sinkHandler) {
return createOneWayPipeConnection(executor, sourceHandler, sinkHandler);
}
/**
* Create a TCP acceptor.
*
* @param executor the executor to use to execute the handlers
* @param optionMap the initial configuration for the acceptor
* @return the TCP acceptor
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpAcceptor createTcpAcceptor(Executor executor, OptionMap optionMap) {
throw new UnsupportedOperationException("TCP Acceptor");
}
/**
* Create a TCP acceptor.
*
* @param optionMap the initial configuration for the acceptor
* @return the TCP acceptor
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public TcpAcceptor createTcpAcceptor(OptionMap optionMap) {
return createTcpAcceptor(executor, optionMap);
}
/**
* Create a local stream server. The stream server can be bound to one or more files in the filesystem.
*
* @param executor the executor to use to execute the handlers
* @param openListener a listener which is notified on channel open
* @param optionMap the initial configuration for the server
*
* @return a factory that can be used to configure the new stream server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalServer createLocalStreamServer(Executor executor, ChannelListener<? super ConnectedStreamChannel<String>> openListener, OptionMap optionMap) {
throw new UnsupportedOperationException("Local IPC Stream Server");
}
/**
* Create a local stream server. The stream server can be bound to one or more files in the filesystem.
*
* @param openListener a listener which is notified on channel open
* @param optionMap the initial configuration for the server
*
* @return a factory that can be used to configure the new stream server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalServer createLocalStreamServer(ChannelListener<? super ConnectedStreamChannel<String>> openListener, OptionMap optionMap) {
return createLocalStreamServer(executor, openListener, optionMap);
}
/**
* Create a local stream connector.
*
* @param executor the executor to use to execute the handlers
* @param optionMap the initial configuration for the connector
*
* @return the stream connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalStreamConnector createLocalStreamConnector(Executor executor, OptionMap optionMap) {
throw new UnsupportedOperationException("Local IPC Stream Connector");
}
/**
* Create a local stream connector.
*
* @param optionMap the initial configuration for the connector
*
* @return the stream connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalStreamConnector createLocalStreamConnector(OptionMap optionMap) {
return createLocalStreamConnector(executor, optionMap);
}
/**
* Create a local datagram server. The datagram server is bound to one or more files in the filesystem.
*
* @param executor the executor to use to execute the handlers
* @param openHandler the initial open-connection handler
* @param optionMap the initial configuration for the server
*
* @return the new datagram server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalServer createLocalDatagramServer(Executor executor, ChannelListener<? super DatagramChannel<String>> openHandler, OptionMap optionMap) {
throw new UnsupportedOperationException("Local IPC Datagram Server");
}
/**
* Create a local datagram server. The datagram server is bound to one or more files in the filesystem.
*
* @param openHandler the initial open-connection handler
* @param optionMap the initial configuration for the server
*
* @return the new datagram server
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalServer createLocalDatagramServer(ChannelListener<? super DatagramChannel<String>> openHandler, OptionMap optionMap) {
return createLocalDatagramServer(executor, openHandler, optionMap);
}
/**
* Create a local datagram connector.
*
* @param executor the executor to use to execute the handlers
* @param optionMap the initial configuration for the connector
* @return the new datagram connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalDatagramConnector createLocalDatagramConnector(Executor executor, OptionMap optionMap) {
throw new UnsupportedOperationException("Local IPC Datagram Connector");
}
/**
* Create a local datagram connector.
*
* @param optionMap the initial configuration for the connector
* @return the new datagram connector
*
* @since 2.0
*/
@SuppressWarnings({ "UnusedDeclaration" })
public LocalDatagramConnector createLocalDatagramConnector(OptionMap optionMap) {
return createLocalDatagramConnector(executor, optionMap);
}
/**
* Wake up any blocking I/O operation being carried out on a given thread. Custom implementors of {@link Thread}
* may call this method from their implementation of {@link Thread#interrupt()} after the default implementation
* to ensure that any thread waiting in a blocking operation is woken up in a timely manner. Some implementations
* may not implement this method, relying instead on the interruption mechanism built in to the JVM; as such this
* method should not be relied upon as a guaranteed way to awaken a blocking thread independently of thread
* interruption.
*
* @param targetThread the thread to awaken
*
* @since 1.2
*/
@SuppressWarnings({ "UnusedDeclaration" })
public void awaken(Thread targetThread) {
// nothing by default
}
/**
* Get the name of this XNIO instance.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Get a string representation of this XNIO instance.
*
* @return the string representation
*/
public String toString() {
return String.format("XNIO provider \"%s\" <%s@%s>", getName(), getClass().getName(), Integer.toHexString(hashCode()));
}
/**
* Close this XNIO provider. Calling this method more than one time has no additional effect.
*/
public abstract void close() throws IOException;
private Closeable registerMBean(final Object mBean, final ObjectName mBeanName) {
final SecurityManager sm = System.getSecurityManager();
final List<MBeanServer> servers = mBeanServers;
synchronized (servers) {
final Iterator<MBeanServer> it = servers.iterator();
if (!it.hasNext()) {
return IoUtils.nullCloseable();
} else {
final List<Registration> registrations = new ArrayList<Registration>(servers.size());
do {
final MBeanServer server = it.next();
if (sm != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
doRegister(mBean, mBeanName, registrations, server);
return null;
}
});
} else {
doRegister(mBean, mBeanName, registrations, server);
}
} while (it.hasNext());
return new RegHandle(registrations);
}
}
}
private static void doRegister(final Object mBean, final ObjectName mBeanName, final List<Registration> registrations, final MBeanServer server) {
try {
final ObjectInstance instance = server.registerMBean(mBean, mBeanName);
registrations.add(new Registration(server, instance.getObjectName()));
} catch (JMException e) {
mlog.debug(e, "Failed to register mBean named \"%s\" on server %s", mBeanName, server);
} catch (RuntimeOperationsException e) {
mlog.debug(e, "Failed to register mBean named \"%s\" on server %s", mBeanName, server);
}
}
private interface Entry extends Map.Entry<String, String> {}
private static Entry entry(final String k, final String v) {
return new Entry() {
public String getKey() {
return k;
}
public String getValue() {
return v;
}
public String setValue(final String value) {
throw new UnsupportedOperationException("setValue");
}
};
}
private static Hashtable<String, String> hashtable(Entry... entries) {
final Hashtable<String, String> table = new Hashtable<String, String>(entries.length);
for (Entry entry : entries) {
table.put(entry.getKey(), entry.getValue());
}
return table;
}
/**
* Get an XNIO property. The property name must start with {@code "xnio."}.
*
* @param name the property name
* @return the property value, or {@code null} if it wasn't found
* @since 1.2
*/
protected String getProperty(final String name) {
if (! name.startsWith("xnio.")) {
throw new SecurityException("Not allowed to read non-XNIO properties");
}
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new GetPropertyAction(name, null));
} else {
return System.getProperty(name);
}
}
/**
* Get an XNIO property. The property name must start with {@code "xnio."}.
*
* @param name the property name
* @param defaultValue the default value
* @return the property value, or {@code defaultValue} if it wasn't found
* @since 1.2
*/
protected String getProperty(final String name, final String defaultValue) {
if (! name.startsWith("xnio.")) {
throw new SecurityException("Not allowed to read non-XNIO properties");
}
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
return AccessController.doPrivileged(new GetPropertyAction(name, defaultValue));
} else {
return System.getProperty(name, defaultValue);
}
}
/**
* Register a TCP server MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final TcpServerMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "server"),
entry("protocol", "tcp"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
/* TODO: name? */
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a TCP connection MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final TcpConnectionMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "connection"),
entry("protocol", "tcp"),
entry("bindAddress", ObjectName.quote(mBean.getBindAddress().toString())),
entry("peerAddress", ObjectName.quote(mBean.getPeerAddress().toString())),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a UDP server MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final UdpServerMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "server"),
entry("protocol", "udp"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a one-way pipe connection MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final OneWayPipeConnectionMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "connection"),
entry("protocol", "local"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a pipe connection MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final PipeConnectionMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "connection"),
entry("protocol", "local"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a pipe server MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final PipeServerMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "server"),
entry("protocol", "local"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a pipe source server MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final PipeSourceServerMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "server"),
entry("protocol", "local-source"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
/**
* Register a pipe sink server MBean.
*
* @param mBean the MBean
* @return a handle which may be used to unregister the MBean
* @since 1.2
*/
protected Closeable registerMBean(final PipeSinkServerMBean mBean) {
try {
final ObjectName mbeanName = new ObjectName(MANAGEMENT_DOMAIN, hashtable(
entry("provider", ObjectName.quote(getName())),
entry("type", "server"),
entry("protocol", "local-sink"),
entry("id", Long.toString(mbeanSequence.getAndIncrement()))
));
return registerMBean(mBean, mbeanName);
} catch (MalformedObjectNameException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
private static final class Registration {
private final MBeanServer server;
private final ObjectName objectName;
private Registration(final MBeanServer server, final ObjectName objectName) {
this.server = server;
this.objectName = objectName;
}
}
private static final class RegHandle implements Closeable {
private final List<Registration> registrations;
private final AtomicBoolean open = new AtomicBoolean(true);
private RegHandle(final List<Registration> registrations) {
this.registrations = registrations;
}
public void close() throws IOException {
if (open.getAndSet(false)) {
final SecurityManager sm = System.getSecurityManager();
for (final Registration registration : registrations) {
if (sm != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
doUnregister(registration);
return null;
}
});
} else {
doUnregister(registration);
}
}
}
}
private static void doUnregister(final Registration registration) {
final MBeanServer server = registration.server;
final ObjectName mBeanName = registration.objectName;
try {
server.unregisterMBean(mBeanName);
} catch (InstanceNotFoundException e) {
mlog.debug(e, "Failed to unregister mBean named \"%s\" on server %s", mBeanName, server);
} catch (MBeanRegistrationException e) {
mlog.debug(e, "Failed to unregister mBean named \"%s\" on server %s", mBeanName, server);
}
}
}
private static final class GetMBeanServersAction implements PrivilegedAction<Collection<? extends MBeanServer>> {
private final String agentId;
public GetMBeanServersAction(final String agentId) {
this.agentId = agentId;
}
public Collection<? extends MBeanServer> run() {
return MBeanServerFactory.findMBeanServer(agentId);
}
}
private static final class GetPropertyAction implements PrivilegedAction<String> {
private final String propertyName;
private final String defaultValue;
private GetPropertyAction(final String propertyName, final String defaultValue) {
this.propertyName = propertyName;
this.defaultValue = defaultValue;
}
public String run() {
return System.getProperty(propertyName, defaultValue);
}
}
}
|
package edu.umd.cs.findbugs.ba.type;
/**
* Interface for objects representing Java types.
* In general, an Type provides a type
* for a value used in a Java method.
* Types of values include:
* <ul>
* <li> basic types (BasicType): int, char, short, double, etc.
* <li> reference types (ReferenceType): includes the type of the null
* value (NullType), class and interface types
* (ClassType), and array types (ArrayType)
* <li> special dataflow types: top (TopType) and bottom (BottomType)
* <li> "extra" types: LongExtraType and DoubleExtraType, which
* arise because BCEL thinks that longs and doubles take two
* stack slots
* </ul>
*
* <p> This class and its descendents were designed to
* address some shortcomings of the BCEL Type class and descendents:
* <ol>
* <li> They are not interned, meaning that many objects
* may exist representing a single type.
* <li> BCEL reference types are inconsistent about whether a signature
* or class name is used to create them.
* <li> BCEL's ArrayType class is not a subtype of ObjectType:
* this is just wrong, IMO.
* <li> BCEL has no data structure to represent a class hierarchy:
* subtype relationships are discovered by a series of
* repository lookups. (This also makes questions like
* "what are all of the direct subclasses of this class"
* difficult to answer efficiently.)
* <li> BCEL has no built-in representation for dataflow top and bottom
* types.
* </ol>
*
* <p> The goals of Type and related classes
* are to be efficient in dataflow analysis, and to make
* class hierarchy queries flexible and easy.
*
* @author David Hovemeyer
*/
public interface Type {
/**
* Return the JVM type signature.
* Note that some types do not have valid JVM signature
* representations. For example, the type of the null
* reference value cannot be represented as a signature.
* However, all basic types, class types, and array types
* have JVM signatures.
*/
public String getSignature();
/**
* Return the type code value as defined in
* org.apache.bcel.Constants or
* {@link edu.umd.cs.findbugs.ba.ExtendedTypes}.
*/
public int getTypeCode();
/**
* Is this type a basic type?
*/
public boolean isBasicType();
/**
* Is this type a reference type?
*/
public boolean isReferenceType();
/**
* Is this a valid array element type?
*/
public boolean isValidArrayElementType();
/**
* Accept an TypeVisitor.
* @param visitor the visitor
*/
public void accept(TypeVisitor visitor);
}
// vim:ts=4
|
package org.commcare.graph.view;
import android.app.Activity;
import android.view.View;
import android.webkit.JavascriptInterface;
import java.util.TimerTask;
public class GraphLoader extends TimerTask {
private final Activity activity;
private final View spinner;
public GraphLoader(Activity a, View v) {
activity = a;
spinner = v;
}
@JavascriptInterface
@Override
public void run() {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
spinner.setVisibility(View.GONE);
}
});
}
}
|
package tela.meusProdutos;
import dao.ProdutoDAO;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
import modelo.Condomino;
import modelo.Produto;
/**
*
* @author Everton Soares
*/
public class CadastrarProduto extends javax.swing.JFrame {
private final Condomino condomino;
private JPanel img;
/**
* Creates new form CadastrarProduto
* @param condomino
*/
public CadastrarProduto(Condomino condomino) {
this.condomino = condomino;
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() {
menuFlutuante = new javax.swing.JPopupMenu();
miAddImagem = new javax.swing.JMenuItem();
miRemoverImagem = new javax.swing.JMenuItem();
lNome = new javax.swing.JLabel();
tfNome = new javax.swing.JTextField();
lQtde = new javax.swing.JLabel();
spQtde = new javax.swing.JSpinner();
lDiaria = new javax.swing.JLabel();
tfDiaria = new javax.swing.JTextField();
lTaxa = new javax.swing.JLabel();
tfTaxa = new javax.swing.JTextField();
painelCategorias = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
listCategorias = new javax.swing.JList();
bAddCategoria = new javax.swing.JButton();
bRemoveCategoria = new javax.swing.JButton();
painelImagens = new javax.swing.JPanel();
imgPrincipal = new javax.swing.JPanel();
img1 = new javax.swing.JPanel();
img2 = new javax.swing.JPanel();
img3 = new javax.swing.JPanel();
jSeparator1 = new javax.swing.JSeparator();
bCadastrar = new javax.swing.JButton();
bCancelar = new javax.swing.JButton();
painelDescricao = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
taDescricao = new javax.swing.JTextArea();
miAddImagem.setText("Adicionar Imagem");
miAddImagem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miAddImagemActionPerformed(evt);
}
});
menuFlutuante.add(miAddImagem);
miRemoverImagem.setText("Remover Imagem");
miRemoverImagem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miRemoverImagemActionPerformed(evt);
}
});
menuFlutuante.add(miRemoverImagem);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Cadatrar Produto");
setResizable(false);
lNome.setText("Nome");
lQtde.setText("Quantidade");
spQtde.setModel(new javax.swing.SpinnerNumberModel(1, 1, 30, 1));
lDiaria.setText("Diária");
tfDiaria.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
tfDiariaFocusLost(evt);
}
});
lTaxa.setText("Taxa por atraso");
tfTaxa.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
tfTaxaFocusLost(evt);
}
});
painelCategorias.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Categorias", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 0, 0))); // NOI18N
jScrollPane1.setViewportView(listCategorias);
javax.swing.GroupLayout painelCategoriasLayout = new javax.swing.GroupLayout(painelCategorias);
painelCategorias.setLayout(painelCategoriasLayout);
painelCategoriasLayout.setHorizontalGroup(
painelCategoriasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelCategoriasLayout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(painelCategoriasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bRemoveCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bAddCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
painelCategoriasLayout.setVerticalGroup(
painelCategoriasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelCategoriasLayout.createSequentialGroup()
.addContainerGap()
.addComponent(bAddCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addComponent(bRemoveCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
painelImagens.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Imagens", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 0, 0))); // NOI18N
imgPrincipal.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 0, 0), 1, true));
imgPrincipal.setLayout(new java.awt.BorderLayout());
img1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
img1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
img1MouseReleased(evt);
}
});
img1.setLayout(new java.awt.BorderLayout());
img2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
img2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
img2MouseReleased(evt);
}
});
img2.setLayout(new java.awt.BorderLayout());
img3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
img3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
img3MouseReleased(evt);
}
});
img3.setLayout(new java.awt.BorderLayout());
javax.swing.GroupLayout painelImagensLayout = new javax.swing.GroupLayout(painelImagens);
painelImagens.setLayout(painelImagensLayout);
painelImagensLayout.setHorizontalGroup(
painelImagensLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelImagensLayout.createSequentialGroup()
.addComponent(imgPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(painelImagensLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(img1, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE)
.addComponent(img2, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE)
.addComponent(img3, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
painelImagensLayout.setVerticalGroup(
painelImagensLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelImagensLayout.createSequentialGroup()
.addGroup(painelImagensLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(imgPrincipal, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(painelImagensLayout.createSequentialGroup()
.addComponent(img1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(img2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(img3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
bCadastrar.setText("Cadastrar");
bCadastrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bCadastrarActionPerformed(evt);
}
});
bCancelar.setText("Cancelar");
bCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bCancelarActionPerformed(evt);
}
});
painelDescricao.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Descrição", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 0, 0))); // NOI18N
taDescricao.setColumns(20);
taDescricao.setRows(5);
jScrollPane2.setViewportView(taDescricao);
javax.swing.GroupLayout painelDescricaoLayout = new javax.swing.GroupLayout(painelDescricao);
painelDescricao.setLayout(painelDescricaoLayout);
painelDescricaoLayout.setHorizontalGroup(
painelDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelDescricaoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2)
.addContainerGap())
);
painelDescricaoLayout.setVerticalGroup(
painelDescricaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(painelDescricaoLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 11, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfNome))
.addComponent(painelDescricao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(painelCategorias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(lTaxa)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfTaxa))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(lDiaria, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfDiaria))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(lQtde)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spQtde, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(painelImagens, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jSeparator1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(bCadastrar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bCancelar)
.addGap(32, 32, 32)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lNome)
.addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lQtde)
.addComponent(spQtde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lDiaria)
.addComponent(tfDiaria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lTaxa)
.addComponent(tfTaxa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(painelCategorias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(painelImagens, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(painelDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(bCadastrar)
.addComponent(bCancelar))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
dispose();
}//GEN-LAST:event_bCancelarActionPerformed
private void img1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_img1MouseReleased
img = img1;
realizarAcao(evt);
}//GEN-LAST:event_img1MouseReleased
private void img2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_img2MouseReleased
img = img2;
realizarAcao(evt);
}//GEN-LAST:event_img2MouseReleased
private void img3MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_img3MouseReleased
img = img3;
realizarAcao(evt);
}//GEN-LAST:event_img3MouseReleased
private void miAddImagemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miAddImagemActionPerformed
addImagem();
}//GEN-LAST:event_miAddImagemActionPerformed
private void miRemoverImagemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miRemoverImagemActionPerformed
removerImagem();
}//GEN-LAST:event_miRemoverImagemActionPerformed
private void tfDiariaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfDiariaFocusLost
if (!tfDiaria.getText().startsWith("R$")) {
tfDiaria.setText("R$" + tfDiaria.getText());
}
}//GEN-LAST:event_tfDiariaFocusLost
private void tfTaxaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfTaxaFocusLost
if (!tfTaxa.getText().endsWith("%")) {
tfTaxa.setText(tfTaxa.getText() + "%");
}
}//GEN-LAST:event_tfTaxaFocusLost
private void bCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCadastrarActionPerformed
cadastrarProduto();
dispose();
}//GEN-LAST:event_bCadastrarActionPerformed
private void realizarAcao(MouseEvent evt) {
if (evt.getButton() == MouseEvent.BUTTON1) {
mudarCorPaineis();
if (evt.getClickCount() > 1){
addImagem();
}
} else if (evt.getButton() == MouseEvent.BUTTON3) {
mudarCorPaineis();
menuFlutuante.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
private void mudarCorPaineis(){
imgPrincipal.removeAll();
imgPrincipal.repaint();
img1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
img3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
img2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
if (img.getComponents().length > 0) {
PainelImagens newImage = new PainelImagens();
newImage.setBfImage(img.getName());
imgPrincipal.add(newImage);
imgPrincipal.revalidate();
img.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 0, 0), 1, true));
}
}
private void addImagem(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG, JPEG, GIF & PNG", "jpg", "gif", "jpeg", "png");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
PainelImagens newImagem = new PainelImagens();
img.setName(chooser.getSelectedFile().getPath());
newImagem.setBfImage(img.getName());
if ( (newImagem.getBfImage().getWidth() + newImagem.getBfImage().getHeight()) > 1000) {
img.setName("");
JOptionPane.showMessageDialog(null, "Imagem deve possuir resolução igual ou inferior a 500x500 pixels", "Imagem Grande", JOptionPane.INFORMATION_MESSAGE);
} else {
carregarImagem(newImagem);
}
}
}
private void removerImagem(){
img.removeAll();
//img.setName("");
mudarCorPaineis();
img.repaint();
}
private void carregarImagem(PainelImagens newPainel){
removerImagem();
img.add(newPainel);
img.revalidate();
}
private void cadastrarProduto(){
BufferedImage imagem;
ByteArrayOutputStream bytesImg = new ByteArrayOutputStream();
byte[] byteArray = null;
try {
imagem = ImageIO.read(new File(img1.getName()));
ImageIO.write(imagem, "jpg", bytesImg);
bytesImg.flush();
byteArray = bytesImg.toByteArray();
bytesImg.close();
} catch (IOException ex) {
Logger.getLogger(CadastrarProduto.class.getName()).log(Level.SEVERE, null, ex);
}
Produto produto = new Produto();
produto.setNome(tfNome.getText());
produto.setQuantidade(Integer.parseInt(spQtde.getValue().toString()));
produto.setDescricao(taDescricao.getText());
produto.setCondomino(condomino);
produto.setImagen(byteArray);
produto.setCategorias(new ArrayList<>());
produto.setDiaria(Double.parseDouble(tfDiaria.getText().substring(2)));
produto.setTaxa(Integer.parseInt(tfTaxa.getText().substring(0, tfTaxa.getText().length() - 1)));
ProdutoDAO produtoDAO = new ProdutoDAO();
produtoDAO.addProduto(produto);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bAddCategoria;
private javax.swing.JButton bCadastrar;
private javax.swing.JButton bCancelar;
private javax.swing.JButton bRemoveCategoria;
private javax.swing.JPanel img1;
private javax.swing.JPanel img2;
private javax.swing.JPanel img3;
private javax.swing.JPanel imgPrincipal;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel lDiaria;
private javax.swing.JLabel lNome;
private javax.swing.JLabel lQtde;
private javax.swing.JLabel lTaxa;
private javax.swing.JList listCategorias;
private javax.swing.JPopupMenu menuFlutuante;
private javax.swing.JMenuItem miAddImagem;
private javax.swing.JMenuItem miRemoverImagem;
private javax.swing.JPanel painelCategorias;
private javax.swing.JPanel painelDescricao;
private javax.swing.JPanel painelImagens;
private javax.swing.JSpinner spQtde;
private javax.swing.JTextArea taDescricao;
private javax.swing.JTextField tfDiaria;
private javax.swing.JTextField tfNome;
private javax.swing.JTextField tfTaxa;
// End of variables declaration//GEN-END:variables
}
|
import java.util.*;
public class Camera
{
private static final String INITIAL_INPUT = "";
public Camera (Vector<String> values, boolean debug)
{
_theComputer = new Intcode(values, INITIAL_INPUT, debug);
_scaffolding = new Scaffold(debug);
_debug = debug;
}
public final void takePicture ()
{
while (!_theComputer.hasHalted())
{
_theComputer.singleStepExecution();
if (_theComputer.hasOutput())
{
String output = _theComputer.getOutput();
_scaffolding.addData(output);
}
}
}
public final void scanForIntersections ()
{
_scaffolding.scanForIntersections();
}
@Override
public String toString ()
{
return _scaffolding.toString();
}
private Intcode _theComputer;
private Scaffold _scaffolding;
private boolean _debug;
}
|
/**
* Cell information for the Map.
*/
public class CellId
{
public static final char ENTRANCE = '@';
public static final char OPEN_PASSAGE = '.';
public static final char STONE_WALL = '
private CellId ()
{
}
}
|
package trikita.anvil;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.InvocationTargetException;
import java.lang.ref.WeakReference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.WeakHashMap;
/**
* Anvil class is a namespace for top-level static methods and interfaces. Most
* users would only use it to call {@code Anvil.render()}.
*
* Internally, Anvil class defines how Renderables are mounted into Views
* and how they are lazily rendered, and this is the key functionality of the
* Anvil library.
*/
public final class Anvil {
private final static Map<View, Mount> mounts = new WeakHashMap<>();
private static Mount currentMount = null;
private static Handler anvilUIHandler = null;
/** Renderable can be mounted and rendered using Anvil library. */
public interface Renderable {
/** This method is a place to define the structure of your layout, its view
* properties and data bindings. */
void view();
}
public interface ViewFactory {
View fromClass(Context c, Class<? extends View> v);
View fromXml(Context c, int xmlId);
}
private final static List<ViewFactory> viewFactories = new ArrayList<ViewFactory>() {{
add(new DefaultViewFactory());
}};
final static class DefaultViewFactory implements ViewFactory {
public View fromClass(Context c, Class<? extends View> viewClass) {
try {
return viewClass.getConstructor(Context.class).newInstance(c);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
public View fromXml(Context c, int xmlId) {
return LayoutInflater.from(c).inflate(xmlId, null, false);
}
};
public static void registerViewFactory(ViewFactory viewFactory) {
if (!viewFactories.contains(viewFactory)) {
viewFactories.add(0, viewFactory);
}
}
private Anvil() {}
private final static Runnable anvilRenderRunnable = new Runnable() {
public void run() {
Anvil.render();
}
};
public interface AttributeSetter<T> {
boolean set(View v, String name, T value, T prevValue);
}
private final static List<AttributeSetter> attributeSetters =
new ArrayList<AttributeSetter>() {{ add(new PropertySetter()); }};
public static void registerAttributeSetter(AttributeSetter setter) {
if (!attributeSetters.contains(setter)) {
attributeSetters.add(0, setter);
}
}
/** Tags: arbitrary data bound to specific views, such as last cached attribute values */
private static Map<View, Map<String, Object>> tags = new WeakHashMap<>();
public static void set(View v, String key, Object value) {
Map<String, Object> attrs = tags.get(v);
if (attrs == null) {
attrs = new HashMap<>();
tags.put(v, attrs);
}
attrs.put(key, value);
}
public static Object get(View v, String key) {
Map<String, Object> attrs = tags.get(v);
if (attrs == null) {
return null;
}
return attrs.get(key);
}
/** Starts the new rendering cycle updating all mounted
* renderables. Update happens in a lazy manner, only the values that has
* been changed since last rendering cycle will be actually updated in the
* views. This method can be called from any thread, so it's safe to use
* {@code Anvil.render()} in background services. */
public static void render() {
// If Anvil.render() is called on a non-UI thread, use UI Handler
if (Looper.myLooper() != Looper.getMainLooper()) {
synchronized (Anvil.class) {
if (anvilUIHandler == null) {
anvilUIHandler = new Handler(Looper.getMainLooper());
}
}
anvilUIHandler.removeCallbacksAndMessages(null);
anvilUIHandler.post(anvilRenderRunnable);
return;
}
Set<Mount> set = new HashSet<>();
set.addAll(mounts.values());
for (Mount m : set) {
render(m);
}
}
/**
* Mounts a renderable function defining the layout into a View. If host is a
* viewgroup it is assumed to be empty, so the Renderable would define what
* its child views would be.
* @param v a View into which the renderable r will be mounted
* @param r a Renderable to mount into a View
*/
public static <T extends View> T mount(T v, Renderable r) {
Mount m = new Mount(v, r);
mounts.put(v, m);
render(v);
return v;
}
/**
* Unmounts a mounted renderable. This would also clean up all the child
* views inside the parent ViewGroup, which acted as a mount point.
* @param v A mount point to unmount from its View
*/
public static void unmount(View v) {
unmount(v, true);
}
public static void unmount(View v, boolean removeChildren) {
Mount m = mounts.get(v);
if (m != null) {
mounts.remove(v);
if (v instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) v;
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
unmount(viewGroup.getChildAt(i));
}
if (removeChildren) {
viewGroup.removeViews(0, childCount);
}
}
}
}
/**
* Returns currently rendered Mount point. Must be called from the
* Renderable's view() method, otherwise it returns null
* @return current mount point
*/
static Mount currentMount() {
return currentMount;
}
/**
* Returns currently rendered View. It allows to access the real view from
* inside the Renderable.
* @return currently rendered View
*/
@SuppressWarnings("unchecked")
public static <T extends View> T currentView() {
if (currentMount == null) {
return null;
}
return (T) currentMount.iterator.currentView();
}
public static void render(View v) {
Mount m = mounts.get(v);
if (m == null) {
return;
}
render(m);
}
static void render(Mount m) {
if (m.lock) {
return;
}
m.lock = true;
Mount prev = currentMount;
currentMount = m;
m.iterator.start();
if (m.renderable != null) {
m.renderable.view();
}
m.iterator.end();
currentMount = prev;
m.lock = false;
}
/** Mount describes a mount point. Mount point is a Renderable function
* attached to some ViewGroup. Mount point keeps track of the virtual layout
* declared by Renderable */
static class Mount {
private boolean lock = false;
private final WeakReference<View> rootView;
private final Renderable renderable;
final Iterator iterator = new Iterator();
Mount(View v, Renderable r) {
this.renderable = r;
this.rootView = new WeakReference<>(v);
}
@SuppressLint("Assert")
class Iterator {
Deque<View> views = new ArrayDeque<>();
Deque<Integer> indices = new ArrayDeque<>();
private void start() {
assert views.size() == 0;
assert indices.size() == 0;
indices.push(0);
views.push(rootView.get());
}
void start(Class<? extends View> c, int layoutId, Object key) {
assert views.peek() instanceof ViewGroup;
ViewGroup vg = (ViewGroup) views.peek();
int i = indices.peek();
View v = null;
if (i < vg.getChildCount()) {
v = vg.getChildAt(i);
}
Context context = rootView.get().getContext();
if (c != null && (v == null || !v.getClass().equals(c))) {
vg.removeView(v);
for (ViewFactory vf : viewFactories) {
v = vf.fromClass(context, c);
if (v != null) {
vg.addView(v, i);
break;
}
}
} else if (c == null && (v == null || get(v, "_layoutId") != Integer.valueOf(layoutId))) {
vg.removeView(v);
for (ViewFactory vf : viewFactories) {
v = vf.fromXml(context, layoutId);
if (v != null) {
set(v, "_layoutId", layoutId);
vg.addView(v, i);
break;
}
}
}
assert v != null;
views.push(v);
indices.push(indices.pop() + 1);
indices.push(0);
}
void end() {
int index = indices.peek();
View v = views.peek();
if (v != null && v instanceof ViewGroup && get(v, "_layoutId") == null && mounts.get(v) == null) {
ViewGroup vg = (ViewGroup) v;
if (index < vg.getChildCount()) {
vg.removeViews(index, vg.getChildCount() - index);
}
}
indices.pop();
views.pop();
}
<T> void attr(String name, T value) {
View currentView = views.peek();
@SuppressWarnings("unchecked")
T currentValue = (T) get(currentView, name);
if (currentValue == null || !currentValue.equals(value)) {
for (AttributeSetter setter : attributeSetters) {
if (setter.set(currentView, name, value, currentValue)) {
set(currentView, name, value);
return;
}
}
}
}
public View currentView() {
return views.peek();
}
}
}
}
|
package polytheque.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.toedter.calendar.JDateChooser;
@SuppressWarnings("serial")
public class AppliReserverJeu extends JPanel implements ActionListener
{
private TacheDAffichage tacheDAffichageDeLApplication;
private JButton boutonvalider;
private Date datedebut;
private Date datefin;
private JButton boutonRetourAccueil;
private JButton boutonRecherche;
private JButton boutonValider;
private JTextField searchContent;
private JTextField DateContent;
private JTextField ExtensionContent;
//TODO
//"Veuiller indiquer la date souhaite de l'emprunt"
//faire un afficherListe de jeux avec que ces jeux l
public AppliReserverJeu(TacheDAffichage afficheAppli)
{
creerPanneauRecherche();
creerPanneauExtension();
creerPanneauDate();
boutonRetourAccueil = new JButton("Acceuil");
this.add(boutonRetourAccueil);
}
private void creerPanneauExtension()
{
// TODO Auto-generated method stub
}
private void creerPanneauRecherche()
{
JPanel searchPanel = new JPanel();
searchPanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelSearch = new JLabel("Recherche par nom :");
labelSearch.setBounds(300, 0, 100, 30);
searchPanel.add(labelSearch);
this.searchContent = new JTextField();
this.searchContent.setBounds(450, 0, 100, 30);
this.searchContent.setColumns(10);
searchPanel.add(this.searchContent, BorderLayout.NORTH);
this.boutonRecherche = new JButton("Rechercher");
this.boutonRecherche.addActionListener(this);
searchPanel.add(boutonRecherche, BorderLayout.NORTH);
this.add(searchPanel);
}
private void creerPanneauDate() {
JPanel DatePanel = new JPanel();
DatePanel.setPreferredSize(new Dimension(TacheDAffichage.LARGEUR, 50));
JLabel labelDate = new JLabel("Cliquez sur la date a laquelle vous voudriez emprunter le jeux :");
labelDate.setBounds(400, 150, 100, 30);
this.add(labelDate);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(400, 200, 60, 20);
DatePanel.add(dateChooser);
this.add(DatePanel);
this.boutonValider = new JButton("Valider");
this.boutonValider.addActionListener(this);
this.add(boutonValider);
}
public void actionPerformed(ActionEvent e)
{
JButton boutonSelectionne = (JButton) e.getSource();
if (boutonSelectionne == this.boutonValider)
{
return;
}
}
}
|
package nxt.peer;
import nxt.Account;
import nxt.BlockchainProcessor;
import nxt.Constants;
import nxt.Nxt;
import nxt.NxtException;
import nxt.util.Convert;
import nxt.util.CountingInputStream;
import nxt.util.CountingOutputStream;
import nxt.util.Logger;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.GZIPInputStream;
final class PeerImpl implements Peer {
private final String peerAddress;
private volatile String announcedAddress;
private volatile int port;
private volatile boolean shareAddress;
private volatile Hallmark hallmark;
private volatile String platform;
private volatile String application;
private volatile String version;
private volatile boolean isOldVersion;
private volatile long adjustedWeight;
private volatile long blacklistingTime;
private volatile State state;
private volatile long downloadedVolume;
private volatile long uploadedVolume;
private volatile int lastUpdated;
private volatile long hallmarkBalance = -1;
private volatile int hallmarkBalanceHeight;
PeerImpl(String peerAddress, String announcedAddress) {
this.peerAddress = peerAddress;
this.announcedAddress = announcedAddress;
try {
this.port = new URL("http://" + announcedAddress).getPort();
} catch (MalformedURLException ignore) {}
this.state = State.NON_CONNECTED;
this.shareAddress = true;
}
@Override
public String getPeerAddress() {
return peerAddress;
}
@Override
public State getState() {
return state;
}
void setState(State state) {
if (this.state == state) {
return;
}
if (this.state == State.NON_CONNECTED) {
this.state = state;
Peers.notifyListeners(this, Peers.Event.ADDED_ACTIVE_PEER);
} else if (state != State.NON_CONNECTED) {
this.state = state;
Peers.notifyListeners(this, Peers.Event.CHANGED_ACTIVE_PEER);
}
}
@Override
public long getDownloadedVolume() {
return downloadedVolume;
}
void updateDownloadedVolume(long volume) {
synchronized (this) {
downloadedVolume += volume;
}
Peers.notifyListeners(this, Peers.Event.DOWNLOADED_VOLUME);
}
@Override
public long getUploadedVolume() {
return uploadedVolume;
}
void updateUploadedVolume(long volume) {
synchronized (this) {
uploadedVolume += volume;
}
Peers.notifyListeners(this, Peers.Event.UPLOADED_VOLUME);
}
@Override
public String getVersion() {
return version;
}
void setVersion(String version) {
this.version = version;
isOldVersion = false;
if (Nxt.APPLICATION.equals(application) && version != null) {
String[] versions = version.split("\\.");
if (versions.length < Constants.MIN_VERSION.length) {
isOldVersion = true;
} else {
for (int i = 0; i < Constants.MIN_VERSION.length; i++) {
try {
int v = Integer.parseInt(versions[i]);
if (v > Constants.MIN_VERSION[i]) {
isOldVersion = false;
break;
} else if (v < Constants.MIN_VERSION[i]) {
isOldVersion = true;
break;
}
} catch (NumberFormatException e) {
isOldVersion = true;
break;
}
}
}
if (isOldVersion) {
Logger.logDebugMessage("Blacklisting %s version %s", peerAddress, version);
}
}
}
@Override
public String getApplication() {
return application;
}
void setApplication(String application) {
this.application = application;
}
@Override
public String getPlatform() {
return platform;
}
void setPlatform(String platform) {
this.platform = platform;
}
@Override
public String getSoftware() {
return Convert.truncate(application, "?", 10, false)
+ " (" + Convert.truncate(version, "?", 10, false) + ")"
+ " @ " + Convert.truncate(platform, "?", 10, false);
}
@Override
public boolean shareAddress() {
return shareAddress;
}
void setShareAddress(boolean shareAddress) {
this.shareAddress = shareAddress;
}
@Override
public String getAnnouncedAddress() {
return announcedAddress;
}
void setAnnouncedAddress(String announcedAddress) {
String announcedPeerAddress = Peers.normalizeHostAndPort(announcedAddress);
if (announcedPeerAddress != null) {
this.announcedAddress = announcedPeerAddress;
try {
this.port = new URL("http://" + announcedPeerAddress).getPort();
} catch (MalformedURLException ignore) {}
}
}
int getPort() {
return port;
}
@Override
public boolean isWellKnown() {
return announcedAddress != null && Peers.wellKnownPeers.contains(announcedAddress);
}
@Override
public Hallmark getHallmark() {
return hallmark;
}
@Override
public int getWeight() {
if (hallmark == null) {
return 0;
}
if (hallmarkBalance == -1 || hallmarkBalanceHeight < Nxt.getBlockchain().getHeight() - 60) {
long accountId = hallmark.getAccountId();
Account account = Account.getAccount(accountId);
hallmarkBalance = account == null ? 0 : account.getBalanceNQT();
hallmarkBalanceHeight = Nxt.getBlockchain().getHeight();
}
return (int)(adjustedWeight * (hallmarkBalance / Constants.ONE_NXT) / Constants.MAX_BALANCE_NXT);
}
@Override
public boolean isBlacklisted() {
return blacklistingTime > 0 || isOldVersion || Peers.knownBlacklistedPeers.contains(peerAddress);
}
@Override
public void blacklist(Exception cause) {
if (cause instanceof NxtException.NotCurrentlyValidException || cause instanceof BlockchainProcessor.BlockOutOfOrderException
|| cause instanceof SQLException || cause.getCause() instanceof SQLException) {
// don't blacklist peers just because a feature is not yet enabled, or because of database timeouts
// prevents erroneous blacklisting during loading of blockchain from scratch
return;
}
if (! isBlacklisted() && ! (cause instanceof IOException)) {
Logger.logDebugMessage("Blacklisting " + peerAddress + " because of: " + cause.toString(), cause);
}
blacklist();
}
@Override
public void blacklist() {
blacklistingTime = System.currentTimeMillis();
setState(State.NON_CONNECTED);
Peers.notifyListeners(this, Peers.Event.BLACKLIST);
}
@Override
public void unBlacklist() {
setState(State.NON_CONNECTED);
blacklistingTime = 0;
Peers.notifyListeners(this, Peers.Event.UNBLACKLIST);
}
void updateBlacklistedStatus(long curTime) {
if (blacklistingTime > 0 && blacklistingTime + Peers.blacklistingPeriod <= curTime) {
unBlacklist();
}
}
@Override
public void deactivate() {
setState(State.NON_CONNECTED);
Peers.notifyListeners(this, Peers.Event.DEACTIVATE);
}
@Override
public void remove() {
Peers.removePeer(this);
Peers.notifyListeners(this, Peers.Event.REMOVE);
}
@Override
public int getLastUpdated() {
return lastUpdated;
}
void setLastUpdated(int lastUpdated) {
this.lastUpdated = lastUpdated;
}
@Override
public JSONObject send(final JSONStreamAware request) {
JSONObject response;
String log = null;
boolean showLog = false;
HttpURLConnection connection = null;
try {
String address = announcedAddress != null ? announcedAddress : peerAddress;
StringBuilder buf = new StringBuilder("http:
buf.append(address);
if (port <= 0) {
buf.append(':');
buf.append(Peers.getDefaultPeerPort());
}
buf.append("/nxt");
URL url = new URL(buf.toString());
if (Peers.communicationLoggingMask != 0) {
StringWriter stringWriter = new StringWriter();
request.writeJSONString(stringWriter);
log = "\"" + url.toString() + "\": " + stringWriter.toString();
}
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setConnectTimeout(Peers.connectTimeout);
connection.setReadTimeout(Peers.readTimeout);
connection.setRequestProperty("Accept-Encoding", "gzip");
CountingOutputStream cos = new CountingOutputStream(connection.getOutputStream());
try (Writer writer = new BufferedWriter(new OutputStreamWriter(cos, "UTF-8"))) {
request.writeJSONString(writer);
}
updateUploadedVolume(cos.getCount());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
CountingInputStream cis = new CountingInputStream(connection.getInputStream());
InputStream responseStream = cis;
if ("gzip".equals(connection.getHeaderField("Content-Encoding"))) {
responseStream = new GZIPInputStream(cis);
}
if ((Peers.communicationLoggingMask & Peers.LOGGING_MASK_200_RESPONSES) != 0) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int numberOfBytes;
try (InputStream inputStream = responseStream) {
while ((numberOfBytes = inputStream.read(buffer, 0, buffer.length)) > 0) {
byteArrayOutputStream.write(buffer, 0, numberOfBytes);
}
}
String responseValue = byteArrayOutputStream.toString("UTF-8");
if (responseValue.length() > 0 && responseStream instanceof GZIPInputStream) {
log += String.format("[length: %d, compression ratio: %.2f]", cis.getCount(), (double)cis.getCount() / (double)responseValue.length());
}
log += " >>> " + responseValue;
showLog = true;
response = (JSONObject) JSONValue.parse(responseValue);
} else {
try (Reader reader = new BufferedReader(new InputStreamReader(responseStream, "UTF-8"))) {
response = (JSONObject)JSONValue.parse(reader);
}
}
updateDownloadedVolume(cis.getCount());
} else {
if ((Peers.communicationLoggingMask & Peers.LOGGING_MASK_NON200_RESPONSES) != 0) {
log += " >>> Peer responded with HTTP " + connection.getResponseCode() + " code!";
showLog = true;
}
if (state == State.CONNECTED) {
setState(State.DISCONNECTED);
} else {
setState(State.NON_CONNECTED);
}
response = null;
}
} catch (RuntimeException|IOException e) {
if (! (e instanceof UnknownHostException || e instanceof SocketTimeoutException || e instanceof SocketException)) {
Logger.logDebugMessage("Error sending JSON request", e);
}
if ((Peers.communicationLoggingMask & Peers.LOGGING_MASK_EXCEPTIONS) != 0) {
log += " >>> " + e.toString();
showLog = true;
}
if (state == State.CONNECTED) {
setState(State.DISCONNECTED);
}
response = null;
}
if (showLog) {
Logger.logMessage(log + "\n");
}
if (connection != null) {
connection.disconnect();
}
return response;
}
@Override
public int compareTo(Peer o) {
if (getWeight() > o.getWeight()) {
return -1;
} else if (getWeight() < o.getWeight()) {
return 1;
}
return getPeerAddress().compareTo(o.getPeerAddress());
}
void connect() {
JSONObject response = send(Peers.myPeerInfoRequest);
if (response != null) {
application = (String)response.get("application");
setVersion((String) response.get("version"));
platform = (String)response.get("platform");
shareAddress = Boolean.TRUE.equals(response.get("shareAddress"));
String newAnnouncedAddress = Convert.emptyToNull((String)response.get("announcedAddress"));
if (newAnnouncedAddress != null && ! newAnnouncedAddress.equals(announcedAddress)) {
// force verification of changed announced address
setState(Peer.State.NON_CONNECTED);
setAnnouncedAddress(newAnnouncedAddress);
return;
}
if (announcedAddress == null) {
setAnnouncedAddress(peerAddress);
//Logger.logDebugMessage("Connected to peer without announced address, setting to " + peerAddress);
}
if (analyzeHallmark(announcedAddress, (String)response.get("hallmark"))) {
setState(State.CONNECTED);
Peers.updateAddress(this);
} else {
blacklist();
}
lastUpdated = Nxt.getEpochTime();
} else {
setState(State.NON_CONNECTED);
}
}
boolean analyzeHallmark(String address, final String hallmarkString) {
if (hallmarkString == null && this.hallmark == null) {
return true;
}
if (this.hallmark != null && this.hallmark.getHallmarkString().equals(hallmarkString)) {
return true;
}
if (hallmarkString == null) {
this.hallmark = null;
return true;
}
try {
URI uri = new URI("http://" + address.trim());
String host = uri.getHost();
Hallmark hallmark = Hallmark.parseHallmark(hallmarkString);
if (!hallmark.isValid()
|| !(hallmark.getHost().equals(host) || InetAddress.getByName(host).equals(InetAddress.getByName(hallmark.getHost())))) {
//Logger.logDebugMessage("Invalid hallmark for " + host + ", hallmark host is " + hallmark.getHost());
return false;
}
this.hallmark = hallmark;
long accountId = Account.getId(hallmark.getPublicKey());
List<PeerImpl> groupedPeers = new ArrayList<>();
int mostRecentDate = 0;
long totalWeight = 0;
for (PeerImpl peer : Peers.allPeers) {
if (peer.hallmark == null) {
continue;
}
if (accountId == peer.hallmark.getAccountId()) {
groupedPeers.add(peer);
if (peer.hallmark.getDate() > mostRecentDate) {
mostRecentDate = peer.hallmark.getDate();
totalWeight = peer.getHallmarkWeight(mostRecentDate);
} else {
totalWeight += peer.getHallmarkWeight(mostRecentDate);
}
}
}
for (PeerImpl peer : groupedPeers) {
peer.adjustedWeight = Constants.MAX_BALANCE_NXT * peer.getHallmarkWeight(mostRecentDate) / totalWeight;
Peers.notifyListeners(peer, Peers.Event.WEIGHT);
}
return true;
} catch (UnknownHostException ignore) {
} catch (URISyntaxException | RuntimeException e) {
Logger.logDebugMessage("Failed to analyze hallmark for peer " + address + ", " + e.toString(), e);
}
return false;
}
private int getHallmarkWeight(int date) {
if (hallmark == null || ! hallmark.isValid() || hallmark.getDate() != date) {
return 0;
}
return hallmark.getWeight();
}
}
|
package analysis.fba;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import org.sbml.jsbml.ext.fbc.FBCModelPlugin;
import org.sbml.jsbml.ext.fbc.FluxBound;
import org.sbml.jsbml.ext.fbc.Objective.Type;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.SBMLDocument;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
import biomodel.util.SBMLutilities;
import com.joptimizer.optimizers.*;
public class FluxBalanceAnalysis {
private String root;
private String sbmlFileName;
private SBMLDocument sbml;
private FBCModelPlugin fbc;
private double absError;
private HashMap<String,Double> fluxes;
public FluxBalanceAnalysis(String root,String sbmlFileName,double absError) {
this.root = root;
this.sbmlFileName = sbmlFileName;
this.absError = absError;
fluxes = new HashMap<String,Double>();
sbml = SBMLutilities.readSBML(root + this.sbmlFileName);
fbc = SBMLutilities.getFBCModelPlugin(sbml.getModel());
}
public static String vectorToString(double[] objective, HashMap<String,Integer> reactionIndex) {
String result = "";
for (String reaction : reactionIndex.keySet()) {
double value = objective[reactionIndex.get(reaction)];
if (value == 1) {
if (!result.equals("")) result += " + ";
result += reaction;
} else if (value == -1) {
if (!result.equals("")) result += " + ";
result += "-" + reaction;
} else if (value != 0) {
if (!result.equals("")) result += " + ";
result += value + "*" + reaction;
}
}
return result;
}
public int PerformFluxBalanceAnalysis(){
if (fbc == null) return -1;
if (fbc.getNumObjective()==0) return -11;
if (fbc.getActiveObjective()==null || fbc.getActiveObjective().equals("")) return -12; //TODO: what if missing active?
HashMap<String, Integer> reactionIndex = new HashMap<String, Integer>();
int kp = 0;
for(int l =0;l<fbc.getListOfFluxBounds().size();l++){
if(!reactionIndex.containsKey(fbc.getFluxBound(l).getReaction())){
reactionIndex.put(fbc.getFluxBound(l).getReaction(), kp);
kp++;
}
}
for (int i = 0; i < fbc.getListOfObjectives().size(); i++) {
if (!fbc.getActiveObjective().equals(fbc.getObjective(i).getId())) continue;
double [] objective = new double[sbml.getModel().getReactionCount()];
for (int j = 0; j < fbc.getObjective(i).getListOfFluxObjectives().size(); j++) {
if (reactionIndex.get(fbc.getObjective(i).getListOfFluxObjectives().get(j).getReaction())==null) {
// no flux bound on objective
return -9;
}
if (fbc.getObjective(i).getType().equals(Type.MINIMIZE)) {
objective [reactionIndex.get(fbc.getObjective(i).getListOfFluxObjectives().get(j).getReaction())] = fbc.getObjective(i).getListOfFluxObjectives().get(j).getCoefficient();
} else {
objective [reactionIndex.get(fbc.getObjective(i).getListOfFluxObjectives().get(j).getReaction())] = (-1)*fbc.getObjective(i).getListOfFluxObjectives().get(j).getCoefficient();
}
}
//System.out.println("Minimize: " + vectorToString(objective,reactionIndex));
//System.out.println("Subject to:");
double [] lowerBounds = new double[sbml.getModel().getReactionCount()];
double [] upperBounds = new double[sbml.getModel().getReactionCount()];
double minLb = LPPrimalDualMethod.DEFAULT_MIN_LOWER_BOUND;
double maxUb = LPPrimalDualMethod.DEFAULT_MAX_UPPER_BOUND;
int m = 0;
for (int j = 0; j < fbc.getListOfFluxBounds().size(); j++) {
FluxBound bound = fbc.getFluxBound(j);
//double R [] = new double [reactionIndex.size()];
double boundVal = bound.getValue();
if (Double.isInfinite(boundVal) && boundVal > 0) boundVal = 10;
if(bound.getOperation().equals(FluxBound.Operation.GREATER_EQUAL)){
if (Double.isInfinite(boundVal)) boundVal = minLb;
lowerBounds[reactionIndex.get(bound.getReaction())] = boundVal;
//R[reactionIndex.get(bound.getReaction())]=1;
//System.out.println(" " + vectorToString(R,reactionIndex) + " >= " + boundVal);
}
else if(bound.getOperation().equals(FluxBound.Operation.LESS_EQUAL)){
if (Double.isInfinite(boundVal)) boundVal = maxUb;
upperBounds[reactionIndex.get(bound.getReaction())] = boundVal;
//R[reactionIndex.get(bound.getReaction())]=1;
//System.out.println(" " + vectorToString(R,reactionIndex) + " <= " + boundVal);
}
else if(bound.getOperation().equals(FluxBound.Operation.EQUAL)){
lowerBounds[reactionIndex.get(bound.getReaction())] = boundVal;
upperBounds[reactionIndex.get(bound.getReaction())] = boundVal;
//R[reactionIndex.get(bound.getReaction())]=1;
//System.out.println(" " + vectorToString(R,reactionIndex) + " == " + boundVal);
}
}
m = 0;
int nonBoundarySpeciesCount = 0;
for (int j = 0; j < sbml.getModel().getSpeciesCount(); j++) {
if (!sbml.getModel().getSpecies(j).getBoundaryCondition()) nonBoundarySpeciesCount++;
}
double[][] stoch = new double [nonBoundarySpeciesCount][(sbml.getModel().getReactionCount())];
double[] zero = new double [nonBoundarySpeciesCount];
for (int j = 0; j < sbml.getModel().getSpeciesCount(); j++) {
Species species = sbml.getModel().getSpecies(j);
if (species.getBoundaryCondition()) continue;
zero[m] = 0;
for (int k = 0; k < sbml.getModel().getReactionCount(); k++) {
Reaction r = sbml.getModel().getReaction(k);
if (reactionIndex.get(r.getId())==null) {
// reaction missing flux bound
return -10;
}
for (int l = 0; l < r.getReactantCount(); l++) {
SpeciesReference sr = r.getReactant(l);
if (sr.getSpecies().equals(species.getId())) {
stoch[m][(reactionIndex.get(r.getId()))]=(-1)*sr.getStoichiometry();
}
}
for (int l = 0; l < r.getProductCount(); l++) {
SpeciesReference sr = r.getProduct(l);
if (sr.getSpecies().equals(species.getId())) {
stoch[m][(reactionIndex.get(r.getId()))]=sr.getStoichiometry();
}
}
}
m++;
}
//optimization problem
LPOptimizationRequest or = new LPOptimizationRequest();
//or.setDumpProblem(true);
or.setC(objective);
or.setA(stoch);
or.setB(zero);
or.setLb(lowerBounds);
or.setUb(upperBounds);
or.setTolerance(absError);
or.setToleranceFeas(absError);
//optimization
LPPrimalDualMethod opt = new LPPrimalDualMethod();
opt.setLPOptimizationRequest(or);
try {
int error = opt.optimize();
File f = new File(root + "sim-rep.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
double [] sol = opt.getLPOptimizationResponse().getSolution();
double objkVal = 0;
double objkCo = 0;
for (int j = 0; j < fbc.getObjective(i).getListOfFluxObjectives().size(); j++) {
objkCo = fbc.getObjective(i).getListOfFluxObjectives().get(j).getCoefficient();
double scale = Math.round(1/absError);
objkVal += Math.round(objkCo*sol[reactionIndex.get(fbc.getObjective(i).getListOfFluxObjectives().get(j).getReaction())] * scale) / scale;
}
String firstLine = ("#total Objective");
String secondLine = ("100 " + objkVal);
for (String reaction : reactionIndex.keySet()) {
double value = sol[reactionIndex.get(reaction)];
double scale = Math.round(1/absError);
value = Math.round(value * scale) / scale;
// System.out.println(reaction + " = " + value);
firstLine += (" " + reaction);
secondLine += (" "+ value);
fluxes.put(reaction, value);
}
bw.write(firstLine);
bw.write("\n");
bw.write(secondLine);
bw.write("\n");
bw.close();
return error;
} catch (Exception e) {
File f = new File(root + "sim-rep.txt");
if (f.exists()) {
f.delete();
}
if (e.getMessage().equals("initial point must be strictly feasible")) return -2;
else if (e.getMessage().equals("infeasible problem")) return -3;
else if (e.getMessage().equals("singular KKT system")) return -4;
else if (e.getMessage().equals("matrix must have at least one row")) return -5;
else if (e.getMessage().equals("matrix is singular")) return -6;
else if (e.getMessage().equals("Equalities matrix A must have full rank")) return -7;
else {
System.out.println(e.getMessage());
return -8;
}
}
}
return -13;
}
public HashMap<String, Double> getFluxes() {
return fluxes;
}
}
|
package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class MainPanel extends JPanel {
private final JTextPane editor1 = new JTextPane();
private final JEditorPane editor2 = new JEditorPane();
public MainPanel() {
super(new BorderLayout());
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontSize(attr, 32);
SimpleAttributeSet a = new SimpleAttributeSet();
StyleConstants.setLineSpacing(a, .5f);
//StyleConstants.setSpaceAbove(a, 5.0f);
//StyleConstants.setSpaceBelow(a, 5.0f);
//StyleConstants.setLeftIndent(a, 5.0f);
//StyleConstants.setRightIndent(a, 5.0f);
editor1.setParagraphAttributes(a, true);
editor1.setText("JTextPane, StyleConstants.setLineSpacing(...);\naaaaaaaa");
setDummyText(editor1, "1234567890", attr);
// StyleSheet styleSheet = new StyleSheet();
// styleSheet.addRule("body {font-size: 24pt; line-height: 2.0}"); //XXX
// HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
// htmlEditorKit.setStyleSheet(styleSheet);
// editor1.setEditorKit(htmlEditorKit);
// editor1.setText("<html><body>12341234<br />asdf_fASdfasf_fasdf_affffFSDdfasdf<br />nasdfasFasdf<font size='32'>12341234<br />asdfasdf</font></body></html>");
editor2.setEditorKit(new BottomInsetEditorKit());
editor2.setText("JEditorPane, BottomInsetEditorKit\nbbbbbbb");
setDummyText(editor2, "0987654321\nasdf", attr);
final JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setTopComponent(new JScrollPane(editor1));
sp.setBottomComponent(new JScrollPane(editor2));
sp.setResizeWeight(0.5);
add(sp);
setPreferredSize(new Dimension(320, 240));
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
sp.setDividerLocation(sp.getSize().height/2);
}
});
}
private static void setDummyText(JEditorPane editor, String str, MutableAttributeSet attr) {
Document doc = editor.getDocument();
try{
doc.insertString(doc.getLength(), str, attr);
editor.setCaretPosition(doc.getLength());
}catch(BadLocationException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class BottomInsetEditorKit extends StyledEditorKit {
@Override public ViewFactory getViewFactory() {
return new ViewFactory() {
@Override public View create(Element elem) {
String kind = elem.getName();
if(kind!=null) {
if(kind.equals(AbstractDocument.ContentElementName)) {
return new LabelView(elem);
}else if(kind.equals(AbstractDocument.ParagraphElementName)) {
return new javax.swing.text.ParagraphView(elem) {
@Override protected short getBottomInset() {
return 5;
}
};
}else if(kind.equals(AbstractDocument.SectionElementName)) {
return new BoxView(elem, View.Y_AXIS);
}else if(kind.equals(StyleConstants.ComponentElementName)) {
return new ComponentView(elem);
}else if(kind.equals(StyleConstants.IconElementName)) {
return new IconView(elem);
}
}
return new LabelView(elem);
}
};
}
}
|
package water;
import water.util.Log;
/**
* A UDP Rebooted packet: this node recently rebooted
*
* @author <a href="mailto:cliffc@h2o.ai"></a>
* @version 1.0
*/
class UDPRebooted extends UDP {
static enum T {
none,
reboot,
shutdown,
oom,
error,
locked,
mismatch;
void send(H2ONode target) {
assert this != none;
new AutoBuffer(target,udp.rebooted._prior).putUdp(udp.rebooted).put1(ordinal()).close();
}
void broadcast() { send(H2O.SELF); }
}
static void checkForSuicide(int first_byte, AutoBuffer ab) {
if( first_byte != UDP.udp.rebooted.ordinal() ) return;
int type = ab.get1();
suicide( T.values()[type], ab._h2o);
}
public static class ShutdownTsk extends DTask<ShutdownTsk> {
final H2ONode _killer;
final int _timeout;
final transient boolean [] _confirmations;
final int _nodeId;
public ShutdownTsk(H2ONode killer, int nodeId, int timeout, boolean [] confirmations){
_nodeId = nodeId;
_killer = killer;
_timeout = timeout;
_confirmations = confirmations;
}
@Override public byte priority(){
return H2O.GUI_PRIORITY;
}
transient boolean _didShutDown;
private synchronized void doShutdown(int exitCode, String msg){
if(_didShutDown)return;
Log.info(msg);
H2O.closeAll();
H2O.exit(exitCode);
}
@Override
protected void compute2() {
Log.info("Orderly shutdown from " + _killer);
// start a separate thread which will force termination after timeout expires (in case we don't get ack ack in time)
new Thread(){
@Override public void run(){
try {Thread.sleep(_timeout);} catch (InterruptedException e) {}
doShutdown(0,"Orderly shutdown may not have been acknowledged to " + _killer + " (no ackack), still exiting with exit code 0.");
}
}.start();
tryComplete();
}
@Override public void onAck(){
_confirmations[_nodeId] = true;
}
@Override public void onAckAck(){
doShutdown(0,"Orderly shutdown acknowledged to " + _killer + ", exiting with exit code 0.");
}
}
static void suicide( T cause, final H2ONode killer ) {
String m;
switch( cause ) {
case none: return;
case reboot: return;
case shutdown:
Log.warn("Orderly shutdown should be handled via ShutdownTsk. Message is from outside of the cloud? Ignoring it.");
return;
case oom: m = "Out of Memory, Heap Space exceeded, increase Heap Size,"; break;
case error: m = "Error leading to a cloud kill"; break;
case locked: m = "Attempting to join an H2O cloud that is no longer accepting new H2O nodes"; break;
case mismatch: m = "Attempting to join an H2O cloud with a different H2O version (is H2O already running?)"; break;
default: m = "Received kill " + cause; break;
}
H2O.closeAll();
Log.err(m+" from "+killer);
H2O.die("Exiting.");
}
@Override AutoBuffer call(AutoBuffer ab) {
checkForSuicide(udp.rebooted.ordinal(),ab);
if( ab._h2o != null )
ab._h2o.rebooted();
return ab;
}
// Pretty-print bytes 1-15; byte 0 is the udp_type enum
@Override String print16( AutoBuffer ab ) {
ab.getPort();
return T.values()[ab.get1()].toString();
}
}
|
package water.cascade;
import water.*;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import java.util.ArrayList;
/**
* Each node in the syntax tree knows how to parse a piece of text from the passed tree.
*/
abstract public class AST extends Iced {
AST[] _asts;
AST parse_impl(Exec e) { throw H2O.fail("Missing parse_impl for "+this.getClass()); }
abstract void exec(Env e);
abstract String value();
abstract int type();
public int numChildren() { return _asts.length; } // Must "apply" each arg, then put the results into ASTOp/UDF
/**
* Walk an AST and execute.
*/
Env treeWalk(Env e) {
// First check if we're a top-level node of type astop
if (this instanceof ASTOp) {
if (this instanceof ASTBinOp) {
// Exec the right branch
_asts[1].treeWalk(e);
// Exec the left branch
_asts[0].treeWalk(e);
// Perform the binary operation
((ASTBinOp) this).apply(e);
} else if (this instanceof ASTUniPrefixOp) {
for (int i = 0; i < _asts.length; ++i) _asts[i].treeWalk(e);
((ASTUniPrefixOp) this).apply(e);
} else if (this instanceof ASTReducerOp) {
for (int i = 0; i < _asts.length; ++i) _asts[i].treeWalk(e);
((ASTReducerOp) this).apply(e);
} else if (this instanceof ASTLs) {
((ASTLs) this).apply(e);
} else {
throw H2O.fail("Unknown AST: " + this.getClass());
// TODO: do the udf op thing: capture env...
}
// Check if there's an assignment
} else if (this instanceof ASTAssign) {
// Exec the right branch
_asts[1].treeWalk(e);
// Do the assignment
this.exec(e); // Special case exec => apply for assignment
// Check if we have an ID node (can be an argument, or part of an assignment).
} else if (this instanceof ASTId) {
ASTId id = (ASTId) this;
assert id.isValid();
if (id.isLookup()) {
// lookup the ID and return an AST
AST ast = e.lookup(id);
e.put(id._id, ast.type(), id._id);
ast.exec(e);
} else if (id.isSet()) {
e.put(((ASTId) this)._id, Env.ID, "");
id.exec(e);
} else {
throw H2O.fail("Got a bad identifier: '" + id.value() + "'. It has no type '!' or '$'.");
}
// Check if we have a slice.
} else if(this instanceof ASTSlice) {
_asts[0].treeWalk(e); // push hex
_asts[1].treeWalk(e); // push rows
_asts[2].treeWalk(e); // push cols
this.exec(e); // do the slice
// Check if String, Num, Null, Series, Key, Span, or Frame
} else if (this instanceof ASTString || this instanceof ASTNum || this instanceof ASTNull ||
this instanceof ASTSeries || this instanceof ASTKey || this instanceof ASTSpan ||
this._asts[0] instanceof ASTFrame) { this.exec(e); }
else { throw H2O.fail("Unknown AST: " + this.getClass());}
return e;
}
protected StringBuilder indent( StringBuilder sb, int d ) {
for( int i=0; i<d; i++ ) sb.append(" ");
return sb.append(' ');
}
StringBuilder toString( StringBuilder sb, int d ) { return indent(sb,d).append(this); }
}
class ASTId extends AST {
final String _id;
final char _type; // either '$' or '!'
ASTId(char type, String id) { _type = type; _id = id; }
ASTId parse_impl(Exec E) { return new ASTId(_type, E.parseID()); }
@Override public String toString() { return _type+_id; }
@Override void exec(Env e) { e.push(new ValId(_type, _id)); } // should this be H2O.fail() ??
@Override int type() { return Env.ID; }
@Override String value() { return _id; }
boolean isSet() { return _type == '!'; }
boolean isLookup() { return _type == '$'; }
boolean isValid() { return isSet() || isLookup(); }
}
class ASTKey extends AST {
final String _key;
ASTKey(String key) { _key = key; }
ASTKey parse_impl(Exec E) { return new ASTKey(E.parseID()); }
@Override public String toString() { return _key; }
@Override void exec(Env e) { (new ASTFrame(_key)).exec(e); }
@Override int type () { return Env.NULL; }
@Override String value() { return _key; }
}
class ASTFrame extends AST {
final String _key;
final Frame _fr;
ASTFrame(Frame fr) { _key = null; _fr = fr; }
ASTFrame(String key) {
Key k = Key.make(key);
if (DKV.get(k) == null) throw H2O.fail("Key "+ key +" no longer exists in the KV store!");
_key = key;
_fr = k.get();
}
@Override public String toString() { return "Frame with key " + _key + ". Frame: :" +_fr.toString(); }
@Override void exec(Env e) { e._locked.add(Key.make(_key)); e.addKeys(_fr); e.push(new ValFrame(_fr)); }
@Override int type () { return Env.ARY; }
@Override String value() { return _key; }
}
class ASTNum extends AST {
final double _d;
ASTNum(double d) { _d = d; }
ASTNum parse_impl(Exec E) { return new ASTNum(Double.valueOf(E.parseID())); }
@Override public String toString() { return Double.toString(_d); }
@Override void exec(Env e) { e.push(new ValNum(_d)); }
@Override int type () { return Env.NUM; }
@Override String value() { return Double.toString(_d); }
double dbl() { return _d; }
}
/**
* ASTSpan parses phrases like 1:10.
*/
class ASTSpan extends AST {
final long _min; final long _max;
final ASTNum _ast_min; final ASTNum _ast_max;
boolean _isCol; boolean _isRow;
ASTSpan(ASTNum min, ASTNum max) { _ast_min = min; _ast_max = max; _min = (long)min._d; _max = (long)max._d; }
ASTSpan parse_impl(Exec E) {
AST l = E.parse();
AST r = E.skipWS().parse();
return new ASTSpan((ASTNum)l, (ASTNum)r);
}
boolean contains(long a) {
if (all_neg()) return _max <= a && a <= _min;
return _min <= a && a <= _max;
}
boolean isColSelector() { return _isCol; }
boolean isRowSelector() { return _isRow; }
void setSlice(boolean row, boolean col) { _isRow = row; _isCol = col; }
@Override void exec(Env e) { ValSpan v = new ValSpan(_ast_min, _ast_max); v.setSlice(_isRow, _isCol); e.push(v); }
@Override String value() { return null; }
@Override int type() { return Env.SPAN; }
@Override public String toString() { return _min + ":" + _max; }
long[] toArray() {
long[] res = new long[(int)_max - (int)_min + 1];
long min = _min;
for (int i = 0; i < res.length; ++i) res[i] = min++;
return res;
}
boolean all_neg() { return _min < 0; }
boolean all_pos() { return !all_neg(); }
}
class ASTSeries extends AST {
final long[] _idxs;
final ASTSpan[] _spans;
boolean _isCol;
boolean _isRow;
ASTSeries(long[] idxs, ASTSpan[] spans) {
_idxs = idxs;
_spans = spans;
}
ASTSeries parse_impl(Exec E) {
ArrayList<Long> l_idxs = new ArrayList<>();
ArrayList<ASTSpan> s_spans = new ArrayList<>();
String[] strs = E.parseString('}').split(";");
for (String s : strs) {
if (s.charAt(0) == '(') {
s_spans.add((ASTSpan) (new Exec(s, null)).parse());
} else l_idxs.add(Long.valueOf(s));
}
long[] idxs = new long[l_idxs.size()];
ASTSpan[] spans = new ASTSpan[s_spans.size()];
for (int i = 0; i < idxs.length; ++i) idxs[i] = l_idxs.get(i);
for (int i = 0; i < spans.length; ++i) spans[i] = s_spans.get(i);
return new ASTSeries(idxs, spans);
}
boolean contains(long a) {
if (_spans != null)
for (ASTSpan s : _spans) if (s.contains(a)) return true;
if (_idxs != null)
for (long l : _idxs) if (l == a) return true;
return false;
}
boolean isColSelector() { return _isCol; }
boolean isRowSelector() { return _isRow; }
void setSlice(boolean row, boolean col) {
_isRow = row;
_isCol = col;
}
@Override
void exec(Env e) {
ValSeries v = new ValSeries(_idxs, _spans);
v.setSlice(_isRow, _isCol);
e.push(v);
}
@Override String value() { return null; }
@Override int type() { return Env.SERIES; }
@Override
public String toString() {
String res = "c(";
if (_spans != null) {
for (ASTSpan s : _spans) {
res += s.toString();
res += ",";
}
if (_idxs == null) res = res.substring(0, res.length() - 1); // remove last comma?
}
if (_idxs != null) {
for (long l : _idxs) {
res += l;
res += ",";
}
res = res.substring(0, res.length() - 1); // remove last comma.
}
res += ")";
return res;
}
long[] toArray() {
int res_length = 0;
if (_spans != null) for (ASTSpan s : _spans) res_length += (int) s._max - (int) s._min + 1;
if (_idxs != null) res_length += _idxs.length;
long[] res = new long[res_length];
int cur = 0;
if (_spans != null) {
for (ASTSpan s : _spans) {
long[] l = s.toArray();
for (int i = 0; i < l.length; ++i) res[cur++] = l[i];
}
}
if (_idxs != null) {
for (int i = 0; i < _idxs.length; ++i) res[cur++] = _idxs[i];
}
return res;
}
}
class ASTString extends AST {
final String _s;
final char _eq;
ASTString(char eq, String s) { _eq = eq; _s = s; }
ASTString parse_impl(Exec E) { return new ASTString(_eq, E.parseString(_eq)); }
@Override public String toString() { return _s; }
@Override void exec(Env e) { e.push(new ValStr(_s)); }
@Override int type () { return Env.STR; }
@Override String value() { return _s; }
}
class ASTNull extends AST {
ASTNull() {}
@Override void exec(Env e) { e.push(new ValNull());}
@Override String value() { return null; }
@Override int type() { return Env.NULL; }
}
class ASTAssign extends AST {
ASTAssign parse_impl(Exec E) {
AST l = E.parse(); // parse the ID on the left, or could be a column, or entire frame, or a row
AST r = E.skipWS().parse(); // parse double, String, or Frame on the right
ASTAssign res = (ASTAssign)clone();
res._asts = new AST[]{l,r};
return res;
}
@Override int type () { throw H2O.fail(); }
@Override String value() { throw H2O.fail(); }
@Override void exec(Env e) {
// Check if lhs is ID, update the symbol table; Otherwise it's a slice!
if( this._asts[0] instanceof ASTId ) {
ASTId id = (ASTId)this._asts[0];
assert id.isSet() : "Expected to set result into the LHS!.";
if (e.isAry()) {
Frame f = e.pop0Ary(); // pop without lowering counts
Key k = Key.make(id._id);
Frame fr = new Frame(k, f.names(), f.vecs());
DKV.put(k, fr);
e._locked.add(fr._key);
e.push(new ValFrame(fr));
e.put(id._id, Env.ARY, id._id);
}
}
// Peel apart a slice assignment
// ASTSlice slice = (ASTSlice)_lhs;
// ASTId id = (ASTId)slice._ast;
// assert id._depth==0; // Can only modify in the local scope.
// // Simple assignment using the slice syntax
// if( slice._rows==null & slice._cols==null ) {
// env.tos_into_slot(id._depth,id._num,id._id);
// return;
// // Pull the LHS off the stack; do not lower the refcnt
// Frame ary = env.frId(id._depth,id._num);
// // Pull the RHS off the stack; do not lower the refcnt
// Frame ary_rhs=null; double d=Double.NaN;
// if( env.isDbl() ) d = env._d[env._sp-1];
// else ary_rhs = env.peekAry(); // Pop without deleting
// // Typed as a double ==> the row & col selectors are simple constants
// if( slice._t == Type.DBL ) { // Typed as a double?
// assert ary_rhs==null;
// long row = (long)((ASTNum)slice._rows)._d-1;
// int col = (int )((ASTNum)slice._cols)._d-1;
// Chunk c = ary.vecs()[col].chunkForRow(row);
// c.set(row,d);
// Futures fs = new Futures();
// c.close(c.cidx(),fs);
// fs.blockForPending();
// env.push(d);
// return;
// // Execute the slice LHS selection operators
// Object cols = ASTSlice.select(ary.numCols(),slice._cols,env);
// Object rows = ASTSlice.select(ary.numRows(),slice._rows,env);
// long[] cs1; long[] rs1;
// if(cols != null && rows != null && (cs1 = (long[])cols).length == 1 && (rs1 = (long[])rows).length == 1) {
// assert ary_rhs == null;
// long row = rs1[0]-1;
// int col = (int)cs1[0]-1;
// if(col >= ary.numCols() || row >= ary.numRows())
// throw H2O.unimpl();
// if(ary.vecs()[col].isEnum())
// ary.vecs()[col].set(row,d);
// env.push(d);
// return;
// // Partial row assignment?
// if( rows != null ) {
// // Only have partial row assignment
// if (cols == null) {
// // For every col at the range of indexes, set the value to be the rhs.
// // If the rhs is a double, then fill with doubles, NA where type is Enum.
// if (ary_rhs == null) {
// // Make a new Vec where each row to be written over has the value d
// final long[] rows0 = (long[]) rows;
// final double d0 = d;
// Vec v = new MRTask2() {
// @Override
// public void map(Chunk cs) {
// for (long er : rows0) {
// er = Math.abs(er) - 1; // 1-based -> 0-based
// if (er < cs._start || er > (cs._len + cs._start - 1)) continue;
// cs.set0((int) (er - cs._start), d0);
// }.doAll(ary.anyVec().makeZero()).getResult()._fr.anyVec();
// // MRTask over the lhs array
// new MRTask2() {
// @Override public void map(Chunk[] chks) {
// // Replace anything that is non-zero in the rep_vec.
// Chunk rep_vec = chks[chks.length-1];
// for (int row = 0; row < chks[0]._len; ++row) {
// if (rep_vec.at0(row) == 0) continue;
// for (Chunk chk : chks) {
// if (chk._vec.isEnum()) { chk.setNA0(row); } else { chk.set0(row, d0); }
// }.doAll(ary.numCols(), ary.add("rep_vec",v));
// UKV.remove(v._key);
// UKV.remove(ary.remove(ary.numCols()-1)._key);
// // If the rhs is an array, then fail if `height` of the rhs != rows.length. Otherwise, fetch-n-fill! (expensive)
// } else {
// throw H2O.unimpl();
// // Have partial row and col assignment
// } else {
// throw H2O.unimpl();
//// throw H2O.unimpl();
// } else {
// assert cols != null; // all/all assignment uses simple-assignment
// // Convert constant into a whole vec
// if (ary_rhs == null)
// ary_rhs = new Frame(ary.anyVec().makeCon(d));
// // Make sure we either have 1 col (repeated) or exactly a matching count
// long[] cs = (long[]) cols; // Columns to act on
// if (ary_rhs.numCols() != 1 &&
// ary_rhs.numCols() != cs.length)
// // Replace the LHS cols with the RHS cols
// Vec rvecs[] = ary_rhs.vecs();
// Futures fs = new Futures();
// for (int i = 0; i < cs.length; i++) {
// int cidx = (int) cs[i] - 1; // Convert 1-based to 0-based
// Vec rv = env.addRef(rvecs[rvecs.length == 1 ? 0 : i]);
// if (cidx == ary.numCols()) {
// if (!rv.group().equals(ary.anyVec().group())) {
// env.subRef(rv);
// rv = ary.anyVec().align(rv);
// env.addRef(rv);
// ary.add("C" + String.valueOf(cidx + 1), rv); // New column name created with 1-based index
// else {
// if (!(rv.group().equals(ary.anyVec().group())) && rv.length() == ary.anyVec().length()) {
// env.subRef(rv);
// rv = ary.anyVec().align(rv);
// env.addRef(rv);
// fs = env.subRef(ary.replace(cidx, rv), fs);
// fs.blockForPending();
// // After slicing, pop all expressions (cannot lower refcnt till after all uses)
// int narg = 0;
// if( rows!= null ) narg++;
// if( cols!= null ) narg++;
// env.pop(narg);
}
// String argName() { return this._asts[0] instanceof ASTId ? ((ASTId)this._asts[0])._id : null; }
@Override public String toString() { return "="; }
// @Override public StringBuilder toString( StringBuilder sb, int d ) {
// indent(sb,d).append(this).append('\n');
// _lhs.toString(sb,d+1).append('\n');
// _eval.toString(sb,d+1);
// return sb;
}
// AST SLICE
class ASTSlice extends AST {
ASTSlice() {}
ASTSlice parse_impl(Exec E) {
AST hex = E.parse();
AST rows = E.skipWS().parse();
if (rows instanceof ASTString) rows = new ASTNull();
if (rows instanceof ASTSpan) ((ASTSpan) rows).setSlice(true, false);
if (rows instanceof ASTSeries) ((ASTSeries) rows).setSlice(true, false);
AST cols = E.skipWS().parse();
if (cols instanceof ASTString) cols = new ASTNull();
if (cols instanceof ASTSpan) ((ASTSpan) cols).setSlice(false, true);
if (cols instanceof ASTSeries) ((ASTSeries) cols).setSlice(false, true);
ASTSlice res = (ASTSlice) clone();
res._asts = new AST[]{hex,rows,cols};
return res;
}
@Override String value() { return null; }
@Override int type() { return 0; }
@Override void exec(Env env) {
// stack looks like: [....,hex,rows,cols], so pop, pop !
int cols_type = env.peekType();
Val cols = env.pop(); int rows_type = env.peekType();
Val rows = rows_type == Env.ARY ? env.pop0() : env.pop();
// Scalar load? Throws AIIOOB if out-of-bounds
if(cols_type == Env.NUM && rows_type == Env.NUM) {
// Known that rows & cols are simple positive constants.
// Use them directly, throwing a runtime error if OOB.
long row = (long)((ValNum)rows)._d;
int col = (int )((ValNum)cols)._d;
Frame ary=env.popAry();
if (ary.vecs()[col].isEnum()) { env.push(new ValStr(ary.vecs()[col].domain()[(int)ary.vecs()[col].at(row)])); }
else env.push( new ValNum(ary.vecs()[col].at(row)));
env.cleanup(ary);
} else {
// Else It's A Big Copy. Some Day look at proper memory sharing,
// disallowing unless an active-temp is available, etc.
// Eval cols before rows (R's eval order).
Frame ary= env.peekAry(); // Get without popping
Object colSelect = select(ary.numCols(),cols,env, true);
Object rowSelect = select(ary.numRows(),rows,env, false);
Frame fr2 = ary.deepSlice(rowSelect,colSelect);
if (colSelect instanceof Frame) for (Vec v : ((Frame)colSelect).vecs()) Keyed.remove(v._key);
if (rowSelect instanceof Frame) for (Vec v : ((Frame)rowSelect).vecs()) Keyed.remove(v._key);
if( fr2 == null ) fr2 = new Frame(); // Replace the null frame with the zero-column frame
env.cleanup(ary, env.popAry(), rows_type == Env.ARY ? ((ValFrame)rows)._fr : null);
env.push(new ValFrame(fr2));
}
}
// Execute a col/row selection & return the selection. NULL means "all".
// Error to mix negatives & positive. Negative list is sorted, with dups
// removed. Positive list can have dups (which replicates cols) and is
// ordered. numbers. 1-based numbering; 0 is ignored & removed.
static Object select( long len, Val v, Env env, boolean isCol) {
if( v.type() == Env.NULL ) return null; // Trivial "all"
env.push(v);
long cols[];
if( env.isNum()) {
int col = (int)env.popDbl(); // Pop double; Silent truncation (R semantics)
if( col < 0 && col < -len ) col=0; // Ignore a non-existent column
if (col < 0) {
ValSeries s = new ValSeries(new long[]{col}, null);
s.setSlice(!isCol, isCol);
return select(len, s, env, isCol);
}
return new long[]{col};
}
if (env.isSeries()) {
ValSeries a = env.popSeries();
if (!a.isValid()) throw new IllegalArgumentException("Cannot mix negative and positive array selection.");
// if selecting out columns, build a long[] cols and return that.
if (a.isColSelector()) return a.toArray();
// Otherwise, we have rows selected: Construct a compatible "predicate" vec
Frame ary = env.peekAry();
Vec v0 = a.all_neg() ? ary.anyVec().makeCon(1) : ary.anyVec().makeZero();
final ValSeries a0 = a;
Frame fr = a0.all_neg()
? new MRTask() {
@Override public void map(Chunk cs) {
for (long i = cs.start(); i < cs.len() + cs.start(); ++i)
if (a0.contains(-i)) cs.set0((int) (i - cs.start() - 1), 0); // -1 for indexing
}
}.doAll(v0).getResult()._fr
: new MRTask() {
@Override public void map(Chunk cs) {
for (long i = cs.start(); i < cs.len() + cs.start(); ++i)
if (a0.contains(i)) cs.set0( (int)(i - cs.start()),1);
}
}.doAll(v0).getResult()._fr;
// Keyed.remove(v0._key);
return fr;
}
if (env.isSpan()) {
ValSpan a = env.popSpan();
if (!a.isValid()) throw new IllegalArgumentException("Cannot mix negative and positive array selection.");
// if selecting out columns, build a long[] cols and return that.
if (a.isColSelector()) return a.toArray();
// Otherwise, we have rows selected: Construct a compatible "predicate" vec
Frame ary = env.peekAry();
final ValSpan a0 = a;
Vec v0 = a.all_neg() ? ary.anyVec().makeCon(1) : ary.anyVec().makeZero();
Frame fr = a0.all_neg()
? new MRTask() {
@Override public void map(Chunk cs) {
for (long i = cs.start(); i < cs.len() + cs.start(); ++i)
if (a0.contains(-i)) cs.set0((int) (i - cs.start() - 1), 0); // -1 for indexing
}
}.doAll(v0).getResult()._fr
: new MRTask() {
@Override public void map(Chunk cs) {
for (long i = cs.start(); i < cs.len() + cs.start(); ++i)
if (a0.contains(i)) cs.set0( (int)(i - cs.start()),1);
}
}.doAll(v0).getResult()._fr;
// Keyed.remove(v0._key);
return fr;
}
// Got a frame/list of results.
// Decide if we're a toss-out or toss-in list
Frame ary = env.peekAry(); // Peek-frame
if( ary.numCols() != 1 ) throw new IllegalArgumentException("Selector must be a single column: "+ary.names());
Vec vec = ary.anyVec();
// Check for a matching column of bools.
if( ary.numRows() == len && vec.min()>=0 && vec.max()<=1 && vec.isInt() )
return ary; // Boolean vector selection.
// Convert single vector to a list of longs selecting rows
if(ary.numRows() > 10000000) throw H2O.fail("Unimplemented: Cannot explicitly select > 10000000 rows in slice.");
cols = MemoryManager.malloc8((int)ary.numRows());
for(int i = 0; i < cols.length; ++i){
if(vec.isNA(i))throw new IllegalArgumentException("Can not use NA as index!");
cols[i] = vec.at8(i);
}
return cols;
}
@Override public String toString() { return "[,]"; }
@Override public StringBuilder toString( StringBuilder sb, int d ) {
indent(sb,d).append(this).append('\n');
_asts[0].toString(sb,d+1).append("\n");
if( _asts[2]==null ) indent(sb,d+1).append("all\n");
else _asts[2].toString(sb,d+1).append("\n");
if( _asts[1]==null ) indent(sb,d+1).append("all");
else _asts[1].toString(sb,d+1);
return sb;
}
}
|
package org.bdgp.MMSlide;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Util {
/**
* Custom HashMap with support for pseudo-map literals.
* @param <K> The key type
* @param <V>
*/
@SuppressWarnings("serial")
public static class HashMap<K,V> extends java.util.HashMap<K,V> {
public HashMap() {
super();
}
// Various chained putters
public HashMap<K,V> with(K k, V v) { this.put(k, v); return this; }
public HashMap<K,V> and(K k, V v) { this.put(k, v); return this; }
public HashMap<K,V> o(K k, V v) { this.put(k, v); return this; }
public HashMap<K,V> _(K k, V v) { this.put(k, v); return this; }
// in-place merge
public Map<K,V> merge(Map<K,V> map) {
this.putAll(map);
return this;
}
}
// static methods for creating various HashMaps
public static <K,V> HashMap<K,V> map(K k, V v) {
return new HashMap<K,V>().with(k, v);
}
public static <K,V> HashMap<K,V> map(Map<K,V> m) {
HashMap<K,V> map = new HashMap<K,V>();
map.putAll(m);
return map;
}
public static HashMap<String,Object> set(String k, Object v) {
return new HashMap<String,Object>().with(k, v);
}
public static HashMap<String,Object> where(String k, Object v) {
return new HashMap<String,Object>().with(k, v);
}
public static HashMap<String,String> attr(String k, String v) {
return new HashMap<String,String>().with(k, v);
}
@SuppressWarnings("serial")
public static class ArrayList<V> extends java.util.ArrayList<V> {
public ArrayList() {
super();
}
public ArrayList<V> concat(List<V> l) {
this.addAll(l);
return this;
}
@SafeVarargs
final public ArrayList<V> push(V ... values) {
this.addAll(Arrays.asList(values));
return this;
}
}
/**
* Simple static function for list literals.
* @param values The list of things to turn into a list literal.
* @return
*/
@SafeVarargs
public static <V> List<V> list(V ... values) {
return Arrays.asList(values);
}
public static <V> List<V> list(List<V> l) {
List<V> list = new ArrayList<V>();
list.addAll(l);
return list;
}
/**
* String join helper function
* @param list The list of strings to join
* @param delim The string to put inbetween the lists
*/
public static String join(List<Object> list) {
return join("", list);
}
public static String join(Object ... list) {
return join("", Arrays.asList(list));
}
public static String join(String delim, Object ... list) {
return join(delim, Arrays.asList(list));
}
public static String join(String delim, List<Object> list) {
StringBuilder sb = new StringBuilder(list.size()>0? list.get(0).toString() : "");
for (int i = 1; i < list.size(); i++) {
sb.append(delim);
sb.append(list.get(i).toString());
}
return sb.toString();
}
public static void sleep(int minwait, int maxwait) {
try { Thread.sleep(minwait + (int)(Math.random()*(maxwait-minwait))); }
catch (InterruptedException e) { }
}
public static void sleep() {
sleep(1000,3000);
}
}
|
package ca.ualberta.cs.xpertsapp.model;
import java.util.ArrayList;
import java.util.List;
import ca.ualberta.cs.xpertsapp.MyApplication;
import ca.ualberta.cs.xpertsapp.interfaces.IObservable;
import ca.ualberta.cs.xpertsapp.interfaces.IObserver;
/**
* Represents a user
*/
public class User implements IObservable {
private String email;
private String name = "";
private String location = "";
private List<String> friends = new ArrayList<String>();
private List<String> services = new ArrayList<String>();
private List<String> trades = new ArrayList<String>();
// Constructor
protected User(String email) {
this.email = email;
}
// Get/Set
/**
* @return The Users email
*/
public String getEmail() {
return this.email;
}
/**
* @return the users name
*/
public String getName() {
if (this.name.equals(""))
return this.getEmail();
return this.name;
}
/**
* @param name the users new name
*/
public void setName(String name) {
if (!this.isEditable()) throw new AssertionError();
this.name = name;
this.notifyObservers();
}
/**
* @return the users location
*/
public String getLocation() {
return this.location;
}
/**
* @param location the users new location
*/
public void setLocation(String location) {
if (!this.isEditable()) throw new AssertionError();
this.location = location;
this.notifyObservers();
}
/**
* @return A List of the users friends
*/
public List<User> getFriends() {
List<User> friends = new ArrayList<User>();
for (String friendID : this.friends) {
friends.add(UserManager.sharedManager().getUser(friendID));
}
return friends;
}
/**
* @param friend The new friend
*/
public void addFriend(User friend) {
//if (!this.isEditable()) throw new AssertionError();
this.friends.add(friend.getEmail());
this.notifyObservers();
}
/**
* @param friend The old friend
*/
public void removeFriend(User friend) {
//if (!this.isEditable()) throw new AssertionError();
this.friends.remove(friend.getEmail());
this.notifyObservers();
}
/**
* @return A List of services
*/
public List<Service> getServices() {
List<Service> services = new ArrayList<Service>();
for (String service : this.services) {
Service s = ServiceManager.sharedManager().getService(service);
if (this.isEditable() || s.isShareable()) {
services.add(s);
}
}
return services;
}
/**
* @param service The new service
*/
public void addService(Service service) {
if (!this.isEditable()) throw new AssertionError();
this.services.add(service.getID());
if(!service.getOwner().equals(this)) {
service.setOwner(this.email);
}
ServiceManager.sharedManager().addService(service);
ServiceManager.sharedManager().notify(service);
this.notifyObservers();
}
/**
* @param service the old service
*/
public void removeService(String service) {
Service s = ServiceManager.sharedManager().getService(service);
if (!this.isEditable()) throw new AssertionError();
this.services.remove(service);
ServiceManager.sharedManager().deleteService(service);
ServiceManager.sharedManager().notify(s);
this.notifyObservers();
}
/**
* @return the number of trades proposed to the user that are waiting for their review
*/
public int newTrades() {
int count = 0;
for (Trade trade : this.getTrades()) {
if (trade.status == 0 && trade.getOwner() != this) {
++count;
}
}
return count;
}
/**
* @return A List of trades that user has participated in
*/
public List<Trade> getTrades() {
List<Trade> trades = new ArrayList<Trade>();
for (String trade : this.trades) {
trades.add(TradeManager.sharedManager().getTrade(trade));
}
return trades;
}
/**
* @param trade The new trade
*/
void addTrade(Trade trade) {
this.trades.add(trade.getID());
this.notifyObservers();
}
protected boolean isEditable() {
return Constants.isTest || this == MyApplication.getLocalUser();
}
// IObservable
private transient List<IObserver> observers = new ArrayList<IObserver>();
@Override
public void addObserver(IObserver observer) {
if (this.observers == null) {
this.observers = new ArrayList<IObserver>();
}
this.observers.add(observer);
}
@Override
public void removeObserver(IObserver observer) {
this.observers.remove(observer);
}
@Override
public void notifyObservers() {
for (IObserver observer : this.observers) {
observer.notify(this);
}
}
}
|
package txtParser;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class TxtParser {
public void readStream() {
Path path = Paths.get("c:/temp", "data.txt");
try (Stream<String> lines = Files.lines(path)) {
String str = path.toString();
String[] strs = str.split("\\|+");
for (String s : strs) {
System.out.println("Split..: " + s);
}
Pattern pattern = Pattern.compile("[^|]+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("Pattern:" + matcher.group());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.powsybl.action.dsl;
import com.powsybl.contingency.Contingency;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
public class ActionDb {
private final Map<String, Contingency> contingencies = new LinkedHashMap<>();
private final Map<String, Rule> rules = new LinkedHashMap<>();
private final Map<String, Action> actions = new LinkedHashMap<>();
public void addContingency(Contingency contingency) {
Objects.requireNonNull(contingency);
contingencies.put(contingency.getId(), contingency);
}
public Collection<Contingency> getContingencies() {
return contingencies.values();
}
public Collection<Action> getActions() {
return actions.values();
}
public Contingency getContingency(String id) {
Objects.requireNonNull(id);
Contingency contingency = contingencies.get(id);
if (contingency == null) {
throw new ActionDslException("Contingency '" + id + "' not found");
}
return contingency;
}
public void addRule(Rule rule) {
Objects.requireNonNull(rule);
String id = rule.getId();
if (rules.containsKey(id)) {
throw new ActionDslException("Rule '" + id + "' is defined several times");
}
rules.put(id, rule);
}
public Collection<Rule> getRules() {
return rules.values();
}
public void addAction(Action action) {
Objects.requireNonNull(action);
String id = action.getId();
if (actions.containsKey(id)) {
throw new ActionDslException("Action '" + id + "' is defined several times");
}
actions.put(id, action);
}
public Action getAction(String id) {
Objects.requireNonNull(id);
Action action = actions.get(id);
if (action == null) {
throw new ActionDslException("Action '" + id + "' not found");
}
return action;
}
/**
* Checks that actions referenced in rules are indeed defined.
*/
void checkUndefinedActions() {
//Collect actions referenced in rules
Set<String> referencedActionsIds = rules.values().stream().flatMap(r -> r.getActions().stream()).collect(Collectors.toSet());
//Check those actions are defined
String strActionIds = referencedActionsIds.stream()
.filter(id -> !actions.containsKey(id))
.collect(Collectors.joining(", "));
if (!strActionIds.isEmpty()) {
throw new ActionDslException("Actions [" + strActionIds + "] not found");
}
}
}
|
package org.hisp.dhis.android.core;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hisp.dhis.android.core.calls.AggregatedDataCall;
import org.hisp.dhis.android.core.calls.Call;
import org.hisp.dhis.android.core.calls.MetadataCall;
import org.hisp.dhis.android.core.calls.SingleDataCall;
import org.hisp.dhis.android.core.calls.TrackedEntityInstancePostCall;
import org.hisp.dhis.android.core.calls.TrackerDataCall;
import org.hisp.dhis.android.core.calls.TrackerEntitiesDataCall;
import org.hisp.dhis.android.core.category.CategoryCategoryComboLinkStore;
import org.hisp.dhis.android.core.category.CategoryCategoryComboLinkStoreImpl;
import org.hisp.dhis.android.core.category.CategoryCategoryOptionLinkStore;
import org.hisp.dhis.android.core.category.CategoryCategoryOptionLinkStoreImpl;
import org.hisp.dhis.android.core.category.CategoryComboHandler;
import org.hisp.dhis.android.core.category.CategoryComboQuery;
import org.hisp.dhis.android.core.category.CategoryComboService;
import org.hisp.dhis.android.core.category.CategoryComboStore;
import org.hisp.dhis.android.core.category.CategoryComboStoreImpl;
import org.hisp.dhis.android.core.category.CategoryHandler;
import org.hisp.dhis.android.core.category.CategoryOptionComboCategoryLinkStore;
import org.hisp.dhis.android.core.category.CategoryOptionComboCategoryLinkStoreImpl;
import org.hisp.dhis.android.core.category.CategoryOptionComboHandler;
import org.hisp.dhis.android.core.category.CategoryOptionComboStore;
import org.hisp.dhis.android.core.category.CategoryOptionComboStoreImpl;
import org.hisp.dhis.android.core.category.CategoryOptionHandler;
import org.hisp.dhis.android.core.category.CategoryOptionStore;
import org.hisp.dhis.android.core.category.CategoryOptionStoreImpl;
import org.hisp.dhis.android.core.category.CategoryQuery;
import org.hisp.dhis.android.core.category.CategoryService;
import org.hisp.dhis.android.core.category.CategoryStore;
import org.hisp.dhis.android.core.category.CategoryStoreImpl;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.common.DeletableStore;
import org.hisp.dhis.android.core.common.DictionaryTableHandler;
import org.hisp.dhis.android.core.common.GenericCallData;
import org.hisp.dhis.android.core.common.GenericHandler;
import org.hisp.dhis.android.core.common.IdentifiableObjectStore;
import org.hisp.dhis.android.core.common.ObjectStore;
import org.hisp.dhis.android.core.common.ObjectStyle;
import org.hisp.dhis.android.core.common.ObjectStyleHandler;
import org.hisp.dhis.android.core.common.ObjectStyleModel;
import org.hisp.dhis.android.core.common.ObjectStyleStore;
import org.hisp.dhis.android.core.common.ObjectWithoutUidStore;
import org.hisp.dhis.android.core.common.Payload;
import org.hisp.dhis.android.core.common.ValueTypeDeviceRenderingModel;
import org.hisp.dhis.android.core.common.ValueTypeDeviceRenderingStore;
import org.hisp.dhis.android.core.common.ValueTypeRendering;
import org.hisp.dhis.android.core.common.ValueTypeRenderingHandler;
import org.hisp.dhis.android.core.configuration.ConfigurationModel;
import org.hisp.dhis.android.core.data.api.FieldsConverterFactory;
import org.hisp.dhis.android.core.data.api.FilterConverterFactory;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
import org.hisp.dhis.android.core.dataelement.DataElement;
import org.hisp.dhis.android.core.dataelement.DataElementHandler;
import org.hisp.dhis.android.core.dataelement.DataElementModel;
import org.hisp.dhis.android.core.dataelement.DataElementStore;
import org.hisp.dhis.android.core.dataset.DataSetDataElementLinkModel;
import org.hisp.dhis.android.core.dataset.DataSetDataElementLinkStore;
import org.hisp.dhis.android.core.dataset.DataSetModel;
import org.hisp.dhis.android.core.dataset.DataSetOrganisationUnitLinkModel;
import org.hisp.dhis.android.core.dataset.DataSetOrganisationUnitLinkStore;
import org.hisp.dhis.android.core.dataset.DataSetParentCall;
import org.hisp.dhis.android.core.dataset.DataSetStore;
import org.hisp.dhis.android.core.datavalue.DataValueEndpointCall;
import org.hisp.dhis.android.core.datavalue.DataValueModel;
import org.hisp.dhis.android.core.datavalue.DataValueStore;
import org.hisp.dhis.android.core.enrollment.EnrollmentHandler;
import org.hisp.dhis.android.core.enrollment.EnrollmentStore;
import org.hisp.dhis.android.core.enrollment.EnrollmentStoreImpl;
import org.hisp.dhis.android.core.event.EventHandler;
import org.hisp.dhis.android.core.event.EventPostCall;
import org.hisp.dhis.android.core.event.EventService;
import org.hisp.dhis.android.core.event.EventStore;
import org.hisp.dhis.android.core.event.EventStoreImpl;
import org.hisp.dhis.android.core.imports.WebResponse;
import org.hisp.dhis.android.core.indicator.DataSetIndicatorLinkModel;
import org.hisp.dhis.android.core.indicator.DataSetIndicatorLinkStore;
import org.hisp.dhis.android.core.indicator.IndicatorModel;
import org.hisp.dhis.android.core.indicator.IndicatorStore;
import org.hisp.dhis.android.core.indicator.IndicatorTypeModel;
import org.hisp.dhis.android.core.indicator.IndicatorTypeStore;
import org.hisp.dhis.android.core.option.OptionSetHandler;
import org.hisp.dhis.android.core.option.OptionSetModel;
import org.hisp.dhis.android.core.option.OptionSetService;
import org.hisp.dhis.android.core.option.OptionSetStore;
import org.hisp.dhis.android.core.option.OptionStore;
import org.hisp.dhis.android.core.option.OptionStoreImpl;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitHandler;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitProgramLinkStore;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitProgramLinkStoreImpl;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitService;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitStore;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitStoreImpl;
import org.hisp.dhis.android.core.period.PeriodModel;
import org.hisp.dhis.android.core.period.PeriodStore;
import org.hisp.dhis.android.core.program.ProgramIndicatorStore;
import org.hisp.dhis.android.core.program.ProgramIndicatorStoreImpl;
import org.hisp.dhis.android.core.program.ProgramRuleActionStore;
import org.hisp.dhis.android.core.program.ProgramRuleActionStoreImpl;
import org.hisp.dhis.android.core.program.ProgramRuleStore;
import org.hisp.dhis.android.core.program.ProgramRuleStoreImpl;
import org.hisp.dhis.android.core.program.ProgramRuleVariableStore;
import org.hisp.dhis.android.core.program.ProgramRuleVariableStoreImpl;
import org.hisp.dhis.android.core.program.ProgramService;
import org.hisp.dhis.android.core.program.ProgramStageDataElementStore;
import org.hisp.dhis.android.core.program.ProgramStageDataElementStoreImpl;
import org.hisp.dhis.android.core.program.ProgramStageSectionProgramIndicatorLinkStore;
import org.hisp.dhis.android.core.program.ProgramStageSectionProgramIndicatorLinkStoreImpl;
import org.hisp.dhis.android.core.program.ProgramStageSectionStore;
import org.hisp.dhis.android.core.program.ProgramStageSectionStoreImpl;
import org.hisp.dhis.android.core.program.ProgramStageStore;
import org.hisp.dhis.android.core.program.ProgramStageStoreImpl;
import org.hisp.dhis.android.core.program.ProgramStore;
import org.hisp.dhis.android.core.program.ProgramStoreImpl;
import org.hisp.dhis.android.core.program.ProgramTrackedEntityAttributeStore;
import org.hisp.dhis.android.core.program.ProgramTrackedEntityAttributeStoreImpl;
import org.hisp.dhis.android.core.relationship.RelationshipTypeStore;
import org.hisp.dhis.android.core.relationship.RelationshipTypeStoreImpl;
import org.hisp.dhis.android.core.resource.ResourceHandler;
import org.hisp.dhis.android.core.resource.ResourceStore;
import org.hisp.dhis.android.core.resource.ResourceStoreImpl;
import org.hisp.dhis.android.core.systeminfo.SystemInfoService;
import org.hisp.dhis.android.core.systeminfo.SystemInfoStore;
import org.hisp.dhis.android.core.systeminfo.SystemInfoStoreImpl;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeStore;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeStoreImpl;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueHandler;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueStore;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueStoreImpl;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueHandler;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueStore;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueStoreImpl;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceEndPointCall;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceHandler;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceStore;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceStoreImpl;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityService;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityStore;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityStoreImpl;
import org.hisp.dhis.android.core.user.AuthenticatedUserStore;
import org.hisp.dhis.android.core.user.AuthenticatedUserStoreImpl;
import org.hisp.dhis.android.core.user.IsUserLoggedInCallable;
import org.hisp.dhis.android.core.user.LogOutUserCallable;
import org.hisp.dhis.android.core.user.User;
import org.hisp.dhis.android.core.user.UserAuthenticateCall;
import org.hisp.dhis.android.core.user.UserCredentialsHandler;
import org.hisp.dhis.android.core.user.UserCredentialsStore;
import org.hisp.dhis.android.core.user.UserCredentialsStoreImpl;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkStore;
import org.hisp.dhis.android.core.user.UserOrganisationUnitLinkStoreImpl;
import org.hisp.dhis.android.core.user.UserRoleStore;
import org.hisp.dhis.android.core.user.UserRoleStoreImpl;
import org.hisp.dhis.android.core.user.UserService;
import org.hisp.dhis.android.core.user.UserStore;
import org.hisp.dhis.android.core.user.UserStoreImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import okhttp3.OkHttpClient;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
// ToDo: handle corner cases when user initially has been signed in, but later was locked (or
// password has changed)
@SuppressWarnings({"PMD.ExcessiveImports", "PMD.TooManyFields"})
public final class D2 {
private final Retrofit retrofit;
private final DatabaseAdapter databaseAdapter;
// services
private final UserService userService;
private final SystemInfoService systemInfoService;
private final ProgramService programService;
private final OrganisationUnitService organisationUnitService;
private final TrackedEntityService trackedEntityService;
private final TrackedEntityInstanceService trackedEntityInstanceService;
private final OptionSetService optionSetService;
private final EventService eventService;
private final CategoryService categoryService;
private final CategoryComboService comboService;
// Queries
private final CategoryQuery categoryQuery = CategoryQuery.defaultQuery();
private final CategoryComboQuery categoryComboQuery = CategoryComboQuery.defaultQuery();
// stores
private final UserStore userStore;
private final UserCredentialsStore userCredentialsStore;
private final UserOrganisationUnitLinkStore userOrganisationUnitLinkStore;
private final AuthenticatedUserStore authenticatedUserStore;
private final OrganisationUnitStore organisationUnitStore;
private final ResourceStore resourceStore;
private final SystemInfoStore systemInfoStore;
private final UserRoleStore userRoleStore;
private final ProgramStore programStore;
private final TrackedEntityAttributeStore trackedEntityAttributeStore;
private final ProgramTrackedEntityAttributeStore programTrackedEntityAttributeStore;
private final ProgramRuleVariableStore programRuleVariableStore;
private final ProgramIndicatorStore programIndicatorStore;
private final ProgramStageSectionProgramIndicatorLinkStore
programStageSectionProgramIndicatorLinkStore;
private final ProgramRuleActionStore programRuleActionStore;
private final ProgramRuleStore programRuleStore;
private final OptionStore optionStore;
private final IdentifiableObjectStore<OptionSetModel> optionSetStore;
private final IdentifiableObjectStore<DataElementModel> dataElementStore;
private final ProgramStageDataElementStore programStageDataElementStore;
private final ProgramStageSectionStore programStageSectionStore;
private final ProgramStageStore programStageStore;
private final RelationshipTypeStore relationshipStore;
private final TrackedEntityStore trackedEntityStore;
private final TrackedEntityInstanceStore trackedEntityInstanceStore;
private final EnrollmentStore enrollmentStore;
private final EventStore eventStore;
private final TrackedEntityDataValueStore trackedEntityDataValueStore;
private final TrackedEntityAttributeValueStore trackedEntityAttributeValueStore;
private final OrganisationUnitProgramLinkStore organisationUnitProgramLinkStore;
private final CategoryOptionStore categoryOptionStore;
private final CategoryStore categoryStore;
private final CategoryComboStore categoryComboStore;
private final CategoryCategoryComboLinkStore categoryCategoryComboLinkStore;
private final CategoryCategoryOptionLinkStore categoryCategoryOptionLinkStore;
private final CategoryOptionComboCategoryLinkStore categoryComboOptionCategoryLinkStore;
private final IdentifiableObjectStore<DataSetModel> dataSetStore;
private final ObjectStore<DataSetDataElementLinkModel> dataSetDataElementLinkStore;
private final ObjectStore<DataSetOrganisationUnitLinkModel> dataSetOrganisationUnitLinkStore;
private final IdentifiableObjectStore<IndicatorModel> indicatorStore;
private final IdentifiableObjectStore<IndicatorTypeModel> indicatorTypeStore;
private final ObjectStore<DataSetIndicatorLinkModel> dataSetIndicatorLinkStore;
private final ObjectWithoutUidStore<DataValueModel> dataValueStore;
private final ObjectWithoutUidStore<PeriodModel> periodStore;
private final ObjectWithoutUidStore<ObjectStyleModel> objectStyleStore;
private final ObjectWithoutUidStore<ValueTypeDeviceRenderingModel> valueTypeDeviceRenderingStore;
//Handlers
private final UserCredentialsHandler userCredentialsHandler;
private final EventHandler eventHandler;
private final TrackedEntityInstanceHandler trackedEntityInstanceHandler;
private final ResourceHandler resourceHandler;
private final CategoryHandler categoryHandler;
private final CategoryComboHandler categoryComboHandler;
private final OrganisationUnitHandler organisationUnitHandler;
private final GenericHandler<DataElement> dataElementHandler;
private final OptionSetHandler optionSetHandler;
private final DictionaryTableHandler<ObjectStyle> styleHandler;
private final DictionaryTableHandler<ValueTypeRendering> renderTypeHandler;
//Generic Call Data
private final GenericCallData genericCallData;
@VisibleForTesting
D2(@NonNull Retrofit retrofit, @NonNull DatabaseAdapter databaseAdapter) {
this.retrofit = retrofit;
this.databaseAdapter = databaseAdapter;
// services
this.userService = retrofit.create(UserService.class);
this.systemInfoService = retrofit.create(SystemInfoService.class);
this.programService = retrofit.create(ProgramService.class);
this.organisationUnitService = retrofit.create(OrganisationUnitService.class);
this.trackedEntityService = retrofit.create(TrackedEntityService.class);
this.optionSetService = retrofit.create(OptionSetService.class);
this.trackedEntityInstanceService = retrofit.create(TrackedEntityInstanceService.class);
this.eventService = retrofit.create(EventService.class);
this.categoryService = retrofit.create(CategoryService.class);
this.comboService = retrofit.create(CategoryComboService.class);
// stores
this.userStore =
new UserStoreImpl(databaseAdapter);
this.userCredentialsStore =
new UserCredentialsStoreImpl(databaseAdapter);
this.userOrganisationUnitLinkStore =
new UserOrganisationUnitLinkStoreImpl(databaseAdapter);
this.authenticatedUserStore =
new AuthenticatedUserStoreImpl(databaseAdapter);
this.organisationUnitStore =
new OrganisationUnitStoreImpl(databaseAdapter);
this.resourceStore =
new ResourceStoreImpl(databaseAdapter);
this.systemInfoStore =
new SystemInfoStoreImpl(databaseAdapter);
this.userRoleStore =
new UserRoleStoreImpl(databaseAdapter);
this.programStore =
new ProgramStoreImpl(databaseAdapter);
this.trackedEntityAttributeStore =
new TrackedEntityAttributeStoreImpl(databaseAdapter);
this.programTrackedEntityAttributeStore =
new ProgramTrackedEntityAttributeStoreImpl(databaseAdapter);
this.programRuleVariableStore =
new ProgramRuleVariableStoreImpl(databaseAdapter);
this.programIndicatorStore =
new ProgramIndicatorStoreImpl(databaseAdapter);
this.programStageSectionProgramIndicatorLinkStore =
new ProgramStageSectionProgramIndicatorLinkStoreImpl(databaseAdapter);
this.programRuleActionStore =
new ProgramRuleActionStoreImpl(databaseAdapter);
this.programRuleStore =
new ProgramRuleStoreImpl(databaseAdapter);
this.optionStore =
new OptionStoreImpl(databaseAdapter);
this.optionSetStore =
OptionSetStore.create(databaseAdapter);
this.dataElementStore =
DataElementStore.create(databaseAdapter);
this.programStageDataElementStore =
new ProgramStageDataElementStoreImpl(databaseAdapter);
this.programStageSectionStore =
new ProgramStageSectionStoreImpl(databaseAdapter);
this.programStageStore =
new ProgramStageStoreImpl(databaseAdapter);
this.relationshipStore =
new RelationshipTypeStoreImpl(databaseAdapter);
this.trackedEntityStore =
new TrackedEntityStoreImpl(databaseAdapter);
this.trackedEntityInstanceStore =
new TrackedEntityInstanceStoreImpl(databaseAdapter);
this.enrollmentStore =
new EnrollmentStoreImpl(databaseAdapter);
this.eventStore =
new EventStoreImpl(databaseAdapter);
this.trackedEntityDataValueStore =
new TrackedEntityDataValueStoreImpl(databaseAdapter);
this.trackedEntityAttributeValueStore =
new TrackedEntityAttributeValueStoreImpl(databaseAdapter);
this.organisationUnitProgramLinkStore =
new OrganisationUnitProgramLinkStoreImpl(databaseAdapter);
this.categoryStore = new CategoryStoreImpl(databaseAdapter);
this.categoryOptionStore = new CategoryOptionStoreImpl(databaseAdapter());
this.categoryCategoryOptionLinkStore = new CategoryCategoryOptionLinkStoreImpl(
databaseAdapter());
this.categoryComboOptionCategoryLinkStore
= new CategoryOptionComboCategoryLinkStoreImpl(databaseAdapter);
this.categoryComboStore = new CategoryComboStoreImpl(databaseAdapter());
this.categoryCategoryComboLinkStore = new CategoryCategoryComboLinkStoreImpl(
databaseAdapter());
CategoryOptionComboStore categoryOptionComboStore = new CategoryOptionComboStoreImpl(
databaseAdapter());
this.dataSetStore = DataSetStore.create(databaseAdapter());
this.dataSetDataElementLinkStore = DataSetDataElementLinkStore.create(databaseAdapter());
this.dataSetOrganisationUnitLinkStore = DataSetOrganisationUnitLinkStore.create(databaseAdapter());
this.indicatorStore = IndicatorStore.create(databaseAdapter());
this.indicatorTypeStore = IndicatorTypeStore.create(databaseAdapter());
this.dataSetIndicatorLinkStore = DataSetIndicatorLinkStore.create(databaseAdapter());
this.dataValueStore = DataValueStore.create(databaseAdapter());
this.periodStore = PeriodStore.create(databaseAdapter());
this.objectStyleStore = ObjectStyleStore.create(databaseAdapter());
this.valueTypeDeviceRenderingStore = ValueTypeDeviceRenderingStore.create(databaseAdapter());
//handlers
userCredentialsHandler = new UserCredentialsHandler(userCredentialsStore);
resourceHandler = new ResourceHandler(resourceStore);
organisationUnitHandler = new OrganisationUnitHandler(organisationUnitStore,
userOrganisationUnitLinkStore, organisationUnitProgramLinkStore, null);
TrackedEntityDataValueHandler trackedEntityDataValueHandler =
new TrackedEntityDataValueHandler(trackedEntityDataValueStore);
CategoryOptionHandler categoryOptionHandler = new CategoryOptionHandler(
categoryOptionStore);
this.eventHandler = new EventHandler(eventStore, trackedEntityDataValueHandler);
TrackedEntityAttributeValueHandler trackedEntityAttributeValueHandler =
new TrackedEntityAttributeValueHandler(trackedEntityAttributeValueStore);
EnrollmentHandler enrollmentHandler = new EnrollmentHandler(enrollmentStore, eventHandler);
trackedEntityInstanceHandler =
new TrackedEntityInstanceHandler(
trackedEntityInstanceStore,
trackedEntityAttributeValueHandler,
enrollmentHandler);
categoryHandler = new CategoryHandler(categoryStore, categoryOptionHandler,
categoryCategoryOptionLinkStore);
CategoryOptionComboHandler optionComboHandler = new CategoryOptionComboHandler(
categoryOptionComboStore);
categoryComboHandler = new CategoryComboHandler(categoryComboStore,
categoryComboOptionCategoryLinkStore,
categoryCategoryComboLinkStore, optionComboHandler);
// handlers
this.optionSetHandler = OptionSetHandler.create(databaseAdapter);
this.dataElementHandler = DataElementHandler.create(databaseAdapter, this.optionSetHandler);
this.styleHandler = ObjectStyleHandler.create(databaseAdapter);
this.renderTypeHandler = ValueTypeRenderingHandler.create(databaseAdapter);
// data
this.genericCallData = GenericCallData.create(databaseAdapter, new ResourceHandler(resourceStore), retrofit);
}
@NonNull
public Retrofit retrofit() {
return retrofit;
}
@NonNull
public DatabaseAdapter databaseAdapter() {
return databaseAdapter;
}
@NonNull
public Call<Response<User>> logIn(@NonNull String username, @NonNull String password) {
if (username == null) {
throw new NullPointerException("username == null");
}
if (password == null) {
throw new NullPointerException("password == null");
}
return new UserAuthenticateCall(userService, databaseAdapter, userStore,
userCredentialsHandler, resourceHandler,
authenticatedUserStore, organisationUnitHandler, username, password
);
}
@NonNull
public Callable<Boolean> isUserLoggedIn() {
AuthenticatedUserStore authenticatedUserStore =
new AuthenticatedUserStoreImpl(databaseAdapter);
return new IsUserLoggedInCallable(authenticatedUserStore);
}
@NonNull
public Callable<Void> logout() {
List<DeletableStore> deletableStoreList = new ArrayList<>();
deletableStoreList.add(authenticatedUserStore);
return new LogOutUserCallable(
deletableStoreList
);
}
@NonNull
public Callable<Void> wipeDB() {
List<DeletableStore> deletableStoreList = new ArrayList<>();
deletableStoreList.add(userStore);
deletableStoreList.add(userCredentialsStore);
deletableStoreList.add(userOrganisationUnitLinkStore);
deletableStoreList.add(authenticatedUserStore);
deletableStoreList.add(organisationUnitStore);
deletableStoreList.add(resourceStore);
deletableStoreList.add(systemInfoStore);
deletableStoreList.add(userRoleStore);
deletableStoreList.add(programStore);
deletableStoreList.add(trackedEntityAttributeStore);
deletableStoreList.add(programTrackedEntityAttributeStore);
deletableStoreList.add(programRuleVariableStore);
deletableStoreList.add(programIndicatorStore);
deletableStoreList.add(programStageSectionProgramIndicatorLinkStore);
deletableStoreList.add(programRuleActionStore);
deletableStoreList.add(programRuleStore);
deletableStoreList.add(optionStore);
deletableStoreList.add(optionSetStore);
deletableStoreList.add(dataElementStore);
deletableStoreList.add(programStageDataElementStore);
deletableStoreList.add(programStageSectionStore);
deletableStoreList.add(programStageStore);
deletableStoreList.add(relationshipStore);
deletableStoreList.add(trackedEntityStore);
deletableStoreList.add(trackedEntityInstanceStore);
deletableStoreList.add(enrollmentStore);
deletableStoreList.add(trackedEntityDataValueStore);
deletableStoreList.add(trackedEntityAttributeValueStore);
deletableStoreList.add(organisationUnitProgramLinkStore);
deletableStoreList.add(eventStore);
deletableStoreList.add(categoryStore);
deletableStoreList.add(categoryOptionStore);
deletableStoreList.add(categoryCategoryOptionLinkStore);
deletableStoreList.add(categoryComboOptionCategoryLinkStore);
deletableStoreList.add(categoryComboStore);
deletableStoreList.add(categoryCategoryComboLinkStore);
deletableStoreList.add(dataSetStore);
deletableStoreList.add(dataSetDataElementLinkStore);
deletableStoreList.add(dataSetOrganisationUnitLinkStore);
deletableStoreList.add(indicatorStore);
deletableStoreList.add(indicatorTypeStore);
deletableStoreList.add(dataSetIndicatorLinkStore);
deletableStoreList.add(dataValueStore);
deletableStoreList.add(periodStore);
deletableStoreList.add(objectStyleStore);
deletableStoreList.add(valueTypeDeviceRenderingStore);
return new LogOutUserCallable(
deletableStoreList
);
}
@NonNull
public Call<Response> syncMetaData() {
return new MetadataCall(
databaseAdapter, systemInfoService, userService, programService, organisationUnitService,
trackedEntityService, optionSetService,
systemInfoStore, resourceStore, userStore,
userCredentialsStore, userRoleStore, organisationUnitStore,
userOrganisationUnitLinkStore, programStore, trackedEntityAttributeStore,
programTrackedEntityAttributeStore, programRuleVariableStore, programIndicatorStore,
programStageSectionProgramIndicatorLinkStore, programRuleActionStore,
programRuleStore,
programStageDataElementStore,
programStageSectionStore,
programStageStore, relationshipStore, trackedEntityStore,
organisationUnitProgramLinkStore, categoryQuery,
categoryService, categoryHandler, categoryComboQuery, comboService,
categoryComboHandler, optionSetHandler, dataElementHandler, DataSetParentCall.FACTORY,
styleHandler, renderTypeHandler, retrofit);
}
@NonNull
public Call<Response> syncAggregatedData() {
return new AggregatedDataCall(genericCallData, DataValueEndpointCall.FACTORY, dataSetStore, periodStore,
organisationUnitStore);
}
@NonNull
public Call<Response> syncSingleData(int eventLimitByOrgUnit) {
return new SingleDataCall(organisationUnitStore, systemInfoStore, systemInfoService,
resourceStore,
eventService, databaseAdapter, resourceHandler, eventHandler, eventLimitByOrgUnit);
}
@NonNull
public Call<Response> syncTrackerData() {
return new TrackerDataCall(trackedEntityInstanceStore, systemInfoStore, systemInfoService,
resourceStore, trackedEntityInstanceService, databaseAdapter, resourceHandler,
trackedEntityInstanceHandler);
}
@NonNull
public Call<Response<Payload<TrackedEntityInstance>>>
downloadTrackedEntityInstance(String trackedEntityInstanceUid) {
return new TrackedEntityInstanceEndPointCall(
trackedEntityInstanceService, databaseAdapter, trackedEntityInstanceHandler,
resourceHandler, new Date(), trackedEntityInstanceUid);
}
@NonNull
public Call<Response> downloadTrackedEntityInstances(int teiLimitByOrgUnit) {
return new TrackerEntitiesDataCall(organisationUnitStore, trackedEntityInstanceService, databaseAdapter,
trackedEntityInstanceHandler, resourceHandler, resourceStore, systemInfoService,
systemInfoStore, teiLimitByOrgUnit);
}
@NonNull
public Call<Response<WebResponse>> syncTrackedEntityInstances() {
return new TrackedEntityInstancePostCall(trackedEntityInstanceService,
trackedEntityInstanceStore, enrollmentStore, eventStore,
trackedEntityDataValueStore,
trackedEntityAttributeValueStore);
}
public Call<Response<WebResponse>> syncSingleEvents() {
return new EventPostCall(eventService, eventStore, trackedEntityDataValueStore);
}
public static class Builder {
private ConfigurationModel configuration;
private DatabaseAdapter databaseAdapter;
private OkHttpClient okHttpClient;
public Builder() {
// empty constructor
}
@NonNull
public Builder configuration(@NonNull ConfigurationModel configuration) {
this.configuration = configuration;
return this;
}
@NonNull
public Builder databaseAdapter(@NonNull DatabaseAdapter databaseAdapter) {
this.databaseAdapter = databaseAdapter;
return this;
}
@NonNull
public Builder okHttpClient(@NonNull OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
return this;
}
public D2 build() {
if (databaseAdapter == null) {
throw new IllegalArgumentException("databaseAdapter == null");
}
if (configuration == null) {
throw new IllegalStateException("configuration must be set first");
}
if (okHttpClient == null) {
throw new IllegalArgumentException("okHttpClient == null");
}
ObjectMapper objectMapper = new ObjectMapper()
.setDateFormat(BaseIdentifiableObject.DATE_FORMAT.raw())
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(configuration.serverUrl())
.client(okHttpClient)
.addConverterFactory(JacksonConverterFactory.create(objectMapper))
.addConverterFactory(FilterConverterFactory.create())
.addConverterFactory(FieldsConverterFactory.create())
.validateEagerly(true)
.build();
return new D2(retrofit, databaseAdapter);
}
}
}
|
package com.eegeo.mobileexampleapp;
import java.io.IOException;
import java.io.InputStream;
import org.json.JSONException;
import org.json.JSONObject;
import com.eegeo.entrypointinfrastructure.EegeoSurfaceView;
import com.eegeo.entrypointinfrastructure.MainActivity;
import com.eegeo.entrypointinfrastructure.NativeJniCalls;
import com.eegeo.helpers.IRuntimePermissionResultHandler;
import com.eegeo.recce.*;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.view.View;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.Constants;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.NativeCrashManager;
public class BackgroundThreadActivity extends MainActivity
{
final public Object screenshotsCompletedLock = new Object();
private long m_nativeAppWindowPtr;
private EegeoSurfaceView m_surfaceView;
private SurfaceHolder m_surfaceHolder;
private ThreadedUpdateRunner m_threadedRunner;
private Thread m_updater;
private String m_hockeyAppId;
/* The url used if the app is opened by a deep link.
* As the app in singleTask this is set in onNewIntent and must be
* set to null before for the app pauses.
*/
private Uri m_deepLinkUrlData;
private boolean m_rotationInitialised = false;
private boolean m_locationPermissionRecieved;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 52;
static
{
System.loadLibrary("eegeo-mobile-example-app");
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0)
{
finish();
return;
}
m_hockeyAppId = readHockeyAppId();
Constants.loadFromContext(this);
NativeJniCalls.setUpBreakpad(Constants.FILES_PATH);
NativeCrashManager.handleDumpFiles(this, m_hockeyAppId);
PackageInfo pInfo = null;
try
{
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
final String versionName = pInfo.versionName;
final int versionCode = pInfo.versionCode;
m_rotationInitialised = !setDisplayOrientationBasedOnDeviceProperties();
setContentView(R.layout.activity_main);
Intent intent = getIntent();
if(intent !=null)
{
m_deepLinkUrlData = intent.getData();
}
m_surfaceView = (EegeoSurfaceView)findViewById(R.id.surface);
m_surfaceView.getHolder().addCallback(this);
m_surfaceView.setActivity(this);
DisplayMetrics dm = getResources().getDisplayMetrics();
final float dpi = dm.ydpi;
final int density = dm.densityDpi;
final Activity activity = this;
boolean locationPermissionGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
m_locationPermissionRecieved = locationPermissionGranted;
getRuntimePermissionDispatcher().addRuntimePermissionResultHandler(new IRuntimePermissionResultHandler()
{
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if(requestCode == LOCATION_PERMISSION_REQUEST_CODE)
{
m_locationPermissionRecieved = true;
}
}
});
this.getRuntimePermissionDispatcher().hasLocationPermissionsWithCode(LOCATION_PERMISSION_REQUEST_CODE);
m_threadedRunner = new ThreadedUpdateRunner(false);
m_updater = new Thread(m_threadedRunner);
m_updater.start();
m_threadedRunner.blockUntilThreadStartedRunning();
runOnNativeThread(new Runnable()
{
public void run()
{
m_nativeAppWindowPtr = NativeJniCalls.createNativeCode(activity, getAssets(), dpi, density, versionName, versionCode);
if(m_nativeAppWindowPtr == 0)
{
throw new RuntimeException("Failed to start native code.");
}
}
});
}
public void runOnNativeThread(Runnable runnable)
{
m_threadedRunner.postTo(runnable);
}
@Override
protected void onResume()
{
super.onResume();
updateSystemNavigation();
if(hasValidHockeyAppId())
{
registerCrashLogging();
}
}
@Override
protected void onPause()
{
super.onPause();
}
@Override
protected void onDestroy()
{
super.onDestroy();
if (m_threadedRunner == null)
{
return;
}
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.stopUpdatingNativeCode();
m_threadedRunner.flagUpdatingNativeCodeStopped();
}
});
m_threadedRunner.blockUntilThreadHasStoppedUpdatingPlatform();
NativeJniCalls.destroyApplicationUi();
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
NativeJniCalls.destroyNativeCode();
m_threadedRunner.destroyed();
}
});
m_threadedRunner.blockUntilThreadHasDestroyedPlatform();
m_nativeAppWindowPtr = 0;
}
@Override
public void onBackPressed()
{
if (!checkLocalBackButtonListeners())
{
moveTaskToBack(true);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
//nothing to do
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
runOnNativeThread(new Runnable()
{
public void run()
{
m_threadedRunner.stop();
NativeJniCalls.pauseNativeCode();
}
});
}
@Override
public void surfaceChanged(final SurfaceHolder holder, int format, int width, int height)
{
m_surfaceHolder = holder;
if (!m_rotationInitialised)
{
return;
}
runOnNativeThread(new Runnable()
{
public void run()
{
m_surfaceHolder = holder;
if(m_surfaceHolder != null)
{
long oldWindow = NativeJniCalls.setNativeSurface(m_surfaceHolder.getSurface());
m_threadedRunner.start();
releaseNativeWindowDeferred(oldWindow);
if(m_deepLinkUrlData != null)
{
NativeJniCalls.handleUrlOpenEvent(m_deepLinkUrlData.getHost(), m_deepLinkUrlData.getPath());
m_deepLinkUrlData = null;
}
NativeJniCalls.resumeNativeCode();
}
}
});
}
@Override
public void onNewIntent(Intent intent) {
m_deepLinkUrlData = intent.getData();
}
public void dispatchRevealUiMessageToUiThreadFromNativeThread(final long nativeCallerPointer)
{
runOnUiThread(new Runnable()
{
public void run()
{
NativeJniCalls.revealApplicationUi(nativeCallerPointer);
}
});
}
public void dispatchUiCreatedMessageToNativeThreadFromUiThread(final long nativeCallerPointer)
{
runOnNativeThread(new Runnable()
{
public void run()
{
NativeJniCalls.handleApplicationUiCreatedOnNativeThread(nativeCallerPointer);
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfiguration)
{
super.onConfigurationChanged(newConfiguration);
m_rotationInitialised = true;
}
@Override
public void onScreenshotsCompleted()
{
synchronized (screenshotsCompletedLock)
{
screenshotsCompletedLock.notifyAll();
}
}
private boolean setDisplayOrientationBasedOnDeviceProperties()
{
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int width = displayMetrics.widthPixels;
final int height = displayMetrics.heightPixels;
if(getResources().getBoolean(R.bool.isPhone))
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
final boolean needsRotation = width > height;
return needsRotation;
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
final boolean needsRotation = width < height;
return needsRotation;
}
}
private String readHockeyAppId()
{
try
{
String applicationConfigurationPath = NativeJniCalls.getAppConfigurationPath();
InputStream is = getAssets().open(applicationConfigurationPath);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String jsonStr = new String(buffer, "UTF-8");
JSONObject json = new JSONObject(jsonStr);
return json.get("hockey_app_id").toString();
} catch (IOException e) {
// Master Ball
} catch (JSONException e) {
// Master Ball
}
return "";
}
private boolean hasValidHockeyAppId()
{
return m_hockeyAppId.length() == 32;
}
private void registerCrashLogging()
{
CrashManager.register(this, m_hockeyAppId, new CrashManagerListener() {
public boolean shouldAutoUploadCrashes() {
return true;
}
});
}
private class ThreadedUpdateRunner implements Runnable
{
private long m_endOfLastFrameNano;
private boolean m_running;
private volatile Handler m_nativeThreadHandler;
private float m_frameThrottleDelaySeconds;
private boolean m_destroyed;
private boolean m_stoppedUpdatingPlatformBeforeTeardown;
public ThreadedUpdateRunner(boolean running)
{
m_endOfLastFrameNano = System.nanoTime();
m_running = false;
m_destroyed = false;
m_stoppedUpdatingPlatformBeforeTeardown = false;
float targetFramesPerSecond = 30.f;
m_frameThrottleDelaySeconds = 1.f/targetFramesPerSecond;
}
synchronized void blockUntilThreadStartedRunning()
{
while(m_nativeThreadHandler == null);
}
synchronized void blockUntilThreadHasDestroyedPlatform()
{
while(!m_destroyed)
{
SystemClock.sleep(200);
}
}
synchronized void blockUntilThreadHasStoppedUpdatingPlatform()
{
while(!m_stoppedUpdatingPlatformBeforeTeardown)
{
SystemClock.sleep(200);
}
}
public void postTo(Runnable runnable)
{
m_nativeThreadHandler.post(runnable);
}
public void start()
{
m_running = true;
}
public void stop()
{
m_running = false;
}
public void destroyed()
{
m_destroyed = true;
}
void flagUpdatingNativeCodeStopped()
{
m_stoppedUpdatingPlatformBeforeTeardown = true;
}
public void run()
{
Looper.prepare();
Handler tmp = new Handler();
m_nativeThreadHandler = tmp;
runOnNativeThread(new Runnable()
{
public void run()
{
long timeNowNano = System.nanoTime();
long nanoDelta = timeNowNano - m_endOfLastFrameNano;
final float deltaSeconds = (float)((double)nanoDelta / 1e9);
if(deltaSeconds > m_frameThrottleDelaySeconds)
{
if(m_running && m_locationPermissionRecieved)
{
NativeJniCalls.updateNativeCode(deltaSeconds);
runOnUiThread(new Runnable()
{
public void run()
{
NativeJniCalls.updateUiViewCode(deltaSeconds);
}
});
}
else
{
SystemClock.sleep(200);
}
m_endOfLastFrameNano = timeNowNano;
}
runOnNativeThread(this);
}
});
Looper.loop();
}
}
public void releaseNativeWindowDeferred(final long oldWindow)
{
runOnNativeThread(new Runnable() {
@Override
public void run() {
NativeJniCalls.releaseNativeWindow(oldWindow);
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
updateSystemNavigation();
}
private void updateSystemNavigation()
{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE);
}
}
|
package com.reactnative.googlefit;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.util.Log;
import android.content.Intent;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.HealthDataTypes;
import com.facebook.react.bridge.WritableMap;
public class GoogleFitModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
private static final String REACT_MODULE = "RNGoogleFit";
private ReactContext mReactContext;
private GoogleFitManager mGoogleFitManager = null;
private String GOOGLE_FIT_APP_URI = "com.google.android.apps.fitness";
public GoogleFitModule(ReactApplicationContext reactContext) {
super(reactContext);
this.mReactContext = reactContext;
}
@Override
public String getName() {
return REACT_MODULE;
}
@Override
public void initialize() {
super.initialize();
getReactApplicationContext().addLifecycleEventListener(this);
}
@Override
public void onHostResume() {
super.onHostResume();
if (mGoogleFitManager != null) {
mGoogleFitManager.resetAuthInProgress();
}
}
@Override
public void onHostPause() {
super.onHostPause();
}
@Override
public void onHostDestroy() {
// todo disconnect from Google Fit
}
@ReactMethod
public void authorize() {
final Activity activity = getCurrentActivity();
if (mGoogleFitManager == null) {
mGoogleFitManager = new GoogleFitManager(mReactContext, activity);
}
if (mGoogleFitManager.isAuthorized()) {
return;
}
mGoogleFitManager.authorize();
}
@ReactMethod
public void isAuthorized (final Promise promise) {
boolean isAuthorized = false;
if (mGoogleFitManager != null && mGoogleFitManager.isAuthorized() ) {
isAuthorized = true;
}
WritableMap map = Arguments.createMap();
map.putBoolean("isAuthorized", isAuthorized);
promise.resolve(map);
}
@ReactMethod
public void disconnect() {
if (mGoogleFitManager != null) {
mGoogleFitManager.disconnect();
}
}
@ReactMethod
public void startFitnessRecording(ReadableArray dataTypes) {
mGoogleFitManager.getRecordingApi().subscribe(dataTypes);
}
@ReactMethod
public void observeSteps() {
mGoogleFitManager.getStepCounter().findFitnessDataSources();
}
@ReactMethod
public void getDailySteps(double startDay, double endDay) {
mGoogleFitManager.getStepHistory().displayLastWeeksData((long) startDay, (long) endDay);
}
@ReactMethod
public void getWeeklySteps(double startDate, double endDate) {
mGoogleFitManager.getStepHistory().displayLastWeeksData((long) startDate, (long) endDate);
}
@ReactMethod
public void getDailyStepCountSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
mGoogleFitManager.getStepHistory().aggregateDataByDate((long) startDate, (long) endDate, successCallback);
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void getActivitySamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
successCallback.invoke(mGoogleFitManager.getActivityHistory().getActivitySamples((long)startDate, (long)endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void getDailyDistanceSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
successCallback.invoke(mGoogleFitManager.getDistanceHistory().aggregateDataByDate((long) startDate, (long) endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void getWeightSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
bodyHistory.setDataType(DataType.TYPE_WEIGHT);
successCallback.invoke(bodyHistory.getHistory((long)startDate, (long)endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void getHeightSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
bodyHistory.setDataType(DataType.TYPE_HEIGHT);
successCallback.invoke(bodyHistory.getHistory((long)startDate, (long)endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void saveHeight(ReadableMap heightSample,
Callback errorCallback,
Callback successCallback) {
try {
BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
bodyHistory.setDataType(DataType.TYPE_HEIGHT);
successCallback.invoke(bodyHistory.save(heightSample));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void getDailyCalorieSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
successCallback.invoke(mGoogleFitManager.getCalorieHistory().aggregateDataByDate((long) startDate, (long) endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void saveFood(ReadableMap foodSample,
Callback errorCallback,
Callback successCallback) {
try {
successCallback.invoke(mGoogleFitManager.getCalorieHistory().saveFood(foodSample));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void saveWeight(ReadableMap weightSample,
Callback errorCallback,
Callback successCallback) {
try {
BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
bodyHistory.setDataType(DataType.TYPE_WEIGHT);
successCallback.invoke(bodyHistory.save(weightSample));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void deleteWeight(ReadableMap options, Callback errorCallback, Callback successCallback) {
try {
BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
bodyHistory.setDataType(DataType.TYPE_WEIGHT);
successCallback.invoke(bodyHistory.delete(options));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void deleteHeight(ReadableMap options, Callback errorCallback, Callback successCallback) {
try {
BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
bodyHistory.setDataType(DataType.TYPE_HEIGHT);
successCallback.invoke(bodyHistory.delete(options));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void isAvailable(Callback errorCallback, Callback successCallback) { // true if GoogleFit installed
try {
successCallback.invoke(isAvailableCheck());
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void isEnabled(Callback errorCallback, Callback successCallback) {
try {
successCallback.invoke(isEnabledCheck());
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void openFit() {
PackageManager pm = mReactContext.getPackageManager();
try {
Intent launchIntent = pm.getLaunchIntentForPackage(GOOGLE_FIT_APP_URI);
mReactContext.startActivity(launchIntent);
} catch (Exception e) {
Log.i(REACT_MODULE, e.toString());
}
}
private boolean isAvailableCheck() {
PackageManager pm = mReactContext.getPackageManager();
try {
pm.getPackageInfo(GOOGLE_FIT_APP_URI, PackageManager.GET_ACTIVITIES);
return true;
} catch (Exception e) {
Log.i(REACT_MODULE, e.toString());
return false;
}
}
private boolean isEnabledCheck() {
if (mGoogleFitManager == null) {
mGoogleFitManager = new GoogleFitManager(mReactContext, getCurrentActivity());
}
return mGoogleFitManager.isAuthorized();
}
@ReactMethod
public void getBloodPressureSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
HeartrateHistory heartrateHistory = mGoogleFitManager.getHeartrateHistory();
heartrateHistory.setDataType(HealthDataTypes.TYPE_BLOOD_PRESSURE);
successCallback.invoke(heartrateHistory.getHistory((long)startDate, (long)endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
@ReactMethod
public void getHeartRateSamples(double startDate,
double endDate,
Callback errorCallback,
Callback successCallback) {
try {
HeartrateHistory heartrateHistory = mGoogleFitManager.getHeartrateHistory();
heartrateHistory.setDataType(DataType.TYPE_HEART_RATE_BPM);
successCallback.invoke(heartrateHistory.getHistory((long)startDate, (long)endDate));
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
}
|
package com.intuit.tank.storage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* FileStorage that writes to the file system.
*
* @author denisa
*
*/
public class FileSystemFileStorage implements FileStorage, Serializable {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LogManager.getLogger(FileSystemFileStorage.class);
private String basePath;
private boolean compress = true;
/**
* @param basePath
*/
public FileSystemFileStorage(String basePath, boolean compress) {
super();
this.basePath = FilenameUtils.normalizeNoEndSeparator(basePath);
this.compress = compress;
File dir = new File(basePath);
if (!dir.exists()) {
LOG.info("Creating storage dir " + dir.getAbsolutePath());
}
}
@Override
public void storeFileData(FileData fileData, InputStream input) {
File file = new File(FilenameUtils.normalize(basePath + "/" + fileData.getPath() + "/" + fileData.getFileName()));
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (OutputStream output = compress ?
new GZIPOutputStream(new FileOutputStream(file)) :
new FileOutputStream(file) ) {
IOUtils.copy(input, output);
} catch (IOException e) {
LOG.error("Error storing file: " + e, e);
throw new RuntimeException(e);
}
}
@Override
public InputStream readFileData(FileData fileData) {
File file = new File(FilenameUtils.normalize(basePath + "/" + fileData.getPath() + "/" + fileData.getFileName()));
try {
return compress ?
new GZIPInputStream(new FileInputStream(file)) :
new FileInputStream(file);
} catch (IOException e) {
LOG.error("Error storing file: " + e, e);
throw new RuntimeException(e);
}
}
@Override
public boolean exists(FileData fileData) {
File file = new File(FilenameUtils.normalize(basePath + "/" + fileData.getPath() + "/" + fileData.getFileName()));
return file.exists();
}
@Override
public List<FileData> listFileData(String path) {
File dir = new File(FilenameUtils.normalize(basePath + "/" + path));
if (dir.exists()) {
return Arrays.stream(dir.listFiles()).filter(File::isFile).map(f -> new FileData(path, f.getName())).collect(Collectors.toList());
}
return new ArrayList<FileData>();
}
@Override
public boolean delete(FileData fileData) {
File file = new File(FilenameUtils.normalize(basePath + "/" + fileData.getPath() + "/" + fileData.getFileName()));
return file.delete();
}
}
|
package com.voxelwind.api.game.level.block;
import com.google.common.collect.ImmutableList;
import com.sun.tools.javac.jvm.Items;
import com.voxelwind.api.game.item.ItemStack;
import com.voxelwind.api.game.item.ItemStackBuilder;
import com.voxelwind.api.game.item.ItemTypes;
import com.voxelwind.api.game.item.data.Dyed;
import com.voxelwind.api.game.item.data.ItemData;
import com.voxelwind.api.game.item.util.DyeColor;
import com.voxelwind.api.server.Server;
import java.util.Collection;
import java.util.Random;
/**
* This class contains all block types recognized by Voxelwind and Pocket Edition.
*/
public class BlockTypes {
private static final Random RANDOM = new Random();
public static final BlockType AIR = new IntBlock(0, "air", 0, false, true, 0, 0, (i1, i2, i3) -> ImmutableList.of(), null);
public static final BlockType STONE = new IntBlock(1, "stone", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType GRASS_BLOCK = new IntBlock(2, "grass_block", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType DIRT = new IntBlock(3, "dirt", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType COBBLESTONE = new IntBlock(4, "cobblestone", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType WOOD_PLANKS = new IntBlock(5, "wood_planks", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType SAPLING = new IntBlock(6, "sapling", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BEDROCK = new IntBlock(7, "bedrock", 64, false, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType WATER = new IntBlock(8, "water", 0, false, true, 0, 2, (i1, i2, i3) -> ImmutableList.of(), null);
public static final BlockType WATER_STATIONARY = new IntBlock(9, "water", 0, false, true, 0, 2, (i1, i2, i3) -> ImmutableList.of(), null);
public static final BlockType LAVA = new IntBlock(10, "lava", 0, false, true, 15, 0, (i1, i2, i3) -> ImmutableList.of(), null);
public static final BlockType LAVA_STATIONAR = new IntBlock(11, "lava", 0, false, true, 15, 0, (i1, i2, i3) -> ImmutableList.of(), null);
public static final BlockType SAND = new IntBlock(12, "sand", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType GRAVEL = new IntBlock(13, "gravel", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType GOLD_ORE = new IntBlock(14, "gold_ore", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType IRON_ORE = new IntBlock(15, "iron_ore", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType COAL_ORE = new IntBlock(16, "coal_ore", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType WOOD = new IntBlock(17, "wood", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType LEAVES = new IntBlock(18, "leaves", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType SPONGE = new IntBlock(19, "sponge", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType GLASS = new IntBlock(20, "glass", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType LAPIS_LAZULI_ORE = new IntBlock(21, "lapis_lazuli_ore", 64, true, false, 0, 15, (server, i2, i3) -> {
return ImmutableList.of(server.createItemStackBuilder()
.material(ItemTypes.DYE)
.itemData(Dyed.of(DyeColor.BLUE))
.amount((4) + RANDOM.nextInt(5))
.build());
}, null);
public static final BlockType LAPIS_LAZULI_BLOCK = new IntBlock(22, "lapis_lazuli_block", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType DISPENSER = new IntBlock(23, "dispenser", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType SANDSTONE = new IntBlock(24, "sandstone", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType NOTE_BLOCK = new IntBlock(25, "note_block", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BED = new IntBlock(26, "bed", 1, true, true, 0, 0, (server, i2, i3) -> {
return ImmutableList.of(server.createItemStackBuilder()
.material(ItemTypes.BED)
.amount(1)
.build());
}, null);
public static final BlockType POWERED_RAIL = new IntBlock(27, "powered_rail", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType DETECTOR_RAIL = new IntBlock(28, "detector_rail", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType COBWEB = new IntBlock(30, "cobweb", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType TALL_GRASS = new IntBlock(31, "tall_grass", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType DEAD_BUSH = new IntBlock(32, "dead_bush", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType WOOL = new IntBlock(35, "wool", 64, true, false, 0, 15, SelfDrop.INSTANCE, Dyed.class);
public static final BlockType DANDELION = new IntBlock(37, "dandelion", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType FLOWER = new IntBlock(38, "flower", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BROWN_MUSHROOM = new IntBlock(39, "brown_mushroom", 64, true, false, 1, 15, SelfDrop.INSTANCE, null);
public static final BlockType RED_MUSHROOM = new IntBlock(40, "red_mushroom", 64, true, false, 1, 15, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_GOLD = new IntBlock(41, "block_of_gold", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_IRON = new IntBlock(42, "block_of_iron", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType DOUBLE_STONE_SLAB = new IntBlock(43, "double_stone_slab", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType STONE_SLAB = new IntBlock(44, "stone_slab", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BRICKS = new IntBlock(45, "bricks", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType TNT = new IntBlock(46, "tnt", 64, true, true, 0, 0, (server, i2, i3) -> ImmutableList.of(), null);
public static final BlockType BOOKSHELF = new IntBlock(47, "bookshelf", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType MOSS_STONE = new IntBlock(48, "moss_stone", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType OBSIDIAN = new IntBlock(49, "obsidian", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType TORCH = new IntBlock(50, "torch", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType FIRE = new IntBlock(51, "fire", 0, true, true, 15, 0, SelfDrop.INSTANCE, null);
public static final BlockType MONSTER_SPAWNER = new IntBlock(52, "monster_spawner", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType OAK_WOOD_STAIRS = new IntBlock(53, "oak_wood_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType CHEST = new IntBlock(54, "chest", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType REDSTONE_WIRE = new IntBlock(55, "redstone_wire", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType DIAMOND_ORE = new IntBlock(56, "diamond_ore", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_DIAMOND = new IntBlock(57, "block_of_diamond", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType CRAFTING_TABLE = new IntBlock(58, "crafting_table", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType CROPS = new IntBlock(59, "crops", 0, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType FARMLAND = new IntBlock(60, "farmland", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType FURNACE = new IntBlock(61, "furnace", 64, true, true, 13, 0, SelfDrop.INSTANCE, null);
public static final BlockType FURNACE_ACTIVE = new IntBlock(62, "furnace", 64, true, true, 13, 0, SelfDrop.INSTANCE, null);
public static final BlockType SIGN = new IntBlock(63, "sign", 16, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType WOODEN_DOOR = new IntBlock(64, "wooden_door", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType LADDER = new IntBlock(65, "ladder", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType RAIL = new IntBlock(66, "rail", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType COBBLESTONE_STAIRS = new IntBlock(67, "cobblestone_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType WALL_SIGN = new IntBlock(68, "sign", 16, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType LEVER = new IntBlock(69, "lever", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType STONE_PRESSURE_PLATE = new IntBlock(70, "stone_pressure_plate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType IRON_DOOR = new IntBlock(71, "iron_door", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType WOODEN_PRESSURE_PLATE = new IntBlock(72, "wooden_pressure_plate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType REDSTONE_ORE = new IntBlock(73, "redstone_ore", 64, true, true, 9, 0, (server, i2, i3) -> {
return ImmutableList.of(server.createItemStackBuilder()
.material(ItemTypes.REDSTONE)
.amount(4 + RANDOM.nextInt(2))
.build());
}, null);
public static final BlockType REDSTONE_ORE_ACTIVE = new IntBlock(74, "redstone_ore", 64, true, true, 9, 0, (server, i2, i3) -> {
return ImmutableList.of(server.createItemStackBuilder()
.material(ItemTypes.REDSTONE)
.amount(4 + RANDOM.nextInt(2))
.build());
}, null);
public static final BlockType REDSTONE_TORCH = new IntBlock(75, "redstone_torch", 64, true, true, 7, 0, SelfDrop.INSTANCE, null);
public static final BlockType REDSTONE_TORCH_ACTIVE = new IntBlock(76, "redstone_torch", 64, true, true, 7, 0, (server, i2, i3) -> {
return ImmutableList.of(server.createItemStackBuilder()
.material(REDSTONE_TORCH)
.amount(1)
.build());
}, null);
public static final BlockType STONE_BUTTON = new IntBlock(77, "stone_button", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType TOP_SNOW = new IntBlock(78, "top_snow", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType ICE = new IntBlock(79, "ice", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType SNOW = new IntBlock(80, "snow", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType CACTUS = new IntBlock(81, "cactus", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType CLAY = new IntBlock(82, "clay", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType SUGAR_CANE = new IntBlock(83, "sugar_cane", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType FENCE = new IntBlock(85, "fence", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType PUMPKIN = new IntBlock(86, "pumpkin", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType NETHERRACK = new IntBlock(87, "netherrack", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType SOUL_SAND = new IntBlock(88, "soul_sand", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType GLOWSTONE = new IntBlock(89, "glowstone", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType PORTAL = new IntBlock(90, "portal", 0, false, false, 0, 15, (server, i2, i3) -> ImmutableList.of(), null);
public static final BlockType JACK_OLANTERN = new IntBlock(91, "jack_o'lantern", 64, true, true, 15, 15, SelfDrop.INSTANCE, null);
public static final BlockType CAKE = new IntBlock(92, "cake", 1, true, true, 0, 0, (server, i2, i3) -> ImmutableList.of(), null);
public static final BlockType REDSTONE_REPEATER = new IntBlock(93, "redstone_repeater", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType REDSTONE_REPEATER_ACTIVE = new IntBlock(94, "redstone_repeater", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType INVISIBLE_BEDROCK = new IntBlock(95, "invisible_bedrock", 64, false, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType TRAPDOOR = new IntBlock(96, "trapdoor", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType MONSTER_EGG = new IntBlock(97, "monster_egg", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType STONE_BRICK = new IntBlock(98, "stone_brick", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BROWN_MUSHROOM_BLOCK = new IntBlock(99, "brown_mushroom", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType RED_MUSHROOM_BLOCK = new IntBlock(100, "red_mushroom", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType IRON_BARS = new IntBlock(101, "iron_bars", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType GLASS_PANE = new IntBlock(102, "glass_pane", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType MELON = new IntBlock(103, "melon", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType PUMPKIN_STEM = new IntBlock(104, "pumpkin_stem", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType MELON_STEM = new IntBlock(105, "melon_stem", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType VINES = new IntBlock(106, "vines", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType FENCE_GATE = new IntBlock(107, "fence_gate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BRICK_STAIRS = new IntBlock(108, "brick_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType STONE_BRICK_STAIRS = new IntBlock(109, "stone_brick_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType MYCELIUM = new IntBlock(110, "mycelium", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType LILY_PAD = new IntBlock(111, "lily_pad", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType NETHER_BRICK = new IntBlock(112, "nether_brick", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType NETHER_BRICK_FENCE = new IntBlock(113, "nether_brick_fence", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType NETHER_BRICK_STAIRS = new IntBlock(114, "nether_brick_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType NETHER_WART = new IntBlock(115, "nether_wart", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType ENCHANTMENT_TABLE = new IntBlock(116, "enchantment_table", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BREWING_STAND = new IntBlock(117, "brewing_stand", 64, true, true, 1, 0, SelfDrop.INSTANCE, null);
public static final BlockType CAULDRON = new IntBlock(118, "cauldron", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType END_PORTAL_FRAME = new IntBlock(120, "end_portal_frame", 64, false, true, 1, 0, SelfDrop.INSTANCE, null);
public static final BlockType END_STONE = new IntBlock(121, "end_stone", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType REDSTONE_LAMP = new IntBlock(122, "redstone_lamp", 64, true, true, 15, 0, SelfDrop.INSTANCE, null);
public static final BlockType REDSTONE_LAMP_ACTIVE = new IntBlock(123, "redstone_lamp", 64, true, true, 15, 0, SelfDrop.INSTANCE, null);
public static final BlockType ACTIVATOR_RAIL = new IntBlock(126, "activator_rail", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType COCOA = new IntBlock(127, "cocoa", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType SANDSTONE_STAIRS = new IntBlock(128, "sandstone_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType EMERALD_ORE = new IntBlock(129, "emerald_ore", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType TRIPWIRE_HOOK = new IntBlock(131, "tripwire_hook", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType TRIPWIRE = new IntBlock(132, "tripwire", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_EMERALD = new IntBlock(133, "block_of_emerald", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType SPRUCE_WOOD_STAIRS = new IntBlock(134, "spruce_wood_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BIRCH_WOOD_STAIRS = new IntBlock(135, "birch_wood_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType JUNGLE_WOOD_STAIRS = new IntBlock(136, "jungle_wood_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType COBBLESTONE_WALL = new IntBlock(139, "cobblestone_wall", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType FLOWER_POT = new IntBlock(140, "flower_pot", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType CARROTS = new IntBlock(141, "carrots", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType POTATO = new IntBlock(142, "potato", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType WOODEN_BUTTON = new IntBlock(143, "wooden_button", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType MOB_HEAD = new IntBlock(144, "mob_head", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType ANVIL = new IntBlock(145, "anvil", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType TRAPPED_CHEST = new IntBlock(146, "trapped_chest", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType WEIGHTED_PRESSURE_PLATE_LIGHT = new IntBlock(147, "weighted_pressure_plate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType WEIGHTED_PRESSURE_PLATE_HEAVY = new IntBlock(148, "weighted_pressure_plate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType DAYLIGHT_SENSOR = new IntBlock(151, "daylight_sensor", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_REDSTONE = new IntBlock(152, "block_of_redstone", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType NETHER_QUARTZ_ORE = new IntBlock(153, "nether_quartz_ore", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_QUARTZ = new IntBlock(155, "block_of_quartz", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType QUARTZ_STAIRS = new IntBlock(156, "quartz_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType WOODEN_DOUBLE_SLAB = new IntBlock(157, "wooden_double_slab", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType WOODEN_SLAB = new IntBlock(158, "wooden_slab", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType STAINED_CLAY = new IntBlock(159, "stained_clay", 64, true, false, 0, 15, SelfDrop.INSTANCE, Dyed.class);
public static final BlockType ACACIA_LEAVES = new IntBlock(161, "acacia_leaves", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType ACACIA_WOOD = new IntBlock(162, "acacia_wood", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType ACACIA_WOOD_STAIRS = new IntBlock(163, "acacia_wood_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType DARK_OAK_WOOD_STAIRS = new IntBlock(164, "dark_oak_wood_stairs", 64, true, true, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType IRON_TRAPDOOR = new IntBlock(167, "iron_trapdoor", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType HAY_BALE = new IntBlock(170, "hay_bale", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType CARPET = new IntBlock(171, "carpet", 64, true, true, 0, 0, SelfDrop.INSTANCE, Dyed.class);
public static final BlockType HARDENED_CLAY = new IntBlock(172, "hardened_clay", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BLOCK_OF_COAL = new IntBlock(173, "block_of_coal", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType PACKED_ICE = new IntBlock(174, "packed_ice", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType SUNFLOWER = new IntBlock(175, "sunflower", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType INVERTED_DAYLIGHT_SENSOR = new IntBlock(178, "inverted_daylight_sensor", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType SPRUCE_FENCE_GATE = new IntBlock(183, "spruce_fence_gate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType BIRCH_FENCE_GATE = new IntBlock(184, "birch_fence_gate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType JUNGLE_FENCE_GATE = new IntBlock(185, "jungle_fence_gate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType DARK_OAK_FENCE_GATE = new IntBlock(186, "dark_oak_fence_gate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType ACACIA_FENCE_GATE = new IntBlock(187, "acacia_fence_gate", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType GRASS_PATH = new IntBlock(198, "grass_path", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType ITEM_FRAME = new IntBlock(199, "item_frame", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType PODZOL = new IntBlock(243, "podzol", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType BEETROOT = new IntBlock(244, "beetroot", 64, true, true, 0, 0, SelfDrop.INSTANCE, null);
public static final BlockType STONECUTTER = new IntBlock(245, "stonecutter", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
public static final BlockType GLOWING_OBSIDIAN = new IntBlock(246, "glowing_obsidian", 64, true, false, 12, 15, SelfDrop.INSTANCE, null);
public static final BlockType NETHER_REACTOR_CORE = new IntBlock(247, "nether_reactor_core", 64, true, false, 0, 15, SelfDrop.INSTANCE, null);
private interface DroppedHandler {
Collection<ItemStack> drop(Server server, Block block, ItemStack with);
}
private static class SelfDrop implements DroppedHandler {
private static SelfDrop INSTANCE = new SelfDrop();
@Override
public Collection<ItemStack> drop(Server server, Block block, ItemStack with) {
ItemStackBuilder builder = server.createItemStackBuilder().material(block.getBlockState().getBlockType()).amount(1);
if (block.getBlockState().getBlockData() != null && block.getBlockState().getBlockData() instanceof BlockData) {
builder.itemData((ItemData) block.getBlockState().getBlockData());
}
return ImmutableList.of(builder.build());
}
}
private static class IntBlock implements BlockType {
private final int id;
private final String name;
private final int maxStackSize;
private final boolean diggable;
private final boolean transparent;
private final int emitLight;
private final int filterLight;
private final DroppedHandler dropHandler;
private final Class<? extends BlockData> aClass;
public IntBlock(int id, String name, int maxStackSize, boolean diggable, boolean transparent, int emitLight, int filterLight, DroppedHandler dropHandler, Class<? extends BlockData> aClass) {
this.id = id;
this.name = name;
this.maxStackSize = maxStackSize;
this.diggable = diggable;
this.transparent = transparent;
this.emitLight = emitLight;
this.filterLight = filterLight;
this.dropHandler = dropHandler;
this.aClass = aClass;
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public Class<? extends ItemData> getMaterialDataClass() {
if (ItemData.class.isAssignableFrom(aClass)) {
return (Class<? extends ItemData>) aClass;
}
return null;
}
@Override
public int getMaximumStackSize() {
return maxStackSize;
}
@Override
public boolean isDiggable() {
return diggable;
}
@Override
public boolean isTransparent() {
return transparent;
}
@Override
public int emitsLight() {
return emitLight;
}
@Override
public int filtersLight() {
return filterLight;
}
@Override
public Collection<ItemStack> getDrops(Server server, Block block, ItemStack with) {
return dropHandler.drop(server, block, with);
}
@Override
public Class<? extends BlockData> getBlockDataClass() {
return aClass;
}
}
}
|
package com.breadwallet.platform;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import com.breadwallet.BreadApp;
import com.breadwallet.presenter.activities.BreadActivity;
import com.breadwallet.tools.util.BRCompressor;
import com.breadwallet.tools.util.Utils;
import com.jniwrappers.BRKey;
import com.platform.APIClient;
import com.platform.tools.BRBitId;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.platform.APIClient.BREAD_POINT;
import io.sigpipe.jbsdiff.InvalidHeaderException;
import io.sigpipe.jbsdiff.Patch;
import okhttp3.Request;
import okhttp3.Response;
import static com.platform.APIClient.BUNDLES;
import static com.platform.APIClient.BUY_FILE;
import static com.platform.APIClient.BUY_EXTRACTED_FOLDER;
@RunWith(AndroidJUnit4.class)
public class PlatformTests {
public static final String TAG = PlatformTests.class.getName();
@Rule
public ActivityTestRule<BreadActivity> mActivityRule = new ActivityTestRule<>(
BreadActivity.class);
// proto is the transport protocol to use for talking to the API (either http or https)
private static final String PROTO = "https";
// host is the server(s) on which the API is hosted
// private static final String HOST = "api.breadwallet.com";
// convenience getter for the API endpoint
private static final String BASE_URL = PROTO + "://" + BreadApp.HOST;
//feePerKb url
private static final String FEE_PER_KB_URL = "/v1/fee-per-kb";
//token
private static final String TOKEN = "/token";
private static final String ME = "/me";
private static final String GET = "GET";
private static final String POST = "POST";
//loading the native library
static {
System.loadLibrary("core");
}
@Test
public void testFeePerKbFetch() {
long fee = APIClient.getInstance(mActivityRule.getActivity()).feePerKb();
System.out.println("testFeePerKbFetch: fee: " + fee);
Assert.assertNotSame(fee, (long) 0);
}
@Test
public void bundleExtractTest() {
File bundleFile = new File(mActivityRule.getActivity().getFilesDir().getAbsolutePath() + BUY_FILE);
Request request = new Request.Builder()
.url(String.format("%s/assets/bundles/%s/download", BASE_URL, BREAD_POINT))
.get().build();
Response response = null;
APIClient apiClient = APIClient.getInstance(mActivityRule.getActivity());
response = apiClient.sendRequest(request, false, 0);
apiClient.writeBundleToFile(response, bundleFile);
String extractFolderName = BreadActivity.getApp().getFilesDir() + "/" + BUNDLES + "/" + BUY_EXTRACTED_FOLDER;
apiClient.tryExtractTar(bundleFile, extractFolderName);
File temp = new File(extractFolderName);
int filesExtracted = temp.listFiles().length;
Log.e(TAG, "bundleExtractTest: filesExtracted: " + filesExtracted);
Assert.assertNotSame(filesExtracted, 0);
Log.e(TAG, "bundleExtractTest: ");
if (temp.isDirectory()) {
String[] children = temp.list();
for (int i = 0; i < children.length; i++) {
new File(temp, children[i]).delete();
}
}
}
@Test
public void bundleDownloadTest() {
APIClient apiClient = APIClient.getInstance(mActivityRule.getActivity());
Request request = new Request.Builder()
.get()
.url("https://s3.amazonaws.com/breadwallet-assets/bread-buy/7f5bc5c6cc005df224a6ea4567e508491acaffdc2e4769e5262a52f5b785e261.tar").build();
Response response = apiClient.sendRequest(request, false, 0);
File bundleFile = new File(mActivityRule.getActivity().getFilesDir().getAbsolutePath() + BUY_FILE);
apiClient.writeBundleToFile(response, bundleFile);
String latestVersion = apiClient.getLatestVersion(BREAD_POINT);
Assert.assertNotNull(latestVersion);
String currentTarVersion = getCurrentVersion(bundleFile);
Log.e(TAG, "bundleUpdateTest: latestVersion: " + latestVersion + ", currentTarVersion: " + currentTarVersion);
Assert.assertNotNull(currentTarVersion);
Assert.assertNotEquals(latestVersion, currentTarVersion);
}
@Test
public void bundleUpdateTest() {
APIClient apiClient = APIClient.getInstance(mActivityRule.getActivity());
Request request = new Request.Builder()
.get()
.url("https://s3.amazonaws.com/breadwallet-assets/bread-buy/bundle.tar").build();
Response response = apiClient.sendRequest(request, false, 0);
File bundleFileOld = new File(mActivityRule.getActivity().getFilesDir().getAbsolutePath() + String.format("/%s/%s.tar", BUNDLES, BREAD_POINT));
byte[] bundleFileOldBytes = apiClient.writeBundleToFile(response, bundleFileOld);
request = new Request.Builder()
.get()
.url("https://s3.amazonaws.com/breadwallet-assets/bread-buy/bundle2.tar").build();
response = apiClient.sendRequest(request, false, 0);
File bundleFileLatest = new File(mActivityRule.getActivity().getFilesDir().getAbsolutePath() + String.format("/%s/%s.tar", BUNDLES, BREAD_POINT + "-test"));
apiClient.writeBundleToFile(response, bundleFileLatest);
request = new Request.Builder()
.get()
.url("https://s3.amazonaws.com/breadwallet-assets/bread-buy/bundle_bundle2.bspatch").build();
response = apiClient.sendRequest(request, false, 0);
File patch = new File(mActivityRule.getActivity().getFilesDir().getAbsolutePath() + String.format("/%s/%s.bspatch", BUNDLES, "patch"));
byte[] patchBytes = apiClient.writeBundleToFile(response, patch);
Assert.assertTrue(bundleFileOld.exists() && bundleFileOld.length() > 10);
Assert.assertTrue(bundleFileLatest.exists() && bundleFileLatest.length() > 10);
Assert.assertTrue(patch.exists() && patch.length() > 10);
Log.e(TAG, "bundleUpdateTest: bundleFileOld.length(): " + bundleFileOld.length());
Log.e(TAG, "bundleUpdateTest: bundleFileLatest.length(): " + bundleFileLatest.length());
Log.e(TAG, "bundleUpdateTest: patch.length(): " + patch.length());
byte[] oldFileBytes = new byte[0];
byte[] correctFileBytes = new byte[0];
try {
FileOutputStream outputStream = new FileOutputStream(mActivityRule.getActivity().getFilesDir().getAbsolutePath() + String.format("/%s/%s.tar", BUNDLES, BREAD_POINT));
Log.e(TAG, "bundleUpdateTest: beforeDiff");
Patch.patch(bundleFileOldBytes, patchBytes, outputStream);
byte[] updatedBundleBytes = IOUtils.toByteArray(new FileInputStream(bundleFileOld));
Log.e(TAG, "bundleUpdateTest: updatedBundleBytes: " + updatedBundleBytes.length);
oldFileBytes = IOUtils.toByteArray(new FileInputStream(bundleFileOld));
correctFileBytes = IOUtils.toByteArray(new FileInputStream(bundleFileLatest));
} catch (IOException | InvalidHeaderException | CompressorException e) {
e.printStackTrace();
} finally {
boolean delete = patch.delete();
Log.e(TAG, "WARNING bundleUpdateTest: deleting patch, file deleted: " + delete);
}
Log.e(TAG, "bundleUpdateTest: oldFileBytes: " + oldFileBytes.length + ", correctFileBytes: " + correctFileBytes.length);
Assert.assertArrayEquals(oldFileBytes, correctFileBytes);
Assert.assertTrue(oldFileBytes.length != 0 && correctFileBytes.length != 0);
}
private String getCurrentVersion(File bundleFile) {
byte[] bFile;
String currentTarVersion = null;
try {
bFile = IOUtils.toByteArray(new FileInputStream(bundleFile));
Log.e(TAG, "bundleUpdateTest: bFile.length: " + bFile.length);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(bFile);
currentTarVersion = Utils.bytesToHex(hash);
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return currentTarVersion;
}
@Test
public void testGetToken() {
APIClient apiClient = APIClient.getInstance(mActivityRule.getActivity());
String token = apiClient.getToken();
Assert.assertNotNull(token);
Assert.assertNotEquals(token.length(), 0);
}
@Test
public void testMeRequest() {
APIClient apiClient = APIClient.getInstance(mActivityRule.getActivity());
Response response = apiClient.buyBitcoinMe();
Assert.assertTrue(response.isSuccessful());
}
@Test
public void testGZIP() {
String data = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip 11111111for the future, " +
"sunscreen would be it.";
Assert.assertFalse(BRCompressor.isGZIPStream(data.getBytes()));
byte[] compressedData = BRCompressor.gZipCompress(data.getBytes());
Assert.assertTrue(BRCompressor.isGZIPStream(compressedData));
Log.e(TAG, "testGZIP: " + new String(compressedData));
Assert.assertNotNull(compressedData);
Assert.assertTrue(compressedData.length > 0);
byte[] decompressedData = BRCompressor.gZipExtract(compressedData);
Assert.assertFalse(BRCompressor.isGZIPStream(decompressedData));
Assert.assertNotNull(decompressedData);
Assert.assertEquals(new String(decompressedData), data);
Assert.assertNotEquals(compressedData.length, decompressedData.length);
}
@Test
public void testBZip2() {
String data = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip 11111111for the future, " +
"sunscreen would be it.";
byte[] compressedData = BRCompressor.bz2Compress(data.getBytes());
Assert.assertNotNull(compressedData);
Assert.assertTrue(compressedData.length > 0);
byte[] decompressedData = BRCompressor.bz2Extract(compressedData);
Assert.assertNotNull(decompressedData);
Assert.assertEquals(new String(decompressedData), data);
Assert.assertNotEquals(compressedData.length, decompressedData.length);
}
@Test
public void testBitIdSignature() {
BRKey key = new BRKey("c4c9b99b714074736b65d9faab39145949894233a09d8100b91104750a82d31f");
String message = "https://breadwallet.com/bitid?nonce=123456789";
String expectedSig = "ICWek6XEVxu/1/x+TtWk178t6uFcToH019RWNnS+JEeJOr2XGkZKQwsSqEvJ7l3sfhUoX1jm4uWP7nmlyG5Y10E=";
String sig = BRBitId.signMessage(message, key);
Log.e(TAG, "sig: " + sig);
String expectedAddress = "mjBrDFeeX9moESGiRZZGeYrsUSNuvgwDVV";
String address = key.address();
Log.e(TAG, "address: " + address);
Assert.assertEquals(expectedAddress, address);
Assert.assertNotNull(sig);
Assert.assertEquals(expectedSig.length(), sig.length());
Assert.assertEquals(expectedSig, sig);
}
}
|
package com.jameslawler.tenseven;
import junit.framework.TestCase;
import java.util.Calendar;
public class CountdownTest extends TestCase {
public void testWhenUpdateCalledWithWalkTimeShouldShowWalk() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 30);
time.set(Calendar.SECOND, 15);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Walk, Countdown.getInstance().State);
assertEquals("06:45", Countdown.getInstance().TimeLeft);
}
public void testWhenUpdateCalledWithRunTimeShouldShowRun() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 32);
time.set(Calendar.SECOND, 15);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Run, Countdown.getInstance().State);
assertEquals("04:45", Countdown.getInstance().TimeLeft);
}
public void testWhenUpdateCalledWithWaitTimeShouldShowWait() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 34);
time.set(Calendar.SECOND, 15);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Wait, Countdown.getInstance().State);
assertEquals("02:45", Countdown.getInstance().TimeLeft);
}
public void testWhenUpdateCalledWithExactlyBeforeSevenPast() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 36);
time.set(Calendar.SECOND, 59);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Wait, Countdown.getInstance().State);
assertEquals("00:01", Countdown.getInstance().TimeLeft);
}
public void testWhenUpdateCalledWithExactlySevenPast() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 37);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Walk, Countdown.getInstance().State);
assertEquals("10:00", Countdown.getInstance().TimeLeft);
}
public void testWhenUpdateCalledWithStartOfNewCountdown() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 37);
time.set(Calendar.SECOND, 1);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Walk, Countdown.getInstance().State);
assertEquals("09:59", Countdown.getInstance().TimeLeft);
}
public void testWhenUpdateCalledWithTimeAfterSevenPast() {
// Arrange
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 17);
time.set(Calendar.MINUTE, 39);
time.set(Calendar.SECOND, 35);
time.set(Calendar.MILLISECOND, 0);
// Act
Countdown.getInstance().Update(time);
// Assert
assertEquals(CountdownState.Walk, Countdown.getInstance().State);
assertEquals("07:25", Countdown.getInstance().TimeLeft);
}
}
|
package com.kuxhausen.huemore.editmood;
import java.util.ArrayList;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.gson.Gson;
import com.kuxhausen.huemore.BulbListFragment;
import com.kuxhausen.huemore.GodObject;
import com.kuxhausen.huemore.GroupListFragment;
import com.kuxhausen.huemore.R;
import com.kuxhausen.huemore.R.id;
import com.kuxhausen.huemore.R.layout;
import com.kuxhausen.huemore.R.menu;
import com.kuxhausen.huemore.network.GetBulbList.OnBulbListReturnedListener;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.InternalArguments;
import com.kuxhausen.huemore.state.api.BulbAttributes;
import com.kuxhausen.huemore.state.api.BulbState;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.support.v7.widget.GridLayout;
import android.support.v7.widget.GridLayout.LayoutParams;
import android.support.v7.widget.GridLayout.Spec;
public class EditAdvancedMoodFragment extends SherlockFragment implements OnClickListener {
Gson gson = new Gson();
GridLayout grid;
MoodRowAdapter rayAdapter;
Button addChannel, addTimeslot;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View myView = inflater.inflate(R.layout.activity_edit_advanced_mood, null);
addTimeslot = (Button) myView.findViewById(R.id.addTimeslotButton);
addTimeslot.setOnClickListener(this);
addChannel = (Button) myView.findViewById(R.id.addChannelButton);
//int h = addChannel.getHeight();
//int w = addChannel.getWidth();
//addChannel.setRotation(270);
//addChannel.setHeight(w);
//addChannel.setWidth(h);
addChannel.setOnClickListener(this);
grid = (GridLayout) myView.findViewById(R.id.advancedGridLayout);
grid.setColumnCount(2);
grid.setRowCount(2);
Log.e("colrow",grid.getColumnCount()+" "+grid.getRowCount());
rayAdapter = new MoodRowAdapter(this.getActivity(), new ArrayList<MoodRow>(), this);
addState();
addState();
addState();
addState();
redrawGrid();
return myView;
}
private void addState() {
MoodRow mr = new MoodRow();
mr.color = 0xff000000;
BulbState example = new BulbState();
example.on = false;
mr.hs = example;
rayAdapter.add(mr);
}
private void addState(int i) {
MoodRow mr = new MoodRow();
mr.color = 0xff000000;
BulbState example = new BulbState();
example.on = false;
mr.hs = example;
rayAdapter.insert(mr, i);
}
private void populateGrid(int index){
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(index % grid.getColumnCount());
vg.rowSpec = GridLayout.spec(index / grid.getRowCount());
grid.addView(rayAdapter.getView(index, null, grid), vg);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
rayAdapter.getItem(requestCode).color = resultCode;
rayAdapter.notifyDataSetChanged();
rayAdapter.getItem(requestCode).hs = gson.fromJson(
data.getStringExtra(InternalArguments.HUE_STATE),
BulbState.class);
/*String[] states = new String[moodRowArray.size()];
for (int i = 0; i < moodRowArray.size(); i++) {
states[i] = gson.toJson(moodRowArray.get(i).hs);
}*/
//Utils.transmit(this.getActivity(), InternalArguments.ENCODED_TRANSIENT_MOOD, getMood(), ((GodObject)this.getActivity()).getBulbs(), null);
redrawGrid();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.clickable_layout:
EditStatePagerDialogFragment cpdf = new EditStatePagerDialogFragment();
//Bundle args = new Bundle();
//args.putString(InternalArguments.PREVIOUS_STATE,
// gson.toJson(rayAdapter.getItem((Integer) v.getTag()).hs));
//cpdf.setArguments(args);
//cpdf.show(this.getFragmentManager(), "dialog");
cpdf.setTargetFragment(this, (Integer) v.getTag());
cpdf.show(getFragmentManager(),
InternalArguments.FRAG_MANAGER_DIALOG_TAG);
break;
case R.id.addChannelButton:
int width = grid.getColumnCount();
grid.setColumnCount(1+width);
for(int i = rayAdapter.getCount(); i>0; i-=width){
addState(i);
}
redrawGrid();
break;
case R.id.addTimeslotButton:
grid.setRowCount(grid.getRowCount()+1);
for(int i = grid.getColumnCount(); i>0; i
addState();
}
redrawGrid();
break;
}
}
private void redrawGrid() {
grid.removeAllViews();
for(int r = 0; r< grid.getRowCount(); r++)
for(int c = 0; c<grid.getColumnCount(); c++){
GridLayout.LayoutParams vg = new GridLayout.LayoutParams();
vg.columnSpec = GridLayout.spec(c);
vg.rowSpec = GridLayout.spec(r);
grid.addView(rayAdapter.getView(r*grid.getColumnCount()+c, null, grid), vg);
}
grid.invalidate();
}
}
|
package ar.edu.unc.famaf.redditreader.model;
import java.util.Date;
public class PostModel {
private String mTitle;
private String mAuthor;
private Date mDate;
private int mCommentNumber;
private String mThumbnail; // This is the image URL
public PostModel() {
}
public PostModel(String title, String author, Date date, int commentNumber, String thumbnail) {
mTitle = title;
mAuthor = author;
mDate = date;
mCommentNumber = commentNumber;
mThumbnail = thumbnail;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public String getAuthor() {
return mAuthor;
}
public void setAuthor(String author) {
mAuthor = author;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public int getCommentNumber() {
return mCommentNumber;
}
public void setCommentNumber(int commentNumber) {
mCommentNumber = commentNumber;
}
public String getThumbnail() {
return mThumbnail;
}
public void setThumbnail(String thumbnail) {
mThumbnail = thumbnail;
}
}
|
package com.example.krakora.budgetkeeper;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.example.krakora.budgetkeeper.data.TableArtists;
import com.example.krakora.budgetkeeper.data.TableTracks;
import com.example.krakora.budgetkeeper.data.TableTracks_Table;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.Select;
import com.raizlabs.android.dbflow.structure.ModelAdapter;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private boolean priceTogle;
public static interface ClickListener{
public void onClick(View view,int position);
public void onLongClick(View view,int position);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// DBFlow init
FlowManager.init(this);
final ModelAdapter<TableTracks> db_tracks = FlowManager.getModelAdapter(TableTracks.class);
final ModelAdapter<TableArtists> db_artists = FlowManager.getModelAdapter(TableArtists.class);
// ListView
/*
ListView lst = (ListView) findViewById(R.id.list_view);
// ListView data
// Create an empty List from String Array elements
String[] values = new String[] {};
final List<String> item_list = new ArrayList<String>(Arrays.asList(values));
// Get data from DB
List<TableArtists> ql = new Select().from(TableArtists.class).queryList();
for (int i = 1; i < ql.size(); i++){
item_list.add(ql.get(i).Name);
};
Collections.sort(item_list);
// Create an ArrayAdapter from the ListView
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, item_list);
// Bind data
lst.setAdapter(arrayAdapter);
*/
// Transaction ListView via RecyclerView
// Create empty list of transaction objects
List<TableTracks> data = new Select().
from(TableTracks.class).
where(TableTracks_Table.Name.is("Outcome")).
or(TableTracks_Table.Name.is("Income")).
orderBy(TableTracks_Table.Name,true).
queryList();
// Setup and Handover data to RecyclerView
RecyclerView rvtl = (RecyclerView) findViewById(R.id.transaction_list);
final AdapterTransaction transactionAdapter = new AdapterTransaction(MainActivity.this, data);
rvtl.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rvtl.setLayoutManager(mLayoutManager);
rvtl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
rvtl.setItemAnimator(new DefaultItemAnimator());
rvtl.setAdapter(transactionAdapter);
// priceTogle init
priceTogle = false;
rvtl.addOnItemTouchListener(
new RecyclerTouchListener(this, rvtl, new ClickListener() {
@Override
public void onClick(View view, final int position) {
//Values are passing to activity & to fragment as well
Snackbar.make(view,
"Single Click on position :" + position,
Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
@Override
public void onLongClick(View view, int position) {
Snackbar.make(view, "Long press on position :" + position,
Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
}));
// FloatingActionButton
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// RecyclerView change handling
// Inset an item
TableTracks t = new TableTracks();
if(priceTogle) {
t.Name = "Income";
t.UnitPrice = 100;
priceTogle = false;
} else {
t.Name = "Outcome";
t.UnitPrice = -100;
priceTogle = true;
};
db_tracks.insert(t);
// Update List
List<TableTracks> data = new Select().
from(TableTracks.class).
where(TableTracks_Table.Name.is("Outcome")).
or(TableTracks_Table.Name.is("Income")).
orderBy(TableTracks_Table.Name,true).
queryList();
transactionAdapter.updateData(data);
// Inform
Snackbar.make(view,
"Fictive transaction `" + t.Name + "` added!",
Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id) {
case R.id.action_settings:
Intent sa = new Intent(this, SettingsActivity.class);
this.startActivity(sa);
break;
case R.id.action_about:
Intent aa = new Intent(this, AboutActivity.class);
this.startActivity(aa);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
|
package com.example.todocloud.service;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import com.example.todocloud.data.Todo;
import com.example.todocloud.datastorage.DbLoader;
import com.example.todocloud.receiver.ReminderReceiver;
import java.util.ArrayList;
import java.util.Date;
public class ReminderService extends IntentService {
private static final String TAG = ReminderService.class.getSimpleName();
public static final String CREATE = "CREATE";
public static final String CANCEL = "CANCEL";
private IntentFilter matcher;
private DbLoader dbLoader;
public ReminderService() {
super(TAG);
matcher = new IntentFilter();
matcher.addAction(CREATE);
matcher.addAction(CANCEL);
}
@Override
public void onCreate() {
super.onCreate();
dbLoader = new DbLoader(this);
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
Todo todo = intent.getParcelableExtra("todo");
if (matcher.matchAction(action)) {
execute(action, todo);
}
}
private void execute(String action, Todo todo) {
if (isSingleReminder(todo)) {
handleReminder(todo, action);
} else {
handleReminders(action);
}
}
private boolean isSingleReminder(Todo todo) {
return todo != null;
}
private void handleReminder(Todo todo, String action) {
Intent reminderIntent = prepareReminderIntent(todo);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this,
(int) todo.get_id(),
reminderIntent,
PendingIntent.FLAG_ONE_SHOT
);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (isNotPastReminderDateTime(todo)) {
if (CREATE.equals(action)) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
todo.getReminderDateTimeInLong(),
pendingIntent
);
} else {
alarmManager.cancel(pendingIntent);
}
} else {
alarmManager.cancel(pendingIntent);
}
}
@NonNull
private Intent prepareReminderIntent(Todo todo) {
Intent reminderIntent = new Intent(this, ReminderReceiver.class);
reminderIntent.putExtra("id", todo.get_id());
reminderIntent.putExtra("msg", todo.getTitle());
return reminderIntent;
}
private boolean isNotPastReminderDateTime(Todo todo) {
return todo.getReminderDateTimeInLong() >= new Date().getTime();
}
private void handleReminders(String action) {
ArrayList<Todo> todos = dbLoader.getTodosWithReminder();
for (Todo todo:todos) {
Intent reminderIntent = prepareReminderIntent(todo);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this, (int) todo.get_id(),
reminderIntent,
PendingIntent.FLAG_ONE_SHOT
);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (isNotPastReminderDateTime(todo)) {
if (CREATE.equals(action)) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
todo.getReminderDateTimeInLong(),
pendingIntent
);
} else {
alarmManager.cancel(pendingIntent);
}
} else {
alarmManager.cancel(pendingIntent);
}
}
}
}
|
package de.dbremes.dbtradealert;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Locale;
import de.dbremes.dbtradealert.DbAccess.DbHelper;
public class QuoteRefresherService extends IntentService {
private static final String CLASS_NAME = "QuoteRefresherService";
public static final String BROADCAST_ACTION_NAME = "QuoteRefresherAction";
public static final String BROADCAST_EXTRA_ERROR = "Error: ";
public static final String BROADCAST_EXTRA_NAME = "Message";
public static final String BROADCAST_EXTRA_REFRESH_COMPLETED = "Refresh completed";
public static final String INTENT_EXTRA_IS_MANUAL_REFRESH = "isManualRefresh";
private static final String exceptionMessage = "Exception caught";
public QuoteRefresherService() {
super("QuoteRefresherService");
} // ctor()
private boolean areExchangesOpenNow() {
final String methodName = "areExchangesOpenNow";
boolean result = false;
Calendar now = Calendar.getInstance();
int hourOfDay = now.get(Calendar.HOUR_OF_DAY);
if (hourOfDay >= 9 && hourOfDay <= 18) {
int dayOfWeek = now.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY) {
result = true;
} else {
Log.d(CLASS_NAME, String.format(
"%s(): Exchanges closed on weekends (day = %d)",
methodName, dayOfWeek));
}
} else {
Log.d(CLASS_NAME, String.format(
"%s(): Exchanges closed after hours (hour = %d)",
methodName, hourOfDay));
}
if (result) {
Log.d(CLASS_NAME, String.format(
"%s(): Exchanges open", methodName));
}
return result;
}// areExchangesOpenNow()
private String buildNotificationLineFromCursor(Cursor cursor) {
String result = null;
String actualName = cursor.getString(0);
float actualValue = cursor.getFloat(1);
String signalName = cursor.getString(2);
float signalValue = cursor.getFloat(3);
String symbol = cursor.getString(4);
result = String.format(Locale.getDefault(),
"%s: %s = %01.2f; %s = %01.2f", symbol, actualName,
actualValue, signalName, signalValue);
return result;
} // buildNotificationLineFromCursor()
@Override
protected void onHandleIntent(Intent intent) {
String baseUrl = "http://download.finance.yahoo.com/d/quotes.csv";
String url = baseUrl
+ "?f=" + DbHelper.QuoteDownloadFormatParameter
+ "&s=" + getSymbolParameterValue();
String quoteCsv = "";
try {
boolean isManualRefresh = intent.getBooleanExtra(INTENT_EXTRA_IS_MANUAL_REFRESH, false);
if (isManualRefresh || areExchangesOpenNow()) {
if (isConnected()) {
quoteCsv = downloadQuotes(url);
DbHelper dbHelper = new DbHelper(this);
dbHelper.updateOrCreateQuotes(quoteCsv);
// Notify user of triggered signals even if app is sleeping
dbHelper.updateSecurityMaxPrice();
sendNotificationForTriggeredSignals(dbHelper);
Log.d(CLASS_NAME,
"onHandleIntent(): quotes updated - initiating screen refresh");
sendLocalBroadcast(BROADCAST_EXTRA_REFRESH_COMPLETED);
} else {
sendLocalBroadcast(BROADCAST_EXTRA_ERROR + "no Internet!");
Log.d(CLASS_NAME, BROADCAST_EXTRA_ERROR + "no Internet!");
}
} else {
Log.d(CLASS_NAME,
"onHandleIntent(): exchanges closed and not a manual refresh - skipping alarm");
}
} catch (IOException e) {
Log.e(CLASS_NAME, exceptionMessage, e);
if (e instanceof UnknownHostException) {
// java.net.UnknownHostException:
// Unable to resolve host "download.finance.yahoo.com":
// No address associated with hostname
sendLocalBroadcast(BROADCAST_EXTRA_ERROR + "broken Internet connection!");
Log.d(CLASS_NAME, BROADCAST_EXTRA_ERROR + "broken Internet connection!");
}
// TODO: cannot rethrow in else case as that doesn't match overridden methods signature?
}
finally {
QuoteRefreshAlarmReceiver.completeWakefulIntent(intent);
}
} // onHandleIntent()
private String downloadQuotes(String urlString) throws IOException {
String result = "";
InputStream inputStream = null;
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
inputStream = conn.getInputStream();
result = getStringFromStream(inputStream);
Log.d(CLASS_NAME, "downloadQuotes(): got " + result.length() + " characters");
} else {
sendLocalBroadcast(BROADCAST_EXTRA_ERROR
+ "download failed (response code " + responseCode + ")!");
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return result;
} // downloadQuotes()
private String getStringFromStream(InputStream inputStream) throws IOException {
// Elaborate solution as this won't work because inputStream.available() always returns 0:
// byte[] data = new byte[inputStream.available()];
// inputStream.read(data);
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} // getStringFromStream()
private String getSymbolParameterValue() {
String result = "";
DbHelper dbHelper = new DbHelper(this);
Cursor cursor = dbHelper.readAllSecuritySymbols();
StringBuilder sb = new StringBuilder();
while (cursor.moveToNext()) {
sb.append(cursor.getString(0) + "+");
}
DbHelper.closeCursor(cursor);
String symbols = sb.toString();
if (sb.length() > 0) {
symbols = symbols.substring(0, symbols.length() - 1);
}
// Index symbols like "^SSMI" start with a "^" which is not allowed in URLs
try {
symbols = URLEncoder.encode(symbols, "UTF-8");
result += symbols;
} catch (UnsupportedEncodingException e) {
Log.e(CLASS_NAME, exceptionMessage, e);
}
return result;
} // getSymbolParameterValue()
private boolean isConnected() {
ConnectivityManager connectivityManager
= (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
} // isConnected()
private void sendLocalBroadcast(String message) {
Intent intent = new Intent(BROADCAST_ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_NAME, message);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
} // sendLocalBroadcast()
private void sendNotificationForTriggeredSignals(DbHelper dbHelper) {
final String methodName = "sendNotificationForTriggeredSignals";
Cursor cursor = dbHelper.readAllTriggeredSignals();
if (cursor.getCount() > 0) {
Context context = getApplicationContext();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.emo_im_money_mouth)
.setDefaults(Notification.DEFAULT_ALL)
.setNumber(cursor.getCount());
// Specify which intent to show when user taps notification
Intent watchlistListIntent = new Intent(this, WatchlistListActivity.class);
PendingIntent watchlistListPendingIntent
= PendingIntent.getActivity(context, 0, watchlistListIntent, 0);
builder.setContentIntent(watchlistListPendingIntent);
// Build back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(WatchlistListActivity.class);
stackBuilder.addNextIntent(watchlistListIntent);
// Create notification
if (cursor.getCount() == 1) {
cursor.moveToFirst();
String s = buildNotificationLineFromCursor(cursor);
builder.setContentTitle("Target hit").setContentText(s);
Log.v(CLASS_NAME, String.format("%s(): Notification = %s", methodName, s));
} else {
builder.setContentTitle(cursor.getCount() + " Targets hit");
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
builder.setStyle(inboxStyle);
while (cursor.moveToNext()) {
String s = buildNotificationLineFromCursor(cursor);
inboxStyle.addLine(s);
Log.v(CLASS_NAME, String.format("%s(): Notification = %s", methodName, s));
}
}
// Show notification
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Show new notification or update pending one
final int notificationId = 1234;
notificationManager.notify(notificationId, builder.build());
}
Log.d(CLASS_NAME,
String.format("%s(): created %d notifications", methodName, cursor.getCount()));
DbHelper.closeCursor(cursor);
} // sendNotificationForTriggeredSignals()
} // class QuoteRefresherService
|
package org.commcare.dalvik.activities;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Vector;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.commcare.android.database.SqlStorage;
import org.commcare.android.database.user.models.FormRecord;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.ManagedUi;
import org.commcare.android.framework.UiElement;
import org.commcare.android.javarosa.AndroidLogger;
import org.commcare.android.models.notifications.NotificationMessageFactory;
import org.commcare.android.tasks.DumpTask;
import org.commcare.android.tasks.FormRecordCleanupTask;
import org.commcare.android.tasks.ProcessAndSendTask;
import org.commcare.android.tasks.ProcessAndSendTask.ProcessIssues;
import org.commcare.android.tasks.SendTask;
import org.commcare.android.util.FileUtil;
import org.commcare.android.util.ReflectionUtil;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.services.storage.StorageFullException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
/**
* @author wspride
*
*/
@ManagedUi(R.layout.screen_form_dump)
public class CommCareFormDumpActivity extends CommCareActivity<CommCareFormDumpActivity> {
@UiElement(R.id.screen_bulk_image1)
ImageView banner;
@UiElement(value = R.id.screen_bulk_form_prompt, locale="bulk.form.prompt")
TextView txtDisplayPrompt;
@UiElement(value = R.id.screen_bulk_form_dump, locale="bulk.form.dump")
Button btnDumpForms;
@UiElement(value = R.id.screen_bulk_form_submit, locale="bulk.form.submit")
Button btnSubmitForms;
@UiElement(value = R.id.screen_bulk_form_messages, locale="bulk.form.messages")
TextView txtInteractiveMessages;
boolean done = false;
AlertDialog mAlertDialog;
static boolean acknowledgedRisk = false;
static final int BULK_DUMP_ID = 2;
static final int BULK_SEND_ID = 3;
static final String KEY_NUMBER_DUMPED = "num_dumped";
public static final String EXTRA_FILE_DESTINATION = "ccodk_mia_filedest";
private int formsOnPhone;
private int formsOnSD;
/* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
final String url = this.getString(R.string.PostURL);
super.onCreate(savedInstanceState);
//get number of unsynced forms for display purposes
Vector<Integer> ids = getUnsyncedForms();
File[] files = CommCareFormDumpActivity.getDumpFiles();
formsOnSD = files.length;
formsOnPhone = ids.size();
setDisplayText();
btnSubmitForms.setOnClickListener(new OnClickListener() {
public void onClick(View v){
formsOnSD = CommCareFormDumpActivity.getDumpFiles().length;
//if there're no forms to dump, just return
if(formsOnSD == 0){
txtInteractiveMessages.setText(Localization.get("bulk.form.no.unsynced.submit"));
TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
return;
}
SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences();
SendTask mSendTask = new SendTask(getApplicationContext(), CommCareApplication._().getCurrentApp().getCommCarePlatform(), settings.getString("PostURL", url), txtInteractiveMessages){
protected int taskId = BULK_SEND_ID;
@Override
protected void deliverResult( CommCareFormDumpActivity receiver, Boolean result) {
if(result == Boolean.TRUE){
Intent i = new Intent(getIntent());
i.putExtra(KEY_NUMBER_DUMPED, formsOnSD);
receiver.setResult(BULK_SEND_ID, i);
receiver.finish();
return;
} else {
//assume that we've already set the error message, but make it look scary
receiver.TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
}
}
@Override
protected void deliverUpdate(CommCareFormDumpActivity receiver, String... update) {
receiver.updateProgress(BULK_SEND_ID, update[0]);
receiver.txtInteractiveMessages.setText(update[0]);
}
@Override
protected void deliverError(CommCareFormDumpActivity receiver, Exception e) {
receiver.txtInteractiveMessages.setText(Localization.get("bulk.form.error", new String[] {e.getMessage()}));
receiver.TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
}
};
mSendTask.connect(CommCareFormDumpActivity.this);
mSendTask.execute();
}
});
btnDumpForms.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(formsOnPhone == 0){
txtInteractiveMessages.setText(Localization.get("bulk.form.no.unsynced.dump"));
TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
return;
}
SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences();
DumpTask mDumpTask = new DumpTask(getApplicationContext(), CommCareApplication._().getCurrentApp().getCommCarePlatform(), txtInteractiveMessages){
protected int taskId = BULK_DUMP_ID;
@Override
protected void deliverResult( CommCareFormDumpActivity receiver, Boolean result) {
if(result == Boolean.TRUE){
Intent i = new Intent(getIntent());
i.putExtra(KEY_NUMBER_DUMPED, formsOnPhone);
receiver.setResult(BULK_DUMP_ID, i);
receiver.finish();
return;
} else {
//assume that we've already set the error message, but make it look scary
receiver.TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
}
}
@Override
protected void deliverUpdate(CommCareFormDumpActivity receiver, String... update) {
receiver.updateProgress(BULK_DUMP_ID, update[0]);
receiver.txtInteractiveMessages.setText(update[0]);
}
@Override
protected void deliverError(CommCareFormDumpActivity receiver, Exception e) {
receiver.txtInteractiveMessages.setText(Localization.get("bulk.form.error", new String[] {e.getMessage()}));
receiver.TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
}
};
mDumpTask.connect(CommCareFormDumpActivity.this);
mDumpTask.execute();
}
});
mAlertDialog = popupWarningMessage();
if(!acknowledgedRisk){
mAlertDialog.show();
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
private AlertDialog popupWarningMessage(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(Localization.get("bulk.form.alert.title"));
alertDialogBuilder
.setMessage(Localization.get("bulk.form.warning"))
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
acknowledgedRisk = true;
dialog.dismiss();
dialog.cancel();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
exitDump();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
return alertDialog;
}
public void setDisplayText(){
btnDumpForms.setText(Localization.get("bulk.form.dump.2", new String[] {""+formsOnPhone}));
btnSubmitForms.setText(Localization.get("bulk.form.submit.2", new String[] {""+formsOnSD}));
txtDisplayPrompt.setText(Localization.get("bulk.form.prompt", new String[] {""+formsOnPhone , ""+formsOnSD}));
}
public static File[] getDumpFiles(){
ArrayList<String> externalMounts = FileUtil.getExternalMounts();
if(externalMounts.size()==0){
return new File[]{};
}
String baseDir = externalMounts.get(0);
String folderName = Localization.get("bulk.form.foldername");
File dumpDirectory = new File( baseDir + "/" + folderName);
File[] files = dumpDirectory.listFiles();
if (files == null){
files = new File[] {};
}
return files;
}
public Vector<Integer> getUnsyncedForms(){
SqlStorage<FormRecord> storage = CommCareApplication._().getUserStorage(FormRecord.class);
//Get all forms which are either unsent or unprocessed
Vector<Integer> ids = storage.getIDsForValues(new String[] {FormRecord.META_STATUS}, new Object[] {FormRecord.STATUS_UNSENT});
ids.addAll(storage.getIDsForValues(new String[] {FormRecord.META_STATUS}, new Object[] {FormRecord.STATUS_COMPLETE}));
return ids;
}
/* (non-Javadoc)
* @see org.commcare.android.framework.CommCareActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
}
private void exitDump(){
finish();
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
if(id == BULK_DUMP_ID) {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(Localization.get("bulk.dump.dialog.title"));
progressDialog.setMessage(Localization.get("bulk.dump.dialog.progress", new String[] {"0"}));
return progressDialog;
}
else if (id == BULK_SEND_ID) {
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(Localization.get("bulk.send.dialog.title"));
progressDialog.setMessage(Localization.get("bulk.send.dialog.progress", new String[] {"0"}));
return progressDialog;
}
return null;
}
/* (non-Javadoc)
* @see org.commcare.android.tasks.templates.CommCareTaskConnector#taskCancelled(int)
*/
@Override
public void taskCancelled(int id) {
txtInteractiveMessages.setText(Localization.get("bulk.form.cancel"));
this.TransplantStyle(txtInteractiveMessages, R.layout.template_text_notification_problem);
}
}
|
package com.mypodcasts.podcast;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.mypodcasts.BuildConfig;
import com.mypodcasts.R;
import com.mypodcasts.podcast.models.Episode;
import com.mypodcasts.podcast.models.Image;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.valueOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.robolectric.Robolectric.buildActivity;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class EpisodeListAdapterTest {
EpisodeListAdapter episodeListAdapter;
Activity activity;
View convertView;
ViewGroup parent;
ImageLoader imageLoaderMock = mock(ImageLoader.class);
List<Episode> episodes;
@Before
public void setup() {
activity = buildActivity(Activity.class).create().get();
convertView = new View(activity);
parent = new ViewGroup(activity) {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
};
episodes = new ArrayList<Episode>() {{
add(new Episode() {
@Override
public Image getImage() {
return new Image() {
@Override
public String getUrl() {
return "http://images.com/photo.jpeg";
}
};
}
@Override
public String getTitle() {
return "123 - Podcast Episode";
}
});
add(new Episode() {
@Override
public String getTitle() {
return "456 - Another Podcast Episode";
}
});
}};
episodeListAdapter = new EpisodeListAdapter(episodes, activity.getLayoutInflater(), imageLoaderMock);
}
@Test
public void itReturnsEpisodesCount() {
assertThat(episodeListAdapter.getCount(), is(episodes.size()));
}
@Test
public void itInflatesEachRow() {
int position = 0;
View row = episodeListAdapter.getView(position, convertView, parent);
assertThat(row.getVisibility(), is(View.VISIBLE));
}
@Test
public void itShowsFirstEpisodeTitle() {
int position = 0;
View row = episodeListAdapter.getView(position, convertView, parent);
TextView textView = (TextView) row.findViewById(R.id.episode_title);
String title = valueOf(textView.getText());
assertThat(title, is("123 - Podcast Episode"));
}
@Test
public void itShowsFirstEpisodeImageUrl() {
int position = 0;
Image image = episodes.get(position).getImage();
View row = episodeListAdapter.getView(position, convertView, parent);
NetworkImageView networkImageView = (NetworkImageView) row.findViewById(R.id.episode_thumbnail);
assertThat(networkImageView.getImageURL(), is(image.getUrl()));
}
@Test
public void itShowsSecondEpisodeTitle() {
int position = 1;
View row = episodeListAdapter.getView(position, convertView, parent);
TextView textView = (TextView) row.findViewById(R.id.episode_title);
String title = valueOf(textView.getText());
assertThat(title, is("456 - Another Podcast Episode"));
}
}
|
package mobi.cangol.mobile.db;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import mobi.cangol.mobile.logging.Log;
public class DatabaseTest extends AndroidTestCase {
private DataService dataService;
private AtomicInteger atomicInteger;
public void setUp() throws Exception {
super.setUp();
DatabaseHelper.createDataBaseHelper(getContext());
dataService = new DataService(getContext());
atomicInteger = new AtomicInteger();
}
public void testDatabase() throws Exception {
Data data=new Data("name_" + atomicInteger.addAndGet(1));
data.setNickname("nickname_"+new Random().nextInt(100));
dataService.save(data);
dataService.refresh(data);
List<Data> list=dataService.findListByName("1");
dataService.delete(list.get(0).getId());
}
}
class DataService implements BaseService<Data> {
private static final String TAG = "DataService";
private Dao<Data, Integer> dao;
public DataService(Context context) {
try {
DatabaseHelper dbHelper = DatabaseHelper
.createDataBaseHelper(context);
dao = dbHelper.getDao(Data.class);
} catch (SQLException e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService init fail!");
}
}
/**
* @return the row ID of the newly inserted row or updated row, or -1 if an error occurred
*/
@Override
public int save(Data obj) {
int result = -1;
try {
if (obj.getId() > 0 && obj.getId() != -1) {
result = dao.update(obj);
if (result > 0) {
result = obj.getId();
}
} else {
result = dao.create(obj);
}
} catch (SQLException e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService save fail!");
}
return result;
}
@Override
public void refresh(Data obj) {
try {
dao.refresh(obj);
} catch (SQLException e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService refresh fail!");
}
}
@Override
public void delete(Integer id) {
try {
dao.deleteById(id);
} catch (Exception e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService delete fail!");
}
}
@Override
public Data find(Integer id) {
try {
return dao.queryForId(id);
} catch (SQLException e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService find fail!");
}
return null;
}
@Override
public int getCount() {
try {
return dao.queryForAll().size();
} catch (SQLException e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService getCount fail!");
}
return -1;
}
public List<Data> getAllList() {
try {
return dao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
android.util.Log.e(TAG, "DataService getAllList fail!");
}
return null;
}
@Override
public List<Data> findList(QueryBuilder queryBuilder) {
return dao.query(queryBuilder);
}
public List<Data> findListByName(String name) {
QueryBuilder queryBuilder = new QueryBuilder(Data.class);
queryBuilder.addQuery("name", name, "like",true);
queryBuilder.addQuery("nickname", name, "like",true);
return dao.query(queryBuilder);
}
}
class DatabaseHelper extends CoreSQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
public static final String DATABASE_NAME = "demo";
public static final int DATABASE_VERSION = 1;
private static DatabaseHelper dataBaseHelper;
public static DatabaseHelper createDataBaseHelper(Context context) {
if (null == dataBaseHelper) {
dataBaseHelper = new DatabaseHelper();
dataBaseHelper.open(context);
}
return dataBaseHelper;
}
@Override
public String getDataBaseName() {
return DATABASE_NAME;
}
@Override
public int getDataBaseVersion() {
return DATABASE_VERSION;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate");
DatabaseUtils.createTable(db, Data.class);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "onUpgrade " + oldVersion + "->" + newVersion);
}
}
@DatabaseTable("TEST_DATA")
class Data {
@DatabaseField(primaryKey = true, notNull = true)
private int id;
@DatabaseField
private String name;
@DatabaseField
private String nickname;
public Data() {
}
public Data(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Data{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", nickname='").append(nickname).append('\'');
sb.append('}');
return sb.toString();
}
}
interface BaseService<T> {
/**
* @param obj
* @return
*/
void refresh(T obj) throws SQLException;
/**
* @param id
*/
void delete(Integer id) throws SQLException;
/**
* @param id
* @return
*/
T find(Integer id) throws SQLException;
/**
* @return
*/
int getCount() throws SQLException;
/**
* @return
*/
List<T> getAllList() throws SQLException;
/**
* @param obj
*/
int save(T obj);
/**
* @param queryBuilder
* @return
*/
List<T> findList(QueryBuilder queryBuilder);
}
|
package org.basex.gui.view.project;
import static org.basex.core.Text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import org.basex.core.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.layout.*;
import org.basex.gui.layout.BaseXFileChooser.Mode;
import org.basex.gui.view.editor.*;
import org.basex.io.*;
import org.basex.util.*;
import org.basex.util.list.*;
public final class ProjectView extends BaseXPanel {
/** Root directory. */
final ProjectDir root;
/** Tree. */
final ProjectTree tree;
/** Editor view. */
final EditorView editor;
/** Filter field. */
private final ProjectFilter filter;
/** Filter list. */
final ProjectList list;
/** Root path. */
private final BaseXTextField path;
/** Splitter. */
private final BaseXSplit split;
/** Last focused component. */
private Component last;
/** Remembers the last focused component. */
final FocusAdapter lastfocus = new FocusAdapter() {
@Override
public void focusGained(final FocusEvent ev) {
last = ev.getComponent();
}
};
/**
* Constructor.
* @param ev editor view
*/
public ProjectView(final EditorView ev) {
super(ev.gui);
editor = ev;
setLayout(new BorderLayout());
tree = new ProjectTree(this);
root = new ProjectDir(new IOFile(root()), this);
tree.init(root);
filter = new ProjectFilter(this);
list = new ProjectList(this);
BaseXLayout.addInteraction(list, gui);
final BaseXBack back = new BaseXBack().layout(new BorderLayout(2, 2));
back.setBorder(new CompoundBorder(new MatteBorder(0, 0, 1, 0, GUIConstants.GRAY),
new EmptyBorder(3, 1, 3, 2)));
path = new BaseXTextField(gui);
path.setText(root.file.path());
path.setEnabled(false);
final BaseXButton browse = new BaseXButton(DOTS, gui);
browse.setMargin(new Insets(0, 2, 0, 2));
browse.setToolTipText(CHOOSE_DIR + DOTS);
browse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
change();
}
});
back.add(path, BorderLayout.CENTER);
back.add(browse, BorderLayout.EAST);
back.add(filter, BorderLayout.SOUTH);
// add scroll bars
final JScrollPane lscroll = new JScrollPane(list);
lscroll.setBorder(new EmptyBorder(0, 0, 0, 0));
final JScrollPane tscroll = new JScrollPane(tree);
tscroll.setBorder(new EmptyBorder(0, 0, 0, 0));
split = new BaseXSplit(false);
split.mode(Fill.NONE);
split.add(lscroll);
split.add(tscroll);
split.init(new double[] { 0.3, 0.7}, new double[] { 0, 1});
split.visible(false);
showList(false);
add(back, BorderLayout.NORTH);
add(split, BorderLayout.CENTER);
last = tree;
tree.addFocusListener(lastfocus);
list.addFocusListener(lastfocus);
}
/**
* Makes the list (in)visible.
* @param vis visibility flag
*/
public void showList(final boolean vis) {
split.visible(vis);
}
/**
* Refreshes the specified file node.
* @param file file to be opened
* @param rename file has been renamed
*/
public void save(final IOFile file, final boolean rename) {
refresh(file);
if(rename) reset();
refresh();
}
/**
* Refreshes the filter view.
*/
public void refresh() {
filter.refresh(true);
}
/**
* Resets the filter cache.
*/
public void reset() {
filter.reset();
}
/**
* Jumps to the specified file.
* @param file file to be focused
*/
public void jump(final IOFile file) {
final IOFile fl = file.normalize();
if(fl.path().startsWith(root.file.path())) tree.expand(root, fl.path());
tree.requestFocusInWindow();
}
/**
* Refreshes the visualization of the specified file, or its parent, in the tree.
* @param file file to be refreshed
*/
private void refresh(final IOFile file) {
final ProjectNode node = find(file);
if(node != null) {
node.refresh();
} else {
final IOFile parent = file.parent();
if(parent != null) refresh(parent);
}
}
/**
* Returns the node for the specified file.
* @param file file to be found
* @return node or {@code null}
*/
private ProjectNode find(final IOFile file) {
final IOFile fl = file.normalize();
if(fl.path().startsWith(root.file.path())) {
final Enumeration<?> en = root.depthFirstEnumeration();
while(en.hasMoreElements()) {
final ProjectNode node = (ProjectNode) en.nextElement();
if(node.file != null && node.file.path().equals(fl.path())) return node;
}
}
return null;
}
/**
* Called when GUI design has changed.
*/
public void refreshLayout() {
filter.refreshLayout();
}
/**
* Focuses the project filter.
* @param ea calling editor
*/
public void findFiles(final EditorArea ea) {
if(isFocusOwner()) {
filter.find(tree.selectedNode());
} else {
filter.find(ea);
}
}
/**
* Focuses the project view.
*/
public void focus() {
last.requestFocusInWindow();
}
/**
* Renames a file or directory in the tree.
* @param node source node
* @param name new name of file or directory
* @return new file reference or {@code null} if operation failed
*/
IOFile rename(final ProjectNode node, final String name) {
// check if chosen file name is valid
if(IOFile.isValidName(name)) {
final IOFile old = node.file;
final IOFile updated = new IOFile(old.file().getParent(), name);
// rename file or show error dialog
if(!old.rename(updated)) {
BaseXDialog.error(gui, Util.info(FILE_NOT_RENAMED_X, old));
} else {
// update tab references if file or directory could be renamed
gui.editor.rename(old, updated);
return updated;
}
}
return null;
}
/**
* Returns a common parent directory.
* @return root directory
*/
private String root() {
final GlobalOptions gopts = gui.context.globalopts;
final String proj = gui.gopts.get(GUIOptions.PROJECTPATH);
if(!proj.isEmpty()) return proj;
final IOFile dir1 = new IOFile(gopts.get(GlobalOptions.REPOPATH));
final IOFile dir2 = new IOFile(gopts.get(GlobalOptions.WEBPATH));
final IOFile dir3 = dir2.resolve(gopts.get(GlobalOptions.RESTXQPATH));
final StringList sl = new StringList();
for(final IOFile f : new IOFile[] { dir1, dir2, dir3}) {
final IOFile p = f.normalize().parent();
if(p != null && !sl.contains(p.path())) sl.add(p.path());
}
return sl.sort().unique().get(0);
}
/**
* Opens the selected file.
* @param file file to be opened
* @param search search string
*/
void open(final IOFile file, final String search) {
final EditorArea ea = editor.open(file);
if(ea == null) return;
// delay search and focus request (avoid keyTyped event to be handled in editor)
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ea.jump(search);
}
});
}
/**
* Changes the root directory.
*/
private void change() {
final ProjectNode child = tree.selectedNode();
final BaseXFileChooser fc = new BaseXFileChooser(CHOOSE_DIR, child.file.path(), gui);
final IOFile io = fc.select(Mode.DOPEN);
if(io != null) {
root.file = io;
root.refresh();
filter.reset();
path.setText(io.path());
gui.gopts.set(GUIOptions.PROJECTPATH, io.path());
}
}
}
|
package org.intermine.bio.dataconversion;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.bio.ontology.OboParser;
import org.intermine.bio.ontology.OboRelation;
import org.intermine.bio.ontology.OboTerm;
import org.intermine.bio.ontology.OboTermSynonym;
import org.intermine.dataconversion.DataConverter;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
/**
* Convert tree of OboTerms into Items.
*
* @author Thomas Riley
* @see DagConverter
*/
public class OboConverter extends DataConverter
{
private static final Logger LOG = Logger.getLogger(DataConverter.class);
protected String dagFilename;
protected String termClass;
protected int uniqueId = 0;
protected int uniqueSynId = 0;
protected Collection<OboTerm> oboTerms;
protected List<OboRelation> oboRelations;
protected Map<String, Item> nameToTerm = new HashMap<String, Item>();
protected Map<String, String> xrefs = new HashMap<String, String>();
protected Map<OboTermSynonym, Item> synToItem = new HashMap<OboTermSynonym, Item>();
protected Item ontology;
private boolean createRelations = true;
/**
* Constructor for this class.
*
* @param writer an ItemWriter used to handle the resultant Items
* @param model the Model
* @param dagFilename the name of the DAG file
* @param dagName the title of the dag, as present in any static data
* @param url the URL of the source of this ontology
* @param termClass the class of the Term
*/
public OboConverter(ItemWriter writer, Model model, String dagFilename, String dagName,
String url, String termClass) {
super(writer, model);
this.dagFilename = dagFilename;
this.termClass = termClass;
ontology = createItem("Ontology");
ontology.addAttribute(new Attribute("name", dagName));
ontology.addAttribute(new Attribute("url", url));
}
/**
* Set to false to prevent storing OntologyRelation objects that include the relationship types
* between terms.
* @param createrelations property to parse
*/
public void setCreaterelations(String createrelations) {
if ("true".equals(createrelations)) {
this.createRelations = true;
} else {
this.createRelations = false;
}
}
/**
* Process every DAG term and output it as a Item.
*
* @throws Exception if an error occurs in processing
*/
public void process() throws Exception {
nameToTerm = new HashMap<String, Item>();
synToItem = new HashMap<OboTermSynonym, Item>();
OboParser parser = new OboParser();
parser.processOntology(new FileReader(new File(dagFilename)));
parser.processRelations(dagFilename);
oboTerms = parser.getOboTerms();
oboRelations = parser.getOboRelations();
storeItems();
}
/**
* Convert DagTerms into Items and relation Items, and write them to the ItemWriter
*
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected void storeItems() throws ObjectStoreException {
long startTime = System.currentTimeMillis();
store(ontology);
for (OboTerm term : oboTerms) {
process(term);
}
for (OboRelation oboRelation : oboRelations) {
processRelation(oboRelation);
}
for (Item termItem: nameToTerm.values()) {
store(termItem);
}
for (Item synItem : synToItem.values()) {
store(synItem);
}
long timeTaken = System.currentTimeMillis() - startTime;
LOG.info("Ran storeItems, took: " + timeTaken + " ms");
}
/**
* @param oboTerms the oboTerms to set
*/
public void setOboTerms(Collection<OboTerm> oboTerms) {
this.oboTerms = oboTerms;
}
/**
* @param oboRelations the OboRelations to set
*/
public void setOboRelations(List<OboRelation> oboRelations) {
this.oboRelations = oboRelations;
}
/**
* Convert a OboTerm into an Item and relation Items, and write the relations to the writer.
*
* @param term a DagTerm
* @return an Item representing the term
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected Item process(OboTerm term) throws ObjectStoreException {
if (term.isObsolete()) {
LOG.info("Not processing obsolete OBO term: " + term.getId() + " " + term.getName());
return null;
}
String termId = (term.getId() == null ? term.getName() : term.getId());
Item item = nameToTerm.get(termId);
if (item == null) {
item = createItem(termClass);
nameToTerm.put(termId, item);
configureItem(termId, item, term);
} else {
if ((!term.getName().equals(item.getAttribute("name").getValue()))
|| ((item.getAttribute("identifier") == null) && (term.getId() != null))
|| ((item.getAttribute("identifier") != null)
&& (!item.getAttribute("identifier").getValue().equals(term.getId())))) {
throw new IllegalArgumentException("Dag is invalid - terms (" + term.getName()
+ ", " + term.getId() + ") and (" + item.getAttribute("name").getValue()
+ ", " + (item.getAttribute("identifier") == null ? "null"
: item.getAttribute("identifier").getValue()) + ") clash");
}
}
return item;
}
/**
* Set up attributes and references for the Item created from a DagTerm. Subclasses
* can override this method to perform extra setup, for example by casting the
* DagTerm to some someclass and retrieving extra attributes. Subclasses should call this
* inherited method first. This method will call process() for each child/component term,
* resulting in recursion.
*
* @param termId the term id
* @param item the Item created (see termClass field for type)
* @param term the source DagTerm
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected void configureItem(String termId, Item item, OboTerm term)
throws ObjectStoreException {
item.addAttribute(new Attribute("name", term.getName()));
item.addReference(new Reference("ontology", ontology.getIdentifier()));
if (term.getId() != null) {
item.addAttribute(new Attribute("identifier", term.getId()));
}
for (OboTermSynonym syn : term.getSynonyms()) {
Item synItem = synToItem.get(syn);
if (synItem == null) {
synItem = createItem("OntologyTermSynonym");
synToItem.put(syn, synItem);
configureSynonymItem(syn, synItem, term);
}
item.addToCollection("synonyms", synItem);
}
for (OboTerm xref : term.getXrefs()) {
String identifier = xref.getId();
String refId = xrefs.get(identifier);
if (refId == null) {
Item xrefTerm = createItem("OntologyTerm");
refId = xrefTerm.getIdentifier();
xrefs.put(identifier, refId);
xrefTerm.setAttribute("identifier", identifier);
// xrefTerm.addToCollection("crossReferences", item.getIdentifier());
store(xrefTerm);
}
item.addToCollection("crossReferences", refId);
}
OboTerm oboterm = term;
if (!StringUtils.isEmpty(oboterm.getNamespace())) {
item.setAttribute("namespace", oboterm.getNamespace());
}
if (!StringUtils.isEmpty(oboterm.getDescription())) {
item.setAttribute("description", oboterm.getDescription());
}
item.setAttribute("obsolete", "" + oboterm.isObsolete());
// Term is its own parent
item.addToCollection("parents", item);
}
/**
* Set up attributes and references for the Item created from a DagTermSynonym. Subclasses
* can override this method to perform extra setup, for example by casting the
* DagTermSynonym to some someclass and retrieving extra attributes. Subclasses should call this
* inherited method first.
*
* @param syn the DagTermSynonym object (or a subclass of)
* @param item the Item created to store the synonym
* @param term the source DagTerm
* @throws ObjectStoreException if an error occurs while writing to the itemWriter
*/
protected void configureSynonymItem(OboTermSynonym syn, Item item, OboTerm term)
throws ObjectStoreException {
item.setAttribute("name", syn.getName());
item.setAttribute("type", syn.getType());
}
/**
* Process and store OboRelations
* @param oboRelation the relation to process
* @throws ObjectStoreException if problem storing
*/
protected void processRelation(OboRelation oboRelation)
throws ObjectStoreException {
// create the relation item
if (nameToTerm.get(oboRelation.getParentTermId()) != null
&& nameToTerm.get(oboRelation.getChildTermId()) != null) {
// add parent to term for easier querying in webapp
nameToTerm.get(oboRelation.getChildTermId()).addToCollection("parents",
nameToTerm.get(oboRelation.getParentTermId()));
if (createRelations) {
Item relation = createItem("OntologyRelation");
relation.setReference("parentTerm", nameToTerm
.get(oboRelation.getParentTermId()));
relation.setReference("childTerm", nameToTerm.get(oboRelation.getChildTermId()));
relation.setAttribute("relationship", oboRelation.getRelationship().getName());
relation.setAttribute("direct", Boolean.toString(oboRelation.isDirect()));
relation.setAttribute("redundant", Boolean.toString(oboRelation.isRedundant()));
// Set the reverse reference
nameToTerm.get(oboRelation.getParentTermId())
.addToCollection("relations", relation);
nameToTerm.get(oboRelation.getChildTermId())
.addToCollection("relations", relation);
store(relation);
}
} else {
LOG.info("GOTerm id not found for relation " + oboRelation.getParentTermId() + " "
+ oboRelation.getChildTermId());
}
}
}
|
package floobits;
import java.io.File;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import floobits.Flog;
class Utils {
public static String defaultBaseDir () {
return FilenameUtils.concat(System.getProperty("user.home"), "floobits");
}
public static String unFuckPath (String path) {
return FilenameUtils.normalize(new File(path).getAbsolutePath());
}
public static Boolean isShared (String path) {
try {
return !getRelativePath(unFuckPath(path), Shared.colabDir, "/").contains("..");
} catch (PathResolutionException e) {
return false;
} catch (StringIndexOutOfBoundsException e) {
return false;
}
}
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) {
// Normalize the paths
String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath);
String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath);
// Undo the changes to the separators made by normalization
if (pathSeparator.equals("/")) {
normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath);
normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath);
} else if (pathSeparator.equals("\\")) {
normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath);
normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath);
} else {
throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'");
}
String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));
// First get all the common elements. Store them as a string,
// and also count how many of them there are.
StringBuffer common = new StringBuffer();
int commonIndex = 0;
while (commonIndex < target.length && commonIndex < base.length
&& target[commonIndex].equals(base[commonIndex])) {
common.append(target[commonIndex] + pathSeparator);
commonIndex++;
}
if (commonIndex == 0) {
// No single common path element. This most
// likely indicates differing drive letters, like C: and D:.
// These paths cannot be relativized.
throw new PathResolutionException("No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath
+ "'");
}
// The number of directories we have to backtrack depends on whether the base is a file or a dir
// For example, the relative path from
// /foo/bar/baz/gg/ff to /foo/bar/baz
// ".." if ff is a file
// "../.." if ff is a directory
// The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because
// the resource referred to by this path may not actually exist, but it's the best I can do
boolean baseIsFile = true;
File baseResource = new File(normalizedBasePath);
if (baseResource.exists()) {
baseIsFile = baseResource.isFile();
} else if (basePath.endsWith(pathSeparator)) {
baseIsFile = false;
}
StringBuffer relative = new StringBuffer();
if (base.length != commonIndex) {
int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;
for (int i = 0; i < numDirsUp; i++) {
relative.append(".." + pathSeparator);
}
}
relative.append(normalizedTargetPath.substring(common.length()));
return relative.toString();
}
static class PathResolutionException extends RuntimeException {
PathResolutionException(String msg) {
super(msg);
}
}
}
|
package com.allforfunmc.moreoresandmore;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBreakable;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@Mod(modid = Main.modid, version = Main.version)
public class Main {
public static final String modid = "moreoresandmore";
public static final String version = "1.0.0";
public static Block blockCompressedCobble;
@EventHandler
public void PreInit(FMLPreInitializationEvent preEvent){
//new mines. test
//blocks
blockCompressedCobble = new CompressedCobble(Material.rock).setBlockName("CompressedCobble").setHardness(5.0F).setResistance(2000.0F);
GameRegistry.registerBlock(blockCompressedCobble, "CompressedCobble");
}
@EventHandler
public void Init(FMLInitializationEvent Event){
//crafting
GameRegistry.addShapedRecipe(new ItemStack(blockCompressedCobble, 1), new Object[]{"XXX", "XXX", "XXX", 'X', Blocks.cobblestone});
}
@EventHandler
public void PostInit(FMLPostInitializationEvent postEvent){
}
}
|
package org.jrgss.api;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.controllers.Controllers;
import org.jrgss.JRGSSApplication;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyConstant;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import java.util.HashMap;
import java.util.Map;
@JRubyClass(name = "Input")
public class Input extends RubyObject {
static Ruby runtime;
static RubyModule rubyClass;
static Map<Integer, Boolean> triggerStatus = new HashMap<>();
static Map<Integer, Boolean> repeatStatus = new HashMap<>();
static Map<Integer, Long> repeatTimestamps = new HashMap<>();
static Map<Integer, Boolean> isPressed = new HashMap<>();
public Input(final Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
private static void updateKey(int i, boolean current, boolean previous) {
isPressed.put(i, current);
if (!previous && current) {
triggerStatus.put(i, true);
repeatStatus.put(i, true);
repeatTimestamps.put(i, System.currentTimeMillis());
} else {
triggerStatus.put(i, false);
}
if (!current) {
repeatStatus.put(i, false);
}
if (current && previous) {
if (System.currentTimeMillis() - repeatTimestamps.get(i) < 200) {
repeatStatus.put(i, false);
} else {
repeatStatus.put(i, true);
repeatTimestamps.put(i, System.currentTimeMillis());
}
}
}
@JRubyMethod(module = true)
public static void update(IRubyObject self) {
//Controller initialization crashes if the window is not focused the first time it's called on OSX
// This is a workaround. To make this less jarring, when you lose focus we simulate the release
// of all buttons (on the keyboard too
if (((JRGSSApplication)Gdx.app).isFocused()) {
for (int i = 1; i < 256; i++) {
Boolean previous = isPressed.get(i);
if (previous == null) {
previous = Boolean.FALSE;
}
boolean current = Gdx.input.isKeyPressed(i);
updateKey(i, current, previous);
}
if (Controllers.getControllers().size > 0) {
for (int i = 0; i < 16; i++) {
Boolean previous = isPressed.get(gamepadButton(i));
if (previous == null) {
previous = Boolean.FALSE;
}
boolean current = Controllers.getControllers().get(0).getButton(i);
updateKey(gamepadButton(i), current, previous);
}
}
} else {
//Simulate button release when switching away from app
for(Map.Entry<Integer, Boolean> entry : isPressed.entrySet()) {
updateKey(entry.getKey(), Boolean.FALSE, entry.getValue());
}
}
}
@JRubyMethod(module = true, name = "press?")
public static IRubyObject isPress_p(ThreadContext context, IRubyObject self, IRubyObject sym) {
boolean result = isPress(sym.asJavaString());
return RubyBoolean.newBoolean(context.getRuntime(), result);
}
public static boolean isPress(String sym) {
for (int i : convertSymToKey(sym)) {
Boolean result = isPressed.get(i);
if (result != null && result) return true;
}
return false;
}
@JRubyMethod(module = true, name = "trigger?")
public static IRubyObject isTrigger_p(ThreadContext context, IRubyObject self, IRubyObject sym) {
boolean result = isTrigger(sym.asJavaString());
return RubyBoolean.newBoolean(context.getRuntime(), result);
}
public static boolean isTrigger(String sym) {
for (int i : convertSymToKey(sym)) {
Boolean result = triggerStatus.get(i);
if (result != null && result) return true;
}
return false;
}
@JRubyMethod(module = true, name = "repeat?")
public static IRubyObject isRepeat_p(ThreadContext context, IRubyObject self, IRubyObject sym) {
boolean result = isRepeat(sym.asJavaString());
return RubyBoolean.newBoolean(context.getRuntime(), result);
}
public static boolean isRepeat(String sym) {
for (int i : convertSymToKey(sym)) {
Boolean result = repeatStatus.get(i);
if (result != null && result) return true;
}
return false;
}
@JRubyMethod(module = true)
public static IRubyObject dir4(IRubyObject self) {
int ret = 0;
if (isPress(DOWN)) {
ret = 2;
}
if (isPress(LEFT)) {
ret = 4;
}
if (isPress(RIGHT)) {
ret = 6;
}
if (isPress(UP)) {
ret = 8;
}
return new RubyFixnum(runtime, ret);
}
@JRubyMethod(module = true)
public static IRubyObject dir8(IRubyObject self) {
return new RubyFixnum(runtime, 0);
}
private static int[] convertSymToKey(String sym) {
int[] ret = bindings.get(sym);
if (ret != null) {
return ret;
}
return new int[]{0};
}
@JRubyConstant
public static final String DOWN = "DOWN";
@JRubyConstant
public static final String LEFT = "LEFT";
@JRubyConstant
public static final String RIGHT = "RIGHT";
@JRubyConstant
public static final String UP = "UP";
@JRubyConstant
public static final String A = "A",
B = "B", C = "C", X = "X", Y = "Y", Z = "Z", L = "L", R = "R";
@JRubyConstant
public static final String SHIFT = "SHIFT", CTRL = "CTRL", ALT = "ALT";
@JRubyConstant
public static final String F5 = "F5", F6 = "F6", F7 = "F7", F8 = "F8", F9 = "F9";
//Default bindings. These can be overwritten later when bindings are read from preferences
private final static HashMap<String, int[]> bindings = new HashMap<>();
static {
bindings.put(DOWN, new int[]{Keys.DOWN, XBOXButtons.DOWN.key()});
bindings.put(LEFT, new int[]{Keys.LEFT, XBOXButtons.LEFT.key()});
bindings.put(RIGHT, new int[]{Keys.RIGHT, XBOXButtons.RIGHT.key()});
bindings.put(UP, new int[]{Keys.UP, XBOXButtons.UP.key()});
bindings.put(C, new int[]{Keys.ENTER, XBOXButtons.A.key()});
bindings.put(B, new int[]{Keys.ESCAPE, XBOXButtons.B.key()});
bindings.put(L, new int[]{Keys.Q, XBOXButtons.LBUMP.key()});
bindings.put(R, new int[]{Keys.W, XBOXButtons.RBUMP.key()});
bindings.put(X, new int[]{Keys.A, XBOXButtons.X.key()});
bindings.put(Y, new int[]{Keys.S, XBOXButtons.Y.key()});
bindings.put(Z, new int[]{Keys.D, XBOXButtons.START.key()});
bindings.put(A, new int[]{Keys.SHIFT_LEFT, Keys.SHIFT_RIGHT});
bindings.put(SHIFT, new int[]{Keys.SHIFT_LEFT, Keys.SHIFT_RIGHT});
bindings.put(ALT, new int[]{Keys.ALT_LEFT, Keys.ALT_RIGHT});
bindings.put(CTRL, new int[]{Keys.CONTROL_LEFT, Keys.CONTROL_RIGHT});
bindings.put(F5, new int[]{Keys.F5});
bindings.put(F6, new int[]{Keys.F6});
bindings.put(F7, new int[]{Keys.F7});
bindings.put(F8, new int[]{Keys.F8});
bindings.put(F9, new int[]{Keys.F9});
}
public static final int GAMEPAD_START = 1000;
private static int gamepadButton(int button) {
return button + GAMEPAD_START;
}
public enum XBOXButtons {
UP,
DOWN,
LEFT,
RIGHT,
START,
BACK,
LSTICK,
RSTICK,
LBUMP,
RBUMP,
XBOX,
A,
B,
X,
Y;
public int key() {
return ordinal() + GAMEPAD_START;
}
}
}
/*
Input.update
Updates input data. As a general rule, this method is called once per frame.
Input.press?(sym) (RGSS3)
Determines whether the button corresponding to the symbol sym is currently being pressed.
If the button is being pressed, returns TRUE. If not, returns FALSE.
if Input.press?(:C)
do_something
end
Input.trigger?(sym) (RGSS3)
Determines whether the button corresponding to the symbol sym is currently being pressed again.
"Pressed again" is seen as time having passed between the button being not pressed and being pressed.
If the button is being pressed, returns TRUE. If not, returns FALSE.
Input.repeat?(sym) (RGSS3)
Determines whether the button corresponding to the symbol sym is currently being pressed again.
Unlike trigger?, takes into account the repeated input of a button being held down continuously.
If the button is being pressed, returns TRUE. If not, returns FALSE.
Input.dir4
Checks the status of the directional buttons, translates the data into a specialized 4-direction input format, and returns the number pad equivalent (2, 4, 6, 8).
If no directional buttons are being pressed (or the equivalent), returns 0.
Input.dir8
Checks the status of the directional buttons, translates the data into a specialized 8-direction input format, and returns the number pad equivalent (1, 2, 3, 4, 6, 7, 8, 9).
If no directional buttons are being pressed (or the equivalent), returns 0.
*/
|
package io.tetrapod.core;
import io.tetrapod.protocol.core.*;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
/**
* Simple service launcher. Some day it might be nice to replace with a ClusterService that was able to launch things.
* <p>
* Don't refer to logging in this class otherwise it gets initialized (upon class load) prior to being setup.
* <p>
* Arguments:
* <ul>
* <li>-host hostname (host to connect to, overrides cluster.properties)
* <li>-port portNum (port to connect to, overrides cluster.properties)
* <li>-token token (reclaim token)
* <li>-forceJoin true (forces a tetrapod to join a cluster even if it's connecting to localhost)
* <li>-webOnly webRootName (service will connect, set web root, and disconnect)
* </ul>
*/
public class Launcher {
private static Map<String, String> opts = null;
private static String serviceClass = null;
public static void main(String[] args) {
loadProperties("cfg/service.properties");
loadClusterProperties();
try {
if (args.length < 1)
usage();
serviceClass = args[0];
opts = getOpts(args, 1, defaultOpts());
System.setProperty("APPNAME", serviceClass.substring(serviceClass.lastIndexOf('.') + 1));
String host = System.getProperty("cluster.host");
int port = Integer.parseInt(System.getProperty("cluster.port"));
if (opts.get("host") != null) {
host = opts.get("host");
}
if (opts.get("port") != null) {
port = Integer.parseInt(opts.get("port"));
}
ServerAddress addr = new ServerAddress(host, port);
Service service = (Service) getClass(serviceClass).newInstance();
service.startNetwork(addr, opts.get("token"), opts);
} catch (Throwable t) {
t.printStackTrace();
usage();
}
}
private static Class<?> getClass(String serviceClass) {
// actual class
try {
return tryName(serviceClass);
} catch (ClassNotFoundException e) {}
// capitalize first letter
serviceClass = serviceClass.substring(0, 1).toUpperCase() + serviceClass.substring(1);
// io.tetrapod.core.X
try {
return tryName("io.tetrapod.core." + serviceClass);
} catch (ClassNotFoundException e) {}
int ix = serviceClass.indexOf("Service");
if (ix > 0) {
// pop off Service if it's there
serviceClass = serviceClass.substring(0, ix);
}
// io.tetrapod.core.XService
try {
return tryName("io.tetrapod.core." + serviceClass + "Service");
} catch (ClassNotFoundException e) {}
// io.tetrapod.lowercase(X).X
try {
return tryName("io.tetrapod." + serviceClass.toLowerCase() + "." + serviceClass);
} catch (ClassNotFoundException e) {}
// io.tetrapod.lowercase(X).XService
try {
return tryName("io.tetrapod." + serviceClass.toLowerCase() + "." + serviceClass + "Service");
} catch (ClassNotFoundException e) {}
return null;
}
private static Class<?> tryName(String name) throws ClassNotFoundException {
System.out.println("trying " + name);
return Class.forName(name);
}
private static void usage() {
System.err.println("\nusage:\n\t java <vmopts> " + Launcher.class.getCanonicalName()
+ " serviceClass [-host hostname] [-port port] [-token authToken]\n");
System.err
.println("\nserviceClass can omit its prefix if it's io.tetrapod.{core|serviceClass.upTo(\"Service\").toLower}.serviceClass[Service]\n");
System.exit(0);
}
private static Map<String, String> defaultOpts() {
Map<String, String> map = new HashMap<>();
map.put("host", null);
map.put("port", null);
map.put("token", null);
return map;
}
private static Map<String, String> getOpts(String[] array, int startIx, Map<String, String> opts) {
for (int i = startIx; i < array.length; i += 2) {
String key = array[i];
String value = array[i + 1];
if (!key.startsWith("-")) {
throw new RuntimeException("expected option, got [" + key + "]");
}
opts.put(key.substring(1), value);
}
return opts;
}
public static void relaunch(String token) throws IOException {
opts.put("token", token);
StringBuilder sb = new StringBuilder();
sb.append("../current/scripts/launch");
// java args?
// for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
// sb.append(' ');
// sb.append(arg);
for (Entry<String, String> entry : opts.entrySet()) {
if (entry.getValue() != null) {
sb.append(' ');
sb.append('-');
sb.append(entry.getKey());
sb.append(' ');
sb.append(entry.getValue());
}
}
System.out.println("EXEC: " + sb);
Runtime.getRuntime().exec(sb.toString());
}
public static boolean loadProperties(String fileName) {
final File file = new File(fileName);
if (file.exists()) {
try (Reader reader = new FileReader(file)) {
System.getProperties().load(reader);
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
private static void loadClusterProperties() {
String name = System.getProperty("user.name");
String[] locs = {
"cluster.properties", // in prod, gets symlinked in
"../../core/Tetrapod-Core/rsc/cluster/%s.cluster.properties",
"../../../core/Tetrapod-Core/rsc/cluster/%s.cluster.properties", // in case services are one level deeper
};
for (String f : locs) {
if (loadProperties(String.format(f, name)))
return;
}
System.err.println("ERR: no cluster properties found");
System.exit(0);
}
public static String getOpt(String key) {
return opts.get(key);
}
}
|
package io.tetrapod.core;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import io.tetrapod.core.utils.Properties;
import io.tetrapod.core.utils.Util;
import io.tetrapod.protocol.core.ServerAddress;
/**
* Simple service launcher. Some day it might be nice to replace with a ClusterService that was able to launch things.
* <p>
* Don't refer to logging in this class otherwise it gets initialized (upon class load) prior to being setup.
* <p>
* Arguments:
* <ul>
* <li>-host hostname (host to connect to, overrides cluster.properties)
* <li>-port portNum (port to connect to, overrides cluster.properties)
* <li>-token token (reclaim token)
* <li>-webOnly webRootName (service will connect, set web root, and disconnect)
* <li>-paused true|false (will start paused, overrides .properties)
* </ul>
*/
public class Launcher {
private static Map<String, String> opts = null;
private static String serviceClass = null;
public static void main(String[] args) {
loadProperties("cfg/service.properties");
loadClusterProperties();
loadSecretProperties();
// set for logback
System.setProperty("devMode", Util.getProperty("devMode"));
System.setProperty("APPNAME", Util.getProperty("APPNAME"));
try {
if (args.length < 1)
usage();
deleteLogs();
serviceClass = args[0];
String appName = serviceClass.substring(serviceClass.lastIndexOf('.') + 1);
Util.setProperty("APPNAME", appName);
opts = getOpts(args, 1, defaultOpts(appName));
String host = Util.getProperty("service.host", "localhost");
int port = Integer.parseInt(Util.getProperty("service.port", "9901"));
if (opts.get("host") != null) {
host = opts.get("host");
}
if (opts.get("port") != null) {
port = Integer.parseInt(opts.get("port"));
}
ServerAddress addr = new ServerAddress(host, port);
Service service = (Service) getClass(serviceClass).newInstance();
service.startNetwork(addr, opts.get("token"), opts);
} catch (Throwable t) {
t.printStackTrace();
usage();
}
}
private static Class<?> getClass(String serviceClass) {
// actual class
try {
return tryName(serviceClass);
} catch (ClassNotFoundException e) {}
// capitalize first letter
serviceClass = serviceClass.substring(0, 1).toUpperCase() + serviceClass.substring(1);
// io.tetrapod.core.X
try {
return tryName("io.tetrapod.core." + serviceClass);
} catch (ClassNotFoundException e) {}
int ix = serviceClass.indexOf("Service");
if (ix > 0) {
// pop off Service if it's there
serviceClass = serviceClass.substring(0, ix);
}
// io.tetrapod.core.XService
try {
return tryName("io.tetrapod.core." + serviceClass + "Service");
} catch (ClassNotFoundException | NoClassDefFoundError e) {}
// io.tetrapod.lowercase(X).X
try {
return tryName("io.tetrapod." + serviceClass.toLowerCase() + "." + serviceClass);
} catch (ClassNotFoundException | NoClassDefFoundError e) {}
// io.tetrapod.lowercase(X).XService
try {
return tryName("io.tetrapod." + serviceClass.toLowerCase() + "." + serviceClass + "Service");
} catch (ClassNotFoundException | NoClassDefFoundError e) {}
// io.tetrapod.lowercase(X).uppercase(X)Service
try {
return tryName("io.tetrapod." + serviceClass.toLowerCase() + "." + serviceClass.toUpperCase() + "Service");
} catch (ClassNotFoundException | NoClassDefFoundError e) {}
return null;
}
private static Class<?> tryName(String name) throws ClassNotFoundException {
// System.out.println("trying " + name);
return Class.forName(name);
}
private static void usage() {
System.err.println("\nusage:\n\t java <vmopts> " + Launcher.class.getCanonicalName()
+ " serviceClass [-host hostname] [-port port] [-token authToken]\n");
System.err
.println("\nserviceClass can omit its prefix if it's io.tetrapod.{core|serviceClass.upTo(\"Service\").toLower}.serviceClass[Service]\n");
System.exit(0);
}
private static Map<String, String> defaultOpts(String appName) {
Map<String, String> map = new HashMap<>();
map.put("host", null);
map.put("port", null);
map.put("token", null);
map.put("paused", Util.getProperty(appName + ".start_paused", "false"));
return map;
}
private static Map<String, String> getOpts(String[] array, int startIx, Map<String, String> opts) {
for (int i = startIx; i < array.length; i += 2) {
String key = array[i];
String value = array.length > i + 1 ? array[i + 1] : null;
if (!key.startsWith("-")) {
throw new RuntimeException("expected option, got [" + key + "]");
}
opts.put(key.substring(1), value);
}
return opts;
}
public static void relaunch(String token) throws IOException {
opts.put("token", token);
StringBuilder sb = new StringBuilder();
sb.append("../current/scripts/launch");
// java args?
// for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
// sb.append(' ');
// sb.append(arg);
for (Entry<String, String> entry : opts.entrySet()) {
if (entry.getValue() != null) {
sb.append(' ');
sb.append('-');
sb.append(entry.getKey());
sb.append(' ');
sb.append(entry.getValue());
}
}
System.out.println("EXEC: " + sb);
Runtime.getRuntime().exec(sb.toString());
}
public static boolean loadProperties(String fileName) {
return loadProperties(fileName, Util.properties);
}
public static boolean loadProperties(String fileName, Properties properties) {
return loadProperties(new File(fileName), properties);
}
public static boolean loadProperties(File file, Properties properties) {
if (file.exists()) {
try (Reader reader = new FileReader(file)) {
properties.load(reader);
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public static void loadClusterProperties() {
loadClusterProperties(Util.properties);
}
public static void loadClusterProperties(Properties properties) {
String name = System.getProperty("user.name");
String[] locs = {
"cluster.properties", // in prod, gets symlinked in
"../core/Tetrapod-Core/rsc/cluster/%s.cluster.properties", "../../core/Tetrapod-Core/rsc/cluster/%s.cluster.properties",
"../../../core/Tetrapod-Core/rsc/cluster/%s.cluster.properties", // in case services are one level deeper
};
for (String f : locs) {
if (loadProperties(String.format(f, name), properties))
return;
}
System.err.println("ERR: no cluster properties found");
System.exit(0);
}
public static void loadSecretProperties() {
loadSecretProperties(Util.properties);
}
public static void loadSecretProperties(Properties properties) {
String file = properties.optString("secrets", null);
if (file != null && !file.isEmpty())
loadProperties(file, properties);
}
public static String getOpt(String key) {
return opts.get(key);
}
public static String getAllOpts() {
StringBuilder sb = new StringBuilder();
for (Entry<String, String> e : opts.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
sb.append(" ");
}
return sb.toString();
}
private static void deleteLogs() {
if (Util.getProperty("delete.logs", "false").equals("true")) {
File logs = new File(System.getProperty("delete.logs.location", "logs"));
if (logs.isDirectory()) {
for (File f : logs.listFiles()) {
f.delete();
}
} else {
logs.delete();
}
}
}
}
|
package be.fastrada;
import java.io.Serializable;
public class Dashboard implements Serializable{
private double maxSpeed;
private double maxTemperature;
private int maxRPM;
private int alarmingTemperature;
private int currentSpeed;
private int currentRPM;
private int currentTemperature;
public void setMaxSpeed(double maxSpeed) {
this.maxSpeed = maxSpeed;
}
public void setMaxTemperature(double maxTemperature) {
this.maxTemperature = maxTemperature;
}
public void setMaxRPM(int maxRPM) {
this.maxRPM = maxRPM;
}
public void setAlarmingTemperature(int alarmingTemperature) {
this.alarmingTemperature = alarmingTemperature;
}
public double getMaxSpeed() {
return maxSpeed;
}
public double getMaxTemperature() {
return maxTemperature;
}
public int getMaxRPM() {
return maxRPM;
}
public int getAlarmingTemperature() {
return alarmingTemperature;
}
public void setCurrentSpeed(int currentSpeed) {
this.currentSpeed = currentSpeed;
}
public void setCurrentRPM(int currentRPM) {
this.currentRPM = currentRPM;
}
public void setCurrentTemperature(int currentTemperature) {
this.currentTemperature = currentTemperature;
}
}
|
package com.plugin.gcm;
import java.util.List;
import com.google.android.gcm.GCMBaseIntentService;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
public static final int NOTIFICATION_ID = 237;
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: "+ regId);
JSONObject json;
try
{
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript( json );
}
catch( JSONException e)
{
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null)
{
boolean foreground = PushPlugin.isInForeground();
extras.putBoolean("foreground", foreground);
if (foreground)
PushPlugin.sendExtras(extras);
else
createNotification(context, extras);
}
}
public void createNotification(Context context, Bundle extras)
{
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setPriority(0)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setWhen(System.currentTimeMillis())
.setContentTitle(appName)
.setContentIntent(contentIntent);
String ticker = extras.getString("ticker");
if (null == ticker || ticker.equals("")) {
ticker = appName;
}
mBuilder.setTicker(ticker);
String message = extras.getString("message");
if (null == message || message.equals("")) {
message = "<missing message content>";
}
mBuilder.setContentText(message);
String msgcnt = extras.getString("msgcnt");
if (null != msgcnt) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
setIcons(mBuilder, context, extras);
// mBuilder.setSmallIcon(getSmallIcon(context, extras));
mBuilder.setSound(getRingtoneUri(context, extras));
mNotificationManager.notify((String) appName, NOTIFICATION_ID, mBuilder.build());
}
/**
* Gets sound passed in message or default ringtone
* @param context
* @param extras
* @return
*/
private Uri getRingtoneUri(Context context, Bundle extras) {
Uri result = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
String soundName = extras.getString("sound");
if (null == soundName || soundName.equals("")) {
return result;
}
Resources res = context.getResources();
int soundId = res.getIdentifier(soundName, "raw", context.getPackageName());
if (0 == soundId) {
return result;
}
result = Uri.parse("android.resource://" + context.getPackageName() + "/" + soundId);
return result;
}
/**
* Sets custom icons if passed in message
* @param builder
* @param context
* @param extras
* @return
*/
private NotificationCompat.Builder setIcons(NotificationCompat.Builder builder, Context context, Bundle extras) {
Resources res = context.getResources();
int smallIcon = context.getApplicationInfo().icon;
Bitmap largeIcon = (((BitmapDrawable)res.getDrawable(smallIcon)).getBitmap());
String iconName = extras.getString("icon");
if (null != iconName && false == iconName.equals("")) {
int smallIconId = res.getIdentifier(iconName, "drawable", context.getPackageName());
int largeIconId = res.getIdentifier(iconName + "_large", "drawable", context.getPackageName());
if (0 != smallIconId) {
smallIcon = smallIconId;
}
if (0 != largeIconId) {
largeIcon = (((BitmapDrawable)res.getDrawable(largeIconId)).getBitmap());
}
}
return builder.setSmallIcon(smallIcon).setLargeIcon(largeIcon);
}
public static void cancelNotification(Context context)
{
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel((String)getAppName(context), NOTIFICATION_ID);
}
private static String getAppName(Context context)
{
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
}
|
package com.leekyoungil.cachemem;
import com.leekyoungil.cachemem.memcached.MemcachedResult;
import com.leekyoungil.cachemem.model.CacheMemLog;
import com.leekyoungil.cachemem.socket.ClientHandler;
import com.leekyoungil.cachemem.socket.WebHandler;
import com.leekyoungil.cachemem.util.CacheMemLogger;
import com.leekyoungil.cachemem.util.CacheMemUtil;
import io.netty.handler.codec.http.HttpHeaders;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.platform.Verticle;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheMem extends Verticle implements CacheMemInterface {
/**
* The constant LOG_QUEUE_MAP.
* queue hashmap .
* (Create the log queue hashmap.)
*/
public static AtomicInteger QUEUE_NO = new AtomicInteger(1);
public static ConcurrentHashMap<Integer, LinkedBlockingQueue<CacheMemLog>> LOG_QUEUE_MAP = new ConcurrentHashMap<>();
/**
* Sets queue no.
*/
public static void setQueueNo () {
if (QUEUE_NO.get() == 1) {
QUEUE_NO.set(2);
} else {
QUEUE_NO.set(1);
}
}
@Override
public void start() {
/**
* HashMap initialization.
*/
LOG_QUEUE_MAP.put(1, new LinkedBlockingQueue<>());
LOG_QUEUE_MAP.put(2, new LinkedBlockingQueue<>());
// Create a Set and Get thread.
makeThreads();
/**
* Create a Logging Thread.
* 1 .
* Start a pop the queue at the once per minutes, and save the log.
*/
new Thread(() -> {
Integer popQueueNo = QUEUE_NO.get();
setQueueNo();
LOG_QUEUE_MAP.get(popQueueNo).stream().parallel().forEach(cacheMemLog -> CacheMemLogger.getInstance().insertLog(cacheMemLog));
LOG_QUEUE_MAP.get(popQueueNo).clear();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
/**
* Create a add to set the TTL value Thread.
* 5 TTL .
* Start a thread at the 5 per minutes, and the TTL time.
*/
new Thread(() -> {
while (true) {
CacheMemUtil.setAddTTLTime();
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
/**
* Create a Vert.x instance
*/
vertx.createHttpServer().setUsePooledBuffers(true).setReceiveBufferSize(BUFF_SIZE).setSendBufferSize(BUFF_SIZE).setTCPKeepAlive(false).setTCPNoDelay(true).setAcceptBacklog(10000).requestHandler((req) -> {
MemcachedResult result = WebHandler.getInstance().actionData(req);
String headerContentType = objectHtmlHeader;
String resultMessage = null;
int headerContentLength = 0;
byte[] resultByte = null;
if (result.isResult() && "success".equals(result.getResultText())) {
try {
resultByte = (byte[]) result.getResultObject();
if (resultByte == null || resultByte.length == 0) {
resultMessage = ("/PURGE".equals(req.path().toUpperCase())) ? result.getResultText() : errorMsg002;
headerContentLength = resultMessage.length();
} else {
headerContentType = objectByteHeader;
headerContentLength = resultByte.length;
req.response().putHeader("Accept-Ranges", "bytes");
}
} catch (Exception ex) {
resultMessage = errorMsg003;
headerContentLength = resultMessage.length();
ex.printStackTrace();
}
} else {
resultMessage = errorMsg001;
headerContentLength = resultMessage.length();
}
req.response().putHeader(HttpHeaders.Names.CONTENT_TYPE, headerContentType);
req.response().putHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(headerContentLength));
if (objectByteHeader.equals(headerContentType) && resultByte != null) {
req.response().write(new Buffer(resultByte));
} else {
req.response().end(resultMessage);
}
req.response().close();
}).listen(vertxSocketPort);
}
/**
* Make threads.
* Set, Get thread .
* (Create a Set and Get thread.)
*/
private void makeThreads () {
/**
* .
* (Execute the number of the socket that is already set.)
*
*/
Arrays.stream(serverSockets).parallel().forEach((portNum) ->
// Data input output Socket Thread Get / Set
new Thread(() -> {
/*
* sorry, non block io is not yet.
*
if (nonblocking) {
ClientHandlerNio clientHandlerNio = new ClientHandlerNio(portNum);
clientHandlerNio.start();
} else {
*/
ServerSocket socketServer = null;
try {
/**
* . (backLog .)
* Create a server socket. (initialization with backLog.)
*/
socketServer = new ServerSocket(portNum, threadSocketMaxConnectionQueue);
socketServer.setReuseAddress(true);
socketServer.setReceiveBufferSize(FlashDb.BUFF_SIZE);
socketServer.setSoTimeout(10000);
socketServer.setPerformancePreferences(2, 1, 0);
/**
* .
* Create a thread pool.
*/
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(basicPoolSize, maximumPoolSize, keepPoolAliveTime, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
threadPool.setRejectedExecutionHandler((r, executor) -> {
try {
Thread.sleep(300);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
executor.execute(r);
});
while (true) {
Socket socket = socketServer.accept();
if (socket != null) {
threadPool.execute(new ClientHandler(socket));
}
}
} catch (IOException e) {
e.printStackTrace();
try {
if (socketServer != null) {
socketServer.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}).start()
);
}
}
|
package crawlers.messenger;
import crawlers.messenger.payload.MessageQuery;
import crawlers.messenger.payload.Messages;
import crawlers.messenger.payload.ThreadInfo;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import play.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static crawlers.messenger.ThreadParser.createMessengerGson;
public class MessengerSession {
private static final String COOKIES_FILENAME = "/messenger_cookies";
private static final String MESSENGER_SCHEME = "https";
private static final String MESSENGER_HOST = "www.messenger.com";
private static final String BASE_URL = "/";
private static final String THREAD_LIST_URL = "/ajax/mercury/threadlist_info.php";
private static final String MESSAGES_URL = "/api/graphqlbatch/";
private static final Pattern USER_ID_REGEX = Pattern.compile("\"USER_ID\":\"(.+?)\"");
private static final Pattern CLIENT_REV_REGEX = Pattern.compile("\"client_revision\":(\\d+)");
private static final Pattern DTSG_REGEX = Pattern.compile("\"DTSGInitialData\".*?,\\{\"token\":\"(.+?)\"}");
private static final String ACCEPT_LANGUAGE = "en-US,en;q=0.5";
private static final String USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36";
private CloseableHttpClient httpClient;
private ThreadParser parser = new ThreadParser();
private String cookies;
private int requestCounter = 1;
private String userId;
private String clientRev;
private String fbDtsg;
MessengerSession() {
httpClient = HttpClients.custom()
.setMaxConnPerRoute(1000)
.setConnectionTimeToLive(15, TimeUnit.SECONDS)
.build();
InputStream secretsStream = getClass().getResourceAsStream(COOKIES_FILENAME);
if(secretsStream==null) {
Logger.warn("Cannot find Messenger cookies file " + COOKIES_FILENAME);
return;
}
try {
cookies = IOUtils.toString(secretsStream, "UTF-8").trim();
} catch (IOException e) {
Logger.warn("Cannot open Messenger cookies file " + COOKIES_FILENAME);
return;
}
try {
initializeSession();
} catch (IOException | URISyntaxException | MessengerSessionFieldNotFoundException e) {
throw new RuntimeException("Could not initialize MessengerSession", e);
}
}
private URIBuilder buildUrl(String path) {
URIBuilder builder = new URIBuilder();
builder.setScheme(MESSENGER_SCHEME).setHost(MESSENGER_HOST).setPath(path);
return builder;
}
private void prepareRequest(HttpMessage request) {
request.addHeader("Accept-Language", ACCEPT_LANGUAGE);
request.addHeader("User-Agent", USER_AGENT);
request.addHeader("Cookie", cookies);
}
private void initializeSession() throws IOException, URISyntaxException, MessengerSessionFieldNotFoundException {
HttpGet request = new HttpGet(buildUrl(BASE_URL).build());
prepareRequest(request);
HttpResponse response = httpClient.execute(request);
String content = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
Matcher userIdMatcher = USER_ID_REGEX.matcher(content);
if (!userIdMatcher.find()) {
throw new MessengerSessionFieldNotFoundException("user_id");
}
userId = userIdMatcher.group(1);
Matcher clientRevMatcher = CLIENT_REV_REGEX.matcher(content);
if (!clientRevMatcher.find()) {
throw new MessengerSessionFieldNotFoundException("client_revision");
}
clientRev = clientRevMatcher.group(1);
Matcher dtsgMatcher = DTSG_REGEX.matcher(content);
if (!dtsgMatcher.find()) {
throw new MessengerSessionFieldNotFoundException("fb_dtsg");
}
fbDtsg = dtsgMatcher.group(1);
}
private List<NameValuePair> getQueryParameters() {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("client", "web_messenger"));
params.add(new BasicNameValuePair("__user", userId));
params.add(new BasicNameValuePair("__a", "1"));
params.add(new BasicNameValuePair("__af", "iw"));
params.add(new BasicNameValuePair("__req", Integer.toString(requestCounter++, 36)));
params.add(new BasicNameValuePair("__be", "-1"));
params.add(new BasicNameValuePair("__pc", "PHASED:messengerdotcom_pkg"));
params.add(new BasicNameValuePair("__rev", clientRev));
params.add(new BasicNameValuePair("fb_dtsg", fbDtsg));
return params;
}
public ThreadInfo getThreadInfo(int offset, int limit) throws IOException, URISyntaxException {
HttpPost request = new HttpPost(buildUrl(THREAD_LIST_URL).build());
List<NameValuePair> queryParameters = getQueryParameters();
queryParameters.add(new BasicNameValuePair("inbox[offset]", "" + offset));
queryParameters.add(new BasicNameValuePair("inbox[limit]", "" + limit));
request.setEntity(new UrlEncodedFormEntity(queryParameters));
prepareRequest(request);
HttpResponse response = httpClient.execute(request);
ThreadInfo threads = parser.getThreads(response.getEntity().getContent());
request.releaseConnection();
return threads;
}
private String createMessageQuery(String threadFbid, Date before, int messageLimit) {
MessageQuery query = new MessageQuery();
MessageQuery.MessageQueryParams queryParams = query.getQueryParams();
queryParams.setId(threadFbid);
queryParams.setBefore(before);
queryParams.setMessageLimit(messageLimit);
return createMessengerGson().toJson(query);
}
public Messages getMessages(String threadId, Date before, int messageLimit) throws IOException, URISyntaxException {
HttpPost request = new HttpPost(buildUrl(MESSAGES_URL).build());
List<NameValuePair> queryParameters = getQueryParameters();
queryParameters.add(new BasicNameValuePair("queries", createMessageQuery(threadId, before, messageLimit)));
request.setEntity(new UrlEncodedFormEntity(queryParameters));
prepareRequest(request);
CloseableHttpResponse response = httpClient.execute(request);
Messages messages = parser.getMessages(response.getEntity().getContent());
request.releaseConnection();
return messages;
}
}
|
package org.jetel.data.parser;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.parser.XLSMapping.SpreadsheetOrientation;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelException;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.ExcelUtils;
import org.jetel.util.ExcelUtils.ExcelType;
import org.jetel.util.SpreadsheetUtils;
public class SpreadsheetDOMParser extends AbstractSpreadsheetParser {
/** the workbook parsed by this parser */
private Workbook workbook;
/** currently parsed sheet */
private Sheet sheet;
private int nextRecordStartRow;
/** last row or last column in sheet (depends on orientation) */
private int lastLine;
private int mappingModulo;
private String password;
private final DataFormatter dataFormatter = new DataFormatter();
private final static FormulaEval FORMULA_EVAL = new FormulaEval();
public SpreadsheetDOMParser(DataRecordMetadata metadata, XLSMapping mappingInfo, String password) {
super(metadata, mappingInfo);
this.password = password;
dataFormatter.addFormat("General", new DecimalFormat("
}
@Override
protected void prepareInput(InputStream inputStream) throws IOException, ComponentNotReadyException {
try {
if (!inputStream.markSupported()) {
inputStream = new PushbackInputStream(inputStream, 8);
}
InputStream bufferedStream = null;
ExcelType documentType = ExcelUtils.getStreamType(inputStream);
if (ExcelUtils.getStreamType(inputStream) == ExcelType.XLS) {
bufferedStream = ExcelUtils.getBufferedStream(inputStream);
inputStream = ExcelUtils.getDecryptedXLSXStream(bufferedStream, password);
if (inputStream == null) {
bufferedStream.reset();
inputStream = bufferedStream;
Biff8EncryptionKey.setCurrentUserPassword(password);
}
} else if (documentType == ExcelType.INVALID) {
throw new ComponentNotReadyException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}
workbook = WorkbookFactory.create(inputStream);
} catch (Exception exception) {
throw new ComponentNotReadyException("Error opening the XLS(X) workbook!", exception);
}
}
@Override
public List<String> getSheetNames() {
List<String> toReturn = new ArrayList<String>(workbook.getNumberOfSheets());
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
toReturn.add(workbook.getSheetName(i));
}
return toReturn;
}
@Override
protected int getRecordStartRow() {
return nextRecordStartRow;
}
@Override
public boolean setCurrentSheet(int sheetNumber) {
try {
sheet = workbook.getSheetAt(sheetNumber);
} catch (IllegalArgumentException e) {
return false;
}
if (mappingInfo.getOrientation() == SpreadsheetOrientation.VERTICAL) {
lastLine = sheet.getLastRowNum();
if (lastLine == 0 && sheet.getPhysicalNumberOfRows() == 0) {
lastLine = -1;
}
} else {
for (Row row : sheet) {
if (row.getLastCellNum() - 1 > lastLine) {
lastLine = row.getLastCellNum() - 1;
}
}
}
mappingModulo = lastLine % mapping.length;
nextRecordStartRow = startLine;
return true;
}
@Override
public String[][] getHeader(int startRow, int startColumn, int endRow, int endColumn) throws ComponentNotReadyException {
if (sheet == null) {
throw new ComponentNotReadyException("No sheet to read from!");
}
if (sheet.getLastRowNum() < endRow - 1) {
throw new ComponentNotReadyException("Sheet does not contain header!");
}
int rowsToRead = endRow - startRow;
String[][] result = new String[rowsToRead][];
List<String> rowResult = new ArrayList<String>();
int lastColumn = startColumn - 1;
for (int i = 0; i < rowsToRead; i++) {
Row row = sheet.getRow(startRow + i);
if (row != null) {
int finalColumn = Math.min(row.getLastCellNum(), endColumn);
for (int j = startColumn; j < finalColumn; j++) {
Cell cell = row.getCell(j);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
// add missing cells
for (int k = lastColumn + 1; k < j; k++) {
rowResult.add(null);
}
rowResult.add(dataFormatter.formatCellValue(cell, FORMULA_EVAL));
lastColumn = j;
}
}
result[i] = rowResult.toArray(new String[rowResult.size()]);
rowResult.clear();
lastColumn = startColumn - 1;
} else {
result[i] = new String[0];
}
}
return result;
}
@Override
protected DataRecord parseNext(DataRecord record) throws JetelException {
record.setToNull();
if (mappingInfo.getOrientation() == SpreadsheetOrientation.VERTICAL) {
if (nextRecordStartRow > lastLine - mapping.length + 1) {
if (mappingModulo > 0) {
return parse(record, nextRecordStartRow, mappingMinColumn, mappingModulo, false);
}
return null;
}
return parse(record, nextRecordStartRow, mappingMinColumn, 0, false);
} else {
if (nextRecordStartRow > lastLine - mapping[0].length + 1) {
if (mappingModulo > 0) {
return parse(record, mappingMinRow, nextRecordStartRow, mappingModulo, true);
}
return null;
}
return parse(record, mappingMinRow, nextRecordStartRow, 0, true);
}
}
private DataRecord parse(DataRecord record, int recordStartRow, int startColumn, int mappingRowStart, boolean horizontal) {
// for (int mappingRowIndex = 0; mappingRowIndex < mapping.length; mappingRowIndex++) {
for (int mappingRowIndex = mappingRowStart; mappingRowIndex < mapping.length; mappingRowIndex++) {
int[] recordRow = mapping[mappingRowIndex];
int[] formatRecordRow = formatMapping != null ? formatMapping[mappingRowIndex] : null;
Row row = sheet.getRow(recordStartRow + mappingRowIndex);
if (row == null) {
processNullRow(record, recordRow, recordStartRow + mappingRowIndex);
processNullRow(record, formatRecordRow, recordStartRow + mappingRowIndex);
continue;
}
int cloverFieldIndex;
for (int column = startColumn; column < recordRow.length + startColumn; column++) {
if ((cloverFieldIndex = recordRow[column - startColumn]) != XLSMapping.UNDEFINED) {
fillCloverField(row.getCell(column), record, cloverFieldIndex, column, horizontal);
}
if (formatRecordRow != null) {
if ((cloverFieldIndex = formatRecordRow[column - startColumn]) != XLSMapping.UNDEFINED) {
fillFormatField(row.getCell(column), record, cloverFieldIndex, column, horizontal);
}
}
}
}
nextRecordStartRow += mappingInfo.getStep();
return record;
}
private void processNullRow(DataRecord record, int[] recordRow, int currentParseRow) {
if (recordRow != null) {
for (int column = 0; column < recordRow.length; column++) {
int cloverFieldIndex;
if ((cloverFieldIndex = recordRow[column]) != XLSMapping.UNDEFINED) {
try {
record.getField(cloverFieldIndex).setNull(true);
if (currentParseRow > lastLine) {
handleException(new BadDataFormatException("Unexpected end of sheet - expected another data row for field " + record.getField(cloverFieldIndex).getMetadata().getName() +
". Occurred"), record, cloverFieldIndex, null, null);
}
} catch (BadDataFormatException e) {
handleException(new BadDataFormatException("Unexpected end of sheet - expected another data row for field " + record.getField(cloverFieldIndex).getMetadata().getName() +
". Moreover, cannot set default value or null", e), record, cloverFieldIndex, null, null);
}
}
}
}
}
private void fillCloverField(Cell cell, DataRecord record, int cloverFieldIndex, int currentParseRow, boolean horizontal) {
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
try {
record.getField(cloverFieldIndex).setNull(true);
if (currentParseRow > lastLine && horizontal) {
handleException(new BadDataFormatException("Unexpected end of sheet - expected another data row for field " + record.getField(cloverFieldIndex).getMetadata().getName() +
". Occurred"), record, cloverFieldIndex, null, null);
}
return;
} catch (BadDataFormatException e) {
handleException(new BadDataFormatException("There is no data cell for field. Moreover, cannot set default value or null", e), record, cloverFieldIndex, null, null);
return;
}
}
char type = metadata.getField(cloverFieldIndex).getType();
String expectedType = null;
// try {
try {
switch (type) {
case DataFieldMetadata.DATE_FIELD:
case DataFieldMetadata.DATETIME_FIELD:
expectedType = "date";
record.getField(cloverFieldIndex).setValue(cell.getDateCellValue());
break;
case DataFieldMetadata.BYTE_FIELD:
expectedType = "byte";
case DataFieldMetadata.STRING_FIELD:
expectedType = "string";
record.getField(cloverFieldIndex).fromString(dataFormatter.formatCellValue(cell, FORMULA_EVAL));
break;
case DataFieldMetadata.DECIMAL_FIELD:
expectedType = "decimal";
case DataFieldMetadata.INTEGER_FIELD:
expectedType = "integer";
case DataFieldMetadata.LONG_FIELD:
expectedType = "long";
case DataFieldMetadata.NUMERIC_FIELD:
expectedType = "number";
record.getField(cloverFieldIndex).setValue(cell.getNumericCellValue());
break;
case DataFieldMetadata.BOOLEAN_FIELD:
expectedType = "boolean";
record.getField(cloverFieldIndex).setValue(cell.getBooleanCellValue());
break;
}
} catch (IllegalStateException e) {
// Thrown by cell.get*CellValue if cell value type expected here in code is different than the actual cell value.
// If the actual cell value is empty string (after trimming), interpret it as null, otherwise rethrow the exception.
if (cell.getCellType() == Cell.CELL_TYPE_STRING && "".equals(cell.getStringCellValue().trim())) {
record.getField(cloverFieldIndex).setNull(true);
} else {
// throw e;
// String errorMessage = "Cannot get " + expectedType + " value from cell of type " + cellTypeToString(cell.getCellType());
try {
record.getField(cloverFieldIndex).setNull(true);
} catch (Exception ex) {
}
String cellCoordinates = SpreadsheetUtils.getColumnReference(cell.getColumnIndex()) + String.valueOf(cell.getRowIndex());
handleException(new BadDataFormatException("Cannot get " + expectedType + " value from cell of type " +
cellTypeToString(cell.getCellType()) + " in " + cellCoordinates), record, cloverFieldIndex, cellCoordinates, dataFormatter.formatCellValue(cell));
}
}
// } catch (RuntimeException exception) { // exception when trying get date or number from a different cell type
// String errorMessage = exception.getMessage();
// try {
// record.getField(cloverFieldIndex).setNull(true);
// } catch (Exception ex) {
// String cellCoordinates = SpreadsheetUtils.getColumnReference(cell.getColumnIndex()) + String.valueOf(cell.getRowIndex());
// handleException(new BadDataFormatException(errorMessage), record, cloverFieldIndex, cellCoordinates, dataFormatter.formatCellValue(cell));
}
private String cellTypeToString(int cellType) {
switch (cellType) {
case Cell.CELL_TYPE_BOOLEAN:
return "Boolean";
case Cell.CELL_TYPE_STRING:
return "String";
case Cell.CELL_TYPE_NUMERIC:
return "Numeric";
default:
return "Unknown";
}
}
private void fillFormatField(Cell cell, DataRecord record, int cloverFieldIndex, int currentParseRow, boolean horizontal) {
String formatString = cell != null ? cell.getCellStyle().getDataFormatString() : null;
try {
// formatString may be null, or namely "GENERAL"
record.getField(cloverFieldIndex).setValue(formatString);
if (currentParseRow > lastLine && horizontal) {
handleException(new BadDataFormatException("Unexpected end of sheet - expected another data row for field " + record.getField(cloverFieldIndex).getMetadata().getName() +
". Occurred"), record, cloverFieldIndex, null, null);
}
} catch (RuntimeException exception) {
String errorMessage = "Failed to set cell format to field; cause: " + exception;
String cellCoordinates = SpreadsheetUtils.getColumnReference(cell.getColumnIndex()) + String.valueOf(cell.getRowIndex());
handleException(new BadDataFormatException(errorMessage), record, cloverFieldIndex, cellCoordinates, formatString);
}
}
@Override
public int skip(int nRec) throws JetelException {
int numberOfRows = nRec * mappingInfo.getStep();
if (nextRecordStartRow + numberOfRows <= lastLine) {
nextRecordStartRow += numberOfRows;
return nRec;
} else {
int retval = 1 + ((lastLine - nextRecordStartRow) / mappingInfo.getStep());
nextRecordStartRow = lastLine + 1;
return retval;
}
}
@Override
public void postExecute() throws ComponentNotReadyException {
super.postExecute();
workbook = null;
sheet = null;
}
@Override
public void close() throws IOException {
super.close();
workbook = null;
sheet = null;
Biff8EncryptionKey.setCurrentUserPassword(null);
}
/**
* This class is used for the dataFormater to return cell formula cached result (stored in the cell XML), not
* formula itself.
*/
private static class FormulaEval implements FormulaEvaluator {
@Override
public void clearAllCachedResultValues() {
}
@Override
public void notifySetFormula(Cell cell) {
}
@Override
public void notifyDeleteCell(Cell cell) {
}
@Override
public void notifyUpdateCell(Cell cell) {
}
@Override
public org.apache.poi.ss.usermodel.CellValue evaluate(Cell cell) {
throw new UnsupportedOperationException();
}
@Override
public void evaluateAll() {
throw new UnsupportedOperationException();
}
@Override
public int evaluateFormulaCell(Cell cell) {
return cell.getCachedFormulaResultType();
}
@Override
public Cell evaluateInCell(Cell cell) {
throw new UnsupportedOperationException();
}
}
}
|
package co.oriens.yandex_translate_android_api;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
//Declare Context
Context ctx;
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
@Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey = "YOUR_API_KEY";
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
|
package ru.liahim.saltmod.common;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDispenser;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraftforge.common.ChestGenHooks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import ru.liahim.saltmod.SaltMod;
import ru.liahim.saltmod.api.ExtractRegistry;
import ru.liahim.saltmod.dispenser.DispenserBehaviorRainmaiker;
import ru.liahim.saltmod.dispenser.DispenserBehaviorSaltPinch;
import ru.liahim.saltmod.entity.EntityRainmaker;
import ru.liahim.saltmod.entity.EntityRainmakerDust;
import ru.liahim.saltmod.init.AchievSalt;
import ru.liahim.saltmod.init.ModBlocks;
import ru.liahim.saltmod.init.ModItems;
import ru.liahim.saltmod.init.SaltConfig;
import ru.liahim.saltmod.inventory.gui.GuiExtractorHandler;
import ru.liahim.saltmod.network.ExtractorButtonMessage;
import ru.liahim.saltmod.network.SaltModEvent;
import ru.liahim.saltmod.network.SaltWortMessage;
import ru.liahim.saltmod.tileentity.TileEntityExtractor;
import ru.liahim.saltmod.world.SaltCrystalGenerator;
import ru.liahim.saltmod.world.SaltLakeGenerator;
import ru.liahim.saltmod.world.SaltOreGenerator;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class CommonProxy {
public static CreativeTabs saltTab = new SaltTab("saltTab");
public static SaltOreGenerator saltOreGenerator = new SaltOreGenerator();
public static SaltCrystalGenerator saltCrystalGenerator = new SaltCrystalGenerator();
public static SaltLakeGenerator saltLakeGenerator = new SaltLakeGenerator();
public static ArmorMaterial mudMaterial = EnumHelper.addArmorMaterial("mudMaterial", 4, new int[]{1, 1, 1, 1}, 15);
//Milk
@SideOnly(Side.CLIENT)
public static IIcon milkIcon;
public static Fluid milk;
public static SimpleNetworkWrapper network;
public void preInit(FMLPreInitializationEvent event) {
SaltModEvent sEvent = new SaltModEvent();
FMLCommonHandler.instance().bus().register(sEvent);
MinecraftForge.EVENT_BUS.register(sEvent);
NetworkRegistry.INSTANCE.registerGuiHandler(SaltMod.instance, new GuiExtractorHandler());
network = NetworkRegistry.INSTANCE.newSimpleChannel(SaltMod.MODID);
network.registerMessage(ExtractorButtonMessage.Handler.class, ExtractorButtonMessage.class, 0, Side.SERVER);
network.registerMessage(SaltWortMessage.Handler.class, SaltWortMessage.class, 1, Side.CLIENT);
}
public void init(FMLInitializationEvent event) {
AchievSalt.init();
ClientProxy.setBlockRenderers();
if (event.getSide().isClient()) {ClientProxy.setEntityRenderers();}
GameRegistry.registerTileEntity(TileEntityExtractor.class, "tileEntityExtractor");
EntityRegistry.registerModEntity(EntityRainmaker.class, "entityRainmaker", 0, SaltMod.instance, 64, 20, true);
EntityRegistry.registerModEntity(EntityRainmakerDust.class, "entityRainmakerDust", 1, SaltMod.instance, 64, 20, false);
BlockDispenser.dispenseBehaviorRegistry.putObject(ModItems.rainmaker, new DispenserBehaviorRainmaiker());
BlockDispenser.dispenseBehaviorRegistry.putObject(ModItems.saltPinch, new DispenserBehaviorSaltPinch());
GameRegistry.registerWorldGenerator(saltOreGenerator, 0);
GameRegistry.registerWorldGenerator(saltCrystalGenerator, 10);
GameRegistry.registerWorldGenerator(saltLakeGenerator, 15);
//Recipe
ExtractRegistry.instance().addExtracting(FluidRegistry.WATER, ModItems.saltPinch, 1000, 0.0F);
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 9), new ItemStack(ModItems.salt));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 5));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 6));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 7));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 8));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBlock, 1, 9));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltLamp));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.salt, 9), new ItemStack(ModBlocks.saltBrickStair));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 40), new ItemStack(ModBlocks.saltSlab, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 40), new ItemStack(ModBlocks.saltSlab, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch, 40), new ItemStack(ModBlocks.saltSlab, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPinch), new ItemStack(ModBlocks.saltCrystal));
GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.saltDirt), new ItemStack(ModItems.salt), new ItemStack(Blocks.dirt));
GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.saltDirt), new ItemStack(ModBlocks.saltDirtLite), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(Items.dye, 1, 2), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fizzyDrink), new ItemStack(ModItems.soda), new ItemStack(Items.potionitem));
GameRegistry.addShapelessRecipe(new ItemStack(Items.potionitem), new ItemStack(Items.glass_bottle), new ItemStack(Items.snowball));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mineralMud), new ItemStack(ModItems.soda), new ItemStack(ModItems.salt), new ItemStack(Items.coal), new ItemStack(Items.clay_ball));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mineralMud), new ItemStack(ModItems.soda), new ItemStack(ModItems.salt), new ItemStack(Items.coal, 1, 1), new ItemStack(Items.clay_ball));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mineralMud, 4), new ItemStack(ModBlocks.mudBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltBeefCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_beef));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPorkchopCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_porkchop));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoBaked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.baked_potato));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltChickenCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_chicken));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishCod), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(Items.fish));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishCodCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_fished));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmon), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(Items.fish, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmonCooked), new ItemStack(ModItems.saltPinch), new ItemStack(Items.cooked_fished, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishClownfish), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.saltPinch), new ItemStack(Items.fish, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltMushroomStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.mushroom_stew));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltMushroomStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltBread), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bread));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltEgg), new ItemStack(ModItems.saltPinch), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pumpkinPorridge), new ItemStack(Items.bowl), new ItemStack(Blocks.pumpkin));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.vegetableStew), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.vegetableStew), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltVegetableStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltVegetableStew), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltVegetableStew), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.vegetableStew));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.potatoMushroom), new ItemStack(Items.bowl), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.potatoMushroom), new ItemStack(Items.bowl), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(ModItems.potatoMushroom), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltPotatoMushroom), new ItemStack(ModItems.potatoMushroom), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishSoup), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSoup), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSoup), new ItemStack(ModItems.fishSoup), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishSalmonSoup), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmonSoup), new ItemStack(Items.bowl), new ItemStack(ModItems.saltPinch), new ItemStack(Items.carrot), new ItemStack(Items.potato), new ItemStack(Items.fish, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltFishSalmonSoup), new ItemStack(ModItems.fishSalmonSoup), new ItemStack(ModItems.saltPinch));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortBeef), new ItemStack(Items.bowl), new ItemStack(Items.cooked_beef), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortPorkchop), new ItemStack(Items.bowl), new ItemStack(Items.cooked_porkchop), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.dandelionSalad), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Blocks.yellow_flower), new ItemStack(Blocks.red_flower, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltDandelionSalad), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Blocks.yellow_flower), new ItemStack(Blocks.red_flower, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltDandelionSalad), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.dandelionSalad));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.wheatSprouts), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWheatSprouts), new ItemStack(ModItems.saltPinch), new ItemStack(Items.bowl), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds), new ItemStack(Items.wheat_seeds));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWheatSprouts), new ItemStack(ModItems.saltPinch), new ItemStack(ModItems.wheatSprouts));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fruitSalad), new ItemStack(Items.bowl), new ItemStack(Items.apple), new ItemStack(Items.carrot), new ItemStack(Items.melon));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.gratedCarrot), new ItemStack(Items.bowl), new ItemStack(Items.carrot), new ItemStack(Items.carrot), new ItemStack(Items.sugar));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.carrotPie), new ItemStack(Items.carrot), new ItemStack(Items.carrot), new ItemStack(Items.sugar), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.applePie), new ItemStack(Items.apple), new ItemStack(Items.apple), new ItemStack(Items.sugar), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.potatoPie), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potato), new ItemStack(Items.potato), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.onionPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.red_flower, 1, 2), new ItemStack(Blocks.red_flower, 1, 2), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishPie), new ItemStack(ModItems.saltPinch), new ItemStack(Items.wheat), new ItemStack(Items.fish), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fishSalmonPie), new ItemStack(ModItems.saltPinch), new ItemStack(Items.wheat), new ItemStack(Items.fish, 1, 1), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mushroomPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mushroomPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.mushroomPie), new ItemStack(ModItems.saltPinch), new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledMushroom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.brown_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledMushroom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.red_mushroom), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledMushroom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.brown_mushroom), new ItemStack(Blocks.red_mushroom));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.pickledFern), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(Blocks.tallgrass, 1, 2), new ItemStack(Blocks.tallgrass, 1, 2));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortPie), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(Items.wheat), new ItemStack(Items.egg));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltWortSalad), new ItemStack(Items.bowl), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.fermentedSaltWort), new ItemStack(Items.glass_bottle), new ItemStack(Items.ghast_tear), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.muffin), new ItemStack(ModItems.soda), new ItemStack(Items.egg), new ItemStack(Items.wheat), new ItemStack(Items.dye, 1, 3));
GameRegistry.addShapelessRecipe(new ItemStack(Items.milk_bucket), new ItemStack(ModItems.powderedMilk), new ItemStack(Items.water_bucket), new ItemStack(Items.bucket));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.saltStar), new ItemStack(Items.gunpowder), new ItemStack(ModItems.salt), new ItemStack(ModItems.salt), new ItemStack(ModItems.salt), new ItemStack(ModItems.salt), new ItemStack(ModItems.soda), new ItemStack(ModItems.soda), new ItemStack(ModItems.soda), new ItemStack(ModItems.soda));
GameRegistry.addShapelessRecipe(new ItemStack(ModItems.rainmaker), new ItemStack(ModItems.saltStar), new ItemStack(ModItems.saltStar), new ItemStack(ModItems.saltStar), new ItemStack(ModItems.saltStar), new ItemStack(ModItems.saltStar), new ItemStack(Items.paper), new ItemStack(Items.gunpowder), new ItemStack(Items.gunpowder), new ItemStack(Items.gunpowder));
GameRegistry.addRecipe(new ItemStack(ModItems.salt), "xxx", "xxx", "xxx", 'x', ModItems.saltPinch);
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock), "xxx", "xxx", "xxx", 'x', ModItems.salt);
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltLamp), "x", "y", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0), 'y', new ItemStack(Blocks.torch));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 4, 5), "xx", "xx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 2, 2), "x", "x", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 1, 1), "x", "x", 'x', new ItemStack(ModBlocks.saltSlab, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 1, 8), "x", "x", 'x', new ItemStack(ModBlocks.saltSlab, 1, 1));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBlock, 1, 9), "x", "x", 'x', new ItemStack(ModBlocks.saltSlab, 1, 2));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltBrickStair, 6), " x", " xx", "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 5));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltSlab, 6, 0), "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 0));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltSlab, 6, 1), "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 5));
GameRegistry.addRecipe(new ItemStack(ModBlocks.saltSlab, 6, 2), "xxx", 'x', new ItemStack(ModBlocks.saltBlock, 1, 2));
GameRegistry.addRecipe(new ItemStack(ModItems.cornedBeef), "xxx", "xyx", "xxx", 'x', ModItems.saltPinch, 'y', Items.rotten_flesh);
GameRegistry.addRecipe(new ItemStack(ModBlocks.mudBlock), "xx", "xx", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudHelmet), "xxx", "x x", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudChestplate), "x x", "xxx", "xxx", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudLeggings), "xxx", "x x", "x x", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModItems.mudBoots), "x x", "x x", 'x', ModItems.mineralMud);
GameRegistry.addRecipe(new ItemStack(ModBlocks.extractor), "xyx", "x x", "xxx", 'x', Blocks.cobblestone, 'y', Items.cauldron);
GameRegistry.addSmelting(ModBlocks.saltOre, new ItemStack(ModItems.salt, 1), 0.7F);
GameRegistry.addSmelting(ModBlocks.saltLake, new ItemStack(ModItems.salt, 1), 0.7F);
GameRegistry.addSmelting(new ItemStack(ModBlocks.saltBlock, 1, 0), new ItemStack(ModBlocks.saltBlock, 1, 6), 0.0F);
GameRegistry.addSmelting(new ItemStack(ModBlocks.saltBlock, 1, 5), new ItemStack(ModBlocks.saltBlock, 1, 7), 0.0F);
GameRegistry.addSmelting(ModItems.saltWortSeed, new ItemStack(ModItems.soda, 1), 0.0F);
//Chest Content
ChestGenHooks.addItem(ChestGenHooks.BONUS_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.DUNGEON_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 3, 3));
ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_CORRIDOR, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.STRONGHOLD_CROSSING, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 5, 5));
ChestGenHooks.addItem(ChestGenHooks.MINESHAFT_CORRIDOR, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 10));
ChestGenHooks.addItem(ChestGenHooks.VILLAGE_BLACKSMITH, new WeightedRandomChestContent(new ItemStack(ModItems.salt), 2, 5, 10));
ChestGenHooks.addItem(ChestGenHooks.PYRAMID_DESERT_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 3, 3));
ChestGenHooks.addItem(ChestGenHooks.PYRAMID_JUNGLE_CHEST, new WeightedRandomChestContent(new ItemStack(ModItems.saltWortSeed), 2, 5, 5));
//OreDictionary
OreDictionary.registerOre("oreSalt", ModBlocks.saltOre);
OreDictionary.registerOre("blockSalt", ModBlocks.saltBlock);
OreDictionary.registerOre("blockSaltCrystal", ModBlocks.saltCrystal);
OreDictionary.registerOre("lumpSalt", ModItems.salt);
OreDictionary.registerOre("dustSalt", ModItems.saltPinch);
OreDictionary.registerOre("dustSoda", ModItems.soda);
OreDictionary.registerOre("dustMilk", ModItems.powderedMilk);
OreDictionary.registerOre("cropSaltwort", ModItems.saltWortSeed);
OreDictionary.registerOre("materialMineralMud", ModItems.mineralMud);
}
public void postInit(FMLPostInitializationEvent event) {
//TF Items & Recipe
Item venisonCooked = GameRegistry.findItem("TwilightForest", "item.venisonCooked");
if (venisonCooked != null) {
GameRegistry.registerItem(SaltConfig.saltVenisonCooked, "saltVenisonCooked");
GameRegistry.registerItem(SaltConfig.saltWortVenison, "saltWortVenison");
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.saltVenisonCooked), new ItemStack(ModItems.saltPinch), new ItemStack(venisonCooked));
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.saltWortVenison), new ItemStack(venisonCooked), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(Items.bowl));
}
Item meefSteak = GameRegistry.findItem("TwilightForest", "item.meefSteak");
if (meefSteak != null) {
GameRegistry.registerItem(SaltConfig.saltMeefSteak, "saltMeefSteak");
GameRegistry.registerItem(SaltConfig.saltWortMeefSteak, "saltWortMeefSteak");
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.saltMeefSteak), new ItemStack(ModItems.saltPinch), new ItemStack(meefSteak));
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.saltWortVenison), new ItemStack(meefSteak), new ItemStack(ModItems.saltWortSeed), new ItemStack(ModItems.saltWortSeed), new ItemStack(Items.bowl));
}
Item meefStroganoff = GameRegistry.findItem("TwilightForest", "item.meefStroganoff");
if (meefStroganoff != null) {
GameRegistry.registerItem(SaltConfig.saltMeefStroganoff, "saltMeefStroganoff");
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.saltMeefStroganoff), new ItemStack(ModItems.saltPinch), new ItemStack(meefStroganoff));
}
Item hydraChop = GameRegistry.findItem("TwilightForest", "item.hydraChop");
if (hydraChop != null) {
GameRegistry.registerItem(SaltConfig.saltHydraChop, "saltHydraChop");
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.saltHydraChop), new ItemStack(ModItems.saltPinch), new ItemStack(hydraChop));
}
Block mushgloom = GameRegistry.findBlock("TwilightForest", "tile.TFPlant");
if (mushgloom != null) {
GameRegistry.registerItem(SaltConfig.pickledMushgloom, "pickledMushgloom");
GameRegistry.addShapelessRecipe(new ItemStack(SaltConfig.pickledMushgloom), new ItemStack(ModItems.saltPinch), new ItemStack(Items.potionitem), new ItemStack(mushgloom, 1, 9), new ItemStack(mushgloom, 1, 9));
}
//Milk Registry
if (FluidRegistry.isFluidRegistered("milk")) {
Fluid milk = FluidRegistry.getFluid("milk");
ExtractRegistry.instance().addExtracting(milk, ModItems.powderedMilk, 1000, 0.0F);
} else {
milk = new Fluid("milk");
FluidRegistry.registerFluid(milk);
FluidContainerRegistry.registerFluidContainer(new FluidStack(milk, FluidContainerRegistry.BUCKET_VOLUME), new ItemStack(Items.milk_bucket), FluidContainerRegistry.EMPTY_BUCKET);
ExtractRegistry.instance().addExtracting(milk, ModItems.powderedMilk, 1000, 0.0F);
}
}
}
|
package application;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
public class MortgageController implements Initializable {
public TextField loanAmountField;
public ComboBox<Double> interestBox;
public ComboBox<Integer> yearBox;
public Button calcButton;
public TextField totalField;
public TableView<MortgagePayment> paymentTable;
public TableColumn<MortgagePayment, String> monthNoCol;
public TableColumn<MortgagePayment, Double> paymentCol;
public TableColumn<MortgagePayment, Double> principlePaidCol;
public TableColumn<MortgagePayment, Double> interestPaidCol;
public TableColumn<MortgagePayment, Double> totalInterestPaidCol;
public TableColumn<MortgagePayment, Double> remainingValueCol;
private ObservableList<MortgagePayment> payments;
@Override
public void initialize(URL location, ResourceBundle resources){
System.out.println("Initializing Mortgage Contoller");
ObservableList<Double> interestOptions =
FXCollections.observableArrayList(
3.25, 3.5, 3.75, 4.0, 4.25, 4.5, 4.75, 5.0);
ObservableList<Integer> yearOptions =
FXCollections.observableArrayList(
5, 10, 15, 30);
interestBox.setItems(interestOptions);
interestBox.getSelectionModel().selectFirst();
yearBox.setItems(yearOptions);
yearBox.getSelectionModel().selectFirst();
monthNoCol.setCellValueFactory(
new PropertyValueFactory<MortgagePayment,String>("monthNo")
);
paymentCol.setCellValueFactory(
new PropertyValueFactory<MortgagePayment,Double>("payment")
);
principlePaidCol.setCellValueFactory(
new PropertyValueFactory<MortgagePayment,Double>("principlePaid")
);
interestPaidCol.setCellValueFactory(
new PropertyValueFactory<MortgagePayment,Double>("interestPaid")
);
totalInterestPaidCol.setCellValueFactory(
new PropertyValueFactory<MortgagePayment,Double>("totalInterestPaid")
);
remainingValueCol.setCellValueFactory(
new PropertyValueFactory<MortgagePayment,Double>("remainingValue")
);
payments = FXCollections.observableArrayList();
paymentTable.setItems(payments);
}
public void handleCalculateAction(ActionEvent event){
System.out.println("You clicked the Calculate Button!");
double interestMonthly = interestBox.getValue() / 12 / 100;
System.out.println("Monthly interest percentage: " + interestMonthly);
int numberMonths = 12 * yearBox.getValue();
int index = 1;
payments = FXCollections.observableArrayList();
double totalPaid = 0;
double totalInterestPaid = 0;
try {
String loanAmountString = loanAmountField.getText();
double remainingBalance = Double.parseDouble(loanAmountString);
System.out.println("Initial principal: " + remainingBalance);
double monthlyPayment = remainingBalance * interestMonthly *
Math.pow(1 + interestMonthly, (double) numberMonths) /
(Math.pow(1 + interestMonthly, (double) numberMonths) - 1);
DecimalFormat df = new DecimalFormat("
monthlyPayment = Double.parseDouble(df.format(monthlyPayment));
System.out.println("Monthly Payment: " + monthlyPayment);
for (index = 1; index < numberMonths; index++){
double interestPaid = remainingBalance * interestMonthly;
double principlePaid = monthlyPayment - interestPaid;
remainingBalance = remainingBalance - monthlyPayment;
totalInterestPaid += interestPaid;
totalPaid += monthlyPayment;
payments.add(new MortgagePayment("Month " + index, monthlyPayment,
principlePaid, interestPaid,
totalInterestPaid, remainingBalance));
}
totalField.setText(df.format(totalPaid));
} catch(Exception e){
System.out.println("Exception thrown while calculating: " + e.getMessage());
e.printStackTrace();
totalField.setText("");
}
}
}
|
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.meta;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.opentsdb.core.TSDB;
import net.opentsdb.uid.UniqueId;
import net.opentsdb.uid.UniqueId.UniqueIdType;
import net.opentsdb.utils.JSON;
import net.opentsdb.utils.JSONException;
import org.hbase.async.AtomicIncrementRequest;
import org.hbase.async.Bytes;
import org.hbase.async.DeleteRequest;
import org.hbase.async.GetRequest;
import org.hbase.async.HBaseException;
import org.hbase.async.KeyValue;
import org.hbase.async.PutRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.stumbleupon.async.Callback;
import com.stumbleupon.async.Deferred;
/**
* Timeseries Metadata is associated with a particular series of data points
* and includes user configurable values and some stats calculated by OpenTSDB.
* Whenever a new timeseries is recorded, an associated TSMeta object will
* be stored with only the tsuid field configured. These meta objects may then
* be used to determine what combinations of metrics and tags exist in the
* system.
* <p>
* When you call {@link #syncToStorage} on this object, it will verify that the
* associated UID objects this meta data is linked with still exist. Then it
* will fetch the existing data and copy changes, overwriting the user fields if
* specific (e.g. via a PUT command). If overwriting is not called for (e.g. a
* POST was issued), then only the fields provided by the user will be saved,
* preserving all of the other fields in storage. Hence the need for the
* {@code changed} hash map and the {@link #syncMeta} method.
* <p>
* The metric and tag UIDMeta objects may be loaded from their respective
* locations in the data storage system if requested. Note that this will cause
* at least 3 extra storage calls when loading.
* @since 2.0
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
@JsonAutoDetect(fieldVisibility = Visibility.PUBLIC_ONLY)
public final class TSMeta {
private static final Logger LOG = LoggerFactory.getLogger(TSMeta.class);
/** Charset used to convert Strings to byte arrays and back. */
private static final Charset CHARSET = Charset.forName("ISO-8859-1");
/** The single column family used by this class. */
private static final byte[] FAMILY = "name".getBytes(CHARSET);
/** The cell qualifier to use for timeseries meta */
private static final byte[] META_QUALIFIER = "ts_meta".getBytes(CHARSET);
/** The cell qualifier to use for timeseries meta */
private static final byte[] COUNTER_QUALIFIER = "ts_ctr".getBytes(CHARSET);
/** Hexadecimal representation of the TSUID this metadata is associated with */
private String tsuid = "";
/** The metric associated with this timeseries */
private UIDMeta metric = null;
/** A list of tagk/tagv pairs of UIDMetadata associated with this timeseries */
private ArrayList<UIDMeta> tags = null;
/** An optional, user supplied descriptive name */
private String display_name = "";
/** An optional short description of the timeseries */
private String description = "";
/** Optional detailed notes about the timeseries */
private String notes = "";
/** A timestamp of when this timeseries was first recorded in seconds */
private long created = 0;
/** Optional user supplied key/values */
private HashMap<String, String> custom = null;
/** An optional field recording the units of data in this timeseries */
private String units = "";
/** An optional field used to record the type of data, e.g. counter, gauge */
private String data_type = "";
/** How long to keep raw data in this timeseries */
private int retention = 0;
/**
* A user defined maximum value for this timeseries, can be used to
* calculate percentages
*/
private double max = Double.NaN;
/**
* A user defined minimum value for this timeseries, can be used to
* calculate percentages
*/
private double min = Double.NaN;
/** The last time this data was recorded in seconds */
private long last_received = 0;
/** The total number of data points recorded since meta has been enabled */
private long total_dps;
/** Tracks fields that have changed by the user to avoid overwrites */
private final HashMap<String, Boolean> changed =
new HashMap<String, Boolean>();
/**
* Default constructor necessary for POJO de/serialization
*/
public TSMeta() {
initializeChangedMap();
}
/**
* Constructor for RPC timeseries parsing that will not set the timestamps
* @param tsuid The UID of the timeseries
*/
public TSMeta(final String tsuid) {
this.tsuid = tsuid;
initializeChangedMap();
}
/**
* Constructor for new timeseries that initializes the created and
* last_received times to the current system time
* @param tsuid The UID of the timeseries
*/
public TSMeta(final byte[] tsuid, final long created) {
this.tsuid = UniqueId.uidToString(tsuid);
// downgrade to seconds
this.created = created > 9999999999L ? created / 1000 : created;
initializeChangedMap();
changed.put("created", true);
}
/** @return a string with details about this object */
@Override
public String toString() {
return tsuid;
}
public Deferred<Object> delete(final TSDB tsdb) {
if (tsuid == null || tsuid.isEmpty()) {
throw new IllegalArgumentException("Missing UID");
}
final DeleteRequest delete = new DeleteRequest(tsdb.uidTable(),
UniqueId.stringToUid(tsuid), FAMILY, META_QUALIFIER);
return tsdb.getClient().delete(delete);
}
public Deferred<Boolean> syncToStorage(final TSDB tsdb,
final boolean overwrite) {
if (tsuid == null || tsuid.isEmpty()) {
throw new IllegalArgumentException("Missing TSUID");
}
boolean has_changes = false;
for (Map.Entry<String, Boolean> entry : changed.entrySet()) {
if (entry.getValue()) {
has_changes = true;
break;
}
}
if (!has_changes) {
LOG.debug(this + " does not have changes, skipping sync to storage");
throw new IllegalStateException("No changes detected in TSUID meta data");
}
/**
* Callback used to verify that the UID name mappings exist. We don't need
* to process the actual name, we just want it to throw an error if any
* of the UIDs don't exist.
*/
class UidCB implements Callback<Object, String> {
@Override
public Object call(String name) throws Exception {
// nothing to do as missing mappings will throw a NoSuchUniqueId
return null;
}
}
// parse out the tags from the tsuid
final List<byte[]> parsed_tags = UniqueId.getTagPairsFromTSUID(tsuid,
TSDB.metrics_width(), TSDB.tagk_width(), TSDB.tagv_width());
// Deferred group used to accumulate UidCB callbacks so the next call
// can wait until all of the UIDs have been verified
ArrayList<Deferred<Object>> uid_group =
new ArrayList<Deferred<Object>>(parsed_tags.size() + 1);
// calculate the metric UID and fetch it's name mapping
final byte[] metric_uid = UniqueId.stringToUid(
tsuid.substring(0, TSDB.metrics_width() * 2));
uid_group.add(tsdb.getUidName(UniqueIdType.METRIC, metric_uid)
.addCallback(new UidCB()));
int idx = 0;
for (byte[] tag : parsed_tags) {
if (idx % 2 == 0) {
uid_group.add(tsdb.getUidName(UniqueIdType.TAGK, tag)
.addCallback(new UidCB()));
} else {
uid_group.add(tsdb.getUidName(UniqueIdType.TAGV, tag)
.addCallback(new UidCB()));
}
idx++;
}
/**
* Callback executed after all of the UID mappings have been verified. This
* will then proceed with the CAS call.
*/
final class ValidateCB implements Callback<Deferred<Boolean>,
ArrayList<Object>> {
private final TSMeta local_meta;
public ValidateCB(final TSMeta local_meta) {
this.local_meta = local_meta;
}
/**
* Nested class that executes the CAS after retrieving existing TSMeta
* from storage.
*/
final class StoreCB implements Callback<Deferred<Boolean>, TSMeta> {
@Override
public Deferred<Boolean> call(TSMeta stored_meta) throws Exception {
if (stored_meta == null) {
throw new IllegalArgumentException("Requested TSMeta did not exist");
}
final byte[] original_meta = stored_meta.getStorageJSON();
local_meta.syncMeta(stored_meta, overwrite);
final PutRequest put = new PutRequest(tsdb.uidTable(),
UniqueId.stringToUid(local_meta.tsuid), FAMILY, META_QUALIFIER,
local_meta.getStorageJSON());
return tsdb.getClient().compareAndSet(put, original_meta);
}
}
/**
* Called on UID mapping verification and continues executing the CAS
* procedure.
* @return Results from the {@link #StoreCB} callback
*/
@Override
public Deferred<Boolean> call(ArrayList<Object> validated)
throws Exception {
return getFromStorage(tsdb, UniqueId.stringToUid(tsuid))
.addCallbackDeferring(new StoreCB());
}
}
// Begins the callback chain by validating that the UID mappings exist
return Deferred.group(uid_group).addCallbackDeferring(new ValidateCB(this));
}
public Deferred<Boolean> storeNew(final TSDB tsdb) {
if (tsuid == null || tsuid.isEmpty()) {
throw new IllegalArgumentException("Missing TSUID");
}
final PutRequest put = new PutRequest(tsdb.uidTable(),
UniqueId.stringToUid(tsuid), FAMILY, META_QUALIFIER, getStorageJSON());
return tsdb.getClient().compareAndSet(put, new byte[0]);
}
public static Deferred<TSMeta> getTSMeta(final TSDB tsdb, final String tsuid) {
return getFromStorage(tsdb, UniqueId.stringToUid(tsuid))
.addCallbackDeferring(new LoadUIDs(tsdb, tsuid));
}
/**
* Parses a TSMeta object from the given column, optionally loading the
* UIDMeta objects
* @param tsdb The TSDB to use for storage access
* @param column The KeyValue column to parse
* @param load_uidmetas Whether or not UIDmeta objects should be loaded
* @return A TSMeta if parsed successfully
* @throws NoSuchUniqueName if one of the UIDMeta objects does not exist
* @throws JSONException if the data was corrupted
*/
public static Deferred<TSMeta> parseFromColumn(final TSDB tsdb,
final KeyValue column, final boolean load_uidmetas) {
if (column.value() == null || column.value().length < 1) {
throw new IllegalArgumentException("Empty column value");
}
final TSMeta meta = JSON.parseToObject(column.value(), TSMeta.class);
// fix in case the tsuid is missing
if (meta.tsuid == null || meta.tsuid.isEmpty()) {
meta.tsuid = UniqueId.uidToString(column.key());
}
if (!load_uidmetas) {
return Deferred.fromResult(meta);
}
final LoadUIDs deferred = new LoadUIDs(tsdb, meta.tsuid);
try {
return deferred.call(meta);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Determines if an entry exists in storage or not.
* This is used by the UID Manager tool to determine if we need to write a
* new TSUID entry or not. It will not attempt to verify if the stored data is
* valid, just checks to see if something is stored in the proper column.
* @param tsdb The TSDB to use for storage access
* @param tsuid The UID of the meta to verify
* @return True if data was found, false if not
* @throws HBaseException if there was an issue fetching
*/
public static Deferred<Boolean> metaExistsInStorage(final TSDB tsdb, final String tsuid) {
final GetRequest get = new GetRequest(tsdb.uidTable(),
UniqueId.stringToUid(tsuid));
get.family(FAMILY);
get.qualifier(META_QUALIFIER);
/**
* Callback from the GetRequest that simply determines if the row is empty
* or not
*/
final class ExistsCB implements Callback<Boolean, ArrayList<KeyValue>> {
@Override
public Boolean call(ArrayList<KeyValue> row) throws Exception {
if (row == null || row.isEmpty() || row.get(0).value() == null) {
return false;
}
return true;
}
}
return tsdb.getClient().get(get).addCallback(new ExistsCB());
}
/**
* Determines if the counter column exists for the TSUID.
* This is used by the UID Manager tool to determine if we need to write a
* new TSUID entry or not. It will not attempt to verify if the stored data is
* valid, just checks to see if something is stored in the proper column.
* @param tsdb The TSDB to use for storage access
* @param tsuid The UID of the meta to verify
* @return True if data was found, false if not
* @throws HBaseException if there was an issue fetching
*/
public static Deferred<Boolean> counterExistsInStorage(final TSDB tsdb,
final byte[] tsuid) {
final GetRequest get = new GetRequest(tsdb.uidTable(), tsuid);
get.family(FAMILY);
get.qualifier(COUNTER_QUALIFIER);
/**
* Callback from the GetRequest that simply determines if the row is empty
* or not
*/
final class ExistsCB implements Callback<Boolean, ArrayList<KeyValue>> {
@Override
public Boolean call(ArrayList<KeyValue> row) throws Exception {
if (row == null || row.isEmpty() || row.get(0).value() == null) {
return false;
}
return true;
}
}
return tsdb.getClient().get(get).addCallback(new ExistsCB());
}
/**
* Increments the tsuid datapoint counter or creates a new counter. Also
* creates a new meta data entry if the counter did not exist.
* <b>Note:</b> This method also:
* <ul><li>Passes the new TSMeta object to the Search plugin after loading
* UIDMeta objects</li>
* <li>Passes the new TSMeta through all configured trees if enabled</li></ul>
* @param tsdb The TSDB to use for storage access
* @param tsuid The TSUID to increment or create
* @return 0 if the put failed, a positive LONG if the put was successful
* @throws HBaseException if there was a storage issue
* @throws JSONException if the data was corrupted
* @throws NoSuchUniqueName if one of the UIDMeta objects does not exist
*/
public static Deferred<Long> incrementAndGetCounter(final TSDB tsdb,
final byte[] tsuid) {
/**
* Callback that will create a new TSMeta if the increment result is 1 or
* will simply return the new value.
*/
final class TSMetaCB implements Callback<Deferred<Long>, Long> {
/**
* Called after incrementing the counter and will create a new TSMeta if
* the returned value was 1 as well as pass the new meta through trees
* and the search indexer if configured.
* @return 0 if the put failed, a positive LONG if the put was successful
*/
@Override
public Deferred<Long> call(final Long incremented_value)
throws Exception {
if (incremented_value > 1) {
// TODO - maybe update the search index every X number of increments?
// Otherwise the search engine would only get last_updated/count
// whenever the user runs the full sync CLI
return Deferred.fromResult(incremented_value);
}
// create a new meta object with the current system timestamp. Ideally
// we would want the data point's timestamp, but that's much more data
// to keep track of and may not be accurate.
final TSMeta meta = new TSMeta(tsuid,
System.currentTimeMillis() / 1000);
/**
* Called after the meta has been passed through tree processing. The
* result of the processing doesn't matter and the user may not even
* have it enabled, so we'll just return the counter.
*/
final class TreeCB implements Callback<Deferred<Long>, Boolean> {
@Override
public Deferred<Long> call(Boolean success) throws Exception {
return Deferred.fromResult(incremented_value);
}
}
/**
* Called after retrieving the newly stored TSMeta and loading
* associated UIDMeta objects. This class will also pass the meta to the
* search plugin and run it through any configured trees
*/
final class FetchNewCB implements Callback<Deferred<Long>, TSMeta> {
@Override
public Deferred<Long> call(TSMeta stored_meta) throws Exception {
// pass to the search plugin
tsdb.indexTSMeta(stored_meta);
// pass through the trees
return tsdb.processTSMetaThroughTrees(stored_meta)
.addCallbackDeferring(new TreeCB());
}
}
/**
* Called after the CAS to store the new TSMeta object. If the CAS
* failed then we return immediately with a 0 for the counter value.
* Otherwise we keep processing to load the meta and pass it on.
*/
final class StoreNewCB implements Callback<Deferred<Long>, Boolean> {
@Override
public Deferred<Long> call(Boolean success) throws Exception {
if (!success) {
LOG.warn("Unable to save metadata: " + meta);
return Deferred.fromResult(0L);
}
LOG.debug("Successfullly created new TSUID entry for: " + meta);
final Deferred<TSMeta> meta = getFromStorage(tsdb, tsuid)
.addCallbackDeferring(
new LoadUIDs(tsdb, UniqueId.uidToString(tsuid)));
return meta.addCallbackDeferring(new FetchNewCB());
}
}
// store the new TSMeta object and setup the callback chain
return meta.storeNew(tsdb).addCallbackDeferring(new StoreNewCB());
}
}
// setup the increment request and execute
final AtomicIncrementRequest inc = new AtomicIncrementRequest(
tsdb.uidTable(), tsuid, FAMILY, COUNTER_QUALIFIER);
return tsdb.getClient().bufferAtomicIncrement(inc).addCallbackDeferring(
new TSMetaCB());
}
private static Deferred<TSMeta> getFromStorage(final TSDB tsdb,
final byte[] tsuid) {
/**
* Called after executing the GetRequest to parse the meta data.
*/
final class GetCB implements Callback<Deferred<TSMeta>, ArrayList<KeyValue>> {
/**
* @return Null if the meta did not exist or a valid TSMeta object if it
* did.
*/
@Override
public Deferred<TSMeta> call(final ArrayList<KeyValue> row) throws Exception {
if (row == null || row.isEmpty()) {
return Deferred.fromResult(null);
}
long dps = 0;
long last_received = 0;
TSMeta meta = null;
for (KeyValue column : row) {
if (Arrays.equals(COUNTER_QUALIFIER, column.qualifier())) {
dps = Bytes.getLong(column.value());
last_received = column.timestamp() / 1000;
} else if (Arrays.equals(META_QUALIFIER, column.qualifier())) {
meta = JSON.parseToObject(column.value(), TSMeta.class);
}
}
if (meta == null) {
LOG.warn("Found a counter TSMeta column without a meta for TSUID: " +
UniqueId.uidToString(row.get(0).key()));
return Deferred.fromResult(null);
}
meta.total_dps = dps;
meta.last_received = last_received;
return Deferred.fromResult(meta);
}
}
final GetRequest get = new GetRequest(tsdb.uidTable(), tsuid);
get.family(FAMILY);
get.qualifiers(new byte[][] { COUNTER_QUALIFIER, META_QUALIFIER });
return tsdb.getClient().get(get).addCallbackDeferring(new GetCB());
}
/** @return The configured meta data column qualifier byte array*/
public static byte[] META_QUALIFIER() {
return META_QUALIFIER;
}
/** @return The configured counter column qualifier byte array*/
public static byte[] COUNTER_QUALIFIER() {
return COUNTER_QUALIFIER;
}
/**
* Syncs the local object with the stored object for atomic writes,
* overwriting the stored data if the user issued a PUT request
* <b>Note:</b> This method also resets the {@code changed} map to false
* for every field
* @param meta The stored object to sync from
* @param overwrite Whether or not all user mutable data in storage should be
* replaced by the local object
*/
private void syncMeta(final TSMeta meta, final boolean overwrite) {
// storage *could* have a missing TSUID if something went pear shaped so
// only use the one that's configured. If the local is missing, we're foobar
if (meta.tsuid != null && !meta.tsuid.isEmpty()) {
tsuid = meta.tsuid;
}
if (tsuid == null || tsuid.isEmpty()) {
throw new IllegalArgumentException("TSUID is empty");
}
if (meta.created > 0 && (meta.created < created || created == 0)) {
created = meta.created;
}
// handle user-accessible stuff
if (!overwrite && !changed.get("display_name")) {
display_name = meta.display_name;
}
if (!overwrite && !changed.get("description")) {
description = meta.description;
}
if (!overwrite && !changed.get("notes")) {
notes = meta.notes;
}
if (!overwrite && !changed.get("custom")) {
custom = meta.custom;
}
if (!overwrite && !changed.get("units")) {
units = meta.units;
}
if (!overwrite && !changed.get("data_type")) {
data_type = meta.data_type;
}
if (!overwrite && !changed.get("retention")) {
retention = meta.retention;
}
if (!overwrite && !changed.get("max")) {
max = meta.max;
}
if (!overwrite && !changed.get("min")) {
min = meta.min;
}
last_received = meta.last_received;
total_dps = meta.total_dps;
// reset changed flags
initializeChangedMap();
}
/**
* Sets or resets the changed map flags
*/
private void initializeChangedMap() {
// set changed flags
changed.put("display_name", false);
changed.put("description", false);
changed.put("notes", false);
changed.put("created", false);
changed.put("custom", false);
changed.put("units", false);
changed.put("data_type", false);
changed.put("retention", false);
changed.put("max", false);
changed.put("min", false);
changed.put("last_received", false);
changed.put("created", false);
}
/**
* Formats the JSON output for writing to storage. It drops objects we don't
* need or want to store (such as the UIDMeta objects or the total dps) to
* save space. It also serializes in order so that we can make a proper CAS
* call. Otherwise the POJO serializer may place the fields in any order
* and CAS calls would fail all the time.
* @return A byte array to write to storage
*/
private byte[] getStorageJSON() {
// 256 bytes is a good starting value, assumes default info
final ByteArrayOutputStream output = new ByteArrayOutputStream(256);
try {
final JsonGenerator json = JSON.getFactory().createGenerator(output);
json.writeStartObject();
json.writeStringField("tsuid", tsuid);
json.writeStringField("displayName", display_name);
json.writeStringField("description", description);
json.writeStringField("notes", notes);
json.writeNumberField("created", created);
if (custom == null) {
json.writeNullField("custom");
} else {
json.writeObjectFieldStart("custom");
for (Map.Entry<String, String> entry : custom.entrySet()) {
json.writeStringField(entry.getKey(), entry.getValue());
}
json.writeEndObject();
}
json.writeStringField("units", units);
json.writeStringField("dataType", data_type);
json.writeNumberField("retention", retention);
json.writeNumberField("max", max);
json.writeNumberField("min", min);
json.writeEndObject();
json.close();
return output.toByteArray();
} catch (IOException e) {
throw new RuntimeException("Unable to serialize TSMeta", e);
}
}
/**
* Asynchronously loads the UIDMeta objects into the given TSMeta object. Used
* by multiple methods so it's broken into it's own class here.
*/
private static class LoadUIDs implements Callback<Deferred<TSMeta>, TSMeta> {
final private TSDB tsdb;
final private String tsuid;
public LoadUIDs(final TSDB tsdb, final String tsuid) {
this.tsdb = tsdb;
this.tsuid = tsuid;
}
/**
* @return A TSMeta object loaded with UIDMetas if successful
* @throws HBaseException if there was a storage issue
* @throws JSONException if the data was corrupted
* @throws NoSuchUniqueName if one of the UIDMeta objects does not exist
*/
@Override
public Deferred<TSMeta> call(final TSMeta meta) throws Exception {
if (meta == null) {
return Deferred.fromResult(null);
}
// split up the tags
final List<byte[]> tags = UniqueId.getTagPairsFromTSUID(tsuid,
TSDB.metrics_width(), TSDB.tagk_width(), TSDB.tagv_width());
meta.tags = new ArrayList<UIDMeta>(tags.size());
// initialize with empty objects, otherwise the "set" operations in
// the callback won't work. Each UIDMeta will be given an index so that
// the callback can store it in the proper location
for (int i = 0; i < tags.size(); i++) {
meta.tags.add(new UIDMeta());
}
// list of fetch calls that we can wait on for completion
ArrayList<Deferred<Object>> uid_group =
new ArrayList<Deferred<Object>>(tags.size() + 1);
/**
* Callback for each getUIDMeta request that will place the resulting
* meta data in the proper location. The meta should always be either an
* actual stored value or a default. On creation, this callback will have
* an index to associate the UIDMeta with the proper location.
*/
final class UIDMetaCB implements Callback<Object, UIDMeta> {
final int index;
public UIDMetaCB(final int index) {
this.index = index;
}
/**
* @return null always since we don't care about the result, just that
* the callback has completed.
*/
@Override
public Object call(final UIDMeta uid_meta) throws Exception {
if (index < 0) {
meta.metric = uid_meta;
} else {
meta.tags.set(index, uid_meta);
}
return null;
}
}
// for the UIDMeta indexes: -1 means metric, >= 0 means tag. Each
// getUIDMeta request must be added to the uid_group array so that we
// can wait for them to complete before returning the TSMeta object,
// otherwise the caller may get a TSMeta with missing UIDMetas
uid_group.add(UIDMeta.getUIDMeta(tsdb, UniqueIdType.METRIC,
tsuid.substring(0, TSDB.metrics_width() * 2)).addCallback(
new UIDMetaCB(-1)));
int idx = 0;
for (byte[] tag : tags) {
if (idx % 2 == 0) {
uid_group.add(UIDMeta.getUIDMeta(tsdb, UniqueIdType.TAGK, tag)
.addCallback(new UIDMetaCB(idx)));
} else {
uid_group.add(UIDMeta.getUIDMeta(tsdb, UniqueIdType.TAGV, tag)
.addCallback(new UIDMetaCB(idx)));
}
idx++;
}
/**
* Super simple callback that is used to wait on the group of getUIDMeta
* deferreds so that we return only when all of the UIDMetas have been
* loaded.
*/
final class CollateCB implements Callback<Deferred<TSMeta>,
ArrayList<Object>> {
@Override
public Deferred<TSMeta> call(ArrayList<Object> uids) throws Exception {
return Deferred.fromResult(meta);
}
}
// start the callback chain by grouping and waiting on all of the UIDMeta
// deferreds
return Deferred.group(uid_group).addCallbackDeferring(new CollateCB());
}
}
/** @return the TSUID as a hex encoded string */
public final String getTSUID() {
return tsuid;
}
/** @return the metric UID meta object */
public final UIDMeta getMetric() {
return metric;
}
/** @return the tag UID meta objects in an array, tagk first, then tagv, etc */
public final ArrayList<UIDMeta> getTags() {
return tags;
}
/** @return optional display name */
public final String getDisplayName() {
return display_name;
}
/** @return optional description */
public final String getDescription() {
return description;
}
/** @return optional notes */
public final String getNotes() {
return notes;
}
/** @return when the TSUID was first recorded, Unix epoch */
public final long getCreated() {
return created;
}
/** @return optional custom key/value map, may be null */
public final HashMap<String, String> getCustom() {
return custom;
}
/** @return optional units */
public final String getUnits() {
return units;
}
/** @return optional data type */
public final String getDataType() {
return data_type;
}
/** @return optional retention, default of 0 means retain indefinitely */
public final int getRetention() {
return retention;
}
/** @return optional max value, set by the user */
public final double getMax() {
return max;
}
/** @return optional min value, set by the user */
public final double getMin() {
return min;
}
/** @return the last received timestamp, Unix epoch */
public final long getLastReceived() {
return last_received;
}
/** @return the total number of data points as tracked by the meta data */
public final long getTotalDatapoints() {
return this.total_dps;
}
/** @param display_name an optional name for the timeseries */
public final void setDisplayName(final String display_name) {
if (!this.display_name.equals(display_name)) {
changed.put("display_name", true);
this.display_name = display_name;
}
}
/** @param description an optional description */
public final void setDescription(final String description) {
if (!this.description.equals(description)) {
changed.put("description", true);
this.description = description;
}
}
/** @param notes optional notes */
public final void setNotes(final String notes) {
if (!this.notes.equals(notes)) {
changed.put("notes", true);
this.notes = notes;
}
}
/** @param created the created timestamp Unix epoch in seconds */
public final void setCreated(final long created) {
if (this.created != created) {
changed.put("created", true);
this.created = created;
}
}
/** @param custom optional key/value map */
public final void setCustom(final HashMap<String, String> custom) {
// equivalency of maps is a pain, users have to submit the whole map
// anyway so we'll just mark it as changed every time we have a non-null
// value
if (this.custom != null || custom != null) {
changed.put("custom", true);
this.custom = custom;
}
}
/** @param units optional units designation */
public final void setUnits(final String units) {
if (!this.units.equals(units)) {
changed.put("units", true);
this.units = units;
}
}
/** @param data_type optional type of data, e.g. "counter", "gauge" */
public final void setDataType(final String data_type) {
if (!this.data_type.equals(data_type)) {
changed.put("data_type", true);
this.data_type = data_type;
}
}
/** @param retention optional rentention in days, 0 = indefinite */
public final void setRetention(final int retention) {
if (this.retention != retention) {
changed.put("retention", true);
this.retention = retention;
}
}
/** @param max optional max value for the timeseries, NaN is the default */
public final void setMax(final double max) {
if (this.max != max) {
changed.put("max", true);
this.max = max;
}
}
/** @param min optional min value for the timeseries, NaN is the default */
public final void setMin(final double min) {
if (this.min != min) {
changed.put("min", true);
this.min = min;
}
}
}
|
public class Color {
private double K; // Kubelka-Munk absorption coefficient
private double S; // Kubelka-Munk scattering coefficient
private double R; // R = Reflectance = 1 + (K/S)-[(K/S)^2+2(K/S)]^0.5 (assuming color is opaque)
/**
* Returns the Color's Kubelka-Munk absorption coefficient
* @return
*/
public double getK(){
return K;
}
/**
* Return's the Color's Kubelka-Munk scattering coefficient
* @return
*/
public double getS(){
return S;
}
/**
* Returns the Color's Reflectance
* @return
*/
public double getReflectance(){
return R;
}
/**
* Creates a new Color
* @param K Kubelka-Munk absorption coefficient
* @param S Kubelka-Munk scattering coefficient
*/
public Color(double K, double S){
this.K = K;
this.S = S;
this.R = calculateReflectance(K, S);
}
/**
* Mixes a collection of colors into this color
* Calculates a new K and S coefficient using a weighted average of all K and S coefficients
* In this implementation we assume each color has an equal concentration so each concentration
* weight will be equal to 1/(1 + colors.size)
* @param colors
*/
public void mix(Color... colors){
// caculate a concentration weight for a equal concentration of all colors in mix
double concentration = 1 / (1 + colors.length);
// calculate first iteration
double K = this.K * concentration;
double S = this.S * concentration;
// sum the weighted average
for(int i=0; i<colors.length; i++){
K += colors[i].getK() * concentration;
S += colors[i].getS() * concentration;
}
// update with results
this.K = K;
this.S = S;
this.R = calculateReflectance(K, S);
}
/**
* Returns a Reflectance measure. Assumes the color is opaque.
* Reflectance = 1 + (K/S)-[(K/S)^2+2(K/S)]^0.5
* @param K Kubelka-Munk absorption coefficient
* @param S Kubelka-Munk scattering coefficient
* @return
*/
private double calculateReflectance(double K, double S){
return 1.0 + (K/S) - Math.pow(Math.pow((K/S), 2.0) + 2.0*(K/S), 0.5);
}
}
|
package com.bbn.bue.common;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
public final class OrderingUtils {
private OrderingUtils() {
throw new UnsupportedOperationException();
}
/**
* Gets a function which maps any iterable to its minimum according to the supplied {@link
* com.google.common.collect.Ordering}. If no such minimum exists for an input, it will throw an
* exception as specified in {@link Ordering#min(Iterable)}.
*/
public static <T> Function<Iterable<T>, T> minFunction(final Ordering<T> ordering) {
return new Function<Iterable<T>, T>() {
@Override
public T apply(Iterable<T> input) {
return ordering.min(input);
}
};
}
/**
* Gets a function which maps any iterable to its maximum according to the supplied {@link
* com.google.common.collect.Ordering}. If no such maximum exists for an input, it will throw an
* exception as specified in {@link Ordering#max(Iterable)}.
*/
public static <T> Function<Iterable<T>, T> maxFunction(final Ordering<T> ordering) {
return new Function<Iterable<T>, T>() {
@Override
public T apply(Iterable<T> input) {
return ordering.max(input);
}
};
}
/**
* Orders Ts in some domain by their image under F using the onFunctionResultOrdering
*/
public static <T,V> Ordering<T> onResultOf(final Function<T, V> F, final Ordering<V> onFunctionResult) {
return new Ordering<T>() {
@Override
public int compare(final T t, final T t1) {
return onFunctionResult.compare(F.apply(t), F.apply(t1));
}
};
}
}
|
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
public class MainWindow {
private JFrame frame;
private Toolkit toolkit;
private JMenuBar menuBar;
private JMenu mnFile;
private JMenu mnHelp;
private JMenuItem mntmOpen;
private JMenuItem mntmSave;
private JMenuItem mntmExit;
private JMenuItem mntmAboutTheAuthors;
private JMenuItem mntmAbout;
private JToolBar toolBar;
private JButton tbbtnOpen;
private JButton tbbtnSave;
private JButton tbbtnPrevious;
private JButton tbbtnNext;
private JButton tbbtnToEnd;
private JPanel panel;
private JPanel panelOriginal;
private JPanel panelExplanation;
private JPanel panelResult;
private JLabel lblOriginal;
private JTextArea textExplanation;
private JLabel lblResult;
private JButton btnPrevious;
private JButton btnNext;
private JButton btnToEnd;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
String osName = System.getProperty("os.name").toLowerCase();
int frameWidth = 0;
int frameHeight = 0;
int btnYPos = 0;
int btnHeight = 0;
if (osName.indexOf("mac") >= 0) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
frameWidth = 694;
frameHeight = 470;
btnYPos = 383;
btnHeight = 29;
} else if(osName.indexOf("windows") >= 0) {
frameWidth = 700;
frameHeight = 500;
btnYPos = 386;
btnHeight = 23;
}
final String separator = File.separator;
Image icon = null;
try {
icon = ImageIO.read(new File("resources" + separator + "icon.png"));
} catch (IOException e) {
e.printStackTrace();
}
frame = new JFrame("Cool Watermarks");
frame.setIconImage(icon);
toolkit = frame.getToolkit();
frame.setSize(frameWidth, frameHeight);
frame.setResizable(false);
Dimension screenDimension = toolkit.getScreenSize();
frame.setLocation((screenDimension.width - frame.getWidth())/2, (screenDimension.height - frame.getHeight())/2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
mnFile = new JMenu("File");
menuBar.add(mnFile);
mntmOpen = new JMenuItem("Open...");
mnFile.add(mntmOpen);
mntmSave = new JMenuItem("Save as...");
mnFile.add(mntmSave);
mnFile.addSeparator();
mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
mntmAboutTheAuthors = new JMenuItem("About the authors...");
mnHelp.add(mntmAboutTheAuthors);
mnHelp.addSeparator();
mntmAbout = new JMenuItem("About...");
mnHelp.add(mntmAbout);
toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setBorder(new MatteBorder(0, 0, 1, 0, (Color) new Color(120, 120, 120)));
frame.getContentPane().add(toolBar, BorderLayout.NORTH);
Icon iconOpen = new ImageIcon("resources" + separator +"open.png");
Icon iconSave = new ImageIcon("resources" + separator +"save.png");
Icon iconPrevious = new ImageIcon("resources" + separator +"previous.png");
Icon iconNext = new ImageIcon("resources" + separator +"next.png");
Icon iconToEnd = new ImageIcon("resources" + separator +"last.png");
tbbtnOpen = new JButton();
tbbtnOpen.setToolTipText("Open");
tbbtnOpen.setIcon(iconOpen);
toolBar.add(tbbtnOpen);
tbbtnSave = new JButton();
tbbtnSave.setToolTipText("Save");
tbbtnSave.setIcon(iconSave);
toolBar.add(tbbtnSave);
toolBar.addSeparator();
tbbtnPrevious = new JButton();
tbbtnPrevious.setToolTipText("Previous step");
tbbtnPrevious.setIcon(iconPrevious);
tbbtnPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setText("", textExplanation);
}
});
toolBar.add(tbbtnPrevious);
tbbtnNext = new JButton();
tbbtnNext.setToolTipText("Next step");
tbbtnNext.setIcon(iconNext);
tbbtnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteImage(lblResult);
}
});
toolBar.add(tbbtnNext);
tbbtnToEnd = new JButton();
tbbtnToEnd.setToolTipText("To end");
tbbtnToEnd.setIcon(iconToEnd);
tbbtnToEnd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteImage(lblOriginal);
}
});
toolBar.add(tbbtnToEnd);
panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
panelOriginal = new JPanel();
panelOriginal.setBounds(10, 9, 330, 204);
panelOriginal.setBorder(new TitledBorder(new LineBorder(new Color(150, 150, 150), 1, true), "Original", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelOriginal.setLayout(null);
panel.add(panelOriginal);
lblOriginal = new JLabel();
lblOriginal.setBounds(5, 15, 320, 184);
lblOriginal.setVerticalAlignment(JLabel.CENTER);
lblOriginal.setHorizontalAlignment(JLabel.CENTER);
panelOriginal.add(lblOriginal);
panelExplanation = new JPanel();
panelExplanation.setBounds(10, 224, 330, 151);
panelExplanation.setBorder(new TitledBorder(new LineBorder(new Color(150, 150, 150), 1, true), "Explanation of the next step", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelExplanation.setLayout(null);
panel.add(panelExplanation);
Color backgroundColor = toolBar.getBackground();
Font normalFont = lblOriginal.getFont();
textExplanation = new JTextArea();
textExplanation.setBounds(5, 15, 320, 131);
textExplanation.setWrapStyleWord(true);
textExplanation.setLineWrap(true);
textExplanation.setAutoscrolls(true);
textExplanation.setEditable(false);
textExplanation.setBorder(null);
textExplanation.setBackground(backgroundColor);
textExplanation.setFont(normalFont);
panelExplanation.add(textExplanation);
panelResult = new JPanel();
panelResult.setBounds(350, 9, 334, 400);
panelResult.setBorder(new TitledBorder(new LineBorder(new Color(150, 150, 150), 1, true), "Result", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelResult.setLayout(null);
panel.add(panelResult);
lblResult = new JLabel();
lblResult.setBounds(5, 15, 324, 380);
lblResult.setVerticalAlignment(JLabel.CENTER);
lblResult.setHorizontalAlignment(JLabel.CENTER);
panelResult.add(lblResult);
btnPrevious = new JButton("Previous");
btnPrevious.setBounds(10, btnYPos, 89, btnHeight);
btnPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setText("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie.", textExplanation);
}
});
panel.add(btnPrevious);
btnNext = new JButton("Next");
btnNext.setBounds(130, btnYPos, 89, btnHeight);
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setResultImage("testImages" + separator + "result.jpg");
}
});
panel.add(btnNext);
btnToEnd = new JButton("To end");
btnToEnd.setBounds(251, btnYPos, 89, btnHeight);
btnToEnd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setOriginalImage("testImages" + separator + "original.jpg");
}
});
panel.add(btnToEnd);
if (osName.indexOf("mac") >= 0) {
LineBorder tbbtnBorder = new LineBorder(backgroundColor, 4, true);
tbbtnOpen.setBackground(backgroundColor);
tbbtnOpen.setBorder(tbbtnBorder);
tbbtnSave.setBackground(backgroundColor);
tbbtnSave.setBorder(tbbtnBorder);
tbbtnPrevious.setBackground(backgroundColor);
tbbtnPrevious.setBorder(tbbtnBorder);
tbbtnNext.setBackground(backgroundColor);
tbbtnNext.setBorder(tbbtnBorder);
tbbtnToEnd.setBackground(backgroundColor);
tbbtnToEnd.setBorder(tbbtnBorder);
}
}
private void setImage(String imagePath, JLabel label) {
Image image = null;
try {
image = ImageIO.read(new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
}
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageAspect = (double) imageHeight / imageWidth;
int labelWidth = label.getWidth();
int labelHeight = label.getHeight();
int finalImageWidth = 0;
int finalImageHeight = 0;
boolean higherLabelWidth = false;
boolean higherLabelHeight = false;
if(imageWidth <= labelWidth) {
higherLabelWidth = true;
}
if(imageHeight <= labelHeight) {
higherLabelHeight = true;
}
if(!higherLabelHeight && !higherLabelWidth) {
int diffWidth = Math.abs(labelWidth - imageWidth);
int diffHeight = Math.abs(labelHeight - imageHeight);
if(diffHeight < diffWidth) {
finalImageWidth = labelWidth;
finalImageHeight = (int) (finalImageWidth * imageAspect);
} else {
finalImageHeight = labelHeight;
finalImageWidth = (int) (finalImageHeight / imageAspect);
}
} else if(!higherLabelHeight && higherLabelWidth) {
finalImageHeight = labelHeight;
finalImageWidth = (int) (finalImageHeight / imageAspect);
} else if(higherLabelHeight && !higherLabelWidth) {
finalImageWidth = labelWidth;
finalImageHeight = (int) (finalImageWidth * imageAspect);
} else if(higherLabelHeight && higherLabelWidth) {
finalImageWidth = imageWidth;
finalImageHeight = imageHeight;
}
image = image.getScaledInstance(finalImageWidth, finalImageHeight, Image.SCALE_DEFAULT);
label.setIcon(new ImageIcon(image));
}
private void deleteImage(JLabel label) {
label.setIcon(null);
}
private void setText(String text, JTextArea textArea ) {
textArea.setText(text);
}
public void setOriginalImage(String imagePath) {
setImage(imagePath, lblOriginal);
}
public void setResultImage(String imagePath) {
setImage(imagePath, lblResult);
}
public void setExplanationText(String text) {
setText(text, textExplanation);
}
public void deleteOriginalImage() {
deleteImage(lblOriginal);
}
public void deleteResultImage() {
deleteImage(lblResult);
}
}
|
package com.mbrlabs.mundus.commons.utils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import org.junit.Test;
import static org.junit.Assert.*;
public class MathUtilsTest {
@Test
public void barryCentric() throws Exception {
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 c = new Vector3(0.0f, 0.0f, 1.0f);
Vector2 pos = new Vector2(0.0f, 0.0f);
assertEquals(1.0f, MathUtils.barryCentric(a, b, c, pos), 0.0f);
}
@Test
public void dst() throws Exception {
assertEquals(1.0f, MathUtils.dst(1.0f, 1.0f, 2.0f, 1.0f), 0.0f);
}
@Test
public void angle() throws Exception {
assertEquals(45.0f, MathUtils.angle(0.0f,0.0f,1.0f,1.0f), 0.0f);
}
}
|
package org.beryl.intents.android;
import org.beryl.diagnostics.Logger;
import org.beryl.graphics.BitmapWrapper;
import org.beryl.intents.IActivityResultHandler;
import org.beryl.intents.IIntentBuilderForResult;
import org.beryl.intents.IntentHelper;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
public class Gallery {
private static final int NUM_INSTANCES = 4;
public static final BitmapWrapper loadBitmapFromUri(Context context, Uri fileUri) {
BitmapWrapper result = new BitmapWrapper(fileUri);
result.conservativeLoad(context, NUM_INSTANCES);
return result;
}
public static class GetImage implements IIntentBuilderForResult {
|
package edu.colorado.csdms.wmt.client.ui;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import edu.colorado.csdms.wmt.client.control.DataURL;
import edu.colorado.csdms.wmt.client.data.ParameterJSO;
import edu.colorado.csdms.wmt.client.ui.widgets.UploadDialogBox;
/**
* Used to display the value of a parameter in a {@link ParameterTable}, a
* ValueCell renders as a ListBox (droplist) if the parameter type = "choice" or
* "file"; otherwise, it renders as an editable TextBox. Changes to the value in
* a ValueCell are stored in the WMT DataManager.
*
* @author Mark Piper (mark.piper@colorado.edu)
*/
public class ValueCell extends HorizontalPanel {
private ParameterJSO parameter;
private UploadDialogBox upload;
private ListBox fileDroplist;
/**
* Makes a ValueCell from the information contained in the input
* {@link ParameterJSO} object.
*
* @param parameter a ParameterJSO object
*/
public ValueCell(ParameterJSO parameter) {
this.parameter = parameter;
this.setStyleName("wmt-ValueCell");
// If the parameter is a separator, short-circuit the method and return.
if (this.parameter.getKey().matches("separator")) {
return;
}
// Helpful locals.
String type = this.parameter.getValue().getType();
String value = this.parameter.getValue().getDefault();
String range = "";
// Make a cell to match the type -- choice, file or other.
// TODO Make classes for ChoiceCell, FileCell and TextCell.
if (type.matches("choice")) {
makeChoiceCell(value);
} else if (type.matches("file")) {
makeFileCell(value);
} else if (type.matches("int")) {
IntegerCell ibox = new IntegerCell(this);
this.add(ibox);
} else if (type.matches("float")) {
DoubleCell dbox = new DoubleCell(this);
this.add(dbox);
} else {
makeTextCell(value);
}
// If the parameter type is numeric, add a tooltip showing the valid range
// of its value.
if (isParameterTypeNumeric()) {
range +=
"Valid range: (" + parameter.getValue().getMin() + ", "
+ parameter.getValue().getMax() + ")";
this.setTitle(range);
}
}
public ParameterJSO getParameter() {
return parameter;
}
public void setParameter(ParameterJSO parameter) {
this.parameter = parameter;
}
/**
* A worker that makes the {@link ValueCell} display a droplist for the
* "choice" parameter type.
*
* @param value the value of the parameter, a String
*/
private void makeChoiceCell(String value) {
ListBox choiceDroplist = new ListBox(false); // no multi select
choiceDroplist.addChangeHandler(new ListSelectionHandler());
choiceDroplist.setStyleName("wmt-DroplistBox");
Integer nChoices = this.parameter.getValue().getChoices().length();
for (int i = 0; i < nChoices; i++) {
choiceDroplist.addItem(this.parameter.getValue().getChoices().get(i));
if (choiceDroplist.getItemText(i).matches(value)) {
choiceDroplist.setSelectedIndex(i);
}
}
choiceDroplist.setVisibleItemCount(1); // show one item -- a droplist
this.add(choiceDroplist);
}
/**
* A worker that makes the {@link ValueCell} display a droplist and a file
* upload button for the "file" parameter type.
*
* @param value the value of the parameter, a String
*/
private void makeFileCell(String value) {
fileDroplist = new ListBox(false); // no multi select
fileDroplist.addChangeHandler(new ListSelectionHandler());
fileDroplist.setStyleName("wmt-FileUploadBox");
// Load the droplist. If the value of the incoming parameter isn't listed
// in the component, append it to the end of the list and select it.
Integer nFiles = this.parameter.getValue().getFiles().length();
Integer selectedIndex = -1;
for (int i = 0; i < nFiles; i++) {
fileDroplist.addItem(this.parameter.getValue().getFiles().get(i));
if (fileDroplist.getItemText(i).matches(value)) {
selectedIndex = i;
}
}
if (selectedIndex > 0) {
fileDroplist.setSelectedIndex(selectedIndex);
} else {
fileDroplist.addItem(value);
fileDroplist.setSelectedIndex(fileDroplist.getItemCount() - 1);
}
fileDroplist.setVisibleItemCount(1); // show one item -- a droplist
this.add(fileDroplist);
Button uploadButton = new Button("<i class='fa fa-cloud-upload'></i>");
uploadButton.setStyleDependentName("slim", true);
uploadButton.addClickHandler(new UploadHandler());
uploadButton.setTitle("Upload file to server");
this.add(uploadButton);
this.setCellVerticalAlignment(fileDroplist, ALIGN_MIDDLE);
uploadButton.getElement().getStyle().setMarginLeft(3, Unit.PX);
}
/**
* A worker that makes the {@link ValueCell} display a text box. This is the
* default for the "string" parameter type.
*
* @param value the value of the parameter.
*/
private void makeTextCell(String value) {
TextBox valueTextBox = new TextBox();
valueTextBox.addKeyUpHandler(new TextEditHandler());
valueTextBox.setStyleName("wmt-TextBoxen");
valueTextBox.setWidth("200px");
valueTextBox.setText(value);
this.add(valueTextBox);
}
/**
* Passes the modified value up to
* {@link ParameterTable#setValue(ParameterJSO, String)}. This isn't an
* elegant solution, but ParameterTable knows the component this parameter
* belongs to and it has access to the DataManager object for storage.
*
* @param value the value read from the ValueCell
*/
public void setValue(String value) {
ParameterTable pt = (ParameterTable) ValueCell.this.getParent();
pt.setValue(parameter, value);
}
/**
* Checks whether the current {@link ValueCell} parameter uses a numeric type
* value (e.g., float or int). Returns a Boolean.
*/
private Boolean isParameterTypeNumeric() {
Boolean isNumeric = true;
String type = parameter.getValue().getType();
if (type.matches("string") || type.matches("choice")
|| type.matches("file")) {
isNumeric = false;
}
return isNumeric;
}
/**
* A class to handle selection in the "choices" ListBox.
*/
public class ListSelectionHandler implements ChangeHandler {
@Override
public void onChange(ChangeEvent event) {
GWT.log("(onChange)");
ListBox listBox = (ListBox) event.getSource();
String value = listBox.getValue(listBox.getSelectedIndex());
setValue(value);
}
}
/**
* A class to handle keyboard events in the TextBox.
* <p>
* Note that every key press generates an event. It might be worth considering
* acting on only Tab or Enter key presses.
*/
public class TextEditHandler implements KeyUpHandler {
@Override
public void onKeyUp(KeyUpEvent event) {
GWT.log("(onKeyUp:text)");
TextBox textBox = (TextBox) event.getSource();
String value = textBox.getText();
setValue(value);
}
}
/**
* Handles a click on the Upload button.
*/
public class UploadHandler implements ClickHandler {
@Override
public void onClick(ClickEvent event) {
ParameterTable pt = (ParameterTable) ValueCell.this.getParent();
if (!pt.data.modelIsSaved()) {
String msg =
"The model must be saved to the server"
+ " before files can be uploaded.";
Window.alert(msg);
return;
}
upload = new UploadDialogBox();
upload.setText("Upload File...");
// Get the id of the model this file belongs to.
String modelId = ((Integer) pt.data.getMetadata().getId()).toString();
upload.getHidden().setValue(modelId);
// Where the form is to be submitted.
upload.getForm().setAction(DataURL.uploadFile(pt.data));
upload.getForm().addSubmitCompleteHandler(new UploadCompleteHandler());
upload.center();
}
}
/**
* When the upload is complete and successful, add the name of the uploaded
* file to the {@link ValueCell} fileDroplist, select it, and save it as the
* value of this parameter.
*/
public class UploadCompleteHandler implements FormPanel.SubmitCompleteHandler {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
upload.hide();
if (event.getResults() != null) {
// Strip the fakepath from the filename.
String fileName =
upload.getUpload().getFilename().replace("C:\\fakepath\\", "");
// Add the filename to the fileDroplist, but only if it's not there
// already.
Integer listIndex = -1;
for (int i = 0; i < fileDroplist.getItemCount(); i++) {
if (fileDroplist.getItemText(i).matches(fileName)) {
listIndex = i;
}
}
if (listIndex > 0) {
fileDroplist.setSelectedIndex(listIndex);
} else {
fileDroplist.addItem(fileName);
fileDroplist.setSelectedIndex(fileDroplist.getItemCount() - 1);
}
// Like, important.
setValue(fileName);
// Say everything is alright.
Window.alert("File uploaded!");
// Mark the model as unsaved.
ParameterTable pt = (ParameterTable) ValueCell.this.getParent();
pt.data.modelIsSaved(false);
pt.data.getPerspective().setModelPanelTitle();
}
}
}
}
|
package water.api;
import hex.Model;
import hex.ModelBuilder;
import hex.ModelParametersBuilderFactory;
import hex.grid.Grid;
import hex.grid.GridSearch;
import hex.grid.HyperSpaceSearchCriteria;
import hex.schemas.GridSearchSchema;
import water.H2O;
import water.Job;
import water.Key;
import water.TypeMap;
import water.exceptions.H2OIllegalArgumentException;
import water.util.PojoUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* A generic grid search handler implementing launch of grid search.
*
* <p>A model specific grid search handlers should inherit from class and implements corresponding
* methods.
*
* FIXME: how to get rid of P, since it is already enforced by S
*
* @param <G> Implementation output of grid search
* @param <MP> Type of model parameters
* @param <P> Type of schema representing model parameters
* @param <S> Schema representing structure of grid search end-point
*/
public class GridSearchHandler<G extends Grid<MP>,
S extends GridSearchSchema<G, S, MP, P>,
MP extends Model.Parameters,
P extends ModelParametersSchema> extends Handler {
// Invoke the handler with parameters. Can throw any exception the called handler can throw.
// TODO: why does this do its own params filling?
// TODO: why does this do its own sub-dispatch?
@Override S handle(int version, water.api.Route route, Properties parms) throws Exception {
// Only here for train or validate-parms
if( !route._handler_method.getName().equals("train") )
throw water.H2O.unimpl();
// Peek out the desired algo from the URL
String ss[] = route._url_pattern_raw.split("/");
String algoURLName = ss[3]; // {}/{99}/{Grid}/{gbm}/
String algoName = ModelBuilder.algoName(algoURLName); // gbm -> GBM; deeplearning -> DeepLearning
String schemaDir = ModelBuilder.schemaDirectory(algoURLName);
// Get the latest version of this algo: /99/Grid/gbm ==> GBMV3
String algoSchemaName = Schema.schemaClass(version, algoName).getSimpleName(); // GBMV3
int algoVersion = Integer.valueOf(algoSchemaName.substring(algoSchemaName.lastIndexOf("V")+1));
// TODO: this is a horrible hack which is going to cause maintenance problems:
String paramSchemaName = schemaDir+algoName+"V"+algoVersion+"$"+ModelBuilder.paramName(algoURLName)+"V"+algoVersion;
// Build the Grid Search schema, and fill it from the parameters
S gss = (S) new GridSearchSchema();
gss.init_meta();
gss.parameters = (P)TypeMap.newFreezable(paramSchemaName);
gss.parameters.init_meta();
// Get default parameters, then overlay the passed-in values
ModelBuilder builder = ModelBuilder.make(algoURLName,null,null); // Default parameter settings
gss.parameters.fillFromImpl(builder._parms); // Defaults for this builder into schema
gss.fillFromParms(parms); // Override defaults from user parms
// Verify list of hyper parameters
// Right now only names, no types
validateHyperParams((P)gss.parameters, gss.hyper_parameters);
// Get actual parameters
MP params = (MP) gss.parameters.createAndFillImpl();
// Get/create a grid for given frame
// FIXME: Grid ID is not pass to grid search builder!
Key<Grid> destKey = gss.grid_id != null ? gss.grid_id.key() : null;
// Create target grid search object (keep it private for now)
// Start grid search and return the schema back with job key
Job<Grid> gsJob = GridSearch.startGridSearch(destKey,
params,
gss.hyper_parameters,
new DefaultModelParametersBuilderFactory<MP, P>(),
(HyperSpaceSearchCriteria)gss.search_criteria.createAndFillImpl());
// Fill schema with job parameters
// FIXME: right now we have to remove grid parameters which we sent back
gss.hyper_parameters = null;
gss.total_models = gsJob._result.get().getModelCount(); // TODO: looks like it's currently always 0
gss.job = (JobV3) Schema.schema(version, Job.class).fillFromImpl(gsJob);
return gss;
}
@SuppressWarnings("unused") // called through reflection by RequestServer
public S train(int version, S gridSearchSchema) { throw H2O.fail(); }
/**
* Validate given hyper parameters with respect to type parameter P.
*
* It verifies that given parameters are annotated in P with @API annotation
*
* @param params regular model build parameters
* @param hyperParams map of hyper parameters
*/
protected void validateHyperParams(P params, Map<String, Object[]> hyperParams) {
List<SchemaMetadata.FieldMetadata> fsMeta = SchemaMetadata.getFieldMetadata(params);
for (Map.Entry<String, Object[]> hparam : hyperParams.entrySet()) {
SchemaMetadata.FieldMetadata fieldMetadata = null;
// Found corresponding metadata about the field
for (SchemaMetadata.FieldMetadata fm : fsMeta) {
if (fm.name.equals(hparam.getKey())) {
fieldMetadata = fm;
break;
}
}
if (fieldMetadata == null) {
throw new H2OIllegalArgumentException(hparam.getKey(), "grid",
"Unknown hyper parameter for grid search!");
}
if (!fieldMetadata.is_gridable) {
throw new H2OIllegalArgumentException(hparam.getKey(), "grid",
"Illegal hyper parameter for grid search! The parameter '"
+ fieldMetadata.name + " is not gridable!");
}
}
}
static class DefaultModelParametersBuilderFactory<MP extends Model.Parameters, PS extends ModelParametersSchema>
implements ModelParametersBuilderFactory<MP> {
@Override
public ModelParametersBuilder<MP> get(MP initialParams) {
return new ModelParametersFromSchemaBuilder<MP, PS>(initialParams);
}
@Override
public PojoUtils.FieldNaming getFieldNamingStrategy() {
return PojoUtils.FieldNaming.DEST_HAS_UNDERSCORES;
}
}
/**
* Model parameters factory building model parameters with respect to its schema. <p> A user calls
* the {@link #set(String, Object)} method with names of parameters as they are defined in Schema.
* The builder transfer the given values from Schema to corresponding model parameters object.
* </p>
*
* @param <MP> type of model parameters
* @param <PS> type of schema representing model parameters
*/
public static class ModelParametersFromSchemaBuilder<MP extends Model.Parameters, PS extends ModelParametersSchema>
implements ModelParametersBuilderFactory.ModelParametersBuilder<MP> {
final private MP params;
final private PS paramsSchema;
final private ArrayList<String> fields;
public ModelParametersFromSchemaBuilder(MP initialParams) {
params = initialParams;
paramsSchema = (PS) Schema.schema(Schema.getHighestSupportedVersion(), params.getClass());
fields = new ArrayList<>(7);
}
public ModelParametersFromSchemaBuilder<MP, PS> set(String name, Object value) {
try {
Field f = paramsSchema.getClass().getField(name);
API api = (API) f.getAnnotations()[0];
Schema.setField(paramsSchema, f, name, value.toString(), api.required(),
paramsSchema.getClass());
fields.add(name);
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException("Cannot find field '" + name + "'" + " to value " + value, e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Cannot set field '" + name + "'" + " to value " + value, e);
} catch (RuntimeException e) {
throw new IllegalArgumentException("Cannot set field '" + name + "'" + " to value" + value, e);
}
return this;
}
public MP build() {
PojoUtils
.copyProperties(params, paramsSchema, PojoUtils.FieldNaming.DEST_HAS_UNDERSCORES, null,
fields.toArray(new String[fields.size()]));
// FIXME: handle these train/valid fields in different way
// See: ModelParametersSchema#fillImpl
if (params._valid == null && paramsSchema.validation_frame != null) {
params._valid = Key.make(paramsSchema.validation_frame.name);
}
if (params._train == null && paramsSchema.training_frame != null) {
params._train = Key.make(paramsSchema.training_frame.name);
}
return params;
}
}
}
|
package de.tud.ess;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ListView;
public class HeadListView extends ListView implements SensorEventListener {
private static final float INVALID_X = 10;
private Sensor mSensor;
private int mLastAccuracy;
private SensorManager mSensorManager;
private float mStartX = INVALID_X;
private static final int SENSOR_RATE_uS = 200000;
private static final float VELOCITY = (float) (Math.PI / 180 * 2);
public HeadListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public HeadListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public HeadListView(Context context) {
super(context);
init();
}
public void init() {
mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
public void activate() {
if (mSensor == null)
return;
mStartX = INVALID_X;
mSensorManager.registerListener(this, mSensor, SENSOR_RATE_uS);
}
public void deactivate() {
mSensorManager.unregisterListener(this);
mStartX = INVALID_X;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
mLastAccuracy = accuracy;
}
@Override
public void onSensorChanged(SensorEvent event) {
float[] mat = new float[9],
orientation = new float[3];
if (mLastAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
return;
SensorManager.getRotationMatrixFromVector(mat, event.values);
SensorManager.remapCoordinateSystem(mat, SensorManager.AXIS_X, SensorManager.AXIS_Z, mat);
SensorManager.getOrientation(mat, orientation);
float z = orientation[0],
x = orientation[1],
y = orientation[2];
if (mStartX == INVALID_X || mStartX > x)
mStartX = x;
int position = (int) ((mStartX - x) * -1/VELOCITY);
if (position >= 0)
setSelection(position);
}
}
|
package cc.topicexplorer.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.fest.util.Strings;
import com.google.common.base.Preconditions;
public final class PropertiesUtil {
private static final Logger logger = Logger.getLogger(PropertiesUtil.class);
private final Properties _hostProperties;
/**
*
* @param hostProperties
* must not be null.
*/
public PropertiesUtil(Properties hostProperties) {
_hostProperties = Preconditions.checkNotNull(hostProperties);
}
/**
* @return {@link Properties} object formerly filled by
* {@link #loadPropertyFile(String, String, PropertyKind)
* loadPropertyFile} method.
*/
public Properties getHostProperties() {
return _hostProperties;
}
/**
* Loads a property file from a resource and stores it into the
* {@code hostProperties}. If any property in the property file already
* exists in the {@code hostProperties} the latter will be overwritten.
*
* @param resource
* will be loaded into a temporary property object via
* {@link Properties#load()}. Properties will be used to update
* the {@code hostProperties}.
* @param prefix
* Every key of the {@code hostProperties} will be led by this
* prefix
* @param propertyKind
* {@code LOCAL} or {@code GLOBAL}. If {@code LOCAL} then a
* warning will be logged everytime there is no {@code GLOBAL}
* equivalent to a specific property.
* @return {@code false} if an error would occur while reading from the
* input stream and if no resource with the name, specified by the
* {@resource} parameter, is found. {@code true} otherwise.
*/
public boolean loadPropertyFile(String resource, String prefix, PropertyKind propertyKind) {
Preconditions.checkArgument(!Strings.isEmpty(resource));
Preconditions.checkNotNull(propertyKind);
InputStream propertyInput = PropertiesUtil.class.getResourceAsStream("/" + resource);
if (propertyInput != null) {
Properties temporaryProperties = new Properties();
try {
temporaryProperties.load(propertyInput);
} catch (IOException e) {
logger.warn("An error occured when reading from the input stream /" + resource, e);
return false;
}
@SuppressWarnings("unchecked")
List<String> propertyNames = (List<String>) Collections.list(temporaryProperties.propertyNames());
if (propertyKind.equals(PropertyKind.LOCAL)) {
for (String propertyName : propertyNames) {
if (!hasAttr(prefix + propertyName)) {
logger.warn("Global equivalent for " + prefix + propertyName + " not found in "
+ resource.replace("local", "global"));
}
}
}
for (String propertyName : propertyNames) {
_hostProperties.setProperty(prefix + propertyName, temporaryProperties.getProperty(propertyName));
}
} else {
logger.warn(resource + " not found");
return false;
}
return true;
}
public static enum PropertyKind {
LOCAL, GLOBAL
}
private boolean hasAttr(String attribute) {
Enumeration<?> eAll = _hostProperties.propertyNames();
while (eAll.hasMoreElements()) {
if (attribute.equals(eAll.nextElement())) {
return true;
}
}
return false;
}
}
|
package core.framework.http;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author neo
*/
class HTTPClientBuilderTest {
private HTTPClientBuilder builder;
@BeforeEach
void createHTTPClientBuilder() {
builder = HTTPClient.builder();
}
@Test
void callTimeout() {
builder.connectTimeout(Duration.ofSeconds(1));
builder.timeout(Duration.ofSeconds(2));
builder.retryWaitTime(Duration.ofMillis(500));
assertThat(builder.callTimeout()).isEqualTo(Duration.ofMillis(1000 + 2000 + 2000));
builder.maxRetries(1);
assertThat(builder.callTimeout()).isEqualTo(Duration.ofMillis(1000 + 2000 + 2000));
builder.maxRetries(2);
assertThat(builder.callTimeout()).isEqualTo(Duration.ofMillis(1000 + 2000 * 2 + 500 + 2000));
builder.maxRetries(3);
assertThat(builder.callTimeout()).isEqualTo(Duration.ofMillis(1000 + 2000 * 3 + 500 + 1000 + 2000));
}
@Test
void trust() {
builder.trust(CERT).trust(CERT).build();
}
@Test
void trustAll() {
builder.trustAll().build();
}
@Test
void clientAuth() {
builder.clientAuth(PRIVATE_KEY, CERT).build();
}
}
|
package com.cloud.storage.resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckHealthAnswer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.ComputeChecksumCommand;
import com.cloud.agent.api.DeleteObjectFromSwiftCommand;
import com.cloud.agent.api.DeleteSnapshotBackupCommand;
import com.cloud.agent.api.DeleteSnapshotsDirCommand;
import com.cloud.agent.api.GetStorageStatsAnswer;
import com.cloud.agent.api.GetStorageStatsCommand;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingStorageCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand;
import com.cloud.agent.api.SecStorageFirewallCfgCommand.PortConfig;
import com.cloud.agent.api.SecStorageSetupAnswer;
import com.cloud.agent.api.SecStorageSetupCommand;
import com.cloud.agent.api.SecStorageVMSetupCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupSecondaryStorageCommand;
import com.cloud.agent.api.downloadSnapshotFromSwiftCommand;
import com.cloud.agent.api.downloadTemplateFromSwiftToSecondaryStorageCommand;
import com.cloud.agent.api.uploadTemplateToSwiftFromSecondaryStorageCommand;
import com.cloud.agent.api.storage.CreateEntityDownloadURLCommand;
import com.cloud.agent.api.storage.DeleteEntityDownloadURLCommand;
import com.cloud.agent.api.storage.DeleteTemplateCommand;
import com.cloud.agent.api.storage.DownloadCommand;
import com.cloud.agent.api.storage.DownloadProgressCommand;
import com.cloud.agent.api.storage.ListTemplateAnswer;
import com.cloud.agent.api.storage.ListTemplateCommand;
import com.cloud.agent.api.storage.UploadCommand;
import com.cloud.agent.api.storage.ssCommand;
import com.cloud.agent.api.to.SwiftTO;
import com.cloud.exception.InternalErrorException;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.resource.ServerResourceBase;
import com.cloud.storage.StorageLayer;
import com.cloud.storage.template.DownloadManager;
import com.cloud.storage.template.DownloadManagerImpl;
import com.cloud.storage.template.DownloadManagerImpl.ZfsPathParser;
import com.cloud.storage.template.TemplateInfo;
import com.cloud.storage.template.TemplateLocation;
import com.cloud.storage.template.UploadManager;
import com.cloud.storage.template.UploadManagerImpl;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.OutputInterpreter;
import com.cloud.utils.script.Script;
import com.cloud.vm.SecondaryStorageVm;
public class NfsSecondaryStorageResource extends ServerResourceBase implements SecondaryStorageResource {
private static final Logger s_logger = Logger.getLogger(NfsSecondaryStorageResource.class);
int _timeout;
String _instance;
String _dc;
String _pod;
String _guid;
String _role;
Map<String, Object> _params;
StorageLayer _storage;
boolean _inSystemVM = false;
boolean _sslCopy = false;
DownloadManager _dlMgr;
UploadManager _upldMgr;
private String _configSslScr;
private String _configAuthScr;
private String _configIpFirewallScr;
private String _publicIp;
private String _hostname;
private String _localgw;
private String _eth1mask;
private String _eth1ip;
final private String _parent = "/mnt/SecStorage";
final private String _tmpltDir = "/var/cloudstack/template";
final private String _tmpltpp = "template.properties";
@Override
public void disconnected() {
}
@Override
public Answer executeRequest(Command cmd) {
if (cmd instanceof DownloadProgressCommand) {
return _dlMgr.handleDownloadCommand(this, (DownloadProgressCommand)cmd);
} else if (cmd instanceof DownloadCommand) {
return _dlMgr.handleDownloadCommand(this, (DownloadCommand)cmd);
} else if (cmd instanceof UploadCommand) {
return _upldMgr.handleUploadCommand(this, (UploadCommand)cmd);
} else if (cmd instanceof CreateEntityDownloadURLCommand){
return _upldMgr.handleCreateEntityURLCommand((CreateEntityDownloadURLCommand)cmd);
} else if(cmd instanceof DeleteEntityDownloadURLCommand){
return _upldMgr.handleDeleteEntityDownloadURLCommand((DeleteEntityDownloadURLCommand)cmd);
} else if (cmd instanceof GetStorageStatsCommand) {
return execute((GetStorageStatsCommand)cmd);
} else if (cmd instanceof CheckHealthCommand) {
return new CheckHealthAnswer((CheckHealthCommand)cmd, true);
} else if (cmd instanceof DeleteTemplateCommand) {
return execute((DeleteTemplateCommand) cmd);
} else if (cmd instanceof ReadyCommand) {
return new ReadyAnswer((ReadyCommand)cmd);
} else if (cmd instanceof SecStorageFirewallCfgCommand){
return execute((SecStorageFirewallCfgCommand)cmd);
} else if (cmd instanceof SecStorageVMSetupCommand){
return execute((SecStorageVMSetupCommand)cmd);
} else if (cmd instanceof SecStorageSetupCommand){
return execute((SecStorageSetupCommand)cmd);
} else if (cmd instanceof ComputeChecksumCommand){
return execute((ComputeChecksumCommand)cmd);
} else if (cmd instanceof ListTemplateCommand){
return execute((ListTemplateCommand)cmd);
} else if (cmd instanceof downloadSnapshotFromSwiftCommand){
return execute((downloadSnapshotFromSwiftCommand)cmd);
} else if (cmd instanceof DeleteSnapshotBackupCommand){
return execute((DeleteSnapshotBackupCommand)cmd);
} else if (cmd instanceof DeleteSnapshotsDirCommand){
return execute((DeleteSnapshotsDirCommand)cmd);
} else if (cmd instanceof downloadTemplateFromSwiftToSecondaryStorageCommand) {
return execute((downloadTemplateFromSwiftToSecondaryStorageCommand) cmd);
} else if (cmd instanceof uploadTemplateToSwiftFromSecondaryStorageCommand) {
return execute((uploadTemplateToSwiftFromSecondaryStorageCommand) cmd);
} else if (cmd instanceof DeleteObjectFromSwiftCommand) {
return execute((DeleteObjectFromSwiftCommand) cmd);
} else {
return Answer.createUnsupportedCommandAnswer(cmd);
}
}
private Answer execute(downloadTemplateFromSwiftToSecondaryStorageCommand cmd) {
SwiftTO swift = cmd.getSwift();
String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
Long accountId = cmd.getAccountId();
Long templateId = cmd.getTemplateId();
try {
String parent = getRootDir(secondaryStorageUrl);
String lPath = parent + "/template/tmpl/" + accountId.toString() + "/" + templateId.toString();
String result = swiftDownload(swift, "T-" + templateId.toString(), "", lPath);
if (result != null) {
String errMsg = "failed to download template from Swift to secondary storage " + lPath + " , err=" + result;
s_logger.warn(errMsg);
return new Answer(cmd, false, errMsg);
}
return new Answer(cmd, true, "success");
} catch (Exception e) {
String errMsg = cmd + " Command failed due to " + e.toString();
s_logger.warn(errMsg, e);
return new Answer(cmd, false, errMsg);
}
}
private Answer execute(uploadTemplateToSwiftFromSecondaryStorageCommand cmd) {
SwiftTO swift = cmd.getSwift();
String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
Long accountId = cmd.getAccountId();
Long templateId = cmd.getTemplateId();
try {
String parent = getRootDir(secondaryStorageUrl);
String lPath = parent + "/template/tmpl/" + accountId.toString() + "/" + templateId.toString();
if (!_storage.isFile(lPath + "/template.properties")) {
String errMsg = cmd + " Command failed due to template doesn't exist ";
s_logger.debug(errMsg);
return new Answer(cmd, false, errMsg);
}
String result = swiftUpload(swift, "T-" + templateId.toString(), lPath, "*");
if (result != null) {
String errMsg = "failed to upload template from secondary storage " + lPath + " to swift , err=" + result;
s_logger.debug(errMsg);
return new Answer(cmd, false, errMsg);
}
return new Answer(cmd, true, "success");
} catch (Exception e) {
String errMsg = cmd + " Command failed due to " + e.toString();
s_logger.warn(errMsg, e);
return new Answer(cmd, false, errMsg);
}
}
private Answer execute(DeleteObjectFromSwiftCommand cmd) {
SwiftTO swift = cmd.getSwift();
String container = cmd.getContainer();
String object = cmd.getObject();
if (object == null) {
object = "";
}
try {
String result = swiftDelete(swift, container, object);
if (result != null) {
String errMsg = "failed to delete object " + container + "/" + object + " , err=" + result;
s_logger.warn(errMsg);
return new Answer(cmd, false, errMsg);
}
return new Answer(cmd, true, "success");
} catch (Exception e) {
String errMsg = cmd + " Command failed due to " + e.toString();
s_logger.warn(errMsg, e);
return new Answer(cmd, false, errMsg);
}
}
String swiftDownload(SwiftTO swift, String container, String rfilename, String lFullPath) {
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("/usr/bin/python /usr/local/cloud/systemvm/scripts/storage/secondary/swift -A "
+ swift.getUrl() + " -U " + swift.getAccount() + ":" + swift.getUserName() + " -K " + swift.getKey()
+ " download " + container + " " + rfilename + " -o " + lFullPath);
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
if (result != null) {
String errMsg = "swiftDownload failed err=" + result;
s_logger.warn(errMsg);
return errMsg;
}
if (parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
for (String line : lines) {
if (line.contains("Errno") || line.contains("failed")) {
String errMsg = "swiftDownload failed , err=" + lines.toString();
s_logger.warn(errMsg);
return errMsg;
}
}
}
return null;
}
String swiftUpload(SwiftTO swift, String container, String lDir, String lFilename) {
Script command = new Script("/bin/bash", s_logger);
long SWIFT_MAX_SIZE = 5L * 1024L * 1024L * 1024L;
command.add("-c");
File file = new File(lDir + "/" + lFilename);
long size = file.length();
if (size <= SWIFT_MAX_SIZE) {
command.add("cd " + lDir + ";/usr/bin/python /usr/local/cloud/systemvm/scripts/storage/secondary/swift -A " + swift.getUrl() + " -U " + swift.getAccount() + ":" + swift.getUserName()
+ " -K " + swift.getKey() + " upload " + container + " " + lFilename);
} else {
command.add("cd " + lDir + ";/usr/bin/python /usr/local/cloud/systemvm/scripts/storage/secondary/swift -A " + swift.getUrl() + " -U " + swift.getAccount() + ":" + swift.getUserName()
+ " -K " + swift.getKey() + " upload -S " + SWIFT_MAX_SIZE + " " + container + " " + lFilename);
}
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
if (result != null) {
String errMsg = "swiftUpload failed , err=" + result;
s_logger.warn(errMsg);
return errMsg;
}
if (parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
for (String line : lines) {
if (line.contains("Errno") || line.contains("failed")) {
String errMsg = "swiftUpload failed , err=" + lines.toString();
s_logger.warn(errMsg);
return errMsg;
}
}
}
return null;
}
String[] swiftList(SwiftTO swift, String container, String rFilename) {
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("/usr/bin/python /usr/local/cloud/systemvm/scripts/storage/secondary/swift -A " + swift.getUrl() + " -U " + swift.getAccount() + ":" + swift.getUserName() + " -K "
+ swift.getKey() + " list " + container + " " + rFilename);
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
if (result == null && parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
return lines;
} else {
if (result != null) {
String errMsg = "swiftList failed , err=" + result;
s_logger.warn(errMsg);
} else {
String errMsg = "swiftList failed, no lines returns";
s_logger.warn(errMsg);
}
}
return null;
}
String swiftDelete(SwiftTO swift, String container, String object) {
Script command = new Script("/bin/bash", s_logger);
command.add("-c");
command.add("/usr/bin/python /usr/local/cloud/systemvm/scripts/storage/secondary/swift -A "
+ swift.getUrl() + " -U " + swift.getAccount() + ":" + swift.getUserName() + " -K " + swift.getKey()
+ " delete " + container + " " + object);
OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser();
String result = command.execute(parser);
if (result != null) {
String errMsg = "swiftDelete failed , err=" + result;
s_logger.warn(errMsg);
return errMsg;
}
if (parser.getLines() != null) {
String[] lines = parser.getLines().split("\\n");
for (String line : lines) {
if (line.contains("Errno") || line.contains("failed")) {
String errMsg = "swiftDelete failed , err=" + lines.toString();
s_logger.warn(errMsg);
return errMsg;
}
}
}
return null;
}
public Answer execute(DeleteSnapshotsDirCommand cmd){
String secondaryStorageUrl = cmd.getSecondaryStorageUrl();
Long accountId = cmd.getAccountId();
Long volumeId = cmd.getVolumeId();
try {
String parent = getRootDir(secondaryStorageUrl);
|
package org.mwdb.chunk.offheap;
import org.mwdb.Constants;
import org.mwdb.chunk.KChunkListener;
import org.mwdb.chunk.KLongLongArrayMap;
import org.mwdb.chunk.KLongLongArrayMapCallBack;
import org.mwdb.utility.PrimitiveHelper;
import org.mwdb.utility.Unsafe;
/**
* @ignore ts
*/
public class ArrayLongLongArrayMap implements KLongLongArrayMap {
private static final sun.misc.Unsafe unsafe = Unsafe.getUnsafe();
private final KChunkListener listener;
private final long root_array_ptr;
//LongArrays
private static final int INDEX_ELEMENT_V = 0;
private static final int INDEX_ELEMENT_NEXT = 1;
private static final int INDEX_ELEMENT_HASH = 2;
private static final int INDEX_ELEMENT_K = 3;
//Long values
private static final int INDEX_ELEMENT_LOCK = 4;
private static final int INDEX_THRESHOLD = 5;
private static final int INDEX_ELEMENT_COUNT = 6;
private static final int INDEX_CAPACITY = 7;
//long[]
private long elementK_ptr;
private long elementV_ptr;
private long elementNext_ptr;
private long elementHash_ptr;
public ArrayLongLongArrayMap(KChunkListener listener, long initialCapacity, long previousAddr) {
this.listener = listener;
if (previousAddr == Constants.OFFHEAP_NULL_PTR) {
this.root_array_ptr = OffHeapLongArray.allocate(9);
/** Init long variables */
//init lock
OffHeapLongArray.set(this.root_array_ptr, INDEX_ELEMENT_LOCK, 0);
//init capacity
OffHeapLongArray.set(this.root_array_ptr, INDEX_CAPACITY, initialCapacity);
//init threshold
OffHeapLongArray.set(this.root_array_ptr, INDEX_THRESHOLD, (long) (initialCapacity * Constants.MAP_LOAD_FACTOR));
//init elementCount
OffHeapLongArray.set(this.root_array_ptr, INDEX_ELEMENT_COUNT, 0);
/** Init Long[] variables */
//init elementK
elementK_ptr = OffHeapLongArray.allocate(initialCapacity);
OffHeapLongArray.set(this.root_array_ptr, INDEX_ELEMENT_K, elementK_ptr);
//init elementV
elementV_ptr = OffHeapLongArray.allocate(initialCapacity);
OffHeapLongArray.set(this.root_array_ptr, INDEX_ELEMENT_V, elementV_ptr);
//init elementNext
elementNext_ptr = OffHeapLongArray.allocate(initialCapacity);
OffHeapLongArray.set(this.root_array_ptr, INDEX_ELEMENT_NEXT, elementNext_ptr);
//init elementHash
elementHash_ptr = OffHeapLongArray.allocate(initialCapacity);
OffHeapLongArray.set(this.root_array_ptr, INDEX_ELEMENT_HASH, elementHash_ptr);
} else {
this.root_array_ptr = previousAddr;
elementK_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_K);
elementV_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_V);
elementHash_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_HASH);
elementNext_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_NEXT);
}
}
private final void consistencyCheck() {
if (OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_V) != elementV_ptr) {
elementK_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_K);
elementV_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_V);
elementHash_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_HASH);
elementNext_ptr = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_NEXT);
}
}
@Override
public final long[] get(long key) {
//LOCK
while (!OffHeapLongArray.compareAndSwap(root_array_ptr, INDEX_ELEMENT_LOCK, 0, 1)) ;
consistencyCheck();
long hashIndex = PrimitiveHelper.longHash(key, OffHeapLongArray.get(this.root_array_ptr, INDEX_CAPACITY));
long[] result = null;
int capacity = 0;
int resultIndex = 0;
long m = OffHeapLongArray.get(elementHash_ptr, hashIndex);
while (m != -1) {
if (key == OffHeapLongArray.get(elementK_ptr, m)) {
if (resultIndex == capacity) {
if (capacity == 0) {
result = new long[1];
capacity = 1;
} else {
long[] temp_result = new long[capacity * 2];
System.arraycopy(result, 0, temp_result, 0, capacity);
capacity = capacity * 2;
result = temp_result;
}
result[resultIndex] = OffHeapLongArray.get(elementV_ptr, m);
resultIndex++;
} else {
result[resultIndex] = OffHeapLongArray.get(elementV_ptr, m);
resultIndex++;
}
}
m = OffHeapLongArray.get(elementNext_ptr, m);
}
//UNLOCK
if (!OffHeapLongArray.compareAndSwap(root_array_ptr, INDEX_ELEMENT_LOCK, 1, 0)) {
throw new RuntimeException("CAS error !!!");
}
if (resultIndex == 0) {
return new long[0];
} else {
return result;
}
}
@Override
public void each(KLongLongArrayMapCallBack callback) {
//LOCK
while (!OffHeapLongArray.compareAndSwap(root_array_ptr, INDEX_ELEMENT_LOCK, 0, 1)) ;
consistencyCheck();
long elementCount = OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_COUNT);
for (long i = 0; i < elementCount; i++) {
long loopValue = OffHeapLongArray.get(elementV_ptr, i);
if (loopValue != Constants.NULL_LONG) {
callback.on(OffHeapLongArray.get(elementK_ptr, i), loopValue);
}
}
//UNLOCK
if (!OffHeapLongArray.compareAndSwap(root_array_ptr, INDEX_ELEMENT_LOCK, 1, 0)) {
throw new RuntimeException("CAS error !!!");
}
}
@Override
public long size() {
return OffHeapLongArray.get(this.root_array_ptr, INDEX_ELEMENT_COUNT);
}
@Override
public void remove(long key, long value) {
throw new RuntimeException("Not implemented yet!!!");
}
public static void free(long addr) {
//free all long[]
OffHeapLongArray.free(OffHeapLongArray.get(addr, INDEX_ELEMENT_K));
OffHeapLongArray.free(OffHeapLongArray.get(addr, INDEX_ELEMENT_V));
OffHeapLongArray.free(OffHeapLongArray.get(addr, INDEX_ELEMENT_NEXT));
OffHeapLongArray.free(OffHeapLongArray.get(addr, INDEX_ELEMENT_HASH));
//free master array
OffHeapLongArray.free(addr);
}
@Override
public final void put(long key, long value) {
//cas to put a lock flag
while (!OffHeapLongArray.compareAndSwap(root_array_ptr, INDEX_ELEMENT_LOCK, 0, 1)) ;
consistencyCheck();
long entry = -1;
long capacity = OffHeapLongArray.get(root_array_ptr, INDEX_CAPACITY);
long elementCount = OffHeapLongArray.get(root_array_ptr, INDEX_ELEMENT_COUNT);
long hashIndex = PrimitiveHelper.longHash(key, capacity);
long m = OffHeapLongArray.get(elementHash_ptr, hashIndex);
while (m != Constants.OFFHEAP_NULL_PTR) {
if (key == OffHeapLongArray.get(elementK_ptr, m) && value == OffHeapLongArray.get(elementV_ptr, m)) {
entry = m;
break;
}
m = OffHeapLongArray.get(elementNext_ptr, m);
}
if (entry == -1) {
//if need to reHash (too small or too much collisions)
if ((elementCount + 1) > OffHeapLongArray.get(root_array_ptr, INDEX_THRESHOLD)) {
long newCapacity = capacity << 1;
//reallocate the string[], indexes are not changed
elementK_ptr = OffHeapStringArray.reallocate(elementK_ptr, capacity, newCapacity);
OffHeapLongArray.set(root_array_ptr, INDEX_ELEMENT_K, elementK_ptr);
//reallocate the long[] values
elementV_ptr = OffHeapLongArray.reallocate(elementV_ptr, capacity, newCapacity);
OffHeapLongArray.set(root_array_ptr, INDEX_ELEMENT_V, elementV_ptr);
//Create two new Hash and Next structures
OffHeapLongArray.free(elementHash_ptr);
OffHeapLongArray.free(elementNext_ptr);
elementHash_ptr = OffHeapLongArray.allocate(newCapacity);
OffHeapLongArray.set(root_array_ptr, INDEX_ELEMENT_HASH, elementHash_ptr);
elementNext_ptr = OffHeapLongArray.allocate(newCapacity);
OffHeapLongArray.set(root_array_ptr, INDEX_ELEMENT_NEXT, elementNext_ptr);
//rehashEveryThing
for (long i = 0; i < elementCount; i++) {
long previousValue = OffHeapLongArray.get(elementV_ptr, i);
long previousKey = OffHeapLongArray.get(elementK_ptr, i);
if (previousValue != Constants.NULL_LONG) {
long newHashIndex = PrimitiveHelper.longHash(previousKey, newCapacity);
long currentHashedIndex = OffHeapLongArray.get(elementHash_ptr, newHashIndex);
if (currentHashedIndex != Constants.OFFHEAP_NULL_PTR) {
OffHeapLongArray.set(elementNext_ptr, i, currentHashedIndex);
}
OffHeapLongArray.set(elementHash_ptr, newHashIndex, i);
}
}
capacity = newCapacity;
OffHeapLongArray.set(root_array_ptr, INDEX_CAPACITY, capacity);
OffHeapLongArray.set(root_array_ptr, INDEX_THRESHOLD, (long) (newCapacity * Constants.MAP_LOAD_FACTOR));
hashIndex = PrimitiveHelper.longHash(key, capacity);
}
//set K
OffHeapLongArray.set(elementK_ptr, elementCount, key);
//set value or index if null
if (value == Constants.NULL_LONG) {
OffHeapLongArray.set(elementV_ptr, elementCount, elementCount);
} else {
OffHeapLongArray.set(elementV_ptr, elementCount, value);
}
long currentHashedElemIndex = OffHeapLongArray.get(elementHash_ptr, hashIndex);
if (currentHashedElemIndex != -1) {
OffHeapLongArray.set(elementNext_ptr, elementCount, currentHashedElemIndex);
}
//now the object is reachable to other thread everything should be ready
OffHeapLongArray.set(elementHash_ptr, hashIndex, elementCount);
//increase element count
OffHeapLongArray.set(root_array_ptr, INDEX_ELEMENT_COUNT, elementCount + 1);
//inform the listener
this.listener.declareDirty(null);
} else {
if (OffHeapLongArray.get(elementV_ptr, entry) != value && value != Constants.NULL_LONG) {
//setValue
OffHeapLongArray.set(elementV_ptr, entry, value);
this.listener.declareDirty(null);
}
}
if (!OffHeapLongArray.compareAndSwap(root_array_ptr, INDEX_ELEMENT_LOCK, 1, 0)) {
throw new RuntimeException("CAS error !!!");
}
}
public long rootAddress() {
return root_array_ptr;
}
public static long cloneMap(long srcAddr) {
// capacity
long capacity = OffHeapLongArray.get(srcAddr, INDEX_CAPACITY);
// clone root array
long newSrcAddr = OffHeapLongArray.cloneArray(srcAddr, capacity);
// copy elementK array
long elementK_ptr = OffHeapLongArray.get(srcAddr, INDEX_ELEMENT_K);
long newElementK_ptr = OffHeapLongArray.cloneArray(elementK_ptr, capacity);
OffHeapLongArray.set(newSrcAddr, INDEX_ELEMENT_V, newElementK_ptr);
// copy elementV array
long elementV_ptr = OffHeapLongArray.get(srcAddr, INDEX_ELEMENT_V);
long newElementV_ptr = OffHeapLongArray.cloneArray(elementV_ptr, capacity);
OffHeapLongArray.set(newSrcAddr, INDEX_ELEMENT_V, newElementV_ptr);
// copy elementNext array
long elementNext_ptr = OffHeapLongArray.get(srcAddr, INDEX_ELEMENT_NEXT);
long newElementNext_ptr = OffHeapLongArray.cloneArray(elementNext_ptr, capacity);
OffHeapLongArray.set(newSrcAddr, INDEX_ELEMENT_NEXT, newElementNext_ptr);
// copy elementHash array
long elementHash_ptr = OffHeapLongArray.get(srcAddr, INDEX_ELEMENT_HASH);
long newElementHash_ptr = OffHeapLongArray.cloneArray(elementHash_ptr, capacity);
OffHeapLongArray.set(newSrcAddr, INDEX_ELEMENT_HASH, newElementHash_ptr);
return newSrcAddr;
}
}
|
package org.tigris.subversion.subclipse.core;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.team.core.TeamException;
import org.osgi.framework.BundleContext;
import org.tigris.subversion.subclipse.core.client.IConsoleListener;
import org.tigris.subversion.subclipse.core.repo.SVNRepositories;
import org.tigris.subversion.subclipse.core.resources.ISVNFileModificationValidatorPrompt;
import org.tigris.subversion.subclipse.core.resources.RepositoryResourcesManager;
import org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager;
import org.tigris.subversion.subclipse.core.resourcesListeners.SyncFileChangeListener;
import org.tigris.subversion.subclipse.core.status.StatusCacheManager;
import org.tigris.subversion.subclipse.core.util.ISimpleDialogsHelper;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.ISVNPromptUserPassword;
/**
* The plugin itself
*/
public class SVNProviderPlugin extends Plugin {
// svn plugin id
public static final String ID = "org.tigris.subversion.subclipse.core"; //$NON-NLS-1$
public static final String PROVIDER_ID="org.tigris.subversion.subclipse.core.svnnature"; //$NON-NLS-1$
public static final String SVN_PROPERTY_TYPES_EXTENSION = "svnPropertyTypes";
public static final String SVN_PROPERTY_GROUPS_EXTENSION = "svnPropertyGroups";
// all projects shared with subversion will have this nature
private static final String NATURE_ID = ID + ".svnnature"; //$NON-NLS-1$
// the plugin instance. @see getPlugin()
private static volatile SVNProviderPlugin instance;
// the console listener
private IConsoleListener consoleListener;
// SVN specific resource delta listeners
private FileModificationManager fileModificationManager;
private SyncFileChangeListener metaFileSyncListener;
// the list of all repositories currently handled by this provider
private SVNRepositories repositories;
private StatusCacheManager statusCacheManager;
private RepositoryResourcesManager repositoryResourcesManager = new RepositoryResourcesManager();
private SVNClientManager svnClientManager;
private SVNAdapterFactories adapterFactories;
private ISVNPromptUserPassword svnPromptUserPassword;
private ISimpleDialogsHelper simpleDialogsHelper;
private ISVNFileModificationValidatorPrompt svnFileModificationValidatorPrompt;
private String dirname;
/**
* This constructor required by the bundle loader (calls newInstance())
*
*/
public SVNProviderPlugin() {
super();
instance = this;
}
/**
* Log the given exception along with the provided message and severity indicator
*/
public static void log(int severity, String message, Throwable e) {
log(new Status(severity, ID, 0, message, e));
}
/**
* Convenience method for logging SVNExceptions to the plugin log
*/
public static void log(TeamException e) {
// For now, we'll log the status. However we should do more
log(e.getStatus());
}
public static void log(IStatus status) {
// For now, we'll log the status. However we should do more
getPlugin().getLog().log(status);
}
/**
* Returns the singleton plug-in instance.
*
* @return the plugin instance
*/
public static SVNProviderPlugin getPlugin() {
return instance;
}
public void start(BundleContext ctxt) throws Exception {
super.start(ctxt);
// register all the adapter factories
adapterFactories = new SVNAdapterFactories();
adapterFactories.startup(null);
statusCacheManager = new StatusCacheManager();
getPluginPreferences().addPropertyChangeListener(statusCacheManager);
// Initialize SVN change listeners. Note tha the report type is important.
IWorkspace workspace = ResourcesPlugin.getWorkspace();
// this listener will listen to modifications to files
fileModificationManager = new FileModificationManager();
// this listener will listen to modification to metafiles (files in .svn
// subdir)
metaFileSyncListener = new SyncFileChangeListener();
workspace.addResourceChangeListener(statusCacheManager,
IResourceChangeEvent.PRE_BUILD);
workspace.addResourceChangeListener(metaFileSyncListener,
IResourceChangeEvent.PRE_BUILD);
workspace.addResourceChangeListener(fileModificationManager,
IResourceChangeEvent.POST_CHANGE);
fileModificationManager.registerSaveParticipant();
}
/**
* @see Plugin#stop(BundleContext ctxt)
*/
public void stop(BundleContext ctxt) throws Exception {
super.stop(ctxt);
// remove listeners
IWorkspace workspace = ResourcesPlugin.getWorkspace();
workspace.removeResourceChangeListener(statusCacheManager);
workspace.removeResourceChangeListener(metaFileSyncListener);
workspace.removeResourceChangeListener(fileModificationManager);
// save the state which includes the known repositories
if (repositories != null) {
repositories.shutdown();
}
adapterFactories.shutdown(null);
getPluginPreferences().removePropertyChangeListener(statusCacheManager);
// save the plugin preferences
savePluginPreferences();
// remove all of this plugin's save participants. This is easier than
// having
// each class that added itself as a participant to have to listen to
// shutdown.
workspace.removeSaveParticipant(this);
svnClientManager.shutdown(null);
}
private static List listeners = new ArrayList();
/*
* @see ITeamManager#addResourceStateChangeListener(IResourceStateChangeListener)
*/
public static void addResourceStateChangeListener(
IResourceStateChangeListener listener) {
listeners.add(listener);
}
/*
* @see ITeamManager#removeResourceStateChangeListener(IResourceStateChangeListener)
*/
public static void removeResourceStateChangeListener(
IResourceStateChangeListener listener) {
listeners.remove(listener);
}
/**
* This method is called by SyncFileChangeListener when metafiles have
* changed
*/
public static void broadcastSyncInfoChanges(final IResource[] resources) {
for (Iterator it = listeners.iterator(); it.hasNext();) {
final IResourceStateChangeListener listener = (IResourceStateChangeListener) it
.next();
ISafeRunnable code = new ISafeRunnable() {
public void run() throws Exception {
listener.resourceSyncInfoChanged(resources);
}
public void handleException(Throwable e) {
// don't log the exception....it is already being logged in
// Platform#run
}
};
Platform.run(code);
}
}
// public static void broadcastDecoratorEnablementChanged(final boolean
// enabled) {
// for(Iterator it=decoratorEnablementListeners.iterator(); it.hasNext();) {
// final ICVSDecoratorEnablementListener listener =
// (ICVSDecoratorEnablementListener)it.next();
// ISafeRunnable code = new ISafeRunnable() {
// public void run() throws Exception {
// listener.decoratorEnablementChanged(enabled);
// public void handleException(Throwable e) {
// // don't log the exception....it is already being logged in Platform#run
// Platform.run(code);
/**
* This method is called by FileModificationManager when some resources have
* changed
*/
public static void broadcastModificationStateChanges(
final IResource[] resources) {
for (Iterator it = listeners.iterator(); it.hasNext();) {
final IResourceStateChangeListener listener = (IResourceStateChangeListener) it
.next();
ISafeRunnable code = new ISafeRunnable() {
public void run() throws Exception {
listener.resourceModified(resources);
}
public void handleException(Throwable e) {
// don't log the exception....it is already being logged in
// Platform#run
}
};
Platform.run(code);
}
}
/**
* This method is called by SVNTeamProvider.configureProject which is
* invoked when a project is mapped
*/
protected static void broadcastProjectConfigured(final IProject project) {
for (Iterator it = listeners.iterator(); it.hasNext();) {
final IResourceStateChangeListener listener = (IResourceStateChangeListener) it
.next();
ISafeRunnable code = new ISafeRunnable() {
public void run() throws Exception {
listener.projectConfigured(project);
}
public void handleException(Throwable e) {
// don't log the exception....it is already being logged in
// Platform#run
}
};
Platform.run(code);
}
}
/**
* This method is called by SVNTeamProvider.deconfigured which is invoked
* after a provider has been unmaped
*/
protected static void broadcastProjectDeconfigured(final IProject project) {
for (Iterator it = listeners.iterator(); it.hasNext();) {
final IResourceStateChangeListener listener = (IResourceStateChangeListener) it
.next();
ISafeRunnable code = new ISafeRunnable() {
public void run() throws Exception {
listener.projectDeconfigured(project);
}
public void handleException(Throwable e) {
// don't log the exception....it is already being logged in
// Platform#run
}
};
Platform.run(code);
}
}
/**
* Register to receive notification of enablement of sync info decoration
* requirements. This can be useful for providing lazy initialization of
* caches that are only required for decorating resource with CVS
* information.
*/
/*
* public void
* addDecoratorEnablementListener(ISVNDecoratorEnablementListener listener) {
* decoratorEnablementListeners.add(listener); }
*/
/**
* De-register the decorator enablement listener.
*/
/*
* public void
* removeDecoratorEnablementListener(ICVSDecoratorEnablementListener
* listener) { decoratorEnablementListeners.remove(listener); }
*/
/**
* get the repository corresponding to the location location is an url
*/
public ISVNRepositoryLocation getRepository(String location)
throws SVNException {
return getRepositories().getRepository(location);
}
/**
* get all the known repositories
*/
public SVNRepositories getRepositories() {
if (repositories == null) {
// load the state which includes the known repositories
repositories = new SVNRepositories();
repositories.startup();
}
return repositories;
}
/**
* get the resource status cache
*/
public StatusCacheManager getStatusCacheManager() {
return statusCacheManager;
}
public SVNClientManager getSVNClientManager() {
if (svnClientManager == null) {
svnClientManager = new SVNClientManager();
try {
svnClientManager.startup(null);
} catch (CoreException e) {
}
}
return svnClientManager;
}
public ISVNClientAdapter createSVNClient() throws SVNException {
return getSVNClientManager().createSVNClient();
}
/**
* Set the console listener for commands.
*
* @param consoleListener
* the listener
*/
public void setConsoleListener(IConsoleListener consoleListener) {
this.consoleListener = consoleListener;
}
/**
* Get the console listener for commands.
*
* @return the consoleListener, or null
*/
public IConsoleListener getConsoleListener() {
return consoleListener;
}
/**
* Answers the repository provider type id for the svn plugin
*/
public static String getTypeId() {
return NATURE_ID;
}
/**
* Same as IWorkspace.run but uses a ISVNRunnable
*/
public static void run(final ISVNRunnable job, IProgressMonitor monitor)
throws SVNException {
final SVNException[] error = new SVNException[1];
try {
ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
try {
monitor = Policy.monitorFor(monitor);
try {
job.run(monitor);
} finally {
monitor.done();
}
} catch (SVNException e) {
error[0] = e;
}
}
}, monitor);
} catch (CoreException e) {
throw SVNException.wrapException(e);
}
if (error[0] != null) {
throw error[0];
}
}
/**
* Same as IWorkspace.run but uses a ISVNRunnable
*/
public static void run(final ISVNRunnable job, ISchedulingRule rule, IProgressMonitor monitor)
throws SVNException {
final SVNException[] error = new SVNException[1];
try {
ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
try {
monitor = Policy.monitorFor(monitor);
try {
job.run(monitor);
} finally {
monitor.done();
}
} catch (SVNException e) {
error[0] = e;
}
}
}, rule, IWorkspace.AVOID_UPDATE, monitor);
} catch (CoreException e) {
throw SVNException.wrapException(e);
}
if (error[0] != null) {
throw error[0];
}
}
/**
* @return the repository resources Manager
*/
public RepositoryResourcesManager getRepositoryResourcesManager() {
return repositoryResourcesManager;
}
public ISVNPromptUserPassword getSvnPromptUserPassword() {
return svnPromptUserPassword;
}
public void setSvnPromptUserPassword(
ISVNPromptUserPassword svnPromptUserPassword) {
this.svnPromptUserPassword = svnPromptUserPassword;
}
public ISimpleDialogsHelper getSimpleDialogsHelper() {
return simpleDialogsHelper;
}
public void setSimpleDialogsHelper(ISimpleDialogsHelper simpleDialogsHelper) {
this.simpleDialogsHelper = simpleDialogsHelper;
}
public ISVNFileModificationValidatorPrompt getSvnFileModificationValidatorPrompt() {
return svnFileModificationValidatorPrompt;
}
public void setSvnFileModificationValidatorPrompt(
ISVNFileModificationValidatorPrompt svnFileModificationValidatorPrompt) {
this.svnFileModificationValidatorPrompt = svnFileModificationValidatorPrompt;
}
public String getAdminDirectoryName() {
if (dirname == null) {
try {
dirname = createSVNClient().getAdminDirectoryName();
} catch (SVNException e) {
dirname = ".svn";
}
}
return dirname;
}
public boolean isAdminDirectory(String name) {
if (".svn".equals(name) || getAdminDirectoryName().equals(name))
return true;
else
return false;
// Calling the adapter method here potentially lead to a thread problem
// that would make native JavaHL crash. So I am recreating the logic
// internally. This method is likely to be a lot faster so it is worth it.
// try {
// return createSVNClient().isAdminDirectory(name);
// } catch (SVNException e) {
// return getAdminDirectoryName().equals(name);
}
}
|
// TODO: test updating the updater somehow (store timestamp of .jar/.class and launch the new one if changed? That might be _very_ fragile...)
// TODO: check that multiple upload sites cannot be uploaded to in one go (stageForUpload() should throw an exception in that case)
// TODO: test cross-site dependency
// TODO: test native dependencies
// TODO: what to do with files that Fiji provides already? Take newer?
// TODO: make a nice button to add Fiji...
// TODO: should we have a list of alternative update sites per FileObject so that we can re-parse the alternatives when an update site was removed? Or just tell the user that there was a problem and we need to reparse everything?
// TODO: make a proper upgrade plan for the Fiji Updater
package imagej.updater.core;
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 imagej.log.LogService;
import imagej.updater.core.Conflicts.Conflict;
import imagej.updater.core.Conflicts.Resolution;
import imagej.updater.core.FileObject.Action;
import imagej.updater.core.FileObject.Status;
import imagej.updater.core.FilesCollection.UpdateSite;
import imagej.updater.util.Progress;
import imagej.updater.util.StderrProgress;
import imagej.updater.util.Util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
/**
* Tests various classes of the {@link imagej.updater} package and subpackages.
*
* @author Johannes Schindelin
*/
public class UpdaterTest {
final Progress progress = new StderrProgress();
protected File ijRoot, webRoot;
// Setup
@Before
public void setup() throws IOException {
ijRoot = createTempDirectory("testUpdaterIJRoot");
webRoot = createTempDirectory("testUpdaterWebRoot");
System.err.println("ij: " + ijRoot + ", web: " + webRoot);
}
@After
public void release() {
rmRF(ijRoot);
rmRF(webRoot);
}
// The tests
@Test
public void testUtilityMethods() {
final long newTimestamp = 20200101000000l;
assertEquals(newTimestamp, Long.parseLong(Util.timestamp(Util
.timestamp2millis(newTimestamp))));
}
@Test
public void testInitialUpload() throws Exception {
final File localDb = new File(ijRoot, "db.xml.gz");
// The progress indicator
initializeUpdateSite();
// Write some files
// bend over for Microsoft
final boolean isWindows = Util.getPlatform().startsWith("win");
final String launcherName =
isWindows ? "ImageJ-win32.exe" : "ImageJ-linux32";
final File ijLauncher = writeFile(ijRoot, launcherName, "false");
ijLauncher.setExecutable(true);
writeJar(ijRoot, "jars/narf.jar", "README.txt", "Hello");
writeJar(ijRoot, "jars/egads.jar", "ClassLauncher", "oioioi");
// Initialize FilesCollection
FilesCollection files = readDb(false, false);
// Write the (empty) files collection with the update site information
assertEquals(0, files.size());
files.write();
assertTrue(localDb.exists());
// Update with the local files
final Checksummer czechsummer = new Checksummer(files, progress);
czechsummer.updateFromLocal();
assertEquals(3, files.size());
final FileObject ij = files.get(launcherName);
final FileObject narf = files.get("jars/narf.jar");
final FileObject egads = files.get("jars/egads.jar");
assertNotEqual(null, ij);
assertNotEqual(null, narf);
assertNotEqual(null, egads);
assertEquals(true, ij.executable);
assertEquals(false, narf.executable);
assertEquals(false, egads.executable);
assertNotEqual(ij.current.checksum, narf.current.checksum);
assertNotEqual(narf.current.checksum, egads.current.checksum);
assertNotEqual(egads.current.checksum, ij.current.checksum);
assertCount(3, files.localOnly());
for (final FileObject file : files.localOnly()) {
file.stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
}
assertCount(3, files.toUpload());
upload(files);
// Simulate update when everything is up-to-date
files = readDb(true, true);
assertCount(3, files);
assertCount(3, files.upToDate());
// Simulate update when local db.xml.gz is missing
localDb.delete();
files = readDb(false, true);
assertCount(3, files);
assertCount(3, files.upToDate());
}
@Test
public void testFilters() throws Exception {
initializeUpdateSite("macros/Hello.txt", "macros/Comma.txt",
"macros/World.txt");
// Make sure that the local db.xml.gz is synchronized with the remote one
FilesCollection files = readDb(true, true);
files.write();
// Modify/delete/add files
writeFile("macros/World.txt", "not enough");
writeFile("jars/hello.jar");
new File(ijRoot, "macros/Comma.txt").delete();
assertTrue(new File(ijRoot, ".checksums").delete());
// Chronological order must be preserved
files = files.clone(new ArrayList<FileObject>());
new XMLFileReader(files).read(FilesCollection.DEFAULT_UPDATE_SITE);
assertCount(3, files);
final String[] names = new String[4];
int counter = 0;
for (final FileObject file : files) {
names[counter++] = file.getFilename();
}
assertEquals(3, counter);
names[counter++] = "jars/hello.jar";
files = readDb(true, true);
counter = 0;
for (final FileObject file : files) {
assertEquals("FileObject " + counter, names[counter++], file
.getFilename());
}
// Check that the filters return the correct counts
assertCount(4, files);
assertStatus(Status.MODIFIED, files, "macros/World.txt");
assertCount(1, files.upToDate());
// Comma(NOT_INSTALLED), World(MODIFIED), hello(LOCAL_ONLY)
assertCount(3, files.uploadable());
}
@Test
public void testUpdater() throws Exception {
final String filename = "macros/hello.ijm";
final File file = new File(ijRoot, filename);
final File db = new File(ijRoot, "db.xml.gz");
initializeUpdateSite(filename);
// New files should be staged for install by default
assertTrue(file.delete());
assertFalse(file.exists());
// Pretend that db.xml.gz is out-of-date
FilesCollection files = new FilesCollection(ijRoot);
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).url = webRoot.toURI().toURL().toString();
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).timestamp =
19991224134121l;
files.write();
files = readDb(true, true);
assertCount(1, files);
assertCount(1, files.shownByDefault());
assertStatus(Status.NEW, files, filename);
assertAction(Action.INSTALL, files, filename);
// Start the update
update(files, progress);
assertTrue(file.exists());
assertTrue("Recorded remote timestamp", files.getUpdateSite(
FilesCollection.DEFAULT_UPDATE_SITE).isLastModified(
new File(webRoot, "db.xml.gz").lastModified()));
assertStatus(Status.INSTALLED, files, filename);
assertAction(Action.INSTALLED, files, filename);
// Modified files should be left alone in a fresh install
assertTrue(db.delete());
writeFile(file, "modified");
files = readDb(false, true);
assertCount(1, files);
assertCount(0, files.shownByDefault());
assertStatus(Status.MODIFIED, files, filename);
assertAction(Action.MODIFIED, files, filename);
}
@Test
public void testUploadConflicts() throws Exception {
initializeUpdateSite("macros/obsolete.ijm", "macros/dependency.ijm");
FilesCollection files = readDb(true, true);
files.write();
final FileObject[] list = makeList(files);
assertEquals(2, list.length);
final File obsolete = files.prefix(list[0]);
assertEquals("obsolete.ijm", obsolete.getName());
final File dependency = files.prefix(list[0]);
// Make sure files are checksummed again when their timestamp changed
final String name = "macros/dependencee.ijm";
final File dependencee = new File(ijRoot, name);
writeFile(dependencee, "not yet uploaded");
touch(dependencee, 20030115203432l);
files = readDb(true, true);
assertCount(3, files);
FileObject object = files.get(name);
assertNotNull(object);
object.stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
assertAction(Action.UPLOAD, files, name);
object.addDependency(list[0].getFilename(), obsolete);
object.addDependency(list[1].getFilename(), dependency);
writeFile(dependencee, "still not uploaded");
Conflicts conflicts = new Conflicts(files);
conflicts.conflicts = new ArrayList<Conflict>();
conflicts.listUploadIssues();
assertCount(1, conflicts.conflicts);
Conflict conflict = conflicts.conflicts.get(0);
assertEquals(conflict.getConflict(), "The timestamp of " + name +
" changed in the meantime");
final Resolution[] resolutions = conflict.getResolutions();
assertEquals(1, resolutions.length);
assertEquals(20030115203432l, object.localTimestamp);
resolutions[0].resolve();
assertNotEqual(20030115203432l, object.localTimestamp);
// Make sure that the resolution allows the upload to succeed
upload(files);
// Make sure that obsolete dependencies are detected and repaired
files = readDb(true, true);
assertTrue(obsolete.delete());
writeFile("macros/independent.ijm");
writeFile(dependencee, "a new version");
files = readDb(true, true);
object = files.get(name);
assertNotNull(object);
assertStatus(Status.MODIFIED, files, name);
assertStatus(Status.NOT_INSTALLED, files, list[0].getFilename());
assertStatus(Status.LOCAL_ONLY, files, "macros/independent.ijm");
// obsolete(NOT_INSTALLED), dependencee(MODIFIED), independent(LOCAL_ONLY)
assertCount(3, files.uploadable());
for (final FileObject object2 : files.uploadable()) {
object2.stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
}
object = files.get("macros/obsolete.ijm");
object.setAction(files, Action.REMOVE);
conflicts = new Conflicts(files);
conflicts.conflicts = new ArrayList<Conflict>();
conflicts.listUploadIssues();
assertCount(2, conflicts.conflicts);
assertEquals("macros/dependencee.ijm", conflicts.conflicts.get(1)
.getFilename());
conflict = conflicts.conflicts.get(0);
assertEquals("macros/obsolete.ijm", conflict.getFilename());
// Resolve by breaking the dependency
final Resolution resolution = conflict.getResolutions()[1];
assertEquals("Break the dependency", resolution.getDescription());
resolution.resolve();
conflicts.conflicts = new ArrayList<Conflict>();
conflicts.listUploadIssues();
assertCount(0, conflicts.conflicts);
}
@Test
public void testUpdateConflicts() throws Exception {
initializeUpdateSite("macros/obsoleted.ijm", "macros/dependency.ijm",
"macros/locally-modified.ijm", "macros/dependencee.ijm");
// Add the dependency relations
FilesCollection files = readDb(true, true);
FileObject[] list = makeList(files);
assertEquals(4, list.length);
FileObject obsoleted = list[0];
FileObject dependency = list[1];
FileObject locallyModified = list[2];
FileObject dependencee = list[3];
dependencee.addDependency(obsoleted.getFilename(), Util.getTimestamp(files
.prefix(obsoleted)), true);
dependencee.addDependency(files, dependency);
dependencee.addDependency(files, locallyModified);
assertTrue(files.prefix(obsoleted).delete());
new Checksummer(files, progress).updateFromLocal();
assertStatus(Status.NOT_INSTALLED, obsoleted);
obsoleted.setAction(files, Action.REMOVE);
writeFile(files.prefix(locallyModified), "modified");
upload(files);
assertTrue(files.prefix(dependency).delete());
assertTrue(files.prefix(dependencee).delete());
// Now pretend a fresh install
assertTrue(new File(ijRoot, "db.xml.gz").delete());
files = readDb(false, true);
list = makeList(files);
assertEquals(4, list.length);
obsoleted = list[0];
dependency = list[1];
locallyModified = list[2];
dependencee = list[3];
assertStatus(Status.OBSOLETE_UNINSTALLED, obsoleted);
assertStatus(Status.NEW, dependency);
assertStatus(Status.MODIFIED, locallyModified);
assertStatus(Status.NEW, dependencee);
// Now trigger the conflicts
writeFile(obsoleted.getFilename());
new Checksummer(files, progress).updateFromLocal();
assertStatus(Status.OBSOLETE, obsoleted);
dependencee.setAction(files, Action.INSTALL);
dependency.setAction(files, Action.NEW);
final Conflicts conflicts = new Conflicts(files);
conflicts.conflicts = new ArrayList<Conflict>();
conflicts.listUpdateIssues();
assertCount(3, conflicts.conflicts);
Conflict conflict = conflicts.conflicts.get(0);
assertEquals(locallyModified.getFilename(), conflict.getFilename());
Resolution[] resolutions = conflict.getResolutions();
assertEquals(2, resolutions.length);
assertTrue(resolutions[0].getDescription().startsWith("Keep"));
assertTrue(resolutions[1].getDescription().startsWith("Update"));
conflict.resolutions[0].resolve();
conflict = conflicts.conflicts.get(1);
assertEquals(obsoleted.getFilename(), conflict.getFilename());
resolutions = conflict.getResolutions();
assertEquals(2, resolutions.length);
assertTrue(resolutions[0].getDescription().startsWith("Uninstall"));
assertTrue(resolutions[1].getDescription().startsWith("Do not update"));
conflict.resolutions[0].resolve();
conflict = conflicts.conflicts.get(2);
assertEquals(null, conflict.getFilename());
resolutions = conflict.getResolutions();
assertEquals(1, resolutions.length);
assertTrue(resolutions[0].getDescription().startsWith("Install"));
conflict.resolutions[0].resolve();
update(files, progress);
assertFalse(files.prefix(obsoleted).exists());
}
@Test
public void testReChecksumming() throws Exception {
writeFile("jars/new.jar");
FilesCollection files = new FilesCollection(ijRoot);
new Checksummer(files, progress).updateFromLocal();
assertStatus(Status.LOCAL_ONLY, files.get("jars/new.jar"));
writeFile("jars/new.jar", "modified");
new Checksummer(files, progress).updateFromLocal();
assertStatus(Status.LOCAL_ONLY, files.get("jars/new.jar"));
}
@Test
public void testStripVersionFromFilename() {
assertEquals("jars/bio-formats.jar", FileObject.getFilename("jars/bio-formats-4.4-imagej-2.0.0-beta1.jar", true));
assertEquals(FileObject.getFilename("jars/ij-data-2.0.0.1-beta1.jar", true), FileObject.getFilename("jars/ij-data-2.0.0.1-SNAPSHOT.jar", true));
assertEquals(FileObject.getFilename("jars/ij-1.44.jar", true), FileObject.getFilename("jars/ij-1.46b.jar", true));
assertEquals(FileObject.getFilename("jars/javassist.jar", true), FileObject.getFilename("jars/javassist-3.9.0.GA.jar", true));
assertEquals(FileObject.getFilename("jars/javassist.jar", true), FileObject.getFilename("jars/javassist-3.16.1-GA.jar", true));
assertEquals(FileObject.getFilename("jars/bsh.jar", true), FileObject.getFilename("jars/bsh-2.0b4.jar", true));
assertEquals(FileObject.getFilename("jars/mpicbg.jar", true), FileObject.getFilename("jars/mpicbg-20111128.jar", true));
}
@Test
public void testUpdateVersionedJars() throws Exception {
initializeUpdateSite("jars/obsoleted-2.1.jar", "jars/without.jar",
"jars/with-2.0.jar", "jars/too-old-3.11.jar", "plugins/plugin.jar");
// Add the dependency relations
FilesCollection files = readDb(true, true);
FileObject[] list = makeList(files);
assertEquals(5, list.length);
FileObject obsoleted = list[0];
FileObject without = list[1];
FileObject with = list[2];
FileObject tooOld = list[3];
FileObject plugin = list[4];
plugin.addDependency(obsoleted.getFilename(), Util.getTimestamp(files
.prefix(obsoleted)), true);
plugin.addDependency(files, without);
plugin.addDependency(files, with);
plugin.addDependency(files, tooOld);
assertTrue(plugin.dependencies.containsKey("jars/without.jar"));
assertTrue(plugin.dependencies.containsKey("jars/with.jar"));
assertEquals("jars/with-2.0.jar", plugin.dependencies.get("jars/with.jar").filename);
assertTrue(plugin.dependencies.containsKey("jars/too-old.jar"));
assertEquals("jars/too-old-3.11.jar", plugin.dependencies.get("jars/too-old.jar").filename);
assertTrue(files.containsKey("jars/without.jar"));
assertTrue(files.containsKey("jars/with.jar"));
assertTrue(files.containsKey("jars/too-old.jar"));
assertNotNull(files.get("jars/with.jar"));
assertSame(files.get("jars/with.jar"), files.get("jars/with-2.0.jar"));
assertTrue(files.prefix(obsoleted).delete());
new Checksummer(files, progress).updateFromLocal();
assertStatus(Status.NOT_INSTALLED, obsoleted);
obsoleted.setAction(files, Action.REMOVE);
//writeFile(files.prefix(jars), "modified");
upload(files);
// Update one .jar file to a newer version
files = readDb(true, true);
assertTrue(files.prefix("jars/too-old-3.11.jar").delete());
writeFile("jars/too-old-3.12.jar");
new Checksummer(files, progress).updateFromLocal();
tooOld = files.get("jars/too-old.jar");
assertTrue(tooOld.getFilename().equals("jars/too-old-3.11.jar"));
assertTrue(tooOld.localFilename.equals("jars/too-old-3.12.jar"));
tooOld.stageForUpload(files, tooOld.updateSite);
upload(files);
// check that webRoot's db.xml.gz's previous versions contain the old filename
final String db = readGzippedStream(new FileInputStream(new File(webRoot, "db.xml.gz")));
Pattern regex = Pattern.compile(".*<previous-version [^>]*filename=\"jars/too-old-3.11.jar\".*", Pattern.DOTALL);
assertTrue(regex.matcher(db).matches());
assertTrue(new File(webRoot, "jars/too-old-3.12.jar-" + tooOld.localTimestamp).exists());
// The dependencies should be updated automatically
files = readDb(true, true);
plugin = files.get("plugins/plugin.jar");
assertTrue(plugin.dependencies.containsKey("jars/too-old.jar"));
assertEquals("jars/too-old-3.12.jar", plugin.dependencies.get("jars/too-old.jar").filename);
}
@Test
public void testMultipleVersionsSameSite() throws Exception {
final String db = "<pluginRecords>"
+ " <plugin filename=\"jars/Jama-1.0.2.jar\">"
+ " <previous-version timestamp=\"1\" checksum=\"a\" />"
+ " <previous-version timestamp=\"2\" checksum=\"b\" />"
+ " </plugin>"
+ " <plugin filename=\"jars/Jama.jar\">"
+ " <version checksum=\"d\" timestamp=\"4\" filesize=\"10\" />"
+ " <previous-version timestamp=\"3\" checksum=\"c\" />"
+ " </plugin>"
+ "</pluginRecords>";
writeGZippedFile(webRoot, "db.xml.gz", db);
final FilesCollection files = new FilesCollection(ijRoot);
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).url = webRoot.toURI().toURL().toString();
new XMLFileReader(files).read(FilesCollection.DEFAULT_UPDATE_SITE);
final FileObject jama = files.get("jars/Jama.jar");
assertNotNull(jama);
assertCount(3, jama.previous);
final FileObject.Version previous[] = new FileObject.Version[3];
for (final FileObject.Version version : jama.previous) {
previous[(int)(version.timestamp - 1)] = version;
}
assertTrue("a".equals(previous[0].checksum));
assertEquals("jars/Jama-1.0.2.jar", previous[0].filename);
assertTrue("b".equals(previous[1].checksum));
assertEquals("jars/Jama-1.0.2.jar", previous[1].filename);
assertTrue("c".equals(previous[2].checksum));
assertEquals("jars/Jama.jar", previous[2].filename);
}
@Test
public void testOverriddenObsolete() throws Exception {
final String db = "<pluginRecords>"
+ " <plugin filename=\"ImageJ-linux64\">"
+ " <previous-version timestamp=\"1\" checksum=\"a\" />"
+ " </plugin>"
+ "</pluginRecords>";
writeGZippedFile(webRoot, "db.xml.gz", db);
File webRoot2 = createTempDirectory("testUpdaterWebRoot2");
final String db2 = "<pluginRecords>"
+ " <plugin filename=\"ImageJ-linux64\">"
+ " <version checksum=\"c\" timestamp=\"3\" filesize=\"10\" />"
+ " <previous-version timestamp=\"2\" checksum=\"b\" />"
+ " </plugin>"
+ "</pluginRecords>";
writeGZippedFile(webRoot2, "db.xml.gz", db2);
FilesCollection files = new FilesCollection(ijRoot);
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).url = webRoot.toURI().toURL().toString();
files.addUpdateSite("Fiji", webRoot2.toURI().toURL().toString(), null, null, 0);
new XMLFileReader(files).read(FilesCollection.DEFAULT_UPDATE_SITE);
new XMLFileReader(files).read("Fiji");
FileObject file = files.get("ImageJ-linux64");
assertNotNull(file);
assertTrue(file.hasPreviousVersion("a"));
assertTrue(file.hasPreviousVersion("b"));
assertTrue(file.hasPreviousVersion("c"));
assertStatus(Status.NEW, files, "ImageJ-linux64");
files = new FilesCollection(ijRoot);
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).url = webRoot2.toURI().toURL().toString();
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).timestamp = 0;
files.addUpdateSite("Fiji", webRoot.toURI().toURL().toString(), null, null, 0);
new XMLFileReader(files).read(FilesCollection.DEFAULT_UPDATE_SITE);
new XMLFileReader(files).read("Fiji");
file = files.get("ImageJ-linux64");
assertNotNull(file);
assertTrue(file.hasPreviousVersion("a"));
assertTrue(file.hasPreviousVersion("b"));
assertTrue(file.hasPreviousVersion("c"));
assertStatus(Status.NEW, files, "ImageJ-linux64");
}
@Test
public void testConflictingVersionsToUpload() throws Exception {
initializeUpdateSite("macros/macro.ijm");
// There should be an upload conflict if .jar file names differ only in version number
writeFile("jars/file.jar");
writeFile("jars/file-3.0.jar");
final FilesCollection files = readDb(true, true);
files.get("jars/file.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
final Conflicts conflicts = new Conflicts(files);
conflicts.conflicts = new ArrayList<Conflict>();
conflicts.listUploadIssues();
assertCount(1, conflicts.conflicts);
// resolve by deleting the file
assertTrue(files.prefix("jars/file.jar").exists());
assertTrue(files.prefix("jars/file-3.0.jar").exists());
conflicts.conflicts.get(0).getResolutions()[0].resolve();
assertTrue(files.prefix("jars/file.jar").exists() ^
files.prefix("jars/file-3.0.jar").exists());
upload(files);
}
@Test
public void testMultipleUpdateSites() throws Exception {
// initialize secondary update site
File webRoot2 = createTempDirectory("testUpdaterWebRoot2");
initializeUpdateSite(ijRoot, webRoot2, progress, "jars/hello.jar");
assertFalse(new File(webRoot, "db.xml.gz").exists());
// initialize main update site
assertTrue(new File(ijRoot, "db.xml.gz").delete());
initializeUpdateSite("macros/macro.ijm");
FilesCollection files = readDb(true, true);
assertStatus(Status.LOCAL_ONLY, files.get("jars/hello.jar"));
// add second update site
files.addUpdateSite("second", webRoot2.toURI().toURL().toString(), "file:localhost", webRoot2.getAbsolutePath() + "/", 0l);
// re-read files from update site
files.reReadUpdateSite("second", progress);
assertStatus(Status.INSTALLED, files.get("jars/hello.jar"));
files.write();
// modify locally and re-read from update site
assertTrue(new File(ijRoot, ".checksums").delete());
assertTrue(new File(ijRoot, "jars/hello.jar").delete());
writeJar("jars/hello-2.0.jar", "new-file", "empty");
new Checksummer(files, progress).updateFromLocal();
files.reReadUpdateSite("second", progress);
assertStatus(Status.MODIFIED, files.get("jars/hello.jar"));
}
@Test
public void testUpdateable() throws Exception {
initializeUpdateSite("jars/hello.jar");
FilesCollection files = readDb(true, true);
assertStatus(Status.INSTALLED, files.get("jars/hello.jar"));
String origChecksum = files.get("jars/hello.jar").getChecksum();
assertEquals(origChecksum, Util.getJarDigest(new File(ijRoot, "jars/hello.jar")));
assertTrue(new File(ijRoot, ".checksums").delete());
assertTrue(new File(ijRoot, "jars/hello.jar").delete());
writeJar("jars/hello-2.0.jar", "new-file", "empty");
new Checksummer(files, progress).updateFromLocal();
String newChecksum = files.get("jars/hello.jar").localChecksum;
assertEquals(newChecksum, Util.getJarDigest(new File(ijRoot, "jars/hello-2.0.jar")));
assertNotEqual(origChecksum, newChecksum);
// upload that version
files.get("jars/hello.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
assertEquals(newChecksum, files.get("jars/hello.jar").localChecksum);
upload(files);
FilesCollection files2 = new FilesCollection(new File(ijRoot, "invalid"));
files2.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).url = webRoot.toURI().toURL().toString();
XMLFileDownloader xmlLoader = new XMLFileDownloader(files2);
xmlLoader.start();
String newChecksum2 = files2.get("jars/hello.jar").current.checksum;
assertEquals(newChecksum, newChecksum2);
// re-write the original version
assertTrue(new File(ijRoot, ".checksums").delete());
writeFile("jars/hello.jar");
assertTrue(new File(ijRoot, "jars/hello-2.0.jar").delete());
files = readDb(true, true);
String origChecksum2 = files.get("jars/hello.jar").localChecksum;
assertEquals(origChecksum, origChecksum2);
assertEquals(origChecksum, Util.getJarDigest(new File(ijRoot, "jars/hello.jar")));
assertTrue(new File(ijRoot, "db.xml.gz").delete());
files = readDb(false, true);
assertEquals(newChecksum, files.get("jars/hello.jar").current.checksum);
assertStatus(Status.UPDATEABLE, files.get("jars/hello.jar"));
files.get("jars/hello.jar").setAction(files, Action.UPDATE);
Installer installer = new Installer(files, progress);
installer.start();
assertEquals(newChecksum, Util.getJarDigest(new File(ijRoot, "update/jars/hello-2.0.jar")));
installer.moveUpdatedIntoPlace();
assertStatus(Status.INSTALLED, files.get("jars/hello.jar"));
assertEquals(newChecksum, Util.getJarDigest(new File(ijRoot, "jars/hello-2.0.jar")));
}
@Test
public void testReReadFiles() throws Exception {
initializeUpdateSite("macros/macro.ijm");
FilesCollection files = readDb(true, true);
files.get("macros/macro.ijm").description = "Narf";
files.write();
upload(files);
files = readDb(true, true);
assertEquals("Narf", files.get("macros/macro.ijm").description);
new Checksummer(files, progress).updateFromLocal();
assertEquals("Narf", files.get("macros/macro.ijm").description);
}
@Test
public void testUpdateTheUpdater() throws Exception {
final String name1 = "jars/ij-updater-core-1.46n.jar";
final String name2 = "jars/ij-updater-core-2.0.0.jar";
// initialize main update site
initializeUpdateSite(name1);
// "change" updater
assertTrue(new File(ijRoot, name1).delete());
writeJar(name2, "files.txt", "modified");
FilesCollection files = readDb(true, true);
assertTrue(files.get(name1) == files.get(name2));
assertStatus(Status.MODIFIED, files.get(name1));
final String modifiedChecksum = files.get(name2).localChecksum;
files.get(name1).stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
upload(files);
// revert back to "old" updater
writeJar(name1);
assertTrue(new File(ijRoot, name2).delete());
// now the updater should be updated first thing
files = readDb(true, true);
FileObject file2 = files.get(name2);
assertNotEqual(file2.localFilename, name2);
assertTrue(file2.isUpdateable());
assertNotEqual(modifiedChecksum, files.get(name2).localChecksum);
assertTrue(Installer.isTheUpdaterUpdateable(files));
Installer.updateTheUpdater(files, progress);
assertTrue(new File(ijRoot, "update/" + name1).exists());
assertEquals(0l, new File(ijRoot, "update/" + name1).length());
assertTrue(new File(ijRoot, "update/" + name2).exists());
assertTrue(new File(ijRoot, name1).delete());
assertFalse(new File(ijRoot, name2).exists());
assertTrue(new File(ijRoot, "update/" + name2).renameTo(new File(ijRoot, name2)));
new Checksummer(files, progress).updateFromLocal();
assertEquals(modifiedChecksum, files.get(name2).current.checksum);
}
@Test
public void testFillMetadataFromPOM() throws Exception {
writeJar("jars/hello.jar", "META-INF/maven/egads/hello/pom.xml", "<project>"
+ " <description>Take over the world!</description>"
+ " <developers>"
+ " <developer><name>Jenna Jenkins</name></developer>"
+ " <developer><name>Bugs Bunny</name></developer>"
+ " </developers>"
+ "</project>");
final FilesCollection files = new FilesCollection(ijRoot);
new Checksummer(files, progress).updateFromLocal();
final FileObject object = files.get("jars/hello.jar");
assertNotNull(object);
assertEquals(object.description, "Take over the world!");
assertCount(2, object.authors);
final String[] authors = new String[2];
int counter = 0;
for (final String author : object.authors) {
authors[counter++] = author;
}
Arrays.sort(authors);
assertEquals(authors[0], "Bugs Bunny");
assertEquals(authors[1], "Jenna Jenkins");
}
@Test
public void testPomPropertiesHashing() throws Exception {
final String oldContents = "blub = true\n"
+ "#Tue Jun 12 06:43:48 IST 2012\n"
+ "narf.egads = pinkie\n";
final String newContents = "blub = true\n"
+ "#Tue Jun 17 09:47:43 CST 2012\n"
+ "narf.egads = pinkie\n";
final String fileName =
"META-INF/maven/net.imagej/updater-test/pom.properties";
final File oldOldJar =
writeJarWithDatedFile("old.jar", 2012, 6, 12, fileName, oldContents);
final File oldNewJar =
writeJarWithDatedFile("new.jar", 2012, 6, 12, fileName, newContents);
final File newOldJar =
writeJarWithDatedFile("old2.jar", 2012, 6, 17, fileName, oldContents);
final File newNewJar =
writeJarWithDatedFile("new2.jar", 2012, 6, 17, fileName, newContents);
// before June 15th, they were considered different
assertNotEqual(Util.getJarDigest(oldOldJar, false, false, false), Util.getJarDigest(oldNewJar, false, false, false));
// after June 15th, they are considered unchanged
assertEquals(Util.getJarDigest(newOldJar, true, false, false), Util.getJarDigest(newNewJar, true, false, false));
// checksums must be different between the old and new way to calculate them
assertNotEqual(Util.getJarDigest(oldOldJar, false, false, false), Util.getJarDigest(newOldJar));
}
@Test
public void testManifestHashing() throws Exception {
final String oldContents =
"Manifest-Version: 1.0\n" + "Built-By: Bugs Bunny\n"
+ "Main-Class: Buxtehude\n";
final String newContents =
"Manifest-Version: 1.0\n" + "Built-By: Donald Duck\n"
+ "Main-Class: Buxtehude\n";
final String fileName = "META-INF/MANIFEST.MF";
final File oldOldJar =
writeJarWithDatedFile("old.jar", 2012, 7, 4, fileName, oldContents);
final File oldNewJar =
writeJarWithDatedFile("new.jar", 2012, 7, 4, fileName, newContents);
final File newOldJar =
writeJarWithDatedFile("old2.jar", 2012, 7, 8, fileName, oldContents);
final File newNewJar =
writeJarWithDatedFile("new2.jar", 2012, 7, 8, fileName, newContents);
// before June 15th, they were considered different
assertNotEqual(Util.getJarDigest(oldOldJar, false, false, false), Util.getJarDigest(oldNewJar, false, false, false));
// after June 15th, they are considered unchanged
assertEquals(Util.getJarDigest(newOldJar, false, true, true), Util.getJarDigest(newNewJar, false, true, true));
// checksums must be different between the old and new way to calculate them
assertNotEqual(Util.getJarDigest(oldOldJar, false, false, false), Util.getJarDigest(newOldJar));
assertNotEqual(Util.getJarDigest(oldOldJar, false, true, false), Util.getJarDigest(newOldJar, false, true, true));
}
private File writeJarWithDatedFile(final String jarFileName, final int year,
final int month, final int day, final String fileName,
final String propertiesContents) throws IOException
{
final File file = new File(ijRoot, jarFileName);
final JarOutputStream out = new JarOutputStream(new FileOutputStream(file));
final JarEntry entry = new JarEntry(fileName);
entry.setTime(new GregorianCalendar(year, month, day).getTimeInMillis());
out.putNextEntry(entry);
out.write(propertiesContents.getBytes());
out.closeEntry();
out.close();
return file;
}
@Test
public void testHandlingOfObsoleteChecksums() throws Exception {
final String newContents =
"blub = true\n" + "#Tue Jun 17 09:47:43 CST 2012\n"
+ "narf.egads = pinkie\n";
final String fileName =
"META-INF/maven/net.imagej/updater-test/pom.properties";
assertTrue(new File(ijRoot, "jars").mkdirs());
File jar =
writeJarWithDatedFile("jars/new.jar", 2012, 6, 17, fileName, newContents);
final String checksumOld = Util.getJarDigest(jar, false, false);
final String checksumNew = Util.getJarDigest(jar, true, true);
assertNotEqual(checksumOld, checksumNew);
final String[][] data =
{
// previous current expect
{ "invalid", checksumOld, checksumOld },
{ checksumOld, checksumNew, checksumNew },
{ checksumOld, "something else", checksumOld },
{ checksumNew, "something else", checksumNew } };
for (final String[] triplet : data) {
final FilesCollection files = new FilesCollection(ijRoot);
final FileObject file =
new FileObject(null, "jars/new.jar", jar.length(), triplet[1], Util
.getTimestamp(jar), Status.NOT_INSTALLED);
file.addPreviousVersion(triplet[0], 1, null);
files.add(file);
new Checksummer(files, progress).updateFromLocal();
final FileObject file2 = files.get("jars/new.jar");
assertTrue(file == file2);
assertEquals(triplet[1], file.getChecksum());
assertEquals(triplet[2], file.localChecksum != null ? file.localChecksum
: file.current.checksum);
}
FilesCollection files = new FilesCollection(ijRoot);
final FileObject file =
new FileObject(FilesCollection.DEFAULT_UPDATE_SITE, "jars/new.jar", jar.length(), checksumOld, Util
.getTimestamp(jar), Status.INSTALLED);
files.add(file);
new File(webRoot, "jars").mkdirs();
assertTrue(jar.renameTo(new File(webRoot, "jars/new.jar-" +
file.current.timestamp)));
new XMLFileWriter(files).write(new GZIPOutputStream(new FileOutputStream(
new File(webRoot, "db.xml.gz"))), false);
files = readDb(false, true);
new Installer(files, progress).start();
jar = new File(ijRoot, "update/jars/new.jar");
assertTrue(jar.exists());
assertEquals(checksumNew, Util.getJarDigest(jar));
assertEquals(checksumOld, files.get("jars/new.jar").getChecksum());
}
@Test
public void testUpdateToDifferentVersion() throws Exception {
initializeUpdateSite("jars/egads-1.0.jar");
FilesCollection files = readDb(true, true);
// upload a newer version
assertTrue(files.prefix("jars/egads-1.0.jar").delete());
writeJar("jars/egads-2.1.jar");
files = readDb(true, true);
files.get("jars/egads.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
upload(files);
assertTrue(files.prefix("jars/egads-2.1.jar").exists());
assertFalse(files.prefix("jars/egads-1.0.jar").exists());
// downgrade locally
assertTrue(files.prefix("jars/egads-2.1.jar").delete());
writeJar("jars/egads-1.0.jar");
files = readDb(true, true);
// update again
assertTrue("egads.jar's status: " + files.get("jars/egads.jar").getStatus(), files.get("jars/egads.jar").stageForUpdate(files, false));
Installer installer = new Installer(files, progress);
installer.start();
assertTrue(files.prefixUpdate("jars/egads-2.1.jar").length() > 0);
assertTrue(files.prefixUpdate("jars/egads-1.0.jar").length() == 0);
installer.moveUpdatedIntoPlace();
assertTrue(files.prefix("jars/egads-2.1.jar").exists());
assertFalse(files.prefix("jars/egads-1.0.jar").exists());
// remove the file from the update site
assertTrue(files.prefix("jars/egads-2.1.jar").delete());
files = readDb(true, true);
files.get("jars/egads.jar").setAction(files, Action.REMOVE);
upload(files);
// re-instate an old version with a different name
writeJar("jars/egads-1.0.jar");
files = readDb(true, true);
assertStatus(Status.OBSOLETE, files, "jars/egads.jar");
// uninstall it
files.get("jars/egads.jar").stageForUninstall(files);
installer = new Installer(files, progress);
installer.start();
assertFalse(files.prefixUpdate("jars/egads-2.1.jar").exists());
assertTrue(files.prefixUpdate("jars/egads-1.0.jar").exists());
assertTrue(files.prefixUpdate("jars/egads-1.0.jar").length() == 0);
installer.moveUpdatedIntoPlace();
assertFalse(files.prefixUpdate("jars/egads-1.0.jar").exists());
assertStatus(Status.OBSOLETE_UNINSTALLED, files, "jars/egads.jar");
}
@Test
public void reconcileMultipleVersions() throws Exception {
initializeUpdateSite();
writeJar(ijRoot, "jars/egads-0.1.jar", "hello", "world");
FilesCollection files = readDb(false, true);
files.get("jars/egads.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
upload(files);
assertTrue(new File(ijRoot, "jars/egads-0.1.jar").delete());
writeJar(ijRoot, "jars/egads-0.2.jar", "hello", "world2");
new Checksummer(files, progress).updateFromLocal();
files.get("jars/egads.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
upload(files);
writeJar(ijRoot, "jars/egads-0.1.jar", "hello", "world");
writeJar(ijRoot, "jars/egads.jar", "hello", "world");
touch(new File(ijRoot, "jars/egads-0.2.jar"), 19800101000001l);
files = readDb(true, true);
List<Conflict> conflicts = files.getConflicts();
assertEquals(1, conflicts.size());
Conflict conflict = conflicts.get(0);
assertEquals(conflict.filename, "jars/egads-0.2.jar");
conflict.resolutions[1].resolve();
assertFalse(new File(ijRoot, "jars/egads.jar").exists());
assertFalse(new File(ijRoot, "jars/egads-0.1.jar").exists());
assertTrue(new File(ijRoot, "jars/egads-0.2.jar").exists());
}
@Test
public void uninstallRemoved() throws Exception {
initializeUpdateSite("jars/to-be-removed.jar");
FilesCollection files = readDb(true, true);
files.write();
File ijRoot2 = makeIJRoot(webRoot);
files = new FilesCollection(ijRoot2);
files.downloadIndexAndChecksum(progress);
files.get("jars/to-be-removed.jar").setAction(files, Action.REMOVE);
upload(files);
// make sure that the timestamp of the update site is "new"
files = new FilesCollection(ijRoot);
files.read();
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE).timestamp = 0;
files.write();
files = readDb(true, true);
FileObject obsolete = files.get("jars/to-be-removed.jar");
assertStatus(Status.OBSOLETE, obsolete);
assertAction(Action.OBSOLETE, obsolete);
}
@Test
public void removeDependencies() throws Exception {
initializeUpdateSite("jars/plugin.jar", "jars/dependency.jar");
writeJar("jars/not-uploaded-0.11.jar");
FilesCollection files = readDb(true, true);
FileObject plugin = files.get("jars/plugin.jar");
plugin.addDependency(files, files.get("jars/dependency.jar"));
plugin.addDependency(files, files.get("jars/not-uploaded.jar"));
List<Conflict> conflicts = new ArrayList<Conflict>();
for (Conflict conflict : new Conflicts(files).getConflicts(true))
conflicts.add(conflict);
assertCount(1, conflicts);
Conflict conflict = conflicts.get(0);
assertEquals(1, conflict.getResolutions().length);
assertTrue(conflict.getResolutions()[0].getDescription().startsWith("Break"));
conflict.getResolutions()[0].resolve();
assertCount(0, new Conflicts(files).getConflicts(true));
}
@Test
public void byteCodeAnalyzer() throws Exception {
writeJar("jars/dependencee.jar", imagej.updater.test.Dependencee.class);
writeJar("jars/dependency.jar", imagej.updater.test.Dependency.class);
FilesCollection files = new FilesCollection(ijRoot);
new Checksummer(files, progress).updateFromLocal();
FileObject dependencee = files.get("jars/dependencee.jar");
assertCount(0, dependencee.getDependencies());
files.updateDependencies(dependencee);
assertCount(1, dependencee.getDependencies());
assertEquals("jars/dependency.jar", dependencee.getDependencies().iterator().next().filename);
writeJar("jars/bogus.jar", imagej.updater.test.Dependency.class, imagej.updater.test.Dependencee.class);
files = new FilesCollection(ijRoot); // force a new dependency analyzer
new Checksummer(files, progress).updateFromLocal();
dependencee = files.get("jars/dependencee.jar");
dependencee.addDependency(files, files.get("jars/dependency.jar"));
files.updateDependencies(dependencee);
assertCount(1, dependencee.getDependencies());
assertEquals("jars/dependency.jar", dependencee.getDependencies().iterator().next().filename);
}
@Test
public void keepObsoleteRecords() throws Exception {
initializeUpdateSite("jars/obsolete.jar");
assertTrue(new File(ijRoot, "jars/obsolete.jar").delete());
FilesCollection files = readDb(true, true);
files.get("jars/obsolete.jar").setAction(files, Action.REMOVE);
upload(files);
writeFile("jars/new.jar");
files = readDb(true, true);
files.get("jars/new.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
upload(files);
String db = readGzippedStream(new FileInputStream(new File(webRoot, "db.xml.gz")));
assertTrue(db.indexOf("<plugin filename=\"jars/obsolete.jar\"") > 0);
}
@Test
public void keepOverriddenObsoleteRecords() throws Exception {
initializeUpdateSite();
// upload to secondary
writeFile("jars/overridden.jar");
FilesCollection files = readDb(false, true);
File webRoot2 = createTempDirectory("testUpdaterWebRoot2");
files.addUpdateSite("Second", webRoot2.toURI().toURL().toString(), "file:localhost", webRoot2.getAbsolutePath() + "/", 0l);
files.get("jars/overridden.jar").stageForUpload(files, "Second");
upload(files, "Second");
files.write();
String obsoleteChecksum = files.get("jars/overridden.jar").getChecksum();
// delete from secondary
assertTrue(new File(ijRoot, "jars/overridden.jar").delete());
files = readDb(true, true);
files.get("jars/overridden.jar").setAction(files, Action.REMOVE);
upload(files, "Second");
files.write();
// upload to primary
assertTrue(new File(ijRoot, "db.xml.gz").delete());
writeJar("jars/overridden.jar", "Jola", "Theo");
files = readDb(false, true);
files.get("jars/overridden.jar").stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
upload(files);
// re-add secondary
files = readDb(true, true);
files.addUpdateSite("Second", webRoot2.toURI().toURL().toString(), "file:localhost", webRoot2.getAbsolutePath() + "/", 0l);
files.write();
// upload sumpin' else to secondary
writeJar("jars/new.jar");
files = readDb(true, true);
files.get("jars/new.jar").stageForUpload(files, "Second");
upload(files, "Second");
String db = readGzippedStream(new FileInputStream(new File(webRoot2, "db.xml.gz")));
assertTrue(db.indexOf("<plugin filename=\"jars/overridden.jar\"") > 0);
assertTrue(db.indexOf(obsoleteChecksum) > 0);
}
@Test
public void testShownByDefault() throws Exception {
initializeUpdateSite("jars/will-have-dependency.jar");
FilesCollection files = readDb(true, true);
files.write();
File ijRoot2 = makeIJRoot(webRoot);
FilesCollection files2 = new FilesCollection(ijRoot2);
files2.downloadIndexAndChecksum(progress);
update(files2, progress);
writeFile("jars/dependency.jar");
new Checksummer(files, progress).updateFromLocal();
final FileObject dependency = files.get("jars/dependency.jar");
assertNotNull(dependency);
dependency.updateSite = FilesCollection.DEFAULT_UPDATE_SITE;
dependency.setAction(files, Action.UPLOAD);
assertCount(1, files.toUpload());
upload(files);
files2 = readDb(true, true, ijRoot2, webRoot, progress);
files2.write();
files.get("jars/will-have-dependency.jar").addDependency(files, dependency);
upload(files);
files2 = readDb(true, true, ijRoot2, webRoot, progress);
assertAction(Action.INSTALL, files2, "jars/dependency.jar");
}
// Debug functions
/**
* This is a hack, albeit not completely a dumb one. As long as you have
* swing-updater compiled and up-to-date, you can use this method to inspect
* the state at any given moment
*
* @param files The collection of files, including the current update site and
* IJ root.
*/
protected void show(final FilesCollection files) {
try {
String url = getClass().getResource("UpdaterTest.class").toString();
final String suffix =
"/core/updater/core/target/test-classes/imagej/updater/core/UpdaterTest.class";
assertTrue(url.endsWith(suffix));
url =
url.substring(0, url.length() - suffix.length()) +
"/ui/swing/updater/target/classes/";
final ClassLoader loader =
new java.net.URLClassLoader(
new java.net.URL[] { new java.net.URL(url) });
final Class<?> clazz =
loader.loadClass("imagej.updater.gui.UpdaterFrame");
final java.lang.reflect.Constructor<?> ctor =
clazz.getConstructor(LogService.class, UploaderService.class, FilesCollection.class);
final Object updaterFrame = ctor.newInstance(Util.getLogService(), null, files);
final java.lang.reflect.Method setVisible =
clazz.getMethod("setVisible", boolean.class);
setVisible.invoke(updaterFrame, true);
final java.lang.reflect.Method isVisible = clazz.getMethod("isVisible");
for (;;) {
Thread.sleep(1000);
if (isVisible.invoke(updaterFrame).equals(Boolean.FALSE)) break;
}
}
catch (final Throwable t) {
t.printStackTrace();
}
}
// Utility functions
protected static File makeIJRoot(final File webRoot) throws IOException {
final File ijRoot = createTempDirectory("testUpdaterIJRoot");
writeGZippedFile(ijRoot, "db.xml.gz", "<pluginRecords><update-site name=\""
+ FilesCollection.DEFAULT_UPDATE_SITE + "\" timestamp=\"0\" url=\""
+ webRoot.toURI().toURL().toString() + "\" ssh-host=\"file:localhost\" "
+ "upload-directory=\"" + webRoot.getAbsolutePath() + "\"/></pluginRecords>");
return ijRoot;
}
protected void initializeUpdateSite(final String... fileNames)
throws Exception {
initializeUpdateSite(ijRoot, webRoot, progress, fileNames);
}
protected static void initializeUpdateSite(final File ijRoot, final File webRoot, final Progress progress, final String... fileNames)
throws Exception
{
final File localDb = new File(ijRoot, "db.xml.gz");
final File remoteDb = new File(webRoot, "db.xml.gz");
// Initialize update site
final String url = webRoot.toURI().toURL().toString() + "/";
final String sshHost = "file:localhost";
final String uploadDirectory = webRoot.getAbsolutePath() + "/";
assertFalse(localDb.exists());
assertFalse(remoteDb.exists());
FilesUploader uploader =
FilesUploader.initialUpload(url, sshHost, uploadDirectory);
assertTrue(uploader.login());
uploader.upload(progress);
assertFalse(localDb.exists());
assertTrue(remoteDb.exists());
final long remoteDbSize = remoteDb.length();
if (fileNames.length > 0) {
// Write files
final List<String> list = new ArrayList<String>();
for (final String name : fileNames) {
writeFile(new File(ijRoot, name), name);
list.add(name);
}
// Initialize db.xml.gz
final FilesCollection files = readDb(false, false, ijRoot, webRoot, progress);
assertEquals(0, files.size());
files.write();
assertTrue(localDb.exists());
final Checksummer czechsummer = new Checksummer(files, progress);
czechsummer.updateFromLocal(list);
for (final String name : fileNames) {
final FileObject file = files.get(name);
assertNotNull(name, file);
file.stageForUpload(files, FilesCollection.DEFAULT_UPDATE_SITE);
}
uploader = new FilesUploader(files, FilesCollection.DEFAULT_UPDATE_SITE);
assertTrue(uploader.login());
uploader.upload(progress);
assertTrue(remoteDb.exists());
assertNotEqual(remoteDb.length(), remoteDbSize);
}
}
protected FilesCollection readDb(final boolean readLocalDb,
final boolean runChecksummer) throws IOException,
ParserConfigurationException, SAXException
{
return readDb(readLocalDb, runChecksummer, ijRoot, webRoot, progress);
}
protected static FilesCollection readDb(final boolean readLocalDb,
final boolean runChecksummer, final File ijRoot, final File webRoot, final Progress progress) throws IOException,
ParserConfigurationException, SAXException {
final FilesCollection files = new FilesCollection(ijRoot);
final File localDb = new File(ijRoot, "db.xml.gz");
if (readLocalDb && runChecksummer) {
files.downloadIndexAndChecksum(progress);
return files;
}
if (readLocalDb) files.read(localDb);
else {
assertFalse(localDb.exists());
// Initialize default update site
final UpdateSite updateSite =
files.getUpdateSite(FilesCollection.DEFAULT_UPDATE_SITE);
assertNotNull(updateSite);
updateSite.url = webRoot.toURI().toURL().toString() + "/";
updateSite.sshHost = "file:localhost";
updateSite.uploadDirectory = webRoot.getAbsolutePath() + "/";
}
new XMLFileReader(files).read(FilesCollection.DEFAULT_UPDATE_SITE);
if (runChecksummer) {
// We're too fast, cannot trust the cached checksums
new File(ijRoot, ".checksums").delete();
final Checksummer czechsummer = new Checksummer(files, progress);
czechsummer.updateFromLocal();
}
return files;
}
protected static void update(final FilesCollection files, final Progress progress) throws IOException {
final File ijRoot = files.prefix(".");
final Installer installer = new Installer(files, progress);
installer.start();
assertTrue(new File(ijRoot, "update").isDirectory());
installer.moveUpdatedIntoPlace();
assertFalse(new File(ijRoot, "update").exists());
}
protected void upload(final FilesCollection files) throws Exception {
upload(files, FilesCollection.DEFAULT_UPDATE_SITE);
}
protected void upload(final FilesCollection files, final String updateSite) throws Exception {
for (final FileObject file : files.toUpload())
assertEquals(updateSite, file.updateSite);
final FilesUploader uploader =
new FilesUploader(files, updateSite);
assertTrue(uploader.login());
uploader.upload(progress);
files.write();
}
protected FileObject[] makeList(final FilesCollection files) {
final List<FileObject> list = new ArrayList<FileObject>();
for (final FileObject object : files)
list.add(object);
return list.toArray(new FileObject[list.size()]);
}
protected static void assertStatus(final Status status,
final FilesCollection files, final String filename)
{
final FileObject file = files.get(filename);
assertStatus(status, file);
}
protected static void
assertStatus(final Status status, final FileObject file)
{
assertNotNull("Object " + file.getFilename(), file);
assertEquals("Status of " + file.getFilename(), status, file.getStatus());
}
protected static void assertAction(final Action action,
final FilesCollection files, final String filename)
{
assertAction(action, files.get(filename));
}
protected static void assertAction(final Action action,
final FileObject file)
{
assertNotNull("Object " + file, file);
assertEquals("Action of " + file.filename, action, file.getAction());
}
protected static void assertNotEqual(final Object object1,
final Object object2)
{
if (object1 == null) {
assertNotNull(object2);
}
else {
assertFalse(object1.equals(object2));
}
}
protected static void assertNotEqual(final long long1, final long long2) {
assertTrue(long1 != long2);
}
protected static void
assertCount(final int count, final Iterable<?> iterable)
{
assertEquals(count, count(iterable));
}
protected static int count(final Iterable<?> iterable) {
int count = 0;
for (@SuppressWarnings("unused")
final Object object : iterable)
{
count++;
}
return count;
}
protected static void print(final Iterable<?> iterable) {
System.err.println("{");
int count = 0;
for (final Object object : iterable) {
System.err.println("\t" +
++count +
": " +
object +
(object instanceof FileObject ? " = " +
((FileObject) object).getStatus() + "/" +
((FileObject) object).getAction() : ""));
}
System.err.println("}");
}
/**
* Create a temporary directory
*
* @param prefix the prefix as for {@link File#createTempFile(String, String)}
* @return the File object describing the directory
* @throws IOException
*/
protected static File createTempDirectory(final String prefix) throws IOException {
final File file = File.createTempFile(prefix, "");
file.delete();
file.mkdir();
return file;
}
/**
* Delete a directory recursively
*
* @param directory
* @return whether it succeeded (see also {@link File.#delete()})
*/
protected boolean rmRF(final File directory) {
if (directory == null) {
return true;
}
final File[] list = directory.listFiles();
if (list == null) {
return true;
}
for (final File file : list) {
if (file.isFile()) {
if (!file.delete()) {
return false;
}
}
else if (file.isDirectory()) {
if (!rmRF(file)) {
return false;
}
}
}
return directory.delete();
}
/**
* Change the mtime of a file
*
* @param file the file to touch
* @param timestamp the mtime as pseudo-long (YYYYMMDDhhmmss)
*/
protected void touch(final File file, final long timestamp) {
final long millis = Util.timestamp2millis(timestamp);
file.setLastModified(millis);
}
/**
* Write a trivial .jar file into the ijRoot
*
* @param name the name of the .jar file
* @return the File object for the .jar file
* @throws FileNotFoundException
* @throws IOException
*/
protected File writeJar(final String name) throws FileNotFoundException,
IOException
{
return writeJar(ijRoot, name, name, name);
}
/**
* Write a .jar file into the ijRoot
*
* @param name the name of the .jar file
* @param args a list of entry name / contents pairs
* @return the File object for the .jar file
* @throws FileNotFoundException
* @throws IOException
*/
protected File writeJar(final String name, final String... args)
throws FileNotFoundException, IOException
{
return writeJar(ijRoot, name, args);
}
/**
* Write a .jar file
*
* @param dir which directory to write into
* @param name the name of the .jar file
* @param args a list of entry name / contents pairs
* @return the File object for the .jar file
* @throws FileNotFoundException
* @throws IOException
*/
protected static File writeJar(final File dir, final String name,
final String... args) throws FileNotFoundException, IOException
{
final File file = new File(dir, name);
file.getParentFile().mkdirs();
final JarOutputStream jar = new JarOutputStream(new FileOutputStream(file));
for (int i = 0; i + 1 < args.length; i += 2) {
final JarEntry entry = new JarEntry(args[i]);
jar.putNextEntry(entry);
jar.write(args[i + 1].getBytes());
jar.closeEntry();
}
jar.close();
return file;
}
protected File writeJar(final String path, Class<?>... classes) throws FileNotFoundException, IOException {
return writeJar(new File(ijRoot, path), classes);
}
protected File writeJar(final File file, Class<?>... classes) throws FileNotFoundException, IOException {
file.getParentFile().mkdirs();
final byte[] buffer = new byte[32768];
final JarOutputStream jar = new JarOutputStream(new FileOutputStream(file));
for (int i = 0; i < classes.length; i++) {
final String path = classes[i].getName().replace('.', '/') + ".class";
final JarEntry entry = new JarEntry(path);
jar.putNextEntry(entry);
final InputStream in = classes[i].getResourceAsStream("/" + path);
for (;;) {
int count = in.read(buffer);
if (count < 0)
break;
jar.write(buffer, 0, count);
}
in.close();
jar.closeEntry();
}
jar.close();
return file;
}
/**
* Write a .gz file
*
* @param dir The directory into which to write
* @param name The file name
* @param content The contents to write
* @return the File object for the file that was written to
* @throws IOException
* @throws FileNotFoundException
*/
protected static File writeGZippedFile(final File dir, final String name,
final String content) throws FileNotFoundException, IOException
{
final File file = new File(dir, name);
file.getParentFile().mkdirs();
writeStream(new GZIPOutputStream(new FileOutputStream(file)), content, true);
return file;
}
/**
* Write a text file into the ijRoot
*
* @param name The file name
* @return the File object for the file that was written to
* @throws IOException
* @throws FileNotFoundException
*/
protected File writeFile(final String name) throws FileNotFoundException,
IOException
{
return writeFile(new File(ijRoot, name), name);
}
/**
* Write a text file into the ijRoot
*
* @param name The file name
* @param content The contents to write
* @return the File object for the file that was written to
* @throws IOException
* @throws FileNotFoundException
*/
protected File writeFile(final String name, final String content)
throws FileNotFoundException, IOException
{
return writeFile(ijRoot, name, content);
}
/**
* Write a text file
*
* @param dir The directory into which to write
* @param name The file name
* @param content The contents to write
* @return the File object for the file that was written to
* @throws IOException
* @throws FileNotFoundException
*/
protected static File writeFile(final File dir, final String name,
final String content) throws FileNotFoundException, IOException
{
final File file = new File(dir, name);
file.getParentFile().mkdirs();
return writeFile(file, content);
}
/**
* Write a text file
*
* @param file The file into which to write
* @param content The contents to write
* @return the File object for the file that was written to
* @throws IOException
* @throws FileNotFoundException
*/
protected static File writeFile(final File file, final String content)
throws FileNotFoundException, IOException
{
final File dir = file.getParentFile();
if (!dir.isDirectory()) dir.mkdirs();
final String name = file.getName();
if (name.endsWith(".jar")) return writeJar(dir, name, name, name);
writeStream(new FileOutputStream(file), content, true);
return file;
}
/**
* Write a string
*
* @param out where to write to
* @param content what to write
* @param close whether to close the stream
*/
protected static void writeStream(final OutputStream out, final String content,
final boolean close)
{
final PrintWriter writer = new PrintWriter(out);
writer.println(content);
if (close) {
writer.close();
}
}
/**
* Read a gzip'ed stream and return what we got as a String
*
* @param in the input stream as compressed by gzip
* @return the contents, as a String
* @throws IOException
*/
protected String readGzippedStream(final InputStream in) throws IOException {
return readStream(new GZIPInputStream(in));
}
/**
* Read a stream and return what we got as a String
*
* @param in the input stream
* @return the contents, as a String
* @throws IOException
*/
protected String readStream(final InputStream in) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] buffer = new byte[16384];
for (;;) {
int count = in.read(buffer);
if (count < 0) break;
out.write(buffer, 0, count);
}
in.close();
out.close();
return out.toString();
}
}
|
package minibot;
import basestation.BaseStation;
import basestation.bot.commands.FourWheelMovement;
import basestation.bot.connection.IceConnection;
import basestation.bot.connection.TCPConnection;
import basestation.bot.robot.Bot;
import basestation.bot.robot.minibot.MiniBot;
import basestation.bot.robot.modbot.ModBot;
import basestation.vision.OverheadVisionSystem;
import basestation.vision.VisionObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.jbox2d.dynamics.World;
import simulator.Simulator;
import simulator.physics.PhysicalObject;
import simulator.simbot.ColorIntensitySensor;
import simulator.simbot.SimBotConnection;
import simulator.simbot.SimBotSensorCenter;
import spark.route.RouteOverview;
import java.util.List;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Collection;
import java.io.*;
import simulator.baseinterface.SimulatorVisionSystem;
import simulator.simbot.SimBot;
import xboxhandler.XboxControllerDriver;
import static spark.Spark.*;
/**
* HTTP connections for modbot GUI
* <p>
* Used for modbot to control and use the GUI while connecting to basestation.
* */
public class BaseHTTPInterface {
// Temp config settings
public static final boolean OVERHEAD_VISION = true;
private static XboxControllerDriver xboxControllerDriver;
public static void main(String[] args) {
// Spark configuration
port(8080);
staticFiles.location("/public");
RouteOverview.enableRouteOverview("/");
//create new visionsystem and simulator instances
SimulatorVisionSystem simvs;
Simulator simulator = new Simulator();
// Show exceptions
exception(Exception.class, (exception,request,response) -> {
exception.printStackTrace();
response.status(500);
response.body("oops");
});
// Global objects
JsonParser jsonParser = new JsonParser();
Gson gson = new Gson();
if (OVERHEAD_VISION) {
OverheadVisionSystem ovs = new OverheadVisionSystem();
BaseStation.getInstance().getVisionManager().addVisionSystem(ovs);
simvs = simulator.getVisionSystem();
BaseStation.getInstance().getVisionManager().addVisionSystem(simvs);
}
// Routes
/* add a new bot from the gui*/
post("/addBot", (req,res) -> {
String body = req.body();
JsonObject addInfo = jsonParser.parse(body).getAsJsonObject(); // gets (ip, port) from js
/* storing json objects into actual variables */
String ip = addInfo.get("ip").getAsString();
int port = addInfo.get("port").getAsInt();
String name = addInfo.get("name").getAsString();
String type = addInfo.get("type").getAsString(); //differentiate between modbot and minibot
/* new modbot is created to add */
Bot newBot;
if(type.equals("modbot")) {
IceConnection ice = new IceConnection(ip, port);
newBot = new ModBot(ice, name);
} else if(type.equals("minibot")) {
TCPConnection c = new TCPConnection(ip, port);
newBot = new MiniBot(c, name);
}
else {
SimBotConnection sbc = new SimBotConnection();
SimBot simbot;
simbot = new SimBot(sbc, name, 50, simulator.getWorld(), 0.0f,
0.0f, 1f, 3.6f, 0, true);
newBot = simbot;
simulator.importPhysicalObject(simbot.getMyPhysicalObject());
// Color sensor TODO put somewhere nice
ColorIntensitySensor colorSensorL = new ColorIntensitySensor((SimBotSensorCenter) simbot.getSensorCenter(),"right",simbot, 5);
ColorIntensitySensor colorSensorR = new ColorIntensitySensor((SimBotSensorCenter) simbot.getSensorCenter(),"left",simbot, -5);
ColorIntensitySensor colorSensorM = new ColorIntensitySensor((SimBotSensorCenter) simbot.getSensorCenter(),"center",simbot, 0);
}
return BaseStation.getInstance().getBotManager().addBot(newBot);
});
/**
* POST /addScenario starts a simulation with the scenario from the
* scenario viewer in the gui
*
* @apiParam scenario a string representing a list of JSON scenario
* objects, which consist of obstacles and bot(s)
* @return the scenario json if it was successfully added
*/
post("/addScenario", (req,res) -> {
String body = req.body();
simulator.resetWorld();
Collection<String> botsnames = BaseStation.getInstance()
.getBotManager()
.getAllTrackedBotsNames();
for (String name :botsnames){
BaseStation.getInstance().getBotManager().removeBotByName(name);
}
JsonObject scenario = jsonParser.parse(body).getAsJsonObject();
String scenarioBody = scenario.get("scenario").getAsString();
JsonArray addInfo = jsonParser.parse(scenarioBody).getAsJsonArray();
for (JsonElement je : addInfo) {
String type = je.getAsJsonObject().get("type").getAsString();
int angle = je.getAsJsonObject().get("angle").getAsInt();
int[] position = gson.fromJson(je.getAsJsonObject().get("position")
.getAsString(),int[].class);
String name = Integer.toString(angle)
+ Arrays.toString(position);
//for scenario obstacles
if (!type.equals("simulator.simbot")){
int size = je.getAsJsonObject().get("size").getAsInt();
PhysicalObject po = new PhysicalObject(name, 100,
simulator.getWorld(), (float)position[0],
(float)position[1], size, angle);
simulator.importPhysicalObject(po);
}
//for bots listed in scenario
else {
Bot newBot;
name = "Simbot"+name;
SimBotConnection sbc = new SimBotConnection();
SimBot simbot;
simbot = new SimBot(sbc, name, 50, simulator.getWorld(), 0.0f,
0.0f, (float) position[0], (float)
position[1], angle, true);
newBot = simbot;
simulator.importPhysicalObject(simbot.getMyPhysicalObject());
// Color sensor TODO put somewhere nice
// ColorIntensitySensor colorSensorL = new ColorIntensitySensor((SimBotSensorCenter) simbot.getSensorCenter(),"right",simbot, 5);
// ColorIntensitySensor colorSensorR = new ColorIntensitySensor((SimBotSensorCenter) simbot.getSensorCenter(),"left",simbot, -5);
// ColorIntensitySensor colorSensorM = new ColorIntensitySensor((SimBotSensorCenter) simbot.getSensorCenter(),"center",simbot, 0);
BaseStation.getInstance().getBotManager().addBot(newBot);
}
}
return addInfo;
});
/**
* POST /saveScenario saves the scenario currently loaded as a txt
* file with the specified name
*
* @apiParam scenario a string representing a list of JSON scenario
* objects, which consist of obstacles and bot(s)
* @apiParam name the name the new scenario txt file
* @return the name of the file if it was successfully saved
*/
post("/saveScenario", (req,res) -> {
String body = req.body();
JsonObject scenario = jsonParser.parse(body).getAsJsonObject();
String scenarioBody = scenario.get("scenario").getAsString();
String fileName = scenario.get("name").getAsString();
//writing new scenario file
File file = new File
("cs-minibot-platform-src/src/main/resources" +
"/public/scenario/"+fileName+".txt");
OutputStream out = new FileOutputStream(file);
FileWriter writer = new FileWriter(file, false);
BufferedWriter bwriter = new BufferedWriter(writer);
bwriter.write(scenarioBody);
bwriter.close();
out.close();
return fileName;
});
/**
* POST /loadScenario loads a scenario into the scenario viewer from a
* txt scenario file with the specified name; does not add scenario
* to the world or start a simulation
*
* @apiParam name the name the scenario txt file to load
* @return the JSON of the scenario if it was loaded successfully
*/
post("/loadScenario", (req,res) -> {
String body = req.body();
JsonObject scenario = jsonParser.parse(body).getAsJsonObject();
String fileName = scenario.get("name").getAsString();
String scenarioData = "";
//loading scenario file
File file = new File
("cs-minibot-platform-src/src/main/resources" +
"/public/scenario/"+fileName+".txt");
FileReader fr= new FileReader(file);
BufferedReader br= new BufferedReader(fr);
String line = br.readLine();
while (line!=null){
scenarioData+=line;
line = br.readLine();
}
br.close();
return scenarioData;
});
/*send commands to the selected bot*/
post("/commandBot", (req,res) -> {
System.out.println("post to command bot called");
String body = req.body();
JsonObject commandInfo = jsonParser.parse(body).getAsJsonObject();
// gets (botID, fl, fr, bl, br) from json
String botName = commandInfo.get("name").getAsString();
int fl = commandInfo.get("fl").getAsInt();
int fr = commandInfo.get("fr").getAsInt();
int bl = commandInfo.get("bl").getAsInt();
int br = commandInfo.get("br").getAsInt();
// Forward the command to the bot
Bot myBot = BaseStation.getInstance().getBotManager()
.getBotByName(botName).get();
FourWheelMovement fwmCommandCenter = (FourWheelMovement) myBot.getCommandCenter();
return fwmCommandCenter.setWheelPower(fl,fr,bl,br);
});
/*remove the selected bot - not sure if still functional*/
post("/removeBot", (req,res) -> {
String body = req.body();
JsonObject removeInfo = jsonParser.parse(body).getAsJsonObject();
String name = removeInfo.get("name").getAsString();
return BaseStation.getInstance().getBotManager().removeBotByName(name);
});
/**
* GET /sendScript sends script to the bot identified by botName
*
* @apiParam name the name of the bot
* @apiParam script the full string containing the script
* @return true if the script sending should be successful
*/
post("/sendScript", (req,res) -> {
String body = req.body();
JsonObject commandInfo = jsonParser.parse(body).getAsJsonObject();
/* storing json objects into actual variables */
String name = commandInfo.get("name").getAsString();
String script = commandInfo.get("script").getAsString();
Bot receiver = BaseStation.getInstance()
.getBotManager()
.getBotByName(name)
.orElseThrow(NoSuchElementException::new);
if (receiver instanceof SimBot)
((SimBot)BaseStation.getInstance()
.getBotManager()
.getBotByName(name)
.orElseThrow(NoSuchElementException::new)).resetServer();
return BaseStation.getInstance()
.getBotManager()
.getBotByName(name)
.orElseThrow(NoSuchElementException::new)
.getCommandCenter().sendKV("SCRIPT",script);
});
get("/trackedBots", (req, res) -> {
Collection<Bot> allBots = BaseStation.getInstance().getBotManager().getAllTrackedBots();
return gson.toJson(allBots);
});
/**
Collects updated JSON objects in the form:
{ "x": vo.coord.x,
"y": vo.coord.y,
"angle": vo.coord.getThetaOrZero(),
"id": vo.id
}
*/
get("/updateloc", (req, res) -> {
// Locations of all active bots
List<VisionObject> vol = BaseStation
.getInstance()
.getVisionManager()
.getAllLocationData();
JsonArray respData = new JsonArray();
for (VisionObject vo : vol) {
JsonObject jo = new JsonObject();
jo.addProperty("x", vo.coord.x);
jo.addProperty("y", vo.coord.y);
jo.addProperty("angle", vo.coord.getThetaOrZero());
jo.addProperty("id", vo.vid);
jo.addProperty("size",vo.size);
respData.add(jo);
}
return respData;
});
post("/discoverBots", (req, res) -> {
return gson.toJson(BaseStation.getInstance().getBotManager().getAllDiscoveredBots());
});
post("/runXbox", (req, res) -> {
String body = req.body();
JsonObject commandInfo = jsonParser.parse(body).getAsJsonObject();
/* storing json objects into actual variables */
String name = commandInfo.get("name").getAsString();
// if this is called for the first time, initialize the Xbox
// Controller
if (xboxControllerDriver == null) {
// xbox not initialized, initialize it first
xboxControllerDriver = new XboxControllerDriver();
// xboxControllerDriver != null
if (xboxControllerDriver.xboxIsConnected()) {
// xbox is connected
// run the driver
xboxControllerDriver.getMbXboxEventHandler().setBotName
(name);
xboxControllerDriver.runDriver();
return true;
} else {
// xbox is not connected, stop the driver
stopXboxDriver();
return false;
}
} else {
// xboxControllerDriver != null -- xbox initialized already
if (xboxControllerDriver.xboxIsConnected()) {
// xbox is connected
// should be already listening in this case
// just set the new name
xboxControllerDriver.getMbXboxEventHandler().setBotName
(name);
return true;
} else {
// xbox is not connected, stop the driver
stopXboxDriver();
return false;
}
}
});
post("/stopXbox", (req, res) -> {
// received stop command, stop the driver
try{
stopXboxDriver();
// no error
return true;
} catch (Exception e) {
// error encountered
return false;
}
});
}
/**
* Tells the Xbox Controller Driver to stop
* Acts as a middleman between this interface and the driver on stopping
*/
private static void stopXboxDriver() {
if (xboxControllerDriver != null) {
// xbox is currently initialized
xboxControllerDriver.stopDriver();
xboxControllerDriver = null;
}
// xboxControllerDriver == null
// might get this request from stopXbox HTTP post
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.