lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
mit
|
7c63b62770e02a1d352a9098799e72174bec4fa2
| 0
|
ashishmgupta/appsensor,ProZachJ/appsensor,ProZachJ/appsensor,timothy22000/appsensor,ProZachJ/appsensor,timothy22000/appsensor,mahmoodm2/appsensor,dscrobonia/appsensor,dscrobonia/appsensor,jtmelton/appsensor,sanjaygouri/appsensor,jtmelton/appsensor,sanjaygouri/appsensor,dscrobonia/appsensor,sims143/appsensor,ksmaheshkumar/appsensor,mahmoodm2/appsensor,ProZachJ/appsensor,ashishmgupta/appsensor,mahmoodm2/appsensor,timothy22000/appsensor,dscrobonia/appsensor,mahmoodm2/appsensor,jtmelton/appsensor,ksmaheshkumar/appsensor,jtmelton/appsensor,ProZachJ/appsensor,mahmoodm2/appsensor,sims143/appsensor,jtmelton/appsensor,dscrobonia/appsensor,timothy22000/appsensor,ProZachJ/appsensor,ashishmgupta/appsensor,dscrobonia/appsensor,jtmelton/appsensor
|
package org.owasp.appsensor.response;
import org.owasp.appsensor.Response;
/**
* The ResponseHandler is executed when a {@link Response} needs to be executed.
* The ResponseHandler is used by the client application, or possibly the server
* side in a local configuration.
*
* @author John Melton (jtmelton@gmail.com) http://www.jtmelton.com/
*/
public interface ResponseHandler {
/** provide increased logging for this specific user */
public final static String LOG = "log";
public final static String LOGOUT = "logout";
public final static String DISABLE_USER = "disableUser";
public final static String DISABLE_COMPONENT_FOR_SPECIFIC_USER = "disableComponentForSpecificUser";
public final static String DISABLE_COMPONENT_FOR_ALL_USERS = "disableComponentForAllUsers";
/**
* The handle method is called when a given response should be processed.
* It is the responsibility of the handle method to actually execute the intented response.
*
* @param response Response object that should be processed
*/
public void handle(Response response);
}
|
appsensor-core/src/main/java/org/owasp/appsensor/response/ResponseHandler.java
|
package org.owasp.appsensor.response;
import org.owasp.appsensor.Response;
/**
* The ResponseHandler is executed when a {@link Response} needs to be executed.
* The ResponseHandler is used by the client application, or possibly the server
* side in a local configuration.
*
* @author John Melton (jtmelton@gmail.com) http://www.jtmelton.com/
*/
public interface ResponseHandler {
public final static String LOG = "log";
public final static String LOGOUT = "logout";
public final static String DISABLE_USER = "disableUser";
public final static String DISABLE_COMPONENT_FOR_SPECIFIC_USER = "disableComponentForSpecificUser";
public final static String DISABLE_COMPONENT_FOR_ALL_USERS = "disableComponentForAllUsers";
/**
* The handle method is called when a given response should be processed.
* It is the responsibility of the handle method to actually execute the intented response.
*
* @param response Response object that should be processed
*/
public void handle(Response response);
}
|
adding javadoc
|
appsensor-core/src/main/java/org/owasp/appsensor/response/ResponseHandler.java
|
adding javadoc
|
|
Java
|
mit
|
68ff1f968320457cbdfcfaf30b0290f2d23e8110
| 0
|
ElodieCarpentier/Mr-Kitten,ElodieCarpentier/MrKitten_visual,ElodieCarpentier/MrKitten_visual,ElodieCarpentier/MrKitten_visual,ElodieCarpentier/Mr-Kitten,ElodieCarpentier/Mr-Kitten
|
import java.util.*;
import mr_kitten.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mr_kitten;
/**
* This class is the main class of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. Users
* can walk around some scenery. That's all. It should really be extended
* to make it more interesting!
*
* To play this game, create an instance of this class and call the "play"
* method.
*
* This main class creates and initialises all the others: it creates all
* rooms, creates the parser and starts the game. It also evaluates and
* executes the commands that the parser returns.
*
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
*/
public class Game
{
private Parser parser;
private Room currentRoom;
/**
* Create the game and initialise its internal map.
*/
public Game()
{
createRooms();
createItems();
Players MrKitten = new Players("Mr.Kitten");
parser = new Parser();
}
/**
* Create all the rooms and link their exits together.
*/
private void createRooms()
{
//Room outside, theatre, pub, lab, office;
Room kitchen,livingRoom,bedroom,street1,street2,sewer,petshop,theGreatDescent,dory,theFishPalace;
Room tavernSanRicardo,starWars,theCloset,theEnd;
kitchen = new Room ("are in the Kitchen of the Master's house");
livingRoom = new Room ("are in the Living room of the Master's house");
bedroom = new Room ("are in the Bedroom of the Master's house");
street1 = new Room ("are in the Street near the entrance of the house");
street2 = new Room ("are in the Street near the Petshop");
sewer = new Room ("are in the Sewer under the streets");
petshop = new Room ("are in the Petshop");
theGreatDescent = new Room ("are going deep down under water");
dory = new Room ("are with Dory the great fish");
theFishPalace = new Room ("are in the Fish Palace");
tavernSanRicardo = new Room ("are in the magnificient Tavern Of San Ricardo");
starWars = new Room ("are in a Galaxy far far away...");
theCloset = new Room ("are ready to fight with lions");
theEnd = new Room ("did it, you did it, Yeah!");
Door door1 = new Door(livingRoom); kitchen.addExit("east", door1);
Door door2 = new Door (bedroom); livingRoom.addExit("east",door2);
//Door door3 = new Door (street1); livingRoom.addExit("south",door3);
Item keyLivingStreet = new Item("home key", "this key opens the door to exit the master's house",0);
LockedDoor door3 = new LockedDoor (keyLivingStreet, street1); livingRoom.addExit("south",door3);
Door door4 = new Door (kitchen); livingRoom.addExit("west",door4);
Door door5 = new Door (livingRoom);bedroom.addExit("west",door5);
Door door6 = new Door (livingRoom); street1.addExit("north",door6);
Door door7 = new Door (street2);street1.addExit("east",door7);
Door door8 = new Door (sewer);street1.addExit("down",door8);
Door door9 = new Door (petshop);street2.addExit("south",door9);
Door door10 = new Door (street1);street2.addExit("west",door10);
Door door11 = new Door (sewer);street2.addExit("down",door11);
Door door12 = new Door (street2);sewer.addExit("up",door12);
Door door13 = new Door (street2);petshop.addExit("north",door13);
Door door14 = new Door (theGreatDescent);petshop.addExit("down", door14);
Door door15 = new Door (dory);theGreatDescent.addExit("west",door15);
Door door16 = new Door (petshop);theGreatDescent.addExit("up",door16);
Door door17 = new Door (theFishPalace);theGreatDescent.addExit("down",door17);
Door door18 = new Door (theGreatDescent);dory.addExit("east",door18);
Door door19 = new Door (tavernSanRicardo);theFishPalace.addExit("south", door19);
Door door20 = new Door (theGreatDescent);theFishPalace.addExit("up",door20);
//Door door21 = new Door (theFishPalace);tavernSanRicardo.addExit("north", door21);
Item keyFishTavern = new Item ("blue key","This key opens the door between the fish palace and the San Ricardo tavern",0);
LockedDoor door21 = new LockedDoor (keyFishTavern, theFishPalace);tavernSanRicardo.addExit("north", door21);
Door door22 = new Door (starWars);tavernSanRicardo.addExit("up", door22);
Door door23 = new Door (theCloset);starWars.addExit("east",door23);
Door door24 = new Door (tavernSanRicardo);starWars.addExit("down",door24);
Door door25 = new Door (theEnd);theCloset.addExit("south", door25);
Door door26 = new Door (starWars);theCloset.addExit("west",door26);
currentRoom = livingRoom; // start game in master's house
}
/*
* Create all the items in the game
*/
private void createItems()
{
Item potion = new Item ("potion","It's nice and warm",1);
Item jaw = new Item ("jaw","It's sharp and ready",5);
Item superPiss = new Item ("superPiss","Wow it's dirty",8);
}
/**
* Main play routine. Loops until end of play.
*/
public void play()
{
printWelcome();
// Enter the main command loop. Here we repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
System.out.println("Thank you for playing. Good bye.");
}
/**
* Print out the opening message for the player.
*/
private void printWelcome()
{
System.out.println();
System.out.println("Welcome to the World of Zuul!");
System.out.println("World of Zuul is a new, incredibly boring adventure game.");
System.out.println("Type 'help' if you need help.");
System.out.println();
System.out.println("You are " + currentRoom.getDescription());
currentRoom.printExits();
}
/**
* Given a command, process (that is: execute) the command.
* @param command The command to be processed.
* @return true If the command ends the game, false otherwise.
*/
private boolean processCommand(Command command)
{
boolean wantToQuit = false;
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return false;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("help"))
printHelp();
else if (commandWord.equals("go"))
goRoom(command);
else if (commandWord.equals("quit"))
wantToQuit = quit(command);
else if (commandWord.equals("look"))
lookRoom(command);
else if (commandWord.equals("fight"))
fightPeople (command);
return wantToQuit;
}
// implementations of user commands:
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/
private void printHelp()
{
System.out.println("You are lost. You are alone. You wander");
System.out.println("around at the university.");
System.out.println();
System.out.println("Your command words are:");
System.out.println(" go quit help");
}
/**
* Try to go to one direction. If there is an exit, enter
* the new room, otherwise print an error message.
*/
private void goRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Go where?");
return;
}
String direction = command.getSecondWord();
// Try to leave current room.
Door nextDoor = null;
nextDoor = currentRoom.getNextRoom(direction);
if (nextDoor == null) {
System.out.println("There is no door!");
}
else {
Room nextRoom = nextDoor.getRoom();
currentRoom = nextRoom;
System.out.println("You " + currentRoom.getDescription());
currentRoom.printExits();
}
}
/**
* "Quit" was entered. Check the rest of the command to see
* whether we really quit the game.
* @return true, if this command quits the game, false otherwise.
*/
private boolean quit(Command command)
{
if(command.hasSecondWord()) {
System.out.println("Quit what?");
return false;
}
else {
return true; // signal that we want to quit
}
}
/*
* You can look into the room to see the description of the room or to describe an item
*/
private void lookRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we describe the current room
System.out.println("You " + currentRoom.getDescription());
currentRoom.printExits();
return;
}
else {
String itemName = command.getSecondWord();
Players.getItemDescription(itemName);
return;
}
}
/*
* You can fight peoples in the current room
*/
private void fightPeople(Command command)
{
ennemi= "Dory"; // REGARDER LA DESCRIPTION DES ROOM POUR VOIR QUI EST LA
int ennemiHP = 25; // REGARDER LA DESCRIPTION DES ACTEURS
int ennemiAD = 10; // REGARDER LA DESCRIPTION DES ACTEURS
int MrKittenHP = 120; // REGARDER LA DESCRIPTION DE MR KITTEN
System.out.println ("Mr Kitten VS "+ ennemi);
while (MrKittenHP>0 || ennemiHP>0){
int intEnnemiHP = ennemiHP;
while(intEnnemiHP == ennemiHP) {
System.out.println (" What would you like ? attack / special attack / items");
intEnnemiHP = fightCommand(command,ennemiHP);
}
ennemiHP = intEnnemiHP;
Random nbRd = new Random();
int nextnb = nbRd.nextInt(ennemiAD)+1;
MrKittenHP = MrKittenHP - nextnb;
}
}
/**
* Give a command to fight
*/
private int fightCommand(Command command, int ennemiHP)
{
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return ennemiHP;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("attack")){
ennemiHP = attack(ennemiHP);
}
else if (commandWord.equals("special attack")){
ennemiHP = specialAttack(ennemiHP);
}
else if (commandWord.equals("items")){
ennemiHP = items(ennemiHP);
}
return ennemiHP;
}
/**
* Reduce ennemi HP by a normal attack
*/
private int attack (int ennemiHP)
{
Random nbRd = new Random();
int nextnb = nbRd.nextInt(7)+1;
ennemiHP = ennemiHP - nextnb;
return ennemiHP;
}
/**
* Choose a special attack
*/
private int specialAttack(int ennemiHP)
{
System.out.println(" What would you like ? ");
for (int i = 0;i<inventory.size();i++){
Item currentItem = inventory.get(i);
if (currentItem.getName().equals("superPiss")){
System.out.println(" superPiss ");
}
if (currentItem.getName().equals("superBite")){
System.out.println(" superBite ");
}
if (currentItem.getName().equals("laserTail")){
System.out.println(" laserTail ");
}
}
ennemiHP = specialCommand(command,ennemiHP);
return ennemiHP;
}
/**
* Reduce ennemi HP by a special attack
*/
private int specialCommand(Command command, int ennemiHP)
{
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return ennemiHP;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("superPiss")){
ennemiHP = ennemiHP - 15;
} else if (commandWord.equals("superBite")){
ennemiHP = ennemiHP - 20;
} else if (commandWord.equals("laserTail")){
ennemiHP = ennemiHP - 25;
}
return ennemiHP;
}
}
|
src/mr_kitten/Game.java
|
import java.util.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mr_kitten;
/**
* This class is the main class of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. Users
* can walk around some scenery. That's all. It should really be extended
* to make it more interesting!
*
* To play this game, create an instance of this class and call the "play"
* method.
*
* This main class creates and initialises all the others: it creates all
* rooms, creates the parser and starts the game. It also evaluates and
* executes the commands that the parser returns.
*
* @author Michael Kolling and David J. Barnes
* @version 2006.03.30
*/
public class Game
{
private Parser parser;
private Room currentRoom;
/**
* Create the game and initialise its internal map.
*/
public Game()
{
createRooms();
createItems();
Players MrKitten = new Players("Mr.Kitten");
parser = new Parser();
}
/**
* Create all the rooms and link their exits together.
*/
private void createRooms()
{
//Room outside, theatre, pub, lab, office;
Room kitchen,livingRoom,bedroom,street1,street2,sewer,petshop,theGreatDescent,dory,theFishPalace;
Room tavernSanRicardo,starWars,theCloset,theEnd;
kitchen = new Room ("are in the Kitchen of the Master's house");
livingRoom = new Room ("are in the Living room of the Master's house");
bedroom = new Room ("are in the Bedroom of the Master's house");
street1 = new Room ("are in the Street near the entrance of the house");
street2 = new Room ("are in the Street near the Petshop");
sewer = new Room ("are in the Sewer under the streets");
petshop = new Room ("are in the Petshop");
theGreatDescent = new Room ("are going deep down under water");
dory = new Room ("are with Dory the great fish");
theFishPalace = new Room ("are in the Fish Palace");
tavernSanRicardo = new Room ("are in the magnificient Tavern Of San Ricardo");
starWars = new Room ("are in a Galaxy far far away...");
theCloset = new Room ("are ready to fight with lions");
theEnd = new Room ("did it, you did it, Yeah!");
Door door1 = new Door(livingRoom); kitchen.addExit("east", door1);
Door door2 = new Door (bedroom); livingRoom.addExit("east",door2);
//Door door3 = new Door (street1); livingRoom.addExit("south",door3);
Item keyLivingStreet = new Item("home key", "this key opens the door to exit the master's house",0);
LockedDoor door3 = new LockedDoor (keyLivingStreet, street1); livingRoom.addExit("south",door3);
Door door4 = new Door (kitchen); livingRoom.addExit("west",door4);
Door door5 = new Door (livingRoom);bedroom.addExit("west",door5);
Door door6 = new Door (livingRoom); street1.addExit("north",door6);
Door door7 = new Door (street2);street1.addExit("east",door7);
Door door8 = new Door (sewer);street1.addExit("down",door8);
Door door9 = new Door (petshop);street2.addExit("south",door9);
Door door10 = new Door (street1);street2.addExit("west",door10);
Door door11 = new Door (sewer);street2.addExit("down",door11);
Door door12 = new Door (street2);sewer.addExit("up",door12);
Door door13 = new Door (street2);petshop.addExit("north",door13);
Door door14 = new Door (theGreatDescent);petshop.addExit("down", door14);
Door door15 = new Door (dory);theGreatDescent.addExit("west",door15);
Door door16 = new Door (petshop);theGreatDescent.addExit("up",door16);
Door door17 = new Door (theFishPalace);theGreatDescent.addExit("down",door17);
Door door18 = new Door (theGreatDescent);dory.addExit("east",door18);
Door door19 = new Door (tavernSanRicardo);theFishPalace.addExit("south", door19);
Door door20 = new Door (theGreatDescent);theFishPalace.addExit("up",door20);
//Door door21 = new Door (theFishPalace);tavernSanRicardo.addExit("north", door21);
Item keyFishTavern = new Item ("blue key","This key opens the door between the fish palace and the San Ricardo tavern",0);
LockedDoor door21 = new LockedDoor (keyFishTavern, theFishPalace);tavernSanRicardo.addExit("north", door21);
Door door22 = new Door (starWars);tavernSanRicardo.addExit("up", door22);
Door door23 = new Door (theCloset);starWars.addExit("east",door23);
Door door24 = new Door (tavernSanRicardo);starWars.addExit("down",door24);
Door door25 = new Door (theEnd);theCloset.addExit("south", door25);
Door door26 = new Door (starWars);theCloset.addExit("west",door26);
currentRoom = livingRoom; // start game in master's house
}
/*
* Create all the items in the game
*/
private void createItems()
{
Item potion = new Item ("potion","It's nice and warm",1);
Item jaw = new Item ("jaw","It's sharp and ready",5);
Item superPiss = new Item ("superPiss","Wow it's dirty",8);
}
/**
* Main play routine. Loops until end of play.
*/
public void play()
{
printWelcome();
// Enter the main command loop. Here we repeatedly read commands and
// execute them until the game is over.
boolean finished = false;
while (! finished) {
Command command = parser.getCommand();
finished = processCommand(command);
}
System.out.println("Thank you for playing. Good bye.");
}
/**
* Print out the opening message for the player.
*/
private void printWelcome()
{
System.out.println();
System.out.println("Welcome to the World of Zuul!");
System.out.println("World of Zuul is a new, incredibly boring adventure game.");
System.out.println("Type 'help' if you need help.");
System.out.println();
System.out.println("You are " + currentRoom.getDescription());
currentRoom.printExits();
}
/**
* Given a command, process (that is: execute) the command.
* @param command The command to be processed.
* @return true If the command ends the game, false otherwise.
*/
private boolean processCommand(Command command)
{
boolean wantToQuit = false;
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return false;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("help"))
printHelp();
else if (commandWord.equals("go"))
goRoom(command);
else if (commandWord.equals("quit"))
wantToQuit = quit(command);
else if (commandWord.equals("look"))
lookRoom(command);
else if (commandWord.equals("fight"))
fightPeople (command);
return wantToQuit;
}
// implementations of user commands:
/**
* Print out some help information.
* Here we print some stupid, cryptic message and a list of the
* command words.
*/
private void printHelp()
{
System.out.println("You are lost. You are alone. You wander");
System.out.println("around at the university.");
System.out.println();
System.out.println("Your command words are:");
System.out.println(" go quit help");
}
/**
* Try to go to one direction. If there is an exit, enter
* the new room, otherwise print an error message.
*/
private void goRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Go where?");
return;
}
String direction = command.getSecondWord();
// Try to leave current room.
Door nextDoor = null;
nextDoor = currentRoom.getNextRoom(direction);
if (nextDoor == null) {
System.out.println("There is no door!");
}
else {
Room nextRoom = nextDoor.getRoom();
currentRoom = nextRoom;
System.out.println("You " + currentRoom.getDescription());
currentRoom.printExits();
}
}
/**
* "Quit" was entered. Check the rest of the command to see
* whether we really quit the game.
* @return true, if this command quits the game, false otherwise.
*/
private boolean quit(Command command)
{
if(command.hasSecondWord()) {
System.out.println("Quit what?");
return false;
}
else {
return true; // signal that we want to quit
}
}
/*
* You can look into the room to see the description of the room or to describe an item
*/
private void lookRoom(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we describe the current room
System.out.println("You " + currentRoom.getDescription());
currentRoom.printExits();
return;
}
else {
String itemName = command.getSecondWord();
Players.getItemDescription(itemName);
return;
}
}
/*
* You can fight peoples in the current room
*/
private void fightPeople(Command command)
{
ennemi= "Dory"; // REGARDER LA DESCRIPTION DES ROOM POUR VOIR QUI EST LA
int ennemiHP = 25; // REGARDER LA DESCRIPTION DES ACTEURS
int ennemiAD = 10; // REGARDER LA DESCRIPTION DES ACTEURS
int MrKittenHP = 120; // REGARDER LA DESCRIPTION DE MR KITTEN
System.out.println ("Mr Kitten VS "+ ennemi);
while (MrKittenHP>0 || ennemiHP>0){
int intEnnemiHP = ennemiHP;
while(intEnnemiHP == ennemiHP) {
System.out.println (" What would you like ? attack / special attack / items");
intEnnemiHP = fightCommand(command,ennemiHP);
}
ennemiHP = intEnnemiHP;
Random nbRd = new Random();
int nextnb = nbRd.nextInt(ennemiAD)+1;
MrKittenHP = MrKittenHP - nextnb;
}
}
/**
* Give a command to fight
*/
private int fightCommand(Command command, int ennemiHP)
{
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return ennemiHP;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("attack")){
ennemiHP = attack(ennemiHP);
}
else if (commandWord.equals("special attack")){
ennemiHP = specialAttack(ennemiHP);
}
else if (commandWord.equals("items")){
ennemiHP = items(ennemiHP);
}
return ennemiHP;
}
/**
* Reduce ennemi HP by a normal attack
*/
private int attack (int ennemiHP)
{
Random nbRd = new Random();
int nextnb = nbRd.nextInt(7)+1;
ennemiHP = ennemiHP - nextnb;
return ennemiHP;
}
/**
* Choose a special attack
*/
private int specialAttack(int ennemiHP)
{
System.out.println(" What would you like ? ");
for (int i = 0;i<inventory.size();i++){
Item currentItem = inventory.get(i);
if (currentItem.getName().equals("superPiss")){
System.out.println(" superPiss ");
}
if (currentItem.getName().equals("superBite")){
System.out.println(" superBite ");
}
if (currentItem.getName().equals("laserTail")){
System.out.println(" laserTail ");
}
}
ennemiHP = specialCommand(command,ennemiHP);
return ennemiHP;
}
/**
* Reduce ennemi HP by a special attack
*/
private int specialCommand(Command command, int ennemiHP)
{
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return ennemiHP;
}
String commandWord = command.getCommandWord();
if (commandWord.equals("superPiss")){
ennemiHP = ennemiHP - 15;
} else if (commandWord.equals("superBite")){
ennemiHP = ennemiHP - 20;
} else if (commandWord.equals("laserTail")){
ennemiHP = ennemiHP - 25;
}
return ennemiHP;
}
}
|
Debug game test1
|
src/mr_kitten/Game.java
|
Debug game test1
|
|
Java
|
epl-1.0
|
2937a5a24ef802d49019271cc876fbd747000859
| 0
|
khatchad/Migrate-Skeletal-Implementation-to-Interface-Refactoring,khatchad/Java-8-Interface-Refactoring,khatchad/Migrate-Skeletal-Implementation-to-Interface-Refactoring
|
package edu.cuny.citytech.defaultrefactoring.ui.handlers;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import edu.cuny.citytech.defaultrefactoring.ui.plugins.MigrateSkeletalImplementationToInterfaceRefactoringPlugin;
import edu.cuny.citytech.defaultrefactoring.ui.wizards.MigrateSkeletalImplementationToInterfaceRefactoringWizard;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
*
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class MigrateSkeletalImplementationToInterfaceHandler extends AbstractHandler {
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection currentSelection = HandlerUtil.getCurrentSelectionChecked(event);
List<?> list = SelectionUtil.toList(currentSelection);
IMethod[] methods = list.stream().filter(e -> e instanceof IMethod).toArray(length -> new IMethod[length]);
IJavaProject[] javaProjects = list.stream().filter(e -> e instanceof IJavaProject)
.toArray(length -> new IJavaProject[length]);
try {
FileWriter writer = new FileWriter("SkeletalImplementation.csv");
String[] cvsHeader = { "Project Name", ",", "Package", ",", "CompilationUnit", ",", "Type Name", ",", "IsClass",
",", "IsInterface", ",", " IsAbstract", ",", "Interfaces Extended",",","number of extenders" };
for (int i = 0; i < cvsHeader.length; i++) {
writer.append(cvsHeader[i]);
}
writer.append('\n');
for (IJavaProject iJavaProject : javaProjects) {
IPackageFragment[] packageFragments = iJavaProject.getPackageFragments();
for (IPackageFragment iPackageFragment : packageFragments) {
ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
for (ICompilationUnit iCompilationUnit : compilationUnits) {
// printing the iCompilationUnit,
IType[] allTypes = iCompilationUnit.getAllTypes();
for (IType iType : allTypes) {
// print the info about the type.
writer.append(iJavaProject.getElementName());
writer.append(',');
writer.append(iPackageFragment.getElementName());
writer.append(',');
writer.append(iCompilationUnit.getElementName());
writer.append(',');
writer.append(iType.getElementName());
writer.append(',');
writer.append(iType.isClass() + "");
writer.append(',');
writer.append(iType.isInterface() + "");
writer.append(',');
writer.append(Flags.isAbstract(iType.getFlags()) + "");
writer.append(',');
// getting all the implemented interface
ITypeHierarchy typeHierarchie = iType.newTypeHierarchy(new NullProgressMonitor());
IType[] interfaceType = typeHierarchie.getAllSuperInterfaces(iType);
IType[] superClass = typeHierarchie.getAllSuperclasses(iType);
int interfaceCount = 0;
int superClassCount = 0;
for (IType InterfaceIType : interfaceType) {
interfaceCount++;
}
for (IType sclass : superClass) {
superClassCount++;
}
writer.append(interfaceCount+" ");
writer.append(',');
writer.append(superClassCount+" ");
// next row (done with this type).
writer.append('\n');
}
}
}
}
// closing the files after done writing
writer.flush();
writer.close();
} catch (JavaModelException | IOException fileException) {
fileException.printStackTrace();
}
getIMethods(event, methods);
return null;
}
private void getIMethods(ExecutionEvent event, IMethod[] methods) throws ExecutionException {
if (methods.length > 0) {
Shell shell = HandlerUtil.getActiveShellChecked(event);
HandlerUtil.getActiveWorkbenchWindowChecked(event).getWorkbench().getProgressService().showInDialog(shell,
Job.create("Migrate skeletal implementation to interface", monitor -> {
try {
MigrateSkeletalImplementationToInterfaceRefactoringWizard.startRefactoring(methods, shell,
monitor);
return Status.OK_STATUS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
return new Status(Status.ERROR, MigrateSkeletalImplementationToInterfaceRefactoringPlugin
.getDefault().getBundle().getSymbolicName(), "Failed to start refactoring.");
}
}));
}
}
}
|
edu.cuny.citytech.defaultrefactoring.ui/src/edu/cuny/citytech/defaultrefactoring/ui/handlers/MigrateSkeletalImplementationToInterfaceHandler.java
|
package edu.cuny.citytech.defaultrefactoring.ui.handlers;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import edu.cuny.citytech.defaultrefactoring.ui.plugins.MigrateSkeletalImplementationToInterfaceRefactoringPlugin;
import edu.cuny.citytech.defaultrefactoring.ui.wizards.MigrateSkeletalImplementationToInterfaceRefactoringWizard;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
*
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class MigrateSkeletalImplementationToInterfaceHandler extends AbstractHandler {
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection currentSelection = HandlerUtil.getCurrentSelectionChecked(event);
List<?> list = SelectionUtil.toList(currentSelection);
IMethod[] methods = list.stream().filter(e -> e instanceof IMethod).toArray(length -> new IMethod[length]);
IJavaProject[] javaProjects = list.stream().filter(e -> e instanceof IJavaProject)
.toArray(length -> new IJavaProject[length]);
try {
FileWriter writer = new FileWriter("InterfaceDefaultRefactoringTest.csv");
String[] cvsHeader = { "Project Name", ",", "Package", ",", "CompilationUnit", ",", "Type Name", ",", "IsClass",
",", "IsInterface", ",", " IsAbstract", ",", "Interfaces Extended" };
for (int i = 0; i < cvsHeader.length; i++) {
writer.append(cvsHeader[i]);
}
writer.append('\n');
for (IJavaProject iJavaProject : javaProjects) {
IPackageFragment[] packageFragments = iJavaProject.getPackageFragments();
for (IPackageFragment iPackageFragment : packageFragments) {
ICompilationUnit[] compilationUnits = iPackageFragment.getCompilationUnits();
for (ICompilationUnit iCompilationUnit : compilationUnits) {
// printing the iCompilationUnit,
IType[] allTypes = iCompilationUnit.getAllTypes();
for (IType iType : allTypes) {
// print the info about the type.
writer.append(iJavaProject.getElementName());
writer.append(',');
writer.append(iPackageFragment.getElementName());
writer.append(',');
writer.append(iCompilationUnit.getElementName());
writer.append(',');
writer.append(iType.getElementName());
writer.append(',');
writer.append(iType.isClass() + "");
writer.append(',');
writer.append(iType.isInterface() + "");
writer.append(',');
writer.append(Flags.isAbstract(iType.getFlags()) + "");
writer.append(',');
// getting all the implemented interface
ITypeHierarchy typeHierarchie = iType.newTypeHierarchy(new NullProgressMonitor());
IType[] interfaceType = typeHierarchie.getAllSuperInterfaces(iType);
int interfaceCount = 0;
for (IType InterfaceIType : interfaceType) {
interfaceCount++;
}
writer.append(interfaceCount+" ");
// next row (done with this type).
writer.append('\n');
}
}
}
}
// closing the files after done writing
writer.flush();
writer.close();
} catch (JavaModelException | IOException fileException) {
fileException.printStackTrace();
}
getIMethods(event, methods);
return null;
}
private void getIMethods(ExecutionEvent event, IMethod[] methods) throws ExecutionException {
if (methods.length > 0) {
Shell shell = HandlerUtil.getActiveShellChecked(event);
HandlerUtil.getActiveWorkbenchWindowChecked(event).getWorkbench().getProgressService().showInDialog(shell,
Job.create("Migrate skeletal implementation to interface", monitor -> {
try {
MigrateSkeletalImplementationToInterfaceRefactoringWizard.startRefactoring(methods, shell,
monitor);
return Status.OK_STATUS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
return new Status(Status.ERROR, MigrateSkeletalImplementationToInterfaceRefactoringPlugin
.getDefault().getBundle().getSymbolicName(), "Failed to start refactoring.");
}
}));
}
}
}
|
adding more analysis
|
edu.cuny.citytech.defaultrefactoring.ui/src/edu/cuny/citytech/defaultrefactoring/ui/handlers/MigrateSkeletalImplementationToInterfaceHandler.java
|
adding more analysis
|
|
Java
|
epl-1.0
|
98aa0b3c9545d76bdfde8a445f853442128e6fe9
| 0
|
ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,css-iter/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter,ControlSystemStudio/org.csstudio.iter
|
/*******************************************************************************
* Copyright (c) 2010-2016 ITER Organization.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.iter.opibuilder.widgets;
import org.csstudio.opibuilder.OPIBuilderPlugin;
import org.csstudio.opibuilder.widgets.editparts.NativeTextEditpartDelegate;
import org.csstudio.opibuilder.widgets.editparts.TextInputEditpart;
import org.csstudio.opibuilder.widgets.figures.NativeTextFigure;
import org.csstudio.opibuilder.widgets.model.TextInputModel;
import org.eclipse.draw2d.IFigure;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
/**
*
* <code>NativeLabeledTextEditpartDelegate</code> adds additional focus lost functionality to the native widget.
*
* @author <a href="mailto:jaka.bobnar@cosylab.com">Jaka Bobnar</a>
*
*/
public class NativeLabeledTextEditpartDelegate extends NativeTextEditpartDelegate {
private Color backgroundFocusColor = null;
private Color originalBackgroundColor = null;
private TextInputEditpart editpart;
private TextInputModel model;
private Text text;
NativeLabeledTextEditpartDelegate(LabeledTextInputEditPartDelegate editpart,
LabeledTextInputModelDelegate model) {
super(editpart, model);
this.editpart = editpart;
this.model = model;
this.backgroundFocusColor = new Color(Display.getDefault(), model.getBackgroundFocusColor());
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
if (this.backgroundFocusColor != null)
this.backgroundFocusColor.dispose();
super.finalize();
}
private FocusAdapter getTextFocusListener(NativeTextFigure figure) {
return new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
// This listener will also be triggered when ENTER is pressed to store the value (even when
// FOCUS_TRAVERSE is set to KEEP).
// When ConfirmOnFocusLost is TRUE, this will cause a bug: the value will be reset to the old value.
// This is because at this point the value of text.getText() will be the old value, set in
// NativeTextEditpartDelegate.outputText().
// Only after the value is successfully set on the PV will the model (and thus text) be updated to the
// new value.
// In such a case, focusLost must not call outputText with the value in text.getText().
if (((LabeledTextInputModelDelegate) model).isConfirmOnFocusLost()) {
if (text.getText().equals(model.getText())) {
// either there is no change or ENTER/CTRL+ENTER was pressed to store it but the figure & model
// were not yet updated.
text.setBackground(originalBackgroundColor);
originalBackgroundColor = null;
return;
}
}
// On mobile, lost focus should output text since there is not enter hit or ctrl key.
// If ConfirmOnFocusLost is set, lost focus should also output text.
if (editpart.getPV() != null && !OPIBuilderPlugin.isMobile(text.getDisplay())
&& ((LabeledTextInputModelDelegate) model).isConfirmOnFocusLost() == false) {
text.setText(model.getText());
} else if (text.isEnabled()) {
outputText(text.getText());
}
text.setBackground(originalBackgroundColor);
originalBackgroundColor = null;
}
@Override
public void focusGained(FocusEvent e) {
if (originalBackgroundColor == null) {
originalBackgroundColor = text.getBackground();
}
text.setBackground(backgroundFocusColor);
}
};
}
/*
* (non-Javadoc)
*
* @see org.csstudio.opibuilder.widgets.editparts.NativeTextEditpartDelegate#doCreateFigure()
*/
@Override
public IFigure doCreateFigure() {
NativeTextFigure figure = (NativeTextFigure)super.doCreateFigure();
text = figure.getSWTWidget();
if (!model.isReadOnly()) {
Listener[] listeners1 = text.getListeners(SWT.FocusIn);
Listener[] listeners2 = text.getListeners(SWT.FocusOut);
for (Listener l : listeners1) {
text.removeListener(SWT.FocusIn, l);
}
for (Listener l : listeners2) {
text.removeListener(SWT.FocusOut, l);
}
text.addFocusListener(getTextFocusListener(figure));
}
return figure;
}
/*
* (non-Javadoc)
*
* @see org.csstudio.opibuilder.widgets.editparts.NativeTextEditpartDelegate#registerPropertyChangeHandlers()
*/
@Override
public void registerPropertyChangeHandlers() {
super.registerPropertyChangeHandlers();
for (String s : LabeledTextInputModel.PROPERTIES_TO_REHANDLE) {
editpart.removeAllPropertyChangeHandlers(s);
}
}
}
|
plugins/org.csstudio.iter.opibuilder.widgets/src/org/csstudio/iter/opibuilder/widgets/NativeLabeledTextEditpartDelegate.java
|
/*******************************************************************************
* Copyright (c) 2010-2016 ITER Organization.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.iter.opibuilder.widgets;
import org.csstudio.opibuilder.OPIBuilderPlugin;
import org.csstudio.opibuilder.widgets.editparts.NativeTextEditpartDelegate;
import org.csstudio.opibuilder.widgets.editparts.TextInputEditpart;
import org.csstudio.opibuilder.widgets.figures.NativeTextFigure;
import org.csstudio.opibuilder.widgets.model.TextInputModel;
import org.eclipse.draw2d.IFigure;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class NativeLabeledTextEditpartDelegate extends NativeTextEditpartDelegate {
private Color backgroundFocusColor = null;
private Color originalBackgroundColor = null;
private TextInputEditpart editpart;
private TextInputModel model;
private Text text;
public NativeLabeledTextEditpartDelegate(LabeledTextInputEditPartDelegate editpart,
LabeledTextInputModelDelegate model) {
super(editpart, model);
this.editpart = editpart;
this.model = model;
this.backgroundFocusColor = new Color(Display.getDefault(), model.getBackgroundFocusColor());
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() throws Throwable {
if (this.backgroundFocusColor != null)
this.backgroundFocusColor.dispose();
super.finalize();
}
private FocusAdapter getTextFocusListener(NativeTextFigure figure) {
return new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
// This listener will also be triggered when ENTER is pressed to store the value (even when
// FOCUS_TRAVERSE is set to KEEP).
// When ConfirmOnFocusLost is TRUE, this will cause a bug: the value will be reset to the old value.
// This is because at this point the value of text.getText() will be the old value, set in
// NativeTextEditpartDelegate.outputText().
// Only after the value is successfully set on the PV will the model (and thus text) be updated to the
// new value.
// In such a case, focusLost must not call outputText with the value in text.getText().
if (((LabeledTextInputModelDelegate) model).isConfirmOnFocusLost()) {
if (text.getText().equals(model.getText())) {
// either there is no change or ENTER/CTRL+ENTER was pressed to store it but the figure & model
// were not yet updated.
text.setBackground(originalBackgroundColor);
originalBackgroundColor = null;
return;
}
}
// On mobile, lost focus should output text since there is not enter hit or ctrl key.
// If ConfirmOnFocusLost is set, lost focus should also output text.
if (editpart.getPV() != null && !OPIBuilderPlugin.isMobile(text.getDisplay())
&& ((LabeledTextInputModelDelegate) model).isConfirmOnFocusLost() == false) {
text.setText(model.getText());
} else if (text.isEnabled()) {
outputText(text.getText());
}
text.setBackground(originalBackgroundColor);
originalBackgroundColor = null;
}
@Override
public void focusGained(FocusEvent e) {
if (originalBackgroundColor == null) {
originalBackgroundColor = text.getBackground();
}
text.setBackground(backgroundFocusColor);
}
};
}
/*
* (non-Javadoc)
*
* @see org.csstudio.opibuilder.widgets.editparts.NativeTextEditpartDelegate#doCreateFigure()
*/
@Override
public IFigure doCreateFigure() {
NativeTextFigure figure = (NativeTextFigure)super.doCreateFigure();
text = figure.getSWTWidget();
if (!model.isReadOnly()) {
Listener[] listeners1 = text.getListeners(SWT.FocusIn);
Listener[] listeners2 = text.getListeners(SWT.FocusOut);
for (Listener l : listeners1) {
text.removeListener(SWT.FocusIn, l);
}
for (Listener l : listeners2) {
text.removeListener(SWT.FocusOut, l);
}
text.addFocusListener(getTextFocusListener(figure));
}
return figure;
}
/*
* (non-Javadoc)
*
* @see org.csstudio.opibuilder.widgets.editparts.NativeTextEditpartDelegate#registerPropertyChangeHandlers()
*/
@Override
public void registerPropertyChangeHandlers() {
super.registerPropertyChangeHandlers();
for (String s : LabeledTextInputModel.PROPERTIES_TO_REHANDLE) {
editpart.removeAllPropertyChangeHandlers(s);
}
}
}
|
Class javadoc added.
|
plugins/org.csstudio.iter.opibuilder.widgets/src/org/csstudio/iter/opibuilder/widgets/NativeLabeledTextEditpartDelegate.java
|
Class javadoc added.
|
|
Java
|
agpl-3.0
|
1f2d67b3e6290deb0acd1995f4ae88eaa88339af
| 0
|
ozwillo/ozwillo-kernel,ozwillo/ozwillo-kernel,ozwillo/ozwillo-kernel
|
package oasis.web.applications;
import java.net.URI;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Strings;
import oasis.model.applications.v2.AppInstance;
import oasis.model.applications.v2.Application;
import oasis.model.authn.ClientType;
import oasis.model.directory.DirectoryRepository;
import oasis.model.directory.Organization;
import oasis.services.applications.AppInstanceService;
import oasis.services.applications.ApplicationService;
import oasis.services.authn.CredentialsService;
import oasis.web.authn.Authenticated;
import oasis.web.authn.OAuth;
import oasis.web.authn.OAuthPrincipal;
import oasis.web.providers.JacksonJsonProvider;
import oasis.web.utils.ResponseFactory;
import oasis.web.webhooks.WebhookSignatureFilter;
@Path("/m/instantiate/{application_id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Authenticated @OAuth
public class MarketBuyEndpoint {
private static final Logger logger = LoggerFactory.getLogger(MarketBuyEndpoint.class);
@Inject ApplicationService applicationService;
@Inject DirectoryRepository directoryRepository;
@Inject AppInstanceService appInstanceService;
@Inject CredentialsService credentialsService;
@Context UriInfo uriInfo;
@Context SecurityContext securityContext;
@PathParam("application_id") String applicationId;
@POST
public Response instantiate(AppInstance instance) {
Application application = applicationService.getApplication(applicationId);
if (application == null) {
return ResponseFactory.notFound("Application doesn't exist");
}
if (!Strings.isNullOrEmpty(instance.getProvider_id())) {
Organization organization = directoryRepository.getOrganization(instance.getProvider_id());
if (organization == null) {
return ResponseFactory.unprocessableEntity("Organization doesn't exist");
}
}
instance.setApplication_id(application.getId());
String userId = ((OAuthPrincipal) securityContext.getUserPrincipal()).getAccessToken().getAccountId();
instance.setInstantiator_id(userId);
instance.setStatus(AppInstance.InstantiationStatus.PENDING);
instance = appInstanceService.createAppInstance(instance);
// FIXME: temporarily set the password to the instance id
credentialsService.setPassword(ClientType.PROVIDER, instance.getId(), instance.getId());
Future<Response> future = ClientBuilder.newClient()
.target(application.getInstantiation_uri())
.register(new WebhookSignatureFilter(application.getInstantiation_secret()))
.register(JacksonJsonProvider.class)
.request()
.async()
.post(Entity.json(new CreateInstanceRequest()
.setInstance_id(instance.getId())
.setClient_id(instance.getId())
.setClient_secret(instance.getId())
.setInstance_registration_uri(uriInfo.getBaseUriBuilder().path(InstanceRegistrationEndpoint.class).build(instance.getId()))));
Response response;
try {
response = future.get(1, TimeUnit.MINUTES);
} catch (InterruptedException | ExecutionException e) {
logger.error("Error calling App Factory for app={} and user={}", applicationId, userId, e);
return ResponseFactory.build(Response.Status.BAD_GATEWAY, "Application factory failed");
} catch (TimeoutException e) {
logger.error("Timeout calling App Factory for app={} and user={}", applicationId, userId, e);
return ResponseFactory.build(Response.Status.GATEWAY_TIMEOUT, "Application factory timed-out");
}
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
appInstanceService.deletePendingInstance(instance.getId());
return ResponseFactory.build(Response.Status.BAD_GATEWAY, "Application factory failed");
}
// Get the possibly-updated instance
instance = appInstanceService.getAppInstance(instance.getId());
return Response.ok(instance).build();
}
public static class CreateInstanceRequest {
@JsonProperty
String instance_id;
@JsonProperty String client_id;
@JsonProperty String client_secret;
@JsonProperty
URI instance_registration_uri;
public CreateInstanceRequest setInstance_id(String instance_id) {
this.instance_id = instance_id;
return this;
}
public CreateInstanceRequest setClient_id(String client_id) {
this.client_id = client_id;
return this;
}
public CreateInstanceRequest setClient_secret(String client_secret) {
this.client_secret = client_secret;
return this;
}
public CreateInstanceRequest setInstance_registration_uri(URI instance_registration_uri) {
this.instance_registration_uri = instance_registration_uri;
return this;
}
}
}
|
oasis-webapp/src/main/java/oasis/web/applications/MarketBuyEndpoint.java
|
package oasis.web.applications;
import java.net.URI;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Strings;
import oasis.model.applications.v2.AppInstance;
import oasis.model.applications.v2.Application;
import oasis.model.authn.ClientType;
import oasis.model.directory.DirectoryRepository;
import oasis.model.directory.Organization;
import oasis.services.applications.AppInstanceService;
import oasis.services.applications.ApplicationService;
import oasis.services.authn.CredentialsService;
import oasis.web.authn.Authenticated;
import oasis.web.authn.OAuth;
import oasis.web.authn.OAuthPrincipal;
import oasis.web.providers.JacksonJsonProvider;
import oasis.web.utils.ResponseFactory;
import oasis.web.webhooks.WebhookSignatureFilter;
@Path("/m/instantiate/{application_id}")
public class MarketBuyEndpoint {
private static final Logger logger = LoggerFactory.getLogger(MarketBuyEndpoint.class);
@Inject ApplicationService applicationService;
@Inject DirectoryRepository directoryRepository;
@Inject AppInstanceService appInstanceService;
@Inject CredentialsService credentialsService;
@Context UriInfo uriInfo;
@Context SecurityContext securityContext;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Authenticated @OAuth
public Response instantiate(
@PathParam("application_id") String applicationId,
AppInstance instance) {
Application application = applicationService.getApplication(applicationId);
if (application == null) {
return ResponseFactory.notFound("Application doesn't exist");
}
if (!Strings.isNullOrEmpty(instance.getProvider_id())) {
Organization organization = directoryRepository.getOrganization(instance.getProvider_id());
if (organization == null) {
return ResponseFactory.unprocessableEntity("Organization doesn't exist");
}
}
instance.setApplication_id(application.getId());
String userId = ((OAuthPrincipal) securityContext.getUserPrincipal()).getAccessToken().getAccountId();
instance.setInstantiator_id(userId);
instance.setStatus(AppInstance.InstantiationStatus.PENDING);
instance = appInstanceService.createAppInstance(instance);
// FIXME: temporarily set the password to the instance id
credentialsService.setPassword(ClientType.PROVIDER, instance.getId(), instance.getId());
Future<Response> future = ClientBuilder.newClient()
.target(application.getInstantiation_uri())
.register(new WebhookSignatureFilter(application.getInstantiation_secret()))
.register(JacksonJsonProvider.class)
.request()
.async()
.post(Entity.json(new CreateInstanceRequest()
.setInstance_id(instance.getId())
.setClient_id(instance.getId())
.setClient_secret(instance.getId())
.setInstance_registration_uri(uriInfo.getBaseUriBuilder().path(InstanceRegistrationEndpoint.class).build(instance.getId()))));
Response response;
try {
response = future.get(1, TimeUnit.MINUTES);
} catch (InterruptedException | ExecutionException e) {
logger.error("Error calling App Factory for app={} and user={}", applicationId, userId, e);
return ResponseFactory.build(Response.Status.BAD_GATEWAY, "Application factory failed");
} catch (TimeoutException e) {
logger.error("Timeout calling App Factory for app={} and user={}", applicationId, userId, e);
return ResponseFactory.build(Response.Status.GATEWAY_TIMEOUT, "Application factory timed-out");
}
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
appInstanceService.deletePendingInstance(instance.getId());
return ResponseFactory.build(Response.Status.BAD_GATEWAY, "Application factory failed");
}
// Get the possibly-updated instance
instance = appInstanceService.getAppInstance(instance.getId());
return Response.ok(instance).build();
}
public static class CreateInstanceRequest {
@JsonProperty
String instance_id;
@JsonProperty String client_id;
@JsonProperty String client_secret;
@JsonProperty
URI instance_registration_uri;
public CreateInstanceRequest setInstance_id(String instance_id) {
this.instance_id = instance_id;
return this;
}
public CreateInstanceRequest setClient_id(String client_id) {
this.client_id = client_id;
return this;
}
public CreateInstanceRequest setClient_secret(String client_secret) {
this.client_secret = client_secret;
return this;
}
public CreateInstanceRequest setInstance_registration_uri(URI instance_registration_uri) {
this.instance_registration_uri = instance_registration_uri;
return this;
}
}
}
|
Small cleanup of MarketBuyEndpoint
Change-Id: Ia1bdf72012e3b5e621ad3749b21deff2d0f1de5d
|
oasis-webapp/src/main/java/oasis/web/applications/MarketBuyEndpoint.java
|
Small cleanup of MarketBuyEndpoint
|
|
Java
|
apache-2.0
|
74f2bbb1d233a7e450fab0e51ac664299f4df1dc
| 0
|
GoogleCloudPlatform/spring-cloud-gcp,GoogleCloudPlatform/spring-cloud-gcp,spring-cloud/spring-cloud-gcp,spring-cloud/spring-cloud-gcp,GoogleCloudPlatform/spring-cloud-gcp,GoogleCloudPlatform/spring-cloud-gcp,spring-cloud/spring-cloud-gcp,GoogleCloudPlatform/spring-cloud-gcp,spring-cloud/spring-cloud-gcp
|
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import com.google.cloud.logging.Payload.JsonPayload;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.google.api.gax.paging.Page;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload.StringPayload;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.gcp.core.GcpProjectIdProvider;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.is;
import static org.junit.Assume.assumeThat;
/**
* Tests for the logging sample app.
*
* @author Daniel Zou
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = { Application.class })
public class LoggingSampleApplicationTests {
private static final String LOG_FILTER_FORMAT = "trace:%s";
@Autowired
private GcpProjectIdProvider projectIdProvider;
@Autowired
private TestRestTemplate testRestTemplate;
@LocalServerPort
private int port;
private Logging logClient;
@BeforeClass
public static void checkToRun() {
assumeThat(
"Spanner Google Cloud Logging integration tests are disabled. "
+ "Please use '-Dit.logging=true' to enable them. ",
System.getProperty("it.logging"), is("true"));
}
@Before
public void setupLogging() {
this.logClient = LoggingOptions.getDefaultInstance().getService();
}
@Test
public void testLogRecordedInStackDriver() {
String url = String.format("http://localhost:%s/log", this.port);
String traceHeader = "gcp-logging-test-" + Instant.now().toEpochMilli();
HttpHeaders headers = new HttpHeaders();
headers.add("x-cloud-trace-context", traceHeader);
ResponseEntity<String> responseEntity = this.testRestTemplate.exchange(
url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
assertThat(responseEntity.getStatusCode().is2xxSuccessful()).isTrue();
String logFilter = String.format(LOG_FILTER_FORMAT, traceHeader);
await().atMost(60, TimeUnit.SECONDS)
.pollInterval(2, TimeUnit.SECONDS)
.untilAsserted(() -> {
Page<LogEntry> logEntryPage = this.logClient.listLogEntries(
Logging.EntryListOption.filter(logFilter));
List<LogEntry> logEntries = new ArrayList<>();
logEntryPage.iterateAll().forEach((le) -> {
logEntries.add(le);
});
List<String> logContents = logEntries.stream()
.map((logEntry) -> (String) ((JsonPayload) logEntry.getPayload())
.getDataAsMap().get("message"))
.collect(Collectors.toList());
assertThat(logContents).containsExactlyInAnyOrder(
"This line was written to the log.",
"This line was also written to the log with the same Trace ID.");
for (LogEntry logEntry : logEntries) {
assertThat(logEntry.getLogName()).isEqualTo("spring.log");
assertThat(logEntry.getResource().getLabels())
.containsEntry("project_id", this.projectIdProvider.getProjectId());
}
});
}
}
|
spring-cloud-gcp-samples/spring-cloud-gcp-logging-sample/src/test/java/com.example/LoggingSampleApplicationTests.java
|
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.google.api.gax.paging.Page;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload.StringPayload;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.gcp.core.GcpProjectIdProvider;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.is;
import static org.junit.Assume.assumeThat;
/**
* Tests for the logging sample app.
*
* @author Daniel Zou
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = { Application.class })
public class LoggingSampleApplicationTests {
private static final String LOG_FILTER_FORMAT = "trace:%s";
@Autowired
private GcpProjectIdProvider projectIdProvider;
@Autowired
private TestRestTemplate testRestTemplate;
@LocalServerPort
private int port;
private Logging logClient;
@BeforeClass
public static void checkToRun() {
assumeThat(
"Spanner Google Cloud Logging integration tests are disabled. "
+ "Please use '-Dit.logging=true' to enable them. ",
System.getProperty("it.logging"), is("true"));
}
@Before
public void setupLogging() {
this.logClient = LoggingOptions.getDefaultInstance().getService();
}
@Test
public void testLogRecordedInStackDriver() {
String url = String.format("http://localhost:%s/log", this.port);
String traceHeader = "gcp-logging-test-" + Instant.now().toEpochMilli();
HttpHeaders headers = new HttpHeaders();
headers.add("x-cloud-trace-context", traceHeader);
ResponseEntity<String> responseEntity = this.testRestTemplate.exchange(
url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
assertThat(responseEntity.getStatusCode().is2xxSuccessful()).isTrue();
String logFilter = String.format(LOG_FILTER_FORMAT, traceHeader);
await().atMost(60, TimeUnit.SECONDS)
.pollInterval(2, TimeUnit.SECONDS)
.untilAsserted(() -> {
Page<LogEntry> logEntryPage = this.logClient.listLogEntries(
Logging.EntryListOption.filter(logFilter));
List<LogEntry> logEntries = new ArrayList<>();
logEntryPage.iterateAll().forEach((le) -> {
logEntries.add(le);
});
List<String> logContents = logEntries.stream()
.map((logEntry) -> ((StringPayload) logEntry.getPayload()).getData())
.collect(Collectors.toList());
assertThat(logContents).containsExactlyInAnyOrder(
"This line was written to the log.",
"This line was also written to the log with the same Trace ID.");
for (LogEntry logEntry : logEntries) {
assertThat(logEntry.getLogName()).isEqualTo("spring.log");
assertThat(logEntry.getResource().getLabels())
.containsEntry("project_id", this.projectIdProvider.getProjectId());
}
});
}
}
|
update test to retrieve json format (#2378)
Same fix as #2377, but for logging sample test.
The logging format switched from text to json in com.google.cloud.google-cloud-logging-logback:v0.117.0 (googleapis/java-logging-logback#43).
This PR fixes the trace integration test by switching from reading textPayload to jsonPayload for verification of trace correlation to log.
|
spring-cloud-gcp-samples/spring-cloud-gcp-logging-sample/src/test/java/com.example/LoggingSampleApplicationTests.java
|
update test to retrieve json format (#2378)
|
|
Java
|
apache-2.0
|
4f02c1917881ae88d194568d2a7f23f7329b5f72
| 0
|
apache/commons-io,apache/commons-io,apache/commons-io
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.file;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.io.file.Counters.PathCounters;
/**
* Copies a source directory to a target directory.
*
* @since 2.7
*/
public class CopyDirectoryVisitor extends CountingPathVisitor {
private static final CopyOption[] EMPTY_COPY_OPTIONS = new CopyOption[0];
private final CopyOption[] copyOptions;
private final Path sourceDirectory;
private final Path targetDirectory;
/**
* Constructs a new visitor that deletes files except for the files and directories explicitly given.
*
* @param pathCounter How to count visits.
* @param sourceDirectory The source directory
* @param targetDirectory The target directory
* @param copyOptions Specifies how the copying should be done.
*/
public CopyDirectoryVisitor(final PathCounters pathCounter, final Path sourceDirectory, final Path targetDirectory,
final CopyOption... copyOptions) {
super(pathCounter);
this.sourceDirectory = sourceDirectory;
this.targetDirectory = targetDirectory;
this.copyOptions = copyOptions == null ? EMPTY_COPY_OPTIONS : copyOptions.clone();
}
/**
* Copies the sourceFile to the targetFile.
*
* @param sourceFile the source file.
* @param targetFile the target file.
* @throws IOException if an I/O error occurs.
* @since 2.8.0
*/
protected void copy(final Path sourceFile, final Path targetFile) throws IOException {
Files.copy(sourceFile, targetFile, copyOptions);
}
/**
* Gets the copy options.
*
* @return the copy options.
* @since 2.8.0
*/
public CopyOption[] getCopyOptions() {
return copyOptions;
}
/**
* Gets the source directory.
*
* @return the source directory.
* @since 2.8.0
*/
public Path getSourceDirectory() {
return sourceDirectory;
}
/**
* Gets the target directory.
*
* @return the target directory.
* @since 2.8.0
*/
public Path getTargetDirectory() {
return targetDirectory;
}
@Override
public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
throws IOException {
final Path newTargetDir = targetDirectory.resolve(sourceDirectory.relativize(directory));
if (Files.notExists(newTargetDir)) {
Files.createDirectory(newTargetDir);
}
return super.preVisitDirectory(directory, attributes);
}
@Override
public FileVisitResult visitFile(final Path sourceFile, final BasicFileAttributes attributes) throws IOException {
final Path targetFile = targetDirectory.resolve(sourceDirectory.relativize(sourceFile));
copy(sourceFile, targetFile);
return super.visitFile(targetFile, attributes);
}
}
|
src/main/java/org/apache/commons/io/file/CopyDirectoryVisitor.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.file;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.io.file.Counters.PathCounters;
/**
* Copies a source directory to a target directory.
*
* @since 2.7
*/
public class CopyDirectoryVisitor extends CountingPathVisitor {
private static final CopyOption[] EMPTY_COPY_OPTIONS = new CopyOption[0];
private final CopyOption[] copyOptions;
private final Path sourceDirectory;
private final Path targetDirectory;
/**
* Constructs a new visitor that deletes files except for the files and directories explicitly given.
*
* @param pathCounter How to count visits.
* @param sourceDirectory The source directory
* @param targetDirectory The target directory
* @param copyOptions Specifies how the copying should be done.
*/
public CopyDirectoryVisitor(final PathCounters pathCounter, final Path sourceDirectory, final Path targetDirectory,
final CopyOption... copyOptions) {
super(pathCounter);
this.sourceDirectory = sourceDirectory;
this.targetDirectory = targetDirectory;
this.copyOptions = copyOptions == null ? EMPTY_COPY_OPTIONS : copyOptions.clone();
}
/**
* Copies the sourceFile to the targetFile.
*
* @param sourceFile the source file.
* @param targetFile the target file.
* @throws IOException if an I/O error occurs.
* @since 2.8.0
*/
protected void copy(final Path sourceFile, final Path targetFile) throws IOException {
Files.copy(sourceFile, targetFile, copyOptions);
}
@Override
public FileVisitResult preVisitDirectory(final Path directory, final BasicFileAttributes attributes)
throws IOException {
final Path newTargetDir = targetDirectory.resolve(sourceDirectory.relativize(directory));
if (Files.notExists(newTargetDir)) {
Files.createDirectory(newTargetDir);
}
return super.preVisitDirectory(directory, attributes);
}
@Override
public FileVisitResult visitFile(final Path sourceFile, final BasicFileAttributes attributes) throws IOException {
final Path targetFile = targetDirectory.resolve(sourceDirectory.relativize(sourceFile));
copy(sourceFile, targetFile);
return super.visitFile(targetFile, attributes);
}
}
|
Add getters for simpler subclassing.
|
src/main/java/org/apache/commons/io/file/CopyDirectoryVisitor.java
|
Add getters for simpler subclassing.
|
|
Java
|
apache-2.0
|
52835362ce83f249fbaa6ae732eeb2207ae2d814
| 0
|
killbill/killbill-analytics-plugin,killbill/killbill-analytics-plugin
|
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.plugin.analytics.json;
import java.util.List;
import javax.annotation.Nullable;
import org.jooq.Field;
import com.fasterxml.jackson.annotation.JsonProperty;
public class FieldJson {
private final String name;
private final String dataType;
private final List<Object> distinctValues;
public FieldJson(final Field<?> field, @Nullable final List<Object> distinctValues) {
this(field.getName(), field.getDataType().getTypeName(), distinctValues);
}
public FieldJson(@JsonProperty("name") final String name,
@JsonProperty("dataType") final String dataType,
@JsonProperty("distinctValues") final List<Object> distinctValues) {
this.name = name;
this.dataType = dataType;
this.distinctValues = distinctValues;
}
public String getName() {
return name;
}
public String getDataType() {
return dataType;
}
public List<Object> getDistinctValues() {
return distinctValues;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FieldJson{");
sb.append("name='").append(name).append('\'');
sb.append(", dataType='").append(dataType).append('\'');
sb.append(", distinctValues=").append(distinctValues);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldJson fieldJson = (FieldJson) o;
if (dataType != null ? !dataType.equals(fieldJson.dataType) : fieldJson.dataType != null) {
return false;
}
if (distinctValues != null ? !distinctValues.equals(fieldJson.distinctValues) : fieldJson.distinctValues != null) {
return false;
}
if (name != null ? !name.equals(fieldJson.name) : fieldJson.name != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (distinctValues != null ? distinctValues.hashCode() : 0);
return result;
}
}
|
src/main/java/org/killbill/billing/plugin/analytics/json/FieldJson.java
|
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2020 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.plugin.analytics.json;
import java.util.List;
import javax.annotation.Nullable;
import org.jooq.Field;
import com.fasterxml.jackson.annotation.JsonProperty;
public class FieldJson {
private final String name;
private final String dataType;
private final List<Object> distinctValues;
public FieldJson(final Field<?> field, @Nullable final List<Object> distinctValues) {
this(field.getName(), field.getDataType() == null ? null : field.getDataType().getTypeName(), distinctValues);
}
public FieldJson(@JsonProperty("name") final String name,
@JsonProperty("dataType") final String dataType,
@JsonProperty("distinctValues") final List<Object> distinctValues) {
this.name = name;
this.dataType = dataType;
this.distinctValues = distinctValues;
}
public String getName() {
return name;
}
public String getDataType() {
return dataType;
}
public List<Object> getDistinctValues() {
return distinctValues;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FieldJson{");
sb.append("name='").append(name).append('\'');
sb.append(", dataType='").append(dataType).append('\'');
sb.append(", distinctValues=").append(distinctValues);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldJson fieldJson = (FieldJson) o;
if (dataType != null ? !dataType.equals(fieldJson.dataType) : fieldJson.dataType != null) {
return false;
}
if (distinctValues != null ? !distinctValues.equals(fieldJson.distinctValues) : fieldJson.distinctValues != null) {
return false;
}
if (name != null ? !name.equals(fieldJson.name) : fieldJson.name != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (dataType != null ? dataType.hashCode() : 0);
result = 31 * result + (distinctValues != null ? distinctValues.hashCode() : 0);
return result;
}
}
|
spotbugs: fix redundant nullcheck
Signed-off-by: Pierre-Alexandre Meyer <ff019a5748a52b5641624af88a54a2f0e46a9fb5@mouraf.org>
|
src/main/java/org/killbill/billing/plugin/analytics/json/FieldJson.java
|
spotbugs: fix redundant nullcheck
|
|
Java
|
apache-2.0
|
118abf47142a3a7ea05d980aba8aded96df8d2f2
| 0
|
xnslong/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,GFriedrich/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.layout;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.util.Transform;
import org.apache.logging.log4j.util.Strings;
/**
* Outputs events as rows in an HTML table on an HTML page.
* <p>
* Appenders using this layout should have their encoding set to UTF-8 or UTF-16, otherwise events containing non ASCII
* characters could result in corrupted log files.
* </p>
*/
@Plugin(name = "HtmlLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
public final class HtmlLayout extends AbstractStringLayout {
/**
* Default font family: {@value}.
*/
public static final String DEFAULT_FONT_FAMILY = "arial,sans-serif";
private static final String TRACE_PREFIX = "<br /> ";
private static final String REGEXP = Strings.LINE_SEPARATOR.equals("\n") ? "\n" : Strings.LINE_SEPARATOR + "|\n";
private static final String DEFAULT_TITLE = "Log4j Log Messages";
private static final String DEFAULT_CONTENT_TYPE = "text/html";
private final long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
// Print no location info by default
private final boolean locationInfo;
private final String title;
private final String contentType;
private final String font;
private final String fontSize;
private final String headerSize;
/**Possible font sizes */
public static enum FontSize {
SMALLER("smaller"), XXSMALL("xx-small"), XSMALL("x-small"), SMALL("small"), MEDIUM("medium"), LARGE("large"),
XLARGE("x-large"), XXLARGE("xx-large"), LARGER("larger");
private final String size;
private FontSize(final String size) {
this.size = size;
}
public String getFontSize() {
return size;
}
public static FontSize getFontSize(final String size) {
for (final FontSize fontSize : values()) {
if (fontSize.size.equals(size)) {
return fontSize;
}
}
return SMALL;
}
public FontSize larger() {
return this.ordinal() < XXLARGE.ordinal() ? FontSize.values()[this.ordinal() + 1] : this;
}
}
private HtmlLayout(final boolean locationInfo, final String title, final String contentType, final Charset charset,
final String font, final String fontSize, final String headerSize) {
super(charset);
this.locationInfo = locationInfo;
this.title = title;
this.contentType = addCharsetToContentType(contentType);
this.font = font;
this.fontSize = fontSize;
this.headerSize = headerSize;
}
/**
* For testing purposes.
*/
public String getTitle() {
return title;
}
/**
* For testing purposes.
*/
public boolean isLocationInfo() {
return locationInfo;
}
private String addCharsetToContentType(final String contentType) {
if (contentType == null) {
return DEFAULT_CONTENT_TYPE + "; charset=" + getCharset();
}
return contentType.contains("charset") ? contentType : contentType + "; charset=" + getCharset();
}
/**
* Format as a String.
*
* @param event The Logging Event.
* @return A String containing the LogEvent as HTML.
*/
@Override
public String toSerializable(final LogEvent event) {
final StringBuilder sbuf = getStringBuilder();
sbuf.append(Strings.LINE_SEPARATOR).append("<tr>").append(Strings.LINE_SEPARATOR);
sbuf.append("<td>");
sbuf.append(event.getTimeMillis() - jvmStartTime);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
final String escapedThread = Transform.escapeHtmlTags(event.getThreadName());
sbuf.append("<td title=\"").append(escapedThread).append(" thread\">");
sbuf.append(escapedThread);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
sbuf.append("<td title=\"Level\">");
if (event.getLevel().equals(Level.DEBUG)) {
sbuf.append("<font color=\"#339933\">");
sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
sbuf.append("</font>");
} else if (event.getLevel().isMoreSpecificThan(Level.WARN)) {
sbuf.append("<font color=\"#993300\"><strong>");
sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
sbuf.append("</strong></font>");
} else {
sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
}
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
String escapedLogger = Transform.escapeHtmlTags(event.getLoggerName());
if (escapedLogger.isEmpty()) {
escapedLogger = LoggerConfig.ROOT;
}
sbuf.append("<td title=\"").append(escapedLogger).append(" logger\">");
sbuf.append(escapedLogger);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
if (locationInfo) {
final StackTraceElement element = event.getSource();
sbuf.append("<td>");
sbuf.append(Transform.escapeHtmlTags(element.getFileName()));
sbuf.append(':');
sbuf.append(element.getLineNumber());
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
}
sbuf.append("<td title=\"Message\">");
sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />"));
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
sbuf.append("</tr>").append(Strings.LINE_SEPARATOR);
if (event.getContextStack() != null && !event.getContextStack().isEmpty()) {
sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
sbuf.append(";\" colspan=\"6\" ");
sbuf.append("title=\"Nested Diagnostic Context\">");
sbuf.append("NDC: ").append(Transform.escapeHtmlTags(event.getContextStack().toString()));
sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
}
if (event.getContextMap() != null && !event.getContextMap().isEmpty()) {
sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
sbuf.append(";\" colspan=\"6\" ");
sbuf.append("title=\"Mapped Diagnostic Context\">");
sbuf.append("MDC: ").append(Transform.escapeHtmlTags(event.getContextMap().toString()));
sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
}
final Throwable throwable = event.getThrown();
if (throwable != null) {
sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : ").append(fontSize);
sbuf.append(";\" colspan=\"6\">");
appendThrowableAsHtml(throwable, sbuf);
sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
}
return sbuf.toString();
}
@Override
/**
* @return The content type.
*/
public String getContentType() {
return contentType;
}
private void appendThrowableAsHtml(final Throwable throwable, final StringBuilder sbuf) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
} catch (final RuntimeException ex) {
// Ignore the exception.
}
pw.flush();
final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
final ArrayList<String> lines = new ArrayList<>();
try {
String line = reader.readLine();
while (line != null) {
lines.add(line);
line = reader.readLine();
}
} catch (final IOException ex) {
if (ex instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
lines.add(ex.toString());
}
boolean first = true;
for (final String line : lines) {
if (!first) {
sbuf.append(TRACE_PREFIX);
} else {
first = false;
}
sbuf.append(Transform.escapeHtmlTags(line));
sbuf.append(Strings.LINE_SEPARATOR);
}
}
private StringBuilder appendLs(StringBuilder sbuilder, String s) {
sbuilder.append(s).append(Strings.LINE_SEPARATOR);
return sbuilder;
}
private StringBuilder append(StringBuilder sbuilder, String s) {
sbuilder.append(s);
return sbuilder;
}
/**
* Returns appropriate HTML headers.
* @return The header as a byte array.
*/
@Override
public byte[] getHeader() {
final StringBuilder sbuf = new StringBuilder();
append(sbuf, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" ");
appendLs(sbuf, "\"http://www.w3.org/TR/html4/loose.dtd\">");
appendLs(sbuf, "<html>");
appendLs(sbuf, "<head>");
append(sbuf, "<meta charset=\"");
append(sbuf, getCharset().toString());
appendLs(sbuf, "\"/>");
append(sbuf, "<title>").append(title);
appendLs(sbuf, "</title>");
appendLs(sbuf, "<style type=\"text/css\">");
appendLs(sbuf, "<!--");
append(sbuf, "body, table {font-family:").append(font).append("; font-size: ");
appendLs(sbuf, headerSize).append(";}");
appendLs(sbuf, "th {background: #336699; color: #FFFFFF; text-align: left;}");
appendLs(sbuf, "-->");
appendLs(sbuf, "</style>");
appendLs(sbuf, "</head>");
appendLs(sbuf, "<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">");
appendLs(sbuf, "<hr size=\"1\" noshade=\"noshade\">");
appendLs(sbuf, "Log session start time " + new java.util.Date() + "<br>");
appendLs(sbuf, "<br>");
appendLs(sbuf,
"<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">");
appendLs(sbuf, "<tr>");
appendLs(sbuf, "<th>Time</th>");
appendLs(sbuf, "<th>Thread</th>");
appendLs(sbuf, "<th>Level</th>");
appendLs(sbuf, "<th>Logger</th>");
if (locationInfo) {
appendLs(sbuf, "<th>File:Line</th>");
}
appendLs(sbuf, "<th>Message</th>");
appendLs(sbuf, "</tr>");
return sbuf.toString().getBytes(getCharset());
}
/**
* Returns the appropriate HTML footers.
* @return the footer as a byte array.
*/
@Override
public byte[] getFooter() {
final StringBuilder sbuf = new StringBuilder();
appendLs(sbuf, "</table>");
appendLs(sbuf, "<br>");
appendLs(sbuf, "</body></html>");
return getBytes(sbuf.toString());
}
/**
* Create an HTML Layout.
* @param locationInfo If "true", location information will be included. The default is false.
* @param title The title to include in the file header. If none is specified the default title will be used.
* @param contentType The content type. Defaults to "text/html".
* @param charset The character set to use. If not specified, the default will be used.
* @param fontSize The font size of the text.
* @param font The font to use for the text.
* @return An HTML Layout.
*/
@PluginFactory
public static HtmlLayout createLayout(
@PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo,
@PluginAttribute(value = "title", defaultString = DEFAULT_TITLE) final String title,
@PluginAttribute("contentType") String contentType,
@PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset,
@PluginAttribute("fontSize") String fontSize,
@PluginAttribute(value = "fontName", defaultString = DEFAULT_FONT_FAMILY) final String font) {
final FontSize fs = FontSize.getFontSize(fontSize);
fontSize = fs.getFontSize();
final String headerSize = fs.larger().getFontSize();
if (contentType == null) {
contentType = DEFAULT_CONTENT_TYPE + "; charset=" + charset;
}
return new HtmlLayout(locationInfo, title, contentType, charset, font, fontSize, headerSize);
}
/**
* Creates an HTML Layout using the default settings.
*
* @return an HTML Layout.
*/
public static HtmlLayout createDefaultLayout() {
return newBuilder().build();
}
@PluginBuilderFactory
public static Builder newBuilder() {
return new Builder();
}
public static class Builder implements org.apache.logging.log4j.core.util.Builder<HtmlLayout> {
@PluginBuilderAttribute
private boolean locationInfo = false;
@PluginBuilderAttribute
private String title = DEFAULT_TITLE;
@PluginBuilderAttribute
private String contentType = null; // defer default value in order to use specified charset
@PluginBuilderAttribute
private Charset charset = StandardCharsets.UTF_8;
@PluginBuilderAttribute
private FontSize fontSize = FontSize.SMALL;
@PluginBuilderAttribute
private String fontName = DEFAULT_FONT_FAMILY;
private Builder() {
}
public Builder withLocationInfo(final boolean locationInfo) {
this.locationInfo = locationInfo;
return this;
}
public Builder withTitle(final String title) {
this.title = title;
return this;
}
public Builder withContentType(final String contentType) {
this.contentType = contentType;
return this;
}
public Builder withCharset(final Charset charset) {
this.charset = charset;
return this;
}
public Builder withFontSize(final FontSize fontSize) {
this.fontSize = fontSize;
return this;
}
public Builder withFontName(final String fontName) {
this.fontName = fontName;
return this;
}
@Override
public HtmlLayout build() {
// TODO: extract charset from content-type
if (contentType == null) {
contentType = DEFAULT_CONTENT_TYPE + "; charset=" + charset;
}
return new HtmlLayout(locationInfo, title, contentType, charset, fontName, fontSize.getFontSize(),
fontSize.larger().getFontSize());
}
}
}
|
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/HtmlLayout.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.layout;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.management.ManagementFactory;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.util.Transform;
import org.apache.logging.log4j.util.Strings;
/**
* Outputs events as rows in an HTML table on an HTML page.
* <p>
* Appenders using this layout should have their encoding set to UTF-8 or UTF-16, otherwise events containing non ASCII
* characters could result in corrupted log files.
* </p>
*/
@Plugin(name = "HtmlLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
public final class HtmlLayout extends AbstractStringLayout {
/**
* Default font family: {@value}.
*/
public static final String DEFAULT_FONT_FAMILY = "arial,sans-serif";
private static final String TRACE_PREFIX = "<br /> ";
private static final String REGEXP = Strings.LINE_SEPARATOR.equals("\n") ? "\n" : Strings.LINE_SEPARATOR + "|\n";
private static final String DEFAULT_TITLE = "Log4j Log Messages";
private static final String DEFAULT_CONTENT_TYPE = "text/html";
private final long jvmStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
// Print no location info by default
private final boolean locationInfo;
private final String title;
private final String contentType;
private final String font;
private final String fontSize;
private final String headerSize;
/**Possible font sizes */
public static enum FontSize {
SMALLER("smaller"), XXSMALL("xx-small"), XSMALL("x-small"), SMALL("small"), MEDIUM("medium"), LARGE("large"),
XLARGE("x-large"), XXLARGE("xx-large"), LARGER("larger");
private final String size;
private FontSize(final String size) {
this.size = size;
}
public String getFontSize() {
return size;
}
public static FontSize getFontSize(final String size) {
for (final FontSize fontSize : values()) {
if (fontSize.size.equals(size)) {
return fontSize;
}
}
return SMALL;
}
public FontSize larger() {
return this.ordinal() < XXLARGE.ordinal() ? FontSize.values()[this.ordinal() + 1] : this;
}
}
private HtmlLayout(final boolean locationInfo, final String title, final String contentType, final Charset charset,
final String font, final String fontSize, final String headerSize) {
super(charset);
this.locationInfo = locationInfo;
this.title = title;
this.contentType = addCharsetToContentType(contentType);
this.font = font;
this.fontSize = fontSize;
this.headerSize = headerSize;
}
/**
* For testing purposes.
*/
public String getTitle() {
return title;
}
/**
* For testing purposes.
*/
public boolean isLocationInfo() {
return locationInfo;
}
private String addCharsetToContentType(final String contentType) {
if (contentType == null) {
return DEFAULT_CONTENT_TYPE + "; charset=" + getCharset();
}
return contentType.contains("charset") ? contentType : contentType + "; charset=" + getCharset();
}
/**
* Format as a String.
*
* @param event The Logging Event.
* @return A String containing the LogEvent as HTML.
*/
@Override
public String toSerializable(final LogEvent event) {
final StringBuilder sbuf = getStringBuilder();
sbuf.append(Strings.LINE_SEPARATOR).append("<tr>").append(Strings.LINE_SEPARATOR);
sbuf.append("<td>");
sbuf.append(event.getTimeMillis() - jvmStartTime);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
final String escapedThread = Transform.escapeHtmlTags(event.getThreadName());
sbuf.append("<td title=\"").append(escapedThread).append(" thread\">");
sbuf.append(escapedThread);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
sbuf.append("<td title=\"Level\">");
if (event.getLevel().equals(Level.DEBUG)) {
sbuf.append("<font color=\"#339933\">");
sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
sbuf.append("</font>");
} else if (event.getLevel().isMoreSpecificThan(Level.WARN)) {
sbuf.append("<font color=\"#993300\"><strong>");
sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
sbuf.append("</strong></font>");
} else {
sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
}
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
String escapedLogger = Transform.escapeHtmlTags(event.getLoggerName());
if (escapedLogger.isEmpty()) {
escapedLogger = LoggerConfig.ROOT;
}
sbuf.append("<td title=\"").append(escapedLogger).append(" logger\">");
sbuf.append(escapedLogger);
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
if (locationInfo) {
final StackTraceElement element = event.getSource();
sbuf.append("<td>");
sbuf.append(Transform.escapeHtmlTags(element.getFileName()));
sbuf.append(':');
sbuf.append(element.getLineNumber());
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
}
sbuf.append("<td title=\"Message\">");
sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />"));
sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
sbuf.append("</tr>").append(Strings.LINE_SEPARATOR);
if (event.getContextStack() != null && !event.getContextStack().isEmpty()) {
sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
sbuf.append(";\" colspan=\"6\" ");
sbuf.append("title=\"Nested Diagnostic Context\">");
sbuf.append("NDC: ").append(Transform.escapeHtmlTags(event.getContextStack().toString()));
sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
}
if (event.getContextMap() != null && !event.getContextMap().isEmpty()) {
sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
sbuf.append(";\" colspan=\"6\" ");
sbuf.append("title=\"Mapped Diagnostic Context\">");
sbuf.append("MDC: ").append(Transform.escapeHtmlTags(event.getContextMap().toString()));
sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
}
final Throwable throwable = event.getThrown();
if (throwable != null) {
sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : ").append(fontSize);
sbuf.append(";\" colspan=\"6\">");
appendThrowableAsHtml(throwable, sbuf);
sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
}
return sbuf.toString();
}
@Override
/**
* @return The content type.
*/
public String getContentType() {
return contentType;
}
private void appendThrowableAsHtml(final Throwable throwable, final StringBuilder sbuf) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
} catch (final RuntimeException ex) {
// Ignore the exception.
}
pw.flush();
final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
final ArrayList<String> lines = new ArrayList<>();
try {
String line = reader.readLine();
while (line != null) {
lines.add(line);
line = reader.readLine();
}
} catch (final IOException ex) {
if (ex instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
lines.add(ex.toString());
}
boolean first = true;
for (final String line : lines) {
if (!first) {
sbuf.append(TRACE_PREFIX);
} else {
first = false;
}
sbuf.append(Transform.escapeHtmlTags(line));
sbuf.append(Strings.LINE_SEPARATOR);
}
}
/**
* Returns appropriate HTML headers.
* @return The header as a byte array.
*/
@Override
public byte[] getHeader() {
final StringBuilder sbuf = new StringBuilder();
sbuf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" ");
sbuf.append("\"http://www.w3.org/TR/html4/loose.dtd\">");
sbuf.append(Strings.LINE_SEPARATOR);
sbuf.append("<html>").append(Strings.LINE_SEPARATOR);
sbuf.append("<head>").append(Strings.LINE_SEPARATOR);
sbuf.append("<meta charset=\"").append(getCharset()).append("\"/>").append(Strings.LINE_SEPARATOR);
sbuf.append("<title>").append(title).append("</title>").append(Strings.LINE_SEPARATOR);
sbuf.append("<style type=\"text/css\">").append(Strings.LINE_SEPARATOR);
sbuf.append("<!--").append(Strings.LINE_SEPARATOR);
sbuf.append("body, table {font-family:").append(font).append("; font-size: ");
sbuf.append(headerSize).append(";}").append(Strings.LINE_SEPARATOR);
sbuf.append("th {background: #336699; color: #FFFFFF; text-align: left;}").append(Strings.LINE_SEPARATOR);
sbuf.append("-->").append(Strings.LINE_SEPARATOR);
sbuf.append("</style>").append(Strings.LINE_SEPARATOR);
sbuf.append("</head>").append(Strings.LINE_SEPARATOR);
sbuf.append("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">").append(Strings.LINE_SEPARATOR);
sbuf.append("<hr size=\"1\" noshade=\"noshade\">").append(Strings.LINE_SEPARATOR);
sbuf.append("Log session start time " + new java.util.Date() + "<br>").append(Strings.LINE_SEPARATOR);
sbuf.append("<br>").append(Strings.LINE_SEPARATOR);
sbuf.append(
"<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">");
sbuf.append(Strings.LINE_SEPARATOR);
sbuf.append("<tr>").append(Strings.LINE_SEPARATOR);
sbuf.append("<th>Time</th>").append(Strings.LINE_SEPARATOR);
sbuf.append("<th>Thread</th>").append(Strings.LINE_SEPARATOR);
sbuf.append("<th>Level</th>").append(Strings.LINE_SEPARATOR);
sbuf.append("<th>Logger</th>").append(Strings.LINE_SEPARATOR);
if (locationInfo) {
sbuf.append("<th>File:Line</th>").append(Strings.LINE_SEPARATOR);
}
sbuf.append("<th>Message</th>").append(Strings.LINE_SEPARATOR);
sbuf.append("</tr>").append(Strings.LINE_SEPARATOR);
return sbuf.toString().getBytes(getCharset());
}
/**
* Returns the appropriate HTML footers.
* @return the footer as a byte array.
*/
@Override
public byte[] getFooter() {
final StringBuilder sbuf = new StringBuilder();
sbuf.append("</table>").append(Strings.LINE_SEPARATOR);
sbuf.append("<br>").append(Strings.LINE_SEPARATOR);
sbuf.append("</body></html>");
return getBytes(sbuf.toString());
}
/**
* Create an HTML Layout.
* @param locationInfo If "true", location information will be included. The default is false.
* @param title The title to include in the file header. If none is specified the default title will be used.
* @param contentType The content type. Defaults to "text/html".
* @param charset The character set to use. If not specified, the default will be used.
* @param fontSize The font size of the text.
* @param font The font to use for the text.
* @return An HTML Layout.
*/
@PluginFactory
public static HtmlLayout createLayout(
@PluginAttribute(value = "locationInfo", defaultBoolean = false) final boolean locationInfo,
@PluginAttribute(value = "title", defaultString = DEFAULT_TITLE) final String title,
@PluginAttribute("contentType") String contentType,
@PluginAttribute(value = "charset", defaultString = "UTF-8") final Charset charset,
@PluginAttribute("fontSize") String fontSize,
@PluginAttribute(value = "fontName", defaultString = DEFAULT_FONT_FAMILY) final String font) {
final FontSize fs = FontSize.getFontSize(fontSize);
fontSize = fs.getFontSize();
final String headerSize = fs.larger().getFontSize();
if (contentType == null) {
contentType = DEFAULT_CONTENT_TYPE + "; charset=" + charset;
}
return new HtmlLayout(locationInfo, title, contentType, charset, font, fontSize, headerSize);
}
/**
* Creates an HTML Layout using the default settings.
*
* @return an HTML Layout.
*/
public static HtmlLayout createDefaultLayout() {
return newBuilder().build();
}
@PluginBuilderFactory
public static Builder newBuilder() {
return new Builder();
}
public static class Builder implements org.apache.logging.log4j.core.util.Builder<HtmlLayout> {
@PluginBuilderAttribute
private boolean locationInfo = false;
@PluginBuilderAttribute
private String title = DEFAULT_TITLE;
@PluginBuilderAttribute
private String contentType = null; // defer default value in order to use specified charset
@PluginBuilderAttribute
private Charset charset = StandardCharsets.UTF_8;
@PluginBuilderAttribute
private FontSize fontSize = FontSize.SMALL;
@PluginBuilderAttribute
private String fontName = DEFAULT_FONT_FAMILY;
private Builder() {
}
public Builder withLocationInfo(final boolean locationInfo) {
this.locationInfo = locationInfo;
return this;
}
public Builder withTitle(final String title) {
this.title = title;
return this;
}
public Builder withContentType(final String contentType) {
this.contentType = contentType;
return this;
}
public Builder withCharset(final Charset charset) {
this.charset = charset;
return this;
}
public Builder withFontSize(final FontSize fontSize) {
this.fontSize = fontSize;
return this;
}
public Builder withFontName(final String fontName) {
this.fontName = fontName;
return this;
}
@Override
public HtmlLayout build() {
// TODO: extract charset from content-type
if (contentType == null) {
contentType = DEFAULT_CONTENT_TYPE + "; charset=" + charset;
}
return new HtmlLayout(locationInfo, title, contentType, charset, fontName, fontSize.getFontSize(),
fontSize.larger().getFontSize());
}
}
}
|
Refactor use of Strings.LINE_SEPARATOR.
|
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/HtmlLayout.java
|
Refactor use of Strings.LINE_SEPARATOR.
|
|
Java
|
apache-2.0
|
f715735913625396f4aa1eaa26349b4122198f50
| 0
|
infraling/atomic,infraling/atomic
|
/**
*
*/
package de.uni_jena.iaa.linktype.atomic.core.wizards.newproject;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import de.hu_berlin.german.korpling.saltnpepper.salt.SaltFactory;
import de.hu_berlin.german.korpling.saltnpepper.salt.graph.Edge;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.SaltProject;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SCorpus;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SCorpusGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SDocument;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.tokenizer.Tokenizer;
import de.uni_jena.iaa.linktype.atomic.core.utils.AtomicProjectUtils;
/**
* @author Stephan Druskat
*
* TODO: Introduce OperationCanceledExceptions!
*
*/
public class NewAtomicProjectWizard extends Wizard implements INewWizard {
private NewAtomicProjectWizardDetailsPage page;
private Object[] typedTokenizerToUse;
public IFile projectIFile;
/**
*
*/
public NewAtomicProjectWizard() {
setNeedsProgressMonitor(true);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// Do nothing.
}
@Override
public void addPages() {
setWindowTitle("New Atomic project");
page = new NewAtomicProjectWizardDetailsPage();
addPage(page);
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
try {
getContainer().run(false, true, new AtomicProjectCreationRunnable());
}
catch (Exception e) {
e.printStackTrace();
}
return true;
}
private final class AtomicProjectCreationRunnable implements IRunnableWithProgress {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
setNeedsProgressMonitor(true);
String projectName = page.getTxtProjectName().getText();
String corpusText = page.getCorpusText();
String tokenizerName = page.getComboTokenizer().getText();
monitor.beginTask("Creating project from corpus", /*100*/IProgressMonitor.UNKNOWN);
// Task 1 : Create IProject
monitor.subTask("Creating Atomic project (1/7)");
IProject iProject = createIProject(projectName);
monitor.worked(1);
// Task 2 : select tokenizer
monitor.subTask("Collecting project metadata (2/7)");
typedTokenizerToUse = getTokenizerInstance(tokenizerName);
monitor.worked(1);
// Task 2 : Create SaltProject and structure
monitor.subTask("Creating data model (3/7)");
SaltProject saltProject = SaltFactory.eINSTANCE.createSaltProject();
saltProject.setSName(projectName);
createSaltProjectStructure(saltProject);
monitor.worked(1);
// Task 3 : Populate project with corpus
monitor.subTask("Populating data model with corpus data (4/7)");
SDocumentGraph sDocumentGraph = createSDocumentStructure(saltProject, corpusText);
monitor.worked(1);
// Task 4 : Tokenize
monitor.subTask("Tokenizing corpus with selected tokenizer (tokenization) (5/7)");
tokenizeCorpusString(sDocumentGraph, typedTokenizerToUse);
monitor.worked(1);
// Task 5 : Annotate tokens with text meta info
monitor.subTask("Tokenizing corpus with selected tokenizer (token annotation) (6/7)");
writeTextToTokens(sDocumentGraph);
monitor.worked(1);
// Task 6 : Annotate tokens with text meta info
monitor.subTask("Serializing project (7/7)");
try {
NewAtomicProjectWizard.this.projectIFile = saveSaltProjectToIPproject(saltProject, iProject, projectName, sDocumentGraph);
} catch (CoreException e) {
e.printStackTrace();
}
monitor.worked(1);
// Finished
monitor.done();
}
private IFile saveSaltProjectToIPproject(SaltProject saltProject, IProject iProject, String projectName, SDocumentGraph sDocumentGraph) throws CoreException {
File iProjectLocation = new File(iProject.getLocation().toString());
URI uri = URI.createFileURI(iProjectLocation.getAbsolutePath());
saltProject.saveSaltProject(uri);
/* TODO Save SaltProject to DOT
* There seems to be a concurrency problem with saving to the same URI!
*/
iProject.refreshLocal(IProject.DEPTH_INFINITE, null);
IFile iFile = iProject.getFile("SaltProject.salt");
return iFile;
}
private void writeTextToTokens(SDocumentGraph sDocumentGraph) {
String text = sDocumentGraph.getSTextualDSs().get(0).getSText();
EList<SToken> tokens = sDocumentGraph.getSTokens();
for (SToken token : tokens) {
for (Edge edge: sDocumentGraph.getOutEdges(token.getSId())) {
if (edge instanceof STextualRelation) {
STextualRelation textualRelation = (STextualRelation) edge;
String primaryText = text.substring(textualRelation.getSStart(), textualRelation.getSEnd());
token.createSProcessingAnnotation("ATOMIC", "TOKEN_TEXT", primaryText);
}
}
}
}
private void tokenizeCorpusString(SDocumentGraph sDocumentGraph, Object[] typedTokenizerToUse) {
if (typedTokenizerToUse[0] instanceof Tokenizer) {
Tokenizer tokenizer = (Tokenizer) typedTokenizerToUse[0];
tokenizer.setsDocumentGraph(sDocumentGraph);
tokenizer.tokenize(sDocumentGraph.getSTextualDSs().get(0));
}
}
private SDocumentGraph createSDocumentStructure(SaltProject saltProject, String corpusText) {
// SDocumentGraph
SDocumentGraph sDocumentGraph = SaltFactory.eINSTANCE.createSDocumentGraph();
sDocumentGraph.setSName("document_graph");
SDocument sDocument = saltProject.getSCorpusGraphs().get(0).getSDocuments().get(0);
sDocument.setSDocumentGraph(sDocumentGraph);
// STextualDS
STextualDS sTextualDS = SaltFactory.eINSTANCE.createSTextualDS();
sTextualDS.setSText(corpusText);
sDocument.getSDocumentGraph().addSNode(sTextualDS);
return sDocumentGraph;
}
private void createSaltProjectStructure(SaltProject saltProject) {
// SCorpusGraph
SCorpusGraph sCorpusGraph = SaltFactory.eINSTANCE.createSCorpusGraph();
saltProject.getSCorpusGraphs().add(sCorpusGraph);
// SCorpus
SCorpus sCorpus = SaltFactory.eINSTANCE.createSCorpus();
sCorpus.setSName("corpus");
sCorpusGraph.addSNode(sCorpus);
// SDocument
SDocument sDocument = SaltFactory.eINSTANCE.createSDocument();
sDocument.setSName("corpus_document");
sCorpusGraph.addSDocument(sCorpus, sDocument);
// return sDocument;
}
/**
* @param tokenizerName
*/
private Object[] getTokenizerInstance(String tokenizerName) {
Object[] typedTokenizer = new Object[2];
Object tokenizer = null;
for (int i = 0; i < AtomicProjectUtils.getTokenizerNames().length; i++) {
if (AtomicProjectUtils.getTokenizerNames()[i].equals(tokenizerName))
tokenizer = AtomicProjectUtils.getTokenizers()[i];
typedTokenizer[0] = tokenizer;
typedTokenizer[1] = tokenizer.getClass();
}
if (typedTokenizer[0] == null) {
ErrorDialog.openError(getShell(), "Tokenizer not found!", "Sorry, it appears that the tokenizer you have chosen is not available.", Status.OK_STATUS);
}
return typedTokenizer;
}
private IProject createIProject(String projectName) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject iProject = root.getProject(projectName);
try {
iProject.create(null);
iProject.open(null);
// addAtomicProjectNatureToIProject(iProject); // FIXME Throws CoreException
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return iProject;
}
}
}
|
de.uni_jena.iaa.linktype.atomic.core/src/de/uni_jena/iaa/linktype/atomic/core/wizards/newproject/NewAtomicProjectWizard.java
|
/**
*
*/
package de.uni_jena.iaa.linktype.atomic.core.wizards.newproject;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import de.hu_berlin.german.korpling.saltnpepper.salt.SaltFactory;
import de.hu_berlin.german.korpling.saltnpepper.salt.graph.Edge;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.SaltProject;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SCorpus;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SCorpusGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SDocument;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SDocumentGraph;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualDS;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.STextualRelation;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.SToken;
import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sDocumentStructure.tokenizer.Tokenizer;
import de.uni_jena.iaa.linktype.atomic.core.utils.AtomicProjectUtils;
/**
* @author stephan
*
* TODO: Introduce OperationCanceledExceptions!
*
*/
public class NewAtomicProjectWizard extends Wizard implements INewWizard {
private NewAtomicProjectWizardDetailsPage page;
private Object[] typedTokenizerToUse;
public IFile projectIFile;
/**
*
*/
public NewAtomicProjectWizard() {
setNeedsProgressMonitor(true);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
// Do nothing.
}
// @Override
// public boolean canFinish(){
// System.err.println("NOT EMPTY: " + (!page.getCorpusText().isEmpty()));
// System.err.println("NOT DEFAULT: " + (!page.getCorpusText().equals(Messages.AtomicProjectBasicsWizardPage_CORPUS_TEXTFIELD_DEFAULT)));
// return ((!page.getCorpusText().isEmpty()) && (!page.getCorpusText().equals(Messages.AtomicProjectBasicsWizardPage_CORPUS_TEXTFIELD_DEFAULT)));
// }
@Override
public void addPages() {
setWindowTitle("New Atomic project");
page = new NewAtomicProjectWizardDetailsPage();
addPage(page);
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
try {
getContainer().run(false, true, new AtomicProjectCreationRunnable());
}
catch (Exception e) {
e.printStackTrace();
}
return true;
}
private final class AtomicProjectCreationRunnable implements IRunnableWithProgress {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
setNeedsProgressMonitor(true);
String projectName = page.getTxtProjectName().getText();
String corpusText = page.getCorpusText();
String tokenizerName = page.getComboTokenizer().getText();
// Tokenizer tokenizer = null;
monitor.beginTask("Creating project from corpus", /*100*/IProgressMonitor.UNKNOWN);
// Task 1 : Create IProject
monitor.subTask("Creating Atomic project (1/7)");
IProject iProject = createIProject(projectName);
monitor.worked(1);
// Task 2 : select tokenizer
monitor.subTask("Collecting project metadata (2/7)");
typedTokenizerToUse = getTokenizerInstance(tokenizerName);
monitor.worked(1);
// Task 2 : Create SaltProject and structure
monitor.subTask("Creating data model (3/7)");
SaltProject saltProject = SaltFactory.eINSTANCE.createSaltProject();
saltProject.setSName(projectName);
createSaltProjectStructure(saltProject);
monitor.worked(1);
// Task 3 : Populate project with corpus
monitor.subTask("Populating data model with corpus data (4/7)");
SDocumentGraph sDocumentGraph = createSDocumentStructure(saltProject, corpusText);
monitor.worked(1);
// Task 4 : Tokenize
monitor.subTask("Tokenizing corpus with selected tokenizer (tokenization) (5/7)");
tokenizeCorpusString(sDocumentGraph, typedTokenizerToUse);
monitor.worked(1);
// Task 5 : Annotate tokens with text meta info
monitor.subTask("Tokenizing corpus with selected tokenizer (token annotation) (6/7)");
writeTextToTokens(sDocumentGraph);
monitor.worked(1);
// Task 6 : Annotate tokens with text meta info
monitor.subTask("Serializing project (7/7)");
try {
NewAtomicProjectWizard.this.projectIFile = saveSaltProjectToIPproject(saltProject, iProject, projectName, sDocumentGraph);
} catch (CoreException e) {
e.printStackTrace();
}
monitor.worked(1);
// Finished
monitor.done();
}
private IFile saveSaltProjectToIPproject(SaltProject saltProject, IProject iProject, String projectName, SDocumentGraph sDocumentGraph) throws CoreException {
File iProjectLocation = new File(iProject.getLocation().toString());
URI uri = URI.createFileURI(iProjectLocation.getAbsolutePath());
saltProject.saveSaltProject(uri);
/* TODO Save SaltProject to DOT
* There seems to be a concurrency problem with saving to the same URI!
*/
iProject.refreshLocal(IProject.DEPTH_INFINITE, null);
IFile iFile = iProject.getFile("SaltProject.salt");
return iFile;
}
private void writeTextToTokens(SDocumentGraph sDocumentGraph) {
String text = sDocumentGraph.getSTextualDSs().get(0).getSText();
EList<SToken> tokens = sDocumentGraph.getSTokens();
for (SToken token : tokens) {
for (Edge edge: sDocumentGraph.getOutEdges(token.getSId())) {
if (edge instanceof STextualRelation) {
STextualRelation textualRelation = (STextualRelation) edge;
String primaryText = text.substring(textualRelation.getSStart(), textualRelation.getSEnd());
token.createSProcessingAnnotation("ATOMIC", "TOKEN_TEXT", primaryText);
}
}
}
}
private void tokenizeCorpusString(SDocumentGraph sDocumentGraph, Object[] typedTokenizerToUse) {
if (typedTokenizerToUse[0] instanceof Tokenizer) {
Tokenizer tokenizer = (Tokenizer) typedTokenizerToUse[0];
tokenizer.setsDocumentGraph(sDocumentGraph);
tokenizer.tokenize(sDocumentGraph.getSTextualDSs().get(0));
}
}
private SDocumentGraph createSDocumentStructure(SaltProject saltProject, String corpusText) {
// SDocumentGraph
SDocumentGraph sDocumentGraph = SaltFactory.eINSTANCE.createSDocumentGraph();
sDocumentGraph.setSName("document_graph");
SDocument sDocument = saltProject.getSCorpusGraphs().get(0).getSDocuments().get(0);
sDocument.setSDocumentGraph(sDocumentGraph);
// STextualDS
STextualDS sTextualDS = SaltFactory.eINSTANCE.createSTextualDS();
sTextualDS.setSText(corpusText);
sDocument.getSDocumentGraph().addSNode(sTextualDS);
return sDocumentGraph;
}
private void createSaltProjectStructure(SaltProject saltProject) {
// SCorpusGraph
SCorpusGraph sCorpusGraph = SaltFactory.eINSTANCE.createSCorpusGraph();
saltProject.getSCorpusGraphs().add(sCorpusGraph);
// SCorpus
SCorpus sCorpus = SaltFactory.eINSTANCE.createSCorpus();
sCorpus.setSName("corpus");
sCorpusGraph.addSNode(sCorpus);
// SDocument
SDocument sDocument = SaltFactory.eINSTANCE.createSDocument();
sDocument.setSName("corpus_document");
sCorpusGraph.addSDocument(sCorpus, sDocument);
// return sDocument;
}
/**
* @param tokenizerName
*/
private Object[] getTokenizerInstance(String tokenizerName) {
Object[] typedTokenizer = new Object[2];
Object tokenizer = null;
for (int i = 0; i < AtomicProjectUtils.getTokenizerNames().length; i++) {
if (AtomicProjectUtils.getTokenizerNames()[i].equals(tokenizerName))
tokenizer = AtomicProjectUtils.getTokenizers()[i];
typedTokenizer[0] = tokenizer;
typedTokenizer[1] = tokenizer.getClass();
}
if (typedTokenizer[0] == null) {
ErrorDialog.openError(getShell(), "Tokenizer not found!", "Sorry, it appears that the tokenizer you have chosen is not available.", Status.OK_STATUS);
}
return typedTokenizer;
}
private IProject createIProject(String projectName) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject iProject = root.getProject(projectName);
try {
iProject.create(null);
iProject.open(null);
// addAtomicProjectNatureToIProject(iProject); // FIXME Throws CoreException
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return iProject;
}
}
}
|
Clean up
|
de.uni_jena.iaa.linktype.atomic.core/src/de/uni_jena/iaa/linktype/atomic/core/wizards/newproject/NewAtomicProjectWizard.java
|
Clean up
|
|
Java
|
apache-2.0
|
bcbf1f8324a50397dc0fddf8032e5afb3a75e752
| 0
|
MerritCR/merrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,joshuawilson/merrit,WANdisco/gerrit,MerritCR/merrit,joshuawilson/merrit,MerritCR/merrit,MerritCR/merrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,joshuawilson/merrit,WANdisco/gerrit,WANdisco/gerrit,WANdisco/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,MerritCR/merrit,MerritCR/merrit,WANdisco/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,joshuawilson/merrit,GerritCodeReview/gerrit,gerrit-review/gerrit,MerritCR/merrit,GerritCodeReview/gerrit,joshuawilson/merrit,joshuawilson/merrit,qtproject/qtqa-gerrit,WANdisco/gerrit,MerritCR/merrit
|
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountProjectWatch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.account.CapabilityControl;
import com.google.gerrit.server.account.GroupBackend;
import com.google.gerrit.server.account.GroupMembership;
import com.google.gerrit.server.account.ListGroupMembership;
import com.google.gerrit.server.account.Realm;
import com.google.gerrit.server.config.AnonymousCowardName;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.config.DisableReverseDnsLookup;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.util.Providers;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.util.SystemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.SocketAddress;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
/** An authenticated user. */
public class IdentifiedUser extends CurrentUser {
/** Create an IdentifiedUser, ignoring any per-request state. */
@Singleton
public static class GenericFactory {
private final CapabilityControl.Factory capabilityControlFactory;
private final StarredChangesUtil starredChangesUtil;
private final AuthConfig authConfig;
private final Realm realm;
private final String anonymousCowardName;
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
private final GroupBackend groupBackend;
private final Boolean disableReverseDnsLookup;
@Inject
public GenericFactory(
@Nullable CapabilityControl.Factory capabilityControlFactory,
@Nullable StarredChangesUtil starredChangesUtil,
AuthConfig authConfig,
Realm realm,
@AnonymousCowardName String anonymousCowardName,
@CanonicalWebUrl Provider<String> canonicalUrl,
@DisableReverseDnsLookup Boolean disableReverseDnsLookup,
AccountCache accountCache,
GroupBackend groupBackend) {
this.capabilityControlFactory = capabilityControlFactory;
this.starredChangesUtil = starredChangesUtil;
this.authConfig = authConfig;
this.realm = realm;
this.anonymousCowardName = anonymousCowardName;
this.canonicalUrl = canonicalUrl;
this.accountCache = accountCache;
this.groupBackend = groupBackend;
this.disableReverseDnsLookup = disableReverseDnsLookup;
}
public IdentifiedUser create(final Account.Id id) {
return create((SocketAddress) null, id);
}
public IdentifiedUser create(Provider<ReviewDb> db, Account.Id id) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, null, db, id, null);
}
public IdentifiedUser create(SocketAddress remotePeer, Account.Id id) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, Providers.of(remotePeer), null,
id, null);
}
public CurrentUser runAs(SocketAddress remotePeer, Account.Id id,
@Nullable CurrentUser caller) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, Providers.of(remotePeer), null,
id, caller);
}
}
/**
* Create an IdentifiedUser, relying on current request state.
* <p>
* Can only be used from within a module that has defined request scoped
* {@code @RemotePeer SocketAddress} and {@code ReviewDb} providers.
*/
@Singleton
public static class RequestFactory {
private final CapabilityControl.Factory capabilityControlFactory;
private final StarredChangesUtil starredChangesUtil;
private final AuthConfig authConfig;
private final Realm realm;
private final String anonymousCowardName;
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
private final GroupBackend groupBackend;
private final Boolean disableReverseDnsLookup;
private final Provider<SocketAddress> remotePeerProvider;
private final Provider<ReviewDb> dbProvider;
@Inject
RequestFactory(
CapabilityControl.Factory capabilityControlFactory,
@Nullable StarredChangesUtil starredChangesUtil,
final AuthConfig authConfig,
Realm realm,
@AnonymousCowardName final String anonymousCowardName,
@CanonicalWebUrl final Provider<String> canonicalUrl,
final AccountCache accountCache,
final GroupBackend groupBackend,
@DisableReverseDnsLookup final Boolean disableReverseDnsLookup,
@RemotePeer final Provider<SocketAddress> remotePeerProvider,
final Provider<ReviewDb> dbProvider) {
this.capabilityControlFactory = capabilityControlFactory;
this.starredChangesUtil = starredChangesUtil;
this.authConfig = authConfig;
this.realm = realm;
this.anonymousCowardName = anonymousCowardName;
this.canonicalUrl = canonicalUrl;
this.accountCache = accountCache;
this.groupBackend = groupBackend;
this.disableReverseDnsLookup = disableReverseDnsLookup;
this.remotePeerProvider = remotePeerProvider;
this.dbProvider = dbProvider;
}
public IdentifiedUser create(Account.Id id) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, remotePeerProvider, dbProvider,
id, null);
}
public IdentifiedUser runAs(Account.Id id, CurrentUser caller) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, remotePeerProvider, dbProvider,
id, caller);
}
}
private static final Logger log =
LoggerFactory.getLogger(IdentifiedUser.class);
private static final GroupMembership registeredGroups =
new ListGroupMembership(ImmutableSet.of(
SystemGroupBackend.ANONYMOUS_USERS,
SystemGroupBackend.REGISTERED_USERS));
@Nullable
private final StarredChangesUtil starredChangesUtil;
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
private final AuthConfig authConfig;
private final Realm realm;
private final GroupBackend groupBackend;
private final String anonymousCowardName;
private final Boolean disableReverseDnsLookup;
private final Set<String> validEmails =
Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
@Nullable
private final Provider<SocketAddress> remotePeerProvider;
@Nullable
private final Provider<ReviewDb> dbProvider;
private final Account.Id accountId;
private AccountState state;
private boolean loadedAllEmails;
private Set<String> invalidEmails;
private GroupMembership effectiveGroups;
private Set<Change.Id> starredChanges;
private ResultSet<Change.Id> starredQuery;
private Collection<AccountProjectWatch> notificationFilters;
private CurrentUser realUser;
private IdentifiedUser(
CapabilityControl.Factory capabilityControlFactory,
@Nullable StarredChangesUtil starredChangesUtil,
final AuthConfig authConfig,
Realm realm,
final String anonymousCowardName,
final Provider<String> canonicalUrl,
final AccountCache accountCache,
final GroupBackend groupBackend,
final Boolean disableReverseDnsLookup,
@Nullable final Provider<SocketAddress> remotePeerProvider,
@Nullable final Provider<ReviewDb> dbProvider,
final Account.Id id,
@Nullable CurrentUser realUser) {
super(capabilityControlFactory);
this.starredChangesUtil = starredChangesUtil;
this.canonicalUrl = canonicalUrl;
this.accountCache = accountCache;
this.groupBackend = groupBackend;
this.authConfig = authConfig;
this.realm = realm;
this.anonymousCowardName = anonymousCowardName;
this.disableReverseDnsLookup = disableReverseDnsLookup;
this.remotePeerProvider = remotePeerProvider;
this.dbProvider = dbProvider;
this.accountId = id;
this.realUser = realUser != null ? realUser : this;
}
@Override
public CurrentUser getRealUser() {
return realUser;
}
// TODO(cranger): maybe get the state through the accountCache instead.
public AccountState state() {
if (state == null) {
state = accountCache.get(getAccountId());
}
return state;
}
@Override
public IdentifiedUser asIdentifiedUser() {
return this;
}
@Override
public Account.Id getAccountId() {
return accountId;
}
/** @return the user's user name; null if one has not been selected/assigned. */
@Override
public String getUserName() {
return state().getUserName();
}
public Account getAccount() {
return state().getAccount();
}
public boolean hasEmailAddress(String email) {
if (validEmails.contains(email)) {
return true;
} else if (invalidEmails != null && invalidEmails.contains(email)) {
return false;
} else if (realm.hasEmailAddress(this, email)) {
validEmails.add(email);
return true;
} else if (invalidEmails == null) {
invalidEmails = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
}
invalidEmails.add(email);
return false;
}
public Set<String> getEmailAddresses() {
if (!loadedAllEmails) {
validEmails.addAll(realm.getEmailAddresses(this));
loadedAllEmails = true;
}
return validEmails;
}
public String getName() {
return getAccount().getName(anonymousCowardName);
}
public String getNameEmail() {
return getAccount().getNameEmail(anonymousCowardName);
}
@Override
public GroupMembership getEffectiveGroups() {
if (effectiveGroups == null) {
if (authConfig.isIdentityTrustable(state().getExternalIds())) {
effectiveGroups = groupBackend.membershipsOf(this);
} else {
effectiveGroups = registeredGroups;
}
}
return effectiveGroups;
}
@Override
public Set<Change.Id> getStarredChanges() {
if (starredChanges == null) {
if (starredChangesUtil == null) {
throw new IllegalStateException("StarredChangesUtil is missing");
}
try {
starredChanges =
FluentIterable.from(
starredQuery != null
? starredQuery
: starredChangesUtil.queryFromIndex(accountId))
.toSet();
} finally {
starredQuery = null;
}
}
return starredChanges;
}
public void clearStarredChanges() {
// Async query may have started before an update that the caller expects
// to see the results of, so we can't trust it.
abortStarredChanges();
starredChanges = null;
}
public void asyncStarredChanges() {
if (starredChanges == null && starredChangesUtil != null) {
starredQuery = starredChangesUtil.queryFromIndex(accountId);
}
}
public void abortStarredChanges() {
if (starredQuery != null) {
try {
starredQuery.close();
} finally {
starredQuery = null;
}
}
}
private void checkRequestScope() {
if (dbProvider == null) {
throw new OutOfScopeException("Not in request scoped user");
}
}
@Override
public Collection<AccountProjectWatch> getNotificationFilters() {
if (notificationFilters == null) {
checkRequestScope();
List<AccountProjectWatch> r;
try {
r = dbProvider.get().accountProjectWatches() //
.byAccount(getAccountId()).toList();
} catch (OrmException e) {
log.warn("Cannot query notification filters of a user", e);
r = Collections.emptyList();
}
notificationFilters = Collections.unmodifiableList(r);
}
return notificationFilters;
}
public PersonIdent newRefLogIdent() {
return newRefLogIdent(new Date(), TimeZone.getDefault());
}
public PersonIdent newRefLogIdent(final Date when, final TimeZone tz) {
final Account ua = getAccount();
String name = ua.getFullName();
if (name == null || name.isEmpty()) {
name = ua.getPreferredEmail();
}
if (name == null || name.isEmpty()) {
name = anonymousCowardName;
}
String user = getUserName();
if (user == null) {
user = "";
}
user = user + "|" + "account-" + ua.getId().toString();
String host = null;
if (remotePeerProvider != null) {
final SocketAddress remotePeer = remotePeerProvider.get();
if (remotePeer instanceof InetSocketAddress) {
final InetSocketAddress sa = (InetSocketAddress) remotePeer;
final InetAddress in = sa.getAddress();
host = in != null ? getHost(in) : sa.getHostName();
}
}
if (host == null || host.isEmpty()) {
host = "unknown";
}
return new PersonIdent(name, user + "@" + host, when, tz);
}
public PersonIdent newCommitterIdent(final Date when, final TimeZone tz) {
final Account ua = getAccount();
String name = ua.getFullName();
String email = ua.getPreferredEmail();
if (email == null || email.isEmpty()) {
// No preferred email is configured. Use a generic identity so we
// don't leak an address the user may have given us, but doesn't
// necessarily want to publish through Git records.
//
String user = getUserName();
if (user == null || user.isEmpty()) {
user = "account-" + ua.getId().toString();
}
String host;
if (canonicalUrl.get() != null) {
try {
host = new URL(canonicalUrl.get()).getHost();
} catch (MalformedURLException e) {
host = SystemReader.getInstance().getHostname();
}
} else {
host = SystemReader.getInstance().getHostname();
}
email = user + "@" + host;
}
if (name == null || name.isEmpty()) {
final int at = email.indexOf('@');
if (0 < at) {
name = email.substring(0, at);
} else {
name = anonymousCowardName;
}
}
return new PersonIdent(name, email, when, tz);
}
@Override
public String toString() {
return "IdentifiedUser[account " + getAccountId() + "]";
}
/** Check if user is the IdentifiedUser */
@Override
public boolean isIdentifiedUser() {
return true;
}
private String getHost(final InetAddress in) {
if (Boolean.FALSE.equals(disableReverseDnsLookup)) {
return in.getCanonicalHostName();
}
return in.getHostAddress();
}
}
|
gerrit-server/src/main/java/com/google/gerrit/server/IdentifiedUser.java
|
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountProjectWatch;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.account.AccountCache;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.account.CapabilityControl;
import com.google.gerrit.server.account.GroupBackend;
import com.google.gerrit.server.account.GroupMembership;
import com.google.gerrit.server.account.ListGroupMembership;
import com.google.gerrit.server.account.Realm;
import com.google.gerrit.server.config.AnonymousCowardName;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.gerrit.server.config.DisableReverseDnsLookup;
import com.google.gerrit.server.group.SystemGroupBackend;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.util.Providers;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.util.SystemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.SocketAddress;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
/** An authenticated user. */
public class IdentifiedUser extends CurrentUser {
/** Create an IdentifiedUser, ignoring any per-request state. */
@Singleton
public static class GenericFactory {
private final CapabilityControl.Factory capabilityControlFactory;
private final StarredChangesUtil starredChangesUtil;
private final AuthConfig authConfig;
private final Realm realm;
private final String anonymousCowardName;
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
private final GroupBackend groupBackend;
private final Boolean disableReverseDnsLookup;
@Inject
public GenericFactory(
@Nullable CapabilityControl.Factory capabilityControlFactory,
@Nullable StarredChangesUtil starredChangesUtil,
AuthConfig authConfig,
Realm realm,
@AnonymousCowardName String anonymousCowardName,
@CanonicalWebUrl Provider<String> canonicalUrl,
@DisableReverseDnsLookup Boolean disableReverseDnsLookup,
AccountCache accountCache,
GroupBackend groupBackend) {
this.capabilityControlFactory = capabilityControlFactory;
this.starredChangesUtil = starredChangesUtil;
this.authConfig = authConfig;
this.realm = realm;
this.anonymousCowardName = anonymousCowardName;
this.canonicalUrl = canonicalUrl;
this.accountCache = accountCache;
this.groupBackend = groupBackend;
this.disableReverseDnsLookup = disableReverseDnsLookup;
}
public IdentifiedUser create(final Account.Id id) {
return create((SocketAddress) null, id);
}
public IdentifiedUser create(Provider<ReviewDb> db, Account.Id id) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, null, db, id, null);
}
public IdentifiedUser create(SocketAddress remotePeer, Account.Id id) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, Providers.of(remotePeer), null,
id, null);
}
public CurrentUser runAs(SocketAddress remotePeer, Account.Id id,
@Nullable CurrentUser caller) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, Providers.of(remotePeer), null,
id, caller);
}
}
/**
* Create an IdentifiedUser, relying on current request state.
* <p>
* Can only be used from within a module that has defined request scoped
* {@code @RemotePeer SocketAddress} and {@code ReviewDb} providers.
*/
@Singleton
public static class RequestFactory {
private final CapabilityControl.Factory capabilityControlFactory;
private final StarredChangesUtil starredChangesUtil;
private final AuthConfig authConfig;
private final Realm realm;
private final String anonymousCowardName;
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
private final GroupBackend groupBackend;
private final Boolean disableReverseDnsLookup;
private final Provider<SocketAddress> remotePeerProvider;
private final Provider<ReviewDb> dbProvider;
@Inject
RequestFactory(
CapabilityControl.Factory capabilityControlFactory,
StarredChangesUtil starredChangesUtil,
final AuthConfig authConfig,
Realm realm,
@AnonymousCowardName final String anonymousCowardName,
@CanonicalWebUrl final Provider<String> canonicalUrl,
final AccountCache accountCache,
final GroupBackend groupBackend,
@DisableReverseDnsLookup final Boolean disableReverseDnsLookup,
@RemotePeer final Provider<SocketAddress> remotePeerProvider,
final Provider<ReviewDb> dbProvider) {
this.capabilityControlFactory = capabilityControlFactory;
this.starredChangesUtil = starredChangesUtil;
this.authConfig = authConfig;
this.realm = realm;
this.anonymousCowardName = anonymousCowardName;
this.canonicalUrl = canonicalUrl;
this.accountCache = accountCache;
this.groupBackend = groupBackend;
this.disableReverseDnsLookup = disableReverseDnsLookup;
this.remotePeerProvider = remotePeerProvider;
this.dbProvider = dbProvider;
}
public IdentifiedUser create(Account.Id id) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, remotePeerProvider, dbProvider,
id, null);
}
public IdentifiedUser runAs(Account.Id id, CurrentUser caller) {
return new IdentifiedUser(capabilityControlFactory, starredChangesUtil,
authConfig, realm, anonymousCowardName, canonicalUrl, accountCache,
groupBackend, disableReverseDnsLookup, remotePeerProvider, dbProvider,
id, caller);
}
}
private static final Logger log =
LoggerFactory.getLogger(IdentifiedUser.class);
private static final GroupMembership registeredGroups =
new ListGroupMembership(ImmutableSet.of(
SystemGroupBackend.ANONYMOUS_USERS,
SystemGroupBackend.REGISTERED_USERS));
@Nullable
private final StarredChangesUtil starredChangesUtil;
private final Provider<String> canonicalUrl;
private final AccountCache accountCache;
private final AuthConfig authConfig;
private final Realm realm;
private final GroupBackend groupBackend;
private final String anonymousCowardName;
private final Boolean disableReverseDnsLookup;
private final Set<String> validEmails =
Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
@Nullable
private final Provider<SocketAddress> remotePeerProvider;
@Nullable
private final Provider<ReviewDb> dbProvider;
private final Account.Id accountId;
private AccountState state;
private boolean loadedAllEmails;
private Set<String> invalidEmails;
private GroupMembership effectiveGroups;
private Set<Change.Id> starredChanges;
private ResultSet<Change.Id> starredQuery;
private Collection<AccountProjectWatch> notificationFilters;
private CurrentUser realUser;
private IdentifiedUser(
CapabilityControl.Factory capabilityControlFactory,
@Nullable StarredChangesUtil starredChangesUtil,
final AuthConfig authConfig,
Realm realm,
final String anonymousCowardName,
final Provider<String> canonicalUrl,
final AccountCache accountCache,
final GroupBackend groupBackend,
final Boolean disableReverseDnsLookup,
@Nullable final Provider<SocketAddress> remotePeerProvider,
@Nullable final Provider<ReviewDb> dbProvider,
final Account.Id id,
@Nullable CurrentUser realUser) {
super(capabilityControlFactory);
this.starredChangesUtil = starredChangesUtil;
this.canonicalUrl = canonicalUrl;
this.accountCache = accountCache;
this.groupBackend = groupBackend;
this.authConfig = authConfig;
this.realm = realm;
this.anonymousCowardName = anonymousCowardName;
this.disableReverseDnsLookup = disableReverseDnsLookup;
this.remotePeerProvider = remotePeerProvider;
this.dbProvider = dbProvider;
this.accountId = id;
this.realUser = realUser != null ? realUser : this;
}
@Override
public CurrentUser getRealUser() {
return realUser;
}
// TODO(cranger): maybe get the state through the accountCache instead.
public AccountState state() {
if (state == null) {
state = accountCache.get(getAccountId());
}
return state;
}
@Override
public IdentifiedUser asIdentifiedUser() {
return this;
}
@Override
public Account.Id getAccountId() {
return accountId;
}
/** @return the user's user name; null if one has not been selected/assigned. */
@Override
public String getUserName() {
return state().getUserName();
}
public Account getAccount() {
return state().getAccount();
}
public boolean hasEmailAddress(String email) {
if (validEmails.contains(email)) {
return true;
} else if (invalidEmails != null && invalidEmails.contains(email)) {
return false;
} else if (realm.hasEmailAddress(this, email)) {
validEmails.add(email);
return true;
} else if (invalidEmails == null) {
invalidEmails = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
}
invalidEmails.add(email);
return false;
}
public Set<String> getEmailAddresses() {
if (!loadedAllEmails) {
validEmails.addAll(realm.getEmailAddresses(this));
loadedAllEmails = true;
}
return validEmails;
}
public String getName() {
return getAccount().getName(anonymousCowardName);
}
public String getNameEmail() {
return getAccount().getNameEmail(anonymousCowardName);
}
@Override
public GroupMembership getEffectiveGroups() {
if (effectiveGroups == null) {
if (authConfig.isIdentityTrustable(state().getExternalIds())) {
effectiveGroups = groupBackend.membershipsOf(this);
} else {
effectiveGroups = registeredGroups;
}
}
return effectiveGroups;
}
@Override
public Set<Change.Id> getStarredChanges() {
if (starredChanges == null) {
if (starredChangesUtil == null) {
throw new IllegalStateException("StarredChangesUtil is missing");
}
try {
starredChanges =
FluentIterable.from(
starredQuery != null
? starredQuery
: starredChangesUtil.queryFromIndex(accountId))
.toSet();
} finally {
starredQuery = null;
}
}
return starredChanges;
}
public void clearStarredChanges() {
// Async query may have started before an update that the caller expects
// to see the results of, so we can't trust it.
abortStarredChanges();
starredChanges = null;
}
public void asyncStarredChanges() {
if (starredChanges == null && starredChangesUtil != null) {
starredQuery = starredChangesUtil.queryFromIndex(accountId);
}
}
public void abortStarredChanges() {
if (starredQuery != null) {
try {
starredQuery.close();
} finally {
starredQuery = null;
}
}
}
private void checkRequestScope() {
if (dbProvider == null) {
throw new OutOfScopeException("Not in request scoped user");
}
}
@Override
public Collection<AccountProjectWatch> getNotificationFilters() {
if (notificationFilters == null) {
checkRequestScope();
List<AccountProjectWatch> r;
try {
r = dbProvider.get().accountProjectWatches() //
.byAccount(getAccountId()).toList();
} catch (OrmException e) {
log.warn("Cannot query notification filters of a user", e);
r = Collections.emptyList();
}
notificationFilters = Collections.unmodifiableList(r);
}
return notificationFilters;
}
public PersonIdent newRefLogIdent() {
return newRefLogIdent(new Date(), TimeZone.getDefault());
}
public PersonIdent newRefLogIdent(final Date when, final TimeZone tz) {
final Account ua = getAccount();
String name = ua.getFullName();
if (name == null || name.isEmpty()) {
name = ua.getPreferredEmail();
}
if (name == null || name.isEmpty()) {
name = anonymousCowardName;
}
String user = getUserName();
if (user == null) {
user = "";
}
user = user + "|" + "account-" + ua.getId().toString();
String host = null;
if (remotePeerProvider != null) {
final SocketAddress remotePeer = remotePeerProvider.get();
if (remotePeer instanceof InetSocketAddress) {
final InetSocketAddress sa = (InetSocketAddress) remotePeer;
final InetAddress in = sa.getAddress();
host = in != null ? getHost(in) : sa.getHostName();
}
}
if (host == null || host.isEmpty()) {
host = "unknown";
}
return new PersonIdent(name, user + "@" + host, when, tz);
}
public PersonIdent newCommitterIdent(final Date when, final TimeZone tz) {
final Account ua = getAccount();
String name = ua.getFullName();
String email = ua.getPreferredEmail();
if (email == null || email.isEmpty()) {
// No preferred email is configured. Use a generic identity so we
// don't leak an address the user may have given us, but doesn't
// necessarily want to publish through Git records.
//
String user = getUserName();
if (user == null || user.isEmpty()) {
user = "account-" + ua.getId().toString();
}
String host;
if (canonicalUrl.get() != null) {
try {
host = new URL(canonicalUrl.get()).getHost();
} catch (MalformedURLException e) {
host = SystemReader.getInstance().getHostname();
}
} else {
host = SystemReader.getInstance().getHostname();
}
email = user + "@" + host;
}
if (name == null || name.isEmpty()) {
final int at = email.indexOf('@');
if (0 < at) {
name = email.substring(0, at);
} else {
name = anonymousCowardName;
}
}
return new PersonIdent(name, email, when, tz);
}
@Override
public String toString() {
return "IdentifiedUser[account " + getAccountId() + "]";
}
/** Check if user is the IdentifiedUser */
@Override
public boolean isIdentifiedUser() {
return true;
}
private String getHost(final InetAddress in) {
if (Boolean.FALSE.equals(disableReverseDnsLookup)) {
return in.getCanonicalHostName();
}
return in.getHostAddress();
}
}
|
IdentifiedUser: Allow null StarredChangesUtil in RequestFactory
This is already explicitly allowed elsewhere in this file for testing
and related purposes; one spot was just missed.
Change-Id: I453ef579771f7331149cd2c30111844dfc2e779c
|
gerrit-server/src/main/java/com/google/gerrit/server/IdentifiedUser.java
|
IdentifiedUser: Allow null StarredChangesUtil in RequestFactory
|
|
Java
|
apache-2.0
|
2d5be477f082bc3954887b60bc97a878f8808764
| 0
|
darshanasbg/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oidc.session.backchannellogout;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oidc.session.OIDCSessionConstants;
import org.wso2.carbon.identity.oidc.session.OIDCSessionState;
import org.wso2.carbon.identity.oidc.session.util.OIDCSessionManagementUtil;
import org.wso2.carbon.identity.openidconnect.ClaimProvider;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.Cookie;
/**
* This class is used to insert sid claim into ID token.
*/
public class ClaimProviderImpl implements ClaimProvider {
private static final Log log = LogFactory.getLog(ClaimProviderImpl.class);
@Override
public Map<String, Object> getAdditionalClaims(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext,
OAuth2AuthorizeRespDTO oAuth2AuthorizeRespDTO)
throws IdentityOAuth2Exception {
Map<String, Object> additionalClaims = new HashMap<>();
String claimValue;
OIDCSessionState previousSession = getSessionState(oAuthAuthzReqMessageContext);
if (previousSession == null) {
// If there is no previous browser session, generate new sid value.
claimValue = UUID.randomUUID().toString();
if (log.isDebugEnabled()) {
log.debug("sid claim is generated for auth request. ");
}
} else {
// Previous browser session exists, get sid claim from OIDCSessionState.
claimValue = previousSession.getSidClaim();
if (log.isDebugEnabled()) {
log.debug("sid claim is found in the session state");
}
}
additionalClaims.put(OAuthConstants.OIDCClaims.SESSION_ID_CLAIM, claimValue);
oAuth2AuthorizeRespDTO.setOidcSessionId(claimValue);
return additionalClaims;
}
private AuthorizationGrantCacheEntry getAuthorizationGrantCacheEntryFromCode(String authorizationCode) {
AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(authorizationCode);
return AuthorizationGrantCache.getInstance().getValueFromCacheByCode(authorizationGrantCacheKey);
}
@Override
public Map<String, Object> getAdditionalClaims(OAuthTokenReqMessageContext oAuthTokenReqMessageContext,
OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO)
throws IdentityOAuth2Exception {
Map<String, Object> additionalClaims = new HashMap<>();
String claimValue = null;
String accessCode = oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getAuthorizationCode();
if (StringUtils.isBlank(accessCode)) {
if (log.isDebugEnabled()) {
log.debug("AccessCode is null. Possibly a back end grant");
}
return additionalClaims;
}
AuthorizationGrantCacheEntry authzGrantCacheEntry =
getAuthorizationGrantCacheEntryFromCode(accessCode);
if (authzGrantCacheEntry != null) {
claimValue = authzGrantCacheEntry.getOidcSessionId();
}
if (claimValue != null) {
if (log.isDebugEnabled()) {
log.debug("sid claim is found in the session state");
}
additionalClaims.put("sid", claimValue);
}
return additionalClaims;
}
/**
* Return previousSessionState using opbs cookie.
*
* @param oAuthAuthzReqMessageContext
* @return OIDCSession state
*/
private OIDCSessionState getSessionState(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) {
Cookie[] cookies = oAuthAuthzReqMessageContext.getAuthorizationReqDTO().getCookie();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (OIDCSessionConstants.OPBS_COOKIE_ID.equals(cookie.getName())) {
OIDCSessionState previousSessionState = OIDCSessionManagementUtil.getSessionManager()
.getOIDCSessionState(cookie.getValue());
return previousSessionState;
}
}
}
return null;
}
}
|
components/org.wso2.carbon.identity.oidc.session/src/main/java/org/wso2/carbon/identity/oidc/session/backchannellogout/ClaimProviderImpl.java
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oidc.session.backchannellogout;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oidc.session.OIDCSessionConstants;
import org.wso2.carbon.identity.oidc.session.OIDCSessionState;
import org.wso2.carbon.identity.oidc.session.util.OIDCSessionManagementUtil;
import org.wso2.carbon.identity.openidconnect.ClaimProvider;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.Cookie;
/**
* This class is used to insert sid claim into ID token.
*/
public class ClaimProviderImpl implements ClaimProvider {
private static final Log log = LogFactory.getLog(ClaimProviderImpl.class);
@Override
public Map<String, Object> getAdditionalClaims(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext,
OAuth2AuthorizeRespDTO oAuth2AuthorizeRespDTO)
throws IdentityOAuth2Exception {
Map<String, Object> additionalClaims = new HashMap<>();
String claimValue;
OIDCSessionState previousSession = getSessionState(oAuthAuthzReqMessageContext);
if (previousSession == null) {
// If there is no previous browser session, generate new sid value.
claimValue = UUID.randomUUID().toString();
if (log.isDebugEnabled()) {
log.debug("sid claim is generated for auth request. ");
}
} else {
// Previous browser session exists, get sid claim from OIDCSessionState.
claimValue = previousSession.getSidClaim();
if (log.isDebugEnabled()) {
log.debug("sid claim is found in the session state");
}
}
additionalClaims.put(OAuthConstants.OIDCClaims.SESSION_ID_CLAIM, claimValue);
oAuth2AuthorizeRespDTO.setOidcSessionId(claimValue);
return additionalClaims;
}
private AuthorizationGrantCacheEntry getAuthorizationGrantCacheEntryFromCode(String authorizationCode) {
AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(authorizationCode);
return AuthorizationGrantCache.getInstance().getValueFromCacheByCode(authorizationGrantCacheKey);
}
@Override
public Map<String, Object> getAdditionalClaims(OAuthTokenReqMessageContext oAuthTokenReqMessageContext,
OAuth2AccessTokenRespDTO oAuth2AccessTokenRespDTO)
throws IdentityOAuth2Exception {
Map<String, Object> additionalClaims = new HashMap<>();
String claimValue = null;
String accessCode = oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getAuthorizationCode();
AuthorizationGrantCacheEntry authzGrantCacheEntry =
getAuthorizationGrantCacheEntryFromCode(accessCode);
if (authzGrantCacheEntry != null) {
claimValue = authzGrantCacheEntry.getOidcSessionId();
}
if (claimValue != null) {
if (log.isDebugEnabled()) {
log.debug("sid claim is found in the session state");
}
additionalClaims.put("sid", claimValue);
}
return additionalClaims;
}
/**
* Return previousSessionState using opbs cookie.
*
* @param oAuthAuthzReqMessageContext
* @return OIDCSession state
*/
private OIDCSessionState getSessionState(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) {
Cookie[] cookies = oAuthAuthzReqMessageContext.getAuthorizationReqDTO().getCookie();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (OIDCSessionConstants.OPBS_COOKIE_ID.equals(cookie.getName())) {
OIDCSessionState previousSessionState = OIDCSessionManagementUtil.getSessionManager()
.getOIDCSessionState(cookie.getValue());
return previousSessionState;
}
}
}
return null;
}
}
|
Blank check for code
|
components/org.wso2.carbon.identity.oidc.session/src/main/java/org/wso2/carbon/identity/oidc/session/backchannellogout/ClaimProviderImpl.java
|
Blank check for code
|
|
Java
|
apache-2.0
|
c3cde5d7557749791c83bcaa184c5c980ccbe549
| 0
|
streamsets/datacollector,kunickiaj/datacollector,streamsets/datacollector,streamsets/datacollector,streamsets/datacollector,kunickiaj/datacollector,kunickiaj/datacollector,kunickiaj/datacollector,kunickiaj/datacollector,streamsets/datacollector
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.execution.runner.standalone;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.streamsets.datacollector.alerts.AlertsUtil;
import com.streamsets.datacollector.callback.CallbackInfo;
import com.streamsets.datacollector.callback.CallbackObjectType;
import com.streamsets.datacollector.config.PipelineConfiguration;
import com.streamsets.datacollector.config.RuleDefinition;
import com.streamsets.datacollector.config.RuleDefinitions;
import com.streamsets.datacollector.config.StageConfiguration;
import com.streamsets.datacollector.creation.PipelineBeanCreator;
import com.streamsets.datacollector.creation.PipelineConfigBean;
import com.streamsets.datacollector.el.JobEL;
import com.streamsets.datacollector.el.PipelineEL;
import com.streamsets.datacollector.event.json.MetricRegistryJson;
import com.streamsets.datacollector.execution.AbstractRunner;
import com.streamsets.datacollector.execution.PipelineState;
import com.streamsets.datacollector.execution.PipelineStatus;
import com.streamsets.datacollector.execution.Runner;
import com.streamsets.datacollector.execution.Snapshot;
import com.streamsets.datacollector.execution.SnapshotInfo;
import com.streamsets.datacollector.execution.SnapshotStore;
import com.streamsets.datacollector.execution.StateListener;
import com.streamsets.datacollector.execution.alerts.AlertInfo;
import com.streamsets.datacollector.execution.metrics.MetricsEventRunnable;
import com.streamsets.datacollector.execution.runner.RetryUtils;
import com.streamsets.datacollector.execution.runner.common.Constants;
import com.streamsets.datacollector.execution.runner.common.DataObserverRunnable;
import com.streamsets.datacollector.execution.runner.common.MetricObserverRunnable;
import com.streamsets.datacollector.execution.runner.common.PipelineRunnerException;
import com.streamsets.datacollector.execution.runner.common.ProduceEmptyBatchesForIdleRunnersRunnable;
import com.streamsets.datacollector.execution.runner.common.ProductionObserver;
import com.streamsets.datacollector.execution.runner.common.ProductionPipeline;
import com.streamsets.datacollector.execution.runner.common.ProductionPipelineBuilder;
import com.streamsets.datacollector.execution.runner.common.ProductionPipelineRunnable;
import com.streamsets.datacollector.execution.runner.common.ProductionPipelineRunner;
import com.streamsets.datacollector.execution.runner.common.RulesConfigLoader;
import com.streamsets.datacollector.execution.runner.common.SampledRecord;
import com.streamsets.datacollector.execution.runner.common.ThreadHealthReporter;
import com.streamsets.datacollector.execution.runner.common.dagger.PipelineProviderModule;
import com.streamsets.datacollector.json.ObjectMapperFactory;
import com.streamsets.datacollector.metrics.MetricsConfigurator;
import com.streamsets.datacollector.runner.Observer;
import com.streamsets.datacollector.runner.Pipeline;
import com.streamsets.datacollector.runner.PipelineRunner;
import com.streamsets.datacollector.runner.PipelineRuntimeException;
import com.streamsets.datacollector.runner.UserContext;
import com.streamsets.datacollector.runner.production.OffsetFileUtil;
import com.streamsets.datacollector.runner.production.ProductionSourceOffsetTracker;
import com.streamsets.datacollector.runner.production.RulesConfigLoaderRunnable;
import com.streamsets.datacollector.runner.production.SourceOffset;
import com.streamsets.datacollector.store.PipelineInfo;
import com.streamsets.datacollector.store.PipelineStoreException;
import com.streamsets.datacollector.util.Configuration;
import com.streamsets.datacollector.util.ContainerError;
import com.streamsets.datacollector.util.LogUtil;
import com.streamsets.datacollector.util.PipelineException;
import com.streamsets.datacollector.validation.Issue;
import com.streamsets.dc.execution.manager.standalone.ResourceManager;
import com.streamsets.dc.execution.manager.standalone.ThreadUsage;
import com.streamsets.lib.security.http.RemoteSSOService;
import com.streamsets.pipeline.api.ErrorListener;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.impl.ErrorMessage;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.executor.SafeScheduledExecutorService;
import com.streamsets.pipeline.lib.log.LogConstants;
import dagger.ObjectGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class StandaloneRunner extends AbstractRunner implements StateListener {
private static final Logger LOG = LoggerFactory.getLogger(StandaloneRunner.class);
public static final String STATS_NULL_TARGET = "com_streamsets_pipeline_stage_destination_devnull_StatsNullDTarget";
public static final String STATS_DPM_DIRECTLY_TARGET =
"com_streamsets_pipeline_stage_destination_devnull_StatsDpmDirectlyDTarget";
public static final String CAPTURE_SNAPSHOT_ON_START = "capture.snapshot.on.start";
public static final boolean CAPTURE_SNAPSHOT_ON_START_DEFAULT = false;
public static final String SNAPSHOT_NUM_BATCHES = "snapshot.num.batches";
public static final int SNAPSHOT_NUM_BATCHES_DEFAULT = 1;
public static final String SNAPSHOT_BATCH_SIZE = "snapshot.batch.size";
public static final int SNAPSHOT_BATCH_SIZE_DEFAULT = 10;
private static final ImmutableList<PipelineStatus> RESET_OFFSET_DISALLOWED_STATUSES = ImmutableList.of(
PipelineStatus.CONNECTING,
PipelineStatus.DISCONNECTING,
PipelineStatus.FINISHING,
PipelineStatus.RETRY,
PipelineStatus.RUNNING,
PipelineStatus.STARTING,
PipelineStatus.STOPPING
);
private static final ImmutableSet<PipelineStatus> FORCE_QUIT_ALLOWED_STATES = ImmutableSet.of(
PipelineStatus.STOPPING,
PipelineStatus.STOPPING_ERROR,
PipelineStatus.STARTING_ERROR,
PipelineStatus.RUNNING_ERROR,
PipelineStatus.FINISHING
);
@Inject SnapshotStore snapshotStore;
@Inject @Named("runnerExecutor") SafeScheduledExecutorService runnerExecutor;
@Inject ResourceManager resourceManager;
private final ObjectGraph objectGraph;
private String pipelineTitle = null;
// User context for the user who started the pipeline
private String token;
/*Mutex objects to synchronize start and stop pipeline methods*/
private ThreadHealthReporter threadHealthReporter;
private DataObserverRunnable observerRunnable;
private ProductionPipeline prodPipeline;
private MetricsEventRunnable metricsEventRunnable;
private int maxRetries;
private ScheduledFuture<Void> retryFuture;
private ProductionPipelineRunnable pipelineRunnable;
private boolean isRetrying;
private volatile boolean isClosed;
private volatile String metricsForRetry;
private final List<ErrorListener> errorListeners;
private static final Map<PipelineStatus, Set<PipelineStatus>> VALID_TRANSITIONS =
new ImmutableMap.Builder<PipelineStatus, Set<PipelineStatus>>()
.put(PipelineStatus.EDITED, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.STARTING, ImmutableSet.of(
PipelineStatus.START_ERROR, // Used when we can't even build runtime structures
PipelineStatus.STARTING_ERROR, // Used when runtime structures are built, but then pipeline's init() fails
PipelineStatus.RUNNING,
PipelineStatus.DISCONNECTING,
PipelineStatus.STOPPING
))
.put(PipelineStatus.STARTING_ERROR, ImmutableSet.of(
PipelineStatus.START_ERROR,
PipelineStatus.STOPPING_ERROR,
PipelineStatus.RETRY
))
.put(PipelineStatus.START_ERROR, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.RUNNING, ImmutableSet.of(
PipelineStatus.RUNNING_ERROR,
PipelineStatus.FINISHING,
PipelineStatus.STOPPING,
PipelineStatus.DISCONNECTING
))
.put(PipelineStatus.RUNNING_ERROR, ImmutableSet.of(
PipelineStatus.RETRY,
PipelineStatus.STOPPING_ERROR,
PipelineStatus.RUN_ERROR
))
.put(PipelineStatus.RETRY, ImmutableSet.of(
PipelineStatus.STARTING,
PipelineStatus.STOPPING,
PipelineStatus.DISCONNECTING
))
.put(PipelineStatus.RUN_ERROR, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.STOPPING_ERROR, ImmutableSet.of(
PipelineStatus.START_ERROR,
PipelineStatus.RUN_ERROR,
PipelineStatus.STOP_ERROR,
PipelineStatus.RETRY
))
.put(PipelineStatus.STOP_ERROR, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.FINISHING, ImmutableSet.of(
PipelineStatus.FINISHED,
PipelineStatus.STOPPING_ERROR
))
.put(PipelineStatus.STOPPING, ImmutableSet.of(
PipelineStatus.STOPPED,
PipelineStatus.STOPPING_ERROR
))
.put(PipelineStatus.FINISHED, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.STOPPED, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.DISCONNECTING, ImmutableSet.of(
PipelineStatus.DISCONNECTED
))
.put(PipelineStatus.DISCONNECTED, ImmutableSet.of(
PipelineStatus.CONNECTING,
PipelineStatus.STARTING,
PipelineStatus.RETRY
))
.put(PipelineStatus.CONNECTING, ImmutableSet.of(
PipelineStatus.STARTING,
PipelineStatus.DISCONNECTING,
PipelineStatus.RETRY
))
.build();
public StandaloneRunner(String name, String rev, ObjectGraph objectGraph) {
super(name, rev);
this.objectGraph = objectGraph;
this.errorListeners = new ArrayList<>();
objectGraph.inject(this);
}
public void addErrorListener(ErrorListener errorListener) {
this.errorListeners.add(errorListener);
}
@Override
public void prepareForDataCollectorStart(String user) throws PipelineException {
PipelineStatus status = getState().getStatus();
try {
MDC.put(LogConstants.USER, user);
LogUtil.injectPipelineInMDC(getPipelineTitle(), getName());
LOG.info("Pipeline " + getName() + " with rev " + getRev() + " is in state: " + status);
String msg = null;
List<PipelineStatus> transitions = new ArrayList<>();
switch (status) {
case STARTING:
msg = "Pipeline was in STARTING state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case RETRY:
msg = "Pipeline was in RETRY state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case CONNECTING:
msg = "Pipeline was in CONNECTING state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case RUNNING:
msg = "Pipeline was in RUNNING state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case DISCONNECTING:
msg = "Pipeline was in DISCONNECTING state, forcing it to DISCONNECTED";
transitions.add(PipelineStatus.DISCONNECTED);
break;
case STARTING_ERROR:
msg = "Pipeline was in STARTING_ERROR state, forcing it to START_ERROR";
transitions.add(PipelineStatus.START_ERROR);
break;
case STOPPING_ERROR:
msg = "Pipeline was in STOPPING_ERROR state, forcing it to STOP_ERROR";
transitions.add(PipelineStatus.STOP_ERROR);
break;
case RUNNING_ERROR:
msg = "Pipeline was in RUNNING_ERROR state, forcing it to terminal state of RUN_ERROR";
transitions.add(PipelineStatus.RUN_ERROR);
break;
case STOPPING:
msg = "Pipeline was in STOPPING state, forcing it to terminal state of STOPPED";
transitions.add(PipelineStatus.STOPPED);
break;
case FINISHING:
msg = "Pipeline was in FINISHING state, forcing it to terminal state of FINISHED";
transitions.add(PipelineStatus.FINISHED);
break;
case DISCONNECTED:
case RUN_ERROR:
case EDITED:
case FINISHED:
case KILLED:
case START_ERROR:
case STOPPED:
case STOP_ERROR:
break;
default:
throw new IllegalStateException(Utils.format("Pipeline in undefined state: '{}'", status));
}
if (msg != null) {
LOG.debug(msg);
}
// Perform the transitions
for (PipelineStatus t : transitions) {
validateAndSetStateTransition(user, t, msg, null);
}
} finally {
MDC.clear();
}
}
@Override
public void onDataCollectorStart(String user) throws PipelineException, StageException {
try {
MDC.put(LogConstants.USER, user);
LogUtil.injectPipelineInMDC(getPipelineTitle(), getName());
PipelineState pipelineState = getState();
PipelineStatus status = pipelineState.getStatus();
Map<String, Object> attributes = pipelineState.getAttributes();
LOG.info("Pipeline '{}::{}' has status: '{}'", getName(), getRev(), status);
//if the pipeline was running and capture snapshot in progress, then cancel and delete snapshots
for(SnapshotInfo snapshotInfo : getSnapshotsInfo()) {
if(snapshotInfo.isInProgress()) {
snapshotStore.deleteSnapshot(snapshotInfo.getName(), snapshotInfo.getRev(), snapshotInfo.getId());
}
}
switch (status) {
case DISCONNECTED:
String msg = "Pipeline was in DISCONNECTED state, changing it to CONNECTING";
LOG.debug(msg);
loadStartPipelineContextFromState(user);
retryOrStart(getStartPipelineContext());
break;
default:
LOG.error(Utils.format("Pipeline cannot start with status: '{}'", status));
}
} finally {
MDC.clear();
}
}
private void retryOrStart(StartPipelineContext context) throws PipelineException, StageException {
PipelineState pipelineState = getState();
if (pipelineState.getRetryAttempt() == 0 || pipelineState.getStatus() == PipelineStatus.DISCONNECTED) {
prepareForStart(context);
Configuration configuraton = objectGraph.get(Configuration.class);
LOG.info("Configuration object :::: " + configuraton.toString());
if (configuraton.get(CAPTURE_SNAPSHOT_ON_START, CAPTURE_SNAPSHOT_ON_START_DEFAULT)) {
int numBatches = configuraton.get(SNAPSHOT_NUM_BATCHES, SNAPSHOT_NUM_BATCHES_DEFAULT);
int batchSize = configuraton.get(SNAPSHOT_BATCH_SIZE, SNAPSHOT_BATCH_SIZE_DEFAULT);
LOG.info("Capturing " + numBatches + " batches of snapshot with size " + batchSize);
startAndCaptureSnapshot(context, "default", "default", numBatches, batchSize);
} else {
start(context);
}
} else {
validateAndSetStateTransition(context.getUser(), PipelineStatus.RETRY, "Changing the state to RETRY on startup", null);
isRetrying = true;
metricsForRetry = getState().getMetrics();
}
}
@Override
public void onDataCollectorStop(String user) throws PipelineException {
try {
MDC.put(LogConstants.USER, user);
LogUtil.injectPipelineInMDC(getPipelineTitle(), getName());
if (getState().getStatus() == PipelineStatus.RETRY) {
LOG.info("Pipeline '{}'::'{}' is in retry", getName(), getRev());
retryFuture.cancel(true);
validateAndSetStateTransition(user, PipelineStatus.DISCONNECTING, null, null);
validateAndSetStateTransition(user, PipelineStatus.DISCONNECTED, "Disconnected as SDC is shutting down", null);
return;
}
if (!getState().getStatus().isActive() || getState().getStatus() == PipelineStatus.DISCONNECTED) {
LOG.info("Pipeline '{}'::'{}' is no longer active", getName(), getRev());
return;
}
LOG.info("Stopping pipeline {}::{}", getName(), getRev());
try {
try {
validateAndSetStateTransition(user, PipelineStatus.DISCONNECTING, "Stopping the pipeline as SDC is shutting down",
null);
} catch (PipelineRunnerException ex) {
// its ok if state validation fails - we will still try to stop pipeline if active
LOG.warn("Cannot transition to PipelineStatus.DISCONNECTING: {}", ex.toString(), ex);
}
stopPipeline(true /* shutting down node process */);
} catch (Exception e) {
LOG.warn("Error while stopping the pipeline: {} ", e.toString(), e);
}
} finally {
MDC.clear();
}
}
@Override
public String getPipelineTitle() throws PipelineException {
if (pipelineTitle == null) {
PipelineInfo pipelineInfo = getPipelineStore().getInfo(getName());
pipelineTitle = pipelineInfo.getTitle();
}
return pipelineTitle;
}
@Override
public synchronized void resetOffset(String user) throws PipelineStoreException, PipelineRunnerException {
PipelineStatus status = getState().getStatus();
LOG.debug("Resetting offset for pipeline {}, {}", getName(), getRev());
if (RESET_OFFSET_DISALLOWED_STATUSES.contains(status)) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0104, getName());
}
ProductionSourceOffsetTracker offsetTracker = new ProductionSourceOffsetTracker(getName(), getRev(), getRuntimeInfo());
offsetTracker.resetOffset();
}
public SourceOffset getCommittedOffsets() throws PipelineException {
return OffsetFileUtil.getOffset(getRuntimeInfo(), getName(), getRev());
}
public void updateCommittedOffsets(SourceOffset sourceOffset) throws PipelineException {
PipelineStatus status = getState().getStatus();
if (status.isActive()) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0118, getName());
}
OffsetFileUtil.saveSourceOffset(getRuntimeInfo(), getName(), getRev(), sourceOffset);
}
@Override
public void stop(String user) throws PipelineException {
stopPipeline(false);
}
@Override
public void forceQuit(String user) throws PipelineException {
if (pipelineRunnable != null && FORCE_QUIT_ALLOWED_STATES.contains(getState().getStatus())) {
LOG.debug("Force Quit the pipeline '{}'::'{}'", getName(), getRev());
pipelineRunnable.forceQuit();
} else {
LOG.info("Ignoring force quit request because pipeline is in {} state", getState().getStatus());
}
}
@Override
public Object getMetrics() throws PipelineStoreException {
if (prodPipeline != null) {
Object metrics = prodPipeline.getPipeline().getRunner().getMetrics();
if (metrics == null && getState().getStatus().isActive()) {
return metricsForRetry;
} else {
return metrics;
}
}
return null;
}
@Override
public String captureSnapshot(
String user,
String snapshotName,
String snapshotLabel,
int batches,
int batchSize
) throws PipelineException {
if(batchSize <= 0) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0107, batchSize);
}
return captureSnapshot(user, snapshotName, snapshotLabel, batches, batchSize, true);
}
public String captureSnapshot(
String user,
String snapshotName,
String snapshotLabel,
int batches,
int batchSize,
boolean checkState
) throws PipelineException {
int maxBatchSize = getConfiguration().get(Constants.SNAPSHOT_MAX_BATCH_SIZE_KEY, Constants.SNAPSHOT_MAX_BATCH_SIZE_DEFAULT);
if(batchSize > maxBatchSize) {
batchSize = maxBatchSize;
}
LOG.debug("Capturing snapshot with batch size {}", batchSize);
if (checkState) {
checkState(getState().getStatus().equals(PipelineStatus.RUNNING), ContainerError.CONTAINER_0105);
}
SnapshotInfo snapshotInfo = snapshotStore.create(user, getName(), getRev(), snapshotName, snapshotLabel, false);
prodPipeline.captureSnapshot(snapshotName, batchSize, batches);
return snapshotInfo.getId();
}
@Override
public String updateSnapshotLabel(String snapshotName, String snapshotLabel)
throws PipelineException {
SnapshotInfo snapshotInfo = snapshotStore.updateLabel(getName(), getRev(), snapshotName, snapshotLabel);
if(snapshotInfo != null) {
return snapshotInfo.getId();
}
return null;
}
@Override
public Snapshot getSnapshot(String id) throws PipelineException {
return snapshotStore.get(getName(), getRev(), id);
}
@Override
public List<SnapshotInfo> getSnapshotsInfo() throws PipelineException {
return snapshotStore.getSummaryForPipeline(getName(), getRev());
}
@Override
public void deleteSnapshot(String id) throws PipelineException {
Snapshot snapshot = getSnapshot(id);
if(snapshot != null && snapshot.getInfo() != null && snapshot.getInfo().isInProgress()) {
prodPipeline.cancelSnapshot(snapshot.getInfo().getId());
}
snapshotStore.deleteSnapshot(getName(), getRev(), id);
}
@Override
public List<Record> getErrorRecords(String stage, int max) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0106);
return prodPipeline.getErrorRecords(stage, max);
}
@Override
public List<ErrorMessage> getErrorMessages(String stage, int max) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0106);
return prodPipeline.getErrorMessages(stage, max);
}
@Override
public List<SampledRecord> getSampledRecords(String sampleId, int max) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0106);
return observerRunnable.getSampledRecords(sampleId, max);
}
@Override
@SuppressWarnings("unchecked")
public List<AlertInfo> getAlerts() throws PipelineException {
List<AlertInfo> alertInfoList = new ArrayList<>();
MetricRegistry metrics = (MetricRegistry)getMetrics();
if(metrics != null) {
RuleDefinitions ruleDefinitions = getPipelineStore().retrieveRules(getName(), getRev());
for(RuleDefinition ruleDefinition: ruleDefinitions.getMetricsRuleDefinitions()) {
Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
AlertsUtil.getAlertGaugeName(ruleDefinition.getId()));
if(gauge != null) {
alertInfoList.add(new AlertInfo(getName(), ruleDefinition, gauge));
}
}
for(RuleDefinition ruleDefinition: ruleDefinitions.getAllDataRuleDefinitions()) {
Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
AlertsUtil.getAlertGaugeName(ruleDefinition.getId()));
if(gauge != null) {
alertInfoList.add(new AlertInfo(getName(), ruleDefinition, gauge));
}
}
}
return alertInfoList;
}
@Override
public boolean deleteAlert(String alertId) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0402);
MetricsConfigurator.resetCounter((MetricRegistry) getMetrics(), AlertsUtil.getUserMetricName(alertId));
return MetricsConfigurator.removeGauge((MetricRegistry) getMetrics(), AlertsUtil.getAlertGaugeName(alertId), getName(), getRev());
}
@Override
public void stateChanged(PipelineStatus pipelineStatus, String message, Map<String, Object> attributes)
throws PipelineRuntimeException {
try {
Map<String, Object> allAttributes = null;
if (attributes != null) {
allAttributes = new HashMap<>();
allAttributes.putAll(getState().getAttributes());
allAttributes.putAll(attributes);
}
validateAndSetStateTransition(getState().getUser(), pipelineStatus, message, allAttributes);
if (pipelineStatus == PipelineStatus.FINISHED && metricsEventRunnable != null) {
this.metricsEventRunnable.onStopOrFinishPipeline();
}
} catch (PipelineStoreException | PipelineRunnerException ex) {
throw new PipelineRuntimeException(ex.getErrorCode(), ex);
}
}
private void validateAndSetStateTransition(String user, PipelineStatus toStatus, String message, Map<String, Object> attributes)
throws PipelineStoreException, PipelineRunnerException {
PipelineState fromState;
PipelineState pipelineState;
synchronized (this) {
fromState = getState();
checkState(VALID_TRANSITIONS.get(fromState.getStatus()).contains(toStatus), ContainerError.CONTAINER_0102,
fromState.getStatus(), toStatus);
long nextRetryTimeStamp = fromState.getNextRetryTimeStamp();
int retryAttempt = fromState.getRetryAttempt();
String metricString = null;
if (toStatus == PipelineStatus.RETRY && fromState.getStatus() != PipelineStatus.CONNECTING) {
retryAttempt = fromState.getRetryAttempt() + 1;
if (retryAttempt > maxRetries && maxRetries != -1) {
LOG.info("Retry attempt '{}' is greater than max no of retries '{}'", retryAttempt, maxRetries);
toStatus = PipelineStatus.RUN_ERROR;
retryAttempt = 0;
nextRetryTimeStamp = 0;
} else {
nextRetryTimeStamp = RetryUtils.getNextRetryTimeStamp(retryAttempt, System.currentTimeMillis());
isRetrying = true;
metricsForRetry = getState().getMetrics();
}
} else if (!toStatus.isActive()) {
retryAttempt = 0;
nextRetryTimeStamp = 0;
}
if (!toStatus.isActive() || toStatus == PipelineStatus.DISCONNECTED
|| (toStatus == PipelineStatus.RETRY && fromState.getStatus() != PipelineStatus.CONNECTING)) {
Object metrics = getMetrics();
if (metrics != null) {
ObjectMapper objectMapper = ObjectMapperFactory.get();
try {
metricString = objectMapper.writeValueAsString(metrics);
} catch (JsonProcessingException e) {
throw new PipelineStoreException(ContainerError.CONTAINER_0210, e.toString(), e);
}
getEventListenerManager().broadcastMetrics(getName(), metricString);
}
if (metricString == null) {
metricString = getState().getMetrics();
}
}
pipelineState =
getPipelineStateStore().saveState(user, getName(), getRev(), toStatus, message, attributes, ExecutionMode.STANDALONE,
metricString, retryAttempt, nextRetryTimeStamp);
if (toStatus == PipelineStatus.RETRY) {
retryFuture = scheduleForRetries(runnerExecutor);
}
}
getEventListenerManager().broadcastStateChange(
fromState,
pipelineState,
ThreadUsage.STANDALONE,
OffsetFileUtil.getOffsets(getRuntimeInfo(), getName(), getRev())
);
}
private void checkState(boolean expr, ContainerError error, Object... args) throws PipelineRunnerException {
if (!expr) {
throw new PipelineRunnerException(error, args);
}
}
@Override
public void prepareForStart(StartPipelineContext context) throws PipelineStoreException, PipelineRunnerException {
PipelineState fromState = getState();
checkState(VALID_TRANSITIONS.get(fromState.getStatus()).contains(PipelineStatus.STARTING), ContainerError.CONTAINER_0102,
fromState.getStatus(), PipelineStatus.STARTING);
if(!resourceManager.requestRunnerResources(ThreadUsage.STANDALONE)) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0166, getName());
}
LOG.info("Preparing to start pipeline '{}::{}'", getName(), getRev());
setStartPipelineContext(context);
validateAndSetStateTransition(context.getUser(), PipelineStatus.STARTING, null, createNewStateAttributes());
token = UUID.randomUUID().toString();
}
@Override
public void prepareForStop(String user) throws PipelineStoreException, PipelineRunnerException {
LOG.info("Preparing to stop pipeline");
if (getState().getStatus() == PipelineStatus.RETRY) {
retryFuture.cancel(true);
validateAndSetStateTransition(user, PipelineStatus.STOPPING, null, null);
validateAndSetStateTransition(user, PipelineStatus.STOPPED, "Stopped while the pipeline was in RETRY state", null);
} else {
validateAndSetStateTransition(user, PipelineStatus.STOPPING, null, null);
}
}
@Override
public void start(StartPipelineContext context) throws PipelineException, StageException {
startPipeline(context);
LOG.debug("Starting the runnable for pipeline {} {}", getName(), getRev());
if(!pipelineRunnable.isStopped()) {
pipelineRunnable.run();
}
}
private void startPipeline(StartPipelineContext context) throws PipelineException, StageException {
Utils.checkState(!isClosed,
Utils.formatL("Cannot start the pipeline '{}::{}' as the runner is already closed", getName(), getRev()));
synchronized (this) {
try {
LOG.info("Starting pipeline {} {}", getName(), getRev());
setStartPipelineContext(context);
UserContext runningUser = new UserContext(context.getUser(),
getRuntimeInfo().isDPMEnabled(),
getConfiguration().get(
RemoteSSOService.DPM_USER_ALIAS_NAME_ENABLED,
RemoteSSOService.DPM_USER_ALIAS_NAME_ENABLED_DEFAULT
)
);
/*
* Implementation Notes: --------------------- What are the different threads and runnables created? - - - - - - - -
* - - - - - - - - - - - - - - - - - - - RulesConfigLoader ProductionObserver MetricObserver
* ProductionPipelineRunner How do threads communicate? - - - - - - - - - - - - - - RulesConfigLoader,
* ProductionObserver and ProductionPipelineRunner share a blocking queue which will hold record samples to be
* evaluated by the Observer [Data Rule evaluation] and rules configuration change requests computed by the
* RulesConfigLoader. MetricsObserverRunner handles evaluating metric rules and a reference is passed to Production
* Observer which updates the MetricsObserverRunner when configuration changes. Other classes: - - - - - - - - Alert
* Manager - responsible for creating alerts and sending email.
*/
PipelineConfiguration pipelineConfiguration = getPipelineConf(getName(), getRev());
List<Issue> errors = new ArrayList<>();
PipelineEL.setConstantsInContext(pipelineConfiguration, runningUser, getState().getTimeStamp());
PipelineConfigBean pipelineConfigBean = PipelineBeanCreator.get().create(
pipelineConfiguration,
errors,
getStartPipelineContext().getRuntimeParameters()
);
if (pipelineConfigBean == null) {
throw new PipelineRuntimeException(ContainerError.CONTAINER_0116, errors);
}
JobEL.setConstantsInContext(pipelineConfigBean.constants);
maxRetries = pipelineConfigBean.retryAttempts;
BlockingQueue<Object> productionObserveRequests =
new ArrayBlockingQueue<>(getConfiguration().get(Constants.OBSERVER_QUEUE_SIZE_KEY,
Constants.OBSERVER_QUEUE_SIZE_DEFAULT), true /* FIFO */);
BlockingQueue<Record> statsQueue = null;
boolean statsAggregationEnabled = isStatsAggregationEnabled(pipelineConfiguration);
if (statsAggregationEnabled) {
statsQueue = new ArrayBlockingQueue<>(
getConfiguration().get(
Constants.STATS_AGGREGATOR_QUEUE_SIZE_KEY,
Constants.STATS_AGGREGATOR_QUEUE_SIZE_DEFAULT
),
true /* FIFO */
);
}
//Need to augment the existing object graph with pipeline related modules.
//This ensures that the singletons defined in those modules are singletons within the
//scope of a pipeline.
//So if a pipeline is started again for the second time, the object graph recreates the production pipeline
//with fresh instances of MetricRegistry, alert manager, observer etc etc..
ObjectGraph objectGraph = this.objectGraph.plus(
new PipelineProviderModule(
getName(),
pipelineConfiguration.getTitle(),
getRev(),
statsAggregationEnabled,
pipelineConfigBean.constants
)
);
threadHealthReporter = objectGraph.get(ThreadHealthReporter.class);
observerRunnable = objectGraph.get(DataObserverRunnable.class);
metricsEventRunnable = objectGraph.get(MetricsEventRunnable.class);
ImmutableList.Builder<Future<?>> taskBuilder = ImmutableList.builder();
ProductionObserver productionObserver = (ProductionObserver) objectGraph.get(Observer.class);
productionObserver.setPipelineStartTime(getState().getTimeStamp());
RulesConfigLoader rulesConfigLoader = objectGraph.get(RulesConfigLoader.class);
RulesConfigLoaderRunnable rulesConfigLoaderRunnable = objectGraph.get(RulesConfigLoaderRunnable.class);
MetricObserverRunnable metricObserverRunnable = objectGraph.get(MetricObserverRunnable.class);
ProductionPipelineRunner runner = (ProductionPipelineRunner) objectGraph.get(PipelineRunner.class);
runner.addErrorListeners(errorListeners);
if (isRetrying) {
ObjectMapper objectMapper = ObjectMapperFactory.get();
MetricRegistryJson metricRegistryJson = null;
try {
if (metricsForRetry != null) {
metricRegistryJson = objectMapper.readValue(metricsForRetry, MetricRegistryJson.class);
runner.updateMetrics(metricRegistryJson);
observerRunnable.setMetricRegistryJson(metricRegistryJson);
}
} catch (IOException ex) {
LOG.warn("Error while serializing slave metrics: , {}", ex.toString(), ex);
}
isRetrying = false;
}
if (pipelineConfigBean.rateLimit > 0) {
runner.setRateLimit(pipelineConfigBean.rateLimit);
}
ProductionPipelineBuilder builder = objectGraph.get(ProductionPipelineBuilder.class);
//register email notifier & webhook notifier with event listener manager
registerEmailNotifierIfRequired(pipelineConfigBean, getName(), pipelineConfiguration.getTitle(), getRev());
registerWebhookNotifierIfRequired(pipelineConfigBean, getName(), pipelineConfiguration.getTitle(), getRev());
//This which are not injected as of now.
productionObserver.setObserveRequests(productionObserveRequests);
runner.setObserveRequests(productionObserveRequests);
runner.setStatsAggregatorRequests(statsQueue);
runner.setDeliveryGuarantee(pipelineConfigBean.deliveryGuarantee);
prodPipeline = builder.build(
runningUser,
pipelineConfiguration,
getState().getTimeStamp(),
context.getInterceptorConfigurations(),
context.getRuntimeParameters()
);
prodPipeline.registerStatusListener(this);
ScheduledFuture<?> metricsFuture = null;
metricsEventRunnable.setStatsQueue(statsQueue);
metricsEventRunnable.setPipelineConfiguration(pipelineConfiguration);
int refreshInterval = getConfiguration().get(MetricsEventRunnable.REFRESH_INTERVAL_PROPERTY,
MetricsEventRunnable.REFRESH_INTERVAL_PROPERTY_DEFAULT);
if(refreshInterval > 0) {
metricsFuture = runnerExecutor.scheduleAtFixedRate(
metricsEventRunnable,
0,
metricsEventRunnable.getScheduledDelay(),
TimeUnit.MILLISECONDS
);
taskBuilder.add(metricsFuture);
}
//Schedule Rules Config Loader
rulesConfigLoader.setStatsQueue(statsQueue);
try {
rulesConfigLoader.load(productionObserver);
} catch (InterruptedException e) {
throw new PipelineRuntimeException(ContainerError.CONTAINER_0403, getName(), e.toString(), e);
}
ScheduledFuture<?> configLoaderFuture = runnerExecutor.scheduleWithFixedDelay(
rulesConfigLoaderRunnable,
1,
RulesConfigLoaderRunnable.SCHEDULED_DELAY,
TimeUnit.SECONDS
);
taskBuilder.add(configLoaderFuture);
ScheduledFuture<?> metricObserverFuture = runnerExecutor.scheduleWithFixedDelay(
metricObserverRunnable,
1,
2,
TimeUnit.SECONDS
);
taskBuilder.add(metricObserverFuture);
// Schedule a task to run empty batches for idle runners
if(pipelineConfigBean.runnerIdleTIme > 0) {
ProduceEmptyBatchesForIdleRunnersRunnable idleRunnersRunnable = new ProduceEmptyBatchesForIdleRunnersRunnable(
runner,
pipelineConfigBean.runnerIdleTIme * 1000 // The value inside the runnable is in milliseconds whereas user config is in seconds
);
// We'll schedule the task to run every 1/10 of the interval (really an arbitrary number)
long period = (pipelineConfigBean.runnerIdleTIme * 1000 )/ 10;
ScheduledFuture<?> idleRunnersFuture = runnerExecutor.scheduleWithFixedDelay(
idleRunnersRunnable,
period,
period,
TimeUnit.MILLISECONDS
);
taskBuilder.add(idleRunnersFuture);
}
observerRunnable.setRequestQueue(productionObserveRequests);
observerRunnable.setStatsQueue(statsQueue);
Future<?> observerFuture = runnerExecutor.submit(observerRunnable);
taskBuilder.add(observerFuture);
pipelineRunnable = new ProductionPipelineRunnable(threadHealthReporter, this, prodPipeline, getName(), getRev(), taskBuilder.build());
} catch (Exception e) {
validateAndSetStateTransition(context.getUser(), PipelineStatus.START_ERROR, e.toString(), null);
throw e;
}
}
}
@Override
public void startAndCaptureSnapshot(
StartPipelineContext context,
String snapshotName,
String snapshotLabel,
int batches,
int batchSize
) throws PipelineException, StageException {
// Method startPipeline() have already try-catch that is handling state transitions
startPipeline(context);
// Method captureSnapshot() doesn't have proper try-catch for state transitions (since it generally doesn't make
// sense there) and thus we do the state transitions here.
try {
captureSnapshot(context.getUser(), snapshotName, snapshotLabel, batches, batchSize, false);
} catch (Exception e) {
LOG.error("Can't start and get snapshot for pipeline {}: {}", getName(), e.toString(), e);
validateAndSetStateTransition(context.getUser(), PipelineStatus.START_ERROR, e.toString(), null);
throw e;
}
LOG.debug("Starting the runnable for pipeline {} {}", getName(), getRev());
if (!pipelineRunnable.isStopped()) {
pipelineRunnable.run();
}
}
private boolean isStatsAggregationEnabled(PipelineConfiguration pipelineConfiguration) throws PipelineStoreException {
boolean isEnabled = false;
StageConfiguration statsAggregatorStage = pipelineConfiguration.getStatsAggregatorStage();
if (statsAggregatorStage != null &&
!statsAggregatorStage.getStageName().equals(STATS_NULL_TARGET) &&
!statsAggregatorStage.getStageName().equals(STATS_DPM_DIRECTLY_TARGET) &&
pipelineConfiguration.getMetadata() != null) {
isEnabled = true;
}
return isEnabled && this.isRemotePipeline();
}
private void stopPipeline(boolean sdcShutting) throws PipelineException {
if (pipelineRunnable != null && !pipelineRunnable.isStopped()) {
LOG.info("Stopping pipeline {} {}", pipelineRunnable.getName(), pipelineRunnable.getRev());
// this is sync call, will wait till pipeline is in terminal state
pipelineRunnable.stop(sdcShutting);
pipelineRunnable = null;
}
if (metricsEventRunnable != null) {
metricsEventRunnable.onStopOrFinishPipeline();
metricsEventRunnable = null;
}
if (threadHealthReporter != null) {
threadHealthReporter.destroy();
threadHealthReporter = null;
}
}
@Override
public void close() {
isClosed = true;
}
public Pipeline getPipeline() {
return prodPipeline != null ? prodPipeline.getPipeline() : null;
}
@Override
public Collection<CallbackInfo> getSlaveCallbackList(CallbackObjectType callbackObjectType) {
throw new UnsupportedOperationException("This method is only supported in Cluster Runner");
}
@Override
public Map<String, Object> updateSlaveCallbackInfo(CallbackInfo callbackInfo) {
throw new UnsupportedOperationException("This method is only supported in Cluster Runner");
}
@Override
public String getToken() {
return token;
}
@Override
public int getRunnerCount() {
return prodPipeline != null ? prodPipeline.getPipeline().getNumOfRunners() : 0;
}
@Override
public Runner getDelegatingRunner() {
return null;
}
private static int getNumBatches() {
String sNumBatches = System.getenv(SNAPSHOT_NUM_BATCHES);
return null != sNumBatches && sNumBatches.matches("\\d+") ? Integer.parseInt(sNumBatches) : 1;
}
private static int getBatchSize() {
String sBatchSize = System.getenv(SNAPSHOT_BATCH_SIZE);
return null != sBatchSize && sBatchSize.matches("\\d+") ? Integer.parseInt(sBatchSize) : 10;
}
}
|
container/src/main/java/com/streamsets/datacollector/execution/runner/standalone/StandaloneRunner.java
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.execution.runner.standalone;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.streamsets.datacollector.alerts.AlertsUtil;
import com.streamsets.datacollector.callback.CallbackInfo;
import com.streamsets.datacollector.callback.CallbackObjectType;
import com.streamsets.datacollector.config.PipelineConfiguration;
import com.streamsets.datacollector.config.RuleDefinition;
import com.streamsets.datacollector.config.RuleDefinitions;
import com.streamsets.datacollector.config.StageConfiguration;
import com.streamsets.datacollector.creation.PipelineBeanCreator;
import com.streamsets.datacollector.creation.PipelineConfigBean;
import com.streamsets.datacollector.el.JobEL;
import com.streamsets.datacollector.el.PipelineEL;
import com.streamsets.datacollector.event.json.MetricRegistryJson;
import com.streamsets.datacollector.execution.AbstractRunner;
import com.streamsets.datacollector.execution.PipelineState;
import com.streamsets.datacollector.execution.PipelineStatus;
import com.streamsets.datacollector.execution.Runner;
import com.streamsets.datacollector.execution.Snapshot;
import com.streamsets.datacollector.execution.SnapshotInfo;
import com.streamsets.datacollector.execution.SnapshotStore;
import com.streamsets.datacollector.execution.StateListener;
import com.streamsets.datacollector.execution.alerts.AlertInfo;
import com.streamsets.datacollector.execution.metrics.MetricsEventRunnable;
import com.streamsets.datacollector.execution.runner.RetryUtils;
import com.streamsets.datacollector.execution.runner.common.Constants;
import com.streamsets.datacollector.execution.runner.common.DataObserverRunnable;
import com.streamsets.datacollector.execution.runner.common.MetricObserverRunnable;
import com.streamsets.datacollector.execution.runner.common.PipelineRunnerException;
import com.streamsets.datacollector.execution.runner.common.ProduceEmptyBatchesForIdleRunnersRunnable;
import com.streamsets.datacollector.execution.runner.common.ProductionObserver;
import com.streamsets.datacollector.execution.runner.common.ProductionPipeline;
import com.streamsets.datacollector.execution.runner.common.ProductionPipelineBuilder;
import com.streamsets.datacollector.execution.runner.common.ProductionPipelineRunnable;
import com.streamsets.datacollector.execution.runner.common.ProductionPipelineRunner;
import com.streamsets.datacollector.execution.runner.common.RulesConfigLoader;
import com.streamsets.datacollector.execution.runner.common.SampledRecord;
import com.streamsets.datacollector.execution.runner.common.ThreadHealthReporter;
import com.streamsets.datacollector.execution.runner.common.dagger.PipelineProviderModule;
import com.streamsets.datacollector.json.ObjectMapperFactory;
import com.streamsets.datacollector.metrics.MetricsConfigurator;
import com.streamsets.datacollector.runner.Observer;
import com.streamsets.datacollector.runner.Pipeline;
import com.streamsets.datacollector.runner.PipelineRunner;
import com.streamsets.datacollector.runner.PipelineRuntimeException;
import com.streamsets.datacollector.runner.UserContext;
import com.streamsets.datacollector.runner.production.OffsetFileUtil;
import com.streamsets.datacollector.runner.production.ProductionSourceOffsetTracker;
import com.streamsets.datacollector.runner.production.RulesConfigLoaderRunnable;
import com.streamsets.datacollector.runner.production.SourceOffset;
import com.streamsets.datacollector.store.PipelineInfo;
import com.streamsets.datacollector.store.PipelineStoreException;
import com.streamsets.datacollector.util.Configuration;
import com.streamsets.datacollector.util.ContainerError;
import com.streamsets.datacollector.util.LogUtil;
import com.streamsets.datacollector.util.PipelineException;
import com.streamsets.datacollector.validation.Issue;
import com.streamsets.dc.execution.manager.standalone.ResourceManager;
import com.streamsets.dc.execution.manager.standalone.ThreadUsage;
import com.streamsets.lib.security.http.RemoteSSOService;
import com.streamsets.pipeline.api.ErrorListener;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.impl.ErrorMessage;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.executor.SafeScheduledExecutorService;
import com.streamsets.pipeline.lib.log.LogConstants;
import dagger.ObjectGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class StandaloneRunner extends AbstractRunner implements StateListener {
private static final Logger LOG = LoggerFactory.getLogger(StandaloneRunner.class);
public static final String STATS_NULL_TARGET = "com_streamsets_pipeline_stage_destination_devnull_StatsNullDTarget";
public static final String STATS_DPM_DIRECTLY_TARGET =
"com_streamsets_pipeline_stage_destination_devnull_StatsDpmDirectlyDTarget";
public static final String CAPTURE_SNAPSHOT_ON_START = "capture.snapshot.on.start";
public static final boolean CAPTURE_SNAPSHOT_ON_START_DEFAULT = false;
public static final String SNAPSHOT_NUM_BATCHES = "snapshot.num.batches";
public static final int SNAPSHOT_NUM_BATCHES_DEFAULT = 1;
public static final String SNAPSHOT_BATCH_SIZE = "snapshot.batch.size";
public static final int SNAPSHOT_BATCH_SIZE_DEFAULT = 10;
private static final ImmutableList<PipelineStatus> RESET_OFFSET_DISALLOWED_STATUSES = ImmutableList.of(
PipelineStatus.CONNECTING,
PipelineStatus.DISCONNECTING,
PipelineStatus.FINISHING,
PipelineStatus.RETRY,
PipelineStatus.RUNNING,
PipelineStatus.STARTING,
PipelineStatus.STOPPING
);
private static final ImmutableSet<PipelineStatus> FORCE_QUIT_ALLOWED_STATES = ImmutableSet.of(
PipelineStatus.STOPPING,
PipelineStatus.STOPPING_ERROR,
PipelineStatus.STARTING_ERROR,
PipelineStatus.RUNNING_ERROR,
PipelineStatus.FINISHING
);
@Inject SnapshotStore snapshotStore;
@Inject @Named("runnerExecutor") SafeScheduledExecutorService runnerExecutor;
@Inject ResourceManager resourceManager;
private final ObjectGraph objectGraph;
private String pipelineTitle = null;
// User context for the user who started the pipeline
private String token;
/*Mutex objects to synchronize start and stop pipeline methods*/
private ThreadHealthReporter threadHealthReporter;
private DataObserverRunnable observerRunnable;
private ProductionPipeline prodPipeline;
private MetricsEventRunnable metricsEventRunnable;
private int maxRetries;
private ScheduledFuture<Void> retryFuture;
private ProductionPipelineRunnable pipelineRunnable;
private boolean isRetrying;
private volatile boolean isClosed;
private volatile String metricsForRetry;
private final List<ErrorListener> errorListeners;
private static final Map<PipelineStatus, Set<PipelineStatus>> VALID_TRANSITIONS =
new ImmutableMap.Builder<PipelineStatus, Set<PipelineStatus>>()
.put(PipelineStatus.EDITED, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.STARTING, ImmutableSet.of(
PipelineStatus.START_ERROR, // Used when we can't even build runtime structures
PipelineStatus.STARTING_ERROR, // Used when runtime structures are built, but then pipeline's init() fails
PipelineStatus.RUNNING,
PipelineStatus.DISCONNECTING,
PipelineStatus.STOPPING
))
.put(PipelineStatus.STARTING_ERROR, ImmutableSet.of(
PipelineStatus.START_ERROR,
PipelineStatus.STOPPING_ERROR,
PipelineStatus.RETRY
))
.put(PipelineStatus.START_ERROR, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.RUNNING, ImmutableSet.of(
PipelineStatus.RUNNING_ERROR,
PipelineStatus.FINISHING,
PipelineStatus.STOPPING,
PipelineStatus.DISCONNECTING
))
.put(PipelineStatus.RUNNING_ERROR, ImmutableSet.of(
PipelineStatus.RETRY,
PipelineStatus.STOPPING_ERROR,
PipelineStatus.RUN_ERROR
))
.put(PipelineStatus.RETRY, ImmutableSet.of(
PipelineStatus.STARTING,
PipelineStatus.STOPPING,
PipelineStatus.DISCONNECTING
))
.put(PipelineStatus.RUN_ERROR, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.STOPPING_ERROR, ImmutableSet.of(
PipelineStatus.START_ERROR,
PipelineStatus.RUN_ERROR,
PipelineStatus.STOP_ERROR,
PipelineStatus.RETRY
))
.put(PipelineStatus.STOP_ERROR, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.FINISHING, ImmutableSet.of(
PipelineStatus.FINISHED,
PipelineStatus.STOPPING_ERROR
))
.put(PipelineStatus.STOPPING, ImmutableSet.of(
PipelineStatus.STOPPED,
PipelineStatus.STOPPING_ERROR
))
.put(PipelineStatus.FINISHED, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.STOPPED, ImmutableSet.of(
PipelineStatus.STARTING
))
.put(PipelineStatus.DISCONNECTING, ImmutableSet.of(
PipelineStatus.DISCONNECTED
))
.put(PipelineStatus.DISCONNECTED, ImmutableSet.of(
PipelineStatus.CONNECTING,
PipelineStatus.STARTING,
PipelineStatus.RETRY
))
.put(PipelineStatus.CONNECTING, ImmutableSet.of(
PipelineStatus.STARTING,
PipelineStatus.DISCONNECTING,
PipelineStatus.RETRY
))
.build();
public StandaloneRunner(String name, String rev, ObjectGraph objectGraph) {
super(name, rev);
this.objectGraph = objectGraph;
this.errorListeners = new ArrayList<>();
objectGraph.inject(this);
}
public void addErrorListener(ErrorListener errorListener) {
this.errorListeners.add(errorListener);
}
@Override
public void prepareForDataCollectorStart(String user) throws PipelineException {
PipelineStatus status = getState().getStatus();
try {
MDC.put(LogConstants.USER, user);
LogUtil.injectPipelineInMDC(getPipelineTitle(), getName());
LOG.info("Pipeline " + getName() + " with rev " + getRev() + " is in state: " + status);
String msg = null;
List<PipelineStatus> transitions = new ArrayList<>();
switch (status) {
case STARTING:
msg = "Pipeline was in STARTING state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case RETRY:
msg = "Pipeline was in RETRY state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case CONNECTING:
msg = "Pipeline was in CONNECTING state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case RUNNING:
msg = "Pipeline was in RUNNING state, forcing it to DISCONNECTING";
transitions.add(PipelineStatus.DISCONNECTING);
transitions.add(PipelineStatus.DISCONNECTED);
break;
case DISCONNECTING:
msg = "Pipeline was in DISCONNECTING state, forcing it to DISCONNECTED";
transitions.add(PipelineStatus.DISCONNECTED);
break;
case STARTING_ERROR:
msg = "Pipeline was in STARTING_ERROR state, forcing it to START_ERROR";
transitions.add(PipelineStatus.START_ERROR);
break;
case STOPPING_ERROR:
msg = "Pipeline was in STOPPING_ERROR state, forcing it to STOP_ERROR";
transitions.add(PipelineStatus.STOP_ERROR);
break;
case RUNNING_ERROR:
msg = "Pipeline was in RUNNING_ERROR state, forcing it to terminal state of RUN_ERROR";
transitions.add(PipelineStatus.RUN_ERROR);
break;
case STOPPING:
msg = "Pipeline was in STOPPING state, forcing it to terminal state of STOPPED";
transitions.add(PipelineStatus.STOPPED);
break;
case FINISHING:
msg = "Pipeline was in FINISHING state, forcing it to terminal state of FINISHED";
transitions.add(PipelineStatus.FINISHED);
break;
case DISCONNECTED:
case RUN_ERROR:
case EDITED:
case FINISHED:
case KILLED:
case START_ERROR:
case STOPPED:
case STOP_ERROR:
break;
default:
throw new IllegalStateException(Utils.format("Pipeline in undefined state: '{}'", status));
}
if (msg != null) {
LOG.debug(msg);
}
// Perform the transitions
for (PipelineStatus t : transitions) {
validateAndSetStateTransition(user, t, msg, null);
}
} finally {
MDC.clear();
}
}
@Override
public void onDataCollectorStart(String user) throws PipelineException, StageException {
try {
MDC.put(LogConstants.USER, user);
LogUtil.injectPipelineInMDC(getPipelineTitle(), getName());
PipelineState pipelineState = getState();
PipelineStatus status = pipelineState.getStatus();
Map<String, Object> attributes = pipelineState.getAttributes();
LOG.info("Pipeline '{}::{}' has status: '{}'", getName(), getRev(), status);
//if the pipeline was running and capture snapshot in progress, then cancel and delete snapshots
for(SnapshotInfo snapshotInfo : getSnapshotsInfo()) {
if(snapshotInfo.isInProgress()) {
snapshotStore.deleteSnapshot(snapshotInfo.getName(), snapshotInfo.getRev(), snapshotInfo.getId());
}
}
switch (status) {
case DISCONNECTED:
String msg = "Pipeline was in DISCONNECTED state, changing it to CONNECTING";
LOG.debug(msg);
loadStartPipelineContextFromState(user);
retryOrStart(getStartPipelineContext());
break;
default:
LOG.error(Utils.format("Pipeline cannot start with status: '{}'", status));
}
} finally {
MDC.clear();
}
}
private void retryOrStart(StartPipelineContext context) throws PipelineException, StageException {
PipelineState pipelineState = getState();
if (pipelineState.getRetryAttempt() == 0 || pipelineState.getStatus() == PipelineStatus.DISCONNECTED) {
prepareForStart(context);
Configuration configuraton = objectGraph.get(Configuration.class);
LOG.info("Configuration object :::: " + configuraton.toString());
if (configuraton.get(CAPTURE_SNAPSHOT_ON_START, CAPTURE_SNAPSHOT_ON_START_DEFAULT)) {
int numBatches = configuraton.get(SNAPSHOT_NUM_BATCHES, SNAPSHOT_NUM_BATCHES_DEFAULT);
int batchSize = configuraton.get(SNAPSHOT_BATCH_SIZE, SNAPSHOT_BATCH_SIZE_DEFAULT);
LOG.info("Capturing " + numBatches + " batches of snapshot with size " + batchSize);
startAndCaptureSnapshot(context, "default", "default", numBatches, batchSize);
} else {
start(context);
}
} else {
validateAndSetStateTransition(context.getUser(), PipelineStatus.RETRY, "Changing the state to RETRY on startup", null);
isRetrying = true;
metricsForRetry = getState().getMetrics();
}
}
@Override
public void onDataCollectorStop(String user) throws PipelineException {
try {
MDC.put(LogConstants.USER, user);
LogUtil.injectPipelineInMDC(getPipelineTitle(), getName());
if (getState().getStatus() == PipelineStatus.RETRY) {
LOG.info("Pipeline '{}'::'{}' is in retry", getName(), getRev());
retryFuture.cancel(true);
validateAndSetStateTransition(user, PipelineStatus.DISCONNECTING, null, null);
validateAndSetStateTransition(user, PipelineStatus.DISCONNECTED, "Disconnected as SDC is shutting down", null);
return;
}
if (!getState().getStatus().isActive() || getState().getStatus() == PipelineStatus.DISCONNECTED) {
LOG.info("Pipeline '{}'::'{}' is no longer active", getName(), getRev());
return;
}
LOG.info("Stopping pipeline {}::{}", getName(), getRev());
try {
try {
validateAndSetStateTransition(user, PipelineStatus.DISCONNECTING, "Stopping the pipeline as SDC is shutting down",
null);
} catch (PipelineRunnerException ex) {
// its ok if state validation fails - we will still try to stop pipeline if active
LOG.warn("Cannot transition to PipelineStatus.DISCONNECTING: {}", ex.toString(), ex);
}
stopPipeline(true /* shutting down node process */);
} catch (Exception e) {
LOG.warn("Error while stopping the pipeline: {} ", e.toString(), e);
}
} finally {
MDC.clear();
}
}
@Override
public String getPipelineTitle() throws PipelineException {
if (pipelineTitle == null) {
PipelineInfo pipelineInfo = getPipelineStore().getInfo(getName());
pipelineTitle = pipelineInfo.getTitle();
}
return pipelineTitle;
}
@Override
public synchronized void resetOffset(String user) throws PipelineStoreException, PipelineRunnerException {
PipelineStatus status = getState().getStatus();
LOG.debug("Resetting offset for pipeline {}, {}", getName(), getRev());
if (RESET_OFFSET_DISALLOWED_STATUSES.contains(status)) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0104, getName());
}
ProductionSourceOffsetTracker offsetTracker = new ProductionSourceOffsetTracker(getName(), getRev(), getRuntimeInfo());
offsetTracker.resetOffset();
}
public SourceOffset getCommittedOffsets() throws PipelineException {
return OffsetFileUtil.getOffset(getRuntimeInfo(), getName(), getRev());
}
public void updateCommittedOffsets(SourceOffset sourceOffset) throws PipelineException {
PipelineStatus status = getState().getStatus();
if (status.isActive()) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0118, getName());
}
OffsetFileUtil.saveSourceOffset(getRuntimeInfo(), getName(), getRev(), sourceOffset);
}
@Override
public void stop(String user) throws PipelineException {
stopPipeline(false);
}
@Override
public void forceQuit(String user) throws PipelineException {
if (pipelineRunnable != null && FORCE_QUIT_ALLOWED_STATES.contains(getState().getStatus())) {
LOG.debug("Force Quit the pipeline '{}'::'{}'", getName(), getRev());
pipelineRunnable.forceQuit();
} else {
LOG.info("Ignoring force quit request because pipeline is in {} state", getState().getStatus());
}
}
@Override
public Object getMetrics() throws PipelineStoreException {
if (prodPipeline != null) {
Object metrics = prodPipeline.getPipeline().getRunner().getMetrics();
if (metrics == null && getState().getStatus().isActive()) {
return metricsForRetry;
} else {
return metrics;
}
}
return null;
}
@Override
public String captureSnapshot(
String user,
String snapshotName,
String snapshotLabel,
int batches,
int batchSize
) throws PipelineException {
if(batchSize <= 0) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0107, batchSize);
}
return captureSnapshot(user, snapshotName, snapshotLabel, batches, batchSize, true);
}
public String captureSnapshot(
String user,
String snapshotName,
String snapshotLabel,
int batches,
int batchSize,
boolean checkState
) throws PipelineException {
int maxBatchSize = getConfiguration().get(Constants.SNAPSHOT_MAX_BATCH_SIZE_KEY, Constants.SNAPSHOT_MAX_BATCH_SIZE_DEFAULT);
if(batchSize > maxBatchSize) {
batchSize = maxBatchSize;
}
LOG.debug("Capturing snapshot with batch size {}", batchSize);
if (checkState) {
checkState(getState().getStatus().equals(PipelineStatus.RUNNING), ContainerError.CONTAINER_0105);
}
SnapshotInfo snapshotInfo = snapshotStore.create(user, getName(), getRev(), snapshotName, snapshotLabel, false);
prodPipeline.captureSnapshot(snapshotName, batchSize, batches);
return snapshotInfo.getId();
}
@Override
public String updateSnapshotLabel(String snapshotName, String snapshotLabel)
throws PipelineException {
SnapshotInfo snapshotInfo = snapshotStore.updateLabel(getName(), getRev(), snapshotName, snapshotLabel);
if(snapshotInfo != null) {
return snapshotInfo.getId();
}
return null;
}
@Override
public Snapshot getSnapshot(String id) throws PipelineException {
return snapshotStore.get(getName(), getRev(), id);
}
@Override
public List<SnapshotInfo> getSnapshotsInfo() throws PipelineException {
return snapshotStore.getSummaryForPipeline(getName(), getRev());
}
@Override
public void deleteSnapshot(String id) throws PipelineException {
Snapshot snapshot = getSnapshot(id);
if(snapshot != null && snapshot.getInfo() != null && snapshot.getInfo().isInProgress()) {
prodPipeline.cancelSnapshot(snapshot.getInfo().getId());
}
snapshotStore.deleteSnapshot(getName(), getRev(), id);
}
@Override
public List<Record> getErrorRecords(String stage, int max) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0106);
return prodPipeline.getErrorRecords(stage, max);
}
@Override
public List<ErrorMessage> getErrorMessages(String stage, int max) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0106);
return prodPipeline.getErrorMessages(stage, max);
}
@Override
public List<SampledRecord> getSampledRecords(String sampleId, int max) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0106);
return observerRunnable.getSampledRecords(sampleId, max);
}
@Override
@SuppressWarnings("unchecked")
public List<AlertInfo> getAlerts() throws PipelineException {
List<AlertInfo> alertInfoList = new ArrayList<>();
MetricRegistry metrics = (MetricRegistry)getMetrics();
if(metrics != null) {
RuleDefinitions ruleDefinitions = getPipelineStore().retrieveRules(getName(), getRev());
for(RuleDefinition ruleDefinition: ruleDefinitions.getMetricsRuleDefinitions()) {
Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
AlertsUtil.getAlertGaugeName(ruleDefinition.getId()));
if(gauge != null) {
alertInfoList.add(new AlertInfo(getName(), ruleDefinition, gauge));
}
}
for(RuleDefinition ruleDefinition: ruleDefinitions.getAllDataRuleDefinitions()) {
Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
AlertsUtil.getAlertGaugeName(ruleDefinition.getId()));
if(gauge != null) {
alertInfoList.add(new AlertInfo(getName(), ruleDefinition, gauge));
}
}
}
return alertInfoList;
}
@Override
public boolean deleteAlert(String alertId) throws PipelineRunnerException, PipelineStoreException {
checkState(getState().getStatus().isActive(), ContainerError.CONTAINER_0402);
MetricsConfigurator.resetCounter((MetricRegistry) getMetrics(), AlertsUtil.getUserMetricName(alertId));
return MetricsConfigurator.removeGauge((MetricRegistry) getMetrics(), AlertsUtil.getAlertGaugeName(alertId), getName(), getRev());
}
@Override
public void stateChanged(PipelineStatus pipelineStatus, String message, Map<String, Object> attributes)
throws PipelineRuntimeException {
try {
Map<String, Object> allAttributes = null;
if (attributes != null) {
allAttributes = new HashMap<>();
allAttributes.putAll(getState().getAttributes());
allAttributes.putAll(attributes);
}
validateAndSetStateTransition(getState().getUser(), pipelineStatus, message, allAttributes);
if (pipelineStatus == PipelineStatus.FINISHED && metricsEventRunnable != null) {
this.metricsEventRunnable.onStopOrFinishPipeline();
}
} catch (PipelineStoreException | PipelineRunnerException ex) {
throw new PipelineRuntimeException(ex.getErrorCode(), ex);
}
}
private void validateAndSetStateTransition(String user, PipelineStatus toStatus, String message, Map<String, Object> attributes)
throws PipelineStoreException, PipelineRunnerException {
PipelineState fromState;
PipelineState pipelineState;
synchronized (this) {
fromState = getState();
checkState(VALID_TRANSITIONS.get(fromState.getStatus()).contains(toStatus), ContainerError.CONTAINER_0102,
fromState.getStatus(), toStatus);
long nextRetryTimeStamp = fromState.getNextRetryTimeStamp();
int retryAttempt = fromState.getRetryAttempt();
String metricString = null;
if (toStatus == PipelineStatus.RETRY && fromState.getStatus() != PipelineStatus.CONNECTING) {
retryAttempt = fromState.getRetryAttempt() + 1;
if (retryAttempt > maxRetries && maxRetries != -1) {
LOG.info("Retry attempt '{}' is greater than max no of retries '{}'", retryAttempt, maxRetries);
toStatus = PipelineStatus.RUN_ERROR;
retryAttempt = 0;
nextRetryTimeStamp = 0;
} else {
nextRetryTimeStamp = RetryUtils.getNextRetryTimeStamp(retryAttempt, System.currentTimeMillis());
isRetrying = true;
metricsForRetry = getState().getMetrics();
}
} else if (!toStatus.isActive()) {
retryAttempt = 0;
nextRetryTimeStamp = 0;
}
if (!toStatus.isActive() || toStatus == PipelineStatus.DISCONNECTED
|| (toStatus == PipelineStatus.RETRY && fromState.getStatus() != PipelineStatus.CONNECTING)) {
Object metrics = getMetrics();
if (metrics != null) {
ObjectMapper objectMapper = ObjectMapperFactory.get();
try {
metricString = objectMapper.writeValueAsString(metrics);
} catch (JsonProcessingException e) {
throw new PipelineStoreException(ContainerError.CONTAINER_0210, e.toString(), e);
}
getEventListenerManager().broadcastMetrics(getName(), metricString);
}
if (metricString == null) {
metricString = getState().getMetrics();
}
}
pipelineState =
getPipelineStateStore().saveState(user, getName(), getRev(), toStatus, message, attributes, ExecutionMode.STANDALONE,
metricString, retryAttempt, nextRetryTimeStamp);
if (toStatus == PipelineStatus.RETRY) {
retryFuture = scheduleForRetries(runnerExecutor);
}
}
getEventListenerManager().broadcastStateChange(
fromState,
pipelineState,
ThreadUsage.STANDALONE,
OffsetFileUtil.getOffsets(getRuntimeInfo(), getName(), getRev())
);
}
private void checkState(boolean expr, ContainerError error, Object... args) throws PipelineRunnerException {
if (!expr) {
throw new PipelineRunnerException(error, args);
}
}
@Override
public void prepareForStart(StartPipelineContext context) throws PipelineStoreException, PipelineRunnerException {
PipelineState fromState = getState();
checkState(VALID_TRANSITIONS.get(fromState.getStatus()).contains(PipelineStatus.STARTING), ContainerError.CONTAINER_0102,
fromState.getStatus(), PipelineStatus.STARTING);
if(!resourceManager.requestRunnerResources(ThreadUsage.STANDALONE)) {
throw new PipelineRunnerException(ContainerError.CONTAINER_0166, getName());
}
LOG.info("Preparing to start pipeline '{}::{}'", getName(), getRev());
setStartPipelineContext(context);
validateAndSetStateTransition(context.getUser(), PipelineStatus.STARTING, null, createNewStateAttributes());
token = UUID.randomUUID().toString();
}
@Override
public void prepareForStop(String user) throws PipelineStoreException, PipelineRunnerException {
LOG.info("Preparing to stop pipeline");
if (getState().getStatus() == PipelineStatus.RETRY) {
retryFuture.cancel(true);
validateAndSetStateTransition(user, PipelineStatus.STOPPING, null, null);
validateAndSetStateTransition(user, PipelineStatus.STOPPED, "Stopped while the pipeline was in RETRY state", null);
} else {
validateAndSetStateTransition(user, PipelineStatus.STOPPING, null, null);
}
}
@Override
public void start(StartPipelineContext context) throws PipelineException, StageException {
startPipeline(context);
LOG.debug("Starting the runnable for pipeline {} {}", getName(), getRev());
if(!pipelineRunnable.isStopped()) {
pipelineRunnable.run();
}
}
private void startPipeline(StartPipelineContext context) throws PipelineException, StageException {
Utils.checkState(!isClosed,
Utils.formatL("Cannot start the pipeline '{}::{}' as the runner is already closed", getName(), getRev()));
synchronized (this) {
try {
LOG.info("Starting pipeline {} {}", getName(), getRev());
setStartPipelineContext(context);
UserContext runningUser = new UserContext(context.getUser(),
getRuntimeInfo().isDPMEnabled(),
getConfiguration().get(
RemoteSSOService.DPM_USER_ALIAS_NAME_ENABLED,
RemoteSSOService.DPM_USER_ALIAS_NAME_ENABLED_DEFAULT
)
);
/*
* Implementation Notes: --------------------- What are the different threads and runnables created? - - - - - - - -
* - - - - - - - - - - - - - - - - - - - RulesConfigLoader ProductionObserver MetricObserver
* ProductionPipelineRunner How do threads communicate? - - - - - - - - - - - - - - RulesConfigLoader,
* ProductionObserver and ProductionPipelineRunner share a blocking queue which will hold record samples to be
* evaluated by the Observer [Data Rule evaluation] and rules configuration change requests computed by the
* RulesConfigLoader. MetricsObserverRunner handles evaluating metric rules and a reference is passed to Production
* Observer which updates the MetricsObserverRunner when configuration changes. Other classes: - - - - - - - - Alert
* Manager - responsible for creating alerts and sending email.
*/
PipelineConfiguration pipelineConfiguration = getPipelineConf(getName(), getRev());
List<Issue> errors = new ArrayList<>();
PipelineEL.setConstantsInContext(pipelineConfiguration, runningUser, getState().getTimeStamp());
PipelineConfigBean pipelineConfigBean = PipelineBeanCreator.get().create(
pipelineConfiguration,
errors,
getStartPipelineContext().getRuntimeParameters()
);
if (pipelineConfigBean == null) {
throw new PipelineRuntimeException(ContainerError.CONTAINER_0116, errors);
}
JobEL.setConstantsInContext(pipelineConfigBean.constants);
maxRetries = pipelineConfigBean.retryAttempts;
BlockingQueue<Object> productionObserveRequests =
new ArrayBlockingQueue<>(getConfiguration().get(Constants.OBSERVER_QUEUE_SIZE_KEY,
Constants.OBSERVER_QUEUE_SIZE_DEFAULT), true /* FIFO */);
BlockingQueue<Record> statsQueue = null;
boolean statsAggregationEnabled = isStatsAggregationEnabled(pipelineConfiguration);
if (statsAggregationEnabled) {
statsQueue = new ArrayBlockingQueue<>(
getConfiguration().get(
Constants.STATS_AGGREGATOR_QUEUE_SIZE_KEY,
Constants.STATS_AGGREGATOR_QUEUE_SIZE_DEFAULT
),
true /* FIFO */
);
}
//Need to augment the existing object graph with pipeline related modules.
//This ensures that the singletons defined in those modules are singletons within the
//scope of a pipeline.
//So if a pipeline is started again for the second time, the object graph recreates the production pipeline
//with fresh instances of MetricRegistry, alert manager, observer etc etc..
ObjectGraph objectGraph = this.objectGraph.plus(
new PipelineProviderModule(
getName(),
pipelineConfiguration.getTitle(),
getRev(),
statsAggregationEnabled,
pipelineConfigBean.constants
)
);
threadHealthReporter = objectGraph.get(ThreadHealthReporter.class);
observerRunnable = objectGraph.get(DataObserverRunnable.class);
metricsEventRunnable = objectGraph.get(MetricsEventRunnable.class);
ImmutableList.Builder<Future<?>> taskBuilder = ImmutableList.builder();
ProductionObserver productionObserver = (ProductionObserver) objectGraph.get(Observer.class);
productionObserver.setPipelineStartTime(getState().getTimeStamp());
RulesConfigLoader rulesConfigLoader = objectGraph.get(RulesConfigLoader.class);
RulesConfigLoaderRunnable rulesConfigLoaderRunnable = objectGraph.get(RulesConfigLoaderRunnable.class);
MetricObserverRunnable metricObserverRunnable = objectGraph.get(MetricObserverRunnable.class);
ProductionPipelineRunner runner = (ProductionPipelineRunner) objectGraph.get(PipelineRunner.class);
runner.addErrorListeners(errorListeners);
if (isRetrying) {
ObjectMapper objectMapper = ObjectMapperFactory.get();
MetricRegistryJson metricRegistryJson = null;
try {
if (metricsForRetry != null) {
metricRegistryJson = objectMapper.readValue(metricsForRetry, MetricRegistryJson.class);
runner.updateMetrics(metricRegistryJson);
observerRunnable.setMetricRegistryJson(metricRegistryJson);
}
} catch (IOException ex) {
LOG.warn("Error while serializing slave metrics: , {}", ex.toString(), ex);
}
isRetrying = false;
}
if (pipelineConfigBean.rateLimit > 0) {
runner.setRateLimit(pipelineConfigBean.rateLimit);
}
ProductionPipelineBuilder builder = objectGraph.get(ProductionPipelineBuilder.class);
//register email notifier & webhook notifier with event listener manager
registerEmailNotifierIfRequired(pipelineConfigBean, getName(), pipelineConfiguration.getTitle(), getRev());
registerWebhookNotifierIfRequired(pipelineConfigBean, getName(), pipelineConfiguration.getTitle(), getRev());
//This which are not injected as of now.
productionObserver.setObserveRequests(productionObserveRequests);
runner.setObserveRequests(productionObserveRequests);
runner.setStatsAggregatorRequests(statsQueue);
runner.setDeliveryGuarantee(pipelineConfigBean.deliveryGuarantee);
prodPipeline = builder.build(
runningUser,
pipelineConfiguration,
getState().getTimeStamp(),
context.getInterceptorConfigurations(),
context.getRuntimeParameters()
);
prodPipeline.registerStatusListener(this);
ScheduledFuture<?> metricsFuture = null;
metricsEventRunnable.setStatsQueue(statsQueue);
metricsEventRunnable.setPipelineConfiguration(pipelineConfiguration);
int refreshInterval = getConfiguration().get(MetricsEventRunnable.REFRESH_INTERVAL_PROPERTY,
MetricsEventRunnable.REFRESH_INTERVAL_PROPERTY_DEFAULT);
if(refreshInterval > 0) {
metricsFuture = runnerExecutor.scheduleAtFixedRate(
metricsEventRunnable,
0,
metricsEventRunnable.getScheduledDelay(),
TimeUnit.MILLISECONDS
);
taskBuilder.add(metricsFuture);
}
//Schedule Rules Config Loader
rulesConfigLoader.setStatsQueue(statsQueue);
try {
rulesConfigLoader.load(productionObserver);
} catch (InterruptedException e) {
throw new PipelineRuntimeException(ContainerError.CONTAINER_0403, getName(), e.toString(), e);
}
ScheduledFuture<?> configLoaderFuture = runnerExecutor.scheduleWithFixedDelay(
rulesConfigLoaderRunnable,
1,
RulesConfigLoaderRunnable.SCHEDULED_DELAY,
TimeUnit.SECONDS
);
taskBuilder.add(configLoaderFuture);
ScheduledFuture<?> metricObserverFuture = runnerExecutor.scheduleWithFixedDelay(
metricObserverRunnable,
1,
2,
TimeUnit.SECONDS
);
taskBuilder.add(metricObserverFuture);
// Schedule a task to run empty batches for idle runners
if(pipelineConfigBean.runnerIdleTIme > 0) {
ProduceEmptyBatchesForIdleRunnersRunnable idleRunnersRunnable = new ProduceEmptyBatchesForIdleRunnersRunnable(
runner,
pipelineConfigBean.runnerIdleTIme * 1000 // The value inside the runnable is in milliseconds whereas user config is in seconds
);
// We'll schedule the task to run every 1/10 of the interval (really an arbitrary number)
long period = (pipelineConfigBean.runnerIdleTIme * 1000 )/ 10;
ScheduledFuture<?> idleRunnersFuture = runnerExecutor.scheduleWithFixedDelay(
idleRunnersRunnable,
period,
period,
TimeUnit.MILLISECONDS
);
taskBuilder.add(idleRunnersFuture);
}
observerRunnable.setRequestQueue(productionObserveRequests);
observerRunnable.setStatsQueue(statsQueue);
Future<?> observerFuture = runnerExecutor.submit(observerRunnable);
taskBuilder.add(observerFuture);
pipelineRunnable = new ProductionPipelineRunnable(threadHealthReporter, this, prodPipeline, getName(), getRev(), taskBuilder.build());
} catch (Exception e) {
validateAndSetStateTransition(context.getUser(), PipelineStatus.START_ERROR, e.toString(), null);
throw e;
}
}
}
@Override
public void startAndCaptureSnapshot(
StartPipelineContext context,
String snapshotName,
String snapshotLabel,
int batches,
int batchSize
) throws PipelineException, StageException {
try {
startPipeline(context);
captureSnapshot(context.getUser(), snapshotName, snapshotLabel, batches, batchSize, false);
LOG.debug("Starting the runnable for pipeline {} {}", getName(), getRev());
if (!pipelineRunnable.isStopped()) {
pipelineRunnable.run();
}
} catch (Exception e) {
LOG.error("Can't start and get snapshot for pipeline {}: {}", getName(), e.toString(), e);
throw e;
}
}
private boolean isStatsAggregationEnabled(PipelineConfiguration pipelineConfiguration) throws PipelineStoreException {
boolean isEnabled = false;
StageConfiguration statsAggregatorStage = pipelineConfiguration.getStatsAggregatorStage();
if (statsAggregatorStage != null &&
!statsAggregatorStage.getStageName().equals(STATS_NULL_TARGET) &&
!statsAggregatorStage.getStageName().equals(STATS_DPM_DIRECTLY_TARGET) &&
pipelineConfiguration.getMetadata() != null) {
isEnabled = true;
}
return isEnabled && this.isRemotePipeline();
}
private void stopPipeline(boolean sdcShutting) throws PipelineException {
if (pipelineRunnable != null && !pipelineRunnable.isStopped()) {
LOG.info("Stopping pipeline {} {}", pipelineRunnable.getName(), pipelineRunnable.getRev());
// this is sync call, will wait till pipeline is in terminal state
pipelineRunnable.stop(sdcShutting);
pipelineRunnable = null;
}
if (metricsEventRunnable != null) {
metricsEventRunnable.onStopOrFinishPipeline();
metricsEventRunnable = null;
}
if (threadHealthReporter != null) {
threadHealthReporter.destroy();
threadHealthReporter = null;
}
}
@Override
public void close() {
isClosed = true;
}
public Pipeline getPipeline() {
return prodPipeline != null ? prodPipeline.getPipeline() : null;
}
@Override
public Collection<CallbackInfo> getSlaveCallbackList(CallbackObjectType callbackObjectType) {
throw new UnsupportedOperationException("This method is only supported in Cluster Runner");
}
@Override
public Map<String, Object> updateSlaveCallbackInfo(CallbackInfo callbackInfo) {
throw new UnsupportedOperationException("This method is only supported in Cluster Runner");
}
@Override
public String getToken() {
return token;
}
@Override
public int getRunnerCount() {
return prodPipeline != null ? prodPipeline.getPipeline().getNumOfRunners() : 0;
}
@Override
public Runner getDelegatingRunner() {
return null;
}
private static int getNumBatches() {
String sNumBatches = System.getenv(SNAPSHOT_NUM_BATCHES);
return null != sNumBatches && sNumBatches.matches("\\d+") ? Integer.parseInt(sNumBatches) : 1;
}
private static int getBatchSize() {
String sBatchSize = System.getenv(SNAPSHOT_BATCH_SIZE);
return null != sBatchSize && sBatchSize.matches("\\d+") ? Integer.parseInt(sBatchSize) : 10;
}
}
|
SDC-13781: Tweak error handling in startAndCaptureSnapshot callback
This one have a long history actually - at some point in really distant
past, I've added error handling with state transition into
startAndCaptureSnapshot via SDC-6217. This was specifically to solve the
problem when someone tries to create snapshot with the same name twice,
but generally for case where starting the pipeline succeeds but
capturing the snapshot fails.
Later on this proved problematical on it's own since if the pipeline
itself failed to start, we tried to do transition from START_ERROR to
START_ERROR which of course failed and thus we removed that state
transition via SDC-11115.
You probably see where this is coming - SDC-11115 broke the initial fix
from SDC-6217. So this is hopefully fix that fixes both. The core behind
it is that method startPipeline does it's own state transitions and thus
doesn't need special try-catch handling (as you can for example see in
the callback start()). The method captureSnapshot() on the other hand
does as it's expected to fail without affecting pipeline state when the
API is called during pipeline run.
Change-Id: I12c3118714da83d390756a9af1392c7c769a13ca
Reviewed-on: https://review.streamsets.net/c/datacollector/+/30161
Tested-by: StreamSets CI <809627f37325a679986bd660c7713476a56d59cd@streamsets.com>
Reviewed-by: Alex Sanchez Cabana <16a9016b243d66f08e64f6a2a241982c7e25b5e0@streamsets.com>
|
container/src/main/java/com/streamsets/datacollector/execution/runner/standalone/StandaloneRunner.java
|
SDC-13781: Tweak error handling in startAndCaptureSnapshot callback
|
|
Java
|
apache-2.0
|
22f3ea9054f4fff76d54934cc3c8b818baaf77fc
| 0
|
reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api,reportportal/service-api
|
/*
* Copyright 2018 EPAM Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.ta.reportportal.core.widget.content.loader;
import com.epam.ta.reportportal.commons.querygen.Filter;
import com.epam.ta.reportportal.commons.validation.BusinessRule;
import com.epam.ta.reportportal.core.widget.content.LoadContentStrategy;
import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil;
import com.epam.ta.reportportal.dao.WidgetContentRepository;
import com.epam.ta.reportportal.entity.widget.WidgetOptions;
import com.epam.ta.reportportal.entity.widget.content.ChartStatisticsContent;
import com.epam.ta.reportportal.ws.model.ErrorType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import static com.epam.ta.reportportal.commons.Predicates.equalTo;
import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.RESULT;
import static com.epam.ta.reportportal.core.widget.util.ContentFieldPatternConstants.COMBINED_CONTENT_FIELDS_REGEX;
import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_FILTERS;
import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_SORTS;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
/**
* @author Pavel Bortnik
*/
@Service
public class LaunchesComparisonContentLoader implements LoadContentStrategy {
@Autowired
private WidgetContentRepository widgetContentRepository;
@Override
public Map<String, ?> loadContent(List<String> contentFields, Map<Filter, Sort> filterSortMapping, WidgetOptions widgetOptions,
int limit) {
validateFilterSortMapping(filterSortMapping);
validateContentFields(contentFields);
Filter filter = GROUP_FILTERS.apply(filterSortMapping.keySet());
Sort sort = GROUP_SORTS.apply(filterSortMapping.values());
List<ChartStatisticsContent> result = widgetContentRepository.launchesComparisonStatistics(filter, contentFields, sort, limit);
return result.isEmpty() ? emptyMap() : singletonMap(RESULT, result);
}
/**
* Mapping should not be empty
*
* @param filterSortMapping Map of ${@link Filter} for query building as key and ${@link Sort} as value for each filter
*/
private void validateFilterSortMapping(Map<Filter, Sort> filterSortMapping) {
BusinessRule.expect(MapUtils.isNotEmpty(filterSortMapping), equalTo(true))
.verify(ErrorType.BAD_REQUEST_ERROR, "Filter-Sort mapping should not be empty");
}
/**
* Validate provided content fields.
* The value of content field should not be empty
* All content fields should match the pattern {@link com.epam.ta.reportportal.core.widget.util.ContentFieldPatternConstants#COMBINED_CONTENT_FIELDS_REGEX}
*
* @param contentFields List of provided content.
*/
private void validateContentFields(List<String> contentFields) {
BusinessRule.expect(CollectionUtils.isNotEmpty(contentFields), equalTo(true))
.verify(ErrorType.BAD_REQUEST_ERROR, "Content fields should not be empty");
BusinessRule.expect(ContentFieldMatcherUtil.match(COMBINED_CONTENT_FIELDS_REGEX, contentFields), equalTo(true))
.verify(ErrorType.BAD_REQUEST_ERROR, "Bad content fields format");
}
}
|
src/main/java/com/epam/ta/reportportal/core/widget/content/loader/LaunchesComparisonContentLoader.java
|
/*
* Copyright 2018 EPAM Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.ta.reportportal.core.widget.content.loader;
import com.epam.ta.reportportal.commons.querygen.Condition;
import com.epam.ta.reportportal.commons.querygen.Filter;
import com.epam.ta.reportportal.commons.querygen.FilterCondition;
import com.epam.ta.reportportal.commons.validation.BusinessRule;
import com.epam.ta.reportportal.core.widget.content.LoadContentStrategy;
import com.epam.ta.reportportal.core.widget.util.ContentFieldMatcherUtil;
import com.epam.ta.reportportal.core.widget.util.WidgetOptionUtil;
import com.epam.ta.reportportal.dao.WidgetContentRepository;
import com.epam.ta.reportportal.entity.widget.WidgetOptions;
import com.epam.ta.reportportal.entity.widget.content.ChartStatisticsContent;
import com.epam.ta.reportportal.ws.model.ErrorType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static com.epam.ta.reportportal.commons.Predicates.equalTo;
import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.LAUNCH_NAME_FIELD;
import static com.epam.ta.reportportal.core.widget.content.constant.ContentLoaderConstants.RESULT;
import static com.epam.ta.reportportal.core.widget.util.ContentFieldPatternConstants.COMBINED_CONTENT_FIELDS_REGEX;
import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_FILTERS;
import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_SORTS;
import static com.epam.ta.reportportal.dao.constant.WidgetContentRepositoryConstants.NAME;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
/**
* @author Pavel Bortnik
*/
@Service
public class LaunchesComparisonContentLoader implements LoadContentStrategy {
@Autowired
private WidgetContentRepository widgetContentRepository;
@Override
public Map<String, ?> loadContent(List<String> contentFields, Map<Filter, Sort> filterSortMapping, WidgetOptions widgetOptions,
int limit) {
validateFilterSortMapping(filterSortMapping);
validateWidgetOptions(widgetOptions);
validateContentFields(contentFields);
Filter filter = GROUP_FILTERS.apply(filterSortMapping.keySet());
Sort sort = GROUP_SORTS.apply(filterSortMapping.values());
filter.withCondition(new FilterCondition(
Condition.EQUALS,
false,
WidgetOptionUtil.getValueByKey(LAUNCH_NAME_FIELD, widgetOptions),
NAME
));
List<ChartStatisticsContent> result = widgetContentRepository.launchesComparisonStatistics(filter, contentFields, sort, limit);
return result.isEmpty() ? emptyMap() : singletonMap(RESULT, result);
}
/**
* Mapping should not be empty
*
* @param filterSortMapping Map of ${@link Filter} for query building as key and ${@link Sort} as value for each filter
*/
private void validateFilterSortMapping(Map<Filter, Sort> filterSortMapping) {
BusinessRule.expect(MapUtils.isNotEmpty(filterSortMapping), equalTo(true))
.verify(ErrorType.BAD_REQUEST_ERROR, "Filter-Sort mapping should not be empty");
}
/**
* Validate provided widget options. For current widget launch name should be specified.
*
* @param widgetOptions Map of stored widget options.
*/
private void validateWidgetOptions(WidgetOptions widgetOptions) {
BusinessRule.expect(WidgetOptionUtil.getValueByKey(LAUNCH_NAME_FIELD, widgetOptions), StringUtils::isNotBlank)
.verify(ErrorType.UNABLE_LOAD_WIDGET_CONTENT, LAUNCH_NAME_FIELD + " should be specified for widget.");
}
/**
* Validate provided content fields.
* The value of content field should not be empty
* All content fields should match the pattern {@link com.epam.ta.reportportal.core.widget.util.ContentFieldPatternConstants#COMBINED_CONTENT_FIELDS_REGEX}
*
* @param contentFields List of provided content.
*/
private void validateContentFields(List<String> contentFields) {
BusinessRule.expect(CollectionUtils.isNotEmpty(contentFields), equalTo(true))
.verify(ErrorType.BAD_REQUEST_ERROR, "Content fields should not be empty");
BusinessRule.expect(ContentFieldMatcherUtil.match(COMBINED_CONTENT_FIELDS_REGEX, contentFields), equalTo(true))
.verify(ErrorType.BAD_REQUEST_ERROR, "Bad content fields format");
}
}
|
Widget options validation fix
|
src/main/java/com/epam/ta/reportportal/core/widget/content/loader/LaunchesComparisonContentLoader.java
|
Widget options validation fix
|
|
Java
|
apache-2.0
|
a336c0df5e67f06da7cb2865d1b3da1f42351d95
| 0
|
aledsage/legacy-brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn
|
package io.brooklyn.camp.brooklyn.spi.creation;
import io.brooklyn.camp.brooklyn.BrooklynCampConstants;
import io.brooklyn.camp.spi.AbstractResource;
import io.brooklyn.camp.spi.ApplicationComponentTemplate;
import io.brooklyn.camp.spi.AssemblyTemplate;
import io.brooklyn.camp.spi.PlatformComponentTemplate;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.config.ConfigKey;
import brooklyn.entity.Application;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.AbstractApplication;
import brooklyn.entity.basic.AbstractEntity;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.entity.basic.EntityInternal;
import brooklyn.entity.basic.VanillaSoftwareProcess;
import brooklyn.entity.group.DynamicCluster;
import brooklyn.entity.group.DynamicRegionsFabric;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.proxying.InternalEntityFactory;
import brooklyn.location.Location;
import brooklyn.management.ManagementContext;
import brooklyn.management.internal.ManagementContextInternal;
import brooklyn.policy.Enricher;
import brooklyn.policy.EnricherSpec;
import brooklyn.policy.Policy;
import brooklyn.policy.PolicySpec;
import brooklyn.util.collections.MutableList;
import brooklyn.util.collections.MutableSet;
import brooklyn.util.config.ConfigBag;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.flags.FlagUtils;
import brooklyn.util.flags.FlagUtils.FlagConfigKeyAndValueRecord;
import brooklyn.util.guava.Maybe;
import brooklyn.util.javalang.Reflections;
import brooklyn.util.text.Strings;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class BrooklynComponentTemplateResolver {
private static final Logger log = LoggerFactory.getLogger(BrooklynComponentTemplateResolver.class);
final ManagementContext mgmt;
final ConfigBag attrs;
final Maybe<AbstractResource> template;
AtomicBoolean alreadyBuilt = new AtomicBoolean(false);
public static class Factory {
/** returns resolver type based on the service type, inspecting the arguments in order to determine the service type */
private static Class<? extends BrooklynComponentTemplateResolver> computeResolverType(String knownServiceType, AbstractResource optionalTemplate, ConfigBag attrs) {
String type = getDeclaredType(knownServiceType, optionalTemplate, attrs);
if (type!=null) {
if (type.startsWith("brooklyn:") || type.startsWith("java:")) return BrooklynComponentTemplateResolver.class;
if (type.equalsIgnoreCase("chef") || type.startsWith("chef:")) return ChefComponentTemplateResolver.class;
// TODO other BrooklynComponentTemplateResolver subclasses detected here
// (perhaps use regexes mapping to subclass name, defined in mgmt?)
}
return null;
}
public static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, Map<String, Object> childAttrs) {
return newInstance(mgmt, ConfigBag.newInstance(childAttrs), null);
}
public static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, AbstractResource template) {
return newInstance(mgmt, ConfigBag.newInstance(template.getCustomAttributes()), template);
}
public static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, String serviceType) {
return newInstance(mgmt, ConfigBag.newInstance().configureStringKey("serviceType", serviceType), null);
}
private static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, ConfigBag attrs, AbstractResource optionalTemplate) {
Class<? extends BrooklynComponentTemplateResolver> rt = computeResolverType(null, optionalTemplate, attrs);
if (rt==null) // use default
rt = BrooklynComponentTemplateResolver.class;
try {
return (BrooklynComponentTemplateResolver) rt.getConstructors()[0].newInstance(mgmt, attrs, optionalTemplate);
} catch (Exception e) { throw Exceptions.propagate(e); }
}
private static String getDeclaredType(String knownServiceType, AbstractResource optionalTemplate, @Nullable ConfigBag attrs) {
String type = knownServiceType;
if (type==null && optionalTemplate!=null) {
type = optionalTemplate.getType();
if (type.equals(AssemblyTemplate.CAMP_TYPE) || type.equals(PlatformComponentTemplate.CAMP_TYPE) || type.equals(ApplicationComponentTemplate.CAMP_TYPE))
// ignore these values for the type; only subclasses are interesting
type = null;
}
if (type==null) type = extractServiceTypeAttribute(attrs);
return type;
}
private static String extractServiceTypeAttribute(@Nullable ConfigBag attrs) {
if (attrs==null) return null;
String type;
type = (String)attrs.getStringKey("serviceType");
if (type==null) type = (String)attrs.getStringKey("service_type");
if (type==null) type = (String)attrs.getStringKey("type");
return type;
}
public static boolean supportsType(ManagementContext mgmt, String serviceType) {
Class<? extends BrooklynComponentTemplateResolver> type = computeResolverType(serviceType, null, null);
if (type!=null) return true;
// can't tell by a prefix; try looking it up
try {
newInstance(mgmt, serviceType).loadEntityClass();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
return false;
}
}
}
public BrooklynComponentTemplateResolver(ManagementContext mgmt, ConfigBag attrs, AbstractResource optionalTemplate) {
this.mgmt = mgmt;
this.attrs = ConfigBag.newInstanceCopying(attrs);
this.template = Maybe.fromNullable(optionalTemplate);
}
protected String getDeclaredType() {
return Factory.getDeclaredType(null, template.orNull(), attrs);
}
protected String getJavaType() {
String type = getDeclaredType();
type = Strings.removeFromStart(type, "brooklyn:", "java:");
// TODO currently a hardcoded list of aliases; would like that to come from mgmt somehow
if (type.equals("cluster") || type.equals("Cluster")) return DynamicCluster.class.getName();
if (type.equals("fabric") || type.equals("Fabric")) return DynamicRegionsFabric.class.getName();
if (type.equals("vanilla") || type.equals("Vanilla")) return VanillaSoftwareProcess.class.getName();
if (type.equals("web-app-cluster") || type.equals("WebAppCluster"))
// TODO use service discovery; currently included as string to avoid needing a reference to it
return "brooklyn.entity.webapp.ControlledDynamicWebAppCluster";
return type;
}
@SuppressWarnings("unchecked")
public <T extends Entity> Class<T> loadEntityClass() {
return (Class<T>)this.<Entity>loadClass(Entity.class, getJavaType());
}
public <T extends Entity> EntitySpec<T> resolveSpec() {
return resolveSpec(this.<T>loadEntityClass(), null);
}
public <T extends Entity> EntitySpec<T> resolveSpec(Class<T> type, Class<? extends T> optionalImpl) {
if (alreadyBuilt.getAndSet(true))
throw new IllegalStateException("Spec can only be used once: "+this);
EntitySpec<T> spec;
if (optionalImpl != null) {
spec = EntitySpec.create(type).impl(optionalImpl);
} else if (type.isInterface()) {
spec = EntitySpec.create(type);
} else {
// If this is a concrete class, particularly for an Application class, we want the proxy
// to expose all interfaces it implements.
Class interfaceclazz = (Application.class.isAssignableFrom(type)) ? Application.class : Entity.class;
List<Class<?>> additionalInterfaceClazzes = Reflections.getAllInterfaces(type);
spec = EntitySpec.create(interfaceclazz).impl(type).additionalInterfaces(additionalInterfaceClazzes);
}
String name, templateId=null, planId=null;
if (template.isPresent()) {
name = template.get().getName();
templateId = template.get().getId();
} else {
name = (String)attrs.getStringKey("name");
}
planId = (String)attrs.getStringKey("id");
if (planId==null)
planId = (String) attrs.getStringKey(BrooklynCampConstants.PLAN_ID_FLAG);
if (!Strings.isBlank(name))
spec.displayName(name);
if (templateId != null)
spec.configure(BrooklynCampConstants.TEMPLATE_ID, templateId);
if (planId != null)
spec.configure(BrooklynCampConstants.PLAN_ID, planId);
List<Location> childLocations = new BrooklynYamlLocationResolver(mgmt).resolveLocations(attrs.getAllConfig(), true);
if (childLocations != null)
spec.locations(childLocations);
decorateSpec(spec);
return spec;
}
/** Subclass as needed for correct classloading, e.g. OSGi-based resolver (created from osgi:<bundle>: prefix
* would use that OSGi mechanism here
*/
@SuppressWarnings("unchecked")
protected <T> Class<T> loadClass(Class<T> optionalSupertype, String typeName) {
try {
if (optionalSupertype!=null && Entity.class.isAssignableFrom(optionalSupertype))
return (Class<T>) BrooklynEntityClassResolver.<Entity>resolveEntity(typeName, mgmt);
else
return BrooklynEntityClassResolver.<T>tryLoadFromClasspath(typeName, mgmt).get();
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
log.warn("Unable to resolve "+typeName+" in spec "+this);
throw Exceptions.propagate(new IllegalStateException("Unable to resolve "
+ (optionalSupertype!=null ? optionalSupertype.getSimpleName()+" " : "")
+ "type '"+typeName+"'", e));
}
}
protected <T extends Entity> void decorateSpec(EntitySpec<T> spec) {
spec.policySpecs(extractPolicySpecs());
spec.enricherSpecs(extractEnricherSpecs());
configureEntityConfig(spec);
}
/** returns new *uninitialised* entity, with just a few of the pieces from the spec;
* initialisation occurs soon after, in {@link #initEntity(ManagementContext, Entity, EntitySpec)},
* inside an execution context and after entity ID's are recognised
*/
protected <T extends Entity> T newEntity(EntitySpec<T> spec) {
Class<? extends T> entityImpl = (spec.getImplementation() != null) ? spec.getImplementation() : mgmt.getEntityManager().getEntityTypeRegistry().getImplementedBy(spec.getType());
InternalEntityFactory entityFactory = ((ManagementContextInternal)mgmt).getEntityFactory();
T entity = entityFactory.constructEntity(entityImpl, spec);
if (entity instanceof AbstractApplication) {
FlagUtils.setFieldsFromFlags(ImmutableMap.of("mgmt", mgmt), entity);
}
// TODO Some of the code below could go into constructEntity?
if (spec.getId() != null) {
FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", spec.getId()), entity);
}
String planId = (String)spec.getConfig().get(BrooklynCampConstants.PLAN_ID.getConfigKey());
if (planId != null) {
((EntityInternal)entity).setConfig(BrooklynCampConstants.PLAN_ID, planId);
}
((ManagementContextInternal)mgmt).prePreManage(entity);
((AbstractEntity)entity).setManagementContext((ManagementContextInternal)mgmt);
((AbstractEntity)entity).setProxy(entityFactory.createEntityProxy(spec, entity));
if (spec.getLocations().size() > 0) {
((AbstractEntity)entity).addLocations(spec.getLocations());
}
if (spec.getParent() != null) entity.setParent(spec.getParent());
return entity;
}
@SuppressWarnings("unchecked")
private void configureEntityConfig(EntitySpec<?> spec) {
ConfigBag bag = ConfigBag.newInstance((Map<Object, Object>) attrs.getStringKey("brooklyn.config"));
List<FlagConfigKeyAndValueRecord> records = FlagUtils.findAllFlagsAndConfigKeys(null, spec.getType(), bag);
Set<String> keyNamesUsed = new LinkedHashSet<String>();
for (FlagConfigKeyAndValueRecord r: records) {
if (r.getFlagMaybeValue().isPresent()) {
Object transformed = transformSpecialFlags(r.getFlagMaybeValue().get(), mgmt);
spec.configure(r.getFlagName(), transformed);
keyNamesUsed.add(r.getFlagName());
}
if (r.getConfigKeyMaybeValue().isPresent()) {
Object transformed = transformSpecialFlags(r.getConfigKeyMaybeValue().get(), mgmt);
spec.configure((ConfigKey<Object>)r.getConfigKey(), transformed);
keyNamesUsed.add(r.getConfigKey().getName());
}
}
// set unused keys as anonymous config keys -
// they aren't flags or known config keys, so must be passed as config keys in order for
// EntitySpec to know what to do with them (as they are passed to the spec as flags)
for (String key: MutableSet.copyOf(bag.getUnusedConfig().keySet())) {
// we don't let a flag with the same name as a config key override the config key
// (that's why we check whether it is used)
if (!keyNamesUsed.contains(key)) {
Object transformed = transformSpecialFlags(bag.getStringKey(key), mgmt);
spec.configure(ConfigKeys.newConfigKey(Object.class, key.toString()), transformed);
}
}
}
/**
* Makes additional transformations to the given flag with the extra knowledge of the flag's management context.
* @return The modified flag, or the flag unchanged.
*/
protected Object transformSpecialFlags(Object flag, ManagementContext mgmt) {
if (flag instanceof EntitySpecConfiguration) {
EntitySpecConfiguration specConfig = (EntitySpecConfiguration) flag;
// TODO: This should called from BrooklynAssemblyTemplateInstantiator.configureEntityConfig
// And have transformSpecialFlags(Object flag, ManagementContext mgmt) drill into the Object flag if it's a map or iterable?
@SuppressWarnings("unchecked")
Map<String, Object> resolvedConfig = (Map<String, Object>)transformSpecialFlags(specConfig.getSpecConfiguration(), mgmt);
specConfig.setSpecConfiguration(resolvedConfig);
return Factory.newInstance(mgmt, specConfig.getSpecConfiguration()).resolveSpec();
}
return flag;
}
protected Map<?, ?> transformSpecialFlags(Map<?, ?> flag, final ManagementContext mgmt) {
// TODO: Re-usable function
return Maps.transformValues(flag, new Function<Object, Object>() {
public Object apply(Object input) {
if (input instanceof Map)
return transformSpecialFlags((Map<?, ?>)input, mgmt);
else if (input instanceof Set<?>)
return MutableSet.of(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof List<?>)
return MutableList.copyOf(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof Iterable<?>)
return transformSpecialFlags((Iterable<?>)input, mgmt);
else
return transformSpecialFlags((Object)input, mgmt);
}
});
}
protected Iterable<?> transformSpecialFlags(Iterable<?> flag, final ManagementContext mgmt) {
return Iterables.transform(flag, new Function<Object, Object>() {
public Object apply(Object input) {
if (input instanceof Map<?, ?>)
return transformSpecialFlags((Map<?, ?>)input, mgmt);
else if (input instanceof Set<?>)
return MutableSet.of(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof List<?>)
return MutableList.copyOf(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof Iterable<?>)
return transformSpecialFlags((Iterable<?>)input, mgmt);
else
return transformSpecialFlags((Object)input, mgmt);
}
});
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getChildren(Map<String, Object> attrs) {
if (attrs==null) return null;
return (List<Map<String, Object>>) attrs.get("brooklyn.children");
}
private <T extends Policy> PolicySpec<?> toCorePolicySpec(Class<T> clazz, Map<?, ?> config) {
Map<?, ?> policyConfig = (config == null) ? Maps.<Object, Object>newLinkedHashMap() : Maps.newLinkedHashMap(config);
PolicySpec<?> result;
result = PolicySpec.create(clazz)
.configure(policyConfig);
return result;
}
private <T extends Enricher> EnricherSpec<?> toCoreEnricherSpec(Class<T> clazz, Map<?, ?> config) {
Map<?, ?> enricherConfig = (config == null) ? Maps.<Object, Object>newLinkedHashMap() : Maps.newLinkedHashMap(config);
EnricherSpec<?> result;
result = EnricherSpec.create(clazz)
.configure(enricherConfig);
return result;
}
private List<PolicySpec<?>> extractPolicySpecs() {
return resolvePolicySpecs(attrs.getStringKey("brooklyn.policies"));
}
private List<PolicySpec<?>> resolvePolicySpecs(Object policies) {
List<PolicySpec<?>> policySpecs = new ArrayList<PolicySpec<?>>();
if (policies instanceof Iterable) {
for (Object policy : (Iterable<?>)policies) {
if (policy instanceof Map) {
String policyTypeName = ((Map<?, ?>) policy).get("policyType").toString();
Class<? extends Policy> policyType = this.loadClass(Policy.class, policyTypeName);
policySpecs.add(toCorePolicySpec(policyType, (Map<?, ?>) ((Map<?, ?>) policy).get("brooklyn.config")));
} else {
throw new IllegalArgumentException("policy should be map, not " + policy.getClass());
}
}
} else if (policies != null) {
// TODO support a "map" short form (for this, and for others)
throw new IllegalArgumentException("policies body should be iterable, not " + policies.getClass());
}
return policySpecs;
}
private List<EnricherSpec<?>> extractEnricherSpecs() {
return resolveEnricherSpecs(attrs.getStringKey("brooklyn.enrichers"));
}
private List<EnricherSpec<?>> resolveEnricherSpecs(Object enrichers) {
List<EnricherSpec<?>> enricherSpecs = Lists.newArrayList();
if (enrichers instanceof Iterable) {
for (Object enricher : (Iterable<?>)enrichers) {
if (enricher instanceof Map) {
String enricherTypeName = ((Map<?, ?>) enricher).get("enricherType").toString();
Class<? extends Enricher> enricherType = this.loadClass(Enricher.class, enricherTypeName);
enricherSpecs.add(toCoreEnricherSpec(enricherType, (Map<?, ?>) ((Map<?, ?>) enricher).get("brooklyn.config")));
} else {
throw new IllegalArgumentException("enricher should be map, not " + enricher.getClass());
}
}
} else if (enrichers != null) {
throw new IllegalArgumentException("enrichers body should be iterable, not " + enrichers.getClass());
}
return enricherSpecs;
}
}
|
usage/camp/src/main/java/io/brooklyn/camp/brooklyn/spi/creation/BrooklynComponentTemplateResolver.java
|
package io.brooklyn.camp.brooklyn.spi.creation;
import io.brooklyn.camp.brooklyn.BrooklynCampConstants;
import io.brooklyn.camp.spi.AbstractResource;
import io.brooklyn.camp.spi.ApplicationComponentTemplate;
import io.brooklyn.camp.spi.AssemblyTemplate;
import io.brooklyn.camp.spi.PlatformComponentTemplate;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.config.ConfigKey;
import brooklyn.entity.Application;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.AbstractApplication;
import brooklyn.entity.basic.AbstractEntity;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.entity.basic.EntityInternal;
import brooklyn.entity.basic.VanillaSoftwareProcess;
import brooklyn.entity.group.DynamicCluster;
import brooklyn.entity.group.DynamicRegionsFabric;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.proxying.InternalEntityFactory;
import brooklyn.location.Location;
import brooklyn.management.ManagementContext;
import brooklyn.management.internal.ManagementContextInternal;
import brooklyn.policy.Enricher;
import brooklyn.policy.EnricherSpec;
import brooklyn.policy.Policy;
import brooklyn.policy.PolicySpec;
import brooklyn.util.collections.MutableList;
import brooklyn.util.collections.MutableSet;
import brooklyn.util.config.ConfigBag;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.flags.FlagUtils;
import brooklyn.util.flags.FlagUtils.FlagConfigKeyAndValueRecord;
import brooklyn.util.guava.Maybe;
import brooklyn.util.javalang.Reflections;
import brooklyn.util.text.Strings;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class BrooklynComponentTemplateResolver {
private static final Logger log = LoggerFactory.getLogger(BrooklynComponentTemplateResolver.class);
final ManagementContext mgmt;
final ConfigBag attrs;
final Maybe<AbstractResource> template;
AtomicBoolean alreadyBuilt = new AtomicBoolean(false);
public static class Factory {
/** returns resolver type based on the service type, inspecting the arguments in order to determine the service type */
private static Class<? extends BrooklynComponentTemplateResolver> computeResolverType(String knownServiceType, AbstractResource optionalTemplate, ConfigBag attrs) {
String type = getDeclaredType(knownServiceType, optionalTemplate, attrs);
if (type!=null) {
if (type.startsWith("brooklyn:") || type.startsWith("java:")) return BrooklynComponentTemplateResolver.class;
if (type.equalsIgnoreCase("chef") || type.startsWith("chef:")) return ChefComponentTemplateResolver.class;
// TODO other BrooklynComponentTemplateResolver subclasses detected here
// (perhaps use regexes mapping to subclass name, defined in mgmt?)
}
return null;
}
public static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, Map<String, Object> childAttrs) {
return newInstance(mgmt, ConfigBag.newInstance(childAttrs), null);
}
public static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, AbstractResource template) {
return newInstance(mgmt, ConfigBag.newInstance(template.getCustomAttributes()), template);
}
public static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, String serviceType) {
return newInstance(mgmt, ConfigBag.newInstance().configureStringKey("serviceType", serviceType), null);
}
private static BrooklynComponentTemplateResolver newInstance(ManagementContext mgmt, ConfigBag attrs, AbstractResource optionalTemplate) {
Class<? extends BrooklynComponentTemplateResolver> rt = computeResolverType(null, optionalTemplate, attrs);
if (rt==null) // use default
rt = BrooklynComponentTemplateResolver.class;
try {
return (BrooklynComponentTemplateResolver) rt.getConstructors()[0].newInstance(mgmt, attrs, optionalTemplate);
} catch (Exception e) { throw Exceptions.propagate(e); }
}
private static String getDeclaredType(String knownServiceType, AbstractResource optionalTemplate, ConfigBag attrs) {
String type = knownServiceType;
if (type==null && optionalTemplate!=null) {
type = optionalTemplate.getType();
if (type.equals(AssemblyTemplate.CAMP_TYPE) || type.equals(PlatformComponentTemplate.CAMP_TYPE) || type.equals(ApplicationComponentTemplate.CAMP_TYPE))
// ignore these values for the type; only subclasses are interesting
type = null;
}
if (type==null) type = extractServiceTypeAttribute(attrs);
return type;
}
private static String extractServiceTypeAttribute(ConfigBag attrs) {
String type;
type = (String)attrs.getStringKey("serviceType");
if (type==null) type = (String)attrs.getStringKey("service_type");
if (type==null) type = (String)attrs.getStringKey("type");
return type;
}
public static boolean supportsType(ManagementContext mgmt, String serviceType) {
Class<? extends BrooklynComponentTemplateResolver> type = computeResolverType(serviceType, null, null);
if (type!=null) return true;
// can't tell by a prefix; try looking it up
try {
newInstance(mgmt, serviceType).loadEntityClass();
return true;
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
return false;
}
}
}
public BrooklynComponentTemplateResolver(ManagementContext mgmt, ConfigBag attrs, AbstractResource optionalTemplate) {
this.mgmt = mgmt;
this.attrs = ConfigBag.newInstanceCopying(attrs);
this.template = Maybe.fromNullable(optionalTemplate);
}
protected String getDeclaredType() {
return Factory.getDeclaredType(null, template.orNull(), attrs);
}
protected String getJavaType() {
String type = getDeclaredType();
type = Strings.removeFromStart(type, "brooklyn:", "java:");
// TODO currently a hardcoded list of aliases; would like that to come from mgmt somehow
if (type.equals("cluster") || type.equals("Cluster")) return DynamicCluster.class.getName();
if (type.equals("fabric") || type.equals("Fabric")) return DynamicRegionsFabric.class.getName();
if (type.equals("vanilla") || type.equals("Vanilla")) return VanillaSoftwareProcess.class.getName();
if (type.equals("web-app-cluster") || type.equals("WebAppCluster"))
// TODO use service discovery; currently included as string to avoid needing a reference to it
return "brooklyn.entity.webapp.ControlledDynamicWebAppCluster";
return type;
}
@SuppressWarnings("unchecked")
public <T extends Entity> Class<T> loadEntityClass() {
return (Class<T>)this.<Entity>loadClass(Entity.class, getJavaType());
}
public <T extends Entity> EntitySpec<T> resolveSpec() {
return resolveSpec(this.<T>loadEntityClass(), null);
}
public <T extends Entity> EntitySpec<T> resolveSpec(Class<T> type, Class<? extends T> optionalImpl) {
if (alreadyBuilt.getAndSet(true))
throw new IllegalStateException("Spec can only be used once: "+this);
EntitySpec<T> spec;
if (optionalImpl != null) {
spec = EntitySpec.create(type).impl(optionalImpl);
} else if (type.isInterface()) {
spec = EntitySpec.create(type);
} else {
// If this is a concrete class, particularly for an Application class, we want the proxy
// to expose all interfaces it implements.
Class interfaceclazz = (Application.class.isAssignableFrom(type)) ? Application.class : Entity.class;
List<Class<?>> additionalInterfaceClazzes = Reflections.getAllInterfaces(type);
spec = EntitySpec.create(interfaceclazz).impl(type).additionalInterfaces(additionalInterfaceClazzes);
}
String name, templateId=null, planId=null;
if (template.isPresent()) {
name = template.get().getName();
templateId = template.get().getId();
} else {
name = (String)attrs.getStringKey("name");
}
planId = (String)attrs.getStringKey("id");
if (planId==null)
planId = (String) attrs.getStringKey(BrooklynCampConstants.PLAN_ID_FLAG);
if (!Strings.isBlank(name))
spec.displayName(name);
if (templateId != null)
spec.configure(BrooklynCampConstants.TEMPLATE_ID, templateId);
if (planId != null)
spec.configure(BrooklynCampConstants.PLAN_ID, planId);
List<Location> childLocations = new BrooklynYamlLocationResolver(mgmt).resolveLocations(attrs.getAllConfig(), true);
if (childLocations != null)
spec.locations(childLocations);
decorateSpec(spec);
return spec;
}
/** Subclass as needed for correct classloading, e.g. OSGi-based resolver (created from osgi:<bundle>: prefix
* would use that OSGi mechanism here
*/
@SuppressWarnings("unchecked")
protected <T> Class<T> loadClass(Class<T> optionalSupertype, String typeName) {
try {
if (optionalSupertype!=null && Entity.class.isAssignableFrom(optionalSupertype))
return (Class<T>) BrooklynEntityClassResolver.<Entity>resolveEntity(typeName, mgmt);
else
return BrooklynEntityClassResolver.<T>tryLoadFromClasspath(typeName, mgmt).get();
} catch (Exception e) {
Exceptions.propagateIfFatal(e);
log.warn("Unable to resolve "+typeName+" in spec "+this);
throw Exceptions.propagate(new IllegalStateException("Unable to resolve "
+ (optionalSupertype!=null ? optionalSupertype.getSimpleName()+" " : "")
+ "type '"+typeName+"'", e));
}
}
protected <T extends Entity> void decorateSpec(EntitySpec<T> spec) {
spec.policySpecs(extractPolicySpecs());
spec.enricherSpecs(extractEnricherSpecs());
configureEntityConfig(spec);
}
/** returns new *uninitialised* entity, with just a few of the pieces from the spec;
* initialisation occurs soon after, in {@link #initEntity(ManagementContext, Entity, EntitySpec)},
* inside an execution context and after entity ID's are recognised
*/
protected <T extends Entity> T newEntity(EntitySpec<T> spec) {
Class<? extends T> entityImpl = (spec.getImplementation() != null) ? spec.getImplementation() : mgmt.getEntityManager().getEntityTypeRegistry().getImplementedBy(spec.getType());
InternalEntityFactory entityFactory = ((ManagementContextInternal)mgmt).getEntityFactory();
T entity = entityFactory.constructEntity(entityImpl, spec);
if (entity instanceof AbstractApplication) {
FlagUtils.setFieldsFromFlags(ImmutableMap.of("mgmt", mgmt), entity);
}
// TODO Some of the code below could go into constructEntity?
if (spec.getId() != null) {
FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", spec.getId()), entity);
}
String planId = (String)spec.getConfig().get(BrooklynCampConstants.PLAN_ID.getConfigKey());
if (planId != null) {
((EntityInternal)entity).setConfig(BrooklynCampConstants.PLAN_ID, planId);
}
((ManagementContextInternal)mgmt).prePreManage(entity);
((AbstractEntity)entity).setManagementContext((ManagementContextInternal)mgmt);
((AbstractEntity)entity).setProxy(entityFactory.createEntityProxy(spec, entity));
if (spec.getLocations().size() > 0) {
((AbstractEntity)entity).addLocations(spec.getLocations());
}
if (spec.getParent() != null) entity.setParent(spec.getParent());
return entity;
}
@SuppressWarnings("unchecked")
private void configureEntityConfig(EntitySpec<?> spec) {
ConfigBag bag = ConfigBag.newInstance((Map<Object, Object>) attrs.getStringKey("brooklyn.config"));
List<FlagConfigKeyAndValueRecord> records = FlagUtils.findAllFlagsAndConfigKeys(null, spec.getType(), bag);
Set<String> keyNamesUsed = new LinkedHashSet<String>();
for (FlagConfigKeyAndValueRecord r: records) {
if (r.getFlagMaybeValue().isPresent()) {
Object transformed = transformSpecialFlags(r.getFlagMaybeValue().get(), mgmt);
spec.configure(r.getFlagName(), transformed);
keyNamesUsed.add(r.getFlagName());
}
if (r.getConfigKeyMaybeValue().isPresent()) {
Object transformed = transformSpecialFlags(r.getConfigKeyMaybeValue().get(), mgmt);
spec.configure((ConfigKey<Object>)r.getConfigKey(), transformed);
keyNamesUsed.add(r.getConfigKey().getName());
}
}
// set unused keys as anonymous config keys -
// they aren't flags or known config keys, so must be passed as config keys in order for
// EntitySpec to know what to do with them (as they are passed to the spec as flags)
for (String key: MutableSet.copyOf(bag.getUnusedConfig().keySet())) {
// we don't let a flag with the same name as a config key override the config key
// (that's why we check whether it is used)
if (!keyNamesUsed.contains(key)) {
Object transformed = transformSpecialFlags(bag.getStringKey(key), mgmt);
spec.configure(ConfigKeys.newConfigKey(Object.class, key.toString()), transformed);
}
}
}
/**
* Makes additional transformations to the given flag with the extra knowledge of the flag's management context.
* @return The modified flag, or the flag unchanged.
*/
protected Object transformSpecialFlags(Object flag, ManagementContext mgmt) {
if (flag instanceof EntitySpecConfiguration) {
EntitySpecConfiguration specConfig = (EntitySpecConfiguration) flag;
// TODO: This should called from BrooklynAssemblyTemplateInstantiator.configureEntityConfig
// And have transformSpecialFlags(Object flag, ManagementContext mgmt) drill into the Object flag if it's a map or iterable?
@SuppressWarnings("unchecked")
Map<String, Object> resolvedConfig = (Map<String, Object>)transformSpecialFlags(specConfig.getSpecConfiguration(), mgmt);
specConfig.setSpecConfiguration(resolvedConfig);
return Factory.newInstance(mgmt, specConfig.getSpecConfiguration()).resolveSpec();
}
return flag;
}
protected Map<?, ?> transformSpecialFlags(Map<?, ?> flag, final ManagementContext mgmt) {
// TODO: Re-usable function
return Maps.transformValues(flag, new Function<Object, Object>() {
public Object apply(Object input) {
if (input instanceof Map)
return transformSpecialFlags((Map<?, ?>)input, mgmt);
else if (input instanceof Set<?>)
return MutableSet.of(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof List<?>)
return MutableList.copyOf(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof Iterable<?>)
return transformSpecialFlags((Iterable<?>)input, mgmt);
else
return transformSpecialFlags((Object)input, mgmt);
}
});
}
protected Iterable<?> transformSpecialFlags(Iterable<?> flag, final ManagementContext mgmt) {
return Iterables.transform(flag, new Function<Object, Object>() {
public Object apply(Object input) {
if (input instanceof Map<?, ?>)
return transformSpecialFlags((Map<?, ?>)input, mgmt);
else if (input instanceof Set<?>)
return MutableSet.of(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof List<?>)
return MutableList.copyOf(transformSpecialFlags((Iterable<?>)input, mgmt));
else if (input instanceof Iterable<?>)
return transformSpecialFlags((Iterable<?>)input, mgmt);
else
return transformSpecialFlags((Object)input, mgmt);
}
});
}
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getChildren(Map<String, Object> attrs) {
if (attrs==null) return null;
return (List<Map<String, Object>>) attrs.get("brooklyn.children");
}
private <T extends Policy> PolicySpec<?> toCorePolicySpec(Class<T> clazz, Map<?, ?> config) {
Map<?, ?> policyConfig = (config == null) ? Maps.<Object, Object>newLinkedHashMap() : Maps.newLinkedHashMap(config);
PolicySpec<?> result;
result = PolicySpec.create(clazz)
.configure(policyConfig);
return result;
}
private <T extends Enricher> EnricherSpec<?> toCoreEnricherSpec(Class<T> clazz, Map<?, ?> config) {
Map<?, ?> enricherConfig = (config == null) ? Maps.<Object, Object>newLinkedHashMap() : Maps.newLinkedHashMap(config);
EnricherSpec<?> result;
result = EnricherSpec.create(clazz)
.configure(enricherConfig);
return result;
}
private List<PolicySpec<?>> extractPolicySpecs() {
return resolvePolicySpecs(attrs.getStringKey("brooklyn.policies"));
}
private List<PolicySpec<?>> resolvePolicySpecs(Object policies) {
List<PolicySpec<?>> policySpecs = new ArrayList<PolicySpec<?>>();
if (policies instanceof Iterable) {
for (Object policy : (Iterable<?>)policies) {
if (policy instanceof Map) {
String policyTypeName = ((Map<?, ?>) policy).get("policyType").toString();
Class<? extends Policy> policyType = this.loadClass(Policy.class, policyTypeName);
policySpecs.add(toCorePolicySpec(policyType, (Map<?, ?>) ((Map<?, ?>) policy).get("brooklyn.config")));
} else {
throw new IllegalArgumentException("policy should be map, not " + policy.getClass());
}
}
} else if (policies != null) {
// TODO support a "map" short form (for this, and for others)
throw new IllegalArgumentException("policies body should be iterable, not " + policies.getClass());
}
return policySpecs;
}
private List<EnricherSpec<?>> extractEnricherSpecs() {
return resolveEnricherSpecs(attrs.getStringKey("brooklyn.enrichers"));
}
private List<EnricherSpec<?>> resolveEnricherSpecs(Object enrichers) {
List<EnricherSpec<?>> enricherSpecs = Lists.newArrayList();
if (enrichers instanceof Iterable) {
for (Object enricher : (Iterable<?>)enrichers) {
if (enricher instanceof Map) {
String enricherTypeName = ((Map<?, ?>) enricher).get("enricherType").toString();
Class<? extends Enricher> enricherType = this.loadClass(Enricher.class, enricherTypeName);
enricherSpecs.add(toCoreEnricherSpec(enricherType, (Map<?, ?>) ((Map<?, ?>) enricher).get("brooklyn.config")));
} else {
throw new IllegalArgumentException("enricher should be map, not " + enricher.getClass());
}
}
} else if (enrichers != null) {
throw new IllegalArgumentException("enrichers body should be iterable, not " + enrichers.getClass());
}
return enricherSpecs;
}
}
|
avoid NPE resolving camp yaml
|
usage/camp/src/main/java/io/brooklyn/camp/brooklyn/spi/creation/BrooklynComponentTemplateResolver.java
|
avoid NPE resolving camp yaml
|
|
Java
|
apache-2.0
|
5458eaa09169a613b66dd48174218fd8c7b09a1f
| 0
|
NRG948/NRG-Scouting-Application
|
package com.competitionapp.nrgscouting;
import java.io.File;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MatchActivity extends MainActivity {
ListView listView;
ArrayAdapter<String> teamAdapter;
String[] matchTeams;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalStoreDir = Environment.getExternalStorageDirectory();
File entries = new File(externalStoreDir,"Entries.txt");
ArrayList<Entry> list=MatchEntry.getAllEntriesInFileIntoObjectForm(entries);
matchTeams=new String[list.size()];
teamAdapter = new ArrayAdapter<String>(MatchActivity.this, android.R.layout.simple_list_item_1, matchTeams);
for(int i=0;i<=matchTeams.length;i++){
matchTeams[i]="Match:"+list.get(i).matchNumber+" Team:"+list.get(i).teamName;
}
}
else{
System.out.println("File not found...");
}
listView = (ListView)findViewById(R.id.list_team);
listView.setAdapter(teamAdapter);
}
}
|
NRGScouting/app/src/main/java/com/competitionapp/nrgscouting/MatchActivity.java
|
package com.competitionapp.nrgscouting;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MatchActivity extends MainActivity {
ListView listView;
ArrayAdapter<String> teamAdapter;
String[] matchTeams = {"948", "492",};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
teamAdapter = new ArrayAdapter<String>(MatchActivity.this, android.R.layout.simple_list_item_1, matchTeams);
setContentView(R.layout.activity_match);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File externalStoreDir = Environment.getExternalStorageDirectory();
File entries = new File(externalStoreDir,"Entries.txt");
ArrayList<Entry> list=MatchEntry.getAllEntriesInFileIntoObjectForm(entries);
for(Entry a:list){
teamAdapter.add("Match:"+a.matchNumber+" Team:"+a.teamName);
}
}
listView = (ListView)findViewById(R.id.list_team);
listView.setAdapter(teamAdapter);
}
}
|
Cool. If the exists, the list works...... according to me
|
NRGScouting/app/src/main/java/com/competitionapp/nrgscouting/MatchActivity.java
|
Cool. If the exists, the list works...... according to me
|
|
Java
|
apache-2.0
|
3b6ec1cd562d69f615eb1291487481023107973f
| 0
|
DBCG/cqf-ruler,DBCG/cqf-ruler,DBCG/cql_measure_processor,DBCG/cqf-ruler,DBCG/cql_measure_processor
|
package org.opencds.cqf.providers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.cqframework.cql.elm.execution.Library;
import org.cqframework.cql.elm.execution.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.CodeableConcept;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.Composition;
import org.hl7.fhir.dstu3.model.DataRequirement;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.ListResource;
import org.hl7.fhir.dstu3.model.Measure;
import org.hl7.fhir.dstu3.model.MeasureReport;
import org.hl7.fhir.dstu3.model.Narrative;
import org.hl7.fhir.dstu3.model.ParameterDefinition;
import org.hl7.fhir.dstu3.model.Parameters;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.dstu3.model.RelatedArtifact;
import org.hl7.fhir.dstu3.model.Resource;
import org.hl7.fhir.dstu3.model.StringType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.opencds.cqf.config.STU3LibraryLoader;
import org.opencds.cqf.evaluation.MeasureEvaluation;
import org.opencds.cqf.evaluation.MeasureEvaluationSeed;
import org.opencds.cqf.helpers.LibraryHelper;
import org.opencds.cqf.helpers.LibraryResourceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.jpa.dao.IFhirSystemDao;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import ca.uhn.fhir.jpa.rp.dstu3.MeasureResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.TokenParamModifier;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
public class FHIRMeasureResourceProvider extends MeasureResourceProvider {
private JpaDataProvider provider;
private IFhirSystemDao systemDao;
private NarrativeProvider narrativeProvider;
private HQMFProvider hqmfProvider;
private LibraryResourceProvider libraryResourceProvider;
private static final Logger logger = LoggerFactory.getLogger(FHIRMeasureResourceProvider.class);
public FHIRMeasureResourceProvider(JpaDataProvider dataProvider, IFhirSystemDao systemDao, NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider) {
this.provider = dataProvider;
this.systemDao = systemDao;
this.libraryResourceProvider = (LibraryResourceProvider) dataProvider.resolveResourceProvider("Library");
this.narrativeProvider = narrativeProvider;
this.hqmfProvider = hqmfProvider;
}
@Operation(name="$hqmf", idempotent = true)
public Parameters hqmf(@IdParam IdType theId) {
Measure theResource = this.getDao().read(theId);
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
String hqmf = this.generateHQMF(theResource, libraryLoader);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(hqmf));
return p;
}
@Operation(name="$refresh-generated-content")
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails, @IdParam IdType theId) {
Measure theResource = this.getDao().read(theId);
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
Narrative n = getMeasureNarrative(theResource.copy(), libraryLoader);
theResource.setText(n.copy());
//logger.info("Narrative: " + n.getDivAsString());
return super.update(theRequest, theResource, theId, theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name="$get-narrative", idempotent = true)
public Parameters getNarrative(@IdParam IdType theId) {
Measure theResource = this.getDao().read(theId);
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
Narrative n = getMeasureNarrative(theResource, libraryLoader);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
private String generateHQMF(Measure theResource, STU3LibraryLoader libraryLoader) {
CqfMeasure cqfMeasure = this.createCqfMeasure(theResource, libraryLoader);
return this.hqmfProvider.generateHQMF(cqfMeasure);
}
private Narrative getMeasureNarrative(Measure theResource, STU3LibraryLoader libraryLoader) {
CqfMeasure cqfMeasure = this.createCqfMeasure(theResource, libraryLoader);
return this.narrativeProvider.getNarrative(this.getContext(), cqfMeasure);
}
/*
*
* NOTE that the source, user, and pass parameters are not standard parameters for the FHIR $evaluate-measure operation
*
* */
@Operation(name = "$evaluate-measure", idempotent = true)
public MeasureReport evaluateMeasure(
@IdParam IdType theId,
@RequiredParam(name="periodStart") String periodStart,
@RequiredParam(name="periodEnd") String periodEnd,
@OptionalParam(name="measure") String measureRef,
@OptionalParam(name="reportType") String reportType,
@OptionalParam(name="patient") String patientRef,
@OptionalParam(name="practitioner") String practitionerRef,
@OptionalParam(name="lastReceivedOn") String lastReceivedOn,
@OptionalParam(name="source") String source,
@OptionalParam(name="user") String user,
@OptionalParam(name="pass") String pass) throws InternalErrorException, FHIRException
{
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(provider, libraryLoader);
Measure measure = this.getDao().read(theId);
if (measure == null)
{
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, source, user, pass);
// resolve report type
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), seed.getMeasurementPeriod());
boolean isQdm = seed.getDataProvider() instanceof Qdm54DataProvider;
if (reportType != null) {
switch (reportType) {
case "patient": return isQdm ? evaluator.evaluateQdmPatientMeasure(seed.getMeasure(), seed.getContext(), patientRef) : evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
case "patient-list": return evaluator.evaluatePatientListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
case "population": return isQdm ? evaluator.evaluateQdmPopulationMeasure(seed.getMeasure(), seed.getContext()) : evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
default: throw new IllegalArgumentException("Invalid report type: " + reportType);
}
}
// default report type is patient
return isQdm ? evaluator.evaluateQdmPatientMeasure(seed.getMeasure(), seed.getContext(), patientRef) : evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
}
@Operation(name = "$evaluate-measure-with-source", idempotent = true)
public MeasureReport evaluateMeasure(
@IdParam IdType theId,
@OperationParam(name="sourceData", min = 1, max = 1, type = Bundle.class) Bundle sourceData,
@OperationParam(name="periodStart", min = 1, max = 1) String periodStart,
@OperationParam(name="periodEnd", min = 1, max = 1) String periodEnd)
{
if (periodStart == null || periodEnd == null) {
throw new IllegalArgumentException("periodStart and periodEnd are required for measure evaluation");
}
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(provider, libraryLoader);
Measure measure = this.getDao().read(theId);
if (measure == null)
{
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, null, null, null);
BundleDataProviderStu3 bundleProvider = new BundleDataProviderStu3(sourceData);
bundleProvider.setTerminologyProvider(provider.getTerminologyProvider());
seed.getContext().registerDataProvider("http://hl7.org/fhir", bundleProvider);
MeasureEvaluation evaluator = new MeasureEvaluation(bundleProvider, seed.getMeasurementPeriod());
return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), "");
}
@Operation(name = "$care-gaps", idempotent = true)
public Bundle careGapsReport(
@RequiredParam(name="periodStart") String periodStart,
@RequiredParam(name="periodEnd") String periodEnd,
@RequiredParam(name="topic") String topic,
@RequiredParam(name="patient") String patientRef
) {
List<IBaseResource> measures = getDao().search(new SearchParameterMap().add("topic", new TokenParam().setModifier(TokenParamModifier.TEXT).setValue(topic))).getResources(0, 1000);
Bundle careGapReport = new Bundle();
careGapReport.setType(Bundle.BundleType.DOCUMENT);
Composition composition = new Composition();
// TODO - this is a placeholder code for now ... replace with preferred code once identified
CodeableConcept typeCode = new CodeableConcept().addCoding(new Coding().setSystem("http://loinc.org").setCode("57024-2"));
composition.setStatus(Composition.CompositionStatus.FINAL)
.setType(typeCode)
.setSubject(new Reference(patientRef.startsWith("Patient/") ? patientRef : "Patient/" + patientRef))
.setTitle(topic + " Care Gap Report");
List<MeasureReport> reports = new ArrayList<>();
MeasureReport report = new MeasureReport();
for (IBaseResource resource : measures) {
Composition.SectionComponent section = new Composition.SectionComponent();
Measure measure = (Measure) resource;
section.addEntry(new Reference(measure.getIdElement().getResourceType() + "/" + measure.getIdElement().getIdPart()));
if (measure.hasTitle()) {
section.setTitle(measure.getTitle());
}
String improvementNotation = "increase"; // defaulting to "increase"
if (measure.hasImprovementNotation()) {
improvementNotation = measure.getImprovementNotation();
section.setText(
new Narrative()
.setStatus(Narrative.NarrativeStatus.GENERATED)
.setDiv(new XhtmlNode().setValue(improvementNotation))
);
}
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(provider, libraryLoader);
seed.setup(measure, periodStart, periodEnd, null, null, null);
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), seed.getMeasurementPeriod());
// TODO - this is configured for patient-level evaluation only
report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
if (report.hasGroup() && measure.hasScoring()) {
int numerator = 0;
int denominator = 0;
for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
if (group.hasPopulation()) {
for (MeasureReport.MeasureReportGroupPopulationComponent population : group.getPopulation()) {
// TODO - currently configured for measures with only 1 numerator and 1 denominator
if (population.hasCode()) {
if (population.getCode().hasCoding()) {
for (Coding coding : population.getCode().getCoding()) {
if (coding.hasCode()) {
if (coding.getCode().equals("numerator") && population.hasCount()) {
numerator = population.getCount();
}
else if (coding.getCode().equals("denominator") && population.hasCount()) {
denominator = population.getCount();
}
}
}
}
}
}
}
}
double proportion = 0.0;
if (measure.getScoring().hasCoding() && denominator != 0) {
for (Coding coding : measure.getScoring().getCoding()) {
if (coding.hasCode() && coding.getCode().equals("proportion")) {
proportion = numerator / denominator;
}
}
}
// TODO - this is super hacky ... change once improvementNotation is specified as a code
if (improvementNotation.toLowerCase().contains("increase")) {
if (proportion < 1.0) {
composition.addSection(section);
reports.add(report);
}
}
else if (improvementNotation.toLowerCase().contains("decrease")) {
if (proportion > 0.0) {
composition.addSection(section);
reports.add(report);
}
}
// TODO - add other types of improvement notation cases
}
}
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition));
for (MeasureReport rep : reports) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep));
}
return careGapReport;
}
@Operation(name = "$collect-data", idempotent = true)
public Parameters collectData(
@IdParam IdType theId,
@RequiredParam(name="periodStart") String periodStart,
@RequiredParam(name="periodEnd") String periodEnd,
@OptionalParam(name="patient") String patientRef,
@OptionalParam(name="practitioner") String practitionerRef,
@OptionalParam(name="lastReceivedOn") String lastReceivedOn
) throws FHIRException
{
// TODO: Spec says that the periods are not required, but I am not sure what to do when they aren't supplied so I made them required
MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, practitionerRef, lastReceivedOn, null, null, null);
report.setGroup(null);
Parameters parameters = new Parameters();
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report)
);
if (report.hasContained())
{
for (Resource contained : report.getContained())
{
if (contained instanceof Bundle)
{
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
}
}
}
// TODO: need a way to resolve referenced resources within the evaluated resources
// Should be able to use _include search with * wildcard, but HAPI doesn't support that
return parameters;
}
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters)
{
Map<String, Resource> resourceMap = new HashMap<>();
if (contained.hasEntry())
{
for (Bundle.BundleEntryComponent entry : contained.getEntry())
{
if (entry.hasResource() && !(entry.getResource() instanceof ListResource))
{
if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue()))
{
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("resource").setResource(entry.getResource())
);
resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());
resolveReferences(entry.getResource(), parameters, resourceMap);
}
}
}
}
}
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap)
{
List<IBase> values;
for (BaseRuntimeChildDefinition child : getContext().getResourceDefinition(resource).getChildren())
{
values = child.getAccessor().getValues(resource);
if (values == null || values.isEmpty())
{
continue;
}
else if (values.get(0) instanceof Reference
&& ((Reference) values.get(0)).getReferenceElement().hasResourceType()
&& ((Reference) values.get(0)).getReferenceElement().hasIdPart())
{
Resource fetchedResource =
(Resource) provider.resolveResourceProvider(
((Reference) values.get(0)).getReferenceElement().getResourceType()
).getDao().read(
new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart())
);
if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue()))
{
parameters.addParameter(
new Parameters.ParametersParameterComponent()
.setName("resource")
.setResource(fetchedResource)
);
resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
}
}
}
}
// TODO - this needs a lot of work
@Operation(name = "$data-requirements", idempotent = true)
public org.hl7.fhir.dstu3.model.Library dataRequirements(
@IdParam IdType theId,
@RequiredParam(name="startPeriod") String startPeriod,
@RequiredParam(name="endPeriod") String endPeriod)
throws InternalErrorException, FHIRException
{
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
Measure measure = this.getDao().read(theId);
return getDataRequirements(measure, libraryLoader);
}
protected org.hl7.fhir.dstu3.model.Library getDataRequirements(Measure measure, STU3LibraryLoader libraryLoader){
LibraryHelper.loadLibraries(measure, libraryLoader, this.libraryResourceProvider);
List<DataRequirement> reqs = new ArrayList<>();
List<RelatedArtifact> dependencies = new ArrayList<>();
List<ParameterDefinition> parameters = new ArrayList<>();
for (Library library : libraryLoader.getLibraries()) {
VersionedIdentifier primaryLibraryIdentifier = library.getIdentifier();
org.hl7.fhir.dstu3.model.Library libraryResource = LibraryResourceHelper.resolveLibraryByName(
(LibraryResourceProvider)provider.resolveResourceProvider("Library"),
primaryLibraryIdentifier.getId(),
primaryLibraryIdentifier.getVersion());
for (RelatedArtifact dependency : libraryResource.getRelatedArtifact()) {
if (dependency.getType().toCode().equals("depends-on")) {
dependencies.add(dependency);
}
}
reqs.addAll(libraryResource.getDataRequirement());
parameters.addAll(libraryResource.getParameter());
}
List<Coding> typeCoding = new ArrayList<>();
typeCoding.add(new Coding().setCode("module-definition"));
org.hl7.fhir.dstu3.model.Library library =
new org.hl7.fhir.dstu3.model.Library().setType(new CodeableConcept().setCoding(typeCoding));
if (!dependencies.isEmpty()) {
library.setRelatedArtifact(dependencies);
}
if (!reqs.isEmpty()) {
library.setDataRequirement(reqs);
}
if (!parameters.isEmpty()) {
library.setParameter(parameters);
}
return library;
}
@Operation(name = "$submit-data", idempotent = true)
public Resource submitData(
RequestDetails details,
@IdParam IdType theId,
@OperationParam(name="measure-report", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
@OperationParam(name="resource") List<IAnyResource> resources)
{
Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
/*
TODO - resource validation using $data-requirements operation
(params are the provided id and the measurement period from the MeasureReport)
TODO - profile validation ... not sure how that would work ...
(get StructureDefinition from URL or must it be stored in Ruler?)
*/
transactionBundle.addEntry(createTransactionEntry(report));
for (IAnyResource resource : resources) {
Resource res = (Resource) resource;
if (res instanceof Bundle) {
for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
transactionBundle.addEntry(entry);
}
}
else {
// Build transaction bundle
transactionBundle.addEntry(createTransactionEntry(res));
}
}
return (Resource) systemDao.transaction(details, transactionBundle);
}
private CqfMeasure createCqfMeasure(Measure measure, STU3LibraryLoader libraryLoader) {
org.hl7.fhir.dstu3.model.Library moduleDefinition = this.getDataRequirements(measure, libraryLoader);
CqfMeasure cqfMeasure = new CqfMeasure(measure);
//Ensure All Related Artifacts for all referenced Libraries
if (!moduleDefinition.getRelatedArtifact().isEmpty()) {
for (RelatedArtifact relatedArtifact : moduleDefinition.getRelatedArtifact()) {
boolean artifactExists = false;
//logger.info("Related Artifact: " + relatedArtifact.getUrl());
for (RelatedArtifact resourceArtifact : cqfMeasure.getRelatedArtifact()) {
if (resourceArtifact.equalsDeep(relatedArtifact)) {
//logger.info("Equals deep true");
artifactExists = true;
break;
}
}
if (!artifactExists) {
cqfMeasure.addRelatedArtifact(relatedArtifact.copy());
}
}
}
//Ensure All Data Requirements for all referenced libraries
Library primaryLibrary = LibraryHelper.resolvePrimaryLibrary(measure, libraryLoader);
VersionedIdentifier primaryLibraryIdentifier = primaryLibrary.getIdentifier();
org.hl7.fhir.dstu3.model.Library libraryResource = LibraryResourceHelper.resolveLibraryByName(
libraryResourceProvider,
primaryLibraryIdentifier.getId(),
primaryLibraryIdentifier.getVersion());
cqfMeasure.setContent(libraryResource.getContent());
cqfMeasure.setDataRequirement(moduleDefinition.getDataRequirement());
cqfMeasure.setParameter(moduleDefinition.getParameter());
return cqfMeasure;
}
private Bundle createTransactionBundle(Bundle bundle) {
Bundle transactionBundle;
if (bundle != null) {
if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
transactionBundle = bundle;
}
else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
if (bundle.hasEntry()) {
for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
if (entry.hasResource()) {
transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
}
}
}
}
}
else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
}
return transactionBundle;
}
private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) {
Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource);
if (resource.hasId()) {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent()
.setMethod(Bundle.HTTPVerb.PUT)
.setUrl(resource.getId())
);
}
else {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent()
.setMethod(Bundle.HTTPVerb.POST)
.setUrl(resource.fhirType())
);
}
return transactionEntry;
}
}
|
src/main/java/org/opencds/cqf/providers/FHIRMeasureResourceProvider.java
|
package org.opencds.cqf.providers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.cqframework.cql.elm.execution.Library;
import org.cqframework.cql.elm.execution.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.CodeableConcept;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.Composition;
import org.hl7.fhir.dstu3.model.DataRequirement;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.ListResource;
import org.hl7.fhir.dstu3.model.Measure;
import org.hl7.fhir.dstu3.model.MeasureReport;
import org.hl7.fhir.dstu3.model.Narrative;
import org.hl7.fhir.dstu3.model.ParameterDefinition;
import org.hl7.fhir.dstu3.model.Parameters;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.dstu3.model.RelatedArtifact;
import org.hl7.fhir.dstu3.model.Resource;
import org.hl7.fhir.dstu3.model.StringType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.opencds.cqf.config.STU3LibraryLoader;
import org.opencds.cqf.evaluation.MeasureEvaluation;
import org.opencds.cqf.evaluation.MeasureEvaluationSeed;
import org.opencds.cqf.helpers.LibraryHelper;
import org.opencds.cqf.helpers.LibraryResourceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.jpa.dao.IFhirSystemDao;
import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;
import ca.uhn.fhir.jpa.rp.dstu3.MeasureResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.TokenParamModifier;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
public class FHIRMeasureResourceProvider extends MeasureResourceProvider {
private JpaDataProvider provider;
private IFhirSystemDao systemDao;
private NarrativeProvider narrativeProvider;
private HQMFProvider hqmfProvider;
private LibraryResourceProvider libraryResourceProvider;
private static final Logger logger = LoggerFactory.getLogger(FHIRMeasureResourceProvider.class);
public FHIRMeasureResourceProvider(JpaDataProvider dataProvider, IFhirSystemDao systemDao, NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider) {
this.provider = dataProvider;
this.systemDao = systemDao;
this.libraryResourceProvider = (LibraryResourceProvider) dataProvider.resolveResourceProvider("Library");
this.narrativeProvider = narrativeProvider;
this.hqmfProvider = hqmfProvider;
}
@Operation(name="$hqmf", idempotent = true)
public Parameters hqmf(@IdParam IdType theId) {
Measure theResource = this.getDao().read(theId);
String hqmf = this.generateHQMF(theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(hqmf));
return p;
}
@Operation(name="$refresh-generated-content")
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails, @IdParam IdType theId) {
Measure theResource = this.getDao().read(theId);
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
LibraryHelper.loadLibraries(theResource, libraryLoader, this.libraryResourceProvider);
//Ensure All Related Artifacts for all referenced Libraries
org.hl7.fhir.dstu3.model.Library moduleDefinition = getDataRequirements(theResource, libraryLoader);
if (!moduleDefinition.getRelatedArtifact().isEmpty()) {
for (RelatedArtifact relatedArtifact : moduleDefinition.getRelatedArtifact()) {
boolean artifactExists = false;
//logger.info("Related Artifact: " + relatedArtifact.getUrl());
for (RelatedArtifact resourceArtifact : theResource.getRelatedArtifact()) {
if (resourceArtifact.equalsDeep(relatedArtifact)) {
//logger.info("Equals deep true");
artifactExists = true;
break;
}
}
if (!artifactExists) {
theResource.addRelatedArtifact(relatedArtifact.copy());
}
}
}
//Ensure All Data Requirements for all referenced libraries
Narrative n = getMeasureNarrative(theResource.copy(), moduleDefinition, libraryLoader);
theResource.setText(n.copy());
//logger.info("Narrative: " + n.getDivAsString());
return super.update(theRequest, theResource, theId, theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name="$get-narrative", idempotent = true)
public Parameters getNarrative(@IdParam IdType theId) {
Measure theResource = this.getDao().read(theId);
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
LibraryHelper.loadLibraries(theResource, libraryLoader, this.libraryResourceProvider);
org.hl7.fhir.dstu3.model.Library moduleDefinition = getDataRequirements(theResource, libraryLoader);
Narrative n = getMeasureNarrative(theResource, moduleDefinition, libraryLoader);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
private String generateHQMF(Measure measure) {
return this.hqmfProvider.generateHQMF(measure);
}
private Narrative getMeasureNarrative(Measure theResource, org.hl7.fhir.dstu3.model.Library moduleDefinition, STU3LibraryLoader libraryLoader) {
//this.getContext().registerCustomType(CqfMeasure.class);
CqfMeasure cqfMeasure = new CqfMeasure(theResource);
//cqfMeasure = this.getContext().newJsonParser().parseResource(CqfMeasure.class, theResource);
//theResource.copyValues(cqfMeasure);
Library primaryLibrary = LibraryHelper.resolvePrimaryLibrary(theResource, libraryLoader);
VersionedIdentifier primaryLibraryIdentifier = primaryLibrary.getIdentifier();
org.hl7.fhir.dstu3.model.Library libraryResource = LibraryResourceHelper.resolveLibraryByName(
libraryResourceProvider,
primaryLibraryIdentifier.getId(),
primaryLibraryIdentifier.getVersion());
cqfMeasure.setContent(libraryResource.getContent());
cqfMeasure.setDataRequirement(moduleDefinition.getDataRequirement());
cqfMeasure.setParameter(moduleDefinition.getParameter());
// for (Library library : libraryLoader.getLibraries().values()) {
// logger.info("Library Annotation: " + library.getAnnotation().size());
// for (ExpressionDef statement : library.getStatements().getDef()) {
// logger.info("Statement: " + statement.getName());
// //logger.info("Expression: " + statement.getExpression().toString());
// //logger.info("Context: " + statement.getContext());
// for (Object annotation : statement.getAnnotation()) {
// logger.info("Annotation: " + annotation);
// }
// //logger.info("Size: " + statement.getAnnotation());
// }
// }
Narrative n = this.narrativeProvider.getNarrative(this.getContext(), cqfMeasure);
return n;
}
/*
*
* NOTE that the source, user, and pass parameters are not standard parameters for the FHIR $evaluate-measure operation
*
* */
@Operation(name = "$evaluate-measure", idempotent = true)
public MeasureReport evaluateMeasure(
@IdParam IdType theId,
@RequiredParam(name="periodStart") String periodStart,
@RequiredParam(name="periodEnd") String periodEnd,
@OptionalParam(name="measure") String measureRef,
@OptionalParam(name="reportType") String reportType,
@OptionalParam(name="patient") String patientRef,
@OptionalParam(name="practitioner") String practitionerRef,
@OptionalParam(name="lastReceivedOn") String lastReceivedOn,
@OptionalParam(name="source") String source,
@OptionalParam(name="user") String user,
@OptionalParam(name="pass") String pass) throws InternalErrorException, FHIRException
{
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(provider, libraryLoader);
Measure measure = this.getDao().read(theId);
if (measure == null)
{
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, source, user, pass);
// resolve report type
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), seed.getMeasurementPeriod());
boolean isQdm = seed.getDataProvider() instanceof Qdm54DataProvider;
if (reportType != null) {
switch (reportType) {
case "patient": return isQdm ? evaluator.evaluateQdmPatientMeasure(seed.getMeasure(), seed.getContext(), patientRef) : evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
case "patient-list": return evaluator.evaluatePatientListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
case "population": return isQdm ? evaluator.evaluateQdmPopulationMeasure(seed.getMeasure(), seed.getContext()) : evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
default: throw new IllegalArgumentException("Invalid report type: " + reportType);
}
}
// default report type is patient
return isQdm ? evaluator.evaluateQdmPatientMeasure(seed.getMeasure(), seed.getContext(), patientRef) : evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
}
@Operation(name = "$evaluate-measure-with-source", idempotent = true)
public MeasureReport evaluateMeasure(
@IdParam IdType theId,
@OperationParam(name="sourceData", min = 1, max = 1, type = Bundle.class) Bundle sourceData,
@OperationParam(name="periodStart", min = 1, max = 1) String periodStart,
@OperationParam(name="periodEnd", min = 1, max = 1) String periodEnd)
{
if (periodStart == null || periodEnd == null) {
throw new IllegalArgumentException("periodStart and periodEnd are required for measure evaluation");
}
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(provider, libraryLoader);
Measure measure = this.getDao().read(theId);
if (measure == null)
{
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, null, null, null);
BundleDataProviderStu3 bundleProvider = new BundleDataProviderStu3(sourceData);
bundleProvider.setTerminologyProvider(provider.getTerminologyProvider());
seed.getContext().registerDataProvider("http://hl7.org/fhir", bundleProvider);
MeasureEvaluation evaluator = new MeasureEvaluation(bundleProvider, seed.getMeasurementPeriod());
return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), "");
}
@Operation(name = "$care-gaps", idempotent = true)
public Bundle careGapsReport(
@RequiredParam(name="periodStart") String periodStart,
@RequiredParam(name="periodEnd") String periodEnd,
@RequiredParam(name="topic") String topic,
@RequiredParam(name="patient") String patientRef
) {
List<IBaseResource> measures = getDao().search(new SearchParameterMap().add("topic", new TokenParam().setModifier(TokenParamModifier.TEXT).setValue(topic))).getResources(0, 1000);
Bundle careGapReport = new Bundle();
careGapReport.setType(Bundle.BundleType.DOCUMENT);
Composition composition = new Composition();
// TODO - this is a placeholder code for now ... replace with preferred code once identified
CodeableConcept typeCode = new CodeableConcept().addCoding(new Coding().setSystem("http://loinc.org").setCode("57024-2"));
composition.setStatus(Composition.CompositionStatus.FINAL)
.setType(typeCode)
.setSubject(new Reference(patientRef.startsWith("Patient/") ? patientRef : "Patient/" + patientRef))
.setTitle(topic + " Care Gap Report");
List<MeasureReport> reports = new ArrayList<>();
MeasureReport report = new MeasureReport();
for (IBaseResource resource : measures) {
Composition.SectionComponent section = new Composition.SectionComponent();
Measure measure = (Measure) resource;
section.addEntry(new Reference(measure.getIdElement().getResourceType() + "/" + measure.getIdElement().getIdPart()));
if (measure.hasTitle()) {
section.setTitle(measure.getTitle());
}
String improvementNotation = "increase"; // defaulting to "increase"
if (measure.hasImprovementNotation()) {
improvementNotation = measure.getImprovementNotation();
section.setText(
new Narrative()
.setStatus(Narrative.NarrativeStatus.GENERATED)
.setDiv(new XhtmlNode().setValue(improvementNotation))
);
}
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(provider, libraryLoader);
seed.setup(measure, periodStart, periodEnd, null, null, null);
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), seed.getMeasurementPeriod());
// TODO - this is configured for patient-level evaluation only
report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
if (report.hasGroup() && measure.hasScoring()) {
int numerator = 0;
int denominator = 0;
for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
if (group.hasPopulation()) {
for (MeasureReport.MeasureReportGroupPopulationComponent population : group.getPopulation()) {
// TODO - currently configured for measures with only 1 numerator and 1 denominator
if (population.hasCode()) {
if (population.getCode().hasCoding()) {
for (Coding coding : population.getCode().getCoding()) {
if (coding.hasCode()) {
if (coding.getCode().equals("numerator") && population.hasCount()) {
numerator = population.getCount();
}
else if (coding.getCode().equals("denominator") && population.hasCount()) {
denominator = population.getCount();
}
}
}
}
}
}
}
}
double proportion = 0.0;
if (measure.getScoring().hasCoding() && denominator != 0) {
for (Coding coding : measure.getScoring().getCoding()) {
if (coding.hasCode() && coding.getCode().equals("proportion")) {
proportion = numerator / denominator;
}
}
}
// TODO - this is super hacky ... change once improvementNotation is specified as a code
if (improvementNotation.toLowerCase().contains("increase")) {
if (proportion < 1.0) {
composition.addSection(section);
reports.add(report);
}
}
else if (improvementNotation.toLowerCase().contains("decrease")) {
if (proportion > 0.0) {
composition.addSection(section);
reports.add(report);
}
}
// TODO - add other types of improvement notation cases
}
}
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition));
for (MeasureReport rep : reports) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep));
}
return careGapReport;
}
@Operation(name = "$collect-data", idempotent = true)
public Parameters collectData(
@IdParam IdType theId,
@RequiredParam(name="periodStart") String periodStart,
@RequiredParam(name="periodEnd") String periodEnd,
@OptionalParam(name="patient") String patientRef,
@OptionalParam(name="practitioner") String practitionerRef,
@OptionalParam(name="lastReceivedOn") String lastReceivedOn
) throws FHIRException
{
// TODO: Spec says that the periods are not required, but I am not sure what to do when they aren't supplied so I made them required
MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, practitionerRef, lastReceivedOn, null, null, null);
report.setGroup(null);
Parameters parameters = new Parameters();
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report)
);
if (report.hasContained())
{
for (Resource contained : report.getContained())
{
if (contained instanceof Bundle)
{
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
}
}
}
// TODO: need a way to resolve referenced resources within the evaluated resources
// Should be able to use _include search with * wildcard, but HAPI doesn't support that
return parameters;
}
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters)
{
Map<String, Resource> resourceMap = new HashMap<>();
if (contained.hasEntry())
{
for (Bundle.BundleEntryComponent entry : contained.getEntry())
{
if (entry.hasResource() && !(entry.getResource() instanceof ListResource))
{
if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue()))
{
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("resource").setResource(entry.getResource())
);
resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());
resolveReferences(entry.getResource(), parameters, resourceMap);
}
}
}
}
}
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap)
{
List<IBase> values;
for (BaseRuntimeChildDefinition child : getContext().getResourceDefinition(resource).getChildren())
{
values = child.getAccessor().getValues(resource);
if (values == null || values.isEmpty())
{
continue;
}
else if (values.get(0) instanceof Reference
&& ((Reference) values.get(0)).getReferenceElement().hasResourceType()
&& ((Reference) values.get(0)).getReferenceElement().hasIdPart())
{
Resource fetchedResource =
(Resource) provider.resolveResourceProvider(
((Reference) values.get(0)).getReferenceElement().getResourceType()
).getDao().read(
new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart())
);
if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue()))
{
parameters.addParameter(
new Parameters.ParametersParameterComponent()
.setName("resource")
.setResource(fetchedResource)
);
resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
}
}
}
}
// TODO - this needs a lot of work
@Operation(name = "$data-requirements", idempotent = true)
public org.hl7.fhir.dstu3.model.Library dataRequirements(
@IdParam IdType theId,
@RequiredParam(name="startPeriod") String startPeriod,
@RequiredParam(name="endPeriod") String endPeriod)
throws InternalErrorException, FHIRException
{
STU3LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
Measure measure = this.getDao().read(theId);
return getDataRequirements(measure, libraryLoader);
}
protected org.hl7.fhir.dstu3.model.Library getDataRequirements(Measure measure, STU3LibraryLoader libraryLoader){
LibraryHelper.loadLibraries(measure, libraryLoader, this.libraryResourceProvider);
List<DataRequirement> reqs = new ArrayList<>();
List<RelatedArtifact> dependencies = new ArrayList<>();
List<ParameterDefinition> parameters = new ArrayList<>();
for (Library library : libraryLoader.getLibraries()) {
VersionedIdentifier primaryLibraryIdentifier = library.getIdentifier();
org.hl7.fhir.dstu3.model.Library libraryResource = LibraryResourceHelper.resolveLibraryByName(
(LibraryResourceProvider)provider.resolveResourceProvider("Library"),
primaryLibraryIdentifier.getId(),
primaryLibraryIdentifier.getVersion());
for (RelatedArtifact dependency : libraryResource.getRelatedArtifact()) {
if (dependency.getType().toCode().equals("depends-on")) {
dependencies.add(dependency);
}
}
reqs.addAll(libraryResource.getDataRequirement());
parameters.addAll(libraryResource.getParameter());
}
List<Coding> typeCoding = new ArrayList<>();
typeCoding.add(new Coding().setCode("module-definition"));
org.hl7.fhir.dstu3.model.Library library =
new org.hl7.fhir.dstu3.model.Library().setType(new CodeableConcept().setCoding(typeCoding));
if (!dependencies.isEmpty()) {
library.setRelatedArtifact(dependencies);
}
if (!reqs.isEmpty()) {
library.setDataRequirement(reqs);
}
if (!parameters.isEmpty()) {
library.setParameter(parameters);
}
return library;
}
@Operation(name = "$submit-data", idempotent = true)
public Resource submitData(
RequestDetails details,
@IdParam IdType theId,
@OperationParam(name="measure-report", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
@OperationParam(name="resource") List<IAnyResource> resources)
{
Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
/*
TODO - resource validation using $data-requirements operation
(params are the provided id and the measurement period from the MeasureReport)
TODO - profile validation ... not sure how that would work ...
(get StructureDefinition from URL or must it be stored in Ruler?)
*/
transactionBundle.addEntry(createTransactionEntry(report));
for (IAnyResource resource : resources) {
Resource res = (Resource) resource;
if (res instanceof Bundle) {
for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
transactionBundle.addEntry(entry);
}
}
else {
// Build transaction bundle
transactionBundle.addEntry(createTransactionEntry(res));
}
}
return (Resource) systemDao.transaction(details, transactionBundle);
}
private Bundle createTransactionBundle(Bundle bundle) {
Bundle transactionBundle;
if (bundle != null) {
if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
transactionBundle = bundle;
}
else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
if (bundle.hasEntry()) {
for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
if (entry.hasResource()) {
transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
}
}
}
}
}
else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
}
return transactionBundle;
}
private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) {
Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource);
if (resource.hasId()) {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent()
.setMethod(Bundle.HTTPVerb.PUT)
.setUrl(resource.getId())
);
}
else {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent()
.setMethod(Bundle.HTTPVerb.POST)
.setUrl(resource.fhirType())
);
}
return transactionEntry;
}
}
|
Refactor FHIRMeasureResourceProvider
|
src/main/java/org/opencds/cqf/providers/FHIRMeasureResourceProvider.java
|
Refactor FHIRMeasureResourceProvider
|
|
Java
|
apache-2.0
|
3f4df8fdcb12689afec4e8e81bd7511e9b84966a
| 0
|
mattgmg1990/CMHome-SDK-Example
|
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.content.Context;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId()); }
}
|
app/src/main/java/org/cyanogenmod/launcher/home/api/sdkexample/receiver/CardDeletedBroadcastReceiver.java
|
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId());
}
}
|
Add Context parameter to onCardDelete to match SDK
|
app/src/main/java/org/cyanogenmod/launcher/home/api/sdkexample/receiver/CardDeletedBroadcastReceiver.java
|
Add Context parameter to onCardDelete to match SDK
|
|
Java
|
apache-2.0
|
3482c9f719435d0574121a2b2710245c6b5789e5
| 0
|
webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno
|
/*******************************************************************************
* Copyright 2015
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.tudarmstadt.ukp.clarin.webanno.project.page;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService;
import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ConstraintsGrammar;
import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ParseException;
import de.tudarmstadt.ukp.clarin.webanno.model.ConstraintSet;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.support.EntityModel;
/**
* A Panel used to add Project Constraints Rules in a selected {@link Project}
*
*
*/
public class ProjectConstraintsPanel
extends Panel
{
private static final long serialVersionUID = 8910455936756021733L;
private static final Log LOG = LogFactory.getLog(ProjectConstraintsPanel.class);
@SpringBean(name = "documentRepository")
private RepositoryService projectRepository;
private SelectionForm selectionForm;
private DetailForm detailForm;
private ImportForm importForm;
public ProjectConstraintsPanel(String id, IModel<Project> aProjectModel)
{
super(id, aProjectModel);
add(selectionForm = new SelectionForm("selectionForm"));
add(detailForm = new DetailForm("detailForm"));
add(importForm = new ImportForm("importForm"));
}
public Project getModelObject()
{
return (Project) getDefaultModelObject();
}
public class SelectionForm
extends Form<ConstraintSet>
{
private static final long serialVersionUID = -4835473062143674510L;
public SelectionForm(String aId)
{
super(aId, Model.of((ConstraintSet) null));
LoadableDetachableModel<List<ConstraintSet>> rulesets = new LoadableDetachableModel<List<ConstraintSet>>()
{
private static final long serialVersionUID = 1L;
@Override
protected List<ConstraintSet> load()
{
return projectRepository.listConstraintSets(ProjectConstraintsPanel.this
.getModelObject());
}
};
add(new ListChoice<ConstraintSet>("ruleset", SelectionForm.this.getModel(), rulesets) {
private static final long serialVersionUID = 1L;
{
setChoiceRenderer(new ChoiceRenderer<ConstraintSet>("name"));
setNullValid(false);
}
@Override
protected void onSelectionChanged(ConstraintSet aNewSelection)
{
ProjectConstraintsPanel.this.detailForm.setModelObject(aNewSelection);
}
@Override
protected boolean wantOnSelectionChangedNotifications()
{
return true;
}
@Override
protected CharSequence getDefaultChoice(String aSelectedValue)
{
return "";
}
});
}
}
public class DetailForm
extends Form<ConstraintSet>
{
private static final long serialVersionUID = 8696334789027911595L;
private TextArea<String> script;
public DetailForm(String aId)
{
super(aId, new CompoundPropertyModel<ConstraintSet>(new EntityModel<ConstraintSet>(null)));
TextField<String> constraintNameTextField = new TextField<>("name");
add(constraintNameTextField);
add(script = new TextArea<String>("script", new LoadableDetachableModel<String>()
{
private static final long serialVersionUID = 1L;
@Override
protected String load()
{
try {
return projectRepository.readConstrainSet(DetailForm.this.getModelObject());
}
catch (IOException e) {
// Cannot call "Component.error()" here - it causes a
// org.apache.wicket.WicketRuntimeException: Cannot modify component
// hierarchy after render phase has started (page version cant change then
// anymore)
LOG.error("Unable to load script", e);
return "Unable to load script: " + ExceptionUtils.getRootCauseMessage(e);
}
}
}));
// Script not editable - if we remove this flag, then the script area will not update
// when switching set selection
script.setEnabled(false);
final IModel<String> exportFilenameModel = new Model<>();
final IModel<File> exportFileModel = new LoadableDetachableModel<File>()
{
private static final long serialVersionUID = 840863954694163375L;
@Override
protected File load()
{
try {
// Use the name of the constraints set instead of the ID under which the
// file is saved internally.
exportFilenameModel.setObject(DetailForm.this.getModelObject().getName());
return projectRepository.exportConstraintAsFile(DetailForm.this
.getModelObject());
}
catch (IOException e) {
throw new WicketRuntimeException(e);
}
}
};
add(new DownloadLink("export", exportFileModel, exportFilenameModel));
Button deleteButton = new Button("delete", new ResourceModel("label")) {
private static final long serialVersionUID = -1195565364207114557L;
@Override
public void onSubmit()
{
projectRepository.removeConstraintSet(DetailForm.this.getModelObject());
DetailForm.this.setModelObject(null);
selectionForm.setModelObject(null);
}
@Override
protected void onConfigure()
{
super.onConfigure();
setVisible(DetailForm.this.getModelObject().getId() >= 0);
}
};
// Add check to prevent accidental delete operation
deleteButton.add(new AttributeModifier("onclick",
"if(!confirm('Do you really want to delete this Constraints rule?')) return false;"));
add(deleteButton);
add(new Button("save", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
// Actually nothing to do here. Wicket will transfer the values from the
// form into the model object and Hibernate will persist it
}
@Override
public void validate() {
super.validate();
//Checking if the name provided already exists or not
if(projectRepository.existConstraintSet(constraintNameTextField.getInput(), ProjectConstraintsPanel.this.getModelObject())
&& !constraintNameTextField.getInput().equals(constraintNameTextField.getModelObject())){
error("Provided name for Constraint already exists, please choose a different name");
}
}
});
add(new Button("cancel", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
{
// Avoid saving data
setDefaultFormProcessing(false);
setVisible(true);
}
@Override
public void onSubmit()
{
DetailForm.this.setModelObject(null);
}
});
}
@Override
protected void onConfigure()
{
super.onConfigure();
setVisible(getModelObject() != null);
}
}
public class ImportForm
extends Form<Void>
{
private static final long serialVersionUID = 8121850699963791359L;
private List<FileUpload> uploads;
public ImportForm(String aId)
{
super(aId);
add(new FileUploadField("uploads", PropertyModel.<List<FileUpload>> of(this, "uploads")));
add(new Button("import", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
try {
importAction();
}
catch (ParseException e) {
error("Exception while parsing the constraint rules file. Please check it. "
+ ExceptionUtils.getRootCauseMessage(e));
}
catch (IOException e) {
error("Unable to read constraints file "
+ ExceptionUtils.getRootCauseMessage(e));
}
}
});
}
private void importAction() throws ParseException, IOException
{
Project project = ProjectConstraintsPanel.this.getModelObject();
if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
if (isEmpty(uploads)) {
error("No document is selected to upload, please select a document first");
return;
}
for (FileUpload constraintRulesFile : uploads) {
// Checking if file is OK as per Constraints Grammar specification
boolean constraintRuleFileIsOK = false;
//Handling Windows BOM
BOMInputStream bomInputStream;
bomInputStream = new BOMInputStream(constraintRulesFile.getInputStream(), false);
ConstraintsGrammar parser = new ConstraintsGrammar(bomInputStream);
// utfInputStream = new
// InputStreamReader(constraintRulesFile.getInputStream(),"UTF-8");
// ConstraintsGrammar parser = new ConstraintsGrammar(utfInputStream);
parser.Parse();
constraintRuleFileIsOK = true;
// Persist rules
if (constraintRuleFileIsOK) {
try {
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.setProject(ProjectConstraintsPanel.this.getModelObject());
//Check if ConstraintSet already exists or not
String constraintFilename = constraintRulesFile.getClientFileName();
if(projectRepository.existConstraintSet(constraintFilename, project)){
constraintFilename = copyConstraintName(projectRepository,constraintFilename);
}
constraintSet.setName(constraintFilename);
projectRepository.createConstraintSet(constraintSet);
projectRepository.writeConstraintSet(constraintSet,
constraintRulesFile.getInputStream());
detailForm.setModelObject(constraintSet);
selectionForm.setModelObject(constraintSet);
}
catch (IOException e) {
detailForm.setModelObject(null);
error("Unable to write constraints file "
+ ExceptionUtils.getRootCauseMessage(e));
}
}
}
}
/**
* Checks if name exists, if yes, creates an alternate name for ConstraintSet
* @param projectRepository
* @param constraintFilename
* @return
*/
private String copyConstraintName(RepositoryService projectRepository, String constraintFilename)
{
String betterConstraintName = "copy_of_" + constraintFilename;
int i = 1;
while (true) {
if (projectRepository.existConstraintSet(betterConstraintName, ProjectConstraintsPanel.this.getModelObject())) {
betterConstraintName = "copy_of_" + constraintFilename + "(" + i + ")";
i++;
}
else {
return betterConstraintName;
}
}
}
}
}
|
webanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/page/ProjectConstraintsPanel.java
|
/*******************************************************************************
* Copyright 2015
* Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology
* Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.tudarmstadt.ukp.clarin.webanno.project.page;
import static org.apache.commons.collections.CollectionUtils.isEmpty;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService;
import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ConstraintsGrammar;
import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ParseException;
import de.tudarmstadt.ukp.clarin.webanno.model.ConstraintSet;
import de.tudarmstadt.ukp.clarin.webanno.model.Project;
import de.tudarmstadt.ukp.clarin.webanno.support.EntityModel;
/**
* A Panel used to add Project Constraints Rules in a selected {@link Project}
*
*
*/
public class ProjectConstraintsPanel
extends Panel
{
private static final long serialVersionUID = 8910455936756021733L;
private static final Log LOG = LogFactory.getLog(ProjectConstraintsPanel.class);
@SpringBean(name = "documentRepository")
private RepositoryService projectRepository;
private SelectionForm selectionForm;
private DetailForm detailForm;
private ImportForm importForm;
public ProjectConstraintsPanel(String id, IModel<Project> aProjectModel)
{
super(id, aProjectModel);
add(selectionForm = new SelectionForm("selectionForm"));
add(detailForm = new DetailForm("detailForm"));
add(importForm = new ImportForm("importForm"));
}
public Project getModelObject()
{
return (Project) getDefaultModelObject();
}
public class SelectionForm
extends Form<ConstraintSet>
{
private static final long serialVersionUID = -4835473062143674510L;
public SelectionForm(String aId)
{
super(aId, Model.of((ConstraintSet) null));
LoadableDetachableModel<List<ConstraintSet>> rulesets = new LoadableDetachableModel<List<ConstraintSet>>()
{
private static final long serialVersionUID = 1L;
@Override
protected List<ConstraintSet> load()
{
return projectRepository.listConstraintSets(ProjectConstraintsPanel.this
.getModelObject());
}
};
add(new ListChoice<ConstraintSet>("ruleset", SelectionForm.this.getModel(), rulesets) {
private static final long serialVersionUID = 1L;
{
setChoiceRenderer(new ChoiceRenderer<ConstraintSet>("name"));
setNullValid(false);
}
@Override
protected void onSelectionChanged(ConstraintSet aNewSelection)
{
ProjectConstraintsPanel.this.detailForm.setModelObject(aNewSelection);
}
@Override
protected boolean wantOnSelectionChangedNotifications()
{
return true;
}
@Override
protected CharSequence getDefaultChoice(String aSelectedValue)
{
return "";
}
});
}
}
public class DetailForm
extends Form<ConstraintSet>
{
private static final long serialVersionUID = 8696334789027911595L;
private TextArea<String> script;
public DetailForm(String aId)
{
super(aId, new CompoundPropertyModel<ConstraintSet>(new EntityModel<ConstraintSet>(null)));
TextField<String> constraintNameTextField = new TextField<>("name");
add(constraintNameTextField);
add(script = new TextArea<String>("script", new LoadableDetachableModel<String>()
{
private static final long serialVersionUID = 1L;
@Override
protected String load()
{
try {
return projectRepository.readConstrainSet(DetailForm.this.getModelObject());
}
catch (IOException e) {
// Cannot call "Component.error()" here - it causes a
// org.apache.wicket.WicketRuntimeException: Cannot modify component
// hierarchy after render phase has started (page version cant change then
// anymore)
LOG.error("Unable to load script", e);
return "Unable to load script: " + ExceptionUtils.getRootCauseMessage(e);
}
}
}));
// Script not editable - if we remove this flag, then the script area will not update
// when switching set selection
script.setEnabled(false);
final IModel<String> exportFilenameModel = new Model<>();
final IModel<File> exportFileModel = new LoadableDetachableModel<File>()
{
private static final long serialVersionUID = 840863954694163375L;
@Override
protected File load()
{
try {
// Use the name of the constraints set instead of the ID under which the
// file is saved internally.
exportFilenameModel.setObject(DetailForm.this.getModelObject().getName());
return projectRepository.exportConstraintAsFile(DetailForm.this
.getModelObject());
}
catch (IOException e) {
throw new WicketRuntimeException(e);
}
}
};
add(new DownloadLink("export", exportFileModel, exportFilenameModel));
Button deleteButton = new Button("delete", new ResourceModel("label")) {
private static final long serialVersionUID = -1195565364207114557L;
@Override
public void onSubmit()
{
projectRepository.removeConstraintSet(DetailForm.this.getModelObject());
DetailForm.this.setModelObject(null);
selectionForm.setModelObject(null);
}
@Override
protected void onConfigure()
{
super.onConfigure();
setVisible(DetailForm.this.getModelObject().getId() >= 0);
}
};
// Add check to prevent accidental delete operation
deleteButton.add(new AttributeModifier("onclick",
"if(!confirm('Do you really want to delete this Constraints rule?')) return false;"));
add(deleteButton);
add(new Button("save", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
// Actually nothing to do here. Wicket will transfer the values from the
// form into the model object and Hibernate will persist it
}
@Override
public void validate() {
super.validate();
//Checking if the name provided already exists or not
if(projectRepository.existConstraintSet(constraintNameTextField.getInput(), ProjectConstraintsPanel.this.getModelObject())
&& !constraintNameTextField.getInput().equals(constraintNameTextField.getModelObject())){
error("Provided name for Constraint already exists, please choose a different name");
}
}
});
add(new Button("cancel", new ResourceModel("label")) {
private static final long serialVersionUID = 1L;
{
// Avoid saving data
setDefaultFormProcessing(false);
setVisible(true);
}
@Override
public void onSubmit()
{
DetailForm.this.setModelObject(null);
}
});
}
@Override
protected void onConfigure()
{
super.onConfigure();
setVisible(getModelObject() != null);
}
}
public class ImportForm
extends Form<Void>
{
private static final long serialVersionUID = 8121850699963791359L;
private List<FileUpload> uploads;
public ImportForm(String aId)
{
super(aId);
add(new FileUploadField("uploads", PropertyModel.<List<FileUpload>> of(this, "uploads")));
add(new Button("import", new ResourceModel("label"))
{
private static final long serialVersionUID = 1L;
@Override
public void onSubmit()
{
importAction();
}
});
}
private void importAction()
{
Project project = ProjectConstraintsPanel.this.getModelObject();
if (project.getId() == 0) {
error("Project not yet created, please save project Details!");
return;
}
if (isEmpty(uploads)) {
error("No document is selected to upload, please select a document first");
return;
}
for (FileUpload constraintRulesFile : uploads) {
// Checking if file is OK as per Constraints Grammar specification
boolean constraintRuleFileIsOK = false;
//Handling Windows BOM
// InputStreamReader utfInputStream;
BOMInputStream bomInputStream;
try {
bomInputStream = new BOMInputStream(constraintRulesFile.getInputStream(), false);
ConstraintsGrammar parser = new ConstraintsGrammar(bomInputStream);
// utfInputStream = new InputStreamReader(constraintRulesFile.getInputStream(),"UTF-8");
// ConstraintsGrammar parser = new ConstraintsGrammar(utfInputStream);
parser.Parse();
constraintRuleFileIsOK = true;
}
catch (IOException e) {
error("Unable to read constraints file "
+ ExceptionUtils.getRootCauseMessage(e));
}
catch (ParseException e) {
error("Exception while parsing the constraint rules file. Please check it"
+ ExceptionUtils.getRootCauseMessage(e));
}
// Persist rules
if (constraintRuleFileIsOK) {
try {
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.setProject(ProjectConstraintsPanel.this.getModelObject());
//Check if ConstraintSet already exists or not
String constraintFilename = constraintRulesFile.getClientFileName();
if(projectRepository.existConstraintSet(constraintFilename, project)){
constraintFilename = copyConstraintName(projectRepository,constraintFilename);
}
constraintSet.setName(constraintFilename);
projectRepository.createConstraintSet(constraintSet);
projectRepository.writeConstraintSet(constraintSet,
constraintRulesFile.getInputStream());
detailForm.setModelObject(constraintSet);
selectionForm.setModelObject(constraintSet);
}
catch (IOException e) {
detailForm.setModelObject(null);
error("Unable to write constraints file "
+ ExceptionUtils.getRootCauseMessage(e));
}
}
}
}
/**
* Checks if name exists, if yes, creates an alternate name for ConstraintSet
* @param projectRepository
* @param constraintFilename
* @return
*/
private String copyConstraintName(RepositoryService projectRepository, String constraintFilename)
{
String betterConstraintName = "copy_of_" + constraintFilename;
int i = 1;
while (true) {
if (projectRepository.existConstraintSet(betterConstraintName, ProjectConstraintsPanel.this.getModelObject())) {
betterConstraintName = "copy_of_" + constraintFilename + "(" + i + ")";
i++;
}
else {
return betterConstraintName;
}
}
}
}
}
|
#80 Errors while loading a constraint script cause internal error
Errors are caught and displayed in Feedback panel on the page while
importing.
fixes #80
|
webanno-project/src/main/java/de/tudarmstadt/ukp/clarin/webanno/project/page/ProjectConstraintsPanel.java
|
#80 Errors while loading a constraint script cause internal error
|
|
Java
|
apache-2.0
|
9b3b25fd4e3c6051252d60f64aa9cece77b46899
| 0
|
sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt,sosy-lab/java-smt
|
/*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2016 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sosy_lab.java_smt.solvers.princess;
import static com.google.common.collect.Iterables.getOnlyElement;
import static scala.collection.JavaConversions.asJavaIterable;
import static scala.collection.JavaConversions.iterableAsScalaIterable;
import static scala.collection.JavaConversions.mapAsJavaMap;
import static scala.collection.JavaConversions.seqAsJavaList;
import ap.SimpleAPI;
import ap.parser.IAtom;
import ap.parser.IConstant;
import ap.parser.IExpression;
import ap.parser.IFormula;
import ap.parser.IFunApp;
import ap.parser.IFunction;
import ap.parser.ITerm;
import ap.parser.SMTLineariser;
import ap.parser.SMTParser2InputAbsy;
import ap.parser.SMTParser2InputAbsy.SMTFunctionType;
import ap.parser.SMTParser2InputAbsy.SMTType;
import ap.terfor.ConstantTerm;
import ap.util.Debug;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.sosy_lab.common.Appender;
import org.sosy_lab.common.Appenders;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.FileOption;
import org.sosy_lab.common.configuration.FileOption.Type;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.io.PathCounterTemplate;
import scala.Tuple2;
import scala.Tuple3;
import scala.collection.Seq;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
/** This is a Wrapper around Princess.
* This Wrapper allows to set a logfile for all Smt-Queries (default "princess.###.smt2").
* It also manages the "shared variables": each variable is declared for all stacks.
*/
@Options(prefix = "solver.princess")
class PrincessEnvironment {
@Option(
secure = true,
description =
"The number of atoms a term has to have before"
+ " it gets abbreviated if there are more identical terms."
)
private int minAtomsForAbbreviation = 100;
@Option(
secure = true,
description =
"Princess needs to copy all symbols for each new prover. "
+ "This flag allows to reuse old unused provers and avoid the overhead."
)
// TODO someone should measure the overhead, perhaps it is negligible.
private boolean reuseProvers = true;
@Option(secure = true, description = "log all queries as Princess-specific Scala code")
private boolean logAllQueriesAsScala = false;
@Option(secure = true, description = "file for Princess-specific dump of queries as Scala code")
@FileOption(Type.OUTPUT_FILE)
private PathCounterTemplate logAllQueriesAsScalaFile =
PathCounterTemplate.ofFormatString("princess-query-%03d-");
/** cache for variables, because they do not implement equals() and hashCode(),
* so we need to have the same objects. */
private final Map<String, IFormula> boolVariablesCache = new HashMap<>();
private final Map<String, ITerm> intVariablesCache = new HashMap<>();
private final Map<String, ITerm> arrayVariablesCache = new HashMap<>();
private final Map<String, IFunction> functionsCache = new HashMap<>();
private final Map<IFunction, PrincessTermType> functionsReturnTypes = new HashMap<>();
private final @Nullable PathCounterTemplate basicLogfile;
private final ShutdownNotifier shutdownNotifier;
/** The wrapped API is the first created API.
* It will never be used outside of this class and never be closed.
* If a variable is declared, it is declared in the first api,
* then copied into all registered APIs. Each API has its own stack for formulas. */
private final SimpleAPI api;
private final List<PrincessAbstractProver<?, ?>> registeredProvers =
new ArrayList<>(); // where an API is used
private final List<SimpleAPI> reusableAPIs = new ArrayList<>();
private final Map<SimpleAPI, Boolean> allAPIs = new LinkedHashMap<>();
PrincessEnvironment(
Configuration config,
@Nullable final PathCounterTemplate pBasicLogfile,
ShutdownNotifier pShutdownNotifier)
throws InvalidConfigurationException {
config.inject(this);
basicLogfile = pBasicLogfile;
shutdownNotifier = pShutdownNotifier;
// this api is only used local in this environment, no need for interpolation
api = getNewApi(false);
}
/** This method returns a new prover, that is registered in this environment.
* All variables are shared in all registered APIs. */
PrincessAbstractProver<?, ?> getNewProver(
boolean useForInterpolation, PrincessFormulaManager mgr, PrincessFormulaCreator creator) {
SimpleAPI newApi = null;
if (reuseProvers) {
// shortcut if we have a reusable stack
for (Iterator<SimpleAPI> it = reusableAPIs.iterator(); it.hasNext(); ) {
newApi = it.next();
if (allAPIs.get(newApi) == useForInterpolation) {
it.remove();
break;
}
}
}
if (newApi == null) {
// if not we have to create a new one
newApi = getNewApi(useForInterpolation);
// add all symbols, that are available until now
boolVariablesCache.values().forEach(newApi::addBooleanVariable);
intVariablesCache.values().forEach(newApi::addConstant);
arrayVariablesCache.values().forEach(newApi::addConstant);
functionsCache.values().forEach(newApi::addFunction);
allAPIs.put(newApi, useForInterpolation);
}
PrincessAbstractProver<?, ?> prover;
if (useForInterpolation) {
prover = new PrincessInterpolatingProver(mgr, creator, newApi, shutdownNotifier);
} else {
prover = new PrincessTheoremProver(mgr, creator, newApi, shutdownNotifier);
}
registeredProvers.add(prover);
return prover;
}
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
private SimpleAPI getNewApi(boolean useForInterpolation) {
File directory = null;
String smtDumpBasename = null;
String scalaDumpBasename = null;
if (basicLogfile != null) {
Path logPath = basicLogfile.getFreshPath();
directory = getAbsoluteParent(logPath);
smtDumpBasename = logPath.getFileName().toString();
if (Files.getFileExtension(smtDumpBasename).equals("smt2")) {
// Princess adds .smt2 anyway
smtDumpBasename = Files.getNameWithoutExtension(smtDumpBasename);
}
smtDumpBasename += "-";
}
if (logAllQueriesAsScala && logAllQueriesAsScalaFile != null) {
Path logPath = logAllQueriesAsScalaFile.getFreshPath();
if (directory == null) {
directory = getAbsoluteParent(logPath);
}
scalaDumpBasename = logPath.getFileName().toString();
}
// We enable assertions because typically we use the "assertionless" JAR where they have no
// effect anyway, but if we use the JAR with assertions we want them to be enabled.
// The constructor parameter to SimpleAPI affects only part of the assertions.
Debug.enableAllAssertions(true);
final SimpleAPI newApi =
SimpleAPI.apply(
true, // enableAssert, see above
false, // no sanitiseNames, because variable names may contain chars like "@" and ":".
smtDumpBasename != null, // dumpSMT
smtDumpBasename, // smtDumpBasename
scalaDumpBasename != null, // dumpScala
scalaDumpBasename, // scalaDumpBasename
directory, // dumpDirectory
SimpleAPI.apply$default$8(), // tightFunctionScopes
SimpleAPI.apply$default$9() // genTotalityAxioms
);
if (useForInterpolation) {
newApi.setConstructProofs(true); // needed for interpolation
}
return newApi;
}
private File getAbsoluteParent(Path path) {
return Optional.ofNullable(path.getParent()).orElse(Paths.get(".")).toAbsolutePath().toFile();
}
int getMinAtomsForAbbreviation() {
return minAtomsForAbbreviation;
}
void unregisterStack(PrincessAbstractProver<?, ?> stack, SimpleAPI usedAPI) {
assert registeredProvers.contains(stack) : "cannot unregister stack, it is not registered";
registeredProvers.remove(stack);
if (reuseProvers) {
reusableAPIs.add(usedAPI);
} else {
allAPIs.remove(usedAPI);
}
}
void removeStack(PrincessAbstractProver<?, ?> stack, SimpleAPI usedAPI) {
assert registeredProvers.contains(stack) : "cannot remove stack, it is not registered";
registeredProvers.remove(stack);
allAPIs.remove(usedAPI);
}
public List<? extends IExpression> parseStringToTerms(String s, PrincessFormulaCreator creator) {
Tuple3<
Seq<IFormula>, scala.collection.immutable.Map<IFunction, SMTFunctionType>,
scala.collection.immutable.Map<ConstantTerm, SMTType>>
triple = api.extractSMTLIBAssertionsSymbols(new StringReader(s));
List<? extends IExpression> formula = seqAsJavaList(triple._1());
Map<IFunction, SMTFunctionType> functionTypes = mapAsJavaMap(triple._2());
Map<ConstantTerm, SMTType> constantTypes = mapAsJavaMap(triple._3());
Set<IExpression> declaredFunctions = new HashSet<>();
for (IExpression f : formula) {
declaredFunctions.addAll(creator.extractVariablesAndUFs(f, true).values());
}
for (IExpression var : declaredFunctions) {
if (var instanceof IConstant) {
SMTType type = constantTypes.get(((IConstant) var).c());
if (type instanceof SMTParser2InputAbsy.SMTArray) {
arrayVariablesCache.put(var.toString(), (ITerm) var);
} else {
intVariablesCache.put(var.toString(), (ITerm) var);
}
addSymbol((IConstant) var);
} else if (var instanceof IAtom) {
boolVariablesCache.put(((IAtom) var).pred().name(), (IFormula) var);
addSymbol((IAtom) var);
} else if (var instanceof IFunApp) {
IFunction fun = ((IFunApp) var).fun();
functionsCache.put(fun.name(), fun);
functionsReturnTypes.put(fun, convertToTermType(functionTypes.get(fun)));
addFunction(fun);
}
}
return formula;
}
private static PrincessTermType convertToTermType(SMTFunctionType type) {
SMTType resultType = type.result();
if (resultType.equals(SMTParser2InputAbsy.SMTBool$.MODULE$)) {
return PrincessTermType.Boolean;
} else {
return PrincessTermType.Integer;
}
}
public Appender dumpFormula(IFormula formula, final PrincessFormulaCreator creator) {
// remove redundant expressions
// TODO do we want to remove redundancy completely (as checked in the unit
// tests (SolverFormulaIOTest class)) or do we want to remove redundancy up
// to the point we do it for formulas that should be asserted
Tuple2<IExpression, scala.collection.immutable.Map<IExpression, IExpression>> tuple =
api.abbrevSharedExpressionsWithMap(formula, 1);
final IExpression lettedFormula = tuple._1();
final Map<IExpression, IExpression> abbrevMap = mapAsJavaMap(tuple._2());
return new Appenders.AbstractAppender() {
@Override
public void appendTo(Appendable out) throws IOException {
Set<IExpression> allVars =
new HashSet<>(creator.extractVariablesAndUFs(lettedFormula, true).values());
Deque<IExpression> declaredFunctions = new ArrayDeque<>(allVars);
Set<String> doneFunctions = new HashSet<>();
Set<String> todoAbbrevs = new HashSet<>();
while (!declaredFunctions.isEmpty()) {
IExpression var = declaredFunctions.poll();
String name = getName(var);
// we don't want to declare variables twice, so doublecheck
// if we have already found the current variable
if (doneFunctions.contains(name)) {
continue;
}
doneFunctions.add(name);
// we do only want to add declare-funs for things we really declared
// the rest is done afterwards
if (name.startsWith("abbrev_")) {
todoAbbrevs.add(name);
Set<IExpression> varsFromAbbrev =
new HashSet<>(creator.extractVariablesAndUFs(abbrevMap.get(var), true).values());
Sets.difference(varsFromAbbrev, allVars).forEach(declaredFunctions::push);
allVars.addAll(varsFromAbbrev);
} else {
out.append("(declare-fun ").append(name);
// function parameters
out.append(" (");
if (var instanceof IFunApp) {
IFunApp function = (IFunApp) var;
Iterator<ITerm> args = asJavaIterable(function.args()).iterator();
while (args.hasNext()) {
args.next();
// Princess does only support IntegerFormulas in UIFs we don't need
// to check the type here separately
if (args.hasNext()) {
out.append("Int ");
} else {
out.append("Int");
}
}
}
out.append(") ");
out.append(getType(var));
out.append(")\n");
}
}
// now as everything we know from the formula is declared we have to add
// the abbreviations, too
for (Entry<IExpression, IExpression> entry : abbrevMap.entrySet()) {
IExpression abbrev = entry.getKey();
IExpression fullFormula = entry.getValue();
String name =
getName(getOnlyElement(creator.extractVariablesAndUFs(abbrev, true).values()));
//only add the necessary abbreviations
if (!todoAbbrevs.contains(name)) {
continue;
}
out.append("(define-fun ").append(name);
// the type of each abbreviation
if (fullFormula instanceof IFormula) {
out.append(" () Bool ");
} else if (fullFormula instanceof ITerm) {
out.append(" () Int ");
}
// the abbreviated formula
out.append(SMTLineariser.asString(fullFormula)).append(" )\n");
}
// now add the final assert
out.append("(assert ").append(SMTLineariser.asString(lettedFormula)).append(')');
}
};
}
private static String getName(IExpression var) {
if (var instanceof IAtom) {
return ((IAtom) var).pred().name();
} else if (var instanceof IConstant) {
return var.toString();
} else if (var instanceof IFunApp) {
String fullStr = ((IFunApp) var).fun().toString();
return fullStr.substring(0, fullStr.indexOf('/'));
}
throw new IllegalArgumentException("The given parameter is no variable or function");
}
private static String getType(IExpression var) {
if (var instanceof IFormula) {
return "Bool";
// functions are included here, they cannot be handled separate for princess
} else if (var instanceof ITerm) {
return "Int";
}
throw new IllegalArgumentException("The given parameter is no variable or function");
}
public IExpression makeVariable(PrincessTermType type, String varname) {
switch (type) {
case Boolean:
{
if (boolVariablesCache.containsKey(varname)) {
return boolVariablesCache.get(varname);
} else {
IFormula var = api.createBooleanVariable(varname);
addSymbol(var);
boolVariablesCache.put(varname, var);
return var;
}
}
case Integer:
{
if (intVariablesCache.containsKey(varname)) {
return intVariablesCache.get(varname);
} else {
ITerm var = api.createConstant(varname);
addSymbol(var);
intVariablesCache.put(varname, var);
return var;
}
}
case Array:
{
if (arrayVariablesCache.containsKey(varname)) {
return arrayVariablesCache.get(varname);
} else {
ITerm var = api.createConstant(varname);
addSymbol(var);
arrayVariablesCache.put(varname, var);
return var;
}
}
default:
throw new AssertionError("unsupported type: " + type);
}
}
/** This function declares a new functionSymbol, that has a given number of params.
* Princess has no support for typed params, only their number is important. */
public IFunction declareFun(String name, int nofArgs, PrincessTermType returnType) {
if (functionsCache.containsKey(name)) {
assert returnType == functionsReturnTypes.get(functionsCache.get(name));
return functionsCache.get(name);
} else {
IFunction funcDecl = api.createFunction(name, nofArgs);
addFunction(funcDecl);
functionsCache.put(name, funcDecl);
functionsReturnTypes.put(funcDecl, returnType);
return funcDecl;
}
}
PrincessTermType getReturnTypeForFunction(IFunction fun) {
return functionsReturnTypes.get(fun);
}
public ITerm makeSelect(ITerm array, ITerm index) {
List<ITerm> args = ImmutableList.of(array, index);
return api.select(iterableAsScalaIterable(args).toSeq());
}
public ITerm makeStore(ITerm array, ITerm index, ITerm value) {
List<ITerm> args = ImmutableList.of(array, index, value);
return api.store(iterableAsScalaIterable(args).toSeq());
}
public boolean hasArrayType(IExpression exp) {
return arrayVariablesCache.containsValue(exp)
|| (exp instanceof IFunApp && ((IFunApp) exp).fun().toString().equals("store/3"));
}
public IFormula elimQuantifiers(IFormula formula) {
return api.simplify(formula);
}
public String getVersion() {
return "Princess (unknown version)";
}
private void addSymbol(IFormula symbol) {
for (SimpleAPI otherAPI : allAPIs.keySet()) {
otherAPI.addBooleanVariable(symbol);
}
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(symbol);
}
}
private void addSymbol(ITerm symbol) {
for (SimpleAPI otherAPI : allAPIs.keySet()) {
otherAPI.addConstant(symbol);
}
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(symbol);
}
}
private void addFunction(IFunction funcDecl) {
for (SimpleAPI otherAPI : allAPIs.keySet()) {
otherAPI.addFunction(funcDecl);
}
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(funcDecl);
}
}
}
|
src/org/sosy_lab/java_smt/solvers/princess/PrincessEnvironment.java
|
/*
* JavaSMT is an API wrapper for a collection of SMT solvers.
* This file is part of JavaSMT.
*
* Copyright (C) 2007-2016 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sosy_lab.java_smt.solvers.princess;
import static com.google.common.collect.Iterables.getOnlyElement;
import static scala.collection.JavaConversions.asJavaIterable;
import static scala.collection.JavaConversions.iterableAsScalaIterable;
import static scala.collection.JavaConversions.mapAsJavaMap;
import static scala.collection.JavaConversions.seqAsJavaList;
import ap.SimpleAPI;
import ap.parser.IAtom;
import ap.parser.IConstant;
import ap.parser.IExpression;
import ap.parser.IFormula;
import ap.parser.IFunApp;
import ap.parser.IFunction;
import ap.parser.ITerm;
import ap.parser.SMTLineariser;
import ap.parser.SMTParser2InputAbsy;
import ap.parser.SMTParser2InputAbsy.SMTFunctionType;
import ap.parser.SMTParser2InputAbsy.SMTType;
import ap.terfor.ConstantTerm;
import ap.util.Debug;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.sosy_lab.common.Appender;
import org.sosy_lab.common.Appenders;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.FileOption;
import org.sosy_lab.common.configuration.FileOption.Type;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.io.PathCounterTemplate;
import scala.Tuple2;
import scala.Tuple3;
import scala.collection.Seq;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
/** This is a Wrapper around Princess.
* This Wrapper allows to set a logfile for all Smt-Queries (default "princess.###.smt2").
* It also manages the "shared variables": each variable is declared for all stacks.
*/
@Options(prefix = "solver.princess")
class PrincessEnvironment {
@Option(
secure = true,
description =
"The number of atoms a term has to have before"
+ " it gets abbreviated if there are more identical terms."
)
private int minAtomsForAbbreviation = 100;
@Option(
secure = true,
description =
"Princess needs to copy all symbols for each new prover. "
+ "This flag allows to reuse old unused provers and avoid the overhead."
)
// TODO someone should measure the overhead, perhaps it is negligible.
private boolean reuseProvers = true;
@Option(secure = true, description = "log all queries as Princess-specific Scala code")
private boolean logAllQueriesAsScala = false;
@Option(secure = true, description = "file for Princess-specific dump of queries as Scala code")
@FileOption(Type.OUTPUT_FILE)
private PathCounterTemplate logAllQueriesAsScalaFile =
PathCounterTemplate.ofFormatString("princess-query-%03d-");
/** cache for variables, because they do not implement equals() and hashCode(),
* so we need to have the same objects. */
private final Map<String, IFormula> boolVariablesCache = new HashMap<>();
private final Map<String, ITerm> intVariablesCache = new HashMap<>();
private final Map<String, ITerm> arrayVariablesCache = new HashMap<>();
private final Map<String, IFunction> functionsCache = new HashMap<>();
private final Map<IFunction, PrincessTermType> functionsReturnTypes = new HashMap<>();
private final @Nullable PathCounterTemplate basicLogfile;
private final ShutdownNotifier shutdownNotifier;
/** The wrapped API is the first created API.
* It will never be used outside of this class and never be closed.
* If a variable is declared, it is declared in the first api,
* then copied into all registered APIs. Each API has its own stack for formulas. */
private final SimpleAPI api;
private final List<PrincessAbstractProver<?, ?>> registeredProvers =
new ArrayList<>(); // where an API is used
private final List<SimpleAPI> reusableAPIs = new ArrayList<>();
private final Map<SimpleAPI, Boolean> allAPIs = new LinkedHashMap<>();
PrincessEnvironment(
Configuration config,
@Nullable final PathCounterTemplate pBasicLogfile,
ShutdownNotifier pShutdownNotifier)
throws InvalidConfigurationException {
config.inject(this);
basicLogfile = pBasicLogfile;
shutdownNotifier = pShutdownNotifier;
// this api is only used local in this environment, no need for interpolation
api = getNewApi(false);
}
/** This method returns a new prover, that is registered in this environment.
* All variables are shared in all registered APIs. */
PrincessAbstractProver<?, ?> getNewProver(
boolean useForInterpolation, PrincessFormulaManager mgr, PrincessFormulaCreator creator) {
SimpleAPI newApi = null;
if (reuseProvers) {
// shortcut if we have a reusable stack
for (Iterator<SimpleAPI> it = reusableAPIs.iterator(); it.hasNext(); ) {
newApi = it.next();
if (allAPIs.get(newApi) == useForInterpolation) {
it.remove();
break;
}
}
}
if (newApi == null) {
// if not we have to create a new one
newApi = getNewApi(useForInterpolation);
// add all symbols, that are available until now
boolVariablesCache.values().forEach(newApi::addBooleanVariable);
intVariablesCache.values().forEach(newApi::addConstant);
arrayVariablesCache.values().forEach(newApi::addConstant);
functionsCache.values().forEach(newApi::addFunction);
allAPIs.put(newApi, useForInterpolation);
}
PrincessAbstractProver<?, ?> prover;
if (useForInterpolation) {
prover = new PrincessInterpolatingProver(mgr, creator, newApi, shutdownNotifier);
} else {
prover = new PrincessTheoremProver(mgr, creator, newApi, shutdownNotifier);
}
registeredProvers.add(prover);
return prover;
}
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
private SimpleAPI getNewApi(boolean useForInterpolation) {
File directory = null;
String smtDumpBasename = null;
String scalaDumpBasename = null;
if (basicLogfile != null) {
Path logPath = basicLogfile.getFreshPath();
directory = getAbsoluteParent(logPath);
smtDumpBasename = logPath.getFileName().toString();
if (Files.getFileExtension(smtDumpBasename).equals("smt2")) {
// Princess adds .smt2 anyway
smtDumpBasename = Files.getNameWithoutExtension(smtDumpBasename);
}
smtDumpBasename += "-";
}
if (logAllQueriesAsScala && logAllQueriesAsScalaFile != null) {
Path logPath = logAllQueriesAsScalaFile.getFreshPath();
if (directory == null) {
directory = getAbsoluteParent(logPath);
}
scalaDumpBasename = logPath.getFileName().toString();
}
// We enable assertions because typically we use the "assertionless" JAR where they have no
// effect anyway, but if we use the JAR with assertions we want them to be enabled.
// The constructor parameter to SimpleAPI affects only part of the assertions.
Debug.enableAllAssertions(true);
final SimpleAPI newApi =
SimpleAPI.apply(
true, // enableAssert, see above
false, // no sanitiseNames, because variable names may contain chars like "@" and ":".
smtDumpBasename != null, // dumpSMT
smtDumpBasename, // smtDumpBasename
scalaDumpBasename != null, // dumpScala
scalaDumpBasename, // scalaDumpBasename
directory, // dumpDirectory
SimpleAPI.apply$default$8(), // tightFunctionScopes
SimpleAPI.apply$default$9() // genTotalityAxioms
);
if (useForInterpolation) {
newApi.setConstructProofs(true); // needed for interpolation
}
return newApi;
}
private File getAbsoluteParent(Path path) {
return Optional.ofNullable(path.getParent()).orElse(Paths.get(".")).toAbsolutePath().toFile();
}
int getMinAtomsForAbbreviation() {
return minAtomsForAbbreviation;
}
void unregisterStack(PrincessAbstractProver<?, ?> stack, SimpleAPI usedAPI) {
assert registeredProvers.contains(stack) : "cannot unregister stack, it is not registered";
registeredProvers.remove(stack);
if (reuseProvers) {
reusableAPIs.add(usedAPI);
} else {
allAPIs.remove(usedAPI);
}
}
void removeStack(PrincessAbstractProver<?, ?> stack, SimpleAPI usedAPI) {
assert registeredProvers.contains(stack) : "cannot remove stack, it is not registered";
registeredProvers.remove(stack);
allAPIs.remove(usedAPI);
}
public List<? extends IExpression> parseStringToTerms(String s, PrincessFormulaCreator creator) {
Tuple3<
Seq<IFormula>, scala.collection.immutable.Map<IFunction, SMTFunctionType>,
scala.collection.immutable.Map<ConstantTerm, SMTType>>
triple = api.extractSMTLIBAssertionsSymbols(new StringReader(s));
List<? extends IExpression> formula = seqAsJavaList(triple._1());
Map<IFunction, SMTFunctionType> functionTypes = mapAsJavaMap(triple._2());
Map<ConstantTerm, SMTType> constantTypes = mapAsJavaMap(triple._3());
Set<IExpression> declaredFunctions = new HashSet<>();
for (IExpression f : formula) {
declaredFunctions.addAll(creator.extractVariablesAndUFs(f, true).values());
}
for (IExpression var : declaredFunctions) {
if (var instanceof IConstant) {
SMTType type = constantTypes.get(((IConstant) var).c());
if (type instanceof SMTParser2InputAbsy.SMTArray) {
arrayVariablesCache.put(var.toString(), (ITerm) var);
} else {
intVariablesCache.put(var.toString(), (ITerm) var);
}
addSymbol((IConstant) var);
} else if (var instanceof IAtom) {
boolVariablesCache.put(((IAtom) var).pred().name(), (IFormula) var);
addSymbol((IAtom) var);
} else if (var instanceof IFunApp) {
IFunction fun = ((IFunApp) var).fun();
functionsCache.put(fun.name(), fun);
functionsReturnTypes.put(fun, convertToTermType(functionTypes.get(fun)));
addFunction(fun);
}
}
return formula;
}
private static PrincessTermType convertToTermType(SMTFunctionType type) {
SMTType resultType = type.result();
if (resultType.equals(SMTParser2InputAbsy.SMTBool$.MODULE$)) {
return PrincessTermType.Boolean;
} else {
return PrincessTermType.Integer;
}
}
public Appender dumpFormula(IFormula formula, final PrincessFormulaCreator creator) {
// remove redundant expressions
// TODO do we want to remove redundancy completely (as checked in the unit
// tests (SolverFormulaIOTest class)) or do we want to remove redundancy up
// to the point we do it for formulas that should be asserted
Tuple2<IExpression, scala.collection.immutable.Map<IExpression, IExpression>> tuple =
api.abbrevSharedExpressionsWithMap(formula, 1);
final IExpression lettedFormula = tuple._1();
final Map<IExpression, IExpression> abbrevMap = mapAsJavaMap(tuple._2());
return new Appenders.AbstractAppender() {
@Override
public void appendTo(Appendable out) throws IOException {
Set<IExpression> allVars =
new HashSet<>(creator.extractVariablesAndUFs(lettedFormula, true).values());
Deque<IExpression> declaredFunctions = new ArrayDeque<>(allVars);
Set<String> doneFunctions = new HashSet<>();
Set<String> todoAbbrevs = new HashSet<>();
while (!declaredFunctions.isEmpty()) {
IExpression var = declaredFunctions.poll();
String name = getName(var);
// we don't want to declare variables twice, so doublecheck
// if we have already found the current variable
if (doneFunctions.contains(name)) {
continue;
}
doneFunctions.add(name);
// we do only want to add declare-funs for things we really declared
// the rest is done afterwards
if (name.startsWith("abbrev_")) {
todoAbbrevs.add(name);
Set<IExpression> varsFromAbbrev =
new HashSet<>(creator.extractVariablesAndUFs(abbrevMap.get(var), true).values());
Sets.difference(varsFromAbbrev, allVars).forEach(declaredFunctions::push);
allVars.addAll(varsFromAbbrev);
} else {
out.append("(declare-fun ").append(name);
// function parameters
out.append(" (");
if (var instanceof IFunApp) {
IFunApp function = (IFunApp) var;
Iterator<ITerm> args = asJavaIterable(function.args()).iterator();
while (args.hasNext()) {
args.next();
// Princess does only support IntegerFormulas in UIFs we don't need
// to check the type here separately
if (args.hasNext()) {
out.append("Int ");
} else {
out.append("Int");
}
}
}
out.append(") ");
out.append(getType(var));
out.append(")\n");
}
}
// now as everything we know from the formula is declared we have to add
// the abbreviations, too
for (Entry<IExpression, IExpression> entry : abbrevMap.entrySet()) {
IExpression abbrev = entry.getKey();
IExpression fullFormula = entry.getValue();
String name =
getName(getOnlyElement(creator.extractVariablesAndUFs(abbrev, true).values()));
//only add the necessary abbreviations
if (!todoAbbrevs.contains(name)) {
continue;
}
out.append("(define-fun ").append(name);
// the type of each abbreviation
if (fullFormula instanceof IFormula) {
out.append(" () Bool ");
} else if (fullFormula instanceof ITerm) {
out.append(" () Int ");
}
// the abbreviated formula
out.append(SMTLineariser.asString(fullFormula)).append(" )\n");
}
// now add the final assert
out.append("(assert ").append(SMTLineariser.asString(lettedFormula)).append(')');
}
};
}
private static String getName(IExpression var) {
if (var instanceof IAtom) {
return ((IAtom) var).pred().name();
} else if (var instanceof IConstant) {
return var.toString();
} else if (var instanceof IFunApp) {
String fullStr = ((IFunApp) var).fun().toString();
return fullStr.substring(0, fullStr.indexOf('/'));
}
throw new IllegalArgumentException("The given parameter is no variable or function");
}
private static String getType(IExpression var) {
if (var instanceof IFormula) {
return "Bool";
// functions are included here, they cannot be handled separate for princess
} else if (var instanceof ITerm) {
return "Int";
}
throw new IllegalArgumentException("The given parameter is no variable or function");
}
public IExpression makeVariable(PrincessTermType type, String varname) {
switch (type) {
case Boolean:
{
if (boolVariablesCache.containsKey(varname)) {
return boolVariablesCache.get(varname);
} else {
IFormula var = api.createBooleanVariable(varname);
addSymbol(var);
boolVariablesCache.put(varname, var);
return var;
}
}
case Integer:
{
if (intVariablesCache.containsKey(varname)) {
return intVariablesCache.get(varname);
} else {
ITerm var = api.createConstant(varname);
addSymbol(var);
intVariablesCache.put(varname, var);
return var;
}
}
case Array:
{
if (arrayVariablesCache.containsKey(varname)) {
return arrayVariablesCache.get(varname);
} else {
ITerm var = api.createConstant(varname);
addSymbol(var);
arrayVariablesCache.put(varname, var);
return var;
}
}
default:
throw new AssertionError("unsupported type: " + type);
}
}
/** This function declares a new functionSymbol, that has a given number of params.
* Princess has no support for typed params, only their number is important. */
public IFunction declareFun(String name, int nofArgs, PrincessTermType returnType) {
if (functionsCache.containsKey(name)) {
assert returnType == functionsReturnTypes.get(functionsCache.get(name));
return functionsCache.get(name);
} else {
IFunction funcDecl = api.createFunction(name, nofArgs);
addFunction(funcDecl);
functionsCache.put(name, funcDecl);
functionsReturnTypes.put(funcDecl, returnType);
return funcDecl;
}
}
PrincessTermType getReturnTypeForFunction(IFunction fun) {
return functionsReturnTypes.get(fun);
}
public ITerm makeSelect(ITerm array, ITerm index) {
List<ITerm> args = ImmutableList.of(array, index);
return api.select(iterableAsScalaIterable(args).toSeq());
}
public ITerm makeStore(ITerm array, ITerm index, ITerm value) {
List<ITerm> args = ImmutableList.of(array, index, value);
return api.store(iterableAsScalaIterable(args).toSeq());
}
public boolean hasArrayType(IExpression exp) {
return arrayVariablesCache.containsValue(exp)
|| (exp instanceof IFunApp && ((IFunApp) exp).fun().toString().equals("store/3"));
}
public IFormula elimQuantifiers(IFormula formula) {
return api.simplify(formula);
}
public String getVersion() {
return "Princess (unknown version)";
}
private void addSymbol(IFormula symbol) {
for (SimpleAPI otherAPI : allAPIs.keySet()) {
otherAPI.addBooleanVariable(symbol);
}
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(symbol);
}
}
private void addSymbol(ITerm symbol) {
for (SimpleAPI otherAPI : allAPIs.keySet()) {
otherAPI.addConstant(symbol);
}
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(symbol);
}
}
private void addFunction(IFunction funcDecl) {
for (SimpleAPI otherAPI : allAPIs.keySet()) {
otherAPI.addFunction(funcDecl);
}
for (PrincessAbstractProver<?, ?> prover : registeredProvers) {
prover.addSymbol(funcDecl);
}
}
}
|
format-source
|
src/org/sosy_lab/java_smt/solvers/princess/PrincessEnvironment.java
|
format-source
|
|
Java
|
apache-2.0
|
13a50b0be1eb4a34b83fec38f1b9a2ed3dff7f21
| 0
|
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
|
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.velocity;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.app.tools.VelocityFormatter;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.NumberTool;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContextException;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractTemplateView;
import org.springframework.web.util.NestedServletException;
/**
* View using the Velocity template engine.
*
* <p>Exposes the following JavaBean properties:
* <ul>
* <li><b>url</b>: the location of the Velocity template to be wrapped,
* relative to the Velocity resource loader path (see VelocityConfigurer).
* <li><b>encoding</b> (optional, default is determined by Velocity configuration):
* the encoding of the Velocity template file
* <li><b>velocityFormatterAttribute</b> (optional, default=null): the name of
* the VelocityFormatter helper object to expose in the Velocity context of this
* view, or <code>null</code> if not needed. VelocityFormatter is part of standard Velocity.
* <li><b>dateToolAttribute</b> (optional, default=null): the name of the
* DateTool helper object to expose in the Velocity context of this view,
* or <code>null</code> if not needed. DateTool is part of Velocity Tools 1.0.
* <li><b>numberToolAttribute</b> (optional, default=null): the name of the
* NumberTool helper object to expose in the Velocity context of this view,
* or <code>null</code> if not needed. NumberTool is part of Velocity Tools 1.1.
* <li><b>cacheTemplate</b> (optional, default=false): whether or not the Velocity
* template should be cached. It should normally be true in production, but setting
* this to false enables us to modify Velocity templates without restarting the
* application (similar to JSPs). Note that this is a minor optimization only,
* as Velocity itself caches templates in a modification-aware fashion.
* </ul>
*
* <p>Depends on a VelocityConfig object such as VelocityConfigurer being
* accessible in the current web application context, with any bean name.
* Alternatively, you can set the VelocityEngine object as bean property.
*
* <p>Note: Spring's Velocity support requires Velocity 1.3 or higher, and optionally
* Velocity Tools 1.0 or 1.1 (depending on the use of DateTool and/or NumberTool).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see VelocityConfig
* @see VelocityConfigurer
* @see #setUrl
* @see #setExposeSpringMacroHelpers
* @see #setEncoding
* @see #setVelocityEngine
* @see VelocityConfig
* @see VelocityConfigurer
*/
public class VelocityView extends AbstractTemplateView {
private Map toolAttributes;
private String velocityFormatterAttribute;
private String dateToolAttribute;
private String numberToolAttribute;
private String encoding;
private boolean cacheTemplate = false;
private VelocityEngine velocityEngine;
private Template template;
/**
* Set tool attributes to expose to the view, as attribute name / class name pairs.
* An instance of the given class will be added to the Velocity context for each
* rendering operation, under the given attribute name.
* <p>For example, an instance of MathTool, which is part of the generic package
* of Velocity Tools, can be bound under the attribute name "math", specifying the
* fully qualified class name "org.apache.velocity.tools.generic.MathTool" as value.
* <p>Note that VelocityView can only create simple generic tools or values, that is,
* classes with a public default constructor and no further initialization needs.
* This class does not do any further checks, to not introduce a required dependency
* on a specific tools package.
* <p>For tools that are part of the view package of Velocity Tools, a special
* Velocity context and a special init callback are needed. Use VelocityToolboxView
* in such a case, or override <code>createVelocityContext</code> and
* <code>initTool</code> accordingly.
* <p>For a simple VelocityFormatter instance or special locale-aware instances
* of DateTool/NumberTool, which are part of the generic package of Velocity Tools,
* specify the "velocityFormatterAttribute", "dateToolAttribute" or
* "numberToolAttribute" properties, respectively.
* @param toolAttributes attribute names as keys, and tool class names as values
* @see org.apache.velocity.tools.generic.MathTool
* @see VelocityToolboxView
* @see #createVelocityContext
* @see #initTool
* @see #setVelocityFormatterAttribute
* @see #setDateToolAttribute
* @see #setNumberToolAttribute
*/
public void setToolAttributes(Properties toolAttributes) {
this.toolAttributes = new HashMap(toolAttributes.size());
for (Enumeration attributeNames = toolAttributes.propertyNames(); attributeNames.hasMoreElements();) {
String attributeName = (String) attributeNames.nextElement();
String className = toolAttributes.getProperty(attributeName);
Class toolClass = null;
try {
toolClass = ClassUtils.forName(className);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(
"Invalid definition for tool '" + attributeName + "' - tool class not found: " + ex.getMessage());
}
this.toolAttributes.put(attributeName, toolClass);
}
}
/**
* Set the name of the VelocityFormatter helper object to expose in the
* Velocity context of this view, or <code>null</code> if not needed.
* <p>VelocityFormatter is part of the standard Velocity distribution.
* @see org.apache.velocity.app.tools.VelocityFormatter
*/
public void setVelocityFormatterAttribute(String velocityFormatterAttribute) {
this.velocityFormatterAttribute = velocityFormatterAttribute;
}
/**
* Set the name of the DateTool helper object to expose in the Velocity context
* of this view, or <code>null</code> if not needed. The exposed DateTool will be aware of
* the current locale, as determined by Spring's LocaleResolver.
* <p>DateTool is part of the generic package of Velocity Tools 1.0.
* Spring uses a special locale-aware subclass of DateTool.
* @see org.apache.velocity.tools.generic.DateTool
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
* @see org.springframework.web.servlet.LocaleResolver
*/
public void setDateToolAttribute(String dateToolAttribute) {
this.dateToolAttribute = dateToolAttribute;
}
/**
* Set the name of the NumberTool helper object to expose in the Velocity context
* of this view, or <code>null</code> if not needed. The exposed NumberTool will be aware of
* the current locale, as determined by Spring's LocaleResolver.
* <p>NumberTool is part of the generic package of Velocity Tools 1.1.
* Spring uses a special locale-aware subclass of NumberTool.
* @see org.apache.velocity.tools.generic.NumberTool
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
* @see org.springframework.web.servlet.LocaleResolver
*/
public void setNumberToolAttribute(String numberToolAttribute) {
this.numberToolAttribute = numberToolAttribute;
}
/**
* Set the encoding of the Velocity template file. Default is determined
* by the VelocityEngine: "ISO-8859-1" if not specified otherwise.
* <p>Specify the encoding in the VelocityEngine rather than per template
* if all your templates share a common encoding.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Return the encoding for the Velocity template.
*/
protected String getEncoding() {
return encoding;
}
/**
* Set whether the Velocity template should be cached. Default is "false".
* It should normally be true in production, but setting this to false enables us to
* modify Velocity templates without restarting the application (similar to JSPs).
* <p>Note that this is a minor optimization only, as Velocity itself caches
* templates in a modification-aware fashion.
*/
public void setCacheTemplate(boolean cacheTemplate) {
this.cacheTemplate = cacheTemplate;
}
/**
* Return whether the Velocity template should be cached.
*/
protected boolean isCacheTemplate() {
return cacheTemplate;
}
/**
* Set the VelocityEngine to be used by this view.
* If this is not set, the default lookup will occur: A single VelocityConfig
* is expected in the current web application context, with any bean name.
* @see VelocityConfig
*/
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
/**
* Return the VelocityEngine used by this view.
*/
protected VelocityEngine getVelocityEngine() {
return velocityEngine;
}
/**
* Invoked on startup. Looks for a single VelocityConfig bean to
* find the relevant VelocityEngine for this factory.
*/
protected void initApplicationContext() throws BeansException {
super.initApplicationContext();
if (getVelocityEngine() == null) {
// No explicit VelocityEngine: try to autodetect one.
setVelocityEngine(autodetectVelocityEngine());
}
checkTemplate();
}
/**
* Autodetect a VelocityEngine via the ApplicationContext.
* Called if no explicit VelocityEngine has been specified.
* @return the VelocityEngine to use for VelocityViews
* @throws BeansException if no VelocityEngine could be found
* @see #getApplicationContext
* @see #setVelocityEngine
*/
protected VelocityEngine autodetectVelocityEngine() throws BeansException {
try {
VelocityConfig velocityConfig = (VelocityConfig)
BeanFactoryUtils.beanOfTypeIncludingAncestors(
getApplicationContext(), VelocityConfig.class, true, false);
return velocityConfig.getVelocityEngine();
}
catch (NoSuchBeanDefinitionException ex) {
throw new ApplicationContextException(
"Must define a single VelocityConfig bean in this web application context " +
"(may be inherited): VelocityConfigurer is the usual implementation. " +
"This bean may be given any name.", ex);
}
}
/**
* Check that the Velocity template used for this view exists and is valid.
* <p>Can be overridden to customize the behavior, for example in case of
* multiple templates to be rendered into a single view.
* @throws ApplicationContextException if the template cannot be found or is invalid
*/
protected void checkTemplate() throws ApplicationContextException {
try {
// Check that we can get the template, even if we might subsequently get it again.
this.template = getTemplate();
}
catch (ResourceNotFoundException ex) {
throw new ApplicationContextException("Cannot find Velocity template for URL [" + getUrl() +
"]: Did you specify the correct resource loader path?", ex);
}
catch (Exception ex) {
throw new ApplicationContextException(
"Could not load Velocity template for URL [" + getUrl() + "]", ex);
}
}
/**
* Process the model map by merging it with the Velocity template.
* Output is directed to the servlet response.
* <p>This method can be overridden if custom behavior is needed.
*/
protected void renderMergedTemplateModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
exposeHelpers(model, request);
// create Velocity Context from model
Context velocityContext = createVelocityContext(model, request, response);
exposeHelpers(velocityContext, request, response);
exposeToolAttributes(velocityContext, request);
doRender(velocityContext, response);
}
/**
* Expose helpers unique to each rendering operation. This is necessary so that
* different rendering operations can't overwrite each other's formats etc.
* <p>Called by <code>renderMergedTemplateModel</code>. The default implementation
* is empty. This method can be overridden to add custom helpers to the model.
* @param model the model that will be passed to the template for merging
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #renderMergedTemplateModel
*/
protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
}
/**
* Create a Velocity Context instance for the given model,
* to be passed to the template for merging.
* <p>Default implementation delegates to <code>createVelocityContext(model)</code>.
* Can be overridden for a special context class, for example ChainedContext which
* is part of the view package of Velocity Tools. ChainedContext is needed for
* initialization of ViewTool instances.
* <p>Have a look at VelocityToolboxView, which pre-implements such a ViewTool
* check. This is not part of the standard VelocityView class to avoid a
* required dependency on the view package of Velocity Tools.
* @param model the model Map, containing the model attributes
* to be exposed to the view
* @param request current HTTP request
* @param response current HTTP response
* @return the Velocity Context
* @throws Exception if there's a fatal error while creating the context
* @see #createVelocityContext(Map)
* @see org.apache.velocity.tools.view.context.ChainedContext
* @see org.apache.velocity.tools.view.tools.ViewTool
* @see #initTool
* @see VelocityToolboxView
*/
protected Context createVelocityContext(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
return createVelocityContext(model);
}
/**
* Create a Velocity Context instance for the given model,
* to be passed to the template for merging.
* <p>Default implementation creates an instance of Velocity's
* VelocityContext implementation class.
* @param model the model Map, containing the model attributes
* to be exposed to the view
* @return the Velocity Context
* @throws Exception if there's a fatal error while creating the context
* @see org.apache.velocity.VelocityContext
*/
protected Context createVelocityContext(Map model) throws Exception {
return new VelocityContext(model);
}
/**
* Expose helpers unique to each rendering operation. This is necessary so that
* different rendering operations can't overwrite each other's formats etc.
* <p>Called by <code>renderMergedTemplateModel</code>. Default implementation
* delegates to <code>exposeHelpers(velocityContext, request)</code>. This method
* can be overridden to add special tools to the context, needing the servlet response
* to initialize (see Velocity Tools, for example LinkTool and ViewTool/ChainedContext).
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest)
*/
protected void exposeHelpers(
Context velocityContext, HttpServletRequest request, HttpServletResponse response) throws Exception {
exposeHelpers(velocityContext, request);
}
/**
* Expose helpers unique to each rendering operation. This is necessary so that
* different rendering operations can't overwrite each other's formats etc.
* <p>Default implementation is empty. This method can be overridden to add
* custom helpers to the Velocity context.
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #exposeHelpers(Map, HttpServletRequest)
*/
protected void exposeHelpers(Context velocityContext, HttpServletRequest request) throws Exception {
}
/**
* Expose the tool attributes, according to corresponding bean property settings.
* <p>Do not override this method unless for further tools driven by bean properties.
* Override one of the <code>exposeHelpers</code> methods to add custom helpers.
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #setVelocityFormatterAttribute
* @see #setDateToolAttribute
* @see #setNumberToolAttribute
* @see #exposeHelpers(Map, HttpServletRequest)
* @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)
*/
protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
// expose generic attributes
if (this.toolAttributes != null) {
for (Iterator it = this.toolAttributes.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String attributeName = (String) entry.getKey();
Class toolClass = (Class) entry.getValue();
try {
Object tool = toolClass.newInstance();
initTool(tool, velocityContext);
velocityContext.put(attributeName, tool);
}
catch (Exception ex) {
throw new NestedServletException(
"Could not instantiate Velocity tool '" + attributeName + "': " + ex.getMessage(), ex);
}
}
}
// expose VelocityFormatter attribute
if (this.velocityFormatterAttribute != null) {
velocityContext.put(this.velocityFormatterAttribute, new VelocityFormatter(velocityContext));
}
// expose locale-aware DateTool/NumberTool attributes
if (this.dateToolAttribute != null || this.numberToolAttribute != null) {
Locale locale = RequestContextUtils.getLocale(request);
if (this.dateToolAttribute != null) {
velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(locale));
}
if (this.numberToolAttribute != null) {
velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(locale));
}
}
}
/**
* Initialize the given tool instance. The default implementation is empty.
* <p>Can be overridden to check for special callback interfaces, for example
* the ViewContext interface which is part of the view package of Velocity Tools.
* In the particular case of ViewContext, you'll usually also need a special
* Velocity context, like ChainedContext which is part of Velocity Tools too.
* <p>Have a look at VelocityToolboxView, which pre-implements such a ViewTool
* check. This is not part of the standard VelocityView class to avoid a
* required dependency on the view package of Velocity Tools.
* @param tool the tool instance to initialize
* @param velocityContext the Velocity context
* @throws Exception if initializion of the tool failed
* @see org.apache.velocity.tools.view.tools.ViewTool
* @see org.apache.velocity.tools.view.context.ChainedContext
* @see #createVelocityContext
* @see VelocityToolboxView
*/
protected void initTool(Object tool, Context velocityContext) throws Exception {
}
/**
* Render the Velocity view to the given response, using the given Velocity
* context which contains the complete template model to use.
* <p>The default implementation renders the template specified by the "url"
* bean property, retrieved via <code>getTemplate</code>. It delegates to the
* <code>mergeTemplate</code> method to merge the template instance with the
* given Velocity context.
* <p>Can be overridden to customize the behavior, for example to render
* multiple templates into a single view.
* @param context the Velocity context to use for rendering
* @param response servlet response (use this to get the OutputStream or Writer)
* @throws Exception if thrown by Velocity
* @see #setUrl
* @see #getTemplate()
* @see #mergeTemplate
*/
protected void doRender(Context context, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Rendering Velocity template [" + getUrl() + "] in VelocityView '" + getBeanName() + "'");
}
mergeTemplate(getTemplate(), context, response);
}
/**
* Retrieve the Velocity template to be rendered by this view.
* <p>By default, the template specified by the "url" bean property will be
* retrieved: either returning a cached template instance or loading a fresh
* instance (according to the "cacheTemplate" bean property)
* @return the Velocity template to render
* @throws Exception if thrown by Velocity
* @see #setUrl
* @see #setCacheTemplate
* @see #getTemplate(String)
*/
protected Template getTemplate() throws Exception {
// We already hold a reference to the template, but we might want to load it
// if not caching. Velocity itself caches templates, so our ability to
// cache templates in this class is a minor optimization only.
if (isCacheTemplate() && this.template != null) {
return this.template;
}
else {
return getTemplate(getUrl());
}
}
/**
* Retrieve the Velocity template specified by the given name,
* using the encoding specified by the "encoding" bean property.
* <p>Can be called by subclasses to retrieve a specific template,
* for example to render multiple templates into a single view.
* @param name the file name of the desired template
* @return the Velocity template
* @throws Exception if thrown by Velocity
* @see org.apache.velocity.app.VelocityEngine#getTemplate
*/
protected Template getTemplate(String name) throws Exception {
return (getEncoding() != null ?
getVelocityEngine().getTemplate(name, getEncoding()) :
getVelocityEngine().getTemplate(name));
}
/**
* Merge the template with the context.
* Can be overridden to customize the behavior.
* @param template the template to merge
* @param context the Velocity context to use for rendering
* @param response servlet response (use this to get the OutputStream or Writer)
* @throws Exception if thrown by Velocity
* @see org.apache.velocity.Template#merge
*/
protected void mergeTemplate(
Template template, Context context, HttpServletResponse response) throws Exception {
try {
template.merge(context, response.getWriter());
}
catch (MethodInvocationException ex) {
throw new NestedServletException(
"Method invocation failed during rendering of Velocity view with name '" +
getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
"], method '" + ex.getMethodName() + "'",
ex.getWrappedThrowable());
}
}
/**
* Subclass of DateTool from Velocity Tools, using a passed-in Locale
* (usually the RequestContext Locale) instead of the default Locale.N
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
*/
private static class LocaleAwareDateTool extends DateTool {
private final Locale locale;
private LocaleAwareDateTool(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
}
/**
* Subclass of NumberTool from Velocity Tools, using a passed-in Locale
* (usually the RequestContext Locale) instead of the default Locale.
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
*/
private static class LocaleAwareNumberTool extends NumberTool {
private final Locale locale;
private LocaleAwareNumberTool(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
}
}
|
src/org/springframework/web/servlet/view/velocity/VelocityView.java
|
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.velocity;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.app.tools.VelocityFormatter;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.NumberTool;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContextException;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractTemplateView;
import org.springframework.web.util.NestedServletException;
/**
* View using the Velocity template engine.
*
* <p>Exposes the following JavaBean properties:
* <ul>
* <li><b>url</b>: the location of the Velocity template to be wrapped,
* relative to the Velocity resource loader path (see VelocityConfigurer).
* <li><b>encoding</b> (optional, default is determined by Velocity configuration):
* the encoding of the Velocity template file
* <li><b>velocityFormatterAttribute</b> (optional, default=null): the name of
* the VelocityFormatter helper object to expose in the Velocity context of this
* view, or <code>null</code> if not needed. VelocityFormatter is part of standard Velocity.
* <li><b>dateToolAttribute</b> (optional, default=null): the name of the
* DateTool helper object to expose in the Velocity context of this view,
* or <code>null</code> if not needed. DateTool is part of Velocity Tools 1.0.
* <li><b>numberToolAttribute</b> (optional, default=null): the name of the
* NumberTool helper object to expose in the Velocity context of this view,
* or <code>null</code> if not needed. NumberTool is part of Velocity Tools 1.1.
* <li><b>cacheTemplate</b> (optional, default=false): whether or not the Velocity
* template should be cached. It should normally be true in production, but setting
* this to false enables us to modify Velocity templates without restarting the
* application (similar to JSPs). Note that this is a minor optimization only,
* as Velocity itself caches templates in a modification-aware fashion.
* </ul>
*
* <p>Depends on a VelocityConfig object such as VelocityConfigurer being
* accessible in the current web application context, with any bean name.
* Alternatively, you can set the VelocityEngine object as bean property.
*
* <p>Note: Spring's Velocity support requires Velocity 1.3 or higher, and optionally
* Velocity Tools 1.0 or 1.1 (depending on the use of DateTool and/or NumberTool).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see VelocityConfig
* @see VelocityConfigurer
* @see #setUrl
* @see #setExposeSpringMacroHelpers
* @see #setEncoding
* @see #setVelocityEngine
* @see VelocityConfig
* @see VelocityConfigurer
*/
public class VelocityView extends AbstractTemplateView {
private Map toolAttributes;
private String velocityFormatterAttribute;
private String dateToolAttribute;
private String numberToolAttribute;
private String encoding;
private boolean cacheTemplate = false;
private VelocityEngine velocityEngine;
private Template template;
/**
* Set tool attributes to expose to the view, as attribute name / class name pairs.
* An instance of the given class will be added to the Velocity context for each
* rendering operation, under the given attribute name.
* <p>For example, an instance of MathTool, which is part of the generic package
* of Velocity Tools, can be bound under the attribute name "math", specifying the
* fully qualified class name "org.apache.velocity.tools.generic.MathTool" as value.
* <p>Note that VelocityView can only create simple generic tools or values, that is,
* classes with a public default constructor and no further initialization needs.
* This class does not do any further checks, to not introduce a required dependency
* on a specific tools package.
* <p>For tools that are part of the view package of Velocity Tools, a special
* Velocity context and a special init callback are needed. Use VelocityToolboxView
* in such a case, or override <code>createVelocityContext</code> and
* <code>initTool</code> accordingly.
* <p>For a simple VelocityFormatter instance or special locale-aware instances
* of DateTool/NumberTool, which are part of the generic package of Velocity Tools,
* specify the "velocityFormatterAttribute", "dateToolAttribute" or
* "numberToolAttribute" properties, respectively.
* @param toolAttributes attribute names as keys, and tool class names as values
* @see org.apache.velocity.tools.generic.MathTool
* @see VelocityToolboxView
* @see #createVelocityContext
* @see #initTool
* @see #setVelocityFormatterAttribute
* @see #setDateToolAttribute
* @see #setNumberToolAttribute
*/
public void setToolAttributes(Properties toolAttributes) {
this.toolAttributes = new HashMap(toolAttributes.size());
for (Enumeration attributeNames = toolAttributes.propertyNames(); attributeNames.hasMoreElements();) {
String attributeName = (String) attributeNames.nextElement();
String className = toolAttributes.getProperty(attributeName);
Class toolClass = null;
try {
toolClass = ClassUtils.forName(className);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(
"Invalid definition for tool '" + attributeName + "' - tool class not found: " + ex.getMessage());
}
this.toolAttributes.put(attributeName, toolClass);
}
}
/**
* Set the name of the VelocityFormatter helper object to expose in the
* Velocity context of this view, or <code>null</code> if not needed.
* <p>VelocityFormatter is part of the standard Velocity distribution.
* @see org.apache.velocity.app.tools.VelocityFormatter
*/
public void setVelocityFormatterAttribute(String velocityFormatterAttribute) {
this.velocityFormatterAttribute = velocityFormatterAttribute;
}
/**
* Set the name of the DateTool helper object to expose in the Velocity context
* of this view, or <code>null</code> if not needed. The exposed DateTool will be aware of
* the current locale, as determined by Spring's LocaleResolver.
* <p>DateTool is part of the generic package of Velocity Tools 1.0.
* Spring uses a special locale-aware subclass of DateTool.
* @see org.apache.velocity.tools.generic.DateTool
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
* @see org.springframework.web.servlet.LocaleResolver
*/
public void setDateToolAttribute(String dateToolAttribute) {
this.dateToolAttribute = dateToolAttribute;
}
/**
* Set the name of the NumberTool helper object to expose in the Velocity context
* of this view, or <code>null</code> if not needed. The exposed NumberTool will be aware of
* the current locale, as determined by Spring's LocaleResolver.
* <p>NumberTool is part of the generic package of Velocity Tools 1.1.
* Spring uses a special locale-aware subclass of NumberTool.
* @see org.apache.velocity.tools.generic.NumberTool
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
* @see org.springframework.web.servlet.LocaleResolver
*/
public void setNumberToolAttribute(String numberToolAttribute) {
this.numberToolAttribute = numberToolAttribute;
}
/**
* Set the encoding of the Velocity template file. Default is determined
* by the VelocityEngine: "ISO-8859-1" if not specified otherwise.
* <p>Specify the encoding in the VelocityEngine rather than per template
* if all your templates share a common encoding.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Return the encoding for the Velocity template.
*/
protected String getEncoding() {
return encoding;
}
/**
* Set whether the Velocity template should be cached. Default is "false".
* It should normally be true in production, but setting this to false enables us to
* modify Velocity templates without restarting the application (similar to JSPs).
* <p>Note that this is a minor optimization only, as Velocity itself caches
* templates in a modification-aware fashion.
*/
public void setCacheTemplate(boolean cacheTemplate) {
this.cacheTemplate = cacheTemplate;
}
/**
* Return whether the Velocity template should be cached.
*/
protected boolean isCacheTemplate() {
return cacheTemplate;
}
/**
* Set the VelocityEngine to be used by this view.
* If this is not set, the default lookup will occur: A single VelocityConfig
* is expected in the current web application context, with any bean name.
* @see VelocityConfig
*/
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
/**
* Return the VelocityEngine used by this view.
*/
protected VelocityEngine getVelocityEngine() {
return velocityEngine;
}
/**
* Invoked on startup. Looks for a single VelocityConfig bean to
* find the relevant VelocityEngine for this factory.
*/
protected void initApplicationContext() throws BeansException {
super.initApplicationContext();
if (getVelocityEngine() == null) {
// No explicit VelocityEngine: try to autodetect one.
setVelocityEngine(autodetectVelocityEngine());
}
checkTemplate();
}
/**
* Autodetect a VelocityEngine via the ApplicationContext.
* Called if no explicit VelocityEngine has been specified.
* @return the VelocityEngine to use for VelocityViews
* @throws BeansException if no VelocityEngine could be found
* @see #getApplicationContext
* @see #setVelocityEngine
*/
protected VelocityEngine autodetectVelocityEngine() throws BeansException {
try {
VelocityConfig velocityConfig = (VelocityConfig)
BeanFactoryUtils.beanOfTypeIncludingAncestors(
getApplicationContext(), VelocityConfig.class, true, false);
return velocityConfig.getVelocityEngine();
}
catch (NoSuchBeanDefinitionException ex) {
throw new ApplicationContextException(
"Must define a single VelocityConfig bean in this web application context " +
"(may be inherited): VelocityConfigurer is the usual implementation. " +
"This bean may be given any name.", ex);
}
}
/**
* Check that the Velocity template used for this view exists and is valid.
* <p>Can be overridden to customize the behavior, for example in case of
* multiple templates to be rendered into a single view.
* @throws ApplicationContextException if the template cannot be found or is invalid
*/
protected void checkTemplate() throws ApplicationContextException {
try {
// Check that we can get the template, even if we might subsequently get it again.
this.template = getTemplate();
}
catch (ResourceNotFoundException ex) {
throw new ApplicationContextException("Cannot find Velocity template for URL [" + getUrl() +
"]: Did you specify the correct resource loader path?", ex);
}
catch (Exception ex) {
throw new ApplicationContextException(
"Could not load Velocity template for URL [" + getUrl() + "]", ex);
}
}
/**
* Process the model map by merging it with the Velocity template.
* Output is directed to the servlet response.
* <p>This method can be overridden if custom behavior is needed.
*/
protected void renderMergedTemplateModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
exposeHelpers(model, request);
// create Velocity Context from model
Context velocityContext = createVelocityContext(model, request, response);
exposeHelpers(velocityContext, request, response);
exposeToolAttributes(velocityContext, request);
doRender(velocityContext, response);
}
/**
* Expose helpers unique to each rendering operation. This is necessary so that
* different rendering operations can't overwrite each other's formats etc.
* <p>Called by <code>renderMergedTemplateModel</code>. The default implementation
* is empty. This method can be overridden to add custom helpers to the model.
* @param model the model that will be passed to the template for merging
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #renderMergedTemplateModel
*/
protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
}
/**
* Create a Velocity Context instance for the given model,
* to be passed to the template for merging.
* <p>Default implementation delegates to <code>createVelocityContext(model)</code>.
* Can be overridden for a special context class, for example ChainedContext which
* is part of the view package of Velocity Tools. ChainedContext is needed for
* initialization of ViewTool instances.
* <p>Have a look at VelocityToolboxView, which pre-implements such a ViewTool
* check. This is not part of the standard VelocityView class to avoid a
* required dependency on the view package of Velocity Tools.
* @param model the model Map, containing the model attributes
* to be exposed to the view
* @param request current HTTP request
* @param response current HTTP response
* @return the Velocity Context
* @throws Exception if there's a fatal error while creating the context
* @see #createVelocityContext(Map)
* @see org.apache.velocity.tools.view.context.ChainedContext
* @see org.apache.velocity.tools.view.tools.ViewTool
* @see #initTool
* @see VelocityToolboxView
*/
protected Context createVelocityContext(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
return createVelocityContext(model);
}
/**
* Create a Velocity Context instance for the given model,
* to be passed to the template for merging.
* <p>Default implementation creates an instance of Velocity's
* VelocityContext implementation class.
* @param model the model Map, containing the model attributes
* to be exposed to the view
* @return the Velocity Context
* @throws Exception if there's a fatal error while creating the context
* @see org.apache.velocity.VelocityContext
*/
protected Context createVelocityContext(Map model) throws Exception {
return new VelocityContext(model);
}
/**
* Expose helpers unique to each rendering operation. This is necessary so that
* different rendering operations can't overwrite each other's formats etc.
* <p>Called by <code>renderMergedTemplateModel</code>. Default implementation
* delegates to <code>exposeHelpers(velocityContext, request)</code>. This method
* can be overridden to add special tools to the context, needing the servlet response
* to initialize (see Velocity Tools, for example LinkTool and ViewTool/ChainedContext).
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest)
*/
protected void exposeHelpers(Context velocityContext, HttpServletRequest request, HttpServletResponse response)
throws Exception {
exposeHelpers(velocityContext, request);
}
/**
* Expose helpers unique to each rendering operation. This is necessary so that
* different rendering operations can't overwrite each other's formats etc.
* <p>Default implementation is empty. This method can be overridden to add
* custom helpers to the Velocity context.
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #exposeHelpers(Map, HttpServletRequest)
*/
protected void exposeHelpers(Context velocityContext, HttpServletRequest request) throws Exception {
}
/**
* Expose the tool attributes, according to corresponding bean property settings.
* <p>Do not override this method unless for further tools driven by bean properties.
* Override one of the <code>exposeHelpers</code> methods to add custom helpers.
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #setVelocityFormatterAttribute
* @see #setDateToolAttribute
* @see #setNumberToolAttribute
* @see #exposeHelpers(Map, HttpServletRequest)
* @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)
*/
protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
// expose generic attributes
if (this.toolAttributes != null) {
for (Iterator it = this.toolAttributes.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String attributeName = (String) entry.getKey();
Class toolClass = (Class) entry.getValue();
try {
Object tool = toolClass.newInstance();
initTool(tool, velocityContext);
velocityContext.put(attributeName, tool);
}
catch (Exception ex) {
throw new NestedServletException(
"Could not instantiate Velocity tool '" + attributeName + "': " + ex.getMessage(), ex);
}
}
}
// expose VelocityFormatter attribute
if (this.velocityFormatterAttribute != null) {
velocityContext.put(this.velocityFormatterAttribute, new VelocityFormatter(velocityContext));
}
// expose locale-aware DateTool/NumberTool attributes
if (this.dateToolAttribute != null || this.numberToolAttribute != null) {
Locale locale = RequestContextUtils.getLocale(request);
if (this.dateToolAttribute != null) {
velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(locale));
}
if (this.numberToolAttribute != null) {
velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(locale));
}
}
}
/**
* Initialize the given tool instance. The default implementation is empty.
* <p>Can be overridden to check for special callback interfaces, for example
* the ViewContext interface which is part of the view package of Velocity Tools.
* In the particular case of ViewContext, you'll usually also need a special
* Velocity context, like ChainedContext which is part of Velocity Tools too.
* <p>Have a look at VelocityToolboxView, which pre-implements such a ViewTool
* check. This is not part of the standard VelocityView class to avoid a
* required dependency on the view package of Velocity Tools.
* @param tool the tool instance to initialize
* @param velocityContext the Velocity context
* @throws Exception if initializion of the tool failed
* @see org.apache.velocity.tools.view.tools.ViewTool
* @see org.apache.velocity.tools.view.context.ChainedContext
* @see #createVelocityContext
* @see VelocityToolboxView
*/
protected void initTool(Object tool, Context velocityContext) throws Exception {
}
/**
* Render the Velocity view to the given response, using the given Velocity
* context which contains the complete template model to use.
* <p>The default implementation renders the template specified by the "url"
* bean property, retrieved via <code>getTemplate</code>. It delegates to the
* <code>mergeTemplate</code> method to merge the template instance with the
* given Velocity context.
* <p>Can be overridden to customize the behavior, for example to render
* multiple templates into a single view.
* @param context the Velocity context to use for rendering
* @param response servlet response (use this to get the OutputStream or Writer)
* @throws Exception if thrown by Velocity
* @see #setUrl
* @see #getTemplate()
* @see #mergeTemplate
*/
protected void doRender(Context context, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Rendering Velocity template [" + getUrl() + "] in VelocityView '" + getBeanName() + "'");
}
mergeTemplate(getTemplate(), context, response);
}
/**
* Retrieve the Velocity template to be rendered by this view.
* <p>By default, the template specified by the "url" bean property will be
* retrieved: either returning a cached template instance or loading a fresh
* instance (according to the "cacheTemplate" bean property)
* @return the Velocity template to render
* @throws Exception if thrown by Velocity
* @see #setUrl
* @see #setCacheTemplate
* @see #getTemplate(String)
*/
protected Template getTemplate() throws Exception {
// We already hold a reference to the template, but we might want to load it
// if not caching. Velocity itself caches templates, so our ability to
// cache templates in this class is a minor optimization only.
if (isCacheTemplate() && this.template != null) {
return this.template;
}
else {
return getTemplate(getUrl());
}
}
/**
* Retrieve the Velocity template specified by the given name,
* using the encoding specified by the "encoding" bean property.
* <p>Can be called by subclasses to retrieve a specific template,
* for example to render multiple templates into a single view.
* @param name the file name of the desired template
* @return the Velocity template
* @throws Exception if thrown by Velocity
* @see org.apache.velocity.app.VelocityEngine#getTemplate
*/
protected Template getTemplate(String name) throws Exception {
return (getEncoding() != null ?
getVelocityEngine().getTemplate(name, getEncoding()) :
getVelocityEngine().getTemplate(name));
}
/**
* Merge the template with the context.
* Can be overridden to customize the behavior.
* @param template the template to merge
* @param context the Velocity context to use for rendering
* @param response servlet response (use this to get the OutputStream or Writer)
* @throws Exception if thrown by Velocity
* @see org.apache.velocity.Template#merge
*/
protected void mergeTemplate(Template template, Context context, HttpServletResponse response)
throws Exception {
template.merge(context, response.getWriter());
}
/**
* Subclass of DateTool from Velocity Tools, using a passed-in Locale
* (usually the RequestContext Locale) instead of the default Locale.N
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
*/
private static class LocaleAwareDateTool extends DateTool {
private final Locale locale;
private LocaleAwareDateTool(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
}
/**
* Subclass of NumberTool from Velocity Tools, using a passed-in Locale
* (usually the RequestContext Locale) instead of the default Locale.
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
*/
private static class LocaleAwareNumberTool extends NumberTool {
private final Locale locale;
private LocaleAwareNumberTool(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
}
}
|
convert Velocity's MethodInvocationException to a Spring NestedServletException with original root cause
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@8386 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
|
src/org/springframework/web/servlet/view/velocity/VelocityView.java
|
convert Velocity's MethodInvocationException to a Spring NestedServletException with original root cause
|
|
Java
|
apache-2.0
|
a5d1a507564df7e50be02e7640ccf2ae177bf9fb
| 0
|
Pardus-Engerek/engerek,rpudil/midpoint,arnost-starosta/midpoint,PetrGasparik/midpoint,Pardus-Engerek/engerek,gureronder/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,rpudil/midpoint,PetrGasparik/midpoint,Pardus-Engerek/engerek,PetrGasparik/midpoint,PetrGasparik/midpoint,gureronder/midpoint,rpudil/midpoint,arnost-starosta/midpoint,gureronder/midpoint,arnost-starosta/midpoint,rpudil/midpoint,gureronder/midpoint,Pardus-Engerek/engerek
|
/*
* Copyright (c) 2010-2014 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.prism;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import org.apache.commons.lang.StringUtils;
/**
* Abstract item definition in the schema.
*
* This is supposed to be a superclass for all item definitions. Items are things
* that can appear in property containers, which generally means only a property
* and property container itself. Therefore this is in fact superclass for those
* two definitions.
*
* The definitions represent data structures of the schema. Therefore instances
* of Java objects from this class represent specific <em>definitions</em> from
* the schema, not specific properties or objects. E.g the definitions does not
* have any value.
*
* To transform definition to a real property or object use the explicit
* instantiate() methods provided in the definition classes. E.g. the
* instantiate() method will create instance of Property using appropriate
* PropertyDefinition.
*
* The convenience methods in Schema are using this abstract class to find
* appropriate definitions easily.
*
* @author Radovan Semancik
*
*/
public abstract class ItemDefinition extends Definition implements Serializable {
private static final long serialVersionUID = -2643332934312107274L;
protected QName name;
private int minOccurs = 1;
private int maxOccurs = 1;
private boolean operational = false;
private boolean dynamic;
private boolean canAdd = true;
private boolean canRead = true;
private boolean canModify = true;
private PrismReferenceValue valueEnumerationRef;
// TODO: annotations
/**
* The constructors should be used only occasionally (if used at all).
* Use the factory methods in the ResourceObjectDefintion instead.
*
* @param name definition name (element Name)
* @param defaultName default element name
* @param typeName type name (XSD complex or simple type)
*/
ItemDefinition(QName elementName, QName typeName, PrismContext prismContext) {
super(typeName, prismContext);
this.name = elementName;
}
/**
* Returns name of the defined entity.
*
* The name is a name of the entity instance if it is fixed by the schema.
* E.g. it may be a name of the property in the container that cannot be
* changed.
*
* The name corresponds to the XML element name in the XML representation of
* the schema. It does NOT correspond to a XSD type name.
*
* Name is optional. If name is not set the null value is returned. If name is
* not set the type is "abstract", does not correspond to the element.
*
* @return the name name of the entity or null.
*/
public QName getName() {
return name;
}
public void setName(QName name) {
this.name = name;
}
public String getNamespace() {
return getName().getNamespaceURI();
}
/**
* Return the number of minimal value occurrences.
*
* @return the minOccurs
*/
public int getMinOccurs() {
return minOccurs;
}
public void setMinOccurs(int minOccurs) {
this.minOccurs = minOccurs;
}
/**
* Return the number of maximal value occurrences.
* <p/>
* Any negative number means "unbounded".
*
* @return the maxOccurs
*/
public int getMaxOccurs() {
return maxOccurs;
}
public void setMaxOccurs(int maxOccurs) {
this.maxOccurs = maxOccurs;
}
/**
* Returns true if property is single-valued.
*
* @return true if property is single-valued.
*/
public boolean isSingleValue() {
int maxOccurs = getMaxOccurs();
return maxOccurs >= 0 && maxOccurs <= 1;
}
/**
* Returns true if property is multi-valued.
*
* @return true if property is multi-valued.
*/
public boolean isMultiValue() {
int maxOccurs = getMaxOccurs();
return maxOccurs < 0 || maxOccurs > 1;
}
/**
* Returns true if property is mandatory.
*
* @return true if property is mandatory.
*/
public boolean isMandatory() {
return getMinOccurs() > 0;
}
/**
* Returns true if property is optional.
*
* @return true if property is optional.
*/
public boolean isOptional() {
return getMinOccurs() == 0;
}
public boolean isOperational() {
return operational;
}
public void setOperational(boolean operational) {
this.operational = operational;
}
/**
* Returns true if definition was created during the runtime based on a dynamic information
* such as xsi:type attributes in XML. This means that the definition needs to be stored
* alongside the data to have a successful serialization "roundtrip". The definition is not
* part of any schema and therefore cannot be determined. It may even be different for every
* instance of the associated item (element name).
*/
public boolean isDynamic() {
return dynamic;
}
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic;
}
/**
* Returns true if the property can be read. I.e. if it is returned in objects
* retrieved from "get", "search" and similar operations.
*/
public boolean canRead() {
return canRead;
}
/**
* Returns true if the item can be modified. I.e. if it can be changed
* during a modification of existing object.
*/
public boolean canModify() {
return canModify;
}
/**
*
*/
public void setReadOnly() {
canAdd = false;
canRead = true;
canModify = false;
}
public void setCanRead(boolean read) {
this.canRead = read;
}
public void setCanModify(boolean modify) {
this.canModify = modify;
}
public void setCanAdd(boolean add) {
this.canAdd = add;
}
/**
* Returns true if the item can be added. I.e. if it can be present
* in the object when a new object is created.
*/
public boolean canAdd() {
return canAdd;
}
/**
* Reference to an object that directly or indirectly represents possible values for
* this item. We do not define here what exactly the object has to be. It can be a lookup
* table, script that dynamically produces the values or anything similar.
* The object must produce the values of the correct type for this item otherwise an
* error occurs.
*/
public PrismReferenceValue getValueEnumerationRef() {
return valueEnumerationRef;
}
public void setValueEnumerationRef(PrismReferenceValue valueEnumerationRef) {
this.valueEnumerationRef = valueEnumerationRef;
}
public boolean isValidFor(QName elementQName, Class<? extends ItemDefinition> clazz) {
return isValidFor(elementQName, clazz, false);
}
public boolean isValidFor(QName elementQName, Class<? extends ItemDefinition> clazz, boolean caseInsensitive) {
if (!clazz.isAssignableFrom(this.getClass())) {
return false;
}
if (QNameUtil.match(elementQName, getName(), caseInsensitive)) {
return true;
}
return false;
}
public void adoptElementDefinitionFrom(ItemDefinition otherDef) {
if (otherDef == null) {
return;
}
setName(otherDef.getName());
setMinOccurs(otherDef.getMinOccurs());
setMaxOccurs(otherDef.getMaxOccurs());
}
/**
* Create an item instance. Definition name or default name will
* used as an element name for the instance. The instance will otherwise be empty.
* @return created item instance
*/
abstract public Item instantiate();
/**
* Create an item instance. Definition name will use provided name.
* for the instance. The instance will otherwise be empty.
* @return created item instance
*/
abstract public Item instantiate(QName name);
// add namespace from the definition if it's safe to do so
protected QName addNamespaceIfApplicable(QName name) {
if (StringUtils.isEmpty(name.getNamespaceURI())) {
if (QNameUtil.match(name, this.name)) {
return this.name;
}
}
return name;
}
<T extends ItemDefinition> T findItemDefinition(ItemPath path, Class<T> clazz) {
if (path.isEmpty()) {
if (clazz.isAssignableFrom(this.getClass())) {
return (T) this;
} else {
throw new IllegalArgumentException("Looking for definition of class " + clazz + " but found " + this);
}
} else {
throw new IllegalArgumentException("No definition for path " + path + " in " + this);
}
}
abstract public ItemDelta createEmptyDelta(ItemPath path);
abstract public ItemDefinition clone();
protected void copyDefinitionData(ItemDefinition clone) {
super.copyDefinitionData(clone);
clone.name = this.name;
clone.minOccurs = this.minOccurs;
clone.maxOccurs = this.maxOccurs;
clone.dynamic = this.dynamic;
clone.canAdd = this.canAdd;
clone.canRead = this.canRead;
clone.canModify = this.canModify;
clone.operational = this.operational;
}
public ItemDefinition deepClone() {
return clone();
}
ItemDefinition deepClone(Map<QName,ComplexTypeDefinition> ctdMap) {
return clone();
}
@Override
public void revive(PrismContext prismContext) {
if (this.prismContext != null) {
return;
}
this.prismContext = prismContext;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + maxOccurs;
result = prime * result + minOccurs;
result = prime * result + (canAdd ? 1231 : 1237);
result = prime * result + (canRead ? 1231 : 1237);
result = prime * result + (canModify ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ItemDefinition other = (ItemDefinition) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (maxOccurs != other.maxOccurs)
return false;
if (minOccurs != other.minOccurs)
return false;
if (canAdd != other.canAdd)
return false;
if (canRead != other.canRead)
return false;
if (canModify != other.canModify)
return false;
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getDebugDumpClassName());
sb.append(":");
sb.append(PrettyPrinter.prettyPrint(getName()));
sb.append(" ");
debugDumpShortToString(sb);
return sb.toString();
}
/**
* Used in debugDumping items. Does not need to have name in it as item already has it. Does not need
* to have class as that is just too much info that is almost anytime pretty obvious anyway.
*/
void debugDumpShortToString(StringBuilder sb) {
sb.append(PrettyPrinter.prettyPrint(getTypeName()));
debugMultiplicity(sb);
debugFlags(sb);
}
private void debugMultiplicity(StringBuilder sb) {
sb.append("[");
sb.append(getMinOccurs());
sb.append(",");
sb.append(getMaxOccurs());
sb.append("]");
}
public String debugMultiplicity() {
StringBuilder sb = new StringBuilder();
debugMultiplicity(sb);
return sb.toString();
}
private void debugFlags(StringBuilder sb) {
if (isIgnored()) {
sb.append(",ignored");
}
if (isDynamic()) {
sb.append(",dyn");
}
extendToString(sb);
}
public String debugFlags() {
StringBuilder sb = new StringBuilder();
debugFlags(sb);
// This starts with a collon, we do not want it here
if (sb.length() > 0) {
sb.deleteCharAt(0);
}
return sb.toString();
}
protected void extendToString(StringBuilder sb) {
sb.append(",");
if (canRead()) {
sb.append("R");
} else {
sb.append("-");
}
if (canAdd()) {
sb.append("A");
} else {
sb.append("-");
}
if (canModify()) {
sb.append("M");
} else {
sb.append("-");
}
}
}
|
infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinition.java
|
/*
* Copyright (c) 2010-2014 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.prism;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import org.apache.commons.lang.StringUtils;
/**
* Abstract item definition in the schema.
*
* This is supposed to be a superclass for all item definitions. Items are things
* that can appear in property containers, which generally means only a property
* and property container itself. Therefore this is in fact superclass for those
* two definitions.
*
* The definitions represent data structures of the schema. Therefore instances
* of Java objects from this class represent specific <em>definitions</em> from
* the schema, not specific properties or objects. E.g the definitions does not
* have any value.
*
* To transform definition to a real property or object use the explicit
* instantiate() methods provided in the definition classes. E.g. the
* instantiate() method will create instance of Property using appropriate
* PropertyDefinition.
*
* The convenience methods in Schema are using this abstract class to find
* appropriate definitions easily.
*
* @author Radovan Semancik
*
*/
public abstract class ItemDefinition extends Definition implements Serializable {
private static final long serialVersionUID = -2643332934312107274L;
protected QName name;
private int minOccurs = 1;
private int maxOccurs = 1;
private boolean operational = false;
private boolean dynamic;
private boolean canAdd = true;
private boolean canRead = true;
private boolean canModify = true;
// TODO: annotations
/**
* The constructors should be used only occasionally (if used at all).
* Use the factory methods in the ResourceObjectDefintion instead.
*
* @param name definition name (element Name)
* @param defaultName default element name
* @param typeName type name (XSD complex or simple type)
*/
ItemDefinition(QName elementName, QName typeName, PrismContext prismContext) {
super(typeName, prismContext);
this.name = elementName;
}
/**
* Returns name of the defined entity.
*
* The name is a name of the entity instance if it is fixed by the schema.
* E.g. it may be a name of the property in the container that cannot be
* changed.
*
* The name corresponds to the XML element name in the XML representation of
* the schema. It does NOT correspond to a XSD type name.
*
* Name is optional. If name is not set the null value is returned. If name is
* not set the type is "abstract", does not correspond to the element.
*
* @return the name name of the entity or null.
*/
public QName getName() {
return name;
}
public void setName(QName name) {
this.name = name;
}
public String getNamespace() {
return getName().getNamespaceURI();
}
/**
* Return the number of minimal value occurrences.
*
* @return the minOccurs
*/
public int getMinOccurs() {
return minOccurs;
}
public void setMinOccurs(int minOccurs) {
this.minOccurs = minOccurs;
}
/**
* Return the number of maximal value occurrences.
* <p/>
* Any negative number means "unbounded".
*
* @return the maxOccurs
*/
public int getMaxOccurs() {
return maxOccurs;
}
public void setMaxOccurs(int maxOccurs) {
this.maxOccurs = maxOccurs;
}
/**
* Returns true if property is single-valued.
*
* @return true if property is single-valued.
*/
public boolean isSingleValue() {
int maxOccurs = getMaxOccurs();
return maxOccurs >= 0 && maxOccurs <= 1;
}
/**
* Returns true if property is multi-valued.
*
* @return true if property is multi-valued.
*/
public boolean isMultiValue() {
int maxOccurs = getMaxOccurs();
return maxOccurs < 0 || maxOccurs > 1;
}
/**
* Returns true if property is mandatory.
*
* @return true if property is mandatory.
*/
public boolean isMandatory() {
return getMinOccurs() > 0;
}
/**
* Returns true if property is optional.
*
* @return true if property is optional.
*/
public boolean isOptional() {
return getMinOccurs() == 0;
}
public boolean isOperational() {
return operational;
}
public void setOperational(boolean operational) {
this.operational = operational;
}
/**
* Returns true if definition was created during the runtime based on a dynamic information
* such as xsi:type attributes in XML. This means that the definition needs to be stored
* alongside the data to have a successful serialization "roundtrip". The definition is not
* part of any schema and therefore cannot be determined. It may even be different for every
* instance of the associated item (element name).
*/
public boolean isDynamic() {
return dynamic;
}
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic;
}
/**
* Returns true if the property can be read. I.e. if it is returned in objects
* retrieved from "get", "search" and similar operations.
*/
public boolean canRead() {
return canRead;
}
/**
* Returns true if the item can be modified. I.e. if it can be changed
* during a modification of existing object.
*/
public boolean canModify() {
return canModify;
}
/**
*
*/
public void setReadOnly() {
canAdd = false;
canRead = true;
canModify = false;
}
public void setCanRead(boolean read) {
this.canRead = read;
}
public void setCanModify(boolean modify) {
this.canModify = modify;
}
public void setCanAdd(boolean add) {
this.canAdd = add;
}
/**
* Returns true if the item can be added. I.e. if it can be present
* in the object when a new object is created.
*/
public boolean canAdd() {
return canAdd;
}
public boolean isValidFor(QName elementQName, Class<? extends ItemDefinition> clazz) {
return isValidFor(elementQName, clazz, false);
}
public boolean isValidFor(QName elementQName, Class<? extends ItemDefinition> clazz, boolean caseInsensitive) {
if (!clazz.isAssignableFrom(this.getClass())) {
return false;
}
if (QNameUtil.match(elementQName, getName(), caseInsensitive)) {
return true;
}
return false;
}
public void adoptElementDefinitionFrom(ItemDefinition otherDef) {
if (otherDef == null) {
return;
}
setName(otherDef.getName());
setMinOccurs(otherDef.getMinOccurs());
setMaxOccurs(otherDef.getMaxOccurs());
}
/**
* Create an item instance. Definition name or default name will
* used as an element name for the instance. The instance will otherwise be empty.
* @return created item instance
*/
abstract public Item instantiate();
/**
* Create an item instance. Definition name will use provided name.
* for the instance. The instance will otherwise be empty.
* @return created item instance
*/
abstract public Item instantiate(QName name);
// add namespace from the definition if it's safe to do so
protected QName addNamespaceIfApplicable(QName name) {
if (StringUtils.isEmpty(name.getNamespaceURI())) {
if (QNameUtil.match(name, this.name)) {
return this.name;
}
}
return name;
}
<T extends ItemDefinition> T findItemDefinition(ItemPath path, Class<T> clazz) {
if (path.isEmpty()) {
if (clazz.isAssignableFrom(this.getClass())) {
return (T) this;
} else {
throw new IllegalArgumentException("Looking for definition of class " + clazz + " but found " + this);
}
} else {
throw new IllegalArgumentException("No definition for path " + path + " in " + this);
}
}
abstract public ItemDelta createEmptyDelta(ItemPath path);
abstract public ItemDefinition clone();
protected void copyDefinitionData(ItemDefinition clone) {
super.copyDefinitionData(clone);
clone.name = this.name;
clone.minOccurs = this.minOccurs;
clone.maxOccurs = this.maxOccurs;
clone.dynamic = this.dynamic;
clone.canAdd = this.canAdd;
clone.canRead = this.canRead;
clone.canModify = this.canModify;
clone.operational = this.operational;
}
public ItemDefinition deepClone() {
return clone();
}
ItemDefinition deepClone(Map<QName,ComplexTypeDefinition> ctdMap) {
return clone();
}
@Override
public void revive(PrismContext prismContext) {
if (this.prismContext != null) {
return;
}
this.prismContext = prismContext;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + maxOccurs;
result = prime * result + minOccurs;
result = prime * result + (canAdd ? 1231 : 1237);
result = prime * result + (canRead ? 1231 : 1237);
result = prime * result + (canModify ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ItemDefinition other = (ItemDefinition) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (maxOccurs != other.maxOccurs)
return false;
if (minOccurs != other.minOccurs)
return false;
if (canAdd != other.canAdd)
return false;
if (canRead != other.canRead)
return false;
if (canModify != other.canModify)
return false;
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getDebugDumpClassName());
sb.append(":");
sb.append(PrettyPrinter.prettyPrint(getName()));
sb.append(" ");
debugDumpShortToString(sb);
return sb.toString();
}
/**
* Used in debugDumping items. Does not need to have name in it as item already has it. Does not need
* to have class as that is just too much info that is almost anytime pretty obvious anyway.
*/
void debugDumpShortToString(StringBuilder sb) {
sb.append(PrettyPrinter.prettyPrint(getTypeName()));
debugMultiplicity(sb);
debugFlags(sb);
}
private void debugMultiplicity(StringBuilder sb) {
sb.append("[");
sb.append(getMinOccurs());
sb.append(",");
sb.append(getMaxOccurs());
sb.append("]");
}
public String debugMultiplicity() {
StringBuilder sb = new StringBuilder();
debugMultiplicity(sb);
return sb.toString();
}
private void debugFlags(StringBuilder sb) {
if (isIgnored()) {
sb.append(",ignored");
}
if (isDynamic()) {
sb.append(",dyn");
}
extendToString(sb);
}
public String debugFlags() {
StringBuilder sb = new StringBuilder();
debugFlags(sb);
// This starts with a collon, we do not want it here
if (sb.length() > 0) {
sb.deleteCharAt(0);
}
return sb.toString();
}
protected void extendToString(StringBuilder sb) {
sb.append(",");
if (canRead()) {
sb.append("R");
} else {
sb.append("-");
}
if (canAdd()) {
sb.append("A");
} else {
sb.append("-");
}
if (canModify()) {
sb.append("M");
} else {
sb.append("-");
}
}
}
|
valueEnumerationRef
|
infra/prism/src/main/java/com/evolveum/midpoint/prism/ItemDefinition.java
|
valueEnumerationRef
|
|
Java
|
apache-2.0
|
0452b4c755956c38af0b4d613f98d979da02a4a6
| 0
|
PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr
|
package org.apache.lucene.analysis;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.Random;
/**
* Throws IOException from random Tokenstream methods.
* <p>
* This can be used to simulate a buggy analyzer in IndexWriter,
* where we must delete the document but not abort everything in the buffer.
*/
public final class CrankyTokenFilter extends TokenFilter {
final Random random;
int thingToDo;
/** Creates a new CrankyTokenFilter */
public CrankyTokenFilter(TokenStream input, Random random) {
super(input);
this.random = random;
}
@Override
public boolean incrementToken() throws IOException {
if (thingToDo == 0 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.incrementToken()");
}
return input.incrementToken();
}
@Override
public void end() throws IOException {
super.end();
if (thingToDo == 1 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.end()");
}
}
@Override
public void reset() throws IOException {
super.reset();
thingToDo = random.nextInt(100);
if (thingToDo == 2 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.reset()");
}
}
@Override
public void close() throws IOException {
super.close();
if (thingToDo == 3 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.close()");
}
}
}
|
lucene/test-framework/src/java/org/apache/lucene/analysis/CrankyTokenFilter.java
|
package org.apache.lucene.analysis;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.Random;
/**
* Throws IOException from random Tokenstream methods.
* <p>
* This can be used to simulate a buggy analyzer in IndexWriter,
* where we must delete the document but not abort everything in the buffer.
*/
public final class CrankyTokenFilter extends TokenFilter {
final Random random;
int thingToDo;
/** Creates a new CrankyTokenFilter */
public CrankyTokenFilter(TokenStream input, Random random) {
super(input);
this.random = random;
}
@Override
public boolean incrementToken() throws IOException {
if (thingToDo == 0 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.incrementToken()");
}
return input.incrementToken();
}
@Override
public void end() throws IOException {
super.end();
if (thingToDo == 1 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.end()");
}
}
@Override
public void reset() throws IOException {
super.reset();
thingToDo = random.nextInt(10);
if (thingToDo == 2 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.reset()");
}
}
@Override
public void close() throws IOException {
super.close();
if (thingToDo == 3 && random.nextBoolean()) {
throw new IOException("Fake IOException from TokenStream.close()");
}
}
}
|
LUCENE-5635: consistent with trunk
git-svn-id: 13f9c63152c129021c7e766f4ef575faaaa595a2@1591694 13f79535-47bb-0310-9956-ffa450edef68
|
lucene/test-framework/src/java/org/apache/lucene/analysis/CrankyTokenFilter.java
|
LUCENE-5635: consistent with trunk
|
|
Java
|
apache-2.0
|
36f8326ee5aca21d06a6763b11c36641abacc41d
| 0
|
katsuster/ememu,katsuster/ememu
|
package net.katsuster.ememu.ui;
import java.net.*;
import java.awt.*;
import javax.swing.*;
/**
* プロキシオプションを設定するパネル。
*
* @author katsuhiro
*/
public class ProxyOptionPanel extends JPanel {
private ProxyOption opts;
private JCheckBox chkSet;
private JTextField txtHost, txtPort;
/**
* プロキシオプションを設定するパネルを作成します。
*/
public ProxyOptionPanel() {
this(new ProxyOption());
}
/**
* プロキシオプションを設定するパネルを作成します。
*
* パネル内の各コンポーネントには指定したデフォルト値が設定されます。
*
* @param options オプションのデフォルト値
*/
public ProxyOptionPanel(ProxyOption options) {
super(true);
opts = options;
chkSet = new JCheckBox("Enable proxy configuration");
if (opts.getProxyHost().toString().equals("")) {
chkSet.setSelected(false);
} else {
chkSet.setSelected(true);
}
txtHost = new JTextField(opts.getProxyHost().toString());
txtHost.setPreferredSize(calcPreferredSize(30));
txtHost.setMinimumSize(calcPreferredSize(30));
txtPort = new JTextField(Integer.toString(opts.getProxyPort()));
txtPort.setPreferredSize(calcPreferredSize(10));
txtPort.setMinimumSize(calcPreferredSize(10));
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagLayoutHelper.add(this, layout, chkSet,
0, 0, 2, 1);
GridBagLayoutHelper.add(this, layout, new JLabel("Host:", SwingConstants.RIGHT),
0, 1, 1, 1);
GridBagLayoutHelper.add(this, layout, txtHost,
1, 1, 1, 1);
GridBagLayoutHelper.add(this, layout, new JLabel("Port:", SwingConstants.RIGHT),
0, 2, 1, 1);
GridBagLayoutHelper.add(this, layout, txtPort,
1, 2, 1, 1);
setBorder(BorderFactory.createTitledBorder("Proxies"));
}
/**
* プロキシオプションを取得します。
*
* @return プロキシオプション
*/
public ProxyOption getOption() {
updateOption();
return opts;
}
/**
* パネル内の各コンポーネントの設定値をオプションオブジェクトに反映させます。
*/
protected void updateOption() {
try {
if (chkSet.isSelected()) {
opts.setProxyHost(new URI(txtHost.getText()));
opts.setProxyPort(Integer.valueOf(txtPort.getText()));
} else {
opts.setProxyHost(new URI(""));
opts.setProxyPort(0);
}
} catch (URISyntaxException | NumberFormatException e) {
//ignored
}
txtHost.setText(opts.getProxyHost().toString());
txtPort.setText(Integer.toString(opts.getProxyPort()));
}
/**
* "0" を指定された数だけ並べたときのコンポーネントの推奨サイズを取得します。
*
* @param chars 文字を並べる個数
* @return コンポーネントのサイズ
*/
protected Dimension calcPreferredSize(int chars) {
JTextField tmpTxt = new JTextField(
String.format("%0" + Integer.toString(chars) + "x", 0));
return tmpTxt.getPreferredSize();
}
}
|
emu/src/net/katsuster/ememu/ui/ProxyOptionPanel.java
|
package net.katsuster.ememu.ui;
import java.net.*;
import java.awt.*;
import javax.swing.*;
/**
* プロキシオプションを設定するパネル。
*
* @author katsuhiro
*/
public class ProxyOptionPanel extends JPanel {
private ProxyOption opts;
private JCheckBox chkSet;
private JTextField txtHost, txtPort;
/**
* プロキシオプションを設定するパネルを作成します。
*/
public ProxyOptionPanel() {
this(new ProxyOption());
}
/**
* プロキシオプションを設定するパネルを作成します。
*
* パネル内の各コンポーネントには指定したデフォルト値が設定されます。
*
* @param options オプションのデフォルト値
*/
public ProxyOptionPanel(ProxyOption options) {
super(true);
opts = options;
chkSet = new JCheckBox("Enable proxy configuration");
if (opts.getProxyHost().toString().equals("")) {
chkSet.setSelected(false);
} else {
chkSet.setSelected(true);
}
txtHost = new JTextField(opts.getProxyHost().toString());
txtHost.setPreferredSize(calcPreferredSize(30));
txtHost.setMinimumSize(calcPreferredSize(30));
txtPort = new JTextField(Integer.toString(opts.getProxyPort()));
txtPort.setPreferredSize(calcPreferredSize(10));
txtPort.setMinimumSize(calcPreferredSize(10));
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagLayoutHelper.add(this, layout, chkSet,
0, 0, 2, 1);
GridBagLayoutHelper.add(this, layout, new JLabel("Host:", SwingConstants.RIGHT),
0, 1, 1, 1);
GridBagLayoutHelper.add(this, layout, txtHost,
1, 1, 1, 1);
GridBagLayoutHelper.add(this, layout, new JLabel("Port:", SwingConstants.RIGHT),
0, 2, 1, 1);
GridBagLayoutHelper.add(this, layout, txtPort,
1, 2, 1, 1);
setBorder(BorderFactory.createTitledBorder("Proxies"));
}
/**
* プロキシオプションを取得します。
*
* @return プロキシオプション
*/
public ProxyOption getOption() {
updateOption();
return opts;
}
/**
* パネル内の各コンポーネントの設定値をオプションオブジェクトに反映させます。
*/
protected void updateOption() {
try {
if (chkSet.isSelected()) {
opts.setProxyHost(new URI(txtHost.getText()));
opts.setProxyPort(Integer.valueOf(txtPort.getText()));
} else {
opts.setProxyHost(new URI(""));
opts.setProxyPort(0);
}
} catch (URISyntaxException e) {
//ignored
}
}
/**
* "0" を指定された数だけ並べたときのコンポーネントの推奨サイズを取得します。
*
* @param chars 文字を並べる個数
* @return コンポーネントのサイズ
*/
protected Dimension calcPreferredSize(int chars) {
JTextField tmpTxt = new JTextField(
String.format("%0" + Integer.toString(chars) + "x", 0));
return tmpTxt.getPreferredSize();
}
}
|
Fix crash when specify empty string to "proxy port" text field.
|
emu/src/net/katsuster/ememu/ui/ProxyOptionPanel.java
|
Fix crash when specify empty string to "proxy port" text field.
|
|
Java
|
apache-2.0
|
56a45b620a59a66da0ce03b1bb6db3124f886218
| 0
|
backpaper0/java-you,backpaper0/java-you
|
package javayou;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.context.RequestScoped;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.ws.rs.BeanParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
@RequestScoped
@Path("generate")
public class JavaYouResource {
@Inject
private ManagedExecutorService executor;
/**
* 「あなたと○○、今すぐ○○」画像を生成するリソースメソッド。
*
* @param texts ○○に入れる文字列をまとめたオブジェクト
* @param response JAX-RSの非同期処理で使用するクラス。
* 別スレッドで処理を行って結果をresponse.resume()メソッドへ渡す。
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public void generate(@BeanParam Texts texts,
@Suspended AsyncResponse response) {
//CompletableFutureで(無駄に)非同期処理をしている。
CompletableFuture.runAsync(() -> {
try (InputStream in = getClass().getResourceAsStream("/duke.png")) {
BufferedImage image = ImageIO.read(in);
Graphics2D g = image.createGraphics();
//指定したフォントが無いければデフォルトのフォントが使われるっぽい
g.setFont(new Font("Yutapon coding RegularBackslash",
Font.BOLD, 24));
g.setColor(Color.BLACK);
//Java + You, Download Today!
g.drawString("あなたと", 40, 80);
g.drawString(texts.text1, 60, 120);
g.drawString("今すぐ", 290, 380);
g.drawString(texts.text2, 300, 420);
//Graphics2Dをいじったら忘れずdisposeする
g.dispose();
//byte配列で結果を返しているけれどもっとサイズが大きい、
//またはサイズが予測できない場合は一時ファイルにでも書き出して
//おいてInputStreamを返した方が良いと思う。
//今回はサイズが小さいというのもあり、手抜き実装(・ω<) テヘペロ
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
response.resume(out.toByteArray());
} catch (IOException e) {
response.resume(e);
}
}, executor);
//Java EE環境ではexecutorの指定をしてサーバが管理しているスレッドを使うようにする
}
public static class Texts {
/**
* 1つ目の○○に入れる文字列
*/
@QueryParam("text1")
public String text1;
/**
* 2つ目の○○に入れる文字列
*/
@QueryParam("text2")
public String text2;
}
}
|
src/main/java/javayou/JavaYouResource.java
|
package javayou;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.context.RequestScoped;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
@RequestScoped
@Path("generate")
public class JavaYouResource {
@Inject
private ManagedExecutorService executor;
/**
* 「あなたと○○、今すぐ○○」画像を生成するリソースメソッド。
*
* @param text1 1つ目の○○に入れる文字列
* @param text2 2つ目の○○に入れる文字列
* @param response JAX-RSの非同期処理で使用するクラス。
* 別スレッドで処理を行って結果をresponse.resume()メソッドへ渡す。
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
public void generate(@QueryParam("text1") String text1,
@QueryParam("text2") String text2, @Suspended AsyncResponse response) {
//CompletableFutureで(無駄に)非同期処理をしている。
CompletableFuture.runAsync(() -> {
try (InputStream in = getClass().getResourceAsStream("/duke.png")) {
BufferedImage image = ImageIO.read(in);
Graphics2D g = image.createGraphics();
//指定したフォントが無いければデフォルトのフォントが使われるっぽい
g.setFont(new Font("Yutapon coding RegularBackslash",
Font.BOLD, 24));
g.setColor(Color.BLACK);
//Java + You, Download Today!
g.drawString("あなたと", 40, 80);
g.drawString(text1, 60, 120);
g.drawString("今すぐ", 290, 380);
g.drawString(text2, 300, 420);
//Graphics2Dをいじったら忘れずdisposeする
g.dispose();
//byte配列で結果を返しているけれどもっとサイズが大きい、
//またはサイズが予測できない場合は一時ファイルにでも書き出して
//おいてInputStreamを返した方が良いと思う。
//今回はサイズが小さいというのもあり、手抜き実装(・ω<) テヘペロ
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
response.resume(out.toByteArray());
} catch (IOException e) {
response.resume(e);
}
}, executor);
//Java EE環境ではexecutorの指定をしてサーバが管理しているスレッドを使うようにする
}
}
|
@BeanParamでパラメータをまとめた
|
src/main/java/javayou/JavaYouResource.java
|
@BeanParamでパラメータをまとめた
|
|
Java
|
bsd-3-clause
|
4e695a6edd9ce5841888658659dc5e3b7a2e9105
| 0
|
ojacobson/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo
|
package org.dspace.app.xmlui.aspect.versioning;
import org.apache.avalon.framework.parameters.ParameterException;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.*;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.utils.DSpace;
import org.dspace.versioning.PluggableVersioningService;
import org.dspace.versioning.Version;
import org.dspace.versioning.VersionServiceUtil;
import org.dspace.versioning.VersioningService;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
/**
* Created by IntelliJ IDEA.
* User: fabio.bolognesi
* Date: Apr 4, 2011
* Time: 8:59:47 AM
* To change this template use File | Settings | File Templates.
*/
// Versioning
public class VersionItemForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_title = message("xmlui.aspect.versioning.VersionItemForm.title");
private static final Message T_trail = message("xmlui.aspect.versioning.VersionItemForm.trail");
private static final Message T_head1 = message("xmlui.aspect.versioning.VersionItemForm.head1");
private static final Message T_submit_version= message("xmlui.aspect.versioning.VersionItemForm.submit_version");
private static final Message T_submit_update_version= message("xmlui.aspect.versioning.VersionItemForm.submit_update_version");
private static final Message T_summary = message("xmlui.aspect.versioning.VersionItemForm.summary");
private static final Message T_reason = message("xmlui.aspect.versioning.VersionItemForm.reason");
public void addPageMeta(PageMeta pageMeta) throws WingException{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
//pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException{
String errorString = parameters.getParameter("errors",null);
ArrayList<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
String summary=null;
try {
summary = parameters.getParameter("summary");
} catch (ParameterException e) {
throw new RuntimeException(e);
}
Item item = Item.find(context, itemID);
// DIVISION: Main
Division main = body.addInteractiveDivision("version-item", contextPath+"/item/version", Division.METHOD_POST, "primary administrative version");
main.setHead(T_head1.parameterize(item.getHandle()));
// Fields
List fields = main.addList("fields",List.TYPE_FORM);
Composite addComposite = fields.addItem().addComposite("summary");
addComposite.setLabel(T_summary);
TextArea addValue = addComposite.addTextArea("summary");
addValue.setMaxLength(255);
if (errors.contains("version_reason")) {
addValue.addError(T_reason);
}
else{ addValue.setValue(summary);
}
// Buttons
Para actions = main.addPara();
org.dspace.versioning.VersionHistory history = retrieveVersionHistory(item);
if(history!=null && history.hasNext(item))
actions.addButton("submit_update_version").setValue(T_submit_update_version);
else
actions.addButton("submit_version").setValue(T_submit_version);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("versioning-continue").setValue(knot.getId());
}
private org.dspace.versioning.VersionHistory retrieveVersionHistory(Item item){
VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
org.dspace.versioning.VersionHistory history = versioningService.findVersionHistory(context, item.getID());
return history;
}
}
|
dspace/modules/versioning/versioning-webapp/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionItemForm.java
|
package org.dspace.app.xmlui.aspect.versioning;
import org.apache.avalon.framework.parameters.ParameterException;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.*;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.utils.DSpace;
import org.dspace.versioning.PluggableVersioningService;
import org.dspace.versioning.Version;
import org.dspace.versioning.VersionServiceUtil;
import org.dspace.versioning.VersioningService;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
/**
* Created by IntelliJ IDEA.
* User: fabio.bolognesi
* Date: Apr 4, 2011
* Time: 8:59:47 AM
* To change this template use File | Settings | File Templates.
*/
// Versioning
public class VersionItemForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_title = message("xmlui.aspect.versioning.VersionItemForm.title");
private static final Message T_trail = message("xmlui.aspect.versioning.VersionItemForm.trail");
private static final Message T_head1 = message("xmlui.aspect.versioning.VersionItemForm.head1");
private static final Message T_submit_version= message("xmlui.aspect.versioning.VersionItemForm.submit_version");
private static final Message T_submit_update_version= message("xmlui.aspect.versioning.VersionItemForm.submit_update_version");
private static final Message T_summary = message("xmlui.aspect.versioning.VersionItemForm.summary");
private static final Message T_reason = message("xmlui.aspect.versioning.VersionItemForm.reason");
public void addPageMeta(PageMeta pageMeta) throws WingException{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
//pageMeta.addTrailLink(contextPath+"/admin/item", T_item_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws WingException, SQLException{
String errorString = parameters.getParameter("errors",null);
ArrayList<String> errors = new ArrayList<String>();
if (errorString != null)
{
for (String error : errorString.split(","))
{
errors.add(error);
}
}
// Get our parameters and state
int itemID = parameters.getParameterAsInteger("itemID",-1);
String summary=null;
try {
summary = parameters.getParameter("summary");
} catch (ParameterException e) {
throw new RuntimeException(e);
}
Item item = Item.find(context, itemID);
// DIVISION: Main
Division main = body.addInteractiveDivision("version-item", contextPath+"/item/version", Division.METHOD_POST, "primary administrative version");
main.setHead(T_head1.parameterize(item.getHandle()));
// Fields
List fields = main.addList("fields",List.TYPE_FORM);
Composite addComposite = fields.addItem().addComposite("summary");
addComposite.setLabel(T_summary);
TextArea addValue = addComposite.addTextArea("summary");
if (errors.contains("version_reason")) {
addValue.addError(T_reason);
}
else{ addValue.setValue(summary);
}
// Buttons
Para actions = main.addPara();
org.dspace.versioning.VersionHistory history = retrieveVersionHistory(item);
if(history!=null && history.hasNext(item))
actions.addButton("submit_update_version").setValue(T_submit_update_version);
else
actions.addButton("submit_version").setValue(T_submit_version);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
main.addHidden("versioning-continue").setValue(knot.getId());
}
private org.dspace.versioning.VersionHistory retrieveVersionHistory(Item item){
VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
org.dspace.versioning.VersionHistory history = versioningService.findVersionHistory(context, item.getID());
return history;
}
}
|
max length for version reason is 255.
|
dspace/modules/versioning/versioning-webapp/src/main/java/org/dspace/app/xmlui/aspect/versioning/VersionItemForm.java
|
max length for version reason is 255.
|
|
Java
|
bsd-3-clause
|
b030be68d3fa2be8157e1cb6289d64652cf660d0
| 0
|
PatrickPenguinTurtle/allwpilib,PeterMitrano/allwpilib,robotdotnet/allwpilib,PatrickPenguinTurtle/allwpilib,JLLeitschuh/allwpilib,robotdotnet/allwpilib,robotdotnet/allwpilib,PatrickPenguinTurtle/allwpilib,PatrickPenguinTurtle/allwpilib,PatrickPenguinTurtle/allwpilib,PeterMitrano/allwpilib,PeterMitrano/allwpilib,RAR1741/wpilib,RAR1741/wpilib,333fred/allwpilib,JLLeitschuh/allwpilib,RAR1741/wpilib,JLLeitschuh/allwpilib,333fred/allwpilib,RAR1741/wpilib,333fred/allwpilib,PeterMitrano/allwpilib,RAR1741/wpilib,PatrickPenguinTurtle/allwpilib,PatrickPenguinTurtle/allwpilib,333fred/allwpilib,robotdotnet/allwpilib,PeterMitrano/allwpilib,JLLeitschuh/allwpilib,JLLeitschuh/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,JLLeitschuh/allwpilib,PeterMitrano/allwpilib,333fred/allwpilib,RAR1741/wpilib,PeterMitrano/allwpilib,RAR1741/wpilib,robotdotnet/allwpilib,JLLeitschuh/allwpilib
|
package edu.wpi.first.wpilib.plugins.core.wizards;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
/**
* Utilities for creating a new project and files from templates. Uses
* IProjectCreator to provide hooks for generating the directory
* structure, initial files, initializing and finalizing the creation
* of the new project.
*
* @author Alex Henning
**/
public class ProjectCreationUtils {
/**
* Create a project using the given IProjectCreator.
*
* @param creator The creator that provides the necessary information
* to create the project.
* @return The newly created project.
*/
public static IProject createProject(IProjectCreator creator) {
IProject project = createBaseProject(creator.getName(), null);
try {
creator.initialize(project);
for (String nature : creator.getNatures()) {
addNature(project, nature);
}
addToProjectStructure(project, creator);
addFilesToProject(project, creator);
creator.finalize(project);
} catch (CoreException e) {
WPILibCore.logError("Error creating project "+creator.getName(), e);
project = null;
}
return project;
}
private static IProject createBaseProject(String projectName, IPath location) {
IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (!newProject.exists()) {
IPath projectLocation = location;
IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName());
if (location != null &&
ResourcesPlugin.getWorkspace().getRoot().getLocation().equals(location)) {
projectLocation = null;
}
desc.setLocation(projectLocation);
try {
newProject.create(desc, null);
if (!newProject.isOpen()) {
newProject.open(null);
}
} catch (CoreException e) {
WPILibCore.logError("Can't create new project.", e);
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Error creating project! This may occur if a project of the same name with different case exists in the Workspace");
}
});
}
}else {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Error! A project of the same name already exists in the Workspace");
}
});
}
return newProject;
}
private static void addNature(IProject project, String nature_id) throws CoreException {
if (!project.hasNature(nature_id)) {
IProjectDescription desc = project.getDescription();
String[] prevNatures = desc.getNatureIds();
String[] newNatures = new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length] = nature_id;
desc.setNatureIds(newNatures);
project.setDescription(desc, null);
}
}
private static void addToProjectStructure(IProject project, IProjectCreator creator) throws CoreException {
String[] paths = creator.getProjectType().getFolders(creator.getPackageName());
for (String path : paths) {
IFolder etcFolders = project.getFolder(path);
createFolder(etcFolders);
}
}
private static void createFolder(IFolder folder) throws CoreException {
IContainer parent = folder.getParent();
if (parent instanceof IFolder) {
createFolder((IFolder) parent);
}
if (!folder.exists()) {
folder.create(false, true, null);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, null);
}
private static void addFilesToProject(IProject project, IProjectCreator creator) throws CoreException {
Map<String, String> files = creator.getProjectType().getFiles(creator.getPackageName());
for (Entry<String, String> e : files.entrySet()) {
try {
URL url = new URL(creator.getProjectType().getBaseURL(), e.getValue());
createTemplateFile(project, e.getKey(), url, creator.getValues());
} catch (MalformedURLException e1) {
WPILibCore.logError("Error adding file "+e.toString()+" to project.", e1);
}
}
}
/**
* Create a file in the project from a template. Substituting as required.
*
* @param project The project to use create the file in.
* @param filepath The path of the created file.
* @param filesource The source of the template to use.
* @param vals The map of values to use for substitution.
* @throws CoreException
*/
public static void createTemplateFile(IProject project, String filepath, URL url, Map<String, String> vals) throws CoreException {
IFile template = project.getFile(new Path(filepath));
if (!template.exists()) {
InputStream in = openTemplateContentStream(project, url, vals);
template.create(in, true, null);
}
}
private static InputStream openTemplateContentStream(IProject project, URL url, Map<String, String> vals) {
//http://eclipse-javacc.cvs.sourceforge.net/viewvc/eclipse-javacc/sf.eclipse.javacc/src-plugin/sf/eclipse/javacc/wizards/JJNewWizard.java?view=markup
//eclipse plugin distributing template files
try {
return makeTemplateInputStream(url.openStream(), vals);
} catch (final MalformedURLException e) {
WPILibCore.logError("Malformed URL "+url, e);
} catch (final IOException e) {
WPILibCore.logError("Issue opening input stream.", e);
}
return null;
}
private static InputStream makeTemplateInputStream(InputStream stream, Map<String, String> vals) {
String str;
try {
str = readInput(stream);
stream.close();
} catch (final IOException e) {
WPILibCore.logError("Error reading template.", e);
return null;
}
// Instantiate template
for (Entry<String, String> e : vals.entrySet())
str = str.replace(e.getKey(), e.getValue());
return new ByteArrayInputStream(str.getBytes());
}
private static String readInput(InputStream stream) {
StringBuffer buffer = new StringBuffer();
try {
InputStreamReader isr = new InputStreamReader(stream);
Reader in = new BufferedReader(isr);
int ch;
while ((ch = in.read()) > -1) {
buffer.append((char)ch);
}
in.close();
return buffer.toString();
} catch (IOException e) {
WPILibCore.logError("Error reading input.", e);
return null;
}
}
}
|
eclipse-plugins/edu.wpi.first.wpilib.plugins.core/src/main/java/edu/wpi/first/wpilib/plugins/core/wizards/ProjectCreationUtils.java
|
package edu.wpi.first.wpilib.plugins.core.wizards;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
/**
* Utilities for creating a new project and files from templates. Uses
* IProjectCreator to provide hooks for generating the directory
* structure, initial files, initializing and finalizing the creation
* of the new project.
*
* @author Alex Henning
**/
public class ProjectCreationUtils {
/**
* Create a project using the given IProjectCreator.
*
* @param creator The creator that provides the necessary information
* to create the project.
* @return The newly created project.
*/
public static IProject createProject(IProjectCreator creator) {
IProject project = createBaseProject(creator.getName(), null);
try {
creator.initialize(project);
for (String nature : creator.getNatures()) {
addNature(project, nature);
}
addToProjectStructure(project, creator);
addFilesToProject(project, creator);
creator.finalize(project);
} catch (CoreException e) {
WPILibCore.logError("Error creating project "+creator.getName(), e);
project = null;
}
return project;
}
private static IProject createBaseProject(String projectName, IPath location) {
IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
if (!newProject.exists()) {
IPath projectLocation = location;
IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName());
if (location != null &&
ResourcesPlugin.getWorkspace().getRoot().getLocation().equals(location)) {
projectLocation = null;
}
desc.setLocation(projectLocation);
try {
newProject.create(desc, null);
if (!newProject.isOpen()) {
newProject.open(null);
}
} catch (CoreException e) {
WPILibCore.logError("Can't create new project.", e);
}
}else {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
MessageDialog.openError(Display.getDefault().getActiveShell(), "Error", "Error! A project of the same name already exists in the Workspace");
}
});
}
return newProject;
}
private static void addNature(IProject project, String nature_id) throws CoreException {
if (!project.hasNature(nature_id)) {
IProjectDescription desc = project.getDescription();
String[] prevNatures = desc.getNatureIds();
String[] newNatures = new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length] = nature_id;
desc.setNatureIds(newNatures);
project.setDescription(desc, null);
}
}
private static void addToProjectStructure(IProject project, IProjectCreator creator) throws CoreException {
String[] paths = creator.getProjectType().getFolders(creator.getPackageName());
for (String path : paths) {
IFolder etcFolders = project.getFolder(path);
createFolder(etcFolders);
}
}
private static void createFolder(IFolder folder) throws CoreException {
IContainer parent = folder.getParent();
if (parent instanceof IFolder) {
createFolder((IFolder) parent);
}
if (!folder.exists()) {
folder.create(false, true, null);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, null);
}
private static void addFilesToProject(IProject project, IProjectCreator creator) throws CoreException {
Map<String, String> files = creator.getProjectType().getFiles(creator.getPackageName());
for (Entry<String, String> e : files.entrySet()) {
try {
URL url = new URL(creator.getProjectType().getBaseURL(), e.getValue());
createTemplateFile(project, e.getKey(), url, creator.getValues());
} catch (MalformedURLException e1) {
WPILibCore.logError("Error adding file "+e.toString()+" to project.", e1);
}
}
}
/**
* Create a file in the project from a template. Substituting as required.
*
* @param project The project to use create the file in.
* @param filepath The path of the created file.
* @param filesource The source of the template to use.
* @param vals The map of values to use for substitution.
* @throws CoreException
*/
public static void createTemplateFile(IProject project, String filepath, URL url, Map<String, String> vals) throws CoreException {
IFile template = project.getFile(new Path(filepath));
if (!template.exists()) {
InputStream in = openTemplateContentStream(project, url, vals);
template.create(in, true, null);
}
}
private static InputStream openTemplateContentStream(IProject project, URL url, Map<String, String> vals) {
//http://eclipse-javacc.cvs.sourceforge.net/viewvc/eclipse-javacc/sf.eclipse.javacc/src-plugin/sf/eclipse/javacc/wizards/JJNewWizard.java?view=markup
//eclipse plugin distributing template files
try {
return makeTemplateInputStream(url.openStream(), vals);
} catch (final MalformedURLException e) {
WPILibCore.logError("Malformed URL "+url, e);
} catch (final IOException e) {
WPILibCore.logError("Issue opening input stream.", e);
}
return null;
}
private static InputStream makeTemplateInputStream(InputStream stream, Map<String, String> vals) {
String str;
try {
str = readInput(stream);
stream.close();
} catch (final IOException e) {
WPILibCore.logError("Error reading template.", e);
return null;
}
// Instantiate template
for (Entry<String, String> e : vals.entrySet())
str = str.replace(e.getKey(), e.getValue());
return new ByteArrayInputStream(str.getBytes());
}
private static String readInput(InputStream stream) {
StringBuffer buffer = new StringBuffer();
try {
InputStreamReader isr = new InputStreamReader(stream);
Reader in = new BufferedReader(isr);
int ch;
while ((ch = in.read()) > -1) {
buffer.append((char)ch);
}
in.close();
return buffer.toString();
} catch (IOException e) {
WPILibCore.logError("Error reading input.", e);
return null;
}
}
}
|
Detect projects which are duplicates on Windows due to casing (fixes artf3487).
Change-Id: I5f1ecc657fea226ea0eb1429a0f394a3345264db
|
eclipse-plugins/edu.wpi.first.wpilib.plugins.core/src/main/java/edu/wpi/first/wpilib/plugins/core/wizards/ProjectCreationUtils.java
|
Detect projects which are duplicates on Windows due to casing (fixes artf3487).
|
|
Java
|
mit
|
f96be3457b490e317d5ca40b76a3cb2967615360
| 0
|
Aaylor/Goinfr-O-Mania
|
package graphics;
import engine.*;
import engine.nutritionists.AbstractNutritionist;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
public class BoardView extends Background implements Observer {
private static final int UI_HEIGHT = 50;
private static final double FRISE_HEIGHT = 10;
private final int HEART_PADDING = 5;
private String lifeLabel;
private String scoreLabel;
private String weaponLabel;
private String timeLabel;
private Image gameUI;
private Image barUI;
private Image emptyHeart;
private Image filledHeart;
private Font fontUI;
private Board board;
private boolean paused;
private Font font;
public BoardView(Board board, String background) {
super(background);
this.board = board;
try {
font = Font.createFont(Font.TRUETYPE_FONT,
new File("fonts/LearningCurve.ttf")).deriveFont(Font.PLAIN, 60);
} catch (Exception e) {
e.printStackTrace();
}
gameUI = resizeInitialImage("pictures/frise00.png", FRISE_HEIGHT, true);
barUI = resizeInitialImage("pictures/frise01.png", 6, false);
try {
File file = new File("fonts/Viking_n.ttf");
fontUI = Font.createFont(Font.TRUETYPE_FONT, file)
.deriveFont(Font.PLAIN, 12);
} catch (Exception e) {
fontUI = null;
}
emptyHeart = resizeInitialImage("pictures/heart00.png", 20, true);
filledHeart = resizeInitialImage("pictures/heart01.png", 20, true);
ResourceBundle bundle = MainFrame.getCurrentInstance().getBundle();
lifeLabel = bundle.getString("lifeUI");
scoreLabel = bundle.getString("scoreUI");
weaponLabel = bundle.getString("weaponUI");
timeLabel = bundle.getString("chronoUI");
setDoubleBuffered(true);
}
public boolean isPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
private Image resizeInitialImage(String path, double newValue, boolean what) {
ImageIcon icon = new ImageIcon(path);
double alpha;
int nWidth;
int nHeight;
if (what) {
alpha = newValue / icon.getIconHeight();
nWidth = (int) (icon.getIconWidth() * alpha);
nHeight = (int) newValue;
} else {
alpha = newValue / icon.getIconWidth();
nWidth = (int) newValue;
nHeight = (int) (icon.getIconHeight() * alpha);
}
BufferedImage image =
new BufferedImage(nWidth, nHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(
icon.getImage(),
0, 0, nWidth, nHeight, null
);
return image;
}
private int getRealHeight() {
return getHeight() - UI_HEIGHT;
}
@Override
public Dimension getSize() {
return new Dimension(getWidth(), getHeight() - UI_HEIGHT);
}
@Override
public void update(Observable o, Object arg) {
this.repaint();
}
private void drawUI(Graphics2D g2d) {
EntityManager em = board.getLevel().getEntityManager();
Color initialColor = g2d.getColor();
/* Rectangle */
g2d.setColor(Color.BLACK);
g2d.fillRect(0, getRealHeight(), getWidth(), UI_HEIGHT);
/* Frise */
int start = 0;
do {
g2d.drawImage(
gameUI,
start, getRealHeight(),
gameUI.getWidth(null), gameUI.getHeight(null),
null
);
start += gameUI.getWidth(null);
} while(start <= getWidth());
/* Bar */
int distance = getWidth() / 4;
int xPosition = distance;
while (xPosition < getWidth()) {
g2d.drawImage(barUI, xPosition, (int)(getRealHeight() + FRISE_HEIGHT),
barUI.getWidth(null), barUI.getHeight(null), null);
xPosition += distance;
}
/* Glutton informations */
if (em.getGlutton() != null) {
Font initialFont = g2d.getFont();
if (fontUI != null) {
g2d.setFont(fontUI);
}
g2d.setColor(Color.white);
FontMetrics fm = g2d.getFontMetrics(fontUI);
int current_distance = 0;
int middle =
getRealHeight() + ((int)FRISE_HEIGHT) +
((getHeight() - getRealHeight() + ((int)FRISE_HEIGHT)) / 2) -
(fm.getHeight() / 2);
// life
g2d.drawString(lifeLabel, current_distance + 5, middle);
int curX = current_distance + fm.stringWidth(lifeLabel) + 30;
for (int i = 0; i < 6; i++) {
if (i < board.getLevel().getEntityManager().getGlutton().getLife())
g2d.drawImage(filledHeart, curX, (middle - (emptyHeart.getHeight(null) / 2) - 5), null);
else
g2d.drawImage(emptyHeart, curX, (middle - (emptyHeart.getHeight(null) / 2) - 5), null);
curX += emptyHeart.getWidth(null) + HEART_PADDING;
}
current_distance += distance + barUI.getWidth(null);
// score
g2d.drawString(scoreLabel, current_distance + 5, middle);
g2d.drawString(
String.format("%05d", board.getLevel().getScore().getValue()),
current_distance + fm.stringWidth(scoreLabel) + 50, middle
);
current_distance += distance + barUI.getWidth(null);
// weapon
g2d.drawString(weaponLabel, current_distance + 5, middle);
g2d.drawString(
"*TODO*",
current_distance + fm.stringWidth(weaponLabel) + 50, middle
);
current_distance += distance + barUI.getWidth(null);
// chrono
g2d.drawString(timeLabel, current_distance + 5, middle);
g2d.drawString(board.getLevel().getChrono().toString(),
current_distance + fm.stringWidth(timeLabel) + 50, middle);
g2d.setFont(initialFont);
}
g2d.setColor(initialColor);
}
private void drawEntity(Graphics2D g2d, EntityView ev) {
Entity entity = ev.getEntity();
AffineTransform t = new AffineTransform();
t.translate(entity.getX(), entity.getY());
t.scale(1, 1);
if (entity instanceof AbstractMovableEntity) {
AbstractMovableEntity ame = (AbstractMovableEntity) entity;
Circle c = ame.getBoundsCircle();
double dx = entity.getCenterX() +
(c.getRadius() * Math.cos(ame.getDirectionRadian()));
double dy = entity.getCenterY() +
(c.getRadius() * Math.sin(ame.getDirectionRadian()));
double angle = ame.getDirectionRadian();
g2d.rotate(angle, entity.getCenterX(), entity.getCenterY());
g2d.drawImage(ev.getCurrentDrawing(), t, null);
if (ame.getWeapon() != null) {
BufferedImage bi = ame.getWeapon().getNextAnimation();
if (bi != null) {
AffineTransform imgTransform = new AffineTransform();
imgTransform.translate(
ame.getCenterX() + ame.getSize().getWidth() / 2,
ame.getCenterY() - bi.getHeight() / 2
);
g2d.drawImage(bi, imgTransform, null);
}
}
g2d.draw(new Line2D.Double(ame.getCenterX(), ame.getCenterY(), ame.getCenterX() + ame.getSize().getWidth()/2, ame.getCenterY()));
g2d.rotate(-angle, entity.getCenterX(), entity.getCenterY());
} else {
g2d.drawImage(ev.getCurrentDrawing(), t, null);
}
Toolkit.getDefaultToolkit().sync();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D)g;
EntityManager manager = board.getLevel().getEntityManager();
drawUI(graphics2D);
/* Draw the glutton */
if (manager.getGlutton() != null)
drawEntity(graphics2D, manager.getGluttonView());
/* Draw nutritionists */
for (EntityView e : manager.getNutritionistsView())
drawEntity(graphics2D, e);
/* Draw other entities */
for (EntityView e : manager.getOthersView())
drawEntity(graphics2D, e);
if (isPaused()) {
String pause = "Pause";
graphics2D.setFont(font);
graphics2D.setColor(new Color(200, 14, 32));
Rectangle2D rect = graphics2D.getFontMetrics(font)
.getStringBounds(pause, null);
double x = getWidth() - rect.getWidth() - 20;
double y = getHeight() - rect.getHeight();
graphics2D.drawString(pause, (int) x, (int) y);
}
}
}
|
src/graphics/BoardView.java
|
package graphics;
import engine.*;
import engine.nutritionists.AbstractNutritionist;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
public class BoardView extends Background implements Observer {
private static final int UI_HEIGHT = 50;
private static final double FRISE_HEIGHT = 10;
private final int HEART_PADDING = 5;
private String lifeLabel;
private String scoreLabel;
private String weaponLabel;
private String timeLabel;
private Image gameUI;
private Image barUI;
private Image emptyHeart;
private Image filledHeart;
private Font fontUI;
private Board board;
private boolean paused;
private Font font;
public BoardView(Board board, String background) {
super(background);
this.board = board;
try {
font = Font.createFont(Font.TRUETYPE_FONT,
new File("fonts/LearningCurve.ttf")).deriveFont(Font.PLAIN, 60);
} catch (Exception e) {
e.printStackTrace();
}
gameUI = resizeInitialImage("pictures/frise00.png", FRISE_HEIGHT, true);
barUI = resizeInitialImage("pictures/frise01.png", 6, false);
try {
File file = new File("fonts/Viking_n.ttf");
fontUI = Font.createFont(Font.TRUETYPE_FONT, file)
.deriveFont(Font.PLAIN, 12);
} catch (Exception e) {
fontUI = null;
}
emptyHeart = resizeInitialImage("pictures/heart00.png", 20, true);
filledHeart = resizeInitialImage("pictures/heart01.png", 20, true);
ResourceBundle bundle = MainFrame.getCurrentInstance().getBundle();
lifeLabel = bundle.getString("lifeUI");
scoreLabel = bundle.getString("scoreUI");
weaponLabel = bundle.getString("weaponUI");
timeLabel = bundle.getString("chronoUI");
setDoubleBuffered(true);
}
public boolean isPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
private Image resizeInitialImage(String path, double newValue, boolean what) {
ImageIcon icon = new ImageIcon(path);
double alpha;
int nWidth;
int nHeight;
if (what) {
alpha = newValue / icon.getIconHeight();
nWidth = (int) (icon.getIconWidth() * alpha);
nHeight = (int) newValue;
} else {
alpha = newValue / icon.getIconWidth();
nWidth = (int) newValue;
nHeight = (int) (icon.getIconHeight() * alpha);
}
BufferedImage image =
new BufferedImage(nWidth, nHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(
icon.getImage(),
0, 0, nWidth, nHeight, null
);
return image;
}
private int getRealHeight() {
return getHeight() - UI_HEIGHT;
}
@Override
public Dimension getSize() {
return new Dimension(getWidth(), getHeight() - UI_HEIGHT);
}
@Override
public void update(Observable o, Object arg) {
this.repaint();
}
private void drawUI(Graphics2D g2d) {
EntityManager em = board.getLevel().getEntityManager();
Color initialColor = g2d.getColor();
/* Rectangle */
g2d.setColor(Color.BLACK);
g2d.fillRect(0, getRealHeight(), getWidth(), UI_HEIGHT);
/* Frise */
int start = 0;
do {
g2d.drawImage(
gameUI,
start, getRealHeight(),
gameUI.getWidth(null), gameUI.getHeight(null),
null
);
start += gameUI.getWidth(null);
} while(start <= getWidth());
/* Bar */
int distance = getWidth() / 4;
int xPosition = distance;
while (xPosition < getWidth()) {
g2d.drawImage(barUI, xPosition, (int)(getRealHeight() + FRISE_HEIGHT),
barUI.getWidth(null), barUI.getHeight(null), null);
xPosition += distance;
}
/* Glutton informations */
if (em.getGlutton() != null) {
Font initialFont = g2d.getFont();
if (fontUI != null) {
g2d.setFont(fontUI);
}
g2d.setColor(Color.white);
FontMetrics fm = g2d.getFontMetrics(fontUI);
int current_distance = 0;
int middle =
getRealHeight() + ((int)FRISE_HEIGHT) +
((getHeight() - getRealHeight() + ((int)FRISE_HEIGHT)) / 2) -
(fm.getHeight() / 2);
// life
g2d.drawString(lifeLabel, current_distance + 5, middle);
int curX = current_distance + fm.stringWidth(lifeLabel) + 30;
for (int i = 0; i < 6; i++) {
if (i < board.getLevel().getEntityManager().getGlutton().getLife())
g2d.drawImage(filledHeart, curX, (middle - (emptyHeart.getHeight(null) / 2) - 5), null);
else
g2d.drawImage(emptyHeart, curX, (middle - (emptyHeart.getHeight(null) / 2) - 5), null);
curX += emptyHeart.getWidth(null) + HEART_PADDING;
}
current_distance += distance + barUI.getWidth(null);
// score
g2d.drawString(scoreLabel, current_distance + 5, middle);
g2d.drawString(
String.format("%05d", board.getLevel().getScore().getValue()),
current_distance + fm.stringWidth(scoreLabel) + 50, middle
);
current_distance += distance + barUI.getWidth(null);
// weapon
g2d.drawString(weaponLabel, current_distance + 5, middle);
g2d.drawString(
"*TODO*",
current_distance + fm.stringWidth(weaponLabel) + 50, middle
);
current_distance += distance + barUI.getWidth(null);
// chrono
g2d.drawString(timeLabel, current_distance + 5, middle);
g2d.drawString(board.getLevel().getChrono().toString(),
current_distance + fm.stringWidth(timeLabel) + 50, middle);
g2d.setFont(initialFont);
}
g2d.setColor(initialColor);
}
private void drawEntity(Graphics2D g2d, EntityView ev) {
Entity entity = ev.getEntity();
AffineTransform t = new AffineTransform();
t.translate(entity.getX(), entity.getY());
t.scale(1, 1);
if (entity instanceof AbstractMovableEntity) {
AbstractMovableEntity ame = (AbstractMovableEntity) entity;
Circle c = ame.getBoundsCircle();
double dx = entity.getCenterX() +
(c.getRadius() * Math.cos(ame.getDirectionRadian()));
double dy = entity.getCenterY() +
(c.getRadius() * Math.sin(ame.getDirectionRadian()));
double angle = ame.getDirectionRadian();
g2d.rotate(angle, entity.getCenterX(), entity.getCenterY());
g2d.drawImage(ev.getCurrentDrawing(), t, null);
g2d.rotate(-angle, entity.getCenterX(), entity.getCenterY());
}
else {
g2d.drawImage(ev.getCurrentDrawing(), t, null);
}
Toolkit.getDefaultToolkit().sync();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D)g;
EntityManager manager = board.getLevel().getEntityManager();
drawUI(graphics2D);
/* Draw the glutton */
if (manager.getGlutton() != null)
drawEntity(graphics2D, manager.getGluttonView());
/* Draw nutritionists */
for (EntityView e : manager.getNutritionistsView())
drawEntity(graphics2D, e);
/* Draw other entities */
for (EntityView e : manager.getOthersView())
drawEntity(graphics2D, e);
if (isPaused()) {
String pause = "Pause";
graphics2D.setFont(font);
graphics2D.setColor(new Color(200, 14, 32));
Rectangle2D rect = graphics2D.getFontMetrics(font)
.getStringBounds(pause, null);
double x = getWidth() - rect.getWidth() - 20;
double y = getHeight() - rect.getHeight();
graphics2D.drawString(pause, (int) x, (int) y);
}
}
}
|
BoardView.java: now draw animation when bitchslapping opponent.
|
src/graphics/BoardView.java
|
BoardView.java: now draw animation when bitchslapping opponent.
|
|
Java
|
mit
|
110a8c68be022658da0a8203eb7ac9045a58b754
| 0
|
beepscore/ArbitraryLinkedList
|
package com.beepscore.android.arbitrarylinkedlist;
import android.util.Log;
import junit.framework.TestCase;
import java.util.HashMap;
/**
* Created by stevebaker on 5/16/15.
*/
public class ArbitraryLinkedListManagerTest extends TestCase {
ArbitraryLinkedListManager listManager;
public void setUp() throws Exception {
super.setUp();
listManager = new ArbitraryLinkedListManager();
}
public Node getSampleListMultipleArbitrary() {
Node a = new Node();
Node b = new Node();
Node c = new Node();
Node d = new Node();
a.value = "A";
b.value = "B";
c.value = "C";
d.value = "D";
a.next = b;
b.next = c;
c.next = d;
d.next = null;
a.arbitrary = c;
d.arbitrary = b;
return a;
}
public Node getSampleListArbitraryLinksToStart() {
Node a = new Node();
Node b = new Node();
Node c = new Node();
Node d = new Node();
a.value = "a";
b.value = "b";
c.value = "c";
d.value = "d";
a.next = b;
b.next = c;
c.next = d;
d.next = null;
c.arbitrary = a;
return a;
}
/*
* Check test data
*/
public void testGetSampleListArbitraryLinksToStart() {
Node startNode = getSampleListArbitraryLinksToStart();
assertNotNull(startNode.next);
assertNotNull(startNode.next.next);
assertNotNull(startNode.next.next.next);
assertNull(startNode.next.next.next.next);
assertEquals("a", startNode.value);
assertEquals("b", startNode.next.value);
}
public void testArbitraryLinkedListManager() {
assertNotNull(listManager);
}
public void testCorrespondingNodes() {
listManager.correspondingNodes = new HashMap<Node, Node>();
Node originalNode = new Node();
listManager.correspondingNodes.put(originalNode, null);
// get value for key
assertNull(listManager.correspondingNodes.get(originalNode));
Node cloneNode = new Node();
listManager.correspondingNodes.put(originalNode, cloneNode);
assertEquals(cloneNode, listManager.correspondingNodes.get(originalNode));
}
public void testCloneOriginalNext() {
Node a = new Node();
Node b = new Node();
Node cloneA = new Node();
a.value = "a";
b.value = "b";
a.next = b;
listManager.correspondingNodes = new HashMap<Node, Node>();
listManager.cloneOriginalNext(a, cloneA);
assertNotNull(cloneA.next);
// cloneOriginalNext doesn't set cloned next node's value
assertNull(cloneA.next.value);
}
public void testCloneList() {
Node startNode = getSampleListArbitraryLinksToStart();
Node cloneStartNode = listManager.cloneList(startNode);
Log.d("correspondingNodes",
listManager.correspondingNodes.toString());
assertEquals(cloneStartNode,
listManager.correspondingNodes.get(startNode));
assertEquals(4, listManager.correspondingNodes.size());
assertNotNull(cloneStartNode.next);
assertNotNull(cloneStartNode.next.next);
assertNotNull(cloneStartNode.next.next.next);
assertNull(cloneStartNode.next.next.next.next);
assertEquals("a", cloneStartNode.value);
assertEquals("b", cloneStartNode.next.value);
assertEquals("c", cloneStartNode.next.next.value);
assertEquals("d", cloneStartNode.next.next.next.value);
}
public void testCloneListArbitraryLinksToStart() {
Node startNode = getSampleListArbitraryLinksToStart();
Node cloneStartNode = listManager.cloneList(startNode);
assertNull(cloneStartNode.arbitrary);
assertNull(cloneStartNode.next.arbitrary);
assertNotNull(cloneStartNode.next.next.arbitrary);
assertNull(cloneStartNode.next.next.next.arbitrary);
assertEquals("c", cloneStartNode.next.next.value);
assertEquals("a", cloneStartNode.next.next.arbitrary.value);
}
public void testCloneListMultipleArbitraryArbitrary() {
Node startNode = getSampleListMultipleArbitrary();
Node cloneStartNode = listManager.cloneList(startNode);
assertNotNull(cloneStartNode.arbitrary);
assertNull(cloneStartNode.next.arbitrary);
assertNull(cloneStartNode.next.next.arbitrary);
assertNotNull(cloneStartNode.next.next.next.arbitrary);
assertEquals("A", cloneStartNode.value);
assertEquals("C", cloneStartNode.arbitrary.value);
assertEquals("D", cloneStartNode.next.next.next.value);
assertEquals("B", cloneStartNode.next.next.next.arbitrary.value);
}
}
|
app/src/androidTest/java/com/beepscore/android/arbitrarylinkedlist/ArbitraryLinkedListManagerTest.java
|
package com.beepscore.android.arbitrarylinkedlist;
import android.util.Log;
import junit.framework.TestCase;
import java.util.HashMap;
/**
* Created by stevebaker on 5/16/15.
*/
public class ArbitraryLinkedListManagerTest extends TestCase {
ArbitraryLinkedListManager listManager;
public void setUp() {
listManager = new ArbitraryLinkedListManager();
}
public Node getSampleListMultipleArbitrary() {
Node a = new Node();
Node b = new Node();
Node c = new Node();
Node d = new Node();
a.value = "A";
b.value = "B";
c.value = "C";
d.value = "D";
a.next = b;
b.next = c;
c.next = d;
d.next = null;
a.arbitrary = c;
d.arbitrary = b;
return a;
}
public Node getSampleListArbitraryLinksToStart() {
Node a = new Node();
Node b = new Node();
Node c = new Node();
Node d = new Node();
a.value = "a";
b.value = "b";
c.value = "c";
d.value = "d";
a.next = b;
b.next = c;
c.next = d;
d.next = null;
c.arbitrary = a;
return a;
}
/*
* Check test data
*/
public void testGetSampleListArbitraryLinksToStart() {
Node startNode = getSampleListArbitraryLinksToStart();
assertNotNull(startNode.next);
assertNotNull(startNode.next.next);
assertNotNull(startNode.next.next.next);
assertNull(startNode.next.next.next.next);
assertEquals("a", startNode.value);
assertEquals("b", startNode.next.value);
}
public void testArbitraryLinkedListManager() {
assertNotNull(listManager);
}
public void testCorrespondingNodes() {
listManager.correspondingNodes = new HashMap<Node, Node>();
Node originalNode = new Node();
listManager.correspondingNodes.put(originalNode, null);
// get value for key
assertNull(listManager.correspondingNodes.get(originalNode));
Node cloneNode = new Node();
listManager.correspondingNodes.put(originalNode, cloneNode);
assertEquals(cloneNode, listManager.correspondingNodes.get(originalNode));
}
public void testCloneOriginalNext() {
Node a = new Node();
Node b = new Node();
Node cloneA = new Node();
a.value = "a";
b.value = "b";
a.next = b;
listManager.correspondingNodes = new HashMap<Node, Node>();
listManager.cloneOriginalNext(a, cloneA);
assertNotNull(cloneA.next);
// cloneOriginalNext doesn't set cloned next node's value
assertNull(cloneA.next.value);
}
public void testCloneList() {
Node startNode = getSampleListArbitraryLinksToStart();
Node cloneStartNode = listManager.cloneList(startNode);
Log.d("correspondingNodes",
listManager.correspondingNodes.toString());
assertEquals(cloneStartNode,
listManager.correspondingNodes.get(startNode));
assertEquals(4, listManager.correspondingNodes.size());
assertNotNull(cloneStartNode.next);
assertNotNull(cloneStartNode.next.next);
assertNotNull(cloneStartNode.next.next.next);
assertNull(cloneStartNode.next.next.next.next);
assertEquals("a", cloneStartNode.value);
assertEquals("b", cloneStartNode.next.value);
assertEquals("c", cloneStartNode.next.next.value);
assertEquals("d", cloneStartNode.next.next.next.value);
}
public void testCloneListArbitraryLinksToStart() {
Node startNode = getSampleListArbitraryLinksToStart();
Node cloneStartNode = listManager.cloneList(startNode);
assertNull(cloneStartNode.arbitrary);
assertNull(cloneStartNode.next.arbitrary);
assertNotNull(cloneStartNode.next.next.arbitrary);
assertNull(cloneStartNode.next.next.next.arbitrary);
assertEquals("c", cloneStartNode.next.next.value);
assertEquals("a", cloneStartNode.next.next.arbitrary.value);
}
public void testCloneListMultipleArbitraryArbitrary() {
Node startNode = getSampleListMultipleArbitrary();
Node cloneStartNode = listManager.cloneList(startNode);
assertNotNull(cloneStartNode.arbitrary);
assertNull(cloneStartNode.next.arbitrary);
assertNull(cloneStartNode.next.next.arbitrary);
assertNotNull(cloneStartNode.next.next.next.arbitrary);
assertEquals("A", cloneStartNode.value);
assertEquals("C", cloneStartNode.arbitrary.value);
assertEquals("D", cloneStartNode.next.next.next.value);
assertEquals("B", cloneStartNode.next.next.next.arbitrary.value);
}
}
|
In ArbitraryLinkedListManagerTest setUp() call super.setUp()
|
app/src/androidTest/java/com/beepscore/android/arbitrarylinkedlist/ArbitraryLinkedListManagerTest.java
|
In ArbitraryLinkedListManagerTest setUp() call super.setUp()
|
|
Java
|
mit
|
86c109c3a34ad27afcc67dd73e8bd9b05a321cd0
| 0
|
asposeemail/Aspose_Email_Java,aspose-email/Aspose.Email-for-Java,asposeemail/Aspose_Email_Java,aspose-email/Aspose.Email-for-Java,aspose-email/Aspose.Email-for-Java,aspose-email/Aspose.Email-for-Java,aspose-email/Aspose.Email-for-Java,asposeemail/Aspose_Email_Java
|
package com.aspose.email.examples.outlook.pst;
import com.aspose.email.FolderInfo;
import com.aspose.email.MapiContact;
import com.aspose.email.MapiMessage;
import com.aspose.email.MessageInfo;
import com.aspose.email.MessageInfoCollection;
import com.aspose.email.PersonalStorage;
import com.aspose.email.examples.Utils;
public class CreateFolderHierarchyUsingStringNotation {
public static void main(String[] args) {
//ExStart: CreateContactInSubFolderOfContacts
String dataDir = Utils.getSharedDataDir(AccessContactInformationFromPSTFile.class) + "outlook/";
PersonalStorage personalStorage = PersonalStorage.create(dataDir + "CreateFolderHierarchyUsingStringNotation.pst", FileFormatVersion.Unicode);
personalStorage.getRootFolder().addSubFolder("Inbox\\Folder1\\Folder2", true);
//ExEnd: CreateFolderHierarchyUsingStringNotation
}
}
|
Examples/src/main/java/com/aspose/email/examples/outlook/pst/CreateFolderHierarchyUsingStringNotation.java
|
package com.aspose.email.examples.outlook.pst;
import com.aspose.email.FolderInfo;
import com.aspose.email.MapiContact;
import com.aspose.email.MapiMessage;
import com.aspose.email.MessageInfo;
import com.aspose.email.MessageInfoCollection;
import com.aspose.email.PersonalStorage;
import com.aspose.email.examples.Utils;
public class CreateFolderHierarchyUsingStringNotation {
public static void main(String[] args) {
String dataDir = Utils.getSharedDataDir(AccessContactInformationFromPSTFile.class) + "outlook/";
PersonalStorage personalStorage = PersonalStorage.create(String + "CreateFolderHierarchyUsingStringNotation.pst", FileFormatVersion.Unicode);
personalStorage.getRootFolder().addSubFolder("Inbox\\Folder1\\Folder2", true);
}
}
|
Examples for Aspose.Email for Java 18.12 added
Examples for Aspose.Email for Java 18.12 added
|
Examples/src/main/java/com/aspose/email/examples/outlook/pst/CreateFolderHierarchyUsingStringNotation.java
|
Examples for Aspose.Email for Java 18.12 added
|
|
Java
|
mit
|
62310c91d5f8612e558dcb6a324c627517e73101
| 0
|
LoicDelorme/Follow-Up-Your-Garden,LoicDelorme/followUpYourGarden
|
package fr.loicdelorme.followUpYourGarden.core.services.exceptions;
import fr.loicdelorme.followUpYourGarden.core.language.MyResourceBundle;
/**
* This exception is thrown if the green level is not between 0 and 255.
*
* @author DELORME Loïc
* @version 1.0.0
*/
@SuppressWarnings("serial")
public class InvalidGroupOfPlantsGreenLevelException extends Exception
{
/**
* This exception is built when the green level is not valid.
*
* @param greenLevelValue
* The invalid green level.
*/
public InvalidGroupOfPlantsGreenLevelException(int greenLevelValue)
{
super(String.format(MyResourceBundle.getBundle().getString("invalidGroupOfPlantsGreenLevelException"), greenLevelValue));
}
}
|
src/fr/loicdelorme/followUpYourGarden/core/services/exceptions/InvalidGroupOfPlantsGreenLevelException.java
|
package fr.loicdelorme.followUpYourGarden.core.services.exceptions;
/**
* This exception is thrown if the green level is not between 0 and 255.
*
* @author DELORME Loïc
* @version 1.0.0
*/
@SuppressWarnings("serial")
public class InvalidGroupOfPlantsGreenLevelException extends Exception
{
/**
* This exception is built when the green level is not valid.
*
* @param greenLevelValue
* The invalid green level.
*/
public InvalidGroupOfPlantsGreenLevelException(int greenLevelValue)
{
super(new StringBuilder().append("The green level (").append(greenLevelValue).append(") is not valid!").toString());
}
}
|
[update] exception.
|
src/fr/loicdelorme/followUpYourGarden/core/services/exceptions/InvalidGroupOfPlantsGreenLevelException.java
|
[update] exception.
|
|
Java
|
epl-1.0
|
531d2c369cd4f6e1c9d76f2c6f8389023f60e4a4
| 0
|
sbrannen/junit-lambda,junit-team/junit-lambda
|
/*
* Copyright 2015-2017 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.platform.commons.util;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.junit.platform.commons.meta.API.Usage.Internal;
import static org.junit.platform.commons.util.CollectionUtils.toUnmodifiableList;
import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP;
import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.TOP_DOWN;
import java.io.File;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.platform.commons.JUnitException;
import org.junit.platform.commons.meta.API;
/**
* Collection of utilities for working with the Java reflection APIs.
*
* <h3>DISCLAIMER</h3>
*
* <p>These utilities are intended solely for usage within the JUnit framework
* itself. <strong>Any usage by external parties is not supported.</strong>
* Use at your own risk!
*
* <p>Some utilities are published via the maintained {@code ReflectionSupport}
* class.
*
* @since 1.0
* @see org.junit.platform.commons.support.ReflectionSupport
*/
@API(Internal)
public final class ReflectionUtils {
///CLOVER:OFF
private ReflectionUtils() {
/* no-op */
}
///CLOVER:ON
/**
* Modes in which a hierarchy can be traversed — for example, when
* searching for methods or fields within a class hierarchy.
*/
public enum HierarchyTraversalMode {
/**
* Traverse the hierarchy using top-down semantics.
*/
TOP_DOWN,
/**
* Traverse the hierarchy using bottom-up semantics.
*/
BOTTOM_UP;
}
// Pattern: [fully qualified class name]#[methodName]((comma-separated list of parameter type names))
private static final Pattern FULLY_QUALIFIED_METHOD_NAME_PATTERN = Pattern.compile("(.+)#([^()]+?)(\\((.*)\\))?");
// Pattern: "[Ljava.lang.String;", "[[[[Ljava.lang.String;", etc.
private static final Pattern VM_INTERNAL_OBJECT_ARRAY_PATTERN = Pattern.compile("^(\\[+)L(.+);$");
/**
* Pattern: "[x", "[[[[x", etc., where x is Z, B, C, D, F, I, J, S, etc.
*
* <p>The pattern intentionally captures the last bracket with the
* capital letter so that the combination can be looked up via
* {@link #classNameToTypeMap}. For example, the last matched group
* will contain {@code "[I"} instead of simply {@code "I"}.
*
* @see Class#getName()
*/
private static final Pattern VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN = //
Pattern.compile("^(\\[+)(\\[[Z,B,C,D,F,I,J,S])$");
// Pattern: "java.lang.String[]", "int[]", "int[][][][]", etc.
private static final Pattern SOURCE_CODE_SYNTAX_ARRAY_PATTERN = Pattern.compile("^([^\\[\\]]+)((\\[\\])+)+$");
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
private static final ClasspathScanner classpathScanner = new ClasspathScanner(
ClassLoaderUtils::getDefaultClassLoader, ReflectionUtils::loadClass);
/**
* Internal cache of common class names mapped to their types.
*/
private static final Map<String, Class<?>> classNameToTypeMap;
/**
* Internal cache of primitive types mapped to their wrapper types.
*/
private static final Map<Class<?>, Class<?>> primitiveToWrapperMap;
static {
// @formatter:off
List<Class<?>> commonTypes = Arrays.asList(
boolean.class,
byte.class,
char.class,
short.class,
int.class,
long.class,
float.class,
double.class,
boolean[].class,
byte[].class,
char[].class,
short[].class,
int[].class,
long[].class,
float[].class,
double[].class,
boolean[][].class,
byte[][].class,
char[][].class,
short[][].class,
int[][].class,
long[][].class,
float[][].class,
double[][].class,
Boolean.class,
Byte.class,
Character.class,
Short.class,
Integer.class,
Long.class,
Float.class,
Double.class,
String.class,
Boolean[].class,
Byte[].class,
Character[].class,
Short[].class,
Integer[].class,
Long[].class,
Float[].class,
Double[].class,
String[].class,
Boolean[][].class,
Byte[][].class,
Character[][].class,
Short[][].class,
Integer[][].class,
Long[][].class,
Float[][].class,
Double[][].class,
String[][].class
);
// @formatter:on
Map<String, Class<?>> classNamesToTypes = new HashMap<>(64);
commonTypes.forEach(type -> {
classNamesToTypes.put(type.getName(), type);
classNamesToTypes.put(type.getCanonicalName(), type);
});
classNameToTypeMap = Collections.unmodifiableMap(classNamesToTypes);
Map<Class<?>, Class<?>> primitivesToWrappers = new HashMap<>(8);
primitivesToWrappers.put(boolean.class, Boolean.class);
primitivesToWrappers.put(byte.class, Byte.class);
primitivesToWrappers.put(char.class, Character.class);
primitivesToWrappers.put(short.class, Short.class);
primitivesToWrappers.put(int.class, Integer.class);
primitivesToWrappers.put(long.class, Long.class);
primitivesToWrappers.put(float.class, Float.class);
primitivesToWrappers.put(double.class, Double.class);
primitiveToWrapperMap = Collections.unmodifiableMap(primitivesToWrappers);
}
public static boolean isPublic(Class<?> clazz) {
return Modifier.isPublic(clazz.getModifiers());
}
public static boolean isPublic(Member member) {
return Modifier.isPublic(member.getModifiers());
}
public static boolean isPrivate(Class<?> clazz) {
return Modifier.isPrivate(clazz.getModifiers());
}
public static boolean isPrivate(Member member) {
return Modifier.isPrivate(member.getModifiers());
}
public static boolean isAbstract(Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
public static boolean isAbstract(Member member) {
return Modifier.isAbstract(member.getModifiers());
}
public static boolean isStatic(Class<?> clazz) {
return Modifier.isStatic(clazz.getModifiers());
}
public static boolean isStatic(Member member) {
return Modifier.isStatic(member.getModifiers());
}
/**
* Determine if the supplied object is an array.
*
* @param obj the object to test; potentially {@code null}
* @return {@code true} if the object is an array
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine if the supplied object can be assigned to the supplied type
* for the purpose of reflective method invocations.
*
* <p>In contrast to {@link Class#isInstance(Object)}, this method returns
* {@code true} if the supplied type represents a primitive type whose
* wrapper matches the supplied object's type.
*
* <p>Returns {@code true} if the supplied object is {@code null} and the
* supplied type does not represent a primitive type.
*
* @param obj the object to test for assignment compatibility; potentially {@code null}
* @param type the type to check against; never {@code null}
* @return {@code true} if the object is assignment compatible
* @see Class#isInstance(Object)
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignableTo(Object obj, Class<?> type) {
Preconditions.notNull(type, "type must not be null");
if (obj == null) {
return !type.isPrimitive();
}
if (type.isInstance(obj)) {
return true;
}
if (type.isPrimitive()) {
return primitiveToWrapperMap.get(type) == obj.getClass();
}
return false;
}
/**
* Get the wrapper type for the supplied primitive type.
*
* @param type the primitive type for which to retrieve the wrapper type
* @return the corresponding wrapper type or {@code null} if the
* supplied type is {@code null} or not a primitive type
*/
public static Class<?> getWrapperType(Class<?> type) {
return primitiveToWrapperMap.get(type);
}
/**
* Create a new instance of the specified {@link Class} by invoking
* the constructor whose argument list matches the types of the supplied
* arguments.
*
* <p>The constructor will be made accessible if necessary, and any checked
* exception will be {@linkplain ExceptionUtils#throwAsUncheckedException masked}
* as an unchecked exception.
*
* @param clazz the class to instantiate; never {@code null}
* @param args the arguments to pass to the constructor none of which may be {@code null}
* @return the new instance
* @see #newInstance(Constructor, Object...)
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static <T> T newInstance(Class<T> clazz, Object... args) {
Preconditions.notNull(clazz, "class must not be null");
Preconditions.notNull(args, "argument array must not be null");
Preconditions.containsNoNullElements(args, "individual arguments must not be null");
try {
Class<?>[] parameterTypes = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);
return newInstance(clazz.getDeclaredConstructor(parameterTypes), args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Create a new instance of type {@code T} by invoking the supplied constructor
* with the supplied arguments.
*
* <p>The constructor will be made accessible if necessary, and any checked
* exception will be {@linkplain ExceptionUtils#throwAsUncheckedException masked}
* as an unchecked exception.
*
* @param constructor the constructor to invoke; never {@code null}
* @param args the arguments to pass to the constructor
* @return the new instance; never {@code null}
* @see #newInstance(Class, Object...)
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static <T> T newInstance(Constructor<T> constructor, Object... args) {
Preconditions.notNull(constructor, "constructor must not be null");
try {
return makeAccessible(constructor).newInstance(args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Invoke the supplied method, making it accessible if necessary and
* {@linkplain ExceptionUtils#throwAsUncheckedException masking} any
* checked exception as an unchecked exception.
*
* @param method the method to invoke; never {@code null}
* @param target the object on which to invoke the method; may be
* {@code null} if the method is {@code static}
* @param args the arguments to pass to the method
* @return the value returned by the method invocation or {@code null}
* if the return type is {@code void}
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static Object invokeMethod(Method method, Object target, Object... args) {
Preconditions.notNull(method, "method must not be null");
Preconditions.condition((target != null || isStatic(method)),
() -> String.format("Cannot invoke non-static method [%s] on a null target.", method.toGenericString()));
try {
return makeAccessible(method).invoke(target, args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Load a class by its <em>primitive name</em> or <em>fully qualified name</em>,
* using the default {@link ClassLoader}.
*
* <p>See {@link #loadClass(String, ClassLoader)} for details on support for
* class names for arrays.
*
* @param name the name of the class to load; never {@code null} or blank
* @see #loadClass(String, ClassLoader)
*/
public static Optional<Class<?>> loadClass(String name) {
return loadClass(name, ClassLoaderUtils.getDefaultClassLoader());
}
/**
* Load a class by its <em>primitive name</em> or <em>fully qualified name</em>,
* using the supplied {@link ClassLoader}.
*
* <p>Class names for arrays may be specified using either the JVM's internal
* String representation (e.g., {@code [[I} for {@code int[][]},
* {@code [Lava.lang.String;} for {@code java.lang.String[]}, etc.) or
* <em>source code syntax</em> (e.g., {@code int[][]}, {@code java.lang.String[]},
* etc.).
*
* @param name the name of the class to load; never {@code null} or blank
* @param classLoader the {@code ClassLoader} to use; never {@code null}
* @see #loadClass(String)
*/
public static Optional<Class<?>> loadClass(String name, ClassLoader classLoader) {
Preconditions.notBlank(name, "Class name must not be null or blank");
Preconditions.notNull(classLoader, "ClassLoader must not be null");
name = name.trim();
if (classNameToTypeMap.containsKey(name)) {
return Optional.of(classNameToTypeMap.get(name));
}
try {
Matcher matcher;
// Primitive arrays such as "[I", "[[[[D", etc.
matcher = VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String brackets = matcher.group(1);
String componentTypeName = matcher.group(2);
// Calculate dimensions by counting brackets.
int dimensions = brackets.length();
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Object arrays such as "[Ljava.lang.String;", "[[[[Ljava.lang.String;", etc.
matcher = VM_INTERNAL_OBJECT_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String brackets = matcher.group(1);
String componentTypeName = matcher.group(2);
// Calculate dimensions by counting brackets.
int dimensions = brackets.length();
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Arrays such as "java.lang.String[]", "int[]", "int[][][][]", etc.
matcher = SOURCE_CODE_SYNTAX_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String componentTypeName = matcher.group(1);
String bracketPairs = matcher.group(2);
// Calculate dimensions by counting bracket pairs.
int dimensions = bracketPairs.length() / 2;
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Fallback to standard VM class loading
return Optional.of(classLoader.loadClass(name));
}
catch (ClassNotFoundException ex) {
return Optional.empty();
}
}
private static Optional<Class<?>> loadArrayType(ClassLoader classLoader, String componentTypeName, int dimensions)
throws ClassNotFoundException {
Class<?> componentType = classNameToTypeMap.containsKey(componentTypeName)
? classNameToTypeMap.get(componentTypeName) : classLoader.loadClass(componentTypeName);
return Optional.of(Array.newInstance(componentType, new int[dimensions]).getClass());
}
/**
* Load a method by its <em>fully qualified name</em>.
*
* <p>The following formats are supported.
*
* <ul>
* <li>{@code [fully qualified class name]#[methodName]}</li>
* <li>{@code [fully qualified class name]#[methodName](parameter type list)}
* </ul>
*
* <p>The <em>parameter type list</em> is a comma-separated list of primitive
* names or fully qualified class names for the types of parameters accepted
* by the method.
*
* <p>See {@link #loadClass(String, ClassLoader)} for details on the supported
* syntax for array parameter types.
*
* <h3>Examples</h3>
*
* <table border="1">
* <tr><th>Method</th><th>Fully Qualified Method Name</th></tr>
* <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars}</td></tr>
* <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars()}</td></tr>
* <tr><td>{@code java.lang.String.equalsIgnoreCase(String)}</td><td>{@code java.lang.String#equalsIgnoreCase(java.lang.String)}</td></tr>
* <tr><td>{@code java.lang.String.substring(int, int)}</td><td>{@code java.lang.String#substring(int, int)}</td></tr>
* <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg([I)}</td></tr>
* <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg(int[])}</td></tr>
* <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply([[D)}</td></tr>
* <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply(double[][])}</td></tr>
* <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process([Ljava.lang.String;)}</td></tr>
* <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process(java.lang.String[])}</td></tr>
* <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process([[Ljava.lang.String;)}</td></tr>
* <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process(java.lang.String[][])}</td></tr>
* </table>
*
* @param fullyQualifiedMethodName the fully qualified name of the method to load;
* never {@code null} or blank
* @return an {@code Optional} containing the method; never {@code null} but
* potentially empty
* @see #getFullyQualifiedMethodName(Class, String, Class...)
*/
public static Optional<Method> loadMethod(String fullyQualifiedMethodName) {
Preconditions.notBlank(fullyQualifiedMethodName, "Fully qualified method name must not be null or blank");
String fqmn = fullyQualifiedMethodName.trim();
Matcher matcher = FULLY_QUALIFIED_METHOD_NAME_PATTERN.matcher(fqmn);
Preconditions.condition(matcher.matches(),
() -> String.format("Fully qualified method name [%s] does not match pattern [%s]", fqmn,
FULLY_QUALIFIED_METHOD_NAME_PATTERN));
String className = matcher.group(1);
String methodName = matcher.group(2);
// Note: group #3 includes the parameter types enclosed in parentheses;
// group #4 contains the actual parameter types.
String parameterTypeNames = matcher.group(4);
Optional<Class<?>> classOptional = loadClass(className);
if (classOptional.isPresent()) {
try {
return findMethod(classOptional.get(), methodName.trim(), parameterTypeNames);
}
catch (Exception ex) {
/* ignore */
}
}
return Optional.empty();
}
/**
* Build the <em>fully qualified method name</em> for the method described by the
* supplied class, method name, and parameter types.
*
* <p>See {@link #loadMethod(String)} for details on the format.
*
* @param clazz the class that declares the method; never {@code null}
* @param methodName the name of the method; never {@code null} or blank
* @param params the parameter types of the method; may be {@code null} or empty
* @return fully qualified method name; never {@code null}
* @see #loadMethod(String)
*/
public static String getFullyQualifiedMethodName(Class<?> clazz, String methodName, Class<?>... params) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
Preconditions.notNull(params, "params must not be null");
return String.format("%s#%s(%s)", clazz.getName(), methodName, ClassUtils.nullSafeToString(params));
}
/**
* Get the outermost instance of the required type, searching recursively
* through enclosing instances.
*
* <p>If the supplied inner object is of the required type, it will simply
* be returned.
*
* @param inner the inner object from which to begin the search; never {@code null}
* @param requiredType the required type of the outermost instance; never {@code null}
* @return an {@code Optional} containing the outermost instance; never {@code null}
* but potentially empty
*/
public static Optional<Object> getOutermostInstance(Object inner, Class<?> requiredType) {
Preconditions.notNull(inner, "inner object must not be null");
Preconditions.notNull(requiredType, "requiredType must not be null");
if (requiredType.isInstance(inner)) {
return Optional.of(inner);
}
Optional<Object> candidate = getOuterInstance(inner);
if (candidate.isPresent()) {
return getOutermostInstance(candidate.get(), requiredType);
}
return Optional.empty();
}
private static Optional<Object> getOuterInstance(Object inner) {
// This is risky since it depends on the name of the field which is nowhere guaranteed
// but has been stable so far in all JDKs
// @formatter:off
return Arrays.stream(inner.getClass().getDeclaredFields())
.filter(field -> field.getName().startsWith("this$"))
.findFirst()
.map(field -> {
try {
return makeAccessible(field).get(inner);
}
catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
return Optional.empty();
}
});
// @formatter:on
}
public static Set<Path> getAllClasspathRootDirectories() {
// This is quite a hack, since sometimes the classpath is quite different
String fullClassPath = System.getProperty("java.class.path");
// @formatter:off
return Arrays.stream(fullClassPath.split(File.pathSeparator))
.map(Paths::get)
.filter(Files::isDirectory)
.collect(toSet());
// @formatter:on
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findAllClassesInClasspathRoot(URI, Predicate, Predicate)
*/
public static List<Class<?>> findAllClassesInClasspathRoot(URI root, Predicate<Class<?>> classTester,
Predicate<String> classNameFilter) {
// unmodifiable since returned by public, non-internal method(s)
return Collections.unmodifiableList(
classpathScanner.scanForClassesInClasspathRoot(root, classTester, classNameFilter));
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findAllClassesInPackage(String, Predicate, Predicate)
*/
public static List<Class<?>> findAllClassesInPackage(String basePackageName, Predicate<Class<?>> classTester,
Predicate<String> classNameFilter) {
// unmodifiable since returned by public, non-internal method(s)
return Collections.unmodifiableList(
classpathScanner.scanForClassesInPackage(basePackageName, classTester, classNameFilter));
}
public static List<Class<?>> findNestedClasses(Class<?> clazz, Predicate<Class<?>> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Set<Class<?>> candidates = new LinkedHashSet<>();
findNestedClasses(clazz, candidates);
return candidates.stream().filter(predicate).collect(toList());
}
private static void findNestedClasses(Class<?> clazz, Set<Class<?>> candidates) {
if (clazz == Object.class || clazz == null) {
return;
}
// Search class hierarchy
candidates.addAll(Arrays.asList(clazz.getDeclaredClasses()));
findNestedClasses(clazz.getSuperclass(), candidates);
// Search interface hierarchy
for (Class<?> interfaceType : clazz.getInterfaces()) {
findNestedClasses(interfaceType, candidates);
}
}
/**
* Get the sole declared {@link Constructor} for the supplied class.
*
* <p>Throws a {@link PreconditionViolationException} if the supplied
* class declares more than one constructor.
*
* @param clazz the class to get the constructor for
* @return the sole declared constructor; never {@code null}
* @see Class#getDeclaredConstructors()
*/
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getDeclaredConstructor(Class<T> clazz) {
Preconditions.notNull(clazz, "Class must not be null");
try {
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
Preconditions.condition(constructors.length == 1,
() -> String.format("Class [%s] must declare a single constructor", clazz.getName()));
return (Constructor<T>) constructors[0];
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
public static Optional<Method> getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
try {
return Optional.ofNullable(clazz.getMethod(methodName, parameterTypes));
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
private static Class<?>[] resolveParameterTypes(String parameterTypeNames) {
if (StringUtils.isBlank(parameterTypeNames)) {
return EMPTY_CLASS_ARRAY;
}
// @formatter:off
return Arrays.stream(parameterTypeNames.split(","))
.map(ReflectionUtils::loadRequiredParameterType)
.toArray(Class[]::new);
// @formatter:on
}
private static Class<?> loadRequiredParameterType(String typeName) {
return loadClass(typeName).orElseThrow(
() -> new JUnitException(String.format("Failed to load parameter type [%s]", typeName)));
}
/**
* Find the first {@link Method} of the supplied class or interface that
* meets the specified criteria, beginning with the specified class or
* interface and traversing up the type hierarchy until such a method is
* found or the type hierarchy is exhausted.
*
* <p>Note, however, that the current algorithm traverses the entire
* type hierarchy even after having found a match.
*
* @param clazz the class or interface in which to find the method; never {@code null}
* @param methodName the name of the method to find; never {@code null} or empty
* @param parameterTypeNames the fully qualified names of the types of parameters
* accepted by the method, if any, provided as a comma-separated list
* @return an {@code Optional} containing the method found; never {@code null}
* but potentially empty if no such method could be found
* @see #findMethod(Class, String, Class...)
* @see HierarchyTraversalMode#BOTTOM_UP
*/
public static Optional<Method> findMethod(Class<?> clazz, String methodName, String parameterTypeNames) {
return findMethod(clazz, methodName, resolveParameterTypes(parameterTypeNames));
}
/**
* Find the first {@link Method} of the supplied class or interface that
* meets the specified criteria, beginning with the specified class or
* interface and traversing up the type hierarchy until such a method is
* found or the type hierarchy is exhausted.
*
* <p>Note, however, that the current algorithm traverses the entire
* type hierarchy even after having found a match.
*
* @param clazz the class or interface in which to find the method; never {@code null}
* @param methodName the name of the method to find; never {@code null} or empty
* @param parameterTypes the types of parameters accepted by the method, if any;
* never {@code null}
* @return an {@code Optional} containing the method found; never {@code null}
* but potentially empty if no such method could be found
* @see #findMethod(Class, String, String)
* @see HierarchyTraversalMode#BOTTOM_UP
*/
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
Predicate<Method> nameAndParameterTypesMatch = (method -> method.getName().equals(methodName)
&& Arrays.equals(method.getParameterTypes(), parameterTypes));
List<Method> candidates = findMethods(clazz, nameAndParameterTypesMatch, BOTTOM_UP);
return (!candidates.isEmpty() ? Optional.of(candidates.get(0)) : Optional.empty());
}
/**
* Find all {@linkplain Method methods} of the supplied class or interface
* that match the specified {@code predicate}, using top-down search semantics
* within the type hierarchy.
*
* @param clazz the class or interface in which to find the methods; never {@code null}
* @param predicate the method filter; never {@code null}
* @return an immutable list of all such methods found; never {@code null}
* @see HierarchyTraversalMode#TOP_DOWN
* @see #findMethods(Class, Predicate, HierarchyTraversalMode)
*/
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate) {
return findMethods(clazz, predicate, TOP_DOWN);
}
/**
* Find all {@linkplain Method methods} of the supplied class or interface
* that match the specified {@code predicate}.
*
* @param clazz the class or interface in which to find the methods; never {@code null}
* @param predicate the method filter; never {@code null}
* @param traversalMode the hierarchy traversal mode; never {@code null}
* @return an immutable list of all such methods found; never {@code null}
* @see org.junit.platform.commons.support.ReflectionSupport#findMethods(Class, Predicate, org.junit.platform.commons.support.HierarchyTraversalMode)
*/
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate,
HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
return findAllMethodsInHierarchy(clazz, traversalMode).stream()
.filter(predicate)
// unmodifiable since returned by public, non-internal method(s)
.collect(toUnmodifiableList());
// @formatter:on
}
/**
* Return all methods in superclass hierarchy except from Object.
*/
private static List<Method> findAllMethodsInHierarchy(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
List<Method> localMethods = Arrays.stream(clazz.getDeclaredMethods())
.filter(method -> !method.isSynthetic())
.collect(toList());
List<Method> superclassMethods = getSuperclassMethods(clazz, traversalMode).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
List<Method> interfaceMethods = getInterfaceMethods(clazz, traversalMode).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
localMethods.sort(ReflectionUtils::defaultMethodSorter);
List<Method> methods = new ArrayList<>();
if (traversalMode == TOP_DOWN) {
methods.addAll(superclassMethods);
methods.addAll(interfaceMethods);
}
methods.addAll(localMethods);
if (traversalMode == BOTTOM_UP) {
methods.addAll(interfaceMethods);
methods.addAll(superclassMethods);
}
return methods;
}
/**
* Method comparator based upon JUnit4 org.junit.internal.MethodSorter implementation.
*/
private static int defaultMethodSorter(Method method1, Method method2) {
String name1 = method1.getName();
String name2 = method2.getName();
int comparison = Integer.compare(name1.hashCode(), name2.hashCode());
if (comparison == 0) {
comparison = name1.compareTo(name2);
if (comparison == 0) {
comparison = method1.toString().compareTo(method2.toString());
}
}
return comparison;
}
/**
* Read the value of a potentially inaccessible field.
*
* <p>If the field does not exist, an exception occurs while reading it, or
* the value of the field is {@code null}, an empty {@link Optional} is
* returned.
*
* @param clazz the class where the field is declared; never {@code null}
* @param fieldName the name of the field; never {@code null} or empty
* @param instance the instance from where the value is to be read; may
* be {@code null} for a static field
*/
public static <T> Optional<Object> readFieldValue(Class<T> clazz, String fieldName, T instance) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(fieldName, "Field name must not be null or blank");
try {
Field field = makeAccessible(clazz.getDeclaredField(fieldName));
return Optional.ofNullable(field.get(instance));
}
catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
return Optional.empty();
}
}
private static List<Method> getInterfaceMethods(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
List<Method> allInterfaceMethods = new ArrayList<>();
for (Class<?> ifc : clazz.getInterfaces()) {
// @formatter:off
List<Method> localMethods = Arrays.stream(ifc.getDeclaredMethods())
.filter(m -> !isAbstract(m))
.collect(toList());
List<Method> subInterfaceMethods = getInterfaceMethods(ifc, traversalMode).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
if (traversalMode == TOP_DOWN) {
allInterfaceMethods.addAll(subInterfaceMethods);
}
allInterfaceMethods.addAll(localMethods);
if (traversalMode == BOTTOM_UP) {
allInterfaceMethods.addAll(subInterfaceMethods);
}
}
return allInterfaceMethods;
}
private static List<Method> getSuperclassMethods(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Class<?> superclass = clazz.getSuperclass();
if (superclass == null || superclass == Object.class) {
return Collections.emptyList();
}
return findAllMethodsInHierarchy(superclass, traversalMode);
}
private static boolean isMethodShadowedByLocalMethods(Method method, List<Method> localMethods) {
return localMethods.stream().anyMatch(local -> isMethodShadowedBy(method, local));
}
private static boolean isMethodShadowedBy(Method upper, Method lower) {
if (!lower.getName().equals(upper.getName())) {
return false;
}
if (lower.getParameterCount() != upper.getParameterCount()) {
return false;
}
// trivial case: parameter types exactly match
if (Arrays.equals(lower.getParameterTypes(), upper.getParameterTypes())) {
return true;
}
// param count is equal, but types do not match exactly: check for method sub-signatures
// https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.2
for (int i = 0; i < lower.getParameterCount(); i++) {
Class<?> lowerType = lower.getParameterTypes()[i];
Class<?> upperType = upper.getParameterTypes()[i];
if (!upperType.isAssignableFrom(lowerType)) {
return false;
}
}
// lower is sub-signature of upper: check for generics in upper method
if (isGeneric(upper)) {
return true;
}
return false;
}
static boolean isGeneric(Method method) {
if (isGeneric(method.getGenericReturnType())) {
return true;
}
for (Type type : method.getGenericParameterTypes()) {
if (isGeneric(type)) {
return true;
}
}
return false;
}
private static boolean isGeneric(Type type) {
return type instanceof TypeVariable || type instanceof GenericArrayType;
}
@SuppressWarnings("deprecation") // "AccessibleObject.isAccessible()" is deprecated in Java 9
public static <T extends AccessibleObject> T makeAccessible(T object) {
if (!object.isAccessible()) {
object.setAccessible(true);
}
return object;
}
/**
* Get the underlying cause of the supplied {@link Throwable}.
*
* <p>If the supplied {@code Throwable} is an instance of
* {@link InvocationTargetException}, this method will be invoked
* recursively with the underlying
* {@linkplain InvocationTargetException#getTargetException() target
* exception}; otherwise, this method simply returns the supplied
* {@code Throwable}.
*/
private static Throwable getUnderlyingCause(Throwable t) {
if (t instanceof InvocationTargetException) {
return getUnderlyingCause(((InvocationTargetException) t).getTargetException());
}
return t;
}
/**
* Return all classes and interfaces that can be used as assignment types
* for instances of the specified {@link Class}, including itself.
*
* @param clazz the {@code Class} to lookup
* @see Class#isAssignableFrom
*/
public static Set<Class<?>> getAllAssignmentCompatibleClasses(Class<?> clazz) {
Preconditions.notNull(clazz, "class must not be null");
Set<Class<?>> result = new LinkedHashSet<>();
getAllAssignmentCompatibleClasses(clazz, result);
return result;
}
private static void getAllAssignmentCompatibleClasses(Class<?> clazz, Set<Class<?>> result) {
for (Class<?> current = clazz; current != null; current = current.getSuperclass()) {
result.add(current);
for (Class<?> interfaceClass : current.getInterfaces()) {
if (!result.contains(interfaceClass)) {
getAllAssignmentCompatibleClasses(interfaceClass, result);
}
}
}
}
}
|
junit-platform-commons/src/main/java/org/junit/platform/commons/util/ReflectionUtils.java
|
/*
* Copyright 2015-2017 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.platform.commons.util;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.junit.platform.commons.meta.API.Usage.Internal;
import static org.junit.platform.commons.util.CollectionUtils.toUnmodifiableList;
import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP;
import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.TOP_DOWN;
import java.io.File;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.platform.commons.JUnitException;
import org.junit.platform.commons.meta.API;
/**
* Collection of utilities for working with the Java reflection APIs.
*
* <h3>DISCLAIMER</h3>
*
* <p>These utilities are intended solely for usage within the JUnit framework
* itself. <strong>Any usage by external parties is not supported.</strong>
* Use at your own risk!
*
* <p>Some utilities are published via the maintained {@code ReflectionSupport}
* class.
*
* @since 1.0
* @see org.junit.platform.commons.support.ReflectionSupport
*/
@API(Internal)
public final class ReflectionUtils {
///CLOVER:OFF
private ReflectionUtils() {
/* no-op */
}
///CLOVER:ON
/**
* Modes in which a hierarchy can be traversed — for example, when
* searching for methods or fields within a class hierarchy.
*/
public enum HierarchyTraversalMode {
/**
* Traverse the hierarchy using top-down semantics.
*/
TOP_DOWN,
/**
* Traverse the hierarchy using bottom-up semantics.
*/
BOTTOM_UP;
}
// Pattern: [fully qualified class name]#[methodName]((comma-separated list of parameter type names))
private static final Pattern FULLY_QUALIFIED_METHOD_NAME_PATTERN = Pattern.compile("(.+)#([^()]+?)(\\((.*)\\))?");
// Pattern: "[Ljava.lang.String;", "[[[[Ljava.lang.String;", etc.
private static final Pattern VM_INTERNAL_OBJECT_ARRAY_PATTERN = Pattern.compile("^(\\[+)L(.+);$");
/**
* Pattern: "[x", "[[[[x", etc., where x is Z, B, C, D, F, I, J, S, etc.
*
* <p>The pattern intentionally captures the last bracket with the
* capital letter so that the combination can be looked up via
* {@link #classNameToTypeMap}. For example, the last matched group
* will contain {@code "[I"} instead of simply {@code "I"}.
*
* @see Class#getName()
*/
private static final Pattern VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN = //
Pattern.compile("^(\\[+)(\\[[Z,B,C,D,F,I,J,S])$");
// Pattern: "java.lang.String[]", "int[]", "int[][][][]", etc.
private static final Pattern SOURCE_CODE_SYNTAX_ARRAY_PATTERN = Pattern.compile("^([^\\[\\]]+)((\\[\\])+)+$");
private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
private static final ClasspathScanner classpathScanner = new ClasspathScanner(
ClassLoaderUtils::getDefaultClassLoader, ReflectionUtils::loadClass);
/**
* Internal cache of common class names mapped to their types.
*/
private static final Map<String, Class<?>> classNameToTypeMap;
/**
* Internal cache of primitive types mapped to their wrapper types.
*/
private static final Map<Class<?>, Class<?>> primitiveToWrapperMap;
static {
// @formatter:off
List<Class<?>> commonTypes = Arrays.asList(
boolean.class,
byte.class,
char.class,
short.class,
int.class,
long.class,
float.class,
double.class,
boolean[].class,
byte[].class,
char[].class,
short[].class,
int[].class,
long[].class,
float[].class,
double[].class,
boolean[][].class,
byte[][].class,
char[][].class,
short[][].class,
int[][].class,
long[][].class,
float[][].class,
double[][].class,
Boolean.class,
Byte.class,
Character.class,
Short.class,
Integer.class,
Long.class,
Float.class,
Double.class,
String.class,
Boolean[].class,
Byte[].class,
Character[].class,
Short[].class,
Integer[].class,
Long[].class,
Float[].class,
Double[].class,
String[].class,
Boolean[][].class,
Byte[][].class,
Character[][].class,
Short[][].class,
Integer[][].class,
Long[][].class,
Float[][].class,
Double[][].class,
String[][].class
);
// @formatter:on
Map<String, Class<?>> classNamesToTypes = new HashMap<>(64);
commonTypes.forEach(type -> {
classNamesToTypes.put(type.getName(), type);
classNamesToTypes.put(type.getCanonicalName(), type);
});
classNameToTypeMap = Collections.unmodifiableMap(classNamesToTypes);
Map<Class<?>, Class<?>> primitivesToWrappers = new HashMap<>(8);
primitivesToWrappers.put(boolean.class, Boolean.class);
primitivesToWrappers.put(byte.class, Byte.class);
primitivesToWrappers.put(char.class, Character.class);
primitivesToWrappers.put(short.class, Short.class);
primitivesToWrappers.put(int.class, Integer.class);
primitivesToWrappers.put(long.class, Long.class);
primitivesToWrappers.put(float.class, Float.class);
primitivesToWrappers.put(double.class, Double.class);
primitiveToWrapperMap = Collections.unmodifiableMap(primitivesToWrappers);
}
public static boolean isPublic(Class<?> clazz) {
return Modifier.isPublic(clazz.getModifiers());
}
public static boolean isPublic(Member member) {
return Modifier.isPublic(member.getModifiers());
}
public static boolean isPrivate(Class<?> clazz) {
return Modifier.isPrivate(clazz.getModifiers());
}
public static boolean isPrivate(Member member) {
return Modifier.isPrivate(member.getModifiers());
}
public static boolean isAbstract(Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
public static boolean isAbstract(Member member) {
return Modifier.isAbstract(member.getModifiers());
}
public static boolean isStatic(Class<?> clazz) {
return Modifier.isStatic(clazz.getModifiers());
}
public static boolean isStatic(Member member) {
return Modifier.isStatic(member.getModifiers());
}
/**
* Determine if the supplied object is an array.
*
* @param obj the object to test; potentially {@code null}
* @return {@code true} if the object is an array
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine if the supplied object can be assigned to the supplied type
* for the purpose of reflective method invocations.
*
* <p>In contrast to {@link Class#isInstance(Object)}, this method returns
* {@code true} if the supplied type represents a primitive type whose
* wrapper matches the supplied object's type.
*
* <p>Returns {@code true} if the supplied object is {@code null} and the
* supplied type does not represent a primitive type.
*
* @param obj the object to test for assignment compatibility; potentially {@code null}
* @param type the type to check against; never {@code null}
* @return {@code true} if the object is assignment compatible
* @see Class#isInstance(Object)
* @see Class#isAssignableFrom(Class)
*/
public static boolean isAssignableTo(Object obj, Class<?> type) {
Preconditions.notNull(type, "type must not be null");
if (obj == null) {
return !type.isPrimitive();
}
if (type.isInstance(obj)) {
return true;
}
if (type.isPrimitive()) {
return primitiveToWrapperMap.get(type) == obj.getClass();
}
return false;
}
/**
* Get the wrapper type for the supplied primitive type.
*
* @param type the primitive type for which to retrieve the wrapper type
* @return the corresponding wrapper type or {@code null} if the
* supplied type is {@code null} or not a primitive type
*/
public static Class<?> getWrapperType(Class<?> type) {
return primitiveToWrapperMap.get(type);
}
/**
* Create a new instance of the specified {@link Class} by invoking
* the constructor whose argument list matches the types of the supplied
* arguments.
*
* <p>The constructor will be made accessible if necessary, and any checked
* exception will be {@linkplain ExceptionUtils#throwAsUncheckedException masked}
* as an unchecked exception.
*
* @param clazz the class to instantiate; never {@code null}
* @param args the arguments to pass to the constructor none of which may be {@code null}
* @return the new instance
* @see #newInstance(Constructor, Object...)
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static <T> T newInstance(Class<T> clazz, Object... args) {
Preconditions.notNull(clazz, "class must not be null");
Preconditions.notNull(args, "argument array must not be null");
Preconditions.containsNoNullElements(args, "individual arguments must not be null");
try {
Class<?>[] parameterTypes = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);
return newInstance(clazz.getDeclaredConstructor(parameterTypes), args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Create a new instance of type {@code T} by invoking the supplied constructor
* with the supplied arguments.
*
* <p>The constructor will be made accessible if necessary, and any checked
* exception will be {@linkplain ExceptionUtils#throwAsUncheckedException masked}
* as an unchecked exception.
*
* @param constructor the constructor to invoke; never {@code null}
* @param args the arguments to pass to the constructor
* @return the new instance; never {@code null}
* @see #newInstance(Class, Object...)
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static <T> T newInstance(Constructor<T> constructor, Object... args) {
Preconditions.notNull(constructor, "constructor must not be null");
try {
return makeAccessible(constructor).newInstance(args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Invoke the supplied method, making it accessible if necessary and
* {@linkplain ExceptionUtils#throwAsUncheckedException masking} any
* checked exception as an unchecked exception.
*
* @param method the method to invoke; never {@code null}
* @param target the object on which to invoke the method; may be
* {@code null} if the method is {@code static}
* @param args the arguments to pass to the method
* @return the value returned by the method invocation or {@code null}
* if the return type is {@code void}
* @see ExceptionUtils#throwAsUncheckedException(Throwable)
*/
public static Object invokeMethod(Method method, Object target, Object... args) {
Preconditions.notNull(method, "method must not be null");
Preconditions.condition((target != null || isStatic(method)),
() -> String.format("Cannot invoke non-static method [%s] on a null target.", method.toGenericString()));
try {
return makeAccessible(method).invoke(target, args);
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
/**
* Load a class by its <em>primitive name</em> or <em>fully qualified name</em>,
* using the default {@link ClassLoader}.
*
* <p>See {@link #loadClass(String, ClassLoader)} for details on support for
* class names for arrays.
*
* @param name the name of the class to load; never {@code null} or blank
* @see #loadClass(String, ClassLoader)
*/
public static Optional<Class<?>> loadClass(String name) {
return loadClass(name, ClassLoaderUtils.getDefaultClassLoader());
}
/**
* Load a class by its <em>primitive name</em> or <em>fully qualified name</em>,
* using the supplied {@link ClassLoader}.
*
* <p>Class names for arrays may be specified using either the JVM's internal
* String representation (e.g., {@code [[I} for {@code int[][]},
* {@code [Lava.lang.String;} for {@code java.lang.String[]}, etc.) or
* <em>source code syntax</em> (e.g., {@code int[][]}, {@code java.lang.String[]},
* etc.).
*
* @param name the name of the class to load; never {@code null} or blank
* @param classLoader the {@code ClassLoader} to use; never {@code null}
* @see #loadClass(String)
*/
public static Optional<Class<?>> loadClass(String name, ClassLoader classLoader) {
Preconditions.notBlank(name, "Class name must not be null or blank");
Preconditions.notNull(classLoader, "ClassLoader must not be null");
name = name.trim();
if (classNameToTypeMap.containsKey(name)) {
return Optional.of(classNameToTypeMap.get(name));
}
try {
Matcher matcher;
// Primitive arrays such as "[I", "[[[[D", etc.
matcher = VM_INTERNAL_PRIMITIVE_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String brackets = matcher.group(1);
String componentTypeName = matcher.group(2);
// Calculate dimensions by counting brackets.
int dimensions = brackets.length();
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Object arrays such as "[Ljava.lang.String;", "[[[[Ljava.lang.String;", etc.
matcher = VM_INTERNAL_OBJECT_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String brackets = matcher.group(1);
String componentTypeName = matcher.group(2);
// Calculate dimensions by counting brackets.
int dimensions = brackets.length();
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Arrays such as "java.lang.String[]", "int[]", "int[][][][]", etc.
matcher = SOURCE_CODE_SYNTAX_ARRAY_PATTERN.matcher(name);
if (matcher.matches()) {
String componentTypeName = matcher.group(1);
String bracketPairs = matcher.group(2);
// Calculate dimensions by counting bracket pairs.
int dimensions = bracketPairs.length() / 2;
return loadArrayType(classLoader, componentTypeName, dimensions);
}
// Fallback to standard VM class loading
return Optional.of(classLoader.loadClass(name));
}
catch (ClassNotFoundException ex) {
return Optional.empty();
}
}
private static Optional<Class<?>> loadArrayType(ClassLoader classLoader, String componentTypeName, int dimensions)
throws ClassNotFoundException {
Class<?> componentType = classNameToTypeMap.containsKey(componentTypeName)
? classNameToTypeMap.get(componentTypeName) : classLoader.loadClass(componentTypeName);
return Optional.of(Array.newInstance(componentType, new int[dimensions]).getClass());
}
/**
* Load a method by its <em>fully qualified name</em>.
*
* <p>The following formats are supported.
*
* <ul>
* <li>{@code [fully qualified class name]#[methodName]}</li>
* <li>{@code [fully qualified class name]#[methodName](parameter type list)}
* </ul>
*
* <p>The <em>parameter type list</em> is a comma-separated list of primitive
* names or fully qualified class names for the types of parameters accepted
* by the method.
*
* <p>See {@link #loadClass(String, ClassLoader)} for details on the supported
* syntax for array parameter types.
*
* <h3>Examples</h3>
*
* <table border="1">
* <tr><th>Method</th><th>Fully Qualified Method Name</th></tr>
* <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars}</td></tr>
* <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars()}</td></tr>
* <tr><td>{@code java.lang.String.equalsIgnoreCase(String)}</td><td>{@code java.lang.String#equalsIgnoreCase(java.lang.String)}</td></tr>
* <tr><td>{@code java.lang.String.substring(int, int)}</td><td>{@code java.lang.String#substring(int, int)}</td></tr>
* <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg([I)}</td></tr>
* <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg(int[])}</td></tr>
* <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply([[D)}</td></tr>
* <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply(double[][])}</td></tr>
* <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process([Ljava.lang.String;)}</td></tr>
* <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process(java.lang.String[])}</td></tr>
* <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process([[Ljava.lang.String;)}</td></tr>
* <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process(java.lang.String[][])}</td></tr>
* </table>
*
* @param fullyQualifiedMethodName the fully qualified name of the method to load;
* never {@code null} or blank
* @return an {@code Optional} containing the method; never {@code null} but
* potentially empty
* @see #getFullyQualifiedMethodName(Class, String, Class...)
*/
public static Optional<Method> loadMethod(String fullyQualifiedMethodName) {
Preconditions.notBlank(fullyQualifiedMethodName, "Fully qualified method name must not be null or blank");
String fqmn = fullyQualifiedMethodName.trim();
Matcher matcher = FULLY_QUALIFIED_METHOD_NAME_PATTERN.matcher(fqmn);
Preconditions.condition(matcher.matches(),
() -> String.format("Fully qualified method name [%s] does not match pattern [%s]", fqmn,
FULLY_QUALIFIED_METHOD_NAME_PATTERN));
String className = matcher.group(1);
String methodName = matcher.group(2);
// Note: group #3 includes the parameter types enclosed in parentheses;
// group #4 contains the actual parameter types.
String parameterTypeNames = matcher.group(4);
Optional<Class<?>> classOptional = loadClass(className);
if (classOptional.isPresent()) {
try {
return findMethod(classOptional.get(), methodName.trim(), parameterTypeNames);
}
catch (Exception ex) {
/* ignore */
}
}
return Optional.empty();
}
/**
* Build the <em>fully qualified method name</em> for the method described by the
* supplied class, method name, and parameter types.
*
* <p>See {@link #loadMethod(String)} for details on the format.
*
* @param clazz the class that declares the method; never {@code null}
* @param methodName the name of the method; never {@code null} or blank
* @param params the parameter types of the method; may be {@code null} or empty
* @return fully qualified method name; never {@code null}
* @see #loadMethod(String)
*/
public static String getFullyQualifiedMethodName(Class<?> clazz, String methodName, Class<?>... params) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
Preconditions.notNull(params, "params must not be null");
return String.format("%s#%s(%s)", clazz.getName(), methodName, ClassUtils.nullSafeToString(params));
}
/**
* Get the outermost instance of the required type, searching recursively
* through enclosing instances.
*
* <p>If the supplied inner object is of the required type, it will simply
* be returned.
*
* @param inner the inner object from which to begin the search; never {@code null}
* @param requiredType the required type of the outermost instance; never {@code null}
* @return an {@code Optional} containing the outermost instance; never {@code null}
* but potentially empty
*/
public static Optional<Object> getOutermostInstance(Object inner, Class<?> requiredType) {
Preconditions.notNull(inner, "inner object must not be null");
Preconditions.notNull(requiredType, "requiredType must not be null");
if (requiredType.isInstance(inner)) {
return Optional.of(inner);
}
Optional<Object> candidate = getOuterInstance(inner);
if (candidate.isPresent()) {
return getOutermostInstance(candidate.get(), requiredType);
}
return Optional.empty();
}
private static Optional<Object> getOuterInstance(Object inner) {
// This is risky since it depends on the name of the field which is nowhere guaranteed
// but has been stable so far in all JDKs
// @formatter:off
return Arrays.stream(inner.getClass().getDeclaredFields())
.filter(field -> field.getName().startsWith("this$"))
.findFirst()
.map(field -> {
try {
return makeAccessible(field).get(inner);
}
catch (SecurityException | IllegalArgumentException | IllegalAccessException ex) {
return Optional.empty();
}
});
// @formatter:on
}
public static Set<Path> getAllClasspathRootDirectories() {
// This is quite a hack, since sometimes the classpath is quite different
String fullClassPath = System.getProperty("java.class.path");
// @formatter:off
return Arrays.stream(fullClassPath.split(File.pathSeparator))
.map(Paths::get)
.filter(Files::isDirectory)
.collect(toSet());
// @formatter:on
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findAllClassesInClasspathRoot(URI, Predicate, Predicate)
*/
public static List<Class<?>> findAllClassesInClasspathRoot(URI root, Predicate<Class<?>> classTester,
Predicate<String> classNameFilter) {
// unmodifiable since returned by public, non-internal method(s)
return Collections.unmodifiableList(
classpathScanner.scanForClassesInClasspathRoot(root, classTester, classNameFilter));
}
/**
* @see org.junit.platform.commons.support.ReflectionSupport#findAllClassesInPackage(String, Predicate, Predicate)
*/
public static List<Class<?>> findAllClassesInPackage(String basePackageName, Predicate<Class<?>> classTester,
Predicate<String> classNameFilter) {
// unmodifiable since returned by public, non-internal method(s)
return Collections.unmodifiableList(
classpathScanner.scanForClassesInPackage(basePackageName, classTester, classNameFilter));
}
public static List<Class<?>> findNestedClasses(Class<?> clazz, Predicate<Class<?>> predicate) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Set<Class<?>> candidates = new LinkedHashSet<>();
findNestedClasses(clazz, candidates);
return candidates.stream().filter(predicate).collect(toList());
}
private static void findNestedClasses(Class<?> clazz, Set<Class<?>> candidates) {
if (clazz == Object.class || clazz == null) {
return;
}
// Search class hierarchy
candidates.addAll(Arrays.asList(clazz.getDeclaredClasses()));
findNestedClasses(clazz.getSuperclass(), candidates);
// Search interface hierarchy
for (Class<?> interfaceType : clazz.getInterfaces()) {
findNestedClasses(interfaceType, candidates);
}
}
/**
* Get the sole declared {@link Constructor} for the supplied class.
*
* <p>Throws a {@link PreconditionViolationException} if the supplied
* class declares more than one constructor.
*
* @param clazz the class to get the constructor for
* @return the sole declared constructor; never {@code null}
* @see Class#getDeclaredConstructors()
*/
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getDeclaredConstructor(Class<T> clazz) {
Preconditions.notNull(clazz, "Class must not be null");
try {
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
Preconditions.condition(constructors.length == 1,
() -> String.format("Class [%s] must declare a single constructor", clazz.getName()));
return (Constructor<T>) constructors[0];
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
public static Optional<Method> getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
try {
return Optional.ofNullable(clazz.getMethod(methodName, parameterTypes));
}
catch (Throwable t) {
throw ExceptionUtils.throwAsUncheckedException(getUnderlyingCause(t));
}
}
private static Class<?>[] resolveParameterTypes(String parameterTypeNames) {
if (StringUtils.isBlank(parameterTypeNames)) {
return EMPTY_CLASS_ARRAY;
}
// @formatter:off
return Arrays.stream(parameterTypeNames.split(","))
.map(ReflectionUtils::loadRequiredParameterType)
.toArray(Class[]::new);
// @formatter:on
}
private static Class<?> loadRequiredParameterType(String typeName) {
return loadClass(typeName).orElseThrow(
() -> new JUnitException(String.format("Failed to load parameter type [%s]", typeName)));
}
/**
* Find the first {@link Method} of the supplied class or interface that
* meets the specified criteria, beginning with the specified class or
* interface and traversing up the type hierarchy until such a method is
* found or the type hierarchy is exhausted.
*
* <p>Note, however, that the current algorithm traverses the entire
* type hierarchy even after having found a match.
*
* @param clazz the class or interface in which to find the method; never {@code null}
* @param methodName the name of the method to find; never {@code null} or empty
* @param parameterTypeNames the fully qualified names of the types of parameters
* accepted by the method, if any, provided as a comma-separated list
* @return an {@code Optional} containing the method found; never {@code null}
* but potentially empty if no such method could be found
* @see #findMethod(Class, String, Class...)
* @see HierarchyTraversalMode#BOTTOM_UP
*/
public static Optional<Method> findMethod(Class<?> clazz, String methodName, String parameterTypeNames) {
return findMethod(clazz, methodName, resolveParameterTypes(parameterTypeNames));
}
/**
* Find the first {@link Method} of the supplied class or interface that
* meets the specified criteria, beginning with the specified class or
* interface and traversing up the type hierarchy until such a method is
* found or the type hierarchy is exhausted.
*
* <p>Note, however, that the current algorithm traverses the entire
* type hierarchy even after having found a match.
*
* @param clazz the class or interface in which to find the method; never {@code null}
* @param methodName the name of the method to find; never {@code null} or empty
* @param parameterTypes the types of parameters accepted by the method, if any;
* never {@code null}
* @return an {@code Optional} containing the method found; never {@code null}
* but potentially empty if no such method could be found
* @see #findMethod(Class, String, String)
* @see HierarchyTraversalMode#BOTTOM_UP
*/
public static Optional<Method> findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(methodName, "Method name must not be null or blank");
Predicate<Method> nameAndParameterTypesMatch = (method -> method.getName().equals(methodName)
&& Arrays.equals(method.getParameterTypes(), parameterTypes));
List<Method> candidates = findMethods(clazz, nameAndParameterTypesMatch, BOTTOM_UP);
return (!candidates.isEmpty() ? Optional.of(candidates.get(0)) : Optional.empty());
}
/**
* Find all {@linkplain Method methods} of the supplied class or interface
* that match the specified {@code predicate}, using top-down search semantics
* within the type hierarchy.
*
* @param clazz the class or interface in which to find the methods; never {@code null}
* @param predicate the method filter; never {@code null}
* @return an immutable list of all such methods found; never {@code null}
* @see HierarchyTraversalMode#TOP_DOWN
* @see #findMethods(Class, Predicate, HierarchyTraversalMode)
*/
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate) {
return findMethods(clazz, predicate, TOP_DOWN);
}
/**
* Find all {@linkplain Method methods} of the supplied class or interface
* that match the specified {@code predicate}.
*
* @param clazz the class or interface in which to find the methods; never {@code null}
* @param predicate the method filter; never {@code null}
* @param traversalMode the hierarchy traversal mode; never {@code null}
* @return an immutable list of all such methods found; never {@code null}
* @see org.junit.platform.commons.support.ReflectionSupport#findMethods(Class, Predicate, org.junit.platform.commons.support.HierarchyTraversalMode)
*/
public static List<Method> findMethods(Class<?> clazz, Predicate<Method> predicate,
HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(predicate, "Predicate must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
return findAllMethodsInHierarchy(clazz, traversalMode).stream()
.filter(predicate)
// unmodifiable since returned by public, non-internal method(s)
.collect(toUnmodifiableList());
// @formatter:on
}
/**
* Return all methods in superclass hierarchy except from Object.
*/
private static List<Method> findAllMethodsInHierarchy(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
// @formatter:off
List<Method> localMethods = Arrays.stream(clazz.getDeclaredMethods())
.filter(method -> !method.isSynthetic())
.collect(toList());
List<Method> superclassMethods = getSuperclassMethods(clazz, traversalMode).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
List<Method> interfaceMethods = getInterfaceMethods(clazz, traversalMode).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
localMethods.sort(ReflectionUtils::defaultMethodSorter);
List<Method> methods = new ArrayList<>();
if (traversalMode == TOP_DOWN) {
methods.addAll(superclassMethods);
methods.addAll(interfaceMethods);
}
methods.addAll(localMethods);
if (traversalMode == BOTTOM_UP) {
methods.addAll(interfaceMethods);
methods.addAll(superclassMethods);
}
return methods;
}
/**
* Method comparator based upon JUnit4 org.junit.internal.MethodSorter implementation.
*/
private static int defaultMethodSorter(Method method1, Method method2) {
if (method1 == method2) {
return 0;
}
String name1 = method1.getName();
String name2 = method2.getName();
int comparison = Integer.compare(name1.hashCode(), name2.hashCode());
if (comparison == 0) {
comparison = name1.compareTo(name2);
if (comparison == 0) {
comparison = method1.toString().compareTo(method2.toString());
}
}
return comparison;
}
/**
* Read the value of a potentially inaccessible field.
*
* <p>If the field does not exist, an exception occurs while reading it, or
* the value of the field is {@code null}, an empty {@link Optional} is
* returned.
*
* @param clazz the class where the field is declared; never {@code null}
* @param fieldName the name of the field; never {@code null} or empty
* @param instance the instance from where the value is to be read; may
* be {@code null} for a static field
*/
public static <T> Optional<Object> readFieldValue(Class<T> clazz, String fieldName, T instance) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notBlank(fieldName, "Field name must not be null or blank");
try {
Field field = makeAccessible(clazz.getDeclaredField(fieldName));
return Optional.ofNullable(field.get(instance));
}
catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
return Optional.empty();
}
}
private static List<Method> getInterfaceMethods(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Preconditions.notNull(clazz, "Class must not be null");
Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null");
List<Method> allInterfaceMethods = new ArrayList<>();
for (Class<?> ifc : clazz.getInterfaces()) {
// @formatter:off
List<Method> localMethods = Arrays.stream(ifc.getDeclaredMethods())
.filter(m -> !isAbstract(m))
.collect(toList());
List<Method> subInterfaceMethods = getInterfaceMethods(ifc, traversalMode).stream()
.filter(method -> !isMethodShadowedByLocalMethods(method, localMethods))
.collect(toList());
// @formatter:on
if (traversalMode == TOP_DOWN) {
allInterfaceMethods.addAll(subInterfaceMethods);
}
allInterfaceMethods.addAll(localMethods);
if (traversalMode == BOTTOM_UP) {
allInterfaceMethods.addAll(subInterfaceMethods);
}
}
return allInterfaceMethods;
}
private static List<Method> getSuperclassMethods(Class<?> clazz, HierarchyTraversalMode traversalMode) {
Class<?> superclass = clazz.getSuperclass();
if (superclass == null || superclass == Object.class) {
return Collections.emptyList();
}
return findAllMethodsInHierarchy(superclass, traversalMode);
}
private static boolean isMethodShadowedByLocalMethods(Method method, List<Method> localMethods) {
return localMethods.stream().anyMatch(local -> isMethodShadowedBy(method, local));
}
private static boolean isMethodShadowedBy(Method upper, Method lower) {
if (!lower.getName().equals(upper.getName())) {
return false;
}
if (lower.getParameterCount() != upper.getParameterCount()) {
return false;
}
// trivial case: parameter types exactly match
if (Arrays.equals(lower.getParameterTypes(), upper.getParameterTypes())) {
return true;
}
// param count is equal, but types do not match exactly: check for method sub-signatures
// https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.2
for (int i = 0; i < lower.getParameterCount(); i++) {
Class<?> lowerType = lower.getParameterTypes()[i];
Class<?> upperType = upper.getParameterTypes()[i];
if (!upperType.isAssignableFrom(lowerType)) {
return false;
}
}
// lower is sub-signature of upper: check for generics in upper method
if (isGeneric(upper)) {
return true;
}
return false;
}
static boolean isGeneric(Method method) {
if (isGeneric(method.getGenericReturnType())) {
return true;
}
for (Type type : method.getGenericParameterTypes()) {
if (isGeneric(type)) {
return true;
}
}
return false;
}
private static boolean isGeneric(Type type) {
return type instanceof TypeVariable || type instanceof GenericArrayType;
}
@SuppressWarnings("deprecation") // "AccessibleObject.isAccessible()" is deprecated in Java 9
public static <T extends AccessibleObject> T makeAccessible(T object) {
if (!object.isAccessible()) {
object.setAccessible(true);
}
return object;
}
/**
* Get the underlying cause of the supplied {@link Throwable}.
*
* <p>If the supplied {@code Throwable} is an instance of
* {@link InvocationTargetException}, this method will be invoked
* recursively with the underlying
* {@linkplain InvocationTargetException#getTargetException() target
* exception}; otherwise, this method simply returns the supplied
* {@code Throwable}.
*/
private static Throwable getUnderlyingCause(Throwable t) {
if (t instanceof InvocationTargetException) {
return getUnderlyingCause(((InvocationTargetException) t).getTargetException());
}
return t;
}
/**
* Return all classes and interfaces that can be used as assignment types
* for instances of the specified {@link Class}, including itself.
*
* @param clazz the {@code Class} to lookup
* @see Class#isAssignableFrom
*/
public static Set<Class<?>> getAllAssignmentCompatibleClasses(Class<?> clazz) {
Preconditions.notNull(clazz, "class must not be null");
Set<Class<?>> result = new LinkedHashSet<>();
getAllAssignmentCompatibleClasses(clazz, result);
return result;
}
private static void getAllAssignmentCompatibleClasses(Class<?> clazz, Set<Class<?>> result) {
for (Class<?> current = clazz; current != null; current = current.getSuperclass()) {
result.add(current);
for (Class<?> interfaceClass : current.getInterfaces()) {
if (!result.contains(interfaceClass)) {
getAllAssignmentCompatibleClasses(interfaceClass, result);
}
}
}
}
}
|
Remove same instance short-cut as no duplicates are possible here
|
junit-platform-commons/src/main/java/org/junit/platform/commons/util/ReflectionUtils.java
|
Remove same instance short-cut as no duplicates are possible here
|
|
Java
|
epl-1.0
|
3b197859fc6fdfbd2c0b89b98cb1182d1fb374af
| 0
|
RadicalZephyr/ev3java
|
/* Program name: Main
Description: A wall-following robot
Interesting Features:
Hardware:
Port Sensor
1 Touch
2 Ultrasonic
4 Touch
Port Motor
B Left
C Right
Course Number: CSCI 372, Fall 2013
Student Name: Geoff Shannon
References: lejos
*/
package wall_follower;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3TouchSensor;
import lejos.hardware.sensor.EV3UltrasonicSensor;
import lejos.hardware.motor.Motor;
import lejos.hardware.motor.NXTRegulatedMotor;
import lejos.hardware.Button;
import lejos.hardware.LCD;
import lejos.hardware.Sound;
import lejos.robotics.SampleProvider;
import lejos.utility.Delay;
import java.util.List;
import java.util.ArrayList;
public class Main
{
private EV3TouchSensor leftTouch;
private EV3TouchSensor rightTouch;
private NXTRegulatedMotor leftMotor;
private NXTRegulatedMotor rightMotor;
private EV3UltrasonicSensor distance;
private SampleProvider distanceSampler;
public static void main(String[] args) {
Main current = new Main();
boolean done = false;
LCD.clear();
current.promptForStartPush();
current.followWall();
LCD.clear();
LCD.drawString("Done!", 1, 1);
Delay.msDelay(1000);
}
public Main() {
setupSensors();
setupMotors();
}
void setupSensors() {
leftTouch = new EV3TouchSensor(SensorPort.S4);
rightTouch = new EV3TouchSensor(SensorPort.S3);
distance = new EV3UltrasonicSensor(SensorPort.S1);
distance.enable();
distanceSampler = distance.getDistanceMode();
}
void setupMotors() {
leftMotor = Motor.C;
rightMotor = Motor.B;
leftMotor.setAcceleration(3000);
rightMotor.setAcceleration(3000);
leftMotor.setSpeed(200);
rightMotor.setSpeed(200);
}
void promptForStartPush() {
Sound.twoBeeps();
Sound.beep();
LCD.clear();
LCD.drawString("Please push any", 1, 1);
LCD.drawString("button to begin.", 1, 3);
Button.waitForAnyPress();
LCD.clear();
LCD.drawString("Running...", 1, 1);
}
void startMotors() {
leftMotor.backward();
rightMotor.backward();
}
void stopMotors() {
leftMotor.stop();
rightMotor.stop();
leftMotor.flt();
rightMotor.flt();
}
float checkDistance() {
float[] distance = new float[1];
distanceSampler.fetchSample(distance, 0);
return distance[0];
}
void followWall() {
startMotors();
ArrayList<Move> moves = new ArrayList<Move>();
SensorReading prevReading;
SensorReading curReading = readSensors();
Move move;
boolean done = false;
while (!done) {
move = chooseMove(moves, curReading);
execute(move);
prevReading = curReading;
curReading = readSensors();
if (lastMoveWasGood(prevReading, curReading)) {
}
if (Button.readButtons() != 0) {
done = true;
}
}
}
Move chooseMove(List<Move> moves, SensorReading reading) {
return moves.get(0);
}
void execute(Move move) {
}
SensorReading readSensors() {
SensorReading r = new SensorReading();
r.distance = checkDistance();
r.leftTouching = leftTouch.isPressed();
r.rightTouching = rightTouch.isPressed();
return r;
}
boolean lastMoveWasGood(SensorReading previous,
SensorReading current) {
return false;
}
private class SensorReading {
public float distance;
public boolean leftTouching;
public boolean rightTouching;
}
private class Move {
}
}
|
src/java/wall_follower/Main.java
|
/* Program name: Main
Description: A wall-following robot
Interesting Features:
Hardware:
Port Sensor
1 Touch
2 Ultrasonic
4 Touch
Port Motor
B Left
C Right
Course Number: CSCI 372, Fall 2013
Student Name: Geoff Shannon
References: lejos
*/
package wall_follower;
import lejos.hardware.port.SensorPort;
import lejos.hardware.sensor.EV3TouchSensor;
import lejos.hardware.sensor.EV3UltrasonicSensor;
import lejos.hardware.motor.Motor;
import lejos.hardware.motor.NXTRegulatedMotor;
import lejos.hardware.Button;
import lejos.hardware.LCD;
import lejos.hardware.Sound;
import lejos.robotics.SampleProvider;
import lejos.utility.Delay;
public class Main
{
private EV3TouchSensor leftTouch;
private EV3TouchSensor rightTouch;
private NXTRegulatedMotor leftMotor;
private NXTRegulatedMotor rightMotor;
private EV3UltrasonicSensor distance;
private SampleProvider distanceSampler;
public static void main(String[] args) {
Main current = new Main();
boolean done = false;
LCD.clear();
current.promptForStartPush();
current.followWall();
LCD.clear();
LCD.drawString("Done!", 1, 1);
Delay.msDelay(1000);
}
public Main() {
setupSensors();
setupMotors();
}
void setupSensors() {
leftTouch = new EV3TouchSensor(SensorPort.S4);
rightTouch = new EV3TouchSensor(SensorPort.S3);
distance = new EV3UltrasonicSensor(SensorPort.S1);
distance.enable();
distanceSampler = distance.getDistanceMode();
}
void setupMotors() {
leftMotor = Motor.C;
rightMotor = Motor.B;
leftMotor.setAcceleration(3000);
rightMotor.setAcceleration(3000);
leftMotor.setSpeed(200);
rightMotor.setSpeed(200);
}
void promptForStartPush() {
Sound.twoBeeps();
Sound.beep();
LCD.clear();
LCD.drawString("Please push any", 1, 1);
LCD.drawString("button to begin.", 1, 3);
Button.waitForAnyPress();
LCD.clear();
LCD.drawString("Running...", 1, 1);
}
void startMotors() {
leftMotor.backward();
rightMotor.backward();
}
void stopMotors() {
leftMotor.stop();
rightMotor.stop();
leftMotor.flt();
rightMotor.flt();
}
float checkDistance() {
float[] distance = new float[1];
distanceSampler.fetchSample(distance, 0);
return distance[0];
}
void followWall() {
startMotors();
SensorReading prevReading = readSensors();
SensorReading curReading = readSensors();
boolean done = false;
while (!done) {
prevReading = curReading;
curReading = readSensors();
evaluateLastMove(prevReading, curReading);
if (Button.readButtons() != 0) {
done = true;
}
}
}
SensorReading readSensors() {
SensorReading r = new SensorReading();
r.distance = checkDistance();
r.leftTouching = leftTouch.isPressed();
r.rightTouching = rightTouch.isPressed();
return r;
}
void evaluateLastMove(SensorReading previous, SensorReading current) {
}
private class SensorReading {
public float distance;
public boolean leftTouching;
public boolean rightTouching;
}
private class Move {
}
}
|
Stub out the rest of followWall loop
|
src/java/wall_follower/Main.java
|
Stub out the rest of followWall loop
|
|
Java
|
agpl-3.0
|
a3f0115ea71ec0f27528f53d5b7cfff3c24b4ff6
| 0
|
acontes/programming,paraita/programming,mnip91/proactive-component-monitoring,mnip91/proactive-component-monitoring,acontes/programming,ow2-proactive/programming,mnip91/programming-multiactivities,ow2-proactive/programming,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,PaulKh/scale-proactive,jrochas/scale-proactive,fviale/programming,PaulKh/scale-proactive,lpellegr/programming,paraita/programming,lpellegr/programming,fviale/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,jrochas/scale-proactive,lpellegr/programming,acontes/programming,acontes/programming,PaulKh/scale-proactive,jrochas/scale-proactive,jrochas/scale-proactive,acontes/programming,acontes/programming,fviale/programming,lpellegr/programming,mnip91/programming-multiactivities,ow2-proactive/programming,fviale/programming,paraita/programming,ow2-proactive/programming,jrochas/scale-proactive,acontes/programming,jrochas/scale-proactive,paraita/programming,fviale/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,lpellegr/programming,fviale/programming,ow2-proactive/programming,mnip91/proactive-component-monitoring,lpellegr/programming,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,mnip91/proactive-component-monitoring,mnip91/programming-multiactivities,ow2-proactive/programming,paraita/programming,mnip91/programming-multiactivities,paraita/programming,jrochas/scale-proactive
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core.component.control;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.etsi.uri.gcm.api.type.GCMInterfaceType;
import org.etsi.uri.gcm.util.GCM;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.Interface;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.IllegalBindingException;
import org.objectweb.fractal.api.control.IllegalContentException;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;
import org.objectweb.fractal.api.control.LifeCycleController;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.fractal.api.type.InterfaceType;
import org.objectweb.fractal.api.type.TypeFactory;
import org.objectweb.fractal.util.Fractal;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.component.Constants;
import org.objectweb.proactive.core.component.ItfStubObject;
import org.objectweb.proactive.core.component.NFBinding;
import org.objectweb.proactive.core.component.NFBindings;
import org.objectweb.proactive.core.component.PAInterface;
import org.objectweb.proactive.core.component.Utils;
import org.objectweb.proactive.core.component.componentcontroller.HostComponentSetter;
import org.objectweb.proactive.core.component.exceptions.NoSuchComponentException;
import org.objectweb.proactive.core.component.identity.PAComponent;
import org.objectweb.proactive.core.component.identity.PAComponentImpl;
import org.objectweb.proactive.core.component.representative.ItfID;
import org.objectweb.proactive.core.component.representative.PAComponentRepresentative;
import org.objectweb.proactive.core.component.representative.PAComponentRepresentativeImpl;
import org.objectweb.proactive.core.component.representative.PANFComponentRepresentative;
import org.objectweb.proactive.core.component.type.PAComponentType;
import org.objectweb.proactive.core.component.type.PAGCMInterfaceType;
import org.objectweb.proactive.core.component.type.PAGCMTypeFactoryImpl;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* The class implementing the membrane controller.
*
*
* @author The ProActive Team
*
*/
public class PAMembraneControllerImpl extends AbstractPAController implements PAMembraneController,
Serializable, ControllerStateDuplication {
protected static Logger logger = ProActiveLogger.getLogger(Loggers.COMPONENTS);
private Map<String, Component> nfComponents;
private NFBindings nfBindings;//TODO : This structure has to be updated every time a with the membrane is added or removed
private String membraneState;
public PAMembraneControllerImpl(Component owner) {
super(owner);
nfComponents = new HashMap<String, Component>();
membraneState = MEMBRANE_STOPPED;
nfBindings = new NFBindings();
}
@Override
protected void setControllerItfType() {
try {
setItfType(PAGCMTypeFactoryImpl.instance().createFcItfType(Constants.MEMBRANE_CONTROLLER,
PAMembraneController.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE));
} catch (InstantiationException e) {
throw new ProActiveRuntimeException("cannot create controller type : " +
this.getClass().getName());
}
}
private void checkCompatibility(Interface clientItf, Interface serverItf) throws IllegalBindingException {
PAGCMInterfaceType clientItfType = (PAGCMInterfaceType) clientItf.getFcItfType();
try {
if (Utils.isGCMMulticastItf(clientItfType.getFcItfName(), clientItf.getFcItfOwner())) {
GCM.getMulticastController(owner).ensureGCMCompatibility(clientItfType, serverItf);
}
if (Utils.isGCMGathercastItf(serverItf)) {
GCM.getGathercastController(owner).ensureGCMCompatibility(clientItfType, serverItf);
} else if (Utils.isGCMSingletonItf(clientItfType.getFcItfName(), clientItf.getFcItfOwner())) {
PAGCMInterfaceType serverItfType = (PAGCMInterfaceType) serverItf.getFcItfType();
Class<?> cl = Class.forName(clientItfType.getFcItfSignature());
Class<?> sr = Class.forName(serverItfType.getFcItfSignature());
if (!cl.isAssignableFrom(sr)) {
throw new IllegalBindingException("Signatures of interfaces don't correspond (" +
clientItfType.getFcItfSignature() + " and " + serverItfType.getFcItfSignature() + ")");
}
}
} catch (ClassNotFoundException cnfe) {
throw new IllegalBindingException(cnfe.getMessage());
} catch (NoSuchInterfaceException nsie) {
throw new IllegalBindingException(nsie.getMessage());
}
}
/**
* Adds a NF component to the membrane.<br/>
* For adding a NF component B to the membrane of component A, the lifecycle and membrane of A
* must be stopped, and the membrane of B must be started.
*/
public void nfAddFcSubComponent(Component component) throws IllegalContentException,
IllegalLifeCycleException {
// To perform reconfigurations inside the membrane, both the Lifecycle and the Membrane must be STOPPED.
try {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED) ||
GCM.getGCMLifeCycleController(owner).getFcState().equals(LifeCycleController.STARTED)) {
throw new IllegalLifeCycleException(
"To perform reconfiguration inside the membrane, the lifecycle and the membrane must be stopped");
}
} catch (NoSuchInterfaceException e) {
// Without a life cycle controller, the default activity of a GCM component does not work
}
// However, the membrane of the NF component that is going to be added, must be started (why?)
checkMembraneIsStarted(component);
// The component to add must be NF
PAComponent ownerRepresentative = owner.getRepresentativeOnThis();
String name = null;
if (!(component instanceof PANFComponentRepresentative)) {
throw new IllegalContentException(
"Only non-functional components can be added to the membrane");
}
try {
name = GCM.getNameController(component).getFcName();
} catch (NoSuchInterfaceException e) {
IllegalContentException ice = new IllegalContentException(
"The component has to implement the name-controller interface");
ice.initCause(e);
throw ice;
}
// Names must be unique among NF components
if (nfComponents.containsKey(name)) {
throw new IllegalContentException("The name of the component is already assigned to an existing non functional component");
}
// Set the Host component using the 'super-controller' (actually, the extended PASuperController)
try {
Utils.getPASuperController(component).addParent(ownerRepresentative);
} catch (NoSuchInterfaceException e) {
// Nothing to do. If the component doesn't have 'super-controller', it will not reference the host component
}
// cruz: What's the difference between the PA 'super-controller' and 'host-setter-controller' ?
// Set the Host Component using the 'host-setter-controller'
try {
HostComponentSetter hcs = (HostComponentSetter) component.getFcInterface(Constants.HOST_SETTER_CONTROLLER);
hcs.setHostComponent(ownerRepresentative);
} catch (NoSuchInterfaceException e) {
logger.warn("The non-functional component " + name + " doesn't have any reference on its host component");
}
//Add the component inside the Map
nfComponents.put(name, component);
}
private void bindNfServerWithNfClient(String clItf, PAInterface srItf) throws IllegalBindingException,
NoSuchInterfaceException, IllegalLifeCycleException {
PAInterface cl = null;
try {
cl = (PAInterface) owner.getFcInterface(clItf);
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
// Check whether the binding exists
if (nfBindings.hasBinding("membrane", clItf, "membrane", srItf.getFcItfName())) {
throw new IllegalBindingException("The binding : membrane." + clItf + "--->" + "membrane." +
srItf.getFcItfName() + " already exists");
}
if (!tryToBindMulticastInterface(cl, srItf)) {
cl.setFcItfImpl(srItf);
nfBindings.addNormalBinding(new NFBinding(cl, clItf, srItf, "membrane", "membrane"));
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clItf);
}
}
}
private void bindNfServerWithNfCServer(String clItf, PAInterface srItf) throws IllegalBindingException,
NoSuchInterfaceException, IllegalLifeCycleException {
PAInterface cl = null;
Component srOwner = srItf.getFcItfOwner();
// Check whether the binding exists
try {
if (nfBindings.hasBinding("membrane", clItf, GCM.getNameController(srOwner).getFcName(), srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : membrane." + clItf + "--->" +
GCM.getNameController(srOwner).getFcName() + "." + srItf.getFcItfName() +
" already exists");
}
} catch (NoSuchInterfaceException e1) {
e1.printStackTrace();
}
try {
cl = (PAInterface) owner.getFcInterface(clItf);
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
try {// In this case, the nf component controller gets the state of a controller and duplicates it.
ControllerStateDuplication dup = (ControllerStateDuplication) srOwner
.getFcInterface(Constants.CONTROLLER_STATE_DUPLICATION);
Object ob = cl.getFcItfImpl();
if (ob instanceof ControllerStateDuplication) {// The controller is implemented with an object
dup.duplicateController(((ControllerStateDuplication) ob).getState().getStateObject());
} else {// The controller is implemented with a NF component?
if (ob instanceof PAInterface) {
Component cmp = ((PAInterface) ob).getFcItfOwner();
ControllerStateDuplication duplicated = (ControllerStateDuplication) cmp
.getFcInterface(Constants.CONTROLLER_STATE_DUPLICATION);
dup.duplicateController(duplicated.getState().getStateObject());
}
}
} catch (NoSuchInterfaceException e) {
logger.debug("The component controller doesn't have a duplication-controller interface");
}
if (!tryToBindMulticastInterface(cl, srItf)) {
cl.setFcItfImpl(srItf);
try {
nfBindings.addServerAliasBinding(new NFBinding(cl, clItf, srItf, "membrane", Fractal
.getNameController(srOwner).getFcName()));
} catch (NoSuchInterfaceException e) {
logger.warn("Could not add a binding : the component does not not have a Name Controller");
}
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clItf);
}
}
}
private void bindNfClientWithFCServer(String clItf, PAInterface srItf) throws IllegalBindingException,
NoSuchInterfaceException, IllegalLifeCycleException {
PAInterface cl = null;
Component srOwner = null;
try {
cl = (PAInterface) owner.getFcInterface(clItf);
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
srOwner = srItf.getFcItfOwner();
// Check whether the binding exists
try {
if (nfBindings.hasBinding("membrane", clItf, GCM.getNameController(srOwner).getFcName(), srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : membrane." + clItf + "--->" +
GCM.getNameController(srOwner).getFcName() + "." + srItf.getFcItfName() +
" already exists");
}
} catch (NoSuchInterfaceException e1) {
e1.printStackTrace();
}
if (!tryToBindMulticastInterface(cl, srItf)) {
cl.setFcItfImpl(srItf);
try {
nfBindings.addNormalBinding(new NFBinding(cl, clItf, srItf, "membrane", Fractal
.getNameController(srOwner).getFcName()));
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clItf);
}
}
}
private void bindClientNFWithInternalServerNF(String clItf, PAInterface srItf)
throws IllegalBindingException, NoSuchInterfaceException, IllegalLifeCycleException {
bindNfServerWithNfClient(clItf, srItf);
}
/**
* Binding of NF interfaces, or of NF components.
*/
public void nfBindFc(String clientItf, String serverItf) throws NoSuchInterfaceException,
IllegalLifeCycleException, IllegalBindingException, NoSuchComponentException {
ComponentAndInterface client = getComponentAndInterface(clientItf);
ComponentAndInterface server = getComponentAndInterface(serverItf);
PAInterface clItf = (PAInterface) client.getInterface();
PAGCMInterfaceType clItfType = (PAGCMInterfaceType) clItf.getFcItfType();
PAInterface srItf = (PAInterface) server.getInterface();
PAGCMInterfaceType srItfType = (PAGCMInterfaceType) srItf.getFcItfType();
// the membrane of the host component must be stopped to perform bindings
checkMembraneIsStopped();
checkCompatibility(clItf, srItf);
if (srItf instanceof ItfStubObject) {
((ItfStubObject) srItf).setSenderItfID(new ItfID(clientItf, ((PAComponent) clItf.getFcItfOwner())
.getID()));
}
if (client.getComponent() == null) { // The client interface belongs to the membrane
if (!clItfType.isFcClientItf()) { // The client interface is a server one (internal or external) belonging to the membrane
if (server.getComponent() == null) { // The server interface belongs to the membrane
if (srItfType.isFcClientItf()) { // The (server) interface is client (internal or external) belonging to the membrane
if (clItfType.isInternal()) { // Binding between internal server and internal client is forbidden inside the membrane
if (srItfType.isInternal()) { // Trying to bind an internal server NF interface with an internal client NF interface
throw new IllegalBindingException(
"Internal NF server interfaces can not be bound to internal NF client interfaces");
} else { //The server interface belongs to the membrane, and is external client
bindNfServerWithNfClient(clItf.getFcItfName(), srItf); // Internal NF server with external NF client
}
} else { // The client itf is a NF external server
if (srItfType.isInternal()) {
bindNfServerWithNfClient(clItf.getFcItfName(), srItf); // External NF server with internal NF client
} else { // Trying to bind an external server NF interface with an external client NF interface
throw new IllegalBindingException(
"External NF server interfaces can not be bound to external NF client interfaces");
}
}
}
} else { // The server interface belongs to a component. Possible bindings : External/Internal NF server with a server of a NF component
if (srItfType.isFcClientItf() ||
!(server.getComponent() instanceof PANFComponentRepresentative) ||
srItfType.getFcItfName().endsWith("-controller")) {
throw new IllegalBindingException(
"NF server interfaces can be bound only to server F interfaces of NF components");
} else { // NF server interface with a server interface of a NF component : Server alias binding
bindNfServerWithNfCServer(clItf.getFcItfName(), srItf);
}
}
} else { // The client interface is a NF client one. For this method it can be only an internal NF client. It can be bound only to a NF interface of a F component.
if (!clItfType.isInternal()) {
throw new IllegalBindingException(
"With this method, only internal NF client interfaces can be bound");
}
if (server.getComponent() == null) {// The server interface belongs to the membrane. In this case, this interface HAS to be an internal NF server
if (srItfType.getFcItfName().endsWith("-controller") && srItfType.isInternal()) {
bindClientNFWithInternalServerNF(clItfType.getFcItfName(), srItf);// NF internal client ---- NF internal server
} else {
throw new IllegalBindingException(
"Inside the membrane, internal NF interfaces can be bound only with NF internal server of NF interface of F inner components");
}
} else {
if ((server.getComponent() instanceof PANFComponentRepresentative) ||
!(srItfType.getFcItfName().endsWith("-controller"))) {
throw new IllegalBindingException(
"With this method, an internal client NF interface can only be bound to a NF interface of a F inner component");
} else { // OK for binding client NF internal with NF external of F component
bindNfClientWithFCServer(clItf.getFcItfName(), srItf);
}
}
}
} else { // The client interface belongs to a (NF or F)component
if (!clItfType.isFcClientItf()) {
throw new IllegalBindingException("Only a client interface of a NF/F can be bound");
} else {
if (client.getComponent() instanceof PANFComponentRepresentative) { // All possible bindings for client interfaces of NF components
checkMembraneIsStarted(client.getComponent());
if (server.getComponent() == null) { // A client interface of a NF component to a NF external/internal client
if (srItfType.isFcClientItf() && srItfType.getFcItfName().endsWith("-controller")) { // Connection to any (internal/external) client NF interface
GCM.getBindingController(client.getComponent()).bindFc(clItfType.getFcItfName(),
owner.getRepresentativeOnThis().getFcInterface(srItfType.getFcItfName()));// Alias client binding
// Check whether the binding already exist
if (nfBindings.hasBinding(GCM.getNameController(client.getComponent())
.getFcName(), client.getInterface().getFcItfName(), "membrane", srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : " +
GCM.getNameController(client.getComponent()).getFcName() + "." + clItf +
"--->membrane." + srItf.getFcItfName() + " already exists");
}
nfBindings.addClientAliasBinding(new NFBinding(null, clItfType.getFcItfName(),
srItf, GCM.getNameController(client.getComponent()).getFcName(), "membrane"));
} else { // Exception!!
throw new IllegalBindingException(
"A NF component can only be bound to client NF interfaces of the membrane");
}
} else { // Binding of 2 NF components
if (!(server.getComponent() instanceof PANFComponentRepresentative)) { //The server component has to be a NF one
throw new IllegalBindingException(
"A NF component can only be bound to another NF (not F) component");
} else { // Last verification before binding
if (srItfType.isFcClientItf()) {
throw new IllegalBindingException(
"When binding two NF components, a client interface must be bound to a server one");
} else { // Call to binding controller of the component that has the client interface
GCM.getBindingController(client.getComponent()).bindFc(
clItfType.getFcItfName(),
server.getComponent().getFcInterface(srItfType.getFcItfName()));
}
}
}
} else { // Binding for NF client interfaces of inner F components
if (server.getComponent() == null) {
if (!srItfType.isFcClientItf() && srItfType.isInternal()) { // External client NF interface only bound to inner server NF interface
// No need to check the membrane state of Host component
Utils.getPAMembraneController(client.getComponent()).nfBindFc(
clItfType.getFcItfName(),
owner.getRepresentativeOnThis().getFcInterface(srItfType.getFcItfName()));
// Check whether this binding already exist
if (nfBindings.hasBinding(GCM.getNameController(client.getComponent())
.getFcName(), client.getInterface().getFcItfName(), "membrane", srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : " +
GCM.getNameController(client.getComponent()).getFcName() + "." + clItf +
"--->membrane." + srItf.getFcItfName() + " already exists");
}
nfBindings.addNormalBinding(new NFBinding(clItf, clItfType.getFcItfName(), srItf,
GCM.getNameController(client.getComponent()).getFcName(), "membrane"));
} else { // Exception!!
throw new IllegalBindingException(
"The server interface has to be a NF inner server one");
}
// Bind only to a NF internal server
} else { // Exception!!
throw new IllegalBindingException(
"An inner F component can only bind its client NF interfaces to inner server NF interfaces");
}
}
}
}
}
public void nfBindFc(String clientItf, Object serverItf) throws NoSuchInterfaceException,
IllegalLifeCycleException, IllegalBindingException, NoSuchComponentException {// Binds external NF client itf with External NF Server
serverItf = PAFuture.getFutureValue(serverItf);
ComponentAndInterface client = getComponentAndInterface(clientItf);
PAInterface clItf = (PAInterface) client.getInterface();
PAGCMInterfaceType clItfType = (PAGCMInterfaceType) clItf.getFcItfType();
PAInterface srItf = (PAInterface) serverItf;
if (!clItfType.isFcClientItf()) {
throw new IllegalBindingException("This method only binds NF client interfaces");
} else {// OK for binding, but first check that types are compatible
checkMembraneIsStopped();
checkCompatibility(clItf, srItf);
if (nfBindings.hasBinding("membrane", clientItf, null, srItf.getFcItfName())) {
throw new IllegalBindingException("The binding :" + " membrane." + clientItf +
"--> external NF interface already exists");
}
((ItfStubObject) srItf).setSenderItfID(new ItfID(clientItf, ((PAComponent) getFcItfOwner())
.getID()));
if (!tryToBindMulticastInterface(clItf, srItf)) {
PAInterface cl = (PAInterface) owner.getFcInterface(clientItf);
cl.setFcItfImpl(serverItf);
nfBindings.addNormalBinding(new NFBinding(clItf, clientItf, srItf, "membrane", null));
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItf);
}
}
}
}
private boolean tryToBindMulticastInterface(PAInterface clientItf, PAInterface serverItf)
throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException {
if (((GCMInterfaceType) clientItf.getFcItfType()).isGCMMulticastItf()) {
((PAMulticastControllerImpl) ((PAInterface) GCM.getMulticastController(clientItf.getFcItfOwner()))
.getFcItfImpl()).bindFc(clientItf.getFcItfName(), PAFuture.getFutureValue(serverItf));
if (Utils.isGCMGathercastItf(serverItf)) {
GCM.getGathercastController(serverItf.getFcItfOwner()).notifyAddedGCMBinding(
serverItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItf.getFcItfName());
}
return true;
} else {
return false;
}
}
public String nfGetFcState(String component) throws NoSuchComponentException, NoSuchInterfaceException,
IllegalLifeCycleException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no component named " + component);
}
checkMembraneIsStarted(nfComponents.get(component));
return GCM.getGCMLifeCycleController(nfComponents.get(component)).getFcState();
}
public Component[] nfGetFcSubComponents() {
List<Component> nfSubComponents = new ArrayList<Component>(nfComponents.values());
return nfSubComponents.toArray(new Component[nfSubComponents.size()]);
}
public String[] nfListFc(String component) throws NoSuchComponentException, NoSuchInterfaceException,
IllegalLifeCycleException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no " + component + " inside the membrane");
}
checkMembraneIsStarted(nfComponents.get(component));
return GCM.getBindingController(nfComponents.get(component)).listFc();
}
public Object nfLookupFc(String itfname) throws NoSuchInterfaceException, NoSuchComponentException {
ComponentAndInterface itf = getComponentAndInterface(itfname);
PAInterface theItf = (PAInterface) itf.getInterface();
PAGCMInterfaceType theType = (PAGCMInterfaceType) theItf.getFcItfType();
if (itf.getComponent() == null) {//The interface has to belong to the membrane and has to be client!!
theItf = (PAInterface) itf.getInterface();
theType = (PAGCMInterfaceType) theItf.getFcItfType();
if (theType.isFcClientItf()) {//OK, We can return its implementation
return theItf.getFcItfImpl();
} else {
throw new NoSuchInterfaceException("The requested interface: " + theItf.getFcItfName() +
" is not a client one");
}
} else {//The component is either functional or non-functional
if (itf.getComponent() instanceof PANFComponentRepresentative) {
return GCM.getBindingController(itf.getComponent()).lookupFc(theItf.getFcItfName());
} else {//The component is functional, and we are attempting to lookup on a client non-functional external interface
if (theType.getFcItfName().endsWith("-controller")) {
return Utils.getPAMembraneController(itf.getComponent()).nfLookupFc(
itf.getInterface().getFcItfName());
}
//throw new NoSuchComponentException("The specified component: " +
// GCM.getNameController(itf.getComponent()).getFcName() + " is not in the membrane");
}
}
return null;
}
public void nfRemoveFcSubComponent(Component component) throws IllegalContentException,
IllegalLifeCycleException, NoSuchComponentException {
try { /* Check the lifecycle of the membrane and the component */
if (membraneState.equals(MEMBRANE_STARTED) ||
GCM.getGCMLifeCycleController(owner).getFcState().equals(LifeCycleController.STARTED)) {
throw new IllegalLifeCycleException(
"To perform reconfiguration inside the membrane, the lifecycle and the membrane must be stopped");
}
} catch (NoSuchInterfaceException e) {
/* Without a life cycle controller, a GCM component does not work */
}
checkMembraneIsStarted(component);
String componentname = null;
try {
componentname = GCM.getNameController(component).getFcName();
} catch (NoSuchInterfaceException i) {
IllegalContentException ice = new IllegalContentException(
"NF components are identified by their names. The component to remove does not have any.");
ice.initCause(i);
throw ice;
}
PAComponent ownerRepresentative = owner.getRepresentativeOnThis();
if (!nfComponents.containsKey(componentname)) {
throw new NoSuchComponentException("There is no " + componentname + " inside the membrane");
}
Component toRemove = nfComponents.get(componentname);
try {
if (Utils.getPABindingController(toRemove).isBound().booleanValue()) {
throw new IllegalContentException(
"cannot remove a sub component that holds bindings on its external interfaces");
}
} catch (NoSuchInterfaceException ignored) {
// no binding controller
}
try {
Utils.getPASuperController(toRemove).removeParent(ownerRepresentative);
} catch (NoSuchInterfaceException e) {
/* No superController */
}
//Here, when removing a component on which the host holds bindings, remove those bindings
nfBindings.removeServerAliasBindingsOn(componentname);
nfComponents.remove(componentname);
}
public void setControllerObject(String itf, Object controllerclass) throws NoSuchInterfaceException {
try {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED) ||
GCM.getGCMLifeCycleController(owner).getFcState().equals(LifeCycleController.STARTED)) {
throw new IllegalLifeCycleException(
"For the moment, to perform reconfiguration inside the membrane, the lifecycle and the membrane must be stopped");
}
((PAComponentImpl) owner).setControllerObject(itf, controllerclass);
} catch (NoSuchInterfaceException n) {
throw n;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Start the F lifecycle of a NF component.
*
* Requisite: the membrane of the NF component must be started.
*/
public void nfStartFc(String component) throws IllegalLifeCycleException, NoSuchComponentException,
NoSuchInterfaceException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no component named " + component);
}
// Membrane of 'component' must be started
checkMembraneIsStarted(nfComponents.get(component));
GCM.getGCMLifeCycleController(nfComponents.get(component)).startFc();
}
/**
* Stop the F lifecycle of a NF component
*
* Requisite: the membrane of the NF component must be stopped
*/
public void nfStopFc(String component) throws IllegalLifeCycleException, NoSuchComponentException,
NoSuchInterfaceException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no component named " + component);
}
// Membrane of 'component' must be started
checkMembraneIsStarted(nfComponents.get(component));
GCM.getGCMLifeCycleController(nfComponents.get(component)).stopFc();
}
/**
* Unbinds client interfaces exposed by the membrane, or client interfaces of non-functional components.
*
* Requisite: the Membrane must be stopped
*
*/
public void nfUnbindFc(String clientItf) throws NoSuchInterfaceException, IllegalLifeCycleException,
IllegalBindingException, NoSuchComponentException {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED)) {
throw new IllegalLifeCycleException(
"The membrane should be stopped while unbinding non-functional interfaces");
}
ComponentAndInterface theItf = getComponentAndInterface(clientItf);
PAInterface it = (PAInterface) theItf.getInterface();
PAGCMInterfaceType clItfType = (PAGCMInterfaceType) it.getFcItfType();
if (theItf.getComponent() == null) {// Unbind a client interface exposed by the membrane, update the structure
it.setFcItfImpl(null);
nfBindings.removeNormalBinding("membrane", it.getFcItfName());//Here, we deal only with singleton bindings
} else {//Unbind the non-functional component's interface
Component theComp = theItf.getComponent();
checkMembraneIsStarted(theComp);
if (theComp instanceof PANFComponentRepresentative) {
if (clItfType.isFcClientItf()) {
GCM.getBindingController(theComp).unbindFc(theItf.getInterface().getFcItfName());
nfBindings.removeClientAliasBinding(GCM.getNameController(theComp).getFcName(), it
.getFcItfName());
} else {//The interface is not client. It should be.
throw new IllegalBindingException("You should specify a client singleton interface");
}
} else {//The component is a functional one. It should not.
throw new IllegalBindingException(
"You should unbind a functional interface of a non-functional component inside the membrane");
}
}
}
/**
* Start the Membrane of this component, and starts the F lifecycle of inner NF components
* (does not start membranes recursively).
*/
public void startMembrane() throws IllegalLifeCycleException {
InterfaceType[] itfTypes = ((PAComponentType) getFcItfOwner().getFcType()).getNfFcInterfaceTypes();
// Check that all mandatory NF interfaces of this component are bound
for (InterfaceType itfT : itfTypes) {
if (!itfT.isFcOptionalItf()) {//Are all mandatory interfaces bound??
try {
PAInterface paItf = (PAInterface) getFcItfOwner().getFcInterface(itfT.getFcItfName());
if (paItf.getFcItfImpl() == null) {
throw new IllegalLifeCycleException(
"To start the membrane, all mandatory non-functional interfaces have to be bound. The interface " +
itfT.getFcItfName() + " is not.");
}
} catch (NoSuchInterfaceException e) {
IllegalLifeCycleException ilce = new IllegalLifeCycleException("The interface " +
itfT.getFcItfName() +
" declared in the non-functional type was not generated on the server side");
ilce.initCause(e);
throw ilce;
}
}
}
// Start the F lifecycle of NF components.
for (Component c : nfComponents.values()) {
try {
checkMembraneIsStarted(c);
GCM.getGCMLifeCycleController(c).startFc();
} catch (NoSuchInterfaceException nosi) {
// The component has no lifecycle controller, nothing to do with it
}
}
membraneState = MEMBRANE_STARTED;
}
/**
* Stop the membrane of this component, and stops the F lifecycle of inner NF components
* (does not stop membranes recursively)
*/
public void stopMembrane() throws IllegalLifeCycleException {
for (Component c : nfComponents.values()) {
try {
checkMembraneIsStarted(c);
GCM.getGCMLifeCycleController(c).stopFc();
} catch (NoSuchInterfaceException nosi) {
try {
logger.debug("The component" + GCM.getNameController(c).getFcName() + " has no LifeCycle Controller");
} catch (NoSuchInterfaceException e) {
// The component has no lifecycle controller, nothing to do with it
// No LifeCycle and no name for this component
}
}
}
membraneState = MEMBRANE_STOPPED;
}
/**
* Check if all non functional components are stopped
* @return True if all the non functional components are stopped, false if not
*/
private boolean membraneIsStopped() {
boolean result = true;
for (Component c : nfComponents.values()) {
try {
result = result && (GCM.getGCMLifeCycleController(c).getFcState().equals(LifeCycleController.STOPPED));
} catch (NoSuchInterfaceException e) {
// The component has no lifecycle controller, nothing to do with it
}
}
return result;
}
/**
* Returns first occurence of functional components corresponding to the specified name
* @param name The name of the component
* @return The first occurence of functional components corresponding to the specified name
*/
private Component getFunctionalComponent(String name) {
try {
Component[] fComponents = GCM.getContentController(owner).getFcSubComponents();
for (Component c : fComponents) {
try {
if (GCM.getNameController(c).getFcName().compareTo(name) == 0) {
return c;
}
} catch (NoSuchInterfaceException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean hostComponentisPrimitive() {
try {
return owner.getComponentParameters().getHierarchicalType().equals(Constants.PRIMITIVE);
} catch (Exception e) {
}
return false;
}
public Component nfGetFcSubComponent(String name) {
return nfComponents.get(name);
}
public void duplicateController(Object c) {
if (c instanceof HashMap<?, ?>) {
nfComponents = (HashMap<String, Component>) c;
} else {
throw new ProActiveRuntimeException(
"PAMembraneControllerImpl: Impossible to duplicate the controller " + this +
" from the controller" + c);
}
}
private ComponentAndInterface getComponentAndInterface(String itf) throws NoSuchInterfaceException {
String[] itfTab = itf.split("\\.", 2);
if (itfTab.length == 1) {
// The interface tab has only one element : if it exists, it is
//an interface of the membrane
if (itfTab[0].endsWith("-controller")) {
Interface i = (Interface) owner.getFcInterface(itfTab[0]);
return new ComponentAndInterface(i);
} else {
//The interface is not a controller one
throw new NoSuchInterfaceException("The specified interface " + itfTab[0] +
" is not non-functional");
}
} else {
// Normally, component and its interface are specified
// cruz: I have not used this possibility in practice: to specify an interface as "membrane.interfaceName"
// (and it forbids the existence of a component called "membrane")
if (itfTab[0].equals("membrane")) {
Interface i = (Interface) owner.getFcInterface(itfTab[1]);
return new ComponentAndInterface(i);
}
Component searchComponent = null;
try {
if (!hostComponentisPrimitive()) { //Is it a functional component?
searchComponent = getFunctionalComponent(itfTab[0]);
}
if (searchComponent == null) {
//The component we are looking for is not in the functional content
searchComponent = nfGetFcSubComponent(itfTab[0]);
// Is it a non functional component??
if (searchComponent == null) {
throw new NoSuchComponentException("There is no : " + itfTab[0] + " component");
} else {
// The component is non-functional
return new ComponentAndInterface(searchComponent, (Interface) searchComponent
.getFcInterface(itfTab[1]));
}
} else {
// The component is functional
return new ComponentAndInterface(searchComponent, (Interface) searchComponent
.getFcInterface(itfTab[1]));
}
} catch (NoSuchInterfaceException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void checkMembraneIsStopped() throws IllegalLifeCycleException {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED)) {
throw new IllegalLifeCycleException("The membrane should be stopped");
}
}
private void checkMembraneIsStarted(Component comp) throws IllegalLifeCycleException {
try {
if (Utils.getPAMembraneController(comp).getMembraneState().equals(
PAMembraneController.MEMBRANE_STOPPED)) {
throw new IllegalLifeCycleException(
"The desired operation can not be performed. The membrane of a non-functional component is stopped. It should be started.");
}
} catch (NoSuchInterfaceException e) {
//No impact on the rest of the code without a membrane-controller
}
}
public void checkInternalInterfaces() throws IllegalLifeCycleException {
InterfaceType[] itfTypes = ((PAComponentType) getFcItfOwner().getFcType()).getNfFcInterfaceTypes();
PAGCMInterfaceType paItfT;
for (InterfaceType itfT : itfTypes) {
paItfT = (PAGCMInterfaceType) itfT;
if (!itfT.isFcOptionalItf() && paItfT.isInternal()) {
PAInterface paItf;
try {
paItf = (PAInterface) getFcItfOwner().getFcInterface(itfT.getFcItfName());
if (paItf.getFcItfImpl() == null) {
throw new IllegalLifeCycleException(
"When starting the component, all mandatory internal non-functional interfaces have to be bound. The interface " +
itfT.getFcItfName() + " is not.");
}
} catch (NoSuchInterfaceException e) {
IllegalLifeCycleException ilce = new IllegalLifeCycleException("The interface " +
itfT.getFcItfName() +
" declared in the non-functional type was not generated on the server side");
ilce.initCause(e);
throw ilce;
}
}
}
}
class ComponentAndInterface {
private Component theComponent;
private Interface theInterface;
public ComponentAndInterface(Component comp, Interface i) {
theComponent = comp;
theInterface = i;
}
public ComponentAndInterface(Interface i) {
theComponent = null;
theInterface = i;
}
public Component getComponent() {
return theComponent;
}
public void setComponent(Component theComponent) {
this.theComponent = theComponent;
}
public Interface getInterface() {
return theInterface;
}
public void setInterface(Interface theInterface) {
this.theInterface = theInterface;
}
}
public ControllerState getState() {
return new ControllerState((HashMap<String, Component>) nfComponents);
}
public String getMembraneState() {
return membraneState;
}
}
|
src/Core/org/objectweb/proactive/core/component/control/PAMembraneControllerImpl.java
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core.component.control;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.etsi.uri.gcm.api.type.GCMInterfaceType;
import org.etsi.uri.gcm.util.GCM;
import org.objectweb.fractal.api.Component;
import org.objectweb.fractal.api.Interface;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.IllegalBindingException;
import org.objectweb.fractal.api.control.IllegalContentException;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;
import org.objectweb.fractal.api.control.LifeCycleController;
import org.objectweb.fractal.api.factory.InstantiationException;
import org.objectweb.fractal.api.type.InterfaceType;
import org.objectweb.fractal.api.type.TypeFactory;
import org.objectweb.fractal.util.Fractal;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.component.Constants;
import org.objectweb.proactive.core.component.ItfStubObject;
import org.objectweb.proactive.core.component.NFBinding;
import org.objectweb.proactive.core.component.NFBindings;
import org.objectweb.proactive.core.component.PAInterface;
import org.objectweb.proactive.core.component.Utils;
import org.objectweb.proactive.core.component.componentcontroller.HostComponentSetter;
import org.objectweb.proactive.core.component.exceptions.NoSuchComponentException;
import org.objectweb.proactive.core.component.identity.PAComponent;
import org.objectweb.proactive.core.component.identity.PAComponentImpl;
import org.objectweb.proactive.core.component.representative.ItfID;
import org.objectweb.proactive.core.component.representative.PAComponentRepresentativeImpl;
import org.objectweb.proactive.core.component.representative.PANFComponentRepresentative;
import org.objectweb.proactive.core.component.type.PAComponentType;
import org.objectweb.proactive.core.component.type.PAGCMInterfaceType;
import org.objectweb.proactive.core.component.type.PAGCMTypeFactoryImpl;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* The class implementing the membrane controller
* @author The ProActive Team
*
*/
public class PAMembraneControllerImpl extends AbstractPAController implements PAMembraneController,
Serializable, ControllerStateDuplication {
protected static Logger logger = ProActiveLogger.getLogger(Loggers.COMPONENTS);
protected static Logger loggerADL = ProActiveLogger.getLogger(Loggers.COMPONENTS_ADL);
private Map<String, Component> nfComponents;
private NFBindings nfBindings;//TODO : This structure has to be updated every time a with the membrane is added or removed
private String membraneState;
public PAMembraneControllerImpl(Component owner) {
super(owner);
nfComponents = new HashMap<String, Component>();
membraneState = MEMBRANE_STOPPED;
nfBindings = new NFBindings();
}
@Override
protected void setControllerItfType() {
try {
setItfType(PAGCMTypeFactoryImpl.instance().createFcItfType(Constants.MEMBRANE_CONTROLLER,
PAMembraneController.class.getName(), TypeFactory.SERVER, TypeFactory.MANDATORY,
TypeFactory.SINGLE));
} catch (InstantiationException e) {
throw new ProActiveRuntimeException("cannot create controller type : " +
this.getClass().getName());
}
}
private void checkCompatibility(Interface clientItf, Interface serverItf) throws IllegalBindingException {
PAGCMInterfaceType clientItfType = (PAGCMInterfaceType) clientItf.getFcItfType();
try {
if (Utils.isGCMMulticastItf(clientItfType.getFcItfName(), clientItf.getFcItfOwner())) {
GCM.getMulticastController(owner).ensureGCMCompatibility(clientItfType, serverItf);
}
if (Utils.isGCMGathercastItf(serverItf)) {
GCM.getGathercastController(owner).ensureGCMCompatibility(clientItfType, serverItf);
} else if (Utils.isGCMSingletonItf(clientItfType.getFcItfName(), clientItf.getFcItfOwner())) {
PAGCMInterfaceType serverItfType = (PAGCMInterfaceType) serverItf.getFcItfType();
Class<?> cl = Class.forName(clientItfType.getFcItfSignature());
Class<?> sr = Class.forName(serverItfType.getFcItfSignature());
if (!cl.isAssignableFrom(sr)) {
throw new IllegalBindingException("Signatures of interfaces don't correspond (" +
clientItfType.getFcItfSignature() + " and " + serverItfType.getFcItfSignature() + ")");
}
}
} catch (ClassNotFoundException cnfe) {
throw new IllegalBindingException(cnfe.getMessage());
} catch (NoSuchInterfaceException nsie) {
throw new IllegalBindingException(nsie.getMessage());
}
}
public void nfAddFcSubComponent(Component component) throws IllegalContentException,
IllegalLifeCycleException {
try {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED) ||
GCM.getGCMLifeCycleController(owner).getFcState().equals(LifeCycleController.STARTED)) {
throw new IllegalLifeCycleException(
"To perform reconfiguration inside the membrane, the lifecycle and the membrane must be stopped");
}
} catch (NoSuchInterfaceException e) {
// Without a life cycle controller, the default activity of a GCM component does not work
}
checkMembraneIsStarted(component);
PAComponent ownerRepresentative = owner.getRepresentativeOnThis();
String name = null;
if (!(component instanceof PANFComponentRepresentative)) {
throw new IllegalContentException(
"Only non-functional components should be added to the membrane");
}
try {
name = GCM.getNameController(component).getFcName();
} catch (NoSuchInterfaceException e) {
IllegalContentException ice = new IllegalContentException(
"The component has to implement the name-controller interface");
ice.initCause(e);
throw ice;
}
if (nfComponents.containsKey(name)) {
throw new IllegalContentException("The name of the component is already assigned to an existing non functional component");
}
if (!((PAComponentRepresentativeImpl) ownerRepresentative).isPrimitive()) {
/// Host component is composite
Component[] fcomponents = null;
try {
fcomponents = GCM.getContentController(owner).getFcSubComponents();
} catch (NoSuchInterfaceException e) {
IllegalContentException ice = new IllegalContentException(
"The host component seems to be a composite without content-controller interface!!!");
ice.initCause(e);
throw ice;
}
for (Component c : fcomponents) {
// Check that the name of the component is not assigned to an existing functional one
try {
// cruz: why is this needed ?
// When adding an NF component, it should not interfere with the F subcomponents, even less with their membrane.
// It makes more sense to check this in the nfBindFc operation.
//try {
// if (Utils.getPAMembraneController(c).getMembraneState().equals(PAMembraneController.MEMBRANE_STOPPED)) {
// throw new IllegalLifeCycleException(
// "While iterating on functional components, it appears that one of them has its membrane in a stopped state. It should be started.");
// }
//} catch (NoSuchInterfaceException e) {
//If the component does not have any membrane-controller, it won't have any impact
//}
// TODO Check if this must be enforced or not. Theoretically, if are going to allow reconfiguration (insertion/removal)
// of components in the functional part, and in the membrane, AND we want to promote separation concerns,
// we should 'a priori' allow repeated names (there's never a direct binding between F and NF components)
if (GCM.getNameController(c).getFcName().compareTo(name) == 0) {
throw new IllegalContentException(
"The name of the component is already assigned to an existing functional component");
}
} catch (NoSuchInterfaceException e) {
/*
* Do nothing : if the component does not have a name-controller interface, then
* it can not be bound with a non functional component
*/
}
}
} /* end of case with composite */
try {
Utils.getPASuperController(component).addParent(ownerRepresentative);
} catch (NoSuchInterfaceException e) {
/*
* Once again, nothing to do, if the component doesn't have the super-controller, it
* means that it will not reference the host component
*/
}
//If the component has the appropriate interface, give it a reference on the host component
try {
HostComponentSetter hcs = (HostComponentSetter) component
.getFcInterface(Constants.HOST_SETTER_CONTROLLER);
hcs.setHostComponent(ownerRepresentative);
} catch (NoSuchInterfaceException e) {
logger.warn("The non-functional component " + name +
" doesn't have any reference on its host component");
}
//Add the component inside the Map
nfComponents.put(name, component);
}
private void bindNfServerWithNfClient(String clItf, PAInterface srItf) throws IllegalBindingException,
NoSuchInterfaceException, IllegalLifeCycleException {
PAInterface cl = null;
try {
cl = (PAInterface) owner.getFcInterface(clItf);
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
// Check whether the binding exists
if (nfBindings.hasBinding("membrane", clItf, "membrane", srItf.getFcItfName())) {
throw new IllegalBindingException("The binding : membrane." + clItf + "--->" + "membrane." +
srItf.getFcItfName() + " already exists");
}
if (!tryToBindMulticastInterface(cl, srItf)) {
cl.setFcItfImpl(srItf);
nfBindings.addNormalBinding(new NFBinding(cl, clItf, srItf, "membrane", "membrane"));
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clItf);
}
}
}
private void bindNfServerWithNfCServer(String clItf, PAInterface srItf) throws IllegalBindingException,
NoSuchInterfaceException, IllegalLifeCycleException {
PAInterface cl = null;
Component srOwner = srItf.getFcItfOwner();
// Check whether the binding exists
try {
if (nfBindings.hasBinding("membrane", clItf, GCM.getNameController(srOwner).getFcName(), srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : membrane." + clItf + "--->" +
GCM.getNameController(srOwner).getFcName() + "." + srItf.getFcItfName() +
" already exists");
}
} catch (NoSuchInterfaceException e1) {
e1.printStackTrace();
}
try {
cl = (PAInterface) owner.getFcInterface(clItf);
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
try {// In this case, the nf component controller gets the state of a controller and duplicates it.
ControllerStateDuplication dup = (ControllerStateDuplication) srOwner
.getFcInterface(Constants.CONTROLLER_STATE_DUPLICATION);
Object ob = cl.getFcItfImpl();
if (ob instanceof ControllerStateDuplication) {// The controller is implemented with an object
dup.duplicateController(((ControllerStateDuplication) ob).getState().getStateObject());
} else {// The controller is implemented with a NF component?
if (ob instanceof PAInterface) {
Component cmp = ((PAInterface) ob).getFcItfOwner();
ControllerStateDuplication duplicated = (ControllerStateDuplication) cmp
.getFcInterface(Constants.CONTROLLER_STATE_DUPLICATION);
dup.duplicateController(duplicated.getState().getStateObject());
}
}
} catch (NoSuchInterfaceException e) {
logger.debug("The component controller doesn't have a duplication-controller interface");
}
if (!tryToBindMulticastInterface(cl, srItf)) {
cl.setFcItfImpl(srItf);
try {
nfBindings.addServerAliasBinding(new NFBinding(cl, clItf, srItf, "membrane", Fractal
.getNameController(srOwner).getFcName()));
} catch (NoSuchInterfaceException e) {
logger.warn("Could not add a binding : the component does not not have a Name Controller");
}
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clItf);
}
}
}
private void bindNfClientWithFCServer(String clItf, PAInterface srItf) throws IllegalBindingException,
NoSuchInterfaceException, IllegalLifeCycleException {
PAInterface cl = null;
Component srOwner = null;
try {
cl = (PAInterface) owner.getFcInterface(clItf);
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
srOwner = srItf.getFcItfOwner();
// Check whether the binding exists
try {
if (nfBindings.hasBinding("membrane", clItf, GCM.getNameController(srOwner).getFcName(), srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : membrane." + clItf + "--->" +
GCM.getNameController(srOwner).getFcName() + "." + srItf.getFcItfName() +
" already exists");
}
} catch (NoSuchInterfaceException e1) {
e1.printStackTrace();
}
if (!tryToBindMulticastInterface(cl, srItf)) {
cl.setFcItfImpl(srItf);
try {
nfBindings.addNormalBinding(new NFBinding(cl, clItf, srItf, "membrane", Fractal
.getNameController(srOwner).getFcName()));
} catch (NoSuchInterfaceException e) {
e.printStackTrace();
}
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clItf);
}
}
}
private void bindClientNFWithInternalServerNF(String clItf, PAInterface srItf)
throws IllegalBindingException, NoSuchInterfaceException, IllegalLifeCycleException {
bindNfServerWithNfClient(clItf, srItf);
}
public void nfBindFc(String clientItf, String serverItf) throws NoSuchInterfaceException,
IllegalLifeCycleException, IllegalBindingException, NoSuchComponentException {
ComponentAndInterface client = getComponentAndInterface(clientItf);
ComponentAndInterface server = getComponentAndInterface(serverItf);
PAInterface clItf = (PAInterface) client.getInterface();
PAGCMInterfaceType clItfType = (PAGCMInterfaceType) clItf.getFcItfType();
PAInterface srItf = (PAInterface) server.getInterface();
PAGCMInterfaceType srItfType = (PAGCMInterfaceType) srItf.getFcItfType();
checkMembraneIsStopped();
checkCompatibility(clItf, srItf);
if (srItf instanceof ItfStubObject) {
((ItfStubObject) srItf).setSenderItfID(new ItfID(clientItf, ((PAComponent) clItf.getFcItfOwner())
.getID()));
}
if (client.getComponent() == null) { // The client interface belongs to the membrane
if (!clItfType.isFcClientItf()) { // The client interface is a server one (internal or external) belonging to the membrane
if (server.getComponent() == null) { // The server interface belongs to the membrane
if (srItfType.isFcClientItf()) { // The (server) interface is client (internal or external) belonging to the membrane
if (clItfType.isInternal()) { // Binding between internal server and internal client is forbidden inside the membrane
if (srItfType.isInternal()) { // Trying to bind an internal server NF interface with an internal client NF interface
throw new IllegalBindingException(
"Internal NF server interfaces can not be bound to internal NF client interfaces");
} else { //The server interface belongs to the membrane, and is external client
bindNfServerWithNfClient(clItf.getFcItfName(), srItf); // Internal NF server with external NF client
}
} else { // The client itf is a NF external server
if (srItfType.isInternal()) {
bindNfServerWithNfClient(clItf.getFcItfName(), srItf); // External NF server with internal NF client
} else { // Trying to bind an external server NF interface with an external client NF interface
throw new IllegalBindingException(
"External NF server interfaces can not be bound to external NF client interfaces");
}
}
}
} else { // The server interface belongs to a component. Possible bindings : External/Internal NF server with a server of a NF component
if (srItfType.isFcClientItf() ||
!(server.getComponent() instanceof PANFComponentRepresentative) ||
srItfType.getFcItfName().endsWith("-controller")) {
throw new IllegalBindingException(
"NF server interfaces can be bound only to server F interfaces of NF components");
} else { // NF server interface with a server interface of a NF component : Server alias binding
bindNfServerWithNfCServer(clItf.getFcItfName(), srItf);
}
}
} else { // The client interface is a NF client one. For this method it can be only an internal NF client. It can be bound only to a NF interface of a F component.
if (!clItfType.isInternal()) {
throw new IllegalBindingException(
"With this method, only internal NF client interfaces can be bound");
}
if (server.getComponent() == null) {// The server interface belongs to the membrane. In this case, this interface HAS to be an internal NF server
if (srItfType.getFcItfName().endsWith("-controller") && srItfType.isInternal()) {
bindClientNFWithInternalServerNF(clItfType.getFcItfName(), srItf);// NF internal client ---- NF internal server
} else {
throw new IllegalBindingException(
"Inside the membrane, internal NF interfaces can be bound only with NF internal server of NF interface of F inner components");
}
} else {
if ((server.getComponent() instanceof PANFComponentRepresentative) ||
!(srItfType.getFcItfName().endsWith("-controller"))) {
throw new IllegalBindingException(
"With this method, an internal client NF interface can only be bound to a NF interface of a F inner component");
} else { // OK for binding client NF internal with NF external of F component
bindNfClientWithFCServer(clItf.getFcItfName(), srItf);
}
}
}
} else { // The client interface belongs to a (NF or F)component
if (!clItfType.isFcClientItf()) {
throw new IllegalBindingException("Only a client interface of a NF/F can be bound");
} else {
if (client.getComponent() instanceof PANFComponentRepresentative) { // All possible bindings for client interfaces of NF components
checkMembraneIsStarted(client.getComponent());
if (server.getComponent() == null) { // A client interface of a NF component to a NF external/internal client
loggerADL.debug("[PAMembraneControllerImpl] Server Interface Type: "+ srItfType.getFcItfName() +" + is client? "+ srItfType.isFcClientItf() +" internal?" + srItfType.isInternal() + " ... " + (srItfType instanceof Interface) );
if (srItfType.isFcClientItf() && srItfType.getFcItfName().endsWith("-controller")) { // Connection to any (internal/external) client NF interface
GCM.getBindingController(client.getComponent()).bindFc(clItfType.getFcItfName(),
owner.getRepresentativeOnThis().getFcInterface(srItfType.getFcItfName()));// Alias client binding
// Check whether the binding already exist
if (nfBindings.hasBinding(GCM.getNameController(client.getComponent())
.getFcName(), client.getInterface().getFcItfName(), "membrane", srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : " +
GCM.getNameController(client.getComponent()).getFcName() + "." + clItf +
"--->membrane." + srItf.getFcItfName() + " already exists");
}
nfBindings.addClientAliasBinding(new NFBinding(null, clItfType.getFcItfName(),
srItf, GCM.getNameController(client.getComponent()).getFcName(), "membrane"));
} else { // Exception!!
throw new IllegalBindingException(
"A NF component can only be bound to client NF interfaces of the membrane");
}
} else { // Binding of 2 NF components
if (!(server.getComponent() instanceof PANFComponentRepresentative)) { //The server component has to be a NF one
throw new IllegalBindingException(
"A NF component can only be bound to another NF (not F) component");
} else { // Last verification before binding
if (srItfType.isFcClientItf()) {
throw new IllegalBindingException(
"When binding two NF components, a client interface must be bound to a server one");
} else { // Call to binding controller of the component that has the client interface
GCM.getBindingController(client.getComponent()).bindFc(
clItfType.getFcItfName(),
server.getComponent().getFcInterface(srItfType.getFcItfName()));
}
}
}
} else { // Binding for NF client interfaces of inner F components
if (server.getComponent() == null) {
if (!srItfType.isFcClientItf() && srItfType.isInternal()) { // External client NF interface only bound to inner server NF interface
// No need to check the membrane state of Host component
Utils.getPAMembraneController(client.getComponent()).nfBindFc(
clItfType.getFcItfName(),
owner.getRepresentativeOnThis().getFcInterface(srItfType.getFcItfName()));
// Check whether this binding already exist
if (nfBindings.hasBinding(GCM.getNameController(client.getComponent())
.getFcName(), client.getInterface().getFcItfName(), "membrane", srItf
.getFcItfName())) {
throw new IllegalBindingException("The binding : " +
GCM.getNameController(client.getComponent()).getFcName() + "." + clItf +
"--->membrane." + srItf.getFcItfName() + " already exists");
}
nfBindings.addNormalBinding(new NFBinding(clItf, clItfType.getFcItfName(), srItf,
GCM.getNameController(client.getComponent()).getFcName(), "membrane"));
} else { // Exception!!
throw new IllegalBindingException(
"The server interface has to be a NF inner server one");
}
// Bind only to a NF internal server
} else { // Exception!!
throw new IllegalBindingException(
"An inner F component can only bind its client NF interfaces to inner server NF interfaces");
}
}
}
}
}
public void nfBindFc(String clientItf, Object serverItf) throws NoSuchInterfaceException,
IllegalLifeCycleException, IllegalBindingException, NoSuchComponentException {// Binds external NF client itf with External NF Server
serverItf = PAFuture.getFutureValue(serverItf);
ComponentAndInterface client = getComponentAndInterface(clientItf);
PAInterface clItf = (PAInterface) client.getInterface();
PAGCMInterfaceType clItfType = (PAGCMInterfaceType) clItf.getFcItfType();
PAInterface srItf = (PAInterface) serverItf;
if (!clItfType.isFcClientItf()) {
throw new IllegalBindingException("This method only binds NF client interfaces");
} else {// OK for binding, but first check that types are compatible
checkMembraneIsStopped();
checkCompatibility(clItf, srItf);
if (nfBindings.hasBinding("membrane", clientItf, null, srItf.getFcItfName())) {
throw new IllegalBindingException("The binding :" + " membrane." + clientItf +
"--> external NF interface already exists");
}
((ItfStubObject) srItf).setSenderItfID(new ItfID(clientItf, ((PAComponent) getFcItfOwner())
.getID()));
if (!tryToBindMulticastInterface(clItf, srItf)) {
PAInterface cl = (PAInterface) owner.getFcInterface(clientItf);
cl.setFcItfImpl(serverItf);
nfBindings.addNormalBinding(new NFBinding(clItf, clientItf, srItf, "membrane", null));
if (Utils.isGCMGathercastItf(srItf)) {
GCM.getGathercastController(srItf.getFcItfOwner()).notifyAddedGCMBinding(
srItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItf);
}
}
}
}
private boolean tryToBindMulticastInterface(PAInterface clientItf, PAInterface serverItf)
throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException {
if (((GCMInterfaceType) clientItf.getFcItfType()).isGCMMulticastItf()) {
((PAMulticastControllerImpl) ((PAInterface) GCM.getMulticastController(clientItf.getFcItfOwner()))
.getFcItfImpl()).bindFc(clientItf.getFcItfName(), PAFuture.getFutureValue(serverItf));
if (Utils.isGCMGathercastItf(serverItf)) {
GCM.getGathercastController(serverItf.getFcItfOwner()).notifyAddedGCMBinding(
serverItf.getFcItfName(), owner.getRepresentativeOnThis(), clientItf.getFcItfName());
}
return true;
} else {
return false;
}
}
public String nfGetFcState(String component) throws NoSuchComponentException, NoSuchInterfaceException,
IllegalLifeCycleException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no component named " + component);
}
checkMembraneIsStarted(nfComponents.get(component));
return GCM.getGCMLifeCycleController(nfComponents.get(component)).getFcState();
}
public Component[] nfGetFcSubComponents() {
List<Component> nfSubComponents = new ArrayList<Component>(nfComponents.values());
return nfSubComponents.toArray(new Component[nfSubComponents.size()]);
}
public String[] nfListFc(String component) throws NoSuchComponentException, NoSuchInterfaceException,
IllegalLifeCycleException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no " + component + " inside the membrane");
}
checkMembraneIsStarted(nfComponents.get(component));
return GCM.getBindingController(nfComponents.get(component)).listFc();
}
public Object nfLookupFc(String itfname) throws NoSuchInterfaceException, NoSuchComponentException {
ComponentAndInterface itf = getComponentAndInterface(itfname);
PAInterface theItf = (PAInterface) itf.getInterface();
PAGCMInterfaceType theType = (PAGCMInterfaceType) theItf.getFcItfType();
if (itf.getComponent() == null) {//The interface has to belong to the membrane and has to be client!!
theItf = (PAInterface) itf.getInterface();
theType = (PAGCMInterfaceType) theItf.getFcItfType();
if (theType.isFcClientItf()) {//OK, We can return its implementation
return theItf.getFcItfImpl();
} else {
throw new NoSuchInterfaceException("The requested interface: " + theItf.getFcItfName() +
" is not a client one");
}
} else {//The component is either functional or non-functional
if (itf.getComponent() instanceof PANFComponentRepresentative) {
return GCM.getBindingController(itf.getComponent()).lookupFc(theItf.getFcItfName());
} else {//The component is functional, and we are attempting to lookup on a client non-functional external interface
if (theType.getFcItfName().endsWith("-controller")) {
return Utils.getPAMembraneController(itf.getComponent()).nfLookupFc(
itf.getInterface().getFcItfName());
}
//throw new NoSuchComponentException("The specified component: " +
// GCM.getNameController(itf.getComponent()).getFcName() + " is not in the membrane");
}
}
return null;
}
public void nfRemoveFcSubComponent(Component component) throws IllegalContentException,
IllegalLifeCycleException, NoSuchComponentException {
try { /* Check the lifecycle of the membrane and the component */
if (membraneState.equals(MEMBRANE_STARTED) ||
GCM.getGCMLifeCycleController(owner).getFcState().equals(LifeCycleController.STARTED)) {
throw new IllegalLifeCycleException(
"To perform reconfiguration inside the membrane, the lifecycle and the membrane must be stopped");
}
} catch (NoSuchInterfaceException e) {
/* Without a life cycle controller, a GCM component does not work */
}
checkMembraneIsStarted(component);
String componentname = null;
try {
componentname = GCM.getNameController(component).getFcName();
} catch (NoSuchInterfaceException i) {
IllegalContentException ice = new IllegalContentException(
"NF components are identified by their names. The component to remove does not have any.");
ice.initCause(i);
throw ice;
}
PAComponent ownerRepresentative = owner.getRepresentativeOnThis();
if (!nfComponents.containsKey(componentname)) {
throw new NoSuchComponentException("There is no " + componentname + " inside the membrane");
}
Component toRemove = nfComponents.get(componentname);
try {
if (Utils.getPABindingController(toRemove).isBound().booleanValue()) {
throw new IllegalContentException(
"cannot remove a sub component that holds bindings on its external interfaces");
}
} catch (NoSuchInterfaceException ignored) {
// no binding controller
}
try {
Utils.getPASuperController(toRemove).removeParent(ownerRepresentative);
} catch (NoSuchInterfaceException e) {
/* No superController */
}
//Here, when removing a component on which the host holds bindings, remove those bindings
nfBindings.removeServerAliasBindingsOn(componentname);
nfComponents.remove(componentname);
}
public void setControllerObject(String itf, Object controllerclass) throws NoSuchInterfaceException {
try {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED) ||
GCM.getGCMLifeCycleController(owner).getFcState().equals(LifeCycleController.STARTED)) {
throw new IllegalLifeCycleException(
"For the moment, to perform reconfiguration inside the membrane, the lifecycle and the membrane must be stopped");
}
((PAComponentImpl) owner).setControllerObject(itf, controllerclass);
} catch (NoSuchInterfaceException n) {
throw n;
} catch (Exception e) {
e.printStackTrace();
}
}
public void nfStartFc(String component) throws IllegalLifeCycleException, NoSuchComponentException,
NoSuchInterfaceException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no component named " + component);
}
checkMembraneIsStarted(nfComponents.get(component));
GCM.getGCMLifeCycleController(nfComponents.get(component)).startFc();
}
public void nfStopFc(String component) throws IllegalLifeCycleException, NoSuchComponentException,
NoSuchInterfaceException {
if (!nfComponents.containsKey(component)) {
throw new NoSuchComponentException("There is no component named " + component);
}
checkMembraneIsStarted(nfComponents.get(component));
GCM.getGCMLifeCycleController(nfComponents.get(component)).stopFc();
}
public void nfUnbindFc(String clientItf) throws NoSuchInterfaceException, IllegalLifeCycleException,
IllegalBindingException, NoSuchComponentException {//Unbinds client interfaces exposed by the membrane, of client interfaces of non-functional components.
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED)) {
throw new IllegalLifeCycleException(
"The membrane should be stopped while unbinding non-functional interfaces");
}
ComponentAndInterface theItf = getComponentAndInterface(clientItf);
PAInterface it = (PAInterface) theItf.getInterface();
PAGCMInterfaceType clItfType = (PAGCMInterfaceType) it.getFcItfType();
if (theItf.getComponent() == null) {// Unbind a client interface exposed by the membrane, update the structure
it.setFcItfImpl(null);
nfBindings.removeNormalBinding("membrane", it.getFcItfName());//Here, we deal only with singleton bindings
} else {//Unbind the non-functional component's interface
Component theComp = theItf.getComponent();
checkMembraneIsStarted(theComp);
if (theComp instanceof PANFComponentRepresentative) {
if (clItfType.isFcClientItf()) {
GCM.getBindingController(theComp).unbindFc(theItf.getInterface().getFcItfName());
nfBindings.removeClientAliasBinding(GCM.getNameController(theComp).getFcName(), it
.getFcItfName());
} else {//The interface is not client. It should be.
throw new IllegalBindingException("You should specify a client singleton interface");
}
} else {//The component is a functional one. It should not.
throw new IllegalBindingException(
"You should unbind a functional interface of a non-functional component inside the membrane");
}
}
}
public void startMembrane() throws IllegalLifeCycleException {
InterfaceType[] itfTypes = ((PAComponentType) getFcItfOwner().getFcType()).getNfFcInterfaceTypes();
for (InterfaceType itfT : itfTypes) {
if (!itfT.isFcOptionalItf()) {//Are all mandatory interfaces bound??
try {
PAInterface paItf = (PAInterface) getFcItfOwner().getFcInterface(itfT.getFcItfName());
if (paItf.getFcItfImpl() == null) {
throw new IllegalLifeCycleException(
"To start the membrane, all mandatory non-functional interfaces have to be bound. The interface " +
itfT.getFcItfName() + " is not.");
}
} catch (NoSuchInterfaceException e) {
IllegalLifeCycleException ilce = new IllegalLifeCycleException("The interface " +
itfT.getFcItfName() +
" declared in the non-functional type was not generated on the server side");
ilce.initCause(e);
throw ilce;
}
}
}
for (Component c : nfComponents.values()) {
try {
checkMembraneIsStarted(c);
GCM.getGCMLifeCycleController(c).startFc();
} catch (NoSuchInterfaceException nosi) {
/*
* If the component has no lifecycle controller, then it can not be started or
* stopped
*/
}
}
membraneState = MEMBRANE_STARTED;
}
public void stopMembrane() throws IllegalLifeCycleException {
for (Component c : nfComponents.values()) {
try {
checkMembraneIsStarted(c);
GCM.getGCMLifeCycleController(c).stopFc();
} catch (NoSuchInterfaceException nosi) {
try {
logger.debug("The component" + GCM.getNameController(c).getFcName() +
" has no LifeCycle Controller");
} catch (NoSuchInterfaceException e) {// If the component has no lifecycle controller, then it can not be started or stopped
//No LifeCycle and no name for this component
}
}
}
membraneState = MEMBRANE_STOPPED;
}
/**
* Check if all non functional components are stopped
* @return True if all the non functional components are stopped, false if not
*/
private boolean membraneIsStopped() {
boolean result = true;
for (Component c : nfComponents.values()) {
try {
result = result &&
(GCM.getGCMLifeCycleController(c).getFcState().compareTo(LifeCycleController.STOPPED) == 0);
} catch (NoSuchInterfaceException e) {
/* Without a lifecycle controller, the componnet has no lifecycle state */
}
}
return result;
}
/**
* Returns first occurence of functional components corresponding to the specified name
* @param name The name of the component
* @return The first occurence of functional components corresponding to the specified name
*/
private Component getFunctionalComponent(String name) {
try {
Component[] fComponents = GCM.getContentController(owner).getFcSubComponents();
for (Component c : fComponents) {
try {
if (GCM.getNameController(c).getFcName().compareTo(name) == 0) {
return c;
}
} catch (NoSuchInterfaceException e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean hostComponentisPrimitive() {
try {
return owner.getComponentParameters().getHierarchicalType().equals(Constants.PRIMITIVE);
} catch (Exception e) {
}
return false;
}
public Component nfGetFcSubComponent(String name) {
return nfComponents.get(name);
}
public void duplicateController(Object c) {
if (c instanceof HashMap<?, ?>) {
nfComponents = (HashMap<String, Component>) c;
} else {
throw new ProActiveRuntimeException(
"PAMembraneControllerImpl: Impossible to duplicate the controller " + this +
" from the controller" + c);
}
}
private ComponentAndInterface getComponentAndInterface(String itf) throws NoSuchInterfaceException {
String[] itfTab = itf.split("\\.", 2);
if (itfTab.length == 1) {
// The interface tab has only one element : if it exists, it is
//an interface of the membrane
if (itfTab[0].endsWith("-controller")) {
Interface i = (Interface) owner.getFcInterface(itfTab[0]);
return new ComponentAndInterface(i);
} else {
//The interface is not a controller one
throw new NoSuchInterfaceException("The specified interface " + itfTab[0] +
" is not non-functional");
}
} else {
// Normally, component and its interface are specified
// cruz: I have not used this possibility in practice: to specify an interface as "membrane.interfaceName"
// (and it forbids the existence of a component called "membrane")
if (itfTab[0].equals("membrane")) {
Interface i = (Interface) owner.getFcInterface(itfTab[1]);
return new ComponentAndInterface(i);
}
Component searchComponent = null;
try {
if (!hostComponentisPrimitive()) { //Is it a functional component?
searchComponent = getFunctionalComponent(itfTab[0]);
}
if (searchComponent == null) {
//The component we are looking for is not in the functional content
searchComponent = nfGetFcSubComponent(itfTab[0]);
// Is it a non functional component??
if (searchComponent == null) {
throw new NoSuchComponentException("There is no : " + itfTab[0] + " component");
} else {
// The component is non-functional
return new ComponentAndInterface(searchComponent, (Interface) searchComponent
.getFcInterface(itfTab[1]));
}
} else {
// The component is functional
return new ComponentAndInterface(searchComponent, (Interface) searchComponent
.getFcInterface(itfTab[1]));
}
} catch (NoSuchInterfaceException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void checkMembraneIsStopped() throws IllegalLifeCycleException {
if (membraneState.equals(PAMembraneController.MEMBRANE_STARTED)) {
throw new IllegalLifeCycleException("The membrane should be stopped");
}
}
private void checkMembraneIsStarted(Component comp) throws IllegalLifeCycleException {
try {
if (Utils.getPAMembraneController(comp).getMembraneState().equals(
PAMembraneController.MEMBRANE_STOPPED)) {
throw new IllegalLifeCycleException(
"The desired operation can not be performed. The membrane of a non-functional component is stopped. It should be started.");
}
} catch (NoSuchInterfaceException e) {
//No impact on the rest of the code without a membrane-controller
}
}
public void checkInternalInterfaces() throws IllegalLifeCycleException {
InterfaceType[] itfTypes = ((PAComponentType) getFcItfOwner().getFcType()).getNfFcInterfaceTypes();
PAGCMInterfaceType paItfT;
for (InterfaceType itfT : itfTypes) {
paItfT = (PAGCMInterfaceType) itfT;
if (!itfT.isFcOptionalItf() && paItfT.isInternal()) {
PAInterface paItf;
try {
paItf = (PAInterface) getFcItfOwner().getFcInterface(itfT.getFcItfName());
if (paItf.getFcItfImpl() == null) {
throw new IllegalLifeCycleException(
"When strating the component, all mandatory internal non-functional interfaces have to be bound. The interface " +
itfT.getFcItfName() + " is not.");
}
} catch (NoSuchInterfaceException e) {
IllegalLifeCycleException ilce = new IllegalLifeCycleException("The interface " +
itfT.getFcItfName() +
" declared in the non-functional type was not generated on the server side");
ilce.initCause(e);
throw ilce;
}
}
}
}
class ComponentAndInterface {
private Component theComponent;
private Interface theInterface;
public ComponentAndInterface(Component comp, Interface i) {
theComponent = comp;
theInterface = i;
}
public ComponentAndInterface(Interface i) {
theComponent = null;
theInterface = i;
}
public Component getComponent() {
return theComponent;
}
public void setComponent(Component theComponent) {
this.theComponent = theComponent;
}
public Interface getInterface() {
return theInterface;
}
public void setInterface(Interface theInterface) {
this.theInterface = theInterface;
}
}
public ControllerState getState() {
return new ControllerState((HashMap<String, Component>) nfComponents);
}
public String getMembraneState() {
return membraneState;
}
}
|
Removes the check that F components and NF components must have
different names.
Also, cleaner code and comments.
|
src/Core/org/objectweb/proactive/core/component/control/PAMembraneControllerImpl.java
|
Removes the check that F components and NF components must have different names.
|
|
Java
|
apache-2.0
|
c098b48692c1b88673e236112b12d75e1ff35568
| 0
|
doom369/netty,tbrooks8/netty,doom369/netty,NiteshKant/netty,johnou/netty,doom369/netty,johnou/netty,Spikhalskiy/netty,tbrooks8/netty,netty/netty,johnou/netty,johnou/netty,tbrooks8/netty,Spikhalskiy/netty,doom369/netty,doom369/netty,netty/netty,NiteshKant/netty,netty/netty,netty/netty,Spikhalskiy/netty,johnou/netty,netty/netty,tbrooks8/netty,Spikhalskiy/netty,Spikhalskiy/netty,NiteshKant/netty,tbrooks8/netty,NiteshKant/netty,NiteshKant/netty
|
/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.dns;
import io.netty.util.AbstractReferenceCounted;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetectorFactory;
import io.netty.util.ResourceLeakTracker;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.UnstableApi;
import java.util.ArrayList;
import java.util.List;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
/**
* A skeletal implementation of {@link DnsMessage}.
*/
@UnstableApi
public abstract class AbstractDnsMessage extends AbstractReferenceCounted implements DnsMessage {
private static final ResourceLeakDetector<DnsMessage> leakDetector =
ResourceLeakDetectorFactory.instance().newResourceLeakDetector(DnsMessage.class);
private static final int SECTION_QUESTION = DnsSection.QUESTION.ordinal();
private static final int SECTION_COUNT = 4;
private final ResourceLeakTracker<DnsMessage> leak = leakDetector.track(this);
private short id;
private DnsOpCode opCode;
private boolean recursionDesired;
private byte z;
// To reduce the memory footprint of a message,
// each of the following fields is a single record or a list of records.
private Object questions;
private Object answers;
private Object authorities;
private Object additionals;
/**
* Creates a new instance with the specified {@code id} and {@link DnsOpCode#QUERY} opCode.
*/
protected AbstractDnsMessage(int id) {
this(id, DnsOpCode.QUERY);
}
/**
* Creates a new instance with the specified {@code id} and {@code opCode}.
*/
protected AbstractDnsMessage(int id, DnsOpCode opCode) {
setId(id);
setOpCode(opCode);
}
@Override
public int id() {
return id & 0xFFFF;
}
@Override
public DnsMessage setId(int id) {
this.id = (short) id;
return this;
}
@Override
public DnsOpCode opCode() {
return opCode;
}
@Override
public DnsMessage setOpCode(DnsOpCode opCode) {
this.opCode = checkNotNull(opCode, "opCode");
return this;
}
@Override
public boolean isRecursionDesired() {
return recursionDesired;
}
@Override
public DnsMessage setRecursionDesired(boolean recursionDesired) {
this.recursionDesired = recursionDesired;
return this;
}
@Override
public int z() {
return z;
}
@Override
public DnsMessage setZ(int z) {
this.z = (byte) (z & 7);
return this;
}
@Override
public int count(DnsSection section) {
return count(sectionOrdinal(section));
}
private int count(int section) {
final Object records = sectionAt(section);
if (records == null) {
return 0;
}
if (records instanceof DnsRecord) {
return 1;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return recordList.size();
}
@Override
public int count() {
int count = 0;
for (int i = 0; i < SECTION_COUNT; i ++) {
count += count(i);
}
return count;
}
@Override
public <T extends DnsRecord> T recordAt(DnsSection section) {
return recordAt(sectionOrdinal(section));
}
private <T extends DnsRecord> T recordAt(int section) {
final Object records = sectionAt(section);
if (records == null) {
return null;
}
if (records instanceof DnsRecord) {
return castRecord(records);
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
if (recordList.isEmpty()) {
return null;
}
return castRecord(recordList.get(0));
}
@Override
public <T extends DnsRecord> T recordAt(DnsSection section, int index) {
return recordAt(sectionOrdinal(section), index);
}
private <T extends DnsRecord> T recordAt(int section, int index) {
final Object records = sectionAt(section);
if (records == null) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
}
if (records instanceof DnsRecord) {
if (index == 0) {
return castRecord(records);
} else {
throw new IndexOutOfBoundsException("index: " + index + "' (expected: 0)");
}
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return castRecord(recordList.get(index));
}
@Override
public DnsMessage setRecord(DnsSection section, DnsRecord record) {
setRecord(sectionOrdinal(section), record);
return this;
}
private void setRecord(int section, DnsRecord record) {
clear(section);
setSection(section, checkQuestion(section, record));
}
@Override
public <T extends DnsRecord> T setRecord(DnsSection section, int index, DnsRecord record) {
return setRecord(sectionOrdinal(section), index, record);
}
private <T extends DnsRecord> T setRecord(int section, int index, DnsRecord record) {
checkQuestion(section, record);
final Object records = sectionAt(section);
if (records == null) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
}
if (records instanceof DnsRecord) {
if (index == 0) {
setSection(section, record);
return castRecord(records);
} else {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
}
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return castRecord(recordList.set(index, record));
}
@Override
public DnsMessage addRecord(DnsSection section, DnsRecord record) {
addRecord(sectionOrdinal(section), record);
return this;
}
private void addRecord(int section, DnsRecord record) {
checkQuestion(section, record);
final Object records = sectionAt(section);
if (records == null) {
setSection(section, record);
return;
}
if (records instanceof DnsRecord) {
final List<DnsRecord> recordList = newRecordList();
recordList.add(castRecord(records));
recordList.add(record);
setSection(section, recordList);
return;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
recordList.add(record);
}
@Override
public DnsMessage addRecord(DnsSection section, int index, DnsRecord record) {
addRecord(sectionOrdinal(section), index, record);
return this;
}
private void addRecord(int section, int index, DnsRecord record) {
checkQuestion(section, record);
final Object records = sectionAt(section);
if (records == null) {
if (index != 0) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
}
setSection(section, record);
return;
}
if (records instanceof DnsRecord) {
final List<DnsRecord> recordList;
if (index == 0) {
recordList = newRecordList();
recordList.add(record);
recordList.add(castRecord(records));
} else if (index == 1) {
recordList = newRecordList();
recordList.add(castRecord(records));
recordList.add(record);
} else {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0 or 1)");
}
setSection(section, recordList);
return;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
recordList.add(index, record);
}
@Override
public <T extends DnsRecord> T removeRecord(DnsSection section, int index) {
return removeRecord(sectionOrdinal(section), index);
}
private <T extends DnsRecord> T removeRecord(int section, int index) {
final Object records = sectionAt(section);
if (records == null) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
}
if (records instanceof DnsRecord) {
if (index != 0) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
}
T record = castRecord(records);
setSection(section, null);
return record;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return castRecord(recordList.remove(index));
}
@Override
public DnsMessage clear(DnsSection section) {
clear(sectionOrdinal(section));
return this;
}
@Override
public DnsMessage clear() {
for (int i = 0; i < SECTION_COUNT; i ++) {
clear(i);
}
return this;
}
private void clear(int section) {
final Object recordOrList = sectionAt(section);
setSection(section, null);
if (recordOrList instanceof ReferenceCounted) {
((ReferenceCounted) recordOrList).release();
} else if (recordOrList instanceof List) {
@SuppressWarnings("unchecked")
List<DnsRecord> list = (List<DnsRecord>) recordOrList;
if (!list.isEmpty()) {
for (Object r : list) {
ReferenceCountUtil.release(r);
}
}
}
}
@Override
public DnsMessage touch() {
return (DnsMessage) super.touch();
}
@Override
public DnsMessage touch(Object hint) {
if (leak != null) {
leak.record(hint);
}
return this;
}
@Override
public DnsMessage retain() {
return (DnsMessage) super.retain();
}
@Override
public DnsMessage retain(int increment) {
return (DnsMessage) super.retain(increment);
}
@Override
protected void deallocate() {
clear();
final ResourceLeakTracker<DnsMessage> leak = this.leak;
if (leak != null) {
boolean closed = leak.close(this);
assert closed;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DnsMessage)) {
return false;
}
final DnsMessage that = (DnsMessage) obj;
if (id() != that.id()) {
return false;
}
if (this instanceof DnsQuery) {
if (!(that instanceof DnsQuery)) {
return false;
}
} else if (that instanceof DnsQuery) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id() * 31 + (this instanceof DnsQuery? 0 : 1);
}
private Object sectionAt(int section) {
switch (section) {
case 0:
return questions;
case 1:
return answers;
case 2:
return authorities;
case 3:
return additionals;
default:
break;
}
throw new Error(); // Should never reach here.
}
private void setSection(int section, Object value) {
switch (section) {
case 0:
questions = value;
return;
case 1:
answers = value;
return;
case 2:
authorities = value;
return;
case 3:
additionals = value;
return;
default:
break;
}
throw new Error(); // Should never reach here.
}
private static int sectionOrdinal(DnsSection section) {
return checkNotNull(section, "section").ordinal();
}
private static DnsRecord checkQuestion(int section, DnsRecord record) {
if (section == SECTION_QUESTION && !(checkNotNull(record, "record") instanceof DnsQuestion)) {
throw new IllegalArgumentException(
"record: " + record + " (expected: " + StringUtil.simpleClassName(DnsQuestion.class) + ')');
}
return record;
}
@SuppressWarnings("unchecked")
private static <T extends DnsRecord> T castRecord(Object record) {
return (T) record;
}
private static ArrayList<DnsRecord> newRecordList() {
return new ArrayList<DnsRecord>(2);
}
}
|
codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java
|
/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.dns;
import io.netty.util.AbstractReferenceCounted;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetectorFactory;
import io.netty.util.ResourceLeakTracker;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.UnstableApi;
import java.util.ArrayList;
import java.util.List;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
/**
* A skeletal implementation of {@link DnsMessage}.
*/
@UnstableApi
public abstract class AbstractDnsMessage extends AbstractReferenceCounted implements DnsMessage {
private static final ResourceLeakDetector<DnsMessage> leakDetector =
ResourceLeakDetectorFactory.instance().newResourceLeakDetector(DnsMessage.class);
private static final int SECTION_QUESTION = DnsSection.QUESTION.ordinal();
private static final int SECTION_COUNT = 4;
private final ResourceLeakTracker<DnsMessage> leak = leakDetector.track(this);
private short id;
private DnsOpCode opCode;
private boolean recursionDesired;
private byte z;
// To reduce the memory footprint of a message,
// each of the following fields is a single record or a list of records.
private Object questions;
private Object answers;
private Object authorities;
private Object additionals;
/**
* Creates a new instance with the specified {@code id} and {@link DnsOpCode#QUERY} opCode.
*/
protected AbstractDnsMessage(int id) {
this(id, DnsOpCode.QUERY);
}
/**
* Creates a new instance with the specified {@code id} and {@code opCode}.
*/
protected AbstractDnsMessage(int id, DnsOpCode opCode) {
setId(id);
setOpCode(opCode);
}
@Override
public int id() {
return id & 0xFFFF;
}
@Override
public DnsMessage setId(int id) {
this.id = (short) id;
return this;
}
@Override
public DnsOpCode opCode() {
return opCode;
}
@Override
public DnsMessage setOpCode(DnsOpCode opCode) {
this.opCode = checkNotNull(opCode, "opCode");
return this;
}
@Override
public boolean isRecursionDesired() {
return recursionDesired;
}
@Override
public DnsMessage setRecursionDesired(boolean recursionDesired) {
this.recursionDesired = recursionDesired;
return this;
}
@Override
public int z() {
return z;
}
@Override
public DnsMessage setZ(int z) {
this.z = (byte) (z & 7);
return this;
}
@Override
public int count(DnsSection section) {
return count(sectionOrdinal(section));
}
private int count(int section) {
final Object records = sectionAt(section);
if (records == null) {
return 0;
}
if (records instanceof DnsRecord) {
return 1;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return recordList.size();
}
@Override
public int count() {
int count = 0;
for (int i = 0; i < SECTION_COUNT; i ++) {
count += count(i);
}
return count;
}
@Override
public <T extends DnsRecord> T recordAt(DnsSection section) {
return recordAt(sectionOrdinal(section));
}
private <T extends DnsRecord> T recordAt(int section) {
final Object records = sectionAt(section);
if (records == null) {
return null;
}
if (records instanceof DnsRecord) {
return castRecord(records);
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
if (recordList.isEmpty()) {
return null;
}
return castRecord(recordList.get(0));
}
@Override
public <T extends DnsRecord> T recordAt(DnsSection section, int index) {
return recordAt(sectionOrdinal(section), index);
}
private <T extends DnsRecord> T recordAt(int section, int index) {
final Object records = sectionAt(section);
if (records == null) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
}
if (records instanceof DnsRecord) {
if (index == 0) {
return castRecord(records);
} else {
throw new IndexOutOfBoundsException("index: " + index + "' (expected: 0)");
}
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return castRecord(recordList.get(index));
}
@Override
public DnsMessage setRecord(DnsSection section, DnsRecord record) {
setRecord(sectionOrdinal(section), record);
return this;
}
private void setRecord(int section, DnsRecord record) {
clear(section);
setSection(section, checkQuestion(section, record));
}
@Override
public <T extends DnsRecord> T setRecord(DnsSection section, int index, DnsRecord record) {
return setRecord(sectionOrdinal(section), index, record);
}
private <T extends DnsRecord> T setRecord(int section, int index, DnsRecord record) {
checkQuestion(section, record);
final Object records = sectionAt(section);
if (records == null) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
}
if (records instanceof DnsRecord) {
if (index == 0) {
setSection(section, record);
return castRecord(records);
} else {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
}
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return castRecord(recordList.set(index, record));
}
@Override
public DnsMessage addRecord(DnsSection section, DnsRecord record) {
addRecord(sectionOrdinal(section), record);
return this;
}
private void addRecord(int section, DnsRecord record) {
checkQuestion(section, record);
final Object records = sectionAt(section);
if (records == null) {
setSection(section, record);
return;
}
if (records instanceof DnsRecord) {
final List<DnsRecord> recordList = newRecordList();
recordList.add(castRecord(records));
recordList.add(record);
setSection(section, recordList);
return;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
recordList.add(record);
}
@Override
public DnsMessage addRecord(DnsSection section, int index, DnsRecord record) {
addRecord(sectionOrdinal(section), index, record);
return this;
}
private void addRecord(int section, int index, DnsRecord record) {
checkQuestion(section, record);
final Object records = sectionAt(section);
if (records == null) {
if (index != 0) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
}
setSection(section, record);
return;
}
if (records instanceof DnsRecord) {
final List<DnsRecord> recordList;
if (index == 0) {
recordList = newRecordList();
recordList.add(record);
recordList.add(castRecord(records));
} else if (index == 1) {
recordList = newRecordList();
recordList.add(castRecord(records));
recordList.add(record);
} else {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0 or 1)");
}
setSection(section, recordList);
return;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
recordList.add(index, record);
}
@Override
public <T extends DnsRecord> T removeRecord(DnsSection section, int index) {
return removeRecord(sectionOrdinal(section), index);
}
private <T extends DnsRecord> T removeRecord(int section, int index) {
final Object records = sectionAt(section);
if (records == null) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: none)");
}
if (records instanceof DnsRecord) {
if (index != 0) {
throw new IndexOutOfBoundsException("index: " + index + " (expected: 0)");
}
T record = castRecord(records);
setSection(section, null);
return record;
}
@SuppressWarnings("unchecked")
final List<DnsRecord> recordList = (List<DnsRecord>) records;
return castRecord(recordList.remove(index));
}
@Override
public DnsMessage clear(DnsSection section) {
clear(sectionOrdinal(section));
return this;
}
@Override
public DnsMessage clear() {
for (int i = 0; i < SECTION_COUNT; i ++) {
clear(i);
}
return this;
}
private void clear(int section) {
final Object recordOrList = sectionAt(section);
setSection(section, null);
if (recordOrList instanceof ReferenceCounted) {
((ReferenceCounted) recordOrList).release();
} else if (recordOrList instanceof List) {
@SuppressWarnings("unchecked")
List<DnsRecord> list = (List<DnsRecord>) recordOrList;
if (!list.isEmpty()) {
for (Object r : list) {
ReferenceCountUtil.release(r);
}
}
}
}
@Override
public DnsMessage touch() {
return (DnsMessage) super.touch();
}
@Override
public DnsMessage touch(Object hint) {
if (leak != null) {
leak.record(hint);
}
return this;
}
@Override
public DnsMessage retain() {
return (DnsMessage) super.retain();
}
@Override
public DnsMessage retain(int increment) {
return (DnsMessage) super.retain(increment);
}
@Override
protected void deallocate() {
clear();
final ResourceLeakTracker<DnsMessage> leak = this.leak;
if (leak != null) {
boolean closed = leak.close(this);
assert closed;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof DnsMessage)) {
return false;
}
final DnsMessage that = (DnsMessage) obj;
if (id() != that.id()) {
return false;
}
if (this instanceof DnsQuery) {
if (!(that instanceof DnsQuery)) {
return false;
}
} else if (that instanceof DnsQuery) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id() * 31 + (this instanceof DnsQuery? 0 : 1);
}
private Object sectionAt(int section) {
switch (section) {
case 0:
return questions;
case 1:
return answers;
case 2:
return authorities;
case 3:
return additionals;
}
throw new Error(); // Should never reach here.
}
private void setSection(int section, Object value) {
switch (section) {
case 0:
questions = value;
return;
case 1:
answers = value;
return;
case 2:
authorities = value;
return;
case 3:
additionals = value;
return;
}
throw new Error(); // Should never reach here.
}
private static int sectionOrdinal(DnsSection section) {
return checkNotNull(section, "section").ordinal();
}
private static DnsRecord checkQuestion(int section, DnsRecord record) {
if (section == SECTION_QUESTION && !(checkNotNull(record, "record") instanceof DnsQuestion)) {
throw new IllegalArgumentException(
"record: " + record + " (expected: " + StringUtil.simpleClassName(DnsQuestion.class) + ')');
}
return record;
}
@SuppressWarnings("unchecked")
private static <T extends DnsRecord> T castRecord(Object record) {
return (T) record;
}
private static ArrayList<DnsRecord> newRecordList() {
return new ArrayList<DnsRecord>(2);
}
}
|
Add default block in AbstractDnsMessage (#11327)
Motivation:
Every switch block should also have a default case.
Modification:
Add default block in AbstractDnsMessage to ensure we not fall-through by mistake
Result:
Cleanup
Signed-off-by: xingrufei <48e2105060e9cad759ac1d9bc2ede76e24364e70@sogou-inc.com>
|
codec-dns/src/main/java/io/netty/handler/codec/dns/AbstractDnsMessage.java
|
Add default block in AbstractDnsMessage (#11327)
|
|
Java
|
apache-2.0
|
3047e5e2ce41d981bc373000dc98466e38caa0f8
| 0
|
pivotal-amurmann/geode,pivotal-amurmann/geode,PurelyApplied/geode,smanvi-pivotal/geode,PurelyApplied/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,smgoller/geode,smanvi-pivotal/geode,smgoller/geode,masaki-yamakawa/geode,davebarnes97/geode,PurelyApplied/geode,PurelyApplied/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,smgoller/geode,smgoller/geode,jdeppe-pivotal/geode,prasi-in/geode,davebarnes97/geode,smanvi-pivotal/geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,pdxrunner/geode,shankarh/geode,PurelyApplied/geode,masaki-yamakawa/geode,davinash/geode,prasi-in/geode,prasi-in/geode,charliemblack/geode,smgoller/geode,davebarnes97/geode,davebarnes97/geode,shankarh/geode,prasi-in/geode,charliemblack/geode,shankarh/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,davebarnes97/geode,charliemblack/geode,pivotal-amurmann/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,pdxrunner/geode,shankarh/geode,smanvi-pivotal/geode,charliemblack/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode,PurelyApplied/geode,masaki-yamakawa/geode,davinash/geode,deepakddixit/incubator-geode,PurelyApplied/geode,masaki-yamakawa/geode,pdxrunner/geode,deepakddixit/incubator-geode,davinash/geode,pivotal-amurmann/geode,shankarh/geode,davinash/geode,smgoller/geode,davinash/geode,deepakddixit/incubator-geode,pivotal-amurmann/geode,davinash/geode,pdxrunner/geode,pdxrunner/geode,deepakddixit/incubator-geode,charliemblack/geode,pdxrunner/geode,davinash/geode,prasi-in/geode,davebarnes97/geode,davebarnes97/geode,pdxrunner/geode
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.internal;
import com.gemstone.gemfire.InternalGemFireException;
import com.gemstone.gemfire.UnmodifiableException;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.FlowControlParams;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import java.io.*;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
/**
* Provides an implementation of the {@link Config} interface
* that implements functionality that all {@link Config} implementations
* can share.
*/
public abstract class AbstractConfig implements Config {
/**
* Returns the string to use as the exception message when an attempt
* is made to set an unmodifiable attribute.
*/
protected String _getUnmodifiableMsg(String attName) {
return LocalizedStrings.AbstractConfig_THE_0_CONFIGURATION_ATTRIBUTE_CAN_NOT_BE_MODIFIED.toLocalizedString(attName);
}
/**
* Returns a map that contains attribute descriptions
*/
protected abstract Map getAttDescMap();
protected abstract Map<String, ConfigSource> getAttSourceMap();
public final static String sourceHeader = "PropertiesSourceHeader";
/**
* Set to true if most of the attributes can be modified.
* Set to false if most of the attributes are read only.
*/
protected boolean _modifiableDefault() {
return false;
}
/**
* Use {@link #toLoggerString()} instead. If you need to override this in a
* subclass, be careful not to expose any private data or security related
* values. Fixing bug #48155 by not exposing all values.
*/
@Override
public final String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
@Override
public String toLoggerString() {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
printSourceSection(ConfigSource.runtime(), pw);
printSourceSection(ConfigSource.sysprop(), pw);
printSourceSection(ConfigSource.api(), pw);
for (ConfigSource fileSource: getFileSources()) {
printSourceSection(fileSource, pw);
}
printSourceSection(ConfigSource.xml(), pw);
printSourceSection(ConfigSource.launcher(), pw); // fix for bug 46653
printSourceSection(null, pw);
pw.close();
return sw.toString();
}
/***
* Gets the Map of GemFire properties and values from a given ConfigSource
* @param source
* @return map of GemFire properties and values
*/
public Map<String, String> getConfigPropsFromSource(ConfigSource source) {
Map<String, String> configProps = new HashMap<String, String>();
String[] validAttributeNames = getAttributeNames();
Map<String, ConfigSource> sm = getAttSourceMap();
for (int i=0; i < validAttributeNames.length; i++) {
String attName = validAttributeNames[i];
if (source == null) {
if (sm.get(attName) != null) {
continue;
}
} else if (!source.equals(sm.get(attName))) {
continue;
}
configProps.put(attName, this.getAttribute(attName));
}
return configProps;
}
/****
* Gets all the GemFire properties defined using file(s)
* @return Map of GemFire properties and values set using property files
*/
public Map<String, String> getConfigPropsDefinedUsingFiles() {
Map<String, String> configProps = new HashMap<String, String>();
for (ConfigSource fileSource: getFileSources()) {
configProps.putAll(getConfigPropsFromSource(fileSource));
}
return configProps;
}
private List<ConfigSource> getFileSources() {
ArrayList<ConfigSource> result = new ArrayList<ConfigSource>();
for (ConfigSource cs: getAttSourceMap().values()) {
if (cs.getType() == ConfigSource.Type.FILE || cs.getType() == ConfigSource.Type.SECURE_FILE) {
if (!result.contains(cs)) {
result.add(cs);
}
}
}
return result;
}
private void printSourceSection(ConfigSource source, PrintWriter pw) {
String[] validAttributeNames = getAttributeNames();
boolean sourceFound = false;
Map<String, ConfigSource> sm = getAttSourceMap();
boolean secureSource = false;
if (source != null && source.getType() == ConfigSource.Type.SECURE_FILE) {
secureSource = true;
}
for (int i=0; i < validAttributeNames.length; i++) {
String attName = validAttributeNames[i];
if (source == null) {
if (sm.get(attName) != null) {
continue;
}
} else if (!source.equals(sm.get(attName))) {
continue;
}
if (!sourceFound) {
sourceFound = true;
if (source == null) {
pw.println("### GemFire Properties using default values ###");
} else {
pw.println("### GemFire Properties defined with " + source.getDescription() + " ###");
}
}
// hide the shiro-init configuration for now. Remove after we can allow customer to specify shiro.ini file
if(attName.equals(SECURITY_SHIRO_INIT)){
continue;
}
pw.print(attName);
pw.print('=');
if (source == null // always show defaults
|| (!secureSource // show no values from a secure source
&& okToDisplayPropertyValue(attName))) {
pw.println(getAttribute(attName));
} else {
pw.println("********");
}
}
}
private boolean okToDisplayPropertyValue(String attName) {
if (attName.startsWith(SECURITY_PREFIX)) {
return false;
}
if (attName.startsWith(DistributionConfig.SSL_SYSTEM_PROPS_NAME)) {
return false;
}
if (attName.startsWith(DistributionConfig.SYS_PROP_NAME)) {
return false;
}
if (attName.toLowerCase().contains("password") /* bug 45381 */) {
return false;
}
return true;
}
/**
* This class was added to fix bug 39382.
* It does this be overriding "keys" which is used by the store0
* implementation of Properties.
*/
protected static class SortedProperties extends Properties {
private static final long serialVersionUID = 7156507110684631135L;
@Override
public Enumeration keys() {
// the TreeSet gets the sorting we desire but is only safe
// because the keys in this context are always String which is Comparable
return Collections.enumeration(new TreeSet(keySet()));
}
}
public boolean isDeprecated(String attName) {
return false;
}
public Properties toProperties() {
Properties result = new SortedProperties();
String[] attNames = getAttributeNames();
for (int i=0; i < attNames.length; i++) {
if (isDeprecated(attNames[i])) {
continue;
}
result.setProperty(attNames[i], getAttribute(attNames[i]));
}
return result;
}
public void toFile(File f) throws IOException {
FileOutputStream out = new FileOutputStream(f);
try {
toProperties().store(out, null);
}
finally {
out.close();
}
}
public boolean sameAs(Config other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!this.getClass().equals(other.getClass())) {
return false;
}
String[] validAttributeNames = getAttributeNames();
for (int i=0; i < validAttributeNames.length; i++) {
String attName = validAttributeNames[i];
if (this.isDeprecated(attName)) {
// since toProperties skips isDeprecated sameAs
// needs to also skip them.
// See GEODE-405.
continue;
}
Object thisAtt = this.getAttributeObject(attName);
Object otherAtt = other.getAttributeObject(attName);
if (thisAtt == otherAtt) {
continue;
} else if (thisAtt == null) {
return false;
} else if (thisAtt.getClass().isArray()) {
int thisLength = Array.getLength(thisAtt);
int otherLength = Array.getLength(otherAtt);
if (thisLength != otherLength) {
return false;
}
for (int j=0; j < thisLength; j++) {
Object thisArrObj = Array.get(thisAtt, j);
Object otherArrObj = Array.get(otherAtt, j);
if (thisArrObj == otherArrObj) {
continue;
} else if (thisArrObj == null) {
return false;
} else if (!thisArrObj.equals(otherArrObj)) {
return false;
}
}
} else if (!thisAtt.equals(otherAtt)) {
return false;
}
}
return true;
}
protected void checkAttributeName(String attName) {
String[] validAttNames = getAttributeNames();
if (!Arrays.asList(validAttNames).contains(attName.toLowerCase())) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_UNKNOWN_CONFIGURATION_ATTRIBUTE_NAME_0_VALID_ATTRIBUTE_NAMES_ARE_1.toLocalizedString(new Object[] {attName, SystemAdmin.join(validAttNames)}));
}
}
public String getAttribute(String attName) {
Object result = getAttributeObject(attName);
if (result instanceof String) {
return (String)result;
}
if (attName.equalsIgnoreCase(MEMBERSHIP_PORT_RANGE)) {
int[] value = (int[])result;
return ""+value[0]+"-"+value[1];
}
if (result.getClass().isArray()) {
return SystemAdmin.join((Object[])result);
}
if (result instanceof InetAddress) {
InetAddress addr = (InetAddress)result;
String addrName = null;
if (addr.isMulticastAddress() || !SocketCreator.resolve_dns) {
addrName = addr.getHostAddress(); // on Windows getHostName on mcast addrs takes ~5 seconds
} else {
addrName = SocketCreator.getHostName(addr);
}
return addrName;
}
return result.toString();
}
public ConfigSource getAttributeSource(String attName) {
return getAttSourceMap().get(attName);
}
public void setAttribute(String attName, String attValue, ConfigSource source) {
Object attObjectValue;
Class valueType = getAttributeType(attName);
try {
if (valueType.equals(String.class)) {
attObjectValue = attValue;
} else if (valueType.equals(Integer.class)) {
attObjectValue = Integer.valueOf(attValue);
} else if (valueType.equals(Long.class)) {
attObjectValue = Long.valueOf(attValue);
} else if (valueType.equals(Boolean.class)) {
attObjectValue = Boolean.valueOf(attValue);
} else if (valueType.equals(File.class)) {
attObjectValue = new File(attValue);
} else if (valueType.equals(int[].class)) {
int[] value = new int[2];
int minus = attValue.indexOf('-');
if (minus <= 0) {
throw new IllegalArgumentException("expected a setting in the form X-Y but found no dash for attribute " + attName);
}
value[0] = Integer.valueOf(attValue.substring(0, minus)).intValue();
value[1] = Integer.valueOf(attValue.substring(minus+1)).intValue();
attObjectValue = value;
} else if (valueType.equals(InetAddress.class)) {
try {
attObjectValue = InetAddress.getByName(attValue);
} catch (UnknownHostException ex) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_BE_A_VALID_HOST_NAME_2.toLocalizedString(new Object[] {attName, attValue, ex.toString()}));
}
} else if (valueType.equals(String[].class)) {
if (attValue == null || attValue.length() == 0) {
attObjectValue = null;
} else {
String trimAttName = trimAttributeName(attName);
throw new UnmodifiableException(LocalizedStrings.AbstractConfig_THE_0_CONFIGURATION_ATTRIBUTE_CAN_NOT_BE_SET_FROM_THE_COMMAND_LINE_SET_1_FOR_EACH_INDIVIDUAL_PARAMETER_INSTEAD.toLocalizedString(new Object[] {attName, trimAttName}));
}
} else if (valueType.equals(FlowControlParams.class)) {
String values[] = attValue.split(",");
if (values.length != 3) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_HAVE_THREE_ELEMENTS_SEPARATED_BY_COMMAS.toLocalizedString(new Object[] {attName, attValue}));
}
int credits = 0;
float thresh = (float)0.0;
int waittime = 0;
try {
credits = Integer.parseInt(values[0].trim());
thresh = Float.valueOf(values[1].trim()).floatValue();
waittime = Integer.parseInt(values[2].trim());
}
catch (NumberFormatException e) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_BE_COMPOSED_OF_AN_INTEGER_A_FLOAT_AND_AN_INTEGER.toLocalizedString(new Object[] {attName, attValue}));
}
attObjectValue = new FlowControlParams(credits, thresh, waittime);
} else {
throw new InternalGemFireException(LocalizedStrings.AbstractConfig_UNHANDLED_ATTRIBUTE_TYPE_0_FOR_1.toLocalizedString(new Object[] {valueType, attName}));
}
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_BE_A_NUMBER.toLocalizedString(new Object[] {attName, attValue}));
}
setAttributeObject(attName, attObjectValue, source);
}
/**
* Removes the last character of the input string and returns the trimmed name
*/
protected static String trimAttributeName(String attName) {
return attName.substring(0, attName.length()-1);
}
public String getAttributeDescription(String attName) {
checkAttributeName(attName);
if (!getAttDescMap().containsKey(attName)) {
throw new InternalGemFireException(LocalizedStrings.AbstractConfig_UNHANDLED_ATTRIBUTE_NAME_0.toLocalizedString(attName));
}
return (String)getAttDescMap().get(attName);
}
}
|
geode-core/src/main/java/com/gemstone/gemfire/internal/AbstractConfig.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.internal;
import com.gemstone.gemfire.InternalGemFireException;
import com.gemstone.gemfire.UnmodifiableException;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.FlowControlParams;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import java.io.*;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
/**
* Provides an implementation of the {@link Config} interface
* that implements functionality that all {@link Config} implementations
* can share.
*/
public abstract class AbstractConfig implements Config {
/**
* Returns the string to use as the exception message when an attempt
* is made to set an unmodifiable attribute.
*/
protected String _getUnmodifiableMsg(String attName) {
return LocalizedStrings.AbstractConfig_THE_0_CONFIGURATION_ATTRIBUTE_CAN_NOT_BE_MODIFIED.toLocalizedString(attName);
}
/**
* Returns a map that contains attribute descriptions
*/
protected abstract Map getAttDescMap();
protected abstract Map<String, ConfigSource> getAttSourceMap();
public final static String sourceHeader = "PropertiesSourceHeader";
/**
* Set to true if most of the attributes can be modified.
* Set to false if most of the attributes are read only.
*/
protected boolean _modifiableDefault() {
return false;
}
/**
* Use {@link #toLoggerString()} instead. If you need to override this in a
* subclass, be careful not to expose any private data or security related
* values. Fixing bug #48155 by not exposing all values.
*/
@Override
public final String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
@Override
public String toLoggerString() {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
printSourceSection(ConfigSource.runtime(), pw);
printSourceSection(ConfigSource.sysprop(), pw);
printSourceSection(ConfigSource.api(), pw);
for (ConfigSource fileSource: getFileSources()) {
printSourceSection(fileSource, pw);
}
printSourceSection(ConfigSource.xml(), pw);
printSourceSection(ConfigSource.launcher(), pw); // fix for bug 46653
printSourceSection(null, pw);
pw.close();
return sw.toString();
}
/***
* Gets the Map of GemFire properties and values from a given ConfigSource
* @param source
* @return map of GemFire properties and values
*/
public Map<String, String> getConfigPropsFromSource(ConfigSource source) {
Map<String, String> configProps = new HashMap<String, String>();
String[] validAttributeNames = getAttributeNames();
Map<String, ConfigSource> sm = getAttSourceMap();
for (int i=0; i < validAttributeNames.length; i++) {
String attName = validAttributeNames[i];
if (source == null) {
if (sm.get(attName) != null) {
continue;
}
} else if (!source.equals(sm.get(attName))) {
continue;
}
configProps.put(attName, this.getAttribute(attName));
}
return configProps;
}
/****
* Gets all the GemFire properties defined using file(s)
* @return Map of GemFire properties and values set using property files
*/
public Map<String, String> getConfigPropsDefinedUsingFiles() {
Map<String, String> configProps = new HashMap<String, String>();
for (ConfigSource fileSource: getFileSources()) {
configProps.putAll(getConfigPropsFromSource(fileSource));
}
return configProps;
}
private List<ConfigSource> getFileSources() {
ArrayList<ConfigSource> result = new ArrayList<ConfigSource>();
for (ConfigSource cs: getAttSourceMap().values()) {
if (cs.getType() == ConfigSource.Type.FILE || cs.getType() == ConfigSource.Type.SECURE_FILE) {
if (!result.contains(cs)) {
result.add(cs);
}
}
}
return result;
}
private void printSourceSection(ConfigSource source, PrintWriter pw) {
String[] validAttributeNames = getAttributeNames();
boolean sourceFound = false;
Map<String, ConfigSource> sm = getAttSourceMap();
boolean secureSource = false;
if (source != null && source.getType() == ConfigSource.Type.SECURE_FILE) {
secureSource = true;
}
for (int i=0; i < validAttributeNames.length; i++) {
String attName = validAttributeNames[i];
if (source == null) {
if (sm.get(attName) != null) {
continue;
}
} else if (!source.equals(sm.get(attName))) {
continue;
}
if (!sourceFound) {
sourceFound = true;
if (source == null) {
pw.println("### GemFire Properties using default values ###");
} else {
pw.println("### GemFire Properties defined with " + source.getDescription() + " ###");
}
}
// hide the shiro-init configuration for now. Remove after we can allow customer to specify shiro.ini file
if(attName.equals(SECURITY_SHIRO_INIT)){
continue;
}
pw.print(attName);
pw.print('=');
if (source == null // always show defaults
|| (!secureSource // show no values from a secure source
&& okToDisplayPropertyValue(attName))) {
pw.println(getAttribute(attName));
} else {
pw.println("********");
}
}
}
private boolean okToDisplayPropertyValue(String attName) {
if (attName.startsWith(SECURITY_PREFIX)) {
return false;
}
if (attName.startsWith(DistributionConfig.SSL_SYSTEM_PROPS_NAME)) {
return false;
}
if (attName.startsWith(DistributionConfig.SYS_PROP_NAME)) {
return false;
}
if (attName.toLowerCase().contains("password") /* bug 45381 */) {
return false;
}
return true;
}
/**
* This class was added to fix bug 39382.
* It does this be overriding "keys" which is used by the store0
* implementation of Properties.
*/
protected static class SortedProperties extends Properties {
private static final long serialVersionUID = 7156507110684631135L;
@Override
public Enumeration keys() {
// the TreeSet gets the sorting we desire but is only safe
// because the keys in this context are always String which is Comparable
return Collections.enumeration(new TreeSet(keySet()));
}
}
public boolean isDeprecated(String attName) {
return false;
}
public Properties toProperties() {
Properties result = new SortedProperties();
String[] attNames = getAttributeNames();
for (int i=0; i < attNames.length; i++) {
if (isDeprecated(attNames[i])) {
continue;
}
System.out.println("attNames = " + attNames[i]);
result.setProperty(attNames[i], getAttribute(attNames[i]));
}
return result;
}
public void toFile(File f) throws IOException {
FileOutputStream out = new FileOutputStream(f);
try {
toProperties().store(out, null);
}
finally {
out.close();
}
}
public boolean sameAs(Config other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!this.getClass().equals(other.getClass())) {
return false;
}
String[] validAttributeNames = getAttributeNames();
for (int i=0; i < validAttributeNames.length; i++) {
String attName = validAttributeNames[i];
if (this.isDeprecated(attName)) {
// since toProperties skips isDeprecated sameAs
// needs to also skip them.
// See GEODE-405.
continue;
}
Object thisAtt = this.getAttributeObject(attName);
Object otherAtt = other.getAttributeObject(attName);
if (thisAtt == otherAtt) {
continue;
} else if (thisAtt == null) {
return false;
} else if (thisAtt.getClass().isArray()) {
int thisLength = Array.getLength(thisAtt);
int otherLength = Array.getLength(otherAtt);
if (thisLength != otherLength) {
return false;
}
for (int j=0; j < thisLength; j++) {
Object thisArrObj = Array.get(thisAtt, j);
Object otherArrObj = Array.get(otherAtt, j);
if (thisArrObj == otherArrObj) {
continue;
} else if (thisArrObj == null) {
return false;
} else if (!thisArrObj.equals(otherArrObj)) {
return false;
}
}
} else if (!thisAtt.equals(otherAtt)) {
return false;
}
}
return true;
}
protected void checkAttributeName(String attName) {
String[] validAttNames = getAttributeNames();
if (!Arrays.asList(validAttNames).contains(attName.toLowerCase())) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_UNKNOWN_CONFIGURATION_ATTRIBUTE_NAME_0_VALID_ATTRIBUTE_NAMES_ARE_1.toLocalizedString(new Object[] {attName, SystemAdmin.join(validAttNames)}));
}
}
public String getAttribute(String attName) {
Object result = getAttributeObject(attName);
if (result instanceof String) {
return (String)result;
}
if (attName.equalsIgnoreCase(MEMBERSHIP_PORT_RANGE)) {
int[] value = (int[])result;
return ""+value[0]+"-"+value[1];
}
if (result.getClass().isArray()) {
return SystemAdmin.join((Object[])result);
}
if (result instanceof InetAddress) {
InetAddress addr = (InetAddress)result;
String addrName = null;
if (addr.isMulticastAddress() || !SocketCreator.resolve_dns) {
addrName = addr.getHostAddress(); // on Windows getHostName on mcast addrs takes ~5 seconds
} else {
addrName = SocketCreator.getHostName(addr);
}
return addrName;
}
return result.toString();
}
public ConfigSource getAttributeSource(String attName) {
return getAttSourceMap().get(attName);
}
public void setAttribute(String attName, String attValue, ConfigSource source) {
Object attObjectValue;
Class valueType = getAttributeType(attName);
try {
if (valueType.equals(String.class)) {
attObjectValue = attValue;
} else if (valueType.equals(Integer.class)) {
attObjectValue = Integer.valueOf(attValue);
} else if (valueType.equals(Long.class)) {
attObjectValue = Long.valueOf(attValue);
} else if (valueType.equals(Boolean.class)) {
attObjectValue = Boolean.valueOf(attValue);
} else if (valueType.equals(File.class)) {
attObjectValue = new File(attValue);
} else if (valueType.equals(int[].class)) {
int[] value = new int[2];
int minus = attValue.indexOf('-');
if (minus <= 0) {
throw new IllegalArgumentException("expected a setting in the form X-Y but found no dash for attribute " + attName);
}
value[0] = Integer.valueOf(attValue.substring(0, minus)).intValue();
value[1] = Integer.valueOf(attValue.substring(minus+1)).intValue();
attObjectValue = value;
} else if (valueType.equals(InetAddress.class)) {
try {
attObjectValue = InetAddress.getByName(attValue);
} catch (UnknownHostException ex) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_BE_A_VALID_HOST_NAME_2.toLocalizedString(new Object[] {attName, attValue, ex.toString()}));
}
} else if (valueType.equals(String[].class)) {
if (attValue == null || attValue.length() == 0) {
attObjectValue = null;
} else {
String trimAttName = trimAttributeName(attName);
throw new UnmodifiableException(LocalizedStrings.AbstractConfig_THE_0_CONFIGURATION_ATTRIBUTE_CAN_NOT_BE_SET_FROM_THE_COMMAND_LINE_SET_1_FOR_EACH_INDIVIDUAL_PARAMETER_INSTEAD.toLocalizedString(new Object[] {attName, trimAttName}));
}
} else if (valueType.equals(FlowControlParams.class)) {
String values[] = attValue.split(",");
if (values.length != 3) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_HAVE_THREE_ELEMENTS_SEPARATED_BY_COMMAS.toLocalizedString(new Object[] {attName, attValue}));
}
int credits = 0;
float thresh = (float)0.0;
int waittime = 0;
try {
credits = Integer.parseInt(values[0].trim());
thresh = Float.valueOf(values[1].trim()).floatValue();
waittime = Integer.parseInt(values[2].trim());
}
catch (NumberFormatException e) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_BE_COMPOSED_OF_AN_INTEGER_A_FLOAT_AND_AN_INTEGER.toLocalizedString(new Object[] {attName, attValue}));
}
attObjectValue = new FlowControlParams(credits, thresh, waittime);
} else {
throw new InternalGemFireException(LocalizedStrings.AbstractConfig_UNHANDLED_ATTRIBUTE_TYPE_0_FOR_1.toLocalizedString(new Object[] {valueType, attName}));
}
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(LocalizedStrings.AbstractConfig_0_VALUE_1_MUST_BE_A_NUMBER.toLocalizedString(new Object[] {attName, attValue}));
}
setAttributeObject(attName, attObjectValue, source);
}
/**
* Removes the last character of the input string and returns the trimmed name
*/
protected static String trimAttributeName(String attName) {
return attName.substring(0, attName.length()-1);
}
public String getAttributeDescription(String attName) {
checkAttributeName(attName);
if (!getAttDescMap().containsKey(attName)) {
throw new InternalGemFireException(LocalizedStrings.AbstractConfig_UNHANDLED_ATTRIBUTE_NAME_0.toLocalizedString(attName));
}
return (String)getAttDescMap().get(attName);
}
}
|
GEODE-420: reverting debug system out
|
geode-core/src/main/java/com/gemstone/gemfire/internal/AbstractConfig.java
|
GEODE-420: reverting debug system out
|
|
Java
|
apache-2.0
|
4098f6c5cb5bc9ce494d1598bf535c5a9daf2f4a
| 0
|
interseroh/report-cockpit-birt-web,interseroh/report-cockpit-birt-web
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* (c) 2015 - Interseroh
*/
package de.interseroh.report.server.controller;
import de.interseroh.report.server.birt.BirtOutputFormat;
import de.interseroh.report.server.birt.BirtReportException;
import de.interseroh.report.server.birt.BirtReportService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
* @author Ingo Düppe (Crowdcode)
*/
@Controller
@RequestMapping("/report")
public class ReportController {
private static final Logger logger = Logger.getLogger(ReportController.class);
@Autowired
private BirtReportService reportService;
@RequestMapping(value = "/api/{reportName}", method = RequestMethod.GET)
public void renderReportInDefaultFormat(@PathVariable("reportName") String reportName, @PathVariable("format") String format, HttpServletResponse response) throws IOException, BirtReportException {
renderReport(reportName, BirtOutputFormat.HTML5.getFormatName(), response);
}
@RequestMapping(value = "/api/{reportName}/{format}", method = RequestMethod.GET)
public void renderReport(@PathVariable("reportName") String reportName, @PathVariable("format") String format, HttpServletResponse response) throws IOException, BirtReportException {
logger.debug("Rendering " + reportName + " in " + format + ".");
BirtOutputFormat outputFormat = BirtOutputFormat.from(format);
response.setContentType(outputFormat.getContentType());
// TODO idueppe - need configurable folder
String reportFileName = "/reports/" + reportName + ".rptdesign";
HashMap<String, Object> parameters = new HashMap<String, Object>();
switch (outputFormat) {
case HTML5:
reportService.renderHtmlReport(reportFileName, parameters, response.getOutputStream());
break;
case PDF:
response.setHeader("Content-disposition", "inline; filename=" + reportName + ".pdf");
reportService.renderPDFReport(reportFileName, parameters, response.getOutputStream());
break;
case EXCEL2010:
response.setHeader("Content-disposition", "attachment; filename=" + reportName + ".xlsx");
reportService.renderExcelReport(reportFileName, parameters, response.getOutputStream());
case EXCEL:
response.setHeader("Content-disposition", "attachment; filename=" + reportName + ".xls");
reportService.renderExcelReport(reportFileName, parameters, response.getOutputStream());
}
// TODO idueppe - need exception handling
}
@RequestMapping(value = "/{reportName}", method = RequestMethod.GET)
public ModelAndView reportView(@PathVariable("reportName") String reportName, HttpServletRequest request, HttpServletResponse reponse) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/secured/report");
modelAndView.addObject("reportUrl", "/api/" + reportName);
return modelAndView;
}
}
|
src/main/java/de/interseroh/report/server/controller/ReportController.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* (c) 2015 - Interseroh
*/
package de.interseroh.report.server.controller;
import com.ibm.wsdl.extensions.mime.MIMEContentImpl;
import de.interseroh.report.server.birt.BirtReportException;
import de.interseroh.report.server.birt.BirtReportService;
import org.eclipse.birt.report.engine.api.EngineException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.wsdl.extensions.mime.MIMEContent;
import java.io.IOException;
import java.util.HashMap;
/**
* @author Ingo Düppe (Crowdcode)
*/
@Controller
@RequestMapping("/report")
public class ReportController {
@Autowired
private BirtReportService reportService;
@RequestMapping(value="/api/{reportName}", method = RequestMethod.GET)
public void generateReport(@PathVariable("reportName") String reportName, HttpServletRequest request, HttpServletResponse response) throws IOException, BirtReportException {
response.setContentType("text/html; charset=UTF-8");
String reportFileName = "/reports/" + reportName + ".rptdesign";
reportService.renderHtmlReport(reportFileName, new HashMap<String, Object>(), response.getOutputStream());
}
@RequestMapping(value="/{reportName}", method = RequestMethod.GET)
public ModelAndView reportView(@PathVariable("reportName") String reportName, HttpServletRequest request, HttpServletResponse reponse) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/secured/report");
modelAndView.addObject("reportUrl", "/api/"+reportName);
return modelAndView;
}
}
|
Added REST-API to render reports in separate formats.
|
src/main/java/de/interseroh/report/server/controller/ReportController.java
|
Added REST-API to render reports in separate formats.
|
|
Java
|
apache-2.0
|
3eff2e50db9199f0c74b5ed73ac5b37cb96e5cc7
| 0
|
calvingit21/h2o-2,rowhit/h2o-2,eg-zhang/h2o-2,100star/h2o,h2oai/h2o,100star/h2o,100star/h2o,111t8e/h2o-2,111t8e/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o-2,vbelakov/h2o,h2oai/h2o-2,elkingtonmcb/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,vbelakov/h2o,elkingtonmcb/h2o-2,calvingit21/h2o-2,h2oai/h2o,eg-zhang/h2o-2,h2oai/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,100star/h2o,rowhit/h2o-2,eg-zhang/h2o-2,rowhit/h2o-2,elkingtonmcb/h2o-2,vbelakov/h2o,111t8e/h2o-2,rowhit/h2o-2,h2oai/h2o-2,h2oai/h2o,100star/h2o,eg-zhang/h2o-2,100star/h2o,100star/h2o,calvingit21/h2o-2,eg-zhang/h2o-2,h2oai/h2o-2,h2oai/h2o,elkingtonmcb/h2o-2,111t8e/h2o-2,rowhit/h2o-2,vbelakov/h2o,elkingtonmcb/h2o-2,h2oai/h2o,h2oai/h2o,eg-zhang/h2o-2,vbelakov/h2o,calvingit21/h2o-2,elkingtonmcb/h2o-2,100star/h2o,eg-zhang/h2o-2,h2oai/h2o,rowhit/h2o-2,h2oai/h2o-2,rowhit/h2o-2,h2oai/h2o,rowhit/h2o-2,vbelakov/h2o,111t8e/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o-2,rowhit/h2o-2,h2oai/h2o-2,111t8e/h2o-2,calvingit21/h2o-2,h2oai/h2o,h2oai/h2o-2,calvingit21/h2o-2,100star/h2o,h2oai/h2o-2,calvingit21/h2o-2,elkingtonmcb/h2o-2,calvingit21/h2o-2,calvingit21/h2o-2,vbelakov/h2o,vbelakov/h2o,111t8e/h2o-2,rowhit/h2o-2,vbelakov/h2o,111t8e/h2o-2,calvingit21/h2o-2,h2oai/h2o,eg-zhang/h2o-2,vbelakov/h2o
|
package water;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
/**
* Keys
*
* This class defines:
* - A Key's bytes (name) & hash
* - Known Disk & memory replicas.
* - A cache of somewhat expensive to compute stuff related to the current
* Cloud, plus a byte of the desired replication factor.
*
* Keys are expected to be a high-count item, hence the care about size.
*
* Keys are *interned* in the local K/V store, a non-blocking hash set and are
* kept pointer equivalent (via the interning) for cheap compares. The
* interning only happens after a successful insert in the local H2O.STORE via
* H2O.put_if_later.
*
* @author <a href="mailto:cliffc@0xdata.com"></a>
* @version 1.0
*/
public final class Key extends Iced implements Comparable {
// The Key!!!
// Limited to 512 random bytes - to fit better in UDP packets.
public static final int KEY_LENGTH = 512;
public byte[] _kb; // Key bytes, wire-line protocol
transient int _hash; // Hash on key alone (and not value)
// The user keys must be ASCII, so the values 0..31 are reserved for system
// keys. When you create a system key, please do add its number to this list
public static final byte ARRAYLET_CHUNK = 0;
public static final byte KEY_OF_KEYS = 1;
public static final byte BUILT_IN_KEY = 2; // C.f. Constants.BUILT_IN_KEY_*
public static final byte JOB = 3;
public static final byte HDFS_INTERNAL_BLOCK = 10;
public static final byte HDFS_INODE = 11;
public static final byte HDFS_BLOCK_INFO = 12;
public static final byte HDFS_BLOCK_SHADOW = 13;
public static final byte DFJ_INTERNAL_USER = 14;
public static final byte USER_KEY = 32;
// 64 bits of Cloud-specific cached stuff. It is changed atomically by any
// thread that visits it and has the wrong Cloud. It has to be read *in the
// context of a specific Cloud*, since a re-read may be for another Cloud.
private transient volatile long _cache;
private static final AtomicLongFieldUpdater<Key> _cacheUpdater =
AtomicLongFieldUpdater.newUpdater(Key.class, "_cache");
// Accessors and updaters for the Cloud-specific cached stuff.
// The Cloud index, a byte uniquely identifying the last 256 Clouds. It
// changes atomically with the _cache word, so we can tell which Cloud this
// data is a cache of.
private static int cloud( long cache ) { return (int)(cache>>> 0)&0x00FF; }
// Shortcut node index for Home replica#0. This replica is responsible for
// breaking ties on writes. 'char' because I want an unsigned 16bit thing,
// limit of 65534 Cloud members. -1 is reserved for a bare-key
private static int home ( long cache ) { return (int)(cache>>> 8)&0xFFFF; }
// Our replica #, or -1 if we're not one of the first 127 replicas. This
// value is found using the Cloud distribution function and changes for a
// changed Cloud.
private static int replica(long cache) { return (byte)(cache>>>24)&0x00FF; }
// Desired replication factor. Can be zero for temp keys. Not allowed to
// later, because it messes with e.g. meta-data on disk.
private static int desired(long cache) { return (int)(cache>>>32)&0x00FF; }
private static long build_cache( int cidx, int home, int replica, int desired ) {
return // Build the new cache word
((long)(cidx &0xFF)<< 0) |
((long)(home &0xFFFF)<< 8) |
((long)(replica&0xFF)<<24) |
((long)(desired&0xFF)<<32) |
((long)(0 )<<40);
}
public int home ( H2O cloud ) { return home (cloud_info(cloud)); }
public int replica( H2O cloud ) { return replica(cloud_info(cloud)); }
public int desired( ) { return desired(_cache); }
public boolean home() { return home_node()==H2O.SELF; }
public H2ONode home_node( ) {
H2O cloud = H2O.CLOUD;
return cloud._memary[home(cloud)];
}
// Update the cache, but only to strictly newer Clouds
private boolean set_cache( long cache ) {
while( true ) { // Spin till get it
long old = _cache; // Read once at the start
if( !H2O.larger(cloud(cache),cloud(old)) ) // Rolling backwards?
// Attempt to set for an older Cloud. Blow out with a failure; caller
// should retry on a new Cloud.
return false;
assert cloud(cache) != cloud(old) || cache == old;
if( old == cache ) return true; // Fast-path cutout
if( _cacheUpdater.compareAndSet(this,old,cache) ) return true;
// Can fail if the cache is really old, and just got updated to a version
// which is still not the latest, and we are trying to update it again.
}
}
// Return the info word for this Cloud. Use the cache if possible
public long cloud_info( H2O cloud ) {
long x = _cache;
// See if cached for this Cloud. This should be the 99% fast case.
if( cloud(x) == cloud._idx ) return x;
// Cache missed! Probaby it just needs (atomic) updating.
// But we might be holding the stale cloud...
// Figure out home Node in this Cloud
char home = (char)cloud.D(this,0);
// Figure out what replica # I am, if any
int desired = desired(x);
int replica = -1;
for( int i=0; i<desired; i++ ) {
int idx = cloud.D(this,i);
if( idx >= 0 && cloud._memary[idx] == H2O.SELF ) {
replica = i;
break;
}
}
long cache = build_cache(cloud._idx,home,replica,desired);
set_cache(cache); // Attempt to upgrade cache, but ignore failure
return cache; // Return the magic word for this Cloud
}
// Default desired replication factor. Unless specified otherwise, all new
// k-v pairs start with this replication factor.
public static final byte DEFAULT_DESIRED_REPLICA_FACTOR = 2;
// Construct a new Key.
private Key(byte[] kb) {
if( kb.length > KEY_LENGTH ) throw new IllegalArgumentException("Key length would be "+kb.length);
_kb = kb;
// For arraylets, arrange that the first 64Megs/Keys worth spread nicely,
// but that the next 64Meg (and each 64 after that) target the same node,
// so that HDFS blocks hit only 1 node in the typical spread.
int i=0; // Include these header bytes or not
int chk = 0; // Chunk number, for chunks beyond 64Meg
if( kb.length >= 10 && kb[0] == ARRAYLET_CHUNK && kb[1] == 0 ) {
long off = UDP.get8(kb,2);
if( (off >> 20) >= 64 ) { // Is offset >= 64Meg?
i += 2+8; // Skip the length bytes; they are now not part of hash
chk = (int)(off >>> (6+20)); // Divide by 64Meg; comes up with a "block number"
}
}
int hash = 0;
// Quicky hash: http://en.wikipedia.org/wiki/Jenkins_hash_function
for( ; i<kb.length; i++ ) {
hash += kb[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
_hash = hash+chk; // Add sequential block numbering
}
// Make new Keys. Optimistically attempt interning, but no guarantee.
static public Key make(byte[] kb, byte rf) {
if( rf == -1 ) throw new IllegalArgumentException();
Key key = new Key(kb);
Key key2 = H2O.getk(key); // Get the interned version, if any
if( key2 != null ) // There is one! Return it instead
return key2;
// Set the cache with desired replication factor, and a fake cloud index
H2O cloud = H2O.CLOUD; // Read once
key._cache = build_cache(cloud._idx-1,0,0,rf);
key.cloud_info(cloud); // Now compute & cache the real data
return key;
}
static public Key make(byte[] kb) { return make(kb,DEFAULT_DESIRED_REPLICA_FACTOR); }
static public Key make(String s) { return make(decodeKeyName(s));}
static public Key make(String s, byte rf) { return make(decodeKeyName(s), rf);}
static public Key make() { return make( UUID.randomUUID().toString() ); }
// Make a particular system key that is homed to given node and possibly
// specifies also other 2 replicas. Works for both IPv4 and IPv6 addresses.
// If the addresses are not specified, returns a key with no home information.
static public Key make(String s, byte rf, byte systemType, H2ONode... replicas) {
return make(decodeKeyName(s),rf,systemType,replicas);
}
// Make a Key which is homed to specific nodes.
static public Key make(byte[] kb, byte rf, byte systemType, H2ONode... replicas) {
// no more than 3 replicas allowed to be stored in the key
assert 0 <=replicas.length && replicas.length<=3;
assert systemType<32; // only system keys allowed
// Key byte layout is:
// 0 - systemType, from 0-31
// 1 - replica-count, plus up to 3 bits for ip4 vs ip6
// 2-n - zero, one, two or 3 IP4 (4+2 bytes) or IP6 (16+2 bytes) addresses
// n+ - kb.length, repeat of the original kb
AutoBuffer ab = new AutoBuffer();
ab.put1(systemType).put1(replicas.length);
for( H2ONode h2o : replicas )
h2o.write(ab);
ab.putA1(kb);
return make(Arrays.copyOf(ab.buf(),ab.position()),rf);
}
// Custom Serialization Reader: Keys must be interned on construction.
public Key read(AutoBuffer bb) { return make(bb.getA1()); }
public AutoBuffer write(AutoBuffer bb) { return bb.putA1(_kb); }
// Expand a KEY_OF_KEYS into an array of keys
public Key[] flatten() {
assert (_kb[0]&0xFF)==KEY_OF_KEYS;
Value val = DKV.get(this);
if( val == null ) return null;
return ((Key.Ary)val.get())._keys;
}
// User keys must be all ASCII, but we only check the 1st byte
public boolean user_allowed() {
return (_kb[0]&0xFF) >= 32;
}
// Returns the type of the key.
public int type() {
return ((_kb[0]&0xff)>=32) ? USER_KEY : (_kb[0]&0xff);
}
public static final char MAGIC_CHAR = '$';
private static final char[] HEX = "0123456789abcdef".toCharArray();
/** Converts the key to HTML displayable string.
*
* For user keys returns the key itself, for system keys returns their
* hexadecimal values.
*
* @return key as a printable string
*/
public String toString() {
int len = _kb.length;
while( --len >= 0 ) {
char a = (char) _kb[len];
if (' ' <= a && a <= '#') continue;
// then we have $ which is not allowed
if ('%' <= a && a <= '~') continue;
// already in the one above
//if( 'a' <= a && a <= 'z' ) continue;
//if( 'A' <= a && a <= 'Z' ) continue;
//if( '0' <= a && a <= '9' ) continue;
break;
}
if (len>=0) {
StringBuilder sb = new StringBuilder();
sb.append(MAGIC_CHAR);
for( int i = 0; i <= len; ++i ) {
byte a = _kb[i];
sb.append(HEX[(a >> 4) & 0x0F]);
sb.append(HEX[(a >> 0) & 0x0F]);
}
sb.append(MAGIC_CHAR);
for( int i = len + 1; i < _kb.length; ++i ) sb.append((char)_kb[i]);
return sb.toString();
} else {
return new String(_kb);
}
}
private static byte[] decodeKeyName(String what) {
if( what==null ) return null;
if (what.charAt(0) == MAGIC_CHAR) {
int len = what.indexOf(MAGIC_CHAR,1);
String tail = what.substring(len+1);
byte[] res = new byte[(len-1)/2 + tail.length()];
int r = 0;
for( int i = 1; i < len; i+=2 ) {
char h = what.charAt(i);
char l = what.charAt(i+1);
h -= Character.isDigit(h) ? '0' : ('a' - 10);
l -= Character.isDigit(l) ? '0' : ('a' - 10);
res[r++] = (byte)(h << 4 | l);
}
System.arraycopy(tail.getBytes(), 0, res, r, tail.length());
return res;
} else {
return what.getBytes();
}
}
public int hashCode() { return _hash; }
public boolean equals( Object o ) {
if( this == o ) return true;
Key k = (Key)o;
return Arrays.equals(k._kb,_kb);
}
public int compareTo(Object o) {
assert (o instanceof Key);
return this.toString().compareTo(o.toString());
}
// Simple wrapper class defining an array-of-keys that is serializable.
// Note that if you modify any fields of a POJO that is part of a Value,
// - this is not the recommended programming style,
// - those changes are visible to all on the node,
// - but not to other nodes
// - and the POJO might be dropped by the MemoryManager and reconstitued from
// disk and/or the byte array back to it's original form.
public static class Ary extends Iced {
public final Key[] _keys;
Ary( Key[] keys ) { _keys = keys; }
}
}
|
src/main/java/water/Key.java
|
package water;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
/**
* Keys
*
* This class defines:
* - A Key's bytes (name) & hash
* - Known Disk & memory replicas.
* - A cache of somewhat expensive to compute stuff related to the current
* Cloud, plus a byte of the desired replication factor.
*
* Keys are expected to be a high-count item, hence the care about size.
*
* Keys are *interned* in the local K/V store, a non-blocking hash set and are
* kept pointer equivalent (via the interning) for cheap compares. The
* interning only happens after a successful insert in the local H2O.STORE via
* H2O.put_if_later.
*
* @author <a href="mailto:cliffc@0xdata.com"></a>
* @version 1.0
*/
public final class Key extends Iced implements Comparable {
// The Key!!!
// Limited to 512 random bytes - to fit better in UDP packets.
public static final int KEY_LENGTH = 512;
public byte[] _kb; // Key bytes, wire-line protocol
transient int _hash; // Hash on key alone (and not value)
// The user keys must be ASCII, so the values 0..31 are reserved for system
// keys. When you create a system key, please do add its number to this list
public static final byte ARRAYLET_CHUNK = 0;
public static final byte KEY_OF_KEYS = 1;
public static final byte BUILT_IN_KEY = 2; // C.f. Constants.BUILT_IN_KEY_*
public static final byte JOB = 3;
public static final byte HDFS_INTERNAL_BLOCK = 10;
public static final byte HDFS_INODE = 11;
public static final byte HDFS_BLOCK_INFO = 12;
public static final byte HDFS_BLOCK_SHADOW = 13;
public static final byte DFJ_INTERNAL_USER = 14;
public static final byte USER_KEY = 32;
// 64 bits of Cloud-specific cached stuff. It is changed atomically by any
// thread that visits it and has the wrong Cloud. It has to be read *in the
// context of a specific Cloud*, since a re-read may be for another Cloud.
private transient volatile long _cache;
private static final AtomicLongFieldUpdater<Key> _cacheUpdater =
AtomicLongFieldUpdater.newUpdater(Key.class, "_cache");
// Accessors and updaters for the Cloud-specific cached stuff.
// The Cloud index, a byte uniquely identifying the last 256 Clouds. It
// changes atomically with the _cache word, so we can tell which Cloud this
// data is a cache of.
private static int cloud( long cache ) { return (int)(cache>>> 0)&0x00FF; }
// Shortcut node index for Home replica#0. This replica is responsible for
// breaking ties on writes. 'char' because I want an unsigned 16bit thing,
// limit of 65534 Cloud members. -1 is reserved for a bare-key
private static int home ( long cache ) { return (int)(cache>>> 8)&0xFFFF; }
// Our replica #, or -1 if we're not one of the first 127 replicas. This
// value is found using the Cloud distribution function and changes for a
// changed Cloud.
private static int replica(long cache) { return (byte)(cache>>>24)&0x00FF; }
// Desired replication factor. Can be zero for temp keys. Not allowed to
// later, because it messes with e.g. meta-data on disk.
private static int desired(long cache) { return (int)(cache>>>32)&0x00FF; }
private static long build_cache( int cidx, int home, int replica, int desired ) {
return // Build the new cache word
((long)(cidx &0xFF)<< 0) |
((long)(home &0xFFFF)<< 8) |
((long)(replica&0xFF)<<24) |
((long)(desired&0xFF)<<32) |
((long)(0 )<<40);
}
public int home ( H2O cloud ) { return home (cloud_info(cloud)); }
public int replica( H2O cloud ) { return replica(cloud_info(cloud)); }
public int desired( ) { return desired(_cache); }
public boolean home() { return H2O.CLOUD._memary[home(H2O.CLOUD)]==H2O.SELF; }
public H2ONode home_node( ) {
H2O cloud = H2O.CLOUD;
return cloud._memary[home(cloud)];
}
// Update the cache, but only to strictly newer Clouds
private boolean set_cache( long cache ) {
while( true ) { // Spin till get it
long old = _cache; // Read once at the start
if( !H2O.larger(cloud(cache),cloud(old)) ) // Rolling backwards?
// Attempt to set for an older Cloud. Blow out with a failure; caller
// should retry on a new Cloud.
return false;
assert cloud(cache) != cloud(old) || cache == old;
if( old == cache ) return true; // Fast-path cutout
if( _cacheUpdater.compareAndSet(this,old,cache) ) return true;
// Can fail if the cache is really old, and just got updated to a version
// which is still not the latest, and we are trying to update it again.
}
}
// Return the info word for this Cloud. Use the cache if possible
public long cloud_info( H2O cloud ) {
long x = _cache;
// See if cached for this Cloud. This should be the 99% fast case.
if( cloud(x) == cloud._idx ) return x;
// Cache missed! Probaby it just needs (atomic) updating.
// But we might be holding the stale cloud...
// Figure out home Node in this Cloud
char home = (char)cloud.D(this,0);
// Figure out what replica # I am, if any
int desired = desired(x);
int replica = -1;
for( int i=0; i<desired; i++ ) {
int idx = cloud.D(this,i);
if( idx >= 0 && cloud._memary[idx] == H2O.SELF ) {
replica = i;
break;
}
}
long cache = build_cache(cloud._idx,home,replica,desired);
set_cache(cache); // Attempt to upgrade cache, but ignore failure
return cache; // Return the magic word for this Cloud
}
// Default desired replication factor. Unless specified otherwise, all new
// k-v pairs start with this replication factor.
public static final byte DEFAULT_DESIRED_REPLICA_FACTOR = 2;
// Construct a new Key.
private Key(byte[] kb) {
if( kb.length > KEY_LENGTH ) throw new IllegalArgumentException("Key length would be "+kb.length);
_kb = kb;
// For arraylets, arrange that the first 64Megs/Keys worth spread nicely,
// but that the next 64Meg (and each 64 after that) target the same node,
// so that HDFS blocks hit only 1 node in the typical spread.
int i=0; // Include these header bytes or not
int chk = 0; // Chunk number, for chunks beyond 64Meg
if( kb.length >= 10 && kb[0] == ARRAYLET_CHUNK && kb[1] == 0 ) {
long off = UDP.get8(kb,2);
if( (off >> 20) >= 64 ) { // Is offset >= 64Meg?
i += 2+8; // Skip the length bytes; they are now not part of hash
chk = (int)(off >>> (6+20)); // Divide by 64Meg; comes up with a "block number"
}
}
int hash = 0;
// Quicky hash: http://en.wikipedia.org/wiki/Jenkins_hash_function
for( ; i<kb.length; i++ ) {
hash += kb[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
_hash = hash+chk; // Add sequential block numbering
}
// Make new Keys. Optimistically attempt interning, but no guarantee.
static public Key make(byte[] kb, byte rf) {
if( rf == -1 ) throw new IllegalArgumentException();
Key key = new Key(kb);
Key key2 = H2O.getk(key); // Get the interned version, if any
if( key2 != null ) // There is one! Return it instead
return key2;
// Set the cache with desired replication factor, and a fake cloud index
H2O cloud = H2O.CLOUD; // Read once
key._cache = build_cache(cloud._idx-1,0,0,rf);
key.cloud_info(cloud); // Now compute & cache the real data
return key;
}
static public Key make(byte[] kb) { return make(kb,DEFAULT_DESIRED_REPLICA_FACTOR); }
static public Key make(String s) { return make(decodeKeyName(s));}
static public Key make(String s, byte rf) { return make(decodeKeyName(s), rf);}
static public Key make() { return make( UUID.randomUUID().toString() ); }
// Make a particular system key that is homed to given node and possibly
// specifies also other 2 replicas. Works for both IPv4 and IPv6 addresses.
// If the addresses are not specified, returns a key with no home information.
static public Key make(String s, byte rf, byte systemType, H2ONode... replicas) {
return make(decodeKeyName(s),rf,systemType,replicas);
}
// Make a Key which is homed to specific nodes.
static public Key make(byte[] kb, byte rf, byte systemType, H2ONode... replicas) {
// no more than 3 replicas allowed to be stored in the key
assert 0 <=replicas.length && replicas.length<=3;
assert systemType<32; // only system keys allowed
// Key byte layout is:
// 0 - systemType, from 0-31
// 1 - replica-count, plus up to 3 bits for ip4 vs ip6
// 2-n - zero, one, two or 3 IP4 (4+2 bytes) or IP6 (16+2 bytes) addresses
// n+ - kb.length, repeat of the original kb
AutoBuffer ab = new AutoBuffer();
ab.put1(systemType).put1(replicas.length);
for( H2ONode h2o : replicas )
h2o.write(ab);
ab.putA1(kb);
return make(Arrays.copyOf(ab.buf(),ab.position()),rf);
}
// Custom Serialization Reader: Keys must be interned on construction.
public Key read(AutoBuffer bb) { return make(bb.getA1()); }
public AutoBuffer write(AutoBuffer bb) { return bb.putA1(_kb); }
// Expand a KEY_OF_KEYS into an array of keys
public Key[] flatten() {
assert (_kb[0]&0xFF)==KEY_OF_KEYS;
Value val = DKV.get(this);
if( val == null ) return null;
return ((Key.Ary)val.get())._keys;
}
// User keys must be all ASCII, but we only check the 1st byte
public boolean user_allowed() {
return (_kb[0]&0xFF) >= 32;
}
// Returns the type of the key.
public int type() {
return ((_kb[0]&0xff)>=32) ? USER_KEY : (_kb[0]&0xff);
}
public static final char MAGIC_CHAR = '$';
private static final char[] HEX = "0123456789abcdef".toCharArray();
/** Converts the key to HTML displayable string.
*
* For user keys returns the key itself, for system keys returns their
* hexadecimal values.
*
* @return key as a printable string
*/
public String toString() {
int len = _kb.length;
while( --len >= 0 ) {
char a = (char) _kb[len];
if (' ' <= a && a <= '#') continue;
// then we have $ which is not allowed
if ('%' <= a && a <= '~') continue;
// already in the one above
//if( 'a' <= a && a <= 'z' ) continue;
//if( 'A' <= a && a <= 'Z' ) continue;
//if( '0' <= a && a <= '9' ) continue;
break;
}
if (len>=0) {
StringBuilder sb = new StringBuilder();
sb.append(MAGIC_CHAR);
for( int i = 0; i <= len; ++i ) {
byte a = _kb[i];
sb.append(HEX[(a >> 4) & 0x0F]);
sb.append(HEX[(a >> 0) & 0x0F]);
}
sb.append(MAGIC_CHAR);
for( int i = len + 1; i < _kb.length; ++i ) sb.append((char)_kb[i]);
return sb.toString();
} else {
return new String(_kb);
}
}
private static byte[] decodeKeyName(String what) {
if( what==null ) return null;
if (what.charAt(0) == MAGIC_CHAR) {
int len = what.indexOf(MAGIC_CHAR,1);
String tail = what.substring(len+1);
byte[] res = new byte[(len-1)/2 + tail.length()];
int r = 0;
for( int i = 1; i < len; i+=2 ) {
char h = what.charAt(i);
char l = what.charAt(i+1);
h -= Character.isDigit(h) ? '0' : ('a' - 10);
l -= Character.isDigit(l) ? '0' : ('a' - 10);
res[r++] = (byte)(h << 4 | l);
}
System.arraycopy(tail.getBytes(), 0, res, r, tail.length());
return res;
} else {
return what.getBytes();
}
}
public int hashCode() { return _hash; }
public boolean equals( Object o ) {
if( this == o ) return true;
Key k = (Key)o;
return Arrays.equals(k._kb,_kb);
}
public int compareTo(Object o) {
assert (o instanceof Key);
return this.toString().compareTo(o.toString());
}
// Simple wrapper class defining an array-of-keys that is serializable.
// Note that if you modify any fields of a POJO that is part of a Value,
// - this is not the recommended programming style,
// - those changes are visible to all on the node,
// - but not to other nodes
// - and the POJO might be dropped by the MemoryManager and reconstitued from
// disk and/or the byte array back to it's original form.
public static class Ary extends Iced {
public final Key[] _keys;
Ary( Key[] keys ) { _keys = keys; }
}
}
|
cleanup
|
src/main/java/water/Key.java
|
cleanup
|
|
Java
|
apache-2.0
|
b9eaf0f73a7c6ae1607261abea3f2148a07ef7e0
| 0
|
terrameta/plasma,terrameta/plasma,plasma-framework/plasma,plasma-framework/plasma
|
/**
* PlasmaSDO™ License
*
* This is a community release of PlasmaSDO™, a dual-license
* Service Data Object (SDO) 2.1 implementation.
* This particular copy of the software is released under the
* version 2 of the GNU General Public License. PlasmaSDO™ was developed by
* TerraMeta Software, Inc.
*
* Copyright (c) 2013, TerraMeta Software, Inc. All rights reserved.
*
* General License information can be found below.
*
* This distribution may include materials developed by third
* parties. For license and attribution notices for these
* materials, please refer to the documentation that accompanies
* this distribution (see the "Licenses for Third-Party Components"
* appendix) or view the online documentation at
* <http://plasma-sdo.org/licenses/>.
*
*/
package org.plasma.sdo.helper;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.plasma.config.Namespace;
import org.plasma.config.PlasmaConfig;
import org.plasma.sdo.PlasmaDataGraph;
import org.plasma.sdo.PlasmaDataObject;
import org.plasma.sdo.access.client.PojoDataAccessClient;
import org.plasma.sdo.core.CoreConstants;
import org.plasma.sdo.core.CoreDataGraph;
import org.plasma.sdo.core.CoreDataObject;
import commonj.sdo.DataObject;
import commonj.sdo.Type;
import commonj.sdo.helper.DataFactory;
import commonj.sdo.helper.TypeHelper;
public class PlasmaDataFactory implements DataFactory {
private static Log log = LogFactory.getLog(PlasmaDataFactory.class);
static public volatile PlasmaDataFactory INSTANCE = initializeInstance();
private PlasmaDataFactory() {
}
public static PlasmaDataFactory instance()
{
if (INSTANCE == null)
initializeInstance();
return INSTANCE;
}
private static synchronized PlasmaDataFactory initializeInstance()
{
if (INSTANCE == null)
INSTANCE = new PlasmaDataFactory();
return INSTANCE;
}
public PlasmaDataGraph createDataGraph() {
return new CoreDataGraph();
}
public DataObject create(String uri, String typeName) {
Type type = PlasmaTypeHelper.INSTANCE.getType(uri, typeName);
String packageName = PlasmaConfig.getInstance().getSDOImplementationPackageName(uri);
if (packageName != null) {
return this.create(type);
}
else
return new CoreDataObject(type);
}
public DataObject create(Type type) {
DataObject result = null;
if (type.isAbstract())
throw new IllegalArgumentException("attempt to create an abstract type '"
+ type.getURI() + "#" + type.getName() + "'");
if (type.isDataType())
throw new IllegalArgumentException("attempt to create a type which is a datatype '"
+ type.getURI() + "#" + type.getName() + "'");
String packageName = PlasmaConfig.getInstance().getSDOImplementationPackageName(type.getURI());
String className = PlasmaConfig.getInstance().getSDOImplementationClassName(type.getURI(),
type.getName());
String qualifiedName = packageName + "." + className;
try {
Class<?> interfaceImplClass = Class.forName(qualifiedName);
result = this.create(interfaceImplClass, type);
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("no interface class found for qualified name '"
+ qualifiedName + "' - using generic DataObject");
CoreDataObject dataObject = new CoreDataObject(type);
result = dataObject;
}
return result;
}
@SuppressWarnings("rawtypes")
public DataObject create(Class interfaceClass) {
CoreDataObject result = null;
Namespace sdoNamespace = PlasmaConfig.getInstance().getSDONamespaceByInterfacePackage(
interfaceClass.getPackage().getName());
String packageName = PlasmaConfig.getInstance().getSDOImplementationPackageName(sdoNamespace.getUri());
String className = PlasmaConfig.getInstance().getSDOImplementationClassName(sdoNamespace.getUri(),
interfaceClass.getSimpleName());
String qualifiedName = packageName + "." + className;
Class<?>[] types = new Class<?>[0];
Object[] args = new Object[0];
try {
Class<?> interfaceImplClass = Class.forName(qualifiedName);
Constructor<?> constructor = interfaceImplClass.getConstructor(types);
result = (CoreDataObject)constructor.newInstance(args);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
return result;
}
private DataObject create(Class<?> interfaceClass, Type type) {
CoreDataObject result = null;
Class<?>[] types = { Type.class };
Object[] args = { type };
try {
Constructor<?> constructor = interfaceClass.getConstructor(types);
result = (CoreDataObject)constructor.newInstance(args);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
return result;
}
}
|
plasma-sdo/src/main/java/org/plasma/sdo/helper/PlasmaDataFactory.java
|
/**
* PlasmaSDO™ License
*
* This is a community release of PlasmaSDO™, a dual-license
* Service Data Object (SDO) 2.1 implementation.
* This particular copy of the software is released under the
* version 2 of the GNU General Public License. PlasmaSDO™ was developed by
* TerraMeta Software, Inc.
*
* Copyright (c) 2013, TerraMeta Software, Inc. All rights reserved.
*
* General License information can be found below.
*
* This distribution may include materials developed by third
* parties. For license and attribution notices for these
* materials, please refer to the documentation that accompanies
* this distribution (see the "Licenses for Third-Party Components"
* appendix) or view the online documentation at
* <http://plasma-sdo.org/licenses/>.
*
*/
package org.plasma.sdo.helper;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.plasma.config.Namespace;
import org.plasma.config.PlasmaConfig;
import org.plasma.sdo.PlasmaDataGraph;
import org.plasma.sdo.PlasmaDataObject;
import org.plasma.sdo.access.client.PojoDataAccessClient;
import org.plasma.sdo.core.CoreConstants;
import org.plasma.sdo.core.CoreDataGraph;
import org.plasma.sdo.core.CoreDataObject;
import commonj.sdo.DataObject;
import commonj.sdo.Type;
import commonj.sdo.helper.DataFactory;
import commonj.sdo.helper.TypeHelper;
public class PlasmaDataFactory implements DataFactory {
private static Log log = LogFactory.getLog(PlasmaDataFactory.class);
static public PlasmaDataFactory INSTANCE = initializeInstance();
private PlasmaDataFactory() {
}
public static PlasmaDataFactory instance()
{
if (INSTANCE == null)
initializeInstance();
return INSTANCE;
}
private static synchronized PlasmaDataFactory initializeInstance()
{
if (INSTANCE == null)
INSTANCE = new PlasmaDataFactory();
return INSTANCE;
}
public PlasmaDataGraph createDataGraph() {
return new CoreDataGraph();
}
public DataObject create(String uri, String typeName) {
Type type = PlasmaTypeHelper.INSTANCE.getType(uri, typeName);
String packageName = PlasmaConfig.getInstance().getSDOImplementationPackageName(uri);
if (packageName != null) {
return this.create(type);
}
else
return new CoreDataObject(type);
}
public DataObject create(Type type) {
DataObject result = null;
if (type.isAbstract())
throw new IllegalArgumentException("attempt to create an abstract type '"
+ type.getURI() + "#" + type.getName() + "'");
if (type.isDataType())
throw new IllegalArgumentException("attempt to create a type which is a datatype '"
+ type.getURI() + "#" + type.getName() + "'");
String packageName = PlasmaConfig.getInstance().getSDOImplementationPackageName(type.getURI());
String className = PlasmaConfig.getInstance().getSDOImplementationClassName(type.getURI(),
type.getName());
String qualifiedName = packageName + "." + className;
try {
Class<?> interfaceImplClass = Class.forName(qualifiedName);
result = this.create(interfaceImplClass, type);
} catch (ClassNotFoundException e) {
if (log.isDebugEnabled())
log.debug("no interface class found for qualified name '"
+ qualifiedName + "' - using generic DataObject");
CoreDataObject dataObject = new CoreDataObject(type);
result = dataObject;
}
return result;
}
@SuppressWarnings("rawtypes")
public DataObject create(Class interfaceClass) {
CoreDataObject result = null;
Namespace sdoNamespace = PlasmaConfig.getInstance().getSDONamespaceByInterfacePackage(
interfaceClass.getPackage().getName());
String packageName = PlasmaConfig.getInstance().getSDOImplementationPackageName(sdoNamespace.getUri());
String className = PlasmaConfig.getInstance().getSDOImplementationClassName(sdoNamespace.getUri(),
interfaceClass.getSimpleName());
String qualifiedName = packageName + "." + className;
Class<?>[] types = new Class<?>[0];
Object[] args = new Object[0];
try {
Class<?> interfaceImplClass = Class.forName(qualifiedName);
Constructor<?> constructor = interfaceImplClass.getConstructor(types);
result = (CoreDataObject)constructor.newInstance(args);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
return result;
}
private DataObject create(Class<?> interfaceClass, Type type) {
CoreDataObject result = null;
Class<?>[] types = { Type.class };
Object[] args = { type };
try {
Constructor<?> constructor = interfaceClass.getConstructor(types);
result = (CoreDataObject)constructor.newInstance(args);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
return result;
}
}
|
Update PlasmaDataFactory.java
|
plasma-sdo/src/main/java/org/plasma/sdo/helper/PlasmaDataFactory.java
|
Update PlasmaDataFactory.java
|
|
Java
|
apache-2.0
|
211d6b3cd354e7655481ed56ae6d313aacdcbe9d
| 0
|
ddviplinux/cat,xiaojiaqi/cat,dadarom/cat,dadarom/cat,wuqiangxjtu/cat,michael8335/cat,chinaboard/cat,gspandy/cat,bryanchou/cat,wyzssw/cat,dianping/cat,dianping/cat,howepeng/cat,dianping/cat,wyzssw/cat,chinaboard/cat,itnihao/cat,unidal/cat,gspandy/cat,JacksonSha/cat,JacksonSha/cat,wuqiangxjtu/cat,wyzssw/cat,jialinsun/cat,unidal/cat,dadarom/cat,javachengwc/cat,javachengwc/cat,TonyChai24/cat,jialinsun/cat,chqlb/cat,gspandy/cat,itnihao/cat,jialinsun/cat,dianping/cat,cdljsj/cat,jialinsun/cat,jialinsun/cat,TonyChai24/cat,howepeng/cat,unidal/cat,ddviplinux/cat,chinaboard/cat,howepeng/cat,chqlb/cat,xiaojiaqi/cat,chqlb/cat,JacksonSha/cat,unidal/cat,wyzssw/cat,redbeans2015/cat,ddviplinux/cat,JacksonSha/cat,itnihao/cat,cdljsj/cat,dadarom/cat,TonyChai24/cat,chqlb/cat,dadarom/cat,itnihao/cat,michael8335/cat,dadarom/cat,redbeans2015/cat,TonyChai24/cat,xiaojiaqi/cat,TonyChai24/cat,ddviplinux/cat,gspandy/cat,xiaojiaqi/cat,xiaojiaqi/cat,jialinsun/cat,itnihao/cat,redbeans2015/cat,cdljsj/cat,wyzssw/cat,dianping/cat,michael8335/cat,JacksonSha/cat,cdljsj/cat,howepeng/cat,bryanchou/cat,redbeans2015/cat,unidal/cat,bryanchou/cat,michael8335/cat,javachengwc/cat,TonyChai24/cat,ddviplinux/cat,cdljsj/cat,howepeng/cat,michael8335/cat,gspandy/cat,JacksonSha/cat,chinaboard/cat,wuqiangxjtu/cat,howepeng/cat,dianping/cat,itnihao/cat,redbeans2015/cat,ddviplinux/cat,bryanchou/cat,gspandy/cat,javachengwc/cat,unidal/cat,chinaboard/cat,javachengwc/cat,chqlb/cat,bryanchou/cat,cdljsj/cat,wuqiangxjtu/cat,bryanchou/cat,dianping/cat,wuqiangxjtu/cat,javachengwc/cat,chinaboard/cat,wuqiangxjtu/cat,wyzssw/cat,redbeans2015/cat,michael8335/cat,xiaojiaqi/cat,chqlb/cat
|
package com.dianping.cat.storage.dump;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.unidal.helper.Files;
import org.unidal.helper.Scanners;
import org.unidal.helper.Scanners.FileMatcher;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.ContainerHolder;
import org.unidal.lookup.annotation.Inject;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.configuration.ServerConfigManager;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.MessageProducer;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.internal.MessageId;
import com.dianping.cat.message.spi.MessagePathBuilder;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;
import com.dianping.cat.status.ServerStateManager;
public class LocalMessageBucketManager extends ContainerHolder implements MessageBucketManager, Initializable,
LogEnabled {
public static final String ID = "local";
private static final long ONE_HOUR = 60 * 60 * 1000L;
private File m_baseDir;
private Map<String, LocalMessageBucket> m_buckets = new HashMap<String, LocalMessageBucket>();
@Inject
private ServerConfigManager m_configManager;
@Inject
private ServerStateManager m_serverStateManager;
@Inject
private MessagePathBuilder m_pathBuilder;
private String m_localIp = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
private long m_error;
private long m_total;
private long m_totalSize = 0;
private long m_lastTotalSize = 0;
private Logger m_logger;
private int m_gzipThreads = 5;
private BlockingQueue<MessageBlock> m_messageBlocks = new LinkedBlockingQueue<MessageBlock>(10000);
private Map<Integer, LinkedBlockingQueue<MessageItem>> m_messageQueues = new HashMap<Integer, LinkedBlockingQueue<MessageItem>>();
private long[] m_processMessages = new long[m_gzipThreads];
public void archive(long startTime) {
String path = m_pathBuilder.getPath(new Date(startTime), "");
List<String> keys = new ArrayList<String>();
synchronized (m_buckets) {
for (String key : m_buckets.keySet()) {
if (key.startsWith(path)) {
keys.add(key);
}
}
try {
for (String key : keys) {
LocalMessageBucket bucket = m_buckets.get(key);
try {
MessageBlock block = bucket.flushBlock();
if (block != null) {
m_messageBlocks.add(block);
}
} catch (IOException e) {
Cat.logError(e);
}
}
} catch (Exception e) {
Cat.logError(e);
}
}
}
@Override
public void close() throws IOException {
synchronized (m_buckets) {
for (LocalMessageBucket bucket : m_buckets.values()) {
bucket.close();
}
m_buckets.clear();
}
}
void closeIdleBuckets() throws IOException {
long now = System.currentTimeMillis();
long hour = 3600 * 1000L;
List<String> closedKeys = new ArrayList<String>();
synchronized (m_buckets) {
for (Map.Entry<String, LocalMessageBucket> e : m_buckets.entrySet()) {
LocalMessageBucket bucket = e.getValue();
if (now - bucket.getLastAccessTime() > 4 * hour) {
Cat.getProducer().logEvent("Bucket", "Close.Abnormal", Event.SUCCESS, e.getKey());
m_logger.warn("close bucket abnormal " + e.getKey());
bucket.close();
closedKeys.add(e.getKey());
}
}
for (String key : closedKeys) {
m_buckets.remove(key);
}
}
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
@Override
public void initialize() throws InitializationException {
if (m_baseDir == null) {
m_baseDir = new File(m_configManager.getHdfsLocalBaseDir("dump"));
}
Threads.forGroup("Cat").start(new BlockDumper());
Threads.forGroup("Cat").start(new IdleChecker());
Threads.forGroup("Cat").start(new OldMessageMover());
for (int i = 0; i < m_gzipThreads; i++) {
Threads.forGroup("Cat").start(new MessageGzip(i));
}
}
@Override
public MessageTree loadMessage(String messageId) throws IOException {
MessageProducer cat = Cat.getProducer();
Transaction t = cat.newTransaction("BucketService", getClass().getSimpleName());
t.setStatus(Message.SUCCESS);
try {
MessageId id = MessageId.parse(messageId);
final String path = m_pathBuilder.getPath(new Date(id.getTimestamp()), "");
final File dir = new File(m_baseDir, path);
final String key = id.getDomain() + '-' + id.getIpAddress();
final List<String> paths = new ArrayList<String>();
Scanners.forDir().scan(dir, new FileMatcher() {
@Override
public Direction matches(File base, String name) {
if (name.contains(key) && !name.endsWith(".idx")) {
paths.add(path + name);
}
return Direction.NEXT;
}
});
for (String dataFile : paths) {
LocalMessageBucket bucket = m_buckets.get(dataFile);
if (bucket == null) {
File file = new File(m_baseDir, dataFile);
if (file.exists()) {
bucket = (LocalMessageBucket) lookup(MessageBucket.class, LocalMessageBucket.ID);
bucket.setBaseDir(m_baseDir);
bucket.initialize(dataFile);
m_buckets.put(dataFile, bucket);
m_logger.info("create local message bucket by read message tree,path:" + m_baseDir + dataFile);
}
}
if (bucket != null) {
// flush the buffer if have data
MessageBlock block = bucket.flushBlock();
if (block != null) {
m_messageBlocks.offer(block);
LockSupport.parkNanos(50 * 1000 * 1000L); // wait 50 ms
}
MessageTree tree = bucket.findByIndex(id.getIndex());
if (tree != null && tree.getMessageId().equals(messageId)) {
t.addData("path", dataFile);
return tree;
}
}
}
return null;
} catch (IOException e) {
t.setStatus(e);
cat.logError(e);
throw e;
} catch (RuntimeException e) {
t.setStatus(e);
cat.logError(e);
throw e;
} catch (Error e) {
t.setStatus(e);
cat.logError(e);
throw e;
} finally {
t.complete();
}
}
private void moveOldMessages() {
final List<String> paths = new ArrayList<String>();
Scanners.forDir().scan(m_baseDir, new FileMatcher() {
@Override
public Direction matches(File base, String path) {
if (new File(base, path).isFile()) {
if (path.indexOf(".idx") == -1 && shouldMove(path)) {
paths.add(path);
}
}
return Direction.DOWN;
}
});
if (paths.size() > 0) {
String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
Transaction t = Cat.newTransaction("System", "Dump" + "-" + ip);
t.setStatus(Message.SUCCESS);
for (String path : paths) {
File file = new File(m_baseDir, path);
String loginfo = "path:" + m_baseDir + path + ",file size: " + file.length();
LocalMessageBucket bucket = m_buckets.get(path);
if (bucket != null) {
try {
bucket.close();
bucket.archive();
Cat.getProducer().logEvent("Dump", "Outbox.Normal", Message.SUCCESS, loginfo);
m_logger.info("move data file to outbox normal, " + loginfo);
} catch (Exception e) {
t.setStatus(e);
Cat.logError(e);
m_logger.error(e.getMessage(), e);
}
m_buckets.remove(path);
} else {
try {
moveFile(path);
moveFile(path + ".idx");
Cat.getProducer().logEvent("Dump", "Outbox.Abnormal", Message.SUCCESS, loginfo);
m_logger.info("move data file to outbox abnormal, " + loginfo);
} catch (Exception e) {
t.setStatus(e);
Cat.logError(e);
m_logger.error(e.getMessage(), e);
}
}
}
t.complete();
}
}
private void moveFile(String path) throws IOException {
File outbox = new File(m_baseDir, "outbox");
File from = new File(m_baseDir, path);
File to = new File(outbox, path);
to.getParentFile().mkdirs();
Files.forDir().copyFile(from, to);
Files.forDir().delete(from);
File parentFile = from.getParentFile();
parentFile.delete(); // delete it if empty
parentFile.getParentFile().delete(); // delete it if empty
}
public void setBaseDir(File baseDir) {
m_baseDir = baseDir;
}
private boolean shouldMove(String path) {
if (path.indexOf("draft") > -1 || path.indexOf("outbox") > -1) {
return false;
}
long current = System.currentTimeMillis();
long currentHour = current - current % ONE_HOUR;
long lastHour = currentHour - ONE_HOUR;
long nextHour = currentHour + ONE_HOUR;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd/HH");
String currentHourStr = sdf.format(new Date(currentHour));
String lastHourStr = sdf.format(new Date(lastHour));
String nextHourStr = sdf.format(new Date(nextHour));
int indexOf = path.indexOf(currentHourStr);
int indexOfLast = path.indexOf(lastHourStr);
int indexOfNext = path.indexOf(nextHourStr);
if (indexOf > -1 || indexOfLast > -1 || indexOfNext > -1) {
return false;
}
return true;
}
@Override
public void storeMessage(final MessageTree tree, final MessageId id) throws IOException {
String domain = id.getDomain() + id.getIpAddress();
int bucketIndex = Math.abs(domain.hashCode()) % m_gzipThreads;
if (bucketIndex > m_gzipThreads || bucketIndex < 0) {
m_logger.error("Error when compute the message bucket index!" + bucketIndex);
} else {
m_processMessages[bucketIndex]++;
}
LinkedBlockingQueue<MessageItem> items = m_messageQueues.get(bucketIndex);
if (items == null) {
items = new LinkedBlockingQueue<LocalMessageBucketManager.MessageItem>(10000);
m_messageQueues.put(bucketIndex, items);
}
boolean result = items.offer(new MessageItem(tree, id));
if (result == false) {
m_error++;
if (m_error % CatConstants.ERROR_COUNT == 0) {
m_serverStateManager.addMessageDumpLoss(CatConstants.ERROR_COUNT);
m_logger.error("Error when offer message tree to gzip queue! overflow :" + m_error);
}
}
m_total++;
if (m_total % (CatConstants.SUCCESS_COUNT) == 0) {
logState(tree);
}
}
private void logState(final MessageTree tree) {
double amount = m_totalSize - m_lastTotalSize;
m_lastTotalSize = m_totalSize;
m_serverStateManager.addMessageDump(CatConstants.SUCCESS_COUNT);
m_serverStateManager.addMessageSize(amount);
Message message = tree.getMessage();
if (message instanceof Transaction) {
long delay = System.currentTimeMillis() - tree.getMessage().getTimestamp()
- ((Transaction) message).getDurationInMillis();
m_serverStateManager.addProcessDelay(delay);
}
if (m_total % (CatConstants.SUCCESS_COUNT * 1000) == 0) {
m_logger.info("dump message number: " + m_total + " size:" + m_totalSize * 1.0 / 1024 / 1024 / 1024 + "GB");
StringBuilder sb = new StringBuilder("gzip thread process message number :");
for (int i = 0; i < m_gzipThreads; i++) {
sb.append(m_processMessages[i] + "\t");
}
m_logger.info(sb.toString());
}
}
class MessageGzip implements Task {
public int m_index;
public MessageGzip(int index) {
m_index = index;
}
@Override
public void run() {
try {
while (true) {
BlockingQueue<MessageItem> items = m_messageQueues.get(m_index);
if (items != null) {
MessageItem item = items.poll(5, TimeUnit.MILLISECONDS);
if (item != null) {
try {
MessageTree tree = item.getTree();
MessageId id = item.getMessageId();
String name = id.getDomain() + '-' + id.getIpAddress() + '-' + m_localIp;
String dataFile = m_pathBuilder.getPath(new Date(id.getTimestamp()), name);
LocalMessageBucket bucket = m_buckets.get(dataFile);
if (bucket == null) {
bucket = (LocalMessageBucket) lookup(MessageBucket.class, LocalMessageBucket.ID);
bucket.setBaseDir(m_baseDir);
bucket.initialize(dataFile);
m_buckets.put(dataFile, bucket);
}
DefaultMessageTree defaultTree = (DefaultMessageTree) tree;
ChannelBuffer buf = defaultTree.getBuf();
int size = buf.readableBytes();
m_totalSize += size;
MessageBlock bolck = bucket.storeMessage(buf, id);
if (bolck != null) {
if (!m_messageBlocks.offer(bolck)) {
m_logger.error("Error when offer the block to the dump!");
}
}
} catch (Exception e) {
Cat.logError(e);
}
}
}
}
} catch (InterruptedException e) {
// ignore it
}
}
@Override
public String getName() {
return "Message Gizp " + m_index;
}
@Override
public void shutdown() {
}
}
class MessageItem {
private MessageTree m_tree;
private MessageId m_messageId;
public MessageItem(MessageTree tree, MessageId messageId) {
m_tree = tree;
m_messageId = messageId;
}
public MessageTree getTree() {
return m_tree;
}
public void setTree(MessageTree tree) {
m_tree = tree;
}
public MessageId getMessageId() {
return m_messageId;
}
public void setMessageId(MessageId messageId) {
m_messageId = messageId;
}
}
class BlockDumper implements Task {
private int m_errors;
private int m_success;
@Override
public String getName() {
return "LocalMessageBucketManager-BlockDumper";
}
@Override
public void run() {
try {
while (true) {
MessageBlock block = m_messageBlocks.poll(5, TimeUnit.MILLISECONDS);
if (block != null) {
String dataFile = block.getDataFile();
LocalMessageBucket bucket = m_buckets.get(dataFile);
try {
bucket.getWriter().writeBlock(block);
} catch (Throwable e) {
m_errors++;
if (m_errors == 1 || m_errors % 100 == 0) {
Cat.getProducer().logError(
new RuntimeException("Error when dumping for bucket: " + dataFile + ".", e));
}
}
m_success++;
if (m_success % 10000 == 0) {
m_logger.info("block queue size " + m_messageBlocks.size());
}
}
}
} catch (InterruptedException e) {
// ignore it
}
}
@Override
public void shutdown() {
}
}
class IdleChecker implements Task {
@Override
public String getName() {
return "LocalMessageBucketManager-IdleChecker";
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(60 * 1000L); // 1 minute
try {
closeIdleBuckets();
} catch (Throwable e) {
Cat.getProducer().logError(e);
}
}
} catch (InterruptedException e) {
// ignore it
}
}
@Override
public void shutdown() {
}
}
class OldMessageMover implements Task {
@Override
public String getName() {
return "LocalMessageBucketManager-OldMessageMover";
}
@Override
public void run() {
boolean active = true;
while (active) {
try {
moveOldMessages();
} catch (Throwable e) {
m_logger.error(e.getMessage(), e);
}
try {
Thread.sleep(2 * 60 * 1000L);
} catch (InterruptedException e) {
active = false;
}
}
}
@Override
public void shutdown() {
}
}
}
|
cat-core/src/main/java/com/dianping/cat/storage/dump/LocalMessageBucketManager.java
|
package com.dianping.cat.storage.dump;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.unidal.helper.Files;
import org.unidal.helper.Scanners;
import org.unidal.helper.Scanners.FileMatcher;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.ContainerHolder;
import org.unidal.lookup.annotation.Inject;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.configuration.ServerConfigManager;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.MessageProducer;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.internal.MessageId;
import com.dianping.cat.message.spi.MessagePathBuilder;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;
import com.dianping.cat.status.ServerStateManager;
public class LocalMessageBucketManager extends ContainerHolder implements MessageBucketManager, Initializable,
LogEnabled {
public static final String ID = "local";
private static final long ONE_HOUR = 60 * 60 * 1000L;
private File m_baseDir;
private Map<String, LocalMessageBucket> m_buckets = new HashMap<String, LocalMessageBucket>();
@Inject
private ServerConfigManager m_configManager;
@Inject
private ServerStateManager m_serverStateManager;
@Inject
private MessagePathBuilder m_pathBuilder;
private String m_localIp = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
private int m_error;
private int m_total;
private long m_totalSize = 0;
private long m_lastTotalSize = 0;
private Logger m_logger;
private int m_gzipThreads = 3;
private BlockingQueue<MessageBlock> m_messageBlocks = new LinkedBlockingQueue<MessageBlock>(10000);
private Map<Integer, LinkedBlockingQueue<MessageItem>> m_messageQueues = new HashMap<Integer, LinkedBlockingQueue<MessageItem>>();
private long[] m_processMessages = new long[m_gzipThreads];
public void archive(long startTime) {
String path = m_pathBuilder.getPath(new Date(startTime), "");
List<String> keys = new ArrayList<String>();
synchronized (m_buckets) {
for (String key : m_buckets.keySet()) {
if (key.startsWith(path)) {
keys.add(key);
}
}
try {
for (String key : keys) {
LocalMessageBucket bucket = m_buckets.get(key);
try {
MessageBlock block = bucket.flushBlock();
if (block != null) {
m_messageBlocks.add(block);
}
} catch (IOException e) {
Cat.logError(e);
}
}
} catch (Exception e) {
Cat.logError(e);
}
}
}
@Override
public void close() throws IOException {
synchronized (m_buckets) {
for (LocalMessageBucket bucket : m_buckets.values()) {
bucket.close();
}
m_buckets.clear();
}
}
void closeIdleBuckets() throws IOException {
long now = System.currentTimeMillis();
long hour = 3600 * 1000L;
List<String> closedKeys = new ArrayList<String>();
synchronized (m_buckets) {
for (Map.Entry<String, LocalMessageBucket> e : m_buckets.entrySet()) {
LocalMessageBucket bucket = e.getValue();
if (now - bucket.getLastAccessTime() > 4 * hour) {
Cat.getProducer().logEvent("Bucket", "Close.Abnormal", Event.SUCCESS, e.getKey());
m_logger.warn("close bucket abnormal " + e.getKey());
bucket.close();
closedKeys.add(e.getKey());
}
}
for (String key : closedKeys) {
m_buckets.remove(key);
}
}
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
@Override
public void initialize() throws InitializationException {
if (m_baseDir == null) {
m_baseDir = new File(m_configManager.getHdfsLocalBaseDir("dump"));
}
Threads.forGroup("Cat").start(new BlockDumper());
Threads.forGroup("Cat").start(new IdleChecker());
Threads.forGroup("Cat").start(new OldMessageMover());
for (int i = 0; i < m_gzipThreads; i++) {
Threads.forGroup("Cat").start(new MessageGzip(i));
}
}
@Override
public MessageTree loadMessage(String messageId) throws IOException {
MessageProducer cat = Cat.getProducer();
Transaction t = cat.newTransaction("BucketService", getClass().getSimpleName());
t.setStatus(Message.SUCCESS);
try {
MessageId id = MessageId.parse(messageId);
final String path = m_pathBuilder.getPath(new Date(id.getTimestamp()), "");
final File dir = new File(m_baseDir, path);
final String key = id.getDomain() + '-' + id.getIpAddress();
final List<String> paths = new ArrayList<String>();
Scanners.forDir().scan(dir, new FileMatcher() {
@Override
public Direction matches(File base, String name) {
if (name.contains(key) && !name.endsWith(".idx")) {
paths.add(path + name);
}
return Direction.NEXT;
}
});
for (String dataFile : paths) {
LocalMessageBucket bucket = m_buckets.get(dataFile);
if (bucket == null) {
File file = new File(m_baseDir, dataFile);
if (file.exists()) {
bucket = (LocalMessageBucket) lookup(MessageBucket.class, LocalMessageBucket.ID);
bucket.setBaseDir(m_baseDir);
bucket.initialize(dataFile);
m_buckets.put(dataFile, bucket);
m_logger.info("create local message bucket by read message tree,path:" + m_baseDir + dataFile);
}
}
if (bucket != null) {
// flush the buffer if have data
MessageBlock block = bucket.flushBlock();
if (block != null) {
m_messageBlocks.offer(block);
LockSupport.parkNanos(50 * 1000 * 1000L); // wait 50 ms
}
MessageTree tree = bucket.findByIndex(id.getIndex());
if (tree != null && tree.getMessageId().equals(messageId)) {
t.addData("path", dataFile);
return tree;
}
}
}
return null;
} catch (IOException e) {
t.setStatus(e);
cat.logError(e);
throw e;
} catch (RuntimeException e) {
t.setStatus(e);
cat.logError(e);
throw e;
} catch (Error e) {
t.setStatus(e);
cat.logError(e);
throw e;
} finally {
t.complete();
}
}
private void moveOldMessages() {
final List<String> paths = new ArrayList<String>();
Scanners.forDir().scan(m_baseDir, new FileMatcher() {
@Override
public Direction matches(File base, String path) {
if (new File(base, path).isFile()) {
if (path.indexOf(".idx") == -1 && shouldMove(path)) {
paths.add(path);
}
}
return Direction.DOWN;
}
});
if (paths.size() > 0) {
String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();
Transaction t = Cat.newTransaction("System", "Dump" + "-" + ip);
t.setStatus(Message.SUCCESS);
for (String path : paths) {
File file = new File(m_baseDir, path);
String loginfo = "path:" + m_baseDir + path + ",file size: " + file.length();
LocalMessageBucket bucket = m_buckets.get(path);
if (bucket != null) {
try {
bucket.close();
bucket.archive();
Cat.getProducer().logEvent("Dump", "Outbox.Normal", Message.SUCCESS, loginfo);
m_logger.info("move data file to outbox normal, " + loginfo);
} catch (Exception e) {
t.setStatus(e);
Cat.logError(e);
m_logger.error(e.getMessage(), e);
}
m_buckets.remove(path);
} else {
try {
moveFile(path);
moveFile(path + ".idx");
Cat.getProducer().logEvent("Dump", "Outbox.Abnormal", Message.SUCCESS, loginfo);
m_logger.info("move data file to outbox abnormal, " + loginfo);
} catch (Exception e) {
t.setStatus(e);
Cat.logError(e);
m_logger.error(e.getMessage(), e);
}
}
}
t.complete();
}
}
private void moveFile(String path) throws IOException {
File outbox = new File(m_baseDir, "outbox");
File from = new File(m_baseDir, path);
File to = new File(outbox, path);
to.getParentFile().mkdirs();
Files.forDir().copyFile(from, to);
Files.forDir().delete(from);
File parentFile = from.getParentFile();
parentFile.delete(); // delete it if empty
parentFile.getParentFile().delete(); // delete it if empty
}
public void setBaseDir(File baseDir) {
m_baseDir = baseDir;
}
private boolean shouldMove(String path) {
if (path.indexOf("draft") > -1 || path.indexOf("outbox") > -1) {
return false;
}
long current = System.currentTimeMillis();
long currentHour = current - current % ONE_HOUR;
long lastHour = currentHour - ONE_HOUR;
long nextHour = currentHour + ONE_HOUR;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd/HH");
String currentHourStr = sdf.format(new Date(currentHour));
String lastHourStr = sdf.format(new Date(lastHour));
String nextHourStr = sdf.format(new Date(nextHour));
int indexOf = path.indexOf(currentHourStr);
int indexOfLast = path.indexOf(lastHourStr);
int indexOfNext = path.indexOf(nextHourStr);
if (indexOf > -1 || indexOfLast > -1 || indexOfNext > -1) {
return false;
}
return true;
}
@Override
public void storeMessage(final MessageTree tree, final MessageId id) throws IOException {
String domain = id.getDomain() + id.getIpAddress();
int bucketIndex = Math.abs(domain.hashCode()) % m_gzipThreads;
if (bucketIndex > m_gzipThreads || bucketIndex < 0) {
m_logger.error("Error where compute the message bucket index!" + bucketIndex);
} else {
m_processMessages[bucketIndex]++;
}
LinkedBlockingQueue<MessageItem> items = m_messageQueues.get(bucketIndex);
if (items == null) {
items = new LinkedBlockingQueue<LocalMessageBucketManager.MessageItem>(10000);
m_messageQueues.put(bucketIndex, items);
}
boolean result = items.offer(new MessageItem(tree, id));
if (result == false) {
m_error++;
if (m_error % CatConstants.ERROR_COUNT == 0) {
m_serverStateManager.addMessageDumpLoss(CatConstants.ERROR_COUNT);
m_logger.error("Error when offer message tree to gzip queue! overflow :" + m_error);
}
}
m_total++;
if (m_total % (CatConstants.SUCCESS_COUNT) == 0) {
logState(tree);
}
}
private void logState(final MessageTree tree) {
double amount = m_totalSize - m_lastTotalSize;
m_lastTotalSize = m_totalSize;
m_serverStateManager.addMessageDump(CatConstants.SUCCESS_COUNT);
m_serverStateManager.addMessageSize(amount);
Message message = tree.getMessage();
if (message instanceof Transaction) {
long delay = System.currentTimeMillis() - tree.getMessage().getTimestamp()
- ((Transaction) message).getDurationInMillis();
m_serverStateManager.addProcessDelay(delay);
}
if (m_total % (CatConstants.SUCCESS_COUNT * 1000) == 0) {
m_logger.info("Dump message number: " + m_total + " Size:" + m_totalSize * 1.0 / 1024 / 1024 / 1024 + "GB");
StringBuilder sb = new StringBuilder("GzipThread Process Message Number :");
for (int i = 0; i < m_gzipThreads; i++) {
sb.append(m_processMessages[i] + " \t");
}
m_logger.info(sb.toString());
}
}
class MessageGzip implements Task {
public int m_index;
public MessageGzip(int index) {
m_index = index;
}
@Override
public void run() {
try {
while (true) {
BlockingQueue<MessageItem> items = m_messageQueues.get(m_index);
if (items != null) {
MessageItem item = items.poll(5, TimeUnit.MILLISECONDS);
if (item != null) {
try {
MessageTree tree = item.getTree();
MessageId id = item.getMessageId();
String name = id.getDomain() + '-' + id.getIpAddress() + '-' + m_localIp;
String dataFile = m_pathBuilder.getPath(new Date(id.getTimestamp()), name);
LocalMessageBucket bucket = m_buckets.get(dataFile);
if (bucket == null) {
bucket = (LocalMessageBucket) lookup(MessageBucket.class, LocalMessageBucket.ID);
bucket.setBaseDir(m_baseDir);
bucket.initialize(dataFile);
m_buckets.put(dataFile, bucket);
}
DefaultMessageTree defaultTree = (DefaultMessageTree) tree;
ChannelBuffer buf = defaultTree.getBuf();
int size = buf.readableBytes();
m_totalSize += size;
MessageBlock bolck = bucket.storeMessage(buf, id);
if (bolck != null) {
if (!m_messageBlocks.offer(bolck)) {
m_logger.error("Error when offer the block to the dump!");
}
}
} catch (Exception e) {
Cat.logError(e);
}
}
}
}
} catch (InterruptedException e) {
// ignore it
}
}
@Override
public String getName() {
return "Message Gizp " + m_index;
}
@Override
public void shutdown() {
}
}
class MessageItem {
private MessageTree m_tree;
private MessageId m_messageId;
public MessageItem(MessageTree tree, MessageId messageId) {
m_tree = tree;
m_messageId = messageId;
}
public MessageTree getTree() {
return m_tree;
}
public void setTree(MessageTree tree) {
m_tree = tree;
}
public MessageId getMessageId() {
return m_messageId;
}
public void setMessageId(MessageId messageId) {
m_messageId = messageId;
}
}
class BlockDumper implements Task {
private int m_errors;
private int m_success;
@Override
public String getName() {
return "LocalMessageBucketManager-BlockDumper";
}
@Override
public void run() {
try {
while (true) {
MessageBlock block = m_messageBlocks.poll(5, TimeUnit.MILLISECONDS);
if (block != null) {
String dataFile = block.getDataFile();
LocalMessageBucket bucket = m_buckets.get(dataFile);
try {
bucket.getWriter().writeBlock(block);
} catch (Throwable e) {
m_errors++;
if (m_errors == 1 || m_errors % 100 == 0) {
Cat.getProducer().logError(
new RuntimeException("Error when dumping for bucket: " + dataFile + ".", e));
}
}
m_success++;
if (m_success % 1000 == 0) {
m_logger.info("block queue size " + m_messageBlocks.size());
}
}
}
} catch (InterruptedException e) {
// ignore it
}
}
@Override
public void shutdown() {
}
}
class IdleChecker implements Task {
@Override
public String getName() {
return "LocalMessageBucketManager-IdleChecker";
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(60 * 1000L); // 1 minute
try {
closeIdleBuckets();
} catch (Throwable e) {
Cat.getProducer().logError(e);
}
}
} catch (InterruptedException e) {
// ignore it
}
}
@Override
public void shutdown() {
}
}
class OldMessageMover implements Task {
@Override
public String getName() {
return "LocalMessageBucketManager-OldMessageMover";
}
@Override
public void run() {
boolean active = true;
while (active) {
try {
moveOldMessages();
} catch (Throwable e) {
m_logger.error(e.getMessage(), e);
}
try {
Thread.sleep(2 * 60 * 1000L);
} catch (InterruptedException e) {
active = false;
}
}
}
@Override
public void shutdown() {
}
}
}
|
modify int to long
|
cat-core/src/main/java/com/dianping/cat/storage/dump/LocalMessageBucketManager.java
|
modify int to long
|
|
Java
|
apache-2.0
|
e5476533bcfd3035e6eaf0b6e920e13a615f384c
| 0
|
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.shelf;
import com.intellij.diff.DiffContentFactory;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.chains.DiffRequestChain;
import com.intellij.diff.chains.DiffRequestProducer;
import com.intellij.diff.chains.DiffRequestProducerException;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.requests.SimpleDiffRequest;
import com.intellij.diff.requests.UnknownFileTypeDiffRequest;
import com.intellij.diff.tools.util.SoftHardCacheMap;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.AnActionExtensionProvider;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diff.impl.patch.*;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase;
import com.intellij.openapi.diff.impl.patch.apply.GenericPatchApplier;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.UnknownFileType;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.CommitContext;
import com.intellij.openapi.vcs.changes.FilePathsHelper;
import com.intellij.openapi.vcs.changes.patch.AppliedTextPatch;
import com.intellij.openapi.vcs.changes.patch.ApplyPatchForBaseRevisionTexts;
import com.intellij.openapi.vcs.changes.patch.tool.PatchDiffRequest;
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.CalledInBackground;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.intellij.diff.tools.util.DiffNotifications.createNotification;
import static com.intellij.openapi.vcs.changes.patch.PatchDiffRequestFactory.createConflictDiffRequest;
import static com.intellij.openapi.vcs.changes.patch.PatchDiffRequestFactory.createDiffRequest;
import static com.intellij.util.ObjectUtils.assertNotNull;
import static com.intellij.util.ObjectUtils.chooseNotNull;
public class DiffShelvedChangesActionProvider implements AnActionExtensionProvider {
private static final String DIFF_WITH_BASE_ERROR = "Base content not found or not applicable.";
public static final String SHELVED_VERSION = "Shelved Version";
public static final String BASE_VERSION = "Base Version";
public static final String CURRENT_VERSION = "Current Version";
@Override
public boolean isActive(@NotNull AnActionEvent e) {
return e.getData(ShelvedChangesViewManager.SHELVED_CHANGELIST_KEY) != null ||
e.getData(ShelvedChangesViewManager.SHELVED_RECYCLED_CHANGELIST_KEY) != null;
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(isEnabled(e.getDataContext()));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
showShelvedChangesDiff(e.getDataContext());
}
public static boolean isEnabled(final DataContext dc) {
final Project project = CommonDataKeys.PROJECT.getData(dc);
if (project == null) return false;
List<ShelvedChangeList> changeLists = ShelvedChangesViewManager.getShelvedLists(dc);
return changeLists.size() == 1;
}
public static void showShelvedChangesDiff(final DataContext dc) {
showShelvedChangesDiff(dc, false);
}
public static void showShelvedChangesDiff(final DataContext dc, boolean withLocal) {
final Project project = CommonDataKeys.PROJECT.getData(dc);
if (project == null) return;
if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;
List<ShelvedChangeList> changeLists = ShelvedChangesViewManager.getShelvedLists(dc);
ShelvedChangeList changeList = assertNotNull(ContainerUtil.getFirstItem(changeLists));
final List<ShelvedChange> textChanges = changeList.getChanges(project);
final List<ShelvedBinaryFile> binaryChanges = changeList.getBinaryFiles();
final List<ShelveDiffRequestProducer> diffRequestProducers = new ArrayList<>();
processTextChanges(project, textChanges, diffRequestProducers, withLocal);
processBinaryFiles(project, binaryChanges, diffRequestProducers);
Collections.sort(diffRequestProducers, ChangeDiffRequestComparator.getInstance());
// selected changes inside lists
final Set<Object> selectedChanges = new HashSet<>();
selectedChanges.addAll(ShelvedChangesViewManager.getShelveChanges(dc));
selectedChanges.addAll(ShelvedChangesViewManager.getBinaryShelveChanges(dc));
int index = 0;
for (int i = 0; i < diffRequestProducers.size(); i++) {
ShelveDiffRequestProducer producer = diffRequestProducers.get(i);
if (selectedChanges.contains(producer.getBinaryChange()) || selectedChanges.contains(producer.getTextChange())) {
index = i;
break;
}
}
DiffRequestChain chain = new ChangeDiffRequestChain(diffRequestProducers, index);
DiffManager.getInstance().showDiff(project, chain, DiffDialogHints.FRAME);
}
private static class ChangeDiffRequestComparator implements Comparator<DiffRequestProducer> {
private final static ChangeDiffRequestComparator ourInstance = new ChangeDiffRequestComparator();
public static ChangeDiffRequestComparator getInstance() {
return ourInstance;
}
@Override
public int compare(DiffRequestProducer o1, DiffRequestProducer o2) {
return FilePathsHelper.convertPath(o1.getName()).compareTo(FilePathsHelper.convertPath(o2.getName()));
}
}
private static void processBinaryFiles(@NotNull Project project,
@NotNull List<ShelvedBinaryFile> files,
@NotNull List<ShelveDiffRequestProducer> diffRequestProducers) {
final String base = project.getBasePath();
for (final ShelvedBinaryFile shelvedChange : files) {
final File file = new File(base, shelvedChange.AFTER_PATH == null ? shelvedChange.BEFORE_PATH : shelvedChange.AFTER_PATH);
final FilePath filePath = VcsUtil.getFilePath(file);
diffRequestProducers.add(new BinaryShelveDiffRequestProducer(project, shelvedChange, filePath));
}
}
private static void processTextChanges(@NotNull final Project project,
@NotNull List<ShelvedChange> changesFromFirstList,
@NotNull List<ShelveDiffRequestProducer> diffRequestProducers,
boolean withLocal) {
final String base = project.getBasePath();
final ApplyPatchContext patchContext = new ApplyPatchContext(project.getBaseDir(), 0, false, false);
final PatchesPreloader preloader = new PatchesPreloader(project);
final CommitContext commitContext = new CommitContext();
for (final ShelvedChange shelvedChange : changesFromFirstList) {
final String beforePath = shelvedChange.getBeforePath();
final String afterPath = shelvedChange.getAfterPath();
final FilePath filePath = VcsUtil.getFilePath(new File(base, afterPath == null ? beforePath : afterPath));
final boolean isNewFile = FileStatus.ADDED.equals(shelvedChange.getFileStatus());
try {
if (isNewFile) {
diffRequestProducers.add(new NewFileTextShelveDiffRequestProducer(project, shelvedChange, filePath));
}
else {
VirtualFile file = ApplyFilePatchBase.findPatchTarget(patchContext, beforePath, afterPath, isNewFile);
if (file == null || !file.exists()) throw new FileNotFoundException(beforePath);
diffRequestProducers.add(new TextShelveDiffRequestProducer(project, shelvedChange, filePath, file, patchContext, preloader,
commitContext, withLocal));
}
}
catch (IOException e) {
diffRequestProducers.add(new PatchShelveDiffRequestProducer(project, shelvedChange, filePath, preloader, commitContext));
}
}
}
/**
* Simple way to reuse patch parser from GPA -> apply onto empty text
*/
@NotNull
static AppliedTextPatch createAppliedTextPatch(@NotNull TextFilePatch patch) {
final GenericPatchApplier applier = new GenericPatchApplier("", patch.getHunks());
applier.execute();
return AppliedTextPatch.create(applier.getAppliedInfo());
}
static class PatchesPreloader {
private final Project myProject;
private final SoftHardCacheMap<String, PatchInfo> myFilePatchesMap = new SoftHardCacheMap<>(5, 5);
private final ReadWriteLock myLock = new ReentrantReadWriteLock(true);
PatchesPreloader(final Project project) {
myProject = project;
}
@NotNull
@CalledInBackground
public TextFilePatch getPatch(final ShelvedChange shelvedChange, @Nullable CommitContext commitContext) throws VcsException {
String patchPath = shelvedChange.getPatchPath();
if (getInfoFromCache(patchPath) == null || isPatchFileChanged(patchPath)) {
readFilePatchAndUpdateCaches(patchPath, commitContext);
}
PatchInfo patchInfo = getInfoFromCache(patchPath);
if (patchInfo != null) {
for (TextFilePatch textFilePatch : patchInfo.myTextFilePatches) {
if (shelvedChange.getBeforePath().equals(textFilePatch.getBeforeName())) {
return textFilePatch;
}
}
}
throw new VcsException("Can not find patch for " + shelvedChange.getBeforePath() + " in patch file.");
}
private PatchInfo getInfoFromCache(@NotNull String patchPath) {
try {
myLock.readLock().lock();
return myFilePatchesMap.get(patchPath);
}
finally {
myLock.readLock().unlock();
}
}
private void readFilePatchAndUpdateCaches(@NotNull String patchPath, @Nullable CommitContext commitContext) throws VcsException {
try {
myLock.writeLock().lock();
myFilePatchesMap.put(patchPath, new PatchInfo(ShelveChangesManager.loadPatches(myProject, patchPath, commitContext),
new File(patchPath).lastModified()));
}
catch (IOException | PatchSyntaxException e) {
throw new VcsException(e);
}
finally {
myLock.writeLock().unlock();
}
}
public boolean isPatchFileChanged(@NotNull String patchPath) {
PatchInfo patchInfo = getInfoFromCache(patchPath);
long lastModified = new File(patchPath).lastModified();
return patchInfo != null && lastModified != patchInfo.myLoadedTimeStamp;
}
private static class PatchInfo {
private final long myLoadedTimeStamp;
@NotNull private final List<TextFilePatch> myTextFilePatches;
public PatchInfo(@NotNull List<TextFilePatch> patches, long loadedTimeStamp) {
myTextFilePatches = patches;
myLoadedTimeStamp = loadedTimeStamp;
}
}
}
private static abstract class ShelveDiffRequestProducer implements ChangeDiffRequestChain.Producer {
@NotNull protected final FilePath myFilePath;
public ShelveDiffRequestProducer(@NotNull FilePath filePath) {
myFilePath = filePath;
}
@Nullable
public ShelvedChange getTextChange() {
return null;
}
@Nullable
public ShelvedBinaryFile getBinaryChange() {
return null;
}
@NotNull
@Override
public String getName() {
return FileUtil.toSystemDependentName(getFilePath().getPath());
}
@NotNull
@Override
public FilePath getFilePath() {
return myFilePath;
}
}
private static class BinaryShelveDiffRequestProducer extends ShelveDiffRequestProducer {
@NotNull private final Project myProject;
@NotNull private final ShelvedBinaryFile myBinaryChange;
public BinaryShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedBinaryFile change,
@NotNull FilePath filePath) {
super(filePath);
myBinaryChange = change;
myProject = project;
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator)
throws DiffRequestProducerException, ProcessCanceledException {
Change change = myBinaryChange.createChange(myProject);
return createDiffRequest(myProject, change, getName(), context, indicator);
}
@NotNull
@Override
public FileStatus getFileStatus() {
return myBinaryChange.getFileStatus();
}
@NotNull
@Override
public ShelvedBinaryFile getBinaryChange() {
return myBinaryChange;
}
}
private static class PatchShelveDiffRequestProducer extends BaseTextShelveDiffRequestProducer {
private final PatchesPreloader myPreloader;
private final CommitContext myCommitContext;
public PatchShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath,
@NotNull PatchesPreloader preloader,
@NotNull CommitContext commitContext) {
super(project, change, filePath);
myPreloader = preloader;
myCommitContext = commitContext;
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator) throws DiffRequestProducerException {
try {
TextFilePatch patch = myPreloader.getPatch(myChange, myCommitContext);
AppliedTextPatch appliedTextPatch = createAppliedTextPatch(patch);
PatchDiffRequest request = new PatchDiffRequest(appliedTextPatch, getName(), VcsBundle.message("patch.apply.conflict.patch"));
DiffUtil.addNotification(createNotification("Cannot find local file for '" + getFilePath() + "'"), request);
return request;
}
catch (VcsException e) {
throw new DiffRequestProducerException("Can't show diff for '" + getFilePath() + "'", e);
}
}
}
private static class NewFileTextShelveDiffRequestProducer extends BaseTextShelveDiffRequestProducer {
public NewFileTextShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath) {
super(project, change, filePath);
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator)
throws DiffRequestProducerException, ProcessCanceledException {
return createDiffRequest(myProject, myChange.getChange(myProject), getName(), context, indicator);
}
}
private static class TextShelveDiffRequestProducer extends BaseTextShelveDiffRequestProducer {
@NotNull private final VirtualFile myFile;
@NotNull private final ApplyPatchContext myPatchContext;
@NotNull private final PatchesPreloader myPreloader;
@NotNull private final CommitContext myCommitContext;
private final boolean myWithLocal;
public TextShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath,
@NotNull VirtualFile file,
@NotNull ApplyPatchContext patchContext,
@NotNull PatchesPreloader preloader,
@NotNull CommitContext commitContext,
boolean withLocal) {
super(project, change, filePath);
myFile = file;
myPatchContext = patchContext;
myPreloader = preloader;
myCommitContext = commitContext;
myWithLocal = withLocal;
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator)
throws DiffRequestProducerException, ProcessCanceledException {
if (myFile.getFileType() == UnknownFileType.INSTANCE) {
return new UnknownFileTypeDiffRequest(myFile, getName());
}
try {
TextFilePatch patch = myPreloader.getPatch(myChange, myCommitContext);
if (patch.isDeletedFile()) {
return createDiffRequestForDeleted(patch);
}
else {
String path = chooseNotNull(patch.getAfterName(), patch.getBeforeName());
CharSequence baseContents = Extensions.findExtension(PatchEP.EP_NAME, myProject, BaseRevisionTextPatchEP.class)
.provideContent(path, myCommitContext);
ApplyPatchForBaseRevisionTexts texts =
ApplyPatchForBaseRevisionTexts.create(myProject, myFile, myPatchContext.getPathBeforeRename(myFile), patch, baseContents);
if (texts.isBaseRevisionLoaded()) {
assert !texts.isAppliedSomehow();
return createDiffRequestUsingBase(texts);
}
else {
return createDiffRequestUsingLocal(texts, patch, context, indicator);
}
}
}
catch (VcsException e) {
throw new DiffRequestProducerException("Can't show diff for '" + getFilePath() + "'", e);
}
}
@NotNull
private DiffRequest createDiffRequestForDeleted(@NotNull TextFilePatch patch) {
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DiffContent leftContent = myWithLocal
? contentFactory.create(myProject, myFile)
: contentFactory.create(myProject, patch.getSingleHunkPatchText(), myFile);
return new SimpleDiffRequest(getName(), leftContent,
contentFactory.createEmpty(),
myWithLocal ? CURRENT_VERSION : SHELVED_VERSION, null);
}
@NotNull
private DiffRequest createDiffRequestUsingBase(@NotNull ApplyPatchForBaseRevisionTexts texts) {
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DiffContent leftContent = myWithLocal
? contentFactory.create(myProject, myFile)
: contentFactory.create(myProject, assertNotNull(texts.getBase()), myFile);
return new SimpleDiffRequest(getName(), leftContent, contentFactory.create(myProject, texts.getPatched(), myFile),
myWithLocal ? CURRENT_VERSION : BASE_VERSION, SHELVED_VERSION);
}
private DiffRequest createDiffRequestUsingLocal(@NotNull ApplyPatchForBaseRevisionTexts texts,
@NotNull TextFilePatch patch,
@NotNull UserDataHolder context,
@NotNull ProgressIndicator indicator) throws DiffRequestProducerException {
DiffRequest diffRequest = myChange.isConflictingChange(myProject)
? createConflictDiffRequest(myProject, myFile, patch, SHELVED_VERSION, texts, getName())
: createDiffRequest(myProject, myChange.getChange(myProject), getName(), context, indicator);
if (!myWithLocal) {
DiffUtil.addNotification(createNotification(DIFF_WITH_BASE_ERROR + " Showing difference with local version"), diffRequest);
}
return diffRequest;
}
}
private static abstract class BaseTextShelveDiffRequestProducer extends ShelveDiffRequestProducer {
@NotNull protected final Project myProject;
@NotNull protected final ShelvedChange myChange;
public BaseTextShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath) {
super(filePath);
myChange = change;
myProject = project;
}
@NotNull
@Override
public FileStatus getFileStatus() {
return myChange.getFileStatus();
}
@NotNull
@Override
public ShelvedChange getTextChange() {
return myChange;
}
}
}
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/shelf/DiffShelvedChangesActionProvider.java
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.shelf;
import com.intellij.diff.DiffContentFactory;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.chains.DiffRequestChain;
import com.intellij.diff.chains.DiffRequestProducer;
import com.intellij.diff.chains.DiffRequestProducerException;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.requests.SimpleDiffRequest;
import com.intellij.diff.requests.UnknownFileTypeDiffRequest;
import com.intellij.diff.tools.util.SoftHardCacheMap;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.AnActionExtensionProvider;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diff.impl.patch.*;
import com.intellij.openapi.diff.impl.patch.apply.ApplyFilePatchBase;
import com.intellij.openapi.diff.impl.patch.apply.GenericPatchApplier;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.UnknownFileType;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.CommitContext;
import com.intellij.openapi.vcs.changes.FilePathsHelper;
import com.intellij.openapi.vcs.changes.patch.AppliedTextPatch;
import com.intellij.openapi.vcs.changes.patch.ApplyPatchForBaseRevisionTexts;
import com.intellij.openapi.vcs.changes.patch.tool.PatchDiffRequest;
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.CalledInBackground;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.intellij.diff.tools.util.DiffNotifications.createNotification;
import static com.intellij.openapi.vcs.changes.patch.PatchDiffRequestFactory.createConflictDiffRequest;
import static com.intellij.openapi.vcs.changes.patch.PatchDiffRequestFactory.createDiffRequest;
import static com.intellij.util.ObjectUtils.assertNotNull;
import static com.intellij.util.ObjectUtils.chooseNotNull;
public class DiffShelvedChangesActionProvider implements AnActionExtensionProvider {
private static final String DIFF_WITH_BASE_ERROR = "Base content not found or not applicable.";
public static final String SHELVED_VERSION = "Shelved Version";
public static final String BASE_VERSION = "Base Version";
public static final String CURRENT_VERSION = "Current Version";
@Override
public boolean isActive(@NotNull AnActionEvent e) {
return e.getData(ShelvedChangesViewManager.SHELVED_CHANGELIST_KEY) != null ||
e.getData(ShelvedChangesViewManager.SHELVED_RECYCLED_CHANGELIST_KEY) != null;
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(isEnabled(e.getDataContext()));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
showShelvedChangesDiff(e.getDataContext());
}
public static boolean isEnabled(final DataContext dc) {
final Project project = CommonDataKeys.PROJECT.getData(dc);
if (project == null) return false;
List<ShelvedChangeList> changeLists = ShelvedChangesViewManager.getShelvedLists(dc);
return changeLists.size() == 1;
}
public static void showShelvedChangesDiff(final DataContext dc) {
showShelvedChangesDiff(dc, false);
}
public static void showShelvedChangesDiff(final DataContext dc, boolean withLocal) {
final Project project = CommonDataKeys.PROJECT.getData(dc);
if (project == null) return;
if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;
List<ShelvedChangeList> changeLists = ShelvedChangesViewManager.getShelvedLists(dc);
ShelvedChangeList changeList = assertNotNull(ContainerUtil.getFirstItem(changeLists));
final List<ShelvedChange> textChanges = changeList.getChanges(project);
final List<ShelvedBinaryFile> binaryChanges = changeList.getBinaryFiles();
final List<ShelveDiffRequestProducer> diffRequestProducers = new ArrayList<>();
processTextChanges(project, textChanges, diffRequestProducers, withLocal);
processBinaryFiles(project, binaryChanges, diffRequestProducers);
Collections.sort(diffRequestProducers, ChangeDiffRequestComparator.getInstance());
// selected changes inside lists
final Set<Object> selectedChanges = new HashSet<>();
selectedChanges.addAll(ShelvedChangesViewManager.getShelveChanges(dc));
selectedChanges.addAll(ShelvedChangesViewManager.getBinaryShelveChanges(dc));
int index = 0;
for (int i = 0; i < diffRequestProducers.size(); i++) {
ShelveDiffRequestProducer producer = diffRequestProducers.get(i);
if (selectedChanges.contains(producer.getBinaryChange()) || selectedChanges.contains(producer.getTextChange())) {
index = i;
break;
}
}
DiffRequestChain chain = new ChangeDiffRequestChain(diffRequestProducers, index);
DiffManager.getInstance().showDiff(project, chain, DiffDialogHints.FRAME);
}
private static class ChangeDiffRequestComparator implements Comparator<DiffRequestProducer> {
private final static ChangeDiffRequestComparator ourInstance = new ChangeDiffRequestComparator();
public static ChangeDiffRequestComparator getInstance() {
return ourInstance;
}
@Override
public int compare(DiffRequestProducer o1, DiffRequestProducer o2) {
return FilePathsHelper.convertPath(o1.getName()).compareTo(FilePathsHelper.convertPath(o2.getName()));
}
}
private static void processBinaryFiles(@NotNull Project project,
@NotNull List<ShelvedBinaryFile> files,
@NotNull List<ShelveDiffRequestProducer> diffRequestProducers) {
final String base = project.getBasePath();
for (final ShelvedBinaryFile shelvedChange : files) {
final File file = new File(base, shelvedChange.AFTER_PATH == null ? shelvedChange.BEFORE_PATH : shelvedChange.AFTER_PATH);
final FilePath filePath = VcsUtil.getFilePath(file);
diffRequestProducers.add(new BinaryShelveDiffRequestProducer(project, shelvedChange, filePath));
}
}
private static void processTextChanges(@NotNull final Project project,
@NotNull List<ShelvedChange> changesFromFirstList,
@NotNull List<ShelveDiffRequestProducer> diffRequestProducers,
boolean withLocal) {
final String base = project.getBasePath();
final ApplyPatchContext patchContext = new ApplyPatchContext(project.getBaseDir(), 0, false, false);
final PatchesPreloader preloader = new PatchesPreloader(project);
final CommitContext commitContext = new CommitContext();
for (final ShelvedChange shelvedChange : changesFromFirstList) {
final String beforePath = shelvedChange.getBeforePath();
final String afterPath = shelvedChange.getAfterPath();
final FilePath filePath = VcsUtil.getFilePath(new File(base, afterPath == null ? beforePath : afterPath));
final boolean isNewFile = FileStatus.ADDED.equals(shelvedChange.getFileStatus());
try {
if (isNewFile) {
diffRequestProducers.add(new NewFileTextShelveDiffRequestProducer(project, shelvedChange, filePath));
}
else {
VirtualFile file = ApplyFilePatchBase.findPatchTarget(patchContext, beforePath, afterPath, isNewFile);
if (file == null || !file.exists()) throw new FileNotFoundException(beforePath);
diffRequestProducers.add(new TextShelveDiffRequestProducer(project, shelvedChange, filePath, file, patchContext, preloader,
commitContext, withLocal));
}
}
catch (IOException e) {
diffRequestProducers.add(new PatchShelveDiffRequestProducer(project, shelvedChange, filePath, preloader, commitContext));
}
}
}
/**
* Simple way to reuse patch parser from GPA -> apply onto empty text
*/
@NotNull
static AppliedTextPatch createAppliedTextPatch(@NotNull TextFilePatch patch) {
final GenericPatchApplier applier = new GenericPatchApplier("", patch.getHunks());
applier.execute();
return AppliedTextPatch.create(applier.getAppliedInfo());
}
static class PatchesPreloader {
private final Project myProject;
private final SoftHardCacheMap<String, PatchInfo> myFilePatchesMap = new SoftHardCacheMap<>(5, 5);
private final ReadWriteLock myLock = new ReentrantReadWriteLock(true);
PatchesPreloader(final Project project) {
myProject = project;
}
@NotNull
@CalledInBackground
public TextFilePatch getPatch(final ShelvedChange shelvedChange, @Nullable CommitContext commitContext) throws VcsException {
String patchPath = shelvedChange.getPatchPath();
if (getInfoFromCache(patchPath) == null || isPatchFileChanged(patchPath)) {
readFilePatchAndUpdateCaches(patchPath, commitContext);
}
PatchInfo patchInfo = getInfoFromCache(patchPath);
if (patchInfo != null) {
for (TextFilePatch textFilePatch : patchInfo.myTextFilePatches) {
if (shelvedChange.getBeforePath().equals(textFilePatch.getBeforeName())) {
return textFilePatch;
}
}
}
throw new VcsException("Can not find patch for " + shelvedChange.getBeforePath() + " in patch file.");
}
private PatchInfo getInfoFromCache(@NotNull String patchPath) {
try {
myLock.readLock().lock();
return myFilePatchesMap.get(patchPath);
}
finally {
myLock.readLock().unlock();
}
}
private void readFilePatchAndUpdateCaches(@NotNull String patchPath, @Nullable CommitContext commitContext) throws VcsException {
try {
myLock.writeLock().lock();
myFilePatchesMap.put(patchPath, new PatchInfo(ShelveChangesManager.loadPatches(myProject, patchPath, commitContext),
new File(patchPath).lastModified()));
}
catch (IOException | PatchSyntaxException e) {
throw new VcsException(e);
}
finally {
myLock.writeLock().unlock();
}
}
public boolean isPatchFileChanged(@NotNull String patchPath) {
PatchInfo patchInfo = getInfoFromCache(patchPath);
long lastModified = new File(patchPath).lastModified();
return patchInfo != null && lastModified != patchInfo.myLoadedTimeStamp;
}
private static class PatchInfo {
private final long myLoadedTimeStamp;
@NotNull private final List<TextFilePatch> myTextFilePatches;
public PatchInfo(@NotNull List<TextFilePatch> patches, long loadedTimeStamp) {
myTextFilePatches = patches;
myLoadedTimeStamp = loadedTimeStamp;
}
}
}
private static abstract class ShelveDiffRequestProducer implements ChangeDiffRequestChain.Producer {
@NotNull protected final FilePath myFilePath;
public ShelveDiffRequestProducer(@NotNull FilePath filePath) {
myFilePath = filePath;
}
@Nullable
public ShelvedChange getTextChange() {
return null;
}
@Nullable
public ShelvedBinaryFile getBinaryChange() {
return null;
}
@NotNull
@Override
public String getName() {
return FileUtil.toSystemDependentName(getFilePath().getPath());
}
@NotNull
@Override
public FilePath getFilePath() {
return myFilePath;
}
}
private static class BinaryShelveDiffRequestProducer extends ShelveDiffRequestProducer {
@NotNull private final Project myProject;
@NotNull private final ShelvedBinaryFile myBinaryChange;
public BinaryShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedBinaryFile change,
@NotNull FilePath filePath) {
super(filePath);
myBinaryChange = change;
myProject = project;
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator)
throws DiffRequestProducerException, ProcessCanceledException {
Change change = myBinaryChange.createChange(myProject);
return createDiffRequest(myProject, change, getName(), context, indicator);
}
@NotNull
@Override
public FileStatus getFileStatus() {
return myBinaryChange.getFileStatus();
}
@NotNull
@Override
public ShelvedBinaryFile getBinaryChange() {
return myBinaryChange;
}
}
private static class PatchShelveDiffRequestProducer extends BaseTextShelveDiffRequestProducer {
private final PatchesPreloader myPreloader;
private final CommitContext myCommitContext;
public PatchShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath,
@NotNull PatchesPreloader preloader,
@NotNull CommitContext commitContext) {
super(project, change, filePath);
myPreloader = preloader;
myCommitContext = commitContext;
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator) throws DiffRequestProducerException {
try {
TextFilePatch patch = myPreloader.getPatch(myChange, myCommitContext);
AppliedTextPatch appliedTextPatch = createAppliedTextPatch(patch);
PatchDiffRequest request = new PatchDiffRequest(appliedTextPatch, getName(), VcsBundle.message("patch.apply.conflict.patch"));
DiffUtil.addNotification(createNotification("Cannot find local file for '" + getFilePath() + "'"), request);
return request;
}
catch (VcsException e) {
throw new DiffRequestProducerException("Can't show diff for '" + getFilePath() + "'", e);
}
}
}
private static class NewFileTextShelveDiffRequestProducer extends BaseTextShelveDiffRequestProducer {
public NewFileTextShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath) {
super(project, change, filePath);
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator)
throws DiffRequestProducerException, ProcessCanceledException {
return createDiffRequest(myProject, myChange.getChange(myProject), getName(), context, indicator);
}
}
private static class TextShelveDiffRequestProducer extends BaseTextShelveDiffRequestProducer {
@NotNull private final VirtualFile myFile;
@NotNull private final ApplyPatchContext myPatchContext;
@NotNull private final PatchesPreloader myPreloader;
@NotNull private final CommitContext myCommitContext;
private final boolean myWithLocal;
public TextShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath,
@NotNull VirtualFile file,
@NotNull ApplyPatchContext patchContext,
@NotNull PatchesPreloader preloader,
@NotNull CommitContext commitContext,
boolean withLocal) {
super(project, change, filePath);
myFile = file;
myPatchContext = patchContext;
myPreloader = preloader;
myCommitContext = commitContext;
myWithLocal = withLocal;
}
@NotNull
@Override
public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator)
throws DiffRequestProducerException, ProcessCanceledException {
if (myFile.getFileType() == UnknownFileType.INSTANCE) {
return new UnknownFileTypeDiffRequest(myFile, getName());
}
try {
TextFilePatch patch = myPreloader.getPatch(myChange, myCommitContext);
if (patch.isDeletedFile()) {
return createDiffRequestForDeleted(patch);
}
else {
return createDiffRequestForModified(patch, myCommitContext, context, indicator);
}
}
catch (VcsException e) {
throw new DiffRequestProducerException("Can't show diff for '" + getFilePath() + "'", e);
}
}
@NotNull
private DiffRequest createDiffRequestForDeleted(@NotNull TextFilePatch patch) {
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DiffContent leftContent = myWithLocal
? contentFactory.create(myProject, myFile)
: contentFactory.create(myProject, patch.getSingleHunkPatchText(), myFile);
return new SimpleDiffRequest(getName(), leftContent,
contentFactory.createEmpty(),
myWithLocal ? CURRENT_VERSION : SHELVED_VERSION, null);
}
@NotNull
private DiffRequest createDiffRequestForModified(@NotNull TextFilePatch patch,
@NotNull CommitContext commitContext,
@NotNull UserDataHolder context,
@NotNull ProgressIndicator indicator) throws DiffRequestProducerException {
CharSequence baseContents = Extensions.findExtension(PatchEP.EP_NAME, myProject, BaseRevisionTextPatchEP.class)
.provideContent(chooseNotNull(patch.getAfterName(), patch.getBeforeName()), commitContext);
ApplyPatchForBaseRevisionTexts texts =
ApplyPatchForBaseRevisionTexts.create(myProject, myFile, myPatchContext.getPathBeforeRename(myFile), patch, baseContents);
//found base
if (texts.isBaseRevisionLoaded()) {
assert !texts.isAppliedSomehow();
//normal diff
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DiffContent leftContent = myWithLocal
? contentFactory.create(myProject, myFile)
: contentFactory.create(myProject, assertNotNull(texts.getBase()), myFile);
return new SimpleDiffRequest(getName(), leftContent, contentFactory.create(myProject, texts.getPatched(), myFile),
myWithLocal ? CURRENT_VERSION : BASE_VERSION, SHELVED_VERSION);
}
else {
DiffRequest diffRequest = myChange.isConflictingChange(myProject)
? createConflictDiffRequest(myProject, myFile, patch, SHELVED_VERSION, texts, getName())
: createDiffRequest(myProject, myChange.getChange(myProject), getName(), context, indicator);
if (!myWithLocal) {
DiffUtil.addNotification(createNotification(DIFF_WITH_BASE_ERROR + " Showing difference with local version"), diffRequest);
}
return diffRequest;
}
}
}
private static abstract class BaseTextShelveDiffRequestProducer extends ShelveDiffRequestProducer {
@NotNull protected final Project myProject;
@NotNull protected final ShelvedChange myChange;
public BaseTextShelveDiffRequestProducer(@NotNull Project project,
@NotNull ShelvedChange change,
@NotNull FilePath filePath) {
super(filePath);
myChange = change;
myProject = project;
}
@NotNull
@Override
public FileStatus getFileStatus() {
return myChange.getFileStatus();
}
@NotNull
@Override
public ShelvedChange getTextChange() {
return myChange;
}
}
}
|
vcs: cleanup - extract method
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/shelf/DiffShelvedChangesActionProvider.java
|
vcs: cleanup - extract method
|
|
Java
|
apache-2.0
|
db98571df83164f188426654b4f7a05de3a31f6c
| 0
|
quyixia/gerrit,bootstraponline-archive/gerrit-mirror,basilgor/gerrit,thinkernel/gerrit,thinkernel/gerrit,midnightradio/gerrit,jackminicloud/test,WANdisco/gerrit,zommarin/gerrit,gerrit-review/gerrit,Distrotech/gerrit,Distrotech/gerrit,Overruler/gerrit,basilgor/gerrit,TonyChai24/test,thesamet/gerrit,dwhipstock/gerrit,Overruler/gerrit,gcoders/gerrit,Saulis/gerrit,gerrit-review/gerrit,supriyantomaftuh/gerrit,teamblueridge/gerrit,anminhsu/gerrit,thesamet/gerrit,zommarin/gerrit,jackminicloud/test,anminhsu/gerrit,MerritCR/merrit,Saulis/gerrit,thesamet/gerrit,dwhipstock/gerrit,Seinlin/gerrit,gracefullife/gerrit,TonyChai24/test,Seinlin/gerrit,gcoders/gerrit,gerrit-review/gerrit,anminhsu/gerrit,joshuawilson/merrit,netroby/gerrit,MerritCR/merrit,WANdisco/gerrit,thesamet/gerrit,teamblueridge/gerrit,WANdisco/gerrit,gerrit-review/gerrit,ckamm/gerrit,quyixia/gerrit,gerrit-review/gerrit,Team-OctOS/host_gerrit,qtproject/qtqa-gerrit,bpollack/gerrit,thinkernel/gerrit,hdost/gerrit,midnightradio/gerrit,hdost/gerrit,quyixia/gerrit,gracefullife/gerrit,GerritCodeReview/gerrit,jackminicloud/test,thesamet/gerrit,ckamm/gerrit,supriyantomaftuh/gerrit,TonyChai24/test,pkdevbox/gerrit,thinkernel/gerrit,WANdisco/gerrit,Overruler/gerrit,Distrotech/gerrit,quyixia/gerrit,bpollack/gerrit,dwhipstock/gerrit,TonyChai24/test,thinkernel/gerrit,pkdevbox/gerrit,jackminicloud/test,midnightradio/gerrit,Seinlin/gerrit,renchaorevee/gerrit,pkdevbox/gerrit,Distrotech/gerrit,joshuawilson/merrit,renchaorevee/gerrit,Team-OctOS/host_gerrit,midnightradio/gerrit,quyixia/gerrit,Distrotech/gerrit,Saulis/gerrit,Seinlin/gerrit,Team-OctOS/host_gerrit,gcoders/gerrit,dwhipstock/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,thinkernel/gerrit,renchaorevee/gerrit,ckamm/gerrit,jackminicloud/test,supriyantomaftuh/gerrit,gracefullife/gerrit,teamblueridge/gerrit,Overruler/gerrit,joshuawilson/merrit,bootstraponline-archive/gerrit-mirror,GerritCodeReview/gerrit,Seinlin/gerrit,joshuawilson/merrit,quyixia/gerrit,pkdevbox/gerrit,qtproject/qtqa-gerrit,MerritCR/merrit,netroby/gerrit,joshuawilson/merrit,basilgor/gerrit,midnightradio/gerrit,thesamet/gerrit,GerritCodeReview/gerrit,anminhsu/gerrit,Team-OctOS/host_gerrit,Seinlin/gerrit,renchaorevee/gerrit,midnightradio/gerrit,thinkernel/gerrit,hdost/gerrit,bpollack/gerrit,MerritCR/merrit,netroby/gerrit,zommarin/gerrit,gerrit-review/gerrit,gcoders/gerrit,TonyChai24/test,renchaorevee/gerrit,netroby/gerrit,qtproject/qtqa-gerrit,zommarin/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,teamblueridge/gerrit,gcoders/gerrit,Team-OctOS/host_gerrit,GerritCodeReview/gerrit,supriyantomaftuh/gerrit,TonyChai24/test,thesamet/gerrit,netroby/gerrit,supriyantomaftuh/gerrit,anminhsu/gerrit,supriyantomaftuh/gerrit,WANdisco/gerrit,jackminicloud/test,anminhsu/gerrit,MerritCR/merrit,quyixia/gerrit,hdost/gerrit,pkdevbox/gerrit,renchaorevee/gerrit,bpollack/gerrit,gcoders/gerrit,dwhipstock/gerrit,joshuawilson/merrit,Saulis/gerrit,Overruler/gerrit,MerritCR/merrit,bootstraponline-archive/gerrit-mirror,gcoders/gerrit,qtproject/qtqa-gerrit,ckamm/gerrit,jackminicloud/test,MerritCR/merrit,gracefullife/gerrit,qtproject/qtqa-gerrit,hdost/gerrit,joshuawilson/merrit,netroby/gerrit,Team-OctOS/host_gerrit,Distrotech/gerrit,Seinlin/gerrit,bpollack/gerrit,supriyantomaftuh/gerrit,bootstraponline-archive/gerrit-mirror,gracefullife/gerrit,GerritCodeReview/gerrit,anminhsu/gerrit,renchaorevee/gerrit,dwhipstock/gerrit,Distrotech/gerrit,MerritCR/merrit,netroby/gerrit,TonyChai24/test,Saulis/gerrit,qtproject/qtqa-gerrit,pkdevbox/gerrit,bpollack/gerrit,dwhipstock/gerrit,Saulis/gerrit,basilgor/gerrit,gerrit-review/gerrit,WANdisco/gerrit,WANdisco/gerrit,hdost/gerrit,teamblueridge/gerrit,Team-OctOS/host_gerrit,GerritCodeReview/gerrit,bootstraponline-archive/gerrit-mirror,bootstraponline-archive/gerrit-mirror,pkdevbox/gerrit,zommarin/gerrit,ckamm/gerrit,basilgor/gerrit,Overruler/gerrit,hdost/gerrit
|
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
/** Indicates the current branch's queue cannot be processed at this time. */
public class MergeException extends Exception {
private static final long serialVersionUID = 1L;
public MergeException(final String msg) {
super(msg, null);
}
public MergeException(final String msg, final Throwable why) {
super(msg, why);
}
}
|
gerrit-server/src/main/java/com/google/gerrit/server/git/MergeException.java
|
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git;
/** Indicates the current branch's queue cannot be processed at this time. */
public class MergeException extends Exception {
private static final long serialVersionUID = 1L;
MergeException(final String msg) {
super(msg, null);
}
MergeException(final String msg, final Throwable why) {
super(msg, why);
}
}
|
Make MergeException constructors public
Allow MergeExceptions to be thrown from other packages
Change-Id: I8c223778fce001df410349e63e1ef27c75517197
|
gerrit-server/src/main/java/com/google/gerrit/server/git/MergeException.java
|
Make MergeException constructors public
|
|
Java
|
apache-2.0
|
68623323e69d0f2cb574f0bf17a2c9e56c2d34af
| 0
|
ddumontatibm/JavascriptAggregator,chuckdumont/JavascriptAggregator,ddumontatibm/JavascriptAggregator,OpenNTF/JavascriptAggregator,OpenNTF/JavascriptAggregator,OpenNTF/JavascriptAggregator,ddumontatibm/JavascriptAggregator,chuckdumont/JavascriptAggregator,chuckdumont/JavascriptAggregator
|
/*
* (C) Copyright 2012, IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.jaggr.core.impl;
import com.ibm.jaggr.core.BadRequestException;
import com.ibm.jaggr.core.DependencyVerificationException;
import com.ibm.jaggr.core.IAggregator;
import com.ibm.jaggr.core.IAggregatorExtension;
import com.ibm.jaggr.core.IExtensionInitializer;
import com.ibm.jaggr.core.IExtensionInitializer.IExtensionRegistrar;
import com.ibm.jaggr.core.IPlatformServices;
import com.ibm.jaggr.core.IRequestListener;
import com.ibm.jaggr.core.IServiceProviderExtensionPoint;
import com.ibm.jaggr.core.IServiceReference;
import com.ibm.jaggr.core.IServiceRegistration;
import com.ibm.jaggr.core.IShutdownListener;
import com.ibm.jaggr.core.IVariableResolver;
import com.ibm.jaggr.core.InitParams;
import com.ibm.jaggr.core.NotFoundException;
import com.ibm.jaggr.core.PlatformServicesException;
import com.ibm.jaggr.core.ProcessingDependenciesException;
import com.ibm.jaggr.core.cache.ICacheManager;
import com.ibm.jaggr.core.config.IConfig;
import com.ibm.jaggr.core.config.IConfigListener;
import com.ibm.jaggr.core.deps.IDependencies;
import com.ibm.jaggr.core.executors.IExecutors;
import com.ibm.jaggr.core.impl.cache.CacheManagerImpl;
import com.ibm.jaggr.core.impl.config.ConfigImpl;
import com.ibm.jaggr.core.impl.deps.DependenciesImpl;
import com.ibm.jaggr.core.impl.layer.LayerImpl;
import com.ibm.jaggr.core.impl.module.ModuleImpl;
import com.ibm.jaggr.core.layer.ILayer;
import com.ibm.jaggr.core.layer.ILayerCache;
import com.ibm.jaggr.core.layer.ILayerListener;
import com.ibm.jaggr.core.module.IModule;
import com.ibm.jaggr.core.module.IModuleCache;
import com.ibm.jaggr.core.modulebuilder.IModuleBuilder;
import com.ibm.jaggr.core.modulebuilder.IModuleBuilderExtensionPoint;
import com.ibm.jaggr.core.options.IOptions;
import com.ibm.jaggr.core.options.IOptionsListener;
import com.ibm.jaggr.core.resource.IResource;
import com.ibm.jaggr.core.resource.IResourceFactory;
import com.ibm.jaggr.core.resource.IResourceFactoryExtensionPoint;
import com.ibm.jaggr.core.transport.IHttpTransport;
import com.ibm.jaggr.core.transport.IHttpTransportExtensionPoint;
import com.ibm.jaggr.core.util.CopyUtil;
import com.ibm.jaggr.core.util.SequenceNumberProvider;
import com.ibm.jaggr.core.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Implementation for IAggregator and HttpServlet interfaces.
*
* Note that despite the fact that HttpServlet (which this class extends)
* implements Serializable, attempts to serialize instances of this class will
* fail due to the fact that not all instance data is serializable. The
* assumption is that because instances of this class are created by the OSGi
* Framework, and the framework itself does not support serialization, then no
* attempts will be made to serialize instances of this class.
*/
@SuppressWarnings({ "serial", "deprecation" })
public abstract class AbstractAggregatorImpl extends HttpServlet implements IOptionsListener, IAggregator {
/**
* Default value for resourcefactories init-param
*/
protected static final String DEFAULT_RESOURCEFACTORIES =
"com.ibm.jaggr.service.default.resourcefactories"; //$NON-NLS-1$
/**
* Default value for modulebuilders init-param
*/
protected static final String DEFAULT_MODULEBUILDERS =
"com.ibm.jaggr.service.default.modulebuilders"; //$NON-NLS-1$
/**
* Default value for httptransport init-param
*/
protected static final String DEFAULT_HTTPTRANSPORT =
"com.ibm.jaggr.service.dojo.httptransport"; //$NON-NLS-1$
private final static String DEFAULT_CONTENT_TYPE = "application/octet-stream"; //$NON-NLS-1$
private static final Logger log = Logger.getLogger(AbstractAggregatorImpl.class.getName());
protected ICacheManager cacheMgr = null;
protected IConfig config = null;
//protected Bundle bundle = null;
protected String name = null;
protected IDependencies deps = null;
protected List<IServiceRegistration> registrations = new LinkedList<IServiceRegistration>();
protected List<IServiceReference> serviceReferences = Collections.synchronizedList(new LinkedList<IServiceReference>());
protected InitParams initParams = null;
protected IOptions localOptions = null;
protected MimetypesFileTypeMap fileTypeMap = null;
protected FileNameMap fileNameMap = null;
private LinkedList<IAggregatorExtension> resourceFactoryExtensions = new LinkedList<IAggregatorExtension>();
private LinkedList<IAggregatorExtension> moduleBuilderExtensions = new LinkedList<IAggregatorExtension>();
private LinkedList<IAggregatorExtension> serviceProviderExtensions = new LinkedList<IAggregatorExtension>();
private IAggregatorExtension httpTransportExtension = null;
private boolean isShuttingDown = false;
protected IPlatformServices platformServices;
protected Map<String, IResource> resourcePaths;
enum RequestNotifierAction {
start,
end
};
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
final String sourceMethod = "init"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{servletConfig});
}
super.init(servletConfig);
// Default constructor for MimetypesFileTypeMap *should* read our bundle's
// META-INF/mime.types automatically, but some older platforms (Domino)
// don't use the right class loader, so get the input stream ourselves
// and pass it to the constructor.
ClassLoader cld = AbstractAggregatorImpl.class.getClassLoader();
InputStream is = cld.getResourceAsStream("META-INF/mime.types"); //$NON-NLS-1$
// Initialize the type maps (see getContentType)
fileTypeMap = new MimetypesFileTypeMap(is);
fileNameMap = URLConnection.getFileNameMap();
final ServletContext context = servletConfig.getServletContext();
// Set servlet context attributes for access though the request
context.setAttribute(IAggregator.AGGREGATOR_REQATTRNAME, this);
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#destroy()
*/
@Override
public void destroy() {
final String sourceMethod = "destroy"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
shutdown();
super.destroy();
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/**
* Called when the aggregator is shutting down. Note that there is inconsistency
* among servlet bridge implementations over when {@link HttpServlet#destroy()}
* is called relative to when (or even if) the bundle is stopped. So this method
* may be called from the destroy method or the bundle listener or both.
*/
synchronized protected void shutdown() {
final String sourceMethod = "shutdown"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
if (!isShuttingDown) {
isShuttingDown = true;
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IShutdownListener.class.getName(), "(name=" + getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IShutdownListener listener = (IShutdownListener)getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.shutdown(this);
} catch (Exception e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
for (IServiceRegistration registration : registrations) {
registration.unregister();
}
for (IServiceReference ref : serviceReferences) {
getPlatformServices().ungetService(ref);
}
registrations.clear();
serviceReferences.clear();
// Clear references to objects that can potentially reference this object
// so as to avoid memory leaks due to circular references.
resourceFactoryExtensions.clear();
moduleBuilderExtensions.clear();
serviceProviderExtensions.clear();
httpTransportExtension = null;
initParams = null;
cacheMgr = null;
config = null;
deps = null;
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
final String sourceMethod = "doGet"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp});
log.finer("Request URL=" + req.getRequestURI()); //$NON-NLS-1$
}
if (isShuttingDown) {
// Server has been shut-down, or is in the process of shutting down.
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
if (isTraceLogging) {
log.finer("Processing request after server shutdown. Returning SC_SERVICE_UNAVAILABLE"); //$NON-NLS-1$
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
return;
}
resp.addHeader("Server", "JavaScript Aggregator"); //$NON-NLS-1$ //$NON-NLS-2$
String pathInfo = req.getPathInfo();
if (pathInfo == null) {
processAggregatorRequest(req, resp);
} else {
boolean processed = false;
// search resource paths to see if we should treat as aggregator request or resource request
for (Map.Entry<String, IResource> entry : resourcePaths.entrySet()) {
String path = entry.getKey();
if (path.equals(pathInfo) && entry.getValue() == null) {
processAggregatorRequest(req, resp);
processed = true;
break;
}
if (pathInfo.startsWith(path)) {
if ((path.length() == pathInfo.length() || pathInfo.charAt(path.length()) == '/') && entry.getValue() != null) {
String resPath = path.length() == pathInfo.length() ? "" : pathInfo.substring(path.length()+1); //$NON-NLS-1$
IResource res = entry.getValue();
processResourceRequest(req, resp, res, resPath);
processed = true;
break;
}
}
}
if (!processed) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
protected void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, IResource res, String path) {
final String sourceMethod = "processRequest"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp, res, path});
}
try {
IResource resolved = res;
URI uri = res.getURI();
if (path != null && path.length() > 0) {
if (!uri.getPath().endsWith("/")) { //$NON-NLS-1$
// Make sure we resolve against a folder path
uri = new URI(uri.getScheme(), uri.getAuthority(),
uri.getPath() + "/", uri.getQuery(), uri.getFragment()); //$NON-NLS-1$
res = newResource(uri);
}
resolved = res.resolve(path);
}
if (!resolved.exists()) {
throw new NotFoundException(resolved.getURI().toString());
}
// See if this is a conditional GET
long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
if (modifiedSince >= resolved.lastModified()) {
if (log.isLoggable(Level.FINER)) {
log.finer("Returning Not Modified response for resource in servlet" + //$NON-NLS-1$
getName() + ":" + resolved.getURI()); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
} else {
resp.setDateHeader("Last-Modified", resolved.lastModified()); //$NON-NLS-1$
int expires = getConfig().getExpires();
boolean hasCacheBust = req.getHeader("cb") != null || req.getHeader("cachebust") != null; //$NON-NLS-1$ //$NON-NLS-2$
resp.addHeader(
"Cache-Control", //$NON-NLS-1$
"public" + (expires > 0 && hasCacheBust ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
);
resp.setHeader("Content-Type", getContentType(resolved.getPath())); //$NON-NLS-1$
InputStream is = resolved.getInputStream();
OutputStream os = resp.getOutputStream();
CopyUtil.copy(is, os);
}
} catch (NotFoundException e) {
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.WARNING, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) {
final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp});
}
req.setAttribute(AGGREGATOR_REQATTRNAME, this);
ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);
try {
// Validate config last-modified if development mode is enabled
if (getOptions().isDevelopmentMode()) {
long lastModified = -1;
URI configUri = getConfig().getConfigUri();
if (configUri != null) {
try {
// try to get platform URI from IResource in case uri specifies
// aggregator specific scheme like namedbundleresource
configUri = newResource(configUri).getURI();
} catch (UnsupportedOperationException e) {
// Not fatal. Just use uri as specified.
}
lastModified = configUri.toURL().openConnection().getLastModified();
}
if (lastModified > getConfig().lastModified()) {
if (reloadConfig()) {
// If the config has been modified, then dependencies will be revalidated
// asynchronously. Rather than forcing the current request to wait, return
// a response that will display an alert informing the user of what is
// happening and asking them to reload the page.
String content = "alert('" + //$NON-NLS-1$
StringUtil.escapeForJavaScript(Messages.ConfigModified) +
"');"; //$NON-NLS-1$
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
return;
}
}
}
getTransport().decorateRequest(req);
notifyRequestListeners(RequestNotifierAction.start, req, resp);
ILayer layer = getLayer(req);
long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req)) / 1000) * 1000;
if (modifiedSince >= lastModified) {
if (log.isLoggable(Level.FINER)) {
log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
getName() + ":" + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString()); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
else {
// Get the InputStream for the response. This call sets the Content-Type,
// Content-Length and Content-Encoding headers in the response.
InputStream in = layer.getInputStream(req, resp);
// if any of the readers included an error response, then don't cache the layer.
if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
int expires = getConfig().getExpires();
boolean hasCacheBust = req.getHeader("cb") != null || req.getHeader("cachebust") != null; //$NON-NLS-1$ //$NON-NLS-2$
resp.addHeader(
"Cache-Control", //$NON-NLS-1$
"public" + (expires > 0 && hasCacheBust ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
);
}
CopyUtil.copy(in, resp.getOutputStream());
}
notifyRequestListeners(RequestNotifierAction.end, req, resp);
} catch (DependencyVerificationException e) {
// clear the cache now even though it will be cleared when validateDeps has
// finished (asynchronously) so that any new requests will be forced to wait
// until dependencies have been validated.
getCacheManager().clearCache();
getDependencies().validateDeps(false);
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
if (getOptions().isDevelopmentMode()) {
String msg = StringUtil.escapeForJavaScript(
MessageFormat.format(
Messages.DepVerificationFailed,
new Object[]{
e.getMessage(),
"aggregator " + //$NON-NLS-1$
"validatedeps " + //$NON-NLS-1$
getName() +
" clean", //$NON-NLS-1$
getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
}
)
);
String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
try {
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
} catch (IOException e1) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e1.getMessage(), e1);
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
} catch (ProcessingDependenciesException e) {
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
if (getOptions().isDevelopmentMode()) {
String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
try {
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
} catch (IOException e1) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e1.getMessage(), e1);
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
} catch (BadRequestException e) {
exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
} catch (NotFoundException e) {
exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
concurrentMap.clear();
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#reloadConfig()
*/
@Override
public boolean reloadConfig() throws IOException {
return loadConfig(SequenceNumberProvider.incrementAndGetSequenceNumber());
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getDependencies()
*/
@Override
public IDependencies getDependencies() {
return deps;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getName()
*/
@Override
public String getName() {
return name;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getConfig()
*/
@Override
public IConfig getConfig() {
return config;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getCacheManager()
*/
@Override
public ICacheManager getCacheManager() {
return cacheMgr;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.core.IAggregator#getInitParams()
*/
@Override
public InitParams getInitParams() {
return initParams;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#asServlet()
*/
@Override
public HttpServlet asServlet() {
return this;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getTransport()
*/
@Override
public IHttpTransport getTransport() {
IAggregatorExtension ext = getExtensions(IHttpTransportExtensionPoint.ID).iterator().next();
return (IHttpTransport)(ext != null ? ext.getInstance() : null);
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.resource.IResourceProvider#getResource(java.net.URI)
*/
@Override
public IResource newResource(URI uri) {
final String sourceMethod = "newResource"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{uri});
}
if (!uri.isAbsolute()) {
// URI is not absolute, so make it absolute.
try {
uri = getPlatformServices().getAppContextURI().resolve(uri.getPath());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
IResourceFactory factory = null;
String scheme = uri.getScheme();
for (IAggregatorExtension extension : getExtensions(IResourceFactoryExtensionPoint.ID)) {
if (scheme.equals(extension.getAttribute(IResourceFactoryExtensionPoint.SCHEME_ATTRIBUTE))) {
IResourceFactory test = (IResourceFactory)extension.getInstance();
if (test.handles(uri)) {
factory = test;
break;
}
}
}
if (factory == null) {
throw new UnsupportedOperationException(
"No resource factory for " + uri.toString() //$NON-NLS-1$
);
}
IResource result = factory.newResource(uri);
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, result);
}
return result;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.modulebuilder.IModuleBuilderProvider#getModuleBuilder(java.lang.String, com.ibm.jaggr.service.resource.IResource)
*/
@Override
public IModuleBuilder getModuleBuilder(String mid, IResource res) {
IModuleBuilder builder = null;
String path = res.getPath();
int idx = path.lastIndexOf("."); //$NON-NLS-1$
String ext = (idx == -1) ? "" : path.substring(idx+1); //$NON-NLS-1$
if (ext.contains("/")) { //$NON-NLS-1$
ext = ""; //$NON-NLS-1$
}
for (IAggregatorExtension extension : getExtensions(IModuleBuilderExtensionPoint.ID)) {
String extAttrib = extension.getAttribute(IModuleBuilderExtensionPoint.EXTENSION_ATTRIBUTE);
if (ext.equals(extAttrib) || "*".equals(extAttrib)) { //$NON-NLS-1$
IModuleBuilder test = (IModuleBuilder)extension.getInstance();
if (test.handles(mid, res)) {
builder = test;
break;
}
}
}
if (builder == null) {
throw new UnsupportedOperationException(
"No module builder for " + mid //$NON-NLS-1$
);
}
return builder;
}
@Override
public Iterable<IAggregatorExtension> getExtensions(String extensionPointId) {
List<IAggregatorExtension> result = new ArrayList<IAggregatorExtension>();
// List service provider extensions first so that they will be initialized first
// in case any other extension initializers use any variable resolvers.
if (extensionPointId == null || extensionPointId == IServiceProviderExtensionPoint.ID) {
result.addAll(serviceProviderExtensions);
}
if (extensionPointId == null || extensionPointId == IResourceFactoryExtensionPoint.ID) {
result.addAll(resourceFactoryExtensions);
}
if (extensionPointId == null || extensionPointId == IModuleBuilderExtensionPoint.ID) {
result.addAll(moduleBuilderExtensions);
}
if (extensionPointId == null || extensionPointId == IHttpTransportExtensionPoint.ID) {
result.add(httpTransportExtension);
}
return result;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.module.IModuleFactory#newModule(java.lang.String, java.net.URI)
*/
@Override
public IModule newModule(String mid, URI uri) {
return new ModuleImpl(mid, uri);
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#newLayerCache()
*/
@Override
public ILayerCache newLayerCache() {
return LayerImpl.newLayerCache(this);
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#newModuleCache()
*/
@Override
public IModuleCache newModuleCache() {
return ModuleImpl.newModuleCache(this);
}
/**
* Options update listener forwarder. This listener is registered under the option's
* name (the name of the servlet's bundle), and forwards listener events to listeners
* that are registered under the aggregator name.
*
* @param options The options object
* @param sequence The event sequence number
*/
@Override
public void optionsUpdated(IOptions options, long sequence) {
// Options have been updated. Notify any listeners that registered using this
// aggregator instance's name.
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IOptionsListener.class.getName(), "(name=" + getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IOptionsListener listener = (IOptionsListener)getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.optionsUpdated(options, sequence);
} catch (Throwable ignore) {
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
}
/**
* Sets response status and headers for an error response based on the information in the
* specified exception. If development mode is enabled, then returns a 200 status with a
* console.error() message specifying the exception message
*
* @param req
* the request object
* @param resp
* The response object
* @param t
* The exception object
* @param status
* The response status
*/
protected void exceptionResponse(HttpServletRequest req, HttpServletResponse resp, Throwable t, int status) {
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
Level logLevel = (t instanceof BadRequestException || t instanceof NotFoundException)
? Level.WARNING : Level.SEVERE;
if (log.isLoggable(logLevel)) {
String queryArgs = req.getQueryString();
StringBuffer url = req.getRequestURL();
if (queryArgs != null) {
url.append("?").append(queryArgs); //$NON-NLS-1$
}
log.log(logLevel, url.toString(), t);
}
if (getOptions().isDevelopmentMode() || getOptions().isDebugMode()) {
// In development mode, display server exceptions on the browser console
String msg = StringUtil.escapeForJavaScript(
MessageFormat.format(
Messages.ExceptionResponse,
new Object[]{
t.getClass().getName(),
t.getMessage() != null ? StringUtil.escapeForJavaScript(t.getMessage()) : "" //$NON-NLS-1$
}
)
);
String content = "console.error('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
try {
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
} catch (IOException e1) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e1.getMessage(), e1);
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
resp.setStatus(status);
}
}
/**
* Returns the {@code Layer} object for the specified request.
*
* @param request The request object
* @return The layer for the request
* @throws Exception
*/
protected ILayer getLayer(HttpServletRequest request) throws Exception {
// Try non-blocking get() request first
return getCacheManager().getCache().getLayers().getLayer(request);
}
/* (non-Javadoc)
* @see com.ibm.servlets.amd.aggregator.IAggregator#substituteProps(java.lang.String)
*/
@Override
public String substituteProps(String str) {
return substituteProps(str, null);
}
protected final Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}"); //$NON-NLS-1$
/* (non-Javadoc)
* @see com.ibm.jaggr.core.IAggregator#substituteProps(java.lang.String, com.ibm.jaggr.core.IAggregator.SubstitutionTransformer)
*/
@Override
public String substituteProps(String str, SubstitutionTransformer transformer) {
if (str == null) {
return null;
}
StringBuffer buf = new StringBuffer();
Matcher matcher = pattern.matcher(str);
while ( matcher.find() ) {
String propName = matcher.group(1);
String propValue = getPropValue(propName);
if (propValue != null) {
if (transformer != null) {
propValue = transformer.transform(propName, propValue);
}
matcher.appendReplacement(
buf,
propValue
.replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
.replace("$", "\\$") //$NON-NLS-1$ //$NON-NLS-2$
);
} else {
matcher.appendReplacement(buf, "\\${"+propName+"}"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
matcher.appendTail(buf);
return buf.toString();
}
/**
* Returns the value for the property name used by the aggregator. By default,
* it returns the system property indicated by the specified key. This method may be overriden by the platform
* dependent implementation of the aggregator.
* @param propName
* @return Value of the property
*/
public String getPropValue (String propName){
String propValue = null;
propValue = System.getProperty(propName);
IServiceReference[] refs = null;
if (propValue == null) {
try {
refs = getPlatformServices().getServiceReferences(IVariableResolver.class.getName(), "(name=" + getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference sr : refs) {
IVariableResolver resolver = (IVariableResolver)getPlatformServices().getService(sr);
try {
propValue = resolver.resolve(propName);
if (propValue != null) {
break;
}
} finally {
getPlatformServices().ungetService(sr);
}
}
}
}
return propValue;
}
/**
* Loads the {@code IConfig} for this aggregator
*
* @param seq The config change sequence number
* @return True if the new config is changed from the old config
* @throws IOException
*/
protected boolean loadConfig(long seq) throws IOException {
boolean modified = false;
try {
Object previousConfig = config != null ? config.toString() : null;
config = newConfig();
modified = previousConfig != null && !previousConfig.equals(config.toString());
} catch (IOException e) {
throw new IOException(e);
}
notifyConfigListeners(seq);
return modified;
}
/**
* Returns the content type string for the specified filename based on the filename's extension.
* Uses use both MimetypeFileTypeMap and FileNameMap (from URLConnection) because
* MimetypeFileTypeMap provides a convenient way for the application to add new mappings, but
* doesn't provide any default mappings, while FileNameMap, from URLConnection, provides default
* mappings (via <java_home>/lib/content-types.properties) but without easy extensibility.
*
* @param filename
* the file name for which the content type is desired
*
* @return the content type (mime part) string, or application/octet-stream if no match is
* found.
*/
protected String getContentType(String filename) {
String contentType = DEFAULT_CONTENT_TYPE;
if (fileTypeMap != null) {
contentType = fileTypeMap.getContentType(filename);
}
if (DEFAULT_CONTENT_TYPE.equals(contentType) && fileNameMap != null) {
String test = fileNameMap.getContentTypeFor(filename);
if (test != null) {
contentType = test;
}
}
return contentType;
}
/**
* Calls the registered request notifier listeners.
*
* @param action The request action (start or end)
* @param req The request object.
* @param resp The response object.
* @throws IOException
*/
protected void notifyRequestListeners(RequestNotifierAction action, HttpServletRequest req, HttpServletResponse resp) throws IOException {
// notify any listeners that the config has been updated
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IRequestListener.class.getName(), "(name="+getName()+")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IRequestListener listener = (IRequestListener)getPlatformServices().getService(ref);
try {
if (action == RequestNotifierAction.start) {
listener.startRequest(req, resp);
} else {
listener.endRequest(req, resp);
}
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
/**
* Call the registered config change listeners
*
* @param seq The change listener sequence number
* @throws IOException
*/
protected void notifyConfigListeners(long seq) throws IOException {
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IConfigListener.class.getName(), "(name="+getName()+")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IConfigListener listener =
(IConfigListener)getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.configLoaded(config, seq);
} catch (Throwable t) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, t.getMessage(), t);
}
throw new IOException(t);
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
}
/**
* Adds the specified extension to the list of registered extensions.
*
* @param ext
* The extension to add
* @param before
* Reference to an existing extension that the
* new extension should be placed before in the list. If null,
* then the new extension is added to the end of the list
*/
protected void registerExtension(IAggregatorExtension ext, IAggregatorExtension before) {
final String sourceMethod = "registerExtension"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{ext, before});
}
// validate type
String id = ext.getExtensionPointId();
if (IHttpTransportExtensionPoint.ID.equals(id)) {
if (before != null) {
throw new IllegalArgumentException(before.getExtensionPointId());
}
httpTransportExtension = ext;
} else {
List<IAggregatorExtension> list;
if (IResourceFactoryExtensionPoint.ID.equals(id)) {
list = resourceFactoryExtensions;
} else if (IModuleBuilderExtensionPoint.ID.equals(id)) {
list = moduleBuilderExtensions;
} else if (IServiceProviderExtensionPoint.ID.equals(id)) {
list = serviceProviderExtensions;
} else {
throw new IllegalArgumentException(id);
}
if (before == null) {
list.add(ext);
} else {
// find the extension to insert the item in front of
boolean inserted = false;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == before) {
resourceFactoryExtensions.add(i, ext);
inserted = true;
break;
}
}
if (!inserted) {
throw new IllegalArgumentException();
}
}
// If this is a service provider extension the register the specified service if
// one is indicated.
if (IServiceProviderExtensionPoint.ID.equals(id)) {
String interfaceName = ext.getAttribute(IServiceProviderExtensionPoint.SERVICE_ATTRIBUTE);
if (interfaceName != null) {
try {
Dictionary<String, String> props = new Hashtable<String, String>();
// Copy init-params from extension to service dictionary
Set<String> attributeNames = new HashSet<String>(ext.getAttributeNames());
attributeNames.removeAll(Arrays.asList(new String[]{"class", IServiceProviderExtensionPoint.SERVICE_ATTRIBUTE})); //$NON-NLS-1$
for (String propName : attributeNames) {
props.put(propName, ext.getAttribute(propName));
}
// Set name property to aggregator name
props.put("name", getName()); //$NON-NLS-1$
registrations.add(getPlatformServices().registerService(interfaceName, ext.getInstance(), props));
} catch (Exception e) {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.WARNING, e.getMessage(), e);
}
}
}
}
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/**
* For each extension specified, call the extension's
* {@link IExtensionInitializer#initialize} method. Note that this
* can cause additional extensions to be registered though the
* {@link ExtensionRegistrar}.
*
* @param extensions The list of extensions to initialize
* @param reg The extension registrar.
*/
protected void callExtensionInitializers(Iterable<IAggregatorExtension> extensions, ExtensionRegistrar reg) {
final String sourceMethod = "callextensionInitializers"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{extensions, reg});
}
for (IAggregatorExtension extension : extensions) {
Object instance = extension.getInstance();
if (instance instanceof IExtensionInitializer) {
((IExtensionInitializer)instance).initialize(this, extension, reg);
}
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
// Instances of this class are NOT serializable
private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();
}
// Instances of this class are NOT serializable
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new NotSerializableException();
}
protected File initWorkingDirectory(File defaultLocation, Map<String, String> configMap, String versionString) throws FileNotFoundException {
return initWorkingDirectory(defaultLocation, configMap, versionString, Collections.<String>emptySet());
}
/**
* Returns the working directory for this aggregator.
* <p>
* This method is called during aggregator intialization. Subclasses may override this method to
* initialize the aggregator using a different working directory. Use the public
* {@link #getWorkingDirectory()} method to get the working directory from an initialized
* aggregator.
* <p>
* The working directory returned by this method will be located at
* <code><defaultLocation>/<versionString>/<aggregator name></code>
* <p>
* If the directory <code><defaultLocation>/<versionString></code> does not already
* exist when this method is called, then any files in <code>defaultLocation</code> and any
* subdirectories in <code>defaultLocation</code> that are not listed in
* <code>retaindedVersions</code> <strong>WILL BE DELETED</strong>.
*
* @param defaultLocation
* The default, unversioned, directory location. The aggregator assumes that it owns
* this directory and all the files in it.
* @param configMap
* the map of config name/value pairs
* @param versionString
* the version string to qualify the directory location
* @param retainedVersions
* collection of versions to retain when deleting stale version subdirectories.
*
* @return The {@code File} object for the working directory
* @throws FileNotFoundException
*/
protected File initWorkingDirectory(File defaultLocation, Map<String, String> configMap, String versionString, Collection<String> retainedVersions)
throws FileNotFoundException {
final String sourceMethod = "initWorkingDirectory"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{defaultLocation, configMap, versionString, retainedVersions});
}
String dirName = getOptions().getCacheDirectory();
File dirFile = null;
if (dirName == null) {
dirFile = defaultLocation;
} else {
// Make sure the path exists
dirFile = new File(dirName);
dirFile.mkdirs();
}
if (!dirFile.exists()) {
throw new FileNotFoundException(dirFile.toString());
}
if (versionString == null || versionString.length() == 0) {
versionString = "default"; //$NON-NLS-1$
}
// Create a directory using the alias name within the contributing bundle's working
// directory
File versionDir = new File(dirFile, versionString);
if (!versionDir.exists()) {
// Iterate through the default directory, deleting subdirectories who's names are not
// included in retainedVersions
File[] files = dirFile.listFiles();
for (File file : files) {
if (file.isDirectory()) {
if (!retainedVersions.contains(file.getName())) {
if (isTraceLogging) {
log.finer("deleting directory " + file.getAbsolutePath()); //$NON-NLS-1$
}
FileUtils.deleteQuietly(file);
}
} else {
// loose file in top level directory. Delete it
if (isTraceLogging) {
log.finer("Deleting file " + file.getAbsolutePath()); //$NON-NLS-1$
}
file.delete();
}
}
}
File servletDir = null;
try {
servletDir = new File(versionDir, URLEncoder.encode(getName(), "UTF-8")); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
// Should never happen
throw new RuntimeException(e);
}
servletDir.mkdirs();
if (!servletDir.exists()) {
throw new FileNotFoundException(servletDir.getAbsolutePath());
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, servletDir);
}
return servletDir;
}
/**
* Returns the name for this aggregator
* <p>
* This method is called during aggregator intialization. Subclasses may
* override this method to initialize the aggregator using a different
* name. Use the public {@link IAggregator#getName()} method
* to get the name of an initialized aggregator.
*
* @param configMap
* A Map having key-value pairs denoting configuration settings for the aggregator servlet
* @return The aggregator name
*/
protected String getAggregatorName(Map<String, String> configMap) {
// trim leading and trailing '/'
String alias = (String)configMap.get("alias"); //$NON-NLS-1$
while (alias.charAt(0) == '/')
alias = alias.substring(1);
while (alias.charAt(alias.length()-1) == '/')
alias = alias.substring(0, alias.length()-1);
return alias;
}
/**
* Instantiates a new dependencies object
* @param stamp
* the time stamp
* @return The new dependencies
*/
protected IDependencies newDependencies(long stamp) {
return new DependenciesImpl(this, stamp);
}
/**
* Instantiates a new config object
*
* @return The new config
* @throws IOException
*/
protected IConfig newConfig() throws IOException {
return new ConfigImpl(this);
}
/**
* Instantiates a new cache manager
* @param stamp
* the time stamp
* @return The new cache manager
* @throws IOException
*/
protected ICacheManager newCacheManager(long stamp) throws IOException {
return new CacheManagerImpl(this, stamp);
}
@Override
public abstract IOptions getOptions();
@Override
public abstract IExecutors getExecutors();
@Override
public IPlatformServices getPlatformServices() {
return platformServices;
}
/**
* This method does some initialization for the aggregator servlet. This method is called from platform
* dependent Aggregator implementation during its initialization.
*
* @throws Exception
*/
public void initialize()
throws Exception {
// create the config. Keep it local so it won't be seen by deps and cacheMgr
// until after we check for customization last-mods. Then we'll set the config
// in the instance data and call the config listeners.
IConfig config = newConfig();
// Check last-modified times of resources in the overrides folders. These resources
// are considered to be dynamic in a production environment and we want to
// detect new/changed resources in these folders on startup so that we can clear
// caches, etc.
OverrideFoldersTreeWalker walker = new OverrideFoldersTreeWalker(this, config);
walker.walkTree();
deps = newDependencies(walker.getLastModifiedJS());
cacheMgr = newCacheManager(walker.getLastModified());
resourcePaths = getPathsAndAliases(getInitParams());
this.config = config;
}
/**
* Returns a mapping of resource aliases to IResources defined in the init-params.
* If the IResource is null, then the alias is for the aggregator itself rather
* than a resource location.
*
* @param initParams
* The aggregator init-params
*
* @return Mapping of aliases to IResources
*/
protected Map<String, IResource> getPathsAndAliases(InitParams initParams) {
final String sourceMethod = "getPahtsAndAliases"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{initParams});
}
Map<String, IResource> resourcePaths = new HashMap<String, IResource>();
List<String> aliases = initParams.getValues(InitParams.ALIAS_INITPARAM);
for (String alias : aliases) {
addAlias(alias, null, "alias", resourcePaths); //$NON-NLS-1$
}
List<String> resourceIds = initParams.getValues(InitParams.RESOURCEID_INITPARAM);
for (String resourceId : resourceIds) {
aliases = initParams.getValues(resourceId + ":alias"); //$NON-NLS-1$
List<String> baseNames = initParams.getValues(resourceId + ":base-name"); //$NON-NLS-1$
if (aliases == null || aliases.size() != 1) {
throw new IllegalArgumentException(resourceId + ":aliases"); //$NON-NLS-1$
}
if (baseNames == null || baseNames.size() != 1) {
throw new IllegalArgumentException(resourceId + ":base-name"); //$NON-NLS-1$
}
String alias = aliases.get(0);
String baseName = baseNames.get(0);
// make sure not root path
boolean isPathComp = false;
for (String part : alias.split("/")) { //$NON-NLS-1$
if (part.length() > 0) {
isPathComp = true;
break;
}
}
if (!isPathComp) {
throw new IllegalArgumentException(resourceId + ":alias = " + alias); //$NON-NLS-1$
}
IResource res = newResource(URI.create(baseName));
if (res == null) {
throw new NullPointerException();
}
addAlias(alias, res, resourceId + ":alias", resourcePaths); //$NON-NLS-1$
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, resourcePaths);
}
return Collections.unmodifiableMap(resourcePaths);
}
protected void addAlias(String alias, IResource res, String initParamName, Map<String, IResource> map) {
final String sourceMethod = "addAlias"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{alias, res, initParamName, map});
}
String[] parts;
if (alias == null || (parts = alias.split("/")).length == 0) { //$NON-NLS-1$
throw new IllegalArgumentException(initParamName + " = " + alias); //$NON-NLS-1$
}
List<String> nonEmptyParts = new ArrayList<String>(parts.length);
for (String part : parts) {
if (part != null && part.length() > 0) {
nonEmptyParts.add(part);
}
}
alias = "/" + StringUtils.join(nonEmptyParts, "/"); //$NON-NLS-1$ //$NON-NLS-2$
// Make sure no overlapping alias paths
for (String test : map.keySet()) {
if (alias.equals(test)) {
throw new IllegalArgumentException("Duplicate alias path: " + alias); //$NON-NLS-1$
} else if (alias.startsWith(test + "/") || test.startsWith(alias + "/")) { //$NON-NLS-1$ //$NON-NLS-2$
throw new IllegalArgumentException("Overlapping alias paths: " + alias + ", " + test); //$NON-NLS-1$ //$NON-NLS-2$
}
}
map.put(alias, res);
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
/**
* Implements the {@link IExtensionRegistrar} interface
*/
public class ExtensionRegistrar implements IExtensionRegistrar {
boolean open = true;
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IExtensionInitializer.IExtensionRegistrar#registerExtension(java.lang.Object, java.util.Properties, InitParams, java.lang.String, java.lang.String)
*/
@Override
public void registerExtension(
Object impl,
Properties attributes,
InitParams initParams,
String extensionPointId,
String uniqueId,
IAggregatorExtension before) {
if (!open) {
throw new IllegalStateException("ExtensionRegistrar is closed"); //$NON-NLS-1$
}
IAggregatorExtension extension = new AggregatorExtension(
impl,
new Properties(attributes),
initParams,
extensionPointId,
uniqueId,
AbstractAggregatorImpl.this
);
AbstractAggregatorImpl.this.registerExtension(extension, before);
if (impl instanceof IExtensionInitializer) {
((IExtensionInitializer)impl).initialize(AbstractAggregatorImpl.this, extension, this);
}
}
public void closeRegistration() {
open = false;
}
}
/**
* Registers the layer listener
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void registerLayerListener() {
Dictionary dict = new Properties();
dict.put("name", getName()); //$NON-NLS-1$
registrations.add(getPlatformServices().registerService(
ILayerListener.class.getName(), new AggregatorLayerListener(this), dict));
}
}
|
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/AbstractAggregatorImpl.java
|
/*
* (C) Copyright 2012, IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.jaggr.core.impl;
import com.ibm.jaggr.core.BadRequestException;
import com.ibm.jaggr.core.DependencyVerificationException;
import com.ibm.jaggr.core.IAggregator;
import com.ibm.jaggr.core.IAggregatorExtension;
import com.ibm.jaggr.core.IExtensionInitializer;
import com.ibm.jaggr.core.IExtensionInitializer.IExtensionRegistrar;
import com.ibm.jaggr.core.IPlatformServices;
import com.ibm.jaggr.core.IRequestListener;
import com.ibm.jaggr.core.IServiceProviderExtensionPoint;
import com.ibm.jaggr.core.IServiceReference;
import com.ibm.jaggr.core.IServiceRegistration;
import com.ibm.jaggr.core.IShutdownListener;
import com.ibm.jaggr.core.IVariableResolver;
import com.ibm.jaggr.core.InitParams;
import com.ibm.jaggr.core.NotFoundException;
import com.ibm.jaggr.core.PlatformServicesException;
import com.ibm.jaggr.core.ProcessingDependenciesException;
import com.ibm.jaggr.core.cache.ICacheManager;
import com.ibm.jaggr.core.config.IConfig;
import com.ibm.jaggr.core.config.IConfigListener;
import com.ibm.jaggr.core.deps.IDependencies;
import com.ibm.jaggr.core.executors.IExecutors;
import com.ibm.jaggr.core.impl.cache.CacheManagerImpl;
import com.ibm.jaggr.core.impl.config.ConfigImpl;
import com.ibm.jaggr.core.impl.deps.DependenciesImpl;
import com.ibm.jaggr.core.impl.layer.LayerImpl;
import com.ibm.jaggr.core.impl.module.ModuleImpl;
import com.ibm.jaggr.core.layer.ILayer;
import com.ibm.jaggr.core.layer.ILayerCache;
import com.ibm.jaggr.core.layer.ILayerListener;
import com.ibm.jaggr.core.module.IModule;
import com.ibm.jaggr.core.module.IModuleCache;
import com.ibm.jaggr.core.modulebuilder.IModuleBuilder;
import com.ibm.jaggr.core.modulebuilder.IModuleBuilderExtensionPoint;
import com.ibm.jaggr.core.options.IOptions;
import com.ibm.jaggr.core.options.IOptionsListener;
import com.ibm.jaggr.core.resource.IResource;
import com.ibm.jaggr.core.resource.IResourceFactory;
import com.ibm.jaggr.core.resource.IResourceFactoryExtensionPoint;
import com.ibm.jaggr.core.transport.IHttpTransport;
import com.ibm.jaggr.core.transport.IHttpTransportExtensionPoint;
import com.ibm.jaggr.core.util.CopyUtil;
import com.ibm.jaggr.core.util.SequenceNumberProvider;
import com.ibm.jaggr.core.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Implementation for IAggregator and HttpServlet interfaces.
*
* Note that despite the fact that HttpServlet (which this class extends)
* implements Serializable, attempts to serialize instances of this class will
* fail due to the fact that not all instance data is serializable. The
* assumption is that because instances of this class are created by the OSGi
* Framework, and the framework itself does not support serialization, then no
* attempts will be made to serialize instances of this class.
*/
@SuppressWarnings({ "serial", "deprecation" })
public abstract class AbstractAggregatorImpl extends HttpServlet implements IOptionsListener, IAggregator {
/**
* Default value for resourcefactories init-param
*/
protected static final String DEFAULT_RESOURCEFACTORIES =
"com.ibm.jaggr.service.default.resourcefactories"; //$NON-NLS-1$
/**
* Default value for modulebuilders init-param
*/
protected static final String DEFAULT_MODULEBUILDERS =
"com.ibm.jaggr.service.default.modulebuilders"; //$NON-NLS-1$
/**
* Default value for httptransport init-param
*/
protected static final String DEFAULT_HTTPTRANSPORT =
"com.ibm.jaggr.service.dojo.httptransport"; //$NON-NLS-1$
private final static String DEFAULT_CONTENT_TYPE = "application/octet-stream"; //$NON-NLS-1$
private static final Logger log = Logger.getLogger(AbstractAggregatorImpl.class.getName());
protected ICacheManager cacheMgr = null;
protected IConfig config = null;
//protected Bundle bundle = null;
protected String name = null;
protected IDependencies deps = null;
protected List<IServiceRegistration> registrations = new LinkedList<IServiceRegistration>();
protected List<IServiceReference> serviceReferences = Collections.synchronizedList(new LinkedList<IServiceReference>());
protected InitParams initParams = null;
protected IOptions localOptions = null;
protected MimetypesFileTypeMap fileTypeMap = null;
protected FileNameMap fileNameMap = null;
private LinkedList<IAggregatorExtension> resourceFactoryExtensions = new LinkedList<IAggregatorExtension>();
private LinkedList<IAggregatorExtension> moduleBuilderExtensions = new LinkedList<IAggregatorExtension>();
private LinkedList<IAggregatorExtension> serviceProviderExtensions = new LinkedList<IAggregatorExtension>();
private IAggregatorExtension httpTransportExtension = null;
private boolean isShuttingDown = false;
protected IPlatformServices platformServices;
protected Map<String, IResource> resourcePaths;
enum RequestNotifierAction {
start,
end
};
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
final String sourceMethod = "init"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{servletConfig});
}
super.init(servletConfig);
// Initialize the type maps (see getContentType)
fileTypeMap = new MimetypesFileTypeMap();
fileNameMap = URLConnection.getFileNameMap();
final ServletContext context = servletConfig.getServletContext();
// Set servlet context attributes for access though the request
context.setAttribute(IAggregator.AGGREGATOR_REQATTRNAME, this);
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#destroy()
*/
@Override
public void destroy() {
final String sourceMethod = "destroy"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
shutdown();
super.destroy();
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/**
* Called when the aggregator is shutting down. Note that there is inconsistency
* among servlet bridge implementations over when {@link HttpServlet#destroy()}
* is called relative to when (or even if) the bundle is stopped. So this method
* may be called from the destroy method or the bundle listener or both.
*/
synchronized protected void shutdown() {
final String sourceMethod = "shutdown"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
if (!isShuttingDown) {
isShuttingDown = true;
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IShutdownListener.class.getName(), "(name=" + getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IShutdownListener listener = (IShutdownListener)getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.shutdown(this);
} catch (Exception e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
for (IServiceRegistration registration : registrations) {
registration.unregister();
}
for (IServiceReference ref : serviceReferences) {
getPlatformServices().ungetService(ref);
}
registrations.clear();
serviceReferences.clear();
// Clear references to objects that can potentially reference this object
// so as to avoid memory leaks due to circular references.
resourceFactoryExtensions.clear();
moduleBuilderExtensions.clear();
serviceProviderExtensions.clear();
httpTransportExtension = null;
initParams = null;
cacheMgr = null;
config = null;
deps = null;
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
final String sourceMethod = "doGet"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp});
log.finer("Request URL=" + req.getRequestURI()); //$NON-NLS-1$
}
if (isShuttingDown) {
// Server has been shut-down, or is in the process of shutting down.
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
if (isTraceLogging) {
log.finer("Processing request after server shutdown. Returning SC_SERVICE_UNAVAILABLE"); //$NON-NLS-1$
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
return;
}
resp.addHeader("Server", "JavaScript Aggregator"); //$NON-NLS-1$ //$NON-NLS-2$
String pathInfo = req.getPathInfo();
if (pathInfo == null) {
processAggregatorRequest(req, resp);
} else {
boolean processed = false;
// search resource paths to see if we should treat as aggregator request or resource request
for (Map.Entry<String, IResource> entry : resourcePaths.entrySet()) {
String path = entry.getKey();
if (path.equals(pathInfo) && entry.getValue() == null) {
processAggregatorRequest(req, resp);
processed = true;
break;
}
if (pathInfo.startsWith(path)) {
if ((path.length() == pathInfo.length() || pathInfo.charAt(path.length()) == '/') && entry.getValue() != null) {
String resPath = path.length() == pathInfo.length() ? "" : pathInfo.substring(path.length()+1); //$NON-NLS-1$
IResource res = entry.getValue();
processResourceRequest(req, resp, res, resPath);
processed = true;
break;
}
}
}
if (!processed) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
protected void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, IResource res, String path) {
final String sourceMethod = "processRequest"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp, res, path});
}
try {
IResource resolved = res;
URI uri = res.getURI();
if (path != null && path.length() > 0) {
if (!uri.getPath().endsWith("/")) { //$NON-NLS-1$
// Make sure we resolve against a folder path
uri = new URI(uri.getScheme(), uri.getAuthority(),
uri.getPath() + "/", uri.getQuery(), uri.getFragment()); //$NON-NLS-1$
res = newResource(uri);
}
resolved = res.resolve(path);
}
if (!resolved.exists()) {
throw new NotFoundException(resolved.getURI().toString());
}
// See if this is a conditional GET
long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
if (modifiedSince >= resolved.lastModified()) {
if (log.isLoggable(Level.FINER)) {
log.finer("Returning Not Modified response for resource in servlet" + //$NON-NLS-1$
getName() + ":" + resolved.getURI()); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
} else {
resp.setDateHeader("Last-Modified", resolved.lastModified()); //$NON-NLS-1$
int expires = getConfig().getExpires();
boolean hasCacheBust = req.getHeader("cb") != null || req.getHeader("cachebust") != null; //$NON-NLS-1$ //$NON-NLS-2$
resp.addHeader(
"Cache-Control", //$NON-NLS-1$
"public" + (expires > 0 && hasCacheBust ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
);
resp.setHeader("Content-Type", getContentType(resolved.getPath())); //$NON-NLS-1$
InputStream is = resolved.getInputStream();
OutputStream os = resp.getOutputStream();
CopyUtil.copy(is, os);
}
} catch (NotFoundException e) {
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.WARNING, e.getMessage() + " - " + req.getRequestURI(), e); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) {
final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp});
}
req.setAttribute(AGGREGATOR_REQATTRNAME, this);
ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);
try {
// Validate config last-modified if development mode is enabled
if (getOptions().isDevelopmentMode()) {
long lastModified = -1;
URI configUri = getConfig().getConfigUri();
if (configUri != null) {
try {
// try to get platform URI from IResource in case uri specifies
// aggregator specific scheme like namedbundleresource
configUri = newResource(configUri).getURI();
} catch (UnsupportedOperationException e) {
// Not fatal. Just use uri as specified.
}
lastModified = configUri.toURL().openConnection().getLastModified();
}
if (lastModified > getConfig().lastModified()) {
if (reloadConfig()) {
// If the config has been modified, then dependencies will be revalidated
// asynchronously. Rather than forcing the current request to wait, return
// a response that will display an alert informing the user of what is
// happening and asking them to reload the page.
String content = "alert('" + //$NON-NLS-1$
StringUtil.escapeForJavaScript(Messages.ConfigModified) +
"');"; //$NON-NLS-1$
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
return;
}
}
}
getTransport().decorateRequest(req);
notifyRequestListeners(RequestNotifierAction.start, req, resp);
ILayer layer = getLayer(req);
long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req)) / 1000) * 1000;
if (modifiedSince >= lastModified) {
if (log.isLoggable(Level.FINER)) {
log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
getName() + ":" + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString()); //$NON-NLS-1$
}
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
else {
// Get the InputStream for the response. This call sets the Content-Type,
// Content-Length and Content-Encoding headers in the response.
InputStream in = layer.getInputStream(req, resp);
// if any of the readers included an error response, then don't cache the layer.
if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
int expires = getConfig().getExpires();
boolean hasCacheBust = req.getHeader("cb") != null || req.getHeader("cachebust") != null; //$NON-NLS-1$ //$NON-NLS-2$
resp.addHeader(
"Cache-Control", //$NON-NLS-1$
"public" + (expires > 0 && hasCacheBust ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
);
}
CopyUtil.copy(in, resp.getOutputStream());
}
notifyRequestListeners(RequestNotifierAction.end, req, resp);
} catch (DependencyVerificationException e) {
// clear the cache now even though it will be cleared when validateDeps has
// finished (asynchronously) so that any new requests will be forced to wait
// until dependencies have been validated.
getCacheManager().clearCache();
getDependencies().validateDeps(false);
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
if (getOptions().isDevelopmentMode()) {
String msg = StringUtil.escapeForJavaScript(
MessageFormat.format(
Messages.DepVerificationFailed,
new Object[]{
e.getMessage(),
"aggregator " + //$NON-NLS-1$
"validatedeps " + //$NON-NLS-1$
getName() +
" clean", //$NON-NLS-1$
getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
}
)
);
String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
try {
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
} catch (IOException e1) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e1.getMessage(), e1);
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
} catch (ProcessingDependenciesException e) {
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
if (getOptions().isDevelopmentMode()) {
String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
try {
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
} catch (IOException e1) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e1.getMessage(), e1);
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
} catch (BadRequestException e) {
exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
} catch (NotFoundException e) {
exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
} catch (Exception e) {
exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
concurrentMap.clear();
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#reloadConfig()
*/
@Override
public boolean reloadConfig() throws IOException {
return loadConfig(SequenceNumberProvider.incrementAndGetSequenceNumber());
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getDependencies()
*/
@Override
public IDependencies getDependencies() {
return deps;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getName()
*/
@Override
public String getName() {
return name;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getConfig()
*/
@Override
public IConfig getConfig() {
return config;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getCacheManager()
*/
@Override
public ICacheManager getCacheManager() {
return cacheMgr;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.core.IAggregator#getInitParams()
*/
@Override
public InitParams getInitParams() {
return initParams;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#asServlet()
*/
@Override
public HttpServlet asServlet() {
return this;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#getTransport()
*/
@Override
public IHttpTransport getTransport() {
IAggregatorExtension ext = getExtensions(IHttpTransportExtensionPoint.ID).iterator().next();
return (IHttpTransport)(ext != null ? ext.getInstance() : null);
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.resource.IResourceProvider#getResource(java.net.URI)
*/
@Override
public IResource newResource(URI uri) {
final String sourceMethod = "newResource"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{uri});
}
if (!uri.isAbsolute()) {
// URI is not absolute, so make it absolute.
try {
uri = getPlatformServices().getAppContextURI().resolve(uri.getPath());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
IResourceFactory factory = null;
String scheme = uri.getScheme();
for (IAggregatorExtension extension : getExtensions(IResourceFactoryExtensionPoint.ID)) {
if (scheme.equals(extension.getAttribute(IResourceFactoryExtensionPoint.SCHEME_ATTRIBUTE))) {
IResourceFactory test = (IResourceFactory)extension.getInstance();
if (test.handles(uri)) {
factory = test;
break;
}
}
}
if (factory == null) {
throw new UnsupportedOperationException(
"No resource factory for " + uri.toString() //$NON-NLS-1$
);
}
IResource result = factory.newResource(uri);
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, result);
}
return result;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.modulebuilder.IModuleBuilderProvider#getModuleBuilder(java.lang.String, com.ibm.jaggr.service.resource.IResource)
*/
@Override
public IModuleBuilder getModuleBuilder(String mid, IResource res) {
IModuleBuilder builder = null;
String path = res.getPath();
int idx = path.lastIndexOf("."); //$NON-NLS-1$
String ext = (idx == -1) ? "" : path.substring(idx+1); //$NON-NLS-1$
if (ext.contains("/")) { //$NON-NLS-1$
ext = ""; //$NON-NLS-1$
}
for (IAggregatorExtension extension : getExtensions(IModuleBuilderExtensionPoint.ID)) {
String extAttrib = extension.getAttribute(IModuleBuilderExtensionPoint.EXTENSION_ATTRIBUTE);
if (ext.equals(extAttrib) || "*".equals(extAttrib)) { //$NON-NLS-1$
IModuleBuilder test = (IModuleBuilder)extension.getInstance();
if (test.handles(mid, res)) {
builder = test;
break;
}
}
}
if (builder == null) {
throw new UnsupportedOperationException(
"No module builder for " + mid //$NON-NLS-1$
);
}
return builder;
}
@Override
public Iterable<IAggregatorExtension> getExtensions(String extensionPointId) {
List<IAggregatorExtension> result = new ArrayList<IAggregatorExtension>();
// List service provider extensions first so that they will be initialized first
// in case any other extension initializers use any variable resolvers.
if (extensionPointId == null || extensionPointId == IServiceProviderExtensionPoint.ID) {
result.addAll(serviceProviderExtensions);
}
if (extensionPointId == null || extensionPointId == IResourceFactoryExtensionPoint.ID) {
result.addAll(resourceFactoryExtensions);
}
if (extensionPointId == null || extensionPointId == IModuleBuilderExtensionPoint.ID) {
result.addAll(moduleBuilderExtensions);
}
if (extensionPointId == null || extensionPointId == IHttpTransportExtensionPoint.ID) {
result.add(httpTransportExtension);
}
return result;
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.module.IModuleFactory#newModule(java.lang.String, java.net.URI)
*/
@Override
public IModule newModule(String mid, URI uri) {
return new ModuleImpl(mid, uri);
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#newLayerCache()
*/
@Override
public ILayerCache newLayerCache() {
return LayerImpl.newLayerCache(this);
}
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IAggregator#newModuleCache()
*/
@Override
public IModuleCache newModuleCache() {
return ModuleImpl.newModuleCache(this);
}
/**
* Options update listener forwarder. This listener is registered under the option's
* name (the name of the servlet's bundle), and forwards listener events to listeners
* that are registered under the aggregator name.
*
* @param options The options object
* @param sequence The event sequence number
*/
@Override
public void optionsUpdated(IOptions options, long sequence) {
// Options have been updated. Notify any listeners that registered using this
// aggregator instance's name.
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IOptionsListener.class.getName(), "(name=" + getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IOptionsListener listener = (IOptionsListener)getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.optionsUpdated(options, sequence);
} catch (Throwable ignore) {
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
}
/**
* Sets response status and headers for an error response based on the information in the
* specified exception. If development mode is enabled, then returns a 200 status with a
* console.error() message specifying the exception message
*
* @param req
* the request object
* @param resp
* The response object
* @param t
* The exception object
* @param status
* The response status
*/
protected void exceptionResponse(HttpServletRequest req, HttpServletResponse resp, Throwable t, int status) {
resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
Level logLevel = (t instanceof BadRequestException || t instanceof NotFoundException)
? Level.WARNING : Level.SEVERE;
if (log.isLoggable(logLevel)) {
String queryArgs = req.getQueryString();
StringBuffer url = req.getRequestURL();
if (queryArgs != null) {
url.append("?").append(queryArgs); //$NON-NLS-1$
}
log.log(logLevel, url.toString(), t);
}
if (getOptions().isDevelopmentMode() || getOptions().isDebugMode()) {
// In development mode, display server exceptions on the browser console
String msg = StringUtil.escapeForJavaScript(
MessageFormat.format(
Messages.ExceptionResponse,
new Object[]{
t.getClass().getName(),
t.getMessage() != null ? StringUtil.escapeForJavaScript(t.getMessage()) : "" //$NON-NLS-1$
}
)
);
String content = "console.error('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
try {
CopyUtil.copy(new StringReader(content), resp.getOutputStream());
} catch (IOException e1) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e1.getMessage(), e1);
}
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
resp.setStatus(status);
}
}
/**
* Returns the {@code Layer} object for the specified request.
*
* @param request The request object
* @return The layer for the request
* @throws Exception
*/
protected ILayer getLayer(HttpServletRequest request) throws Exception {
// Try non-blocking get() request first
return getCacheManager().getCache().getLayers().getLayer(request);
}
/* (non-Javadoc)
* @see com.ibm.servlets.amd.aggregator.IAggregator#substituteProps(java.lang.String)
*/
@Override
public String substituteProps(String str) {
return substituteProps(str, null);
}
protected final Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}"); //$NON-NLS-1$
/* (non-Javadoc)
* @see com.ibm.jaggr.core.IAggregator#substituteProps(java.lang.String, com.ibm.jaggr.core.IAggregator.SubstitutionTransformer)
*/
@Override
public String substituteProps(String str, SubstitutionTransformer transformer) {
if (str == null) {
return null;
}
StringBuffer buf = new StringBuffer();
Matcher matcher = pattern.matcher(str);
while ( matcher.find() ) {
String propName = matcher.group(1);
String propValue = getPropValue(propName);
if (propValue != null) {
if (transformer != null) {
propValue = transformer.transform(propName, propValue);
}
matcher.appendReplacement(
buf,
propValue
.replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
.replace("$", "\\$") //$NON-NLS-1$ //$NON-NLS-2$
);
} else {
matcher.appendReplacement(buf, "\\${"+propName+"}"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
matcher.appendTail(buf);
return buf.toString();
}
/**
* Returns the value for the property name used by the aggregator. By default,
* it returns the system property indicated by the specified key. This method may be overriden by the platform
* dependent implementation of the aggregator.
* @param propName
* @return Value of the property
*/
public String getPropValue (String propName){
String propValue = null;
propValue = System.getProperty(propName);
IServiceReference[] refs = null;
if (propValue == null) {
try {
refs = getPlatformServices().getServiceReferences(IVariableResolver.class.getName(), "(name=" + getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference sr : refs) {
IVariableResolver resolver = (IVariableResolver)getPlatformServices().getService(sr);
try {
propValue = resolver.resolve(propName);
if (propValue != null) {
break;
}
} finally {
getPlatformServices().ungetService(sr);
}
}
}
}
return propValue;
}
/**
* Loads the {@code IConfig} for this aggregator
*
* @param seq The config change sequence number
* @return True if the new config is changed from the old config
* @throws IOException
*/
protected boolean loadConfig(long seq) throws IOException {
boolean modified = false;
try {
Object previousConfig = config != null ? config.toString() : null;
config = newConfig();
modified = previousConfig != null && !previousConfig.equals(config.toString());
} catch (IOException e) {
throw new IOException(e);
}
notifyConfigListeners(seq);
return modified;
}
/**
* Returns the content type string for the specified filename based on the filename's extension.
* Uses use both MimetypeFileTypeMap and FileNameMap (from URLConnection) because
* MimetypeFileTypeMap provides a convenient way for the application to add new mappings, but
* doesn't provide any default mappings, while FileNameMap, from URLConnection, provides default
* mappings (via <java_home>/lib/content-types.properties) but without easy extensibility.
*
* @param filename
* the file name for which the content type is desired
*
* @return the content type (mime part) string, or application/octet-stream if no match is
* found.
*/
protected String getContentType(String filename) {
String contentType = DEFAULT_CONTENT_TYPE;
if (fileTypeMap != null) {
contentType = fileTypeMap.getContentType(filename);
}
if (DEFAULT_CONTENT_TYPE.equals(contentType) && fileNameMap != null) {
String test = fileNameMap.getContentTypeFor(filename);
if (test != null) {
contentType = test;
}
}
return contentType;
}
/**
* Calls the registered request notifier listeners.
*
* @param action The request action (start or end)
* @param req The request object.
* @param resp The response object.
* @throws IOException
*/
protected void notifyRequestListeners(RequestNotifierAction action, HttpServletRequest req, HttpServletResponse resp) throws IOException {
// notify any listeners that the config has been updated
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IRequestListener.class.getName(), "(name="+getName()+")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IRequestListener listener = (IRequestListener)getPlatformServices().getService(ref);
try {
if (action == RequestNotifierAction.start) {
listener.startRequest(req, resp);
} else {
listener.endRequest(req, resp);
}
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
/**
* Call the registered config change listeners
*
* @param seq The change listener sequence number
* @throws IOException
*/
protected void notifyConfigListeners(long seq) throws IOException {
IServiceReference[] refs = null;
try {
refs = getPlatformServices().getServiceReferences(IConfigListener.class.getName(), "(name="+getName()+")"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
if (refs != null) {
for (IServiceReference ref : refs) {
IConfigListener listener =
(IConfigListener)getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.configLoaded(config, seq);
} catch (Throwable t) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, t.getMessage(), t);
}
throw new IOException(t);
} finally {
getPlatformServices().ungetService(ref);
}
}
}
}
}
/**
* Adds the specified extension to the list of registered extensions.
*
* @param ext
* The extension to add
* @param before
* Reference to an existing extension that the
* new extension should be placed before in the list. If null,
* then the new extension is added to the end of the list
*/
protected void registerExtension(IAggregatorExtension ext, IAggregatorExtension before) {
final String sourceMethod = "registerExtension"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{ext, before});
}
// validate type
String id = ext.getExtensionPointId();
if (IHttpTransportExtensionPoint.ID.equals(id)) {
if (before != null) {
throw new IllegalArgumentException(before.getExtensionPointId());
}
httpTransportExtension = ext;
} else {
List<IAggregatorExtension> list;
if (IResourceFactoryExtensionPoint.ID.equals(id)) {
list = resourceFactoryExtensions;
} else if (IModuleBuilderExtensionPoint.ID.equals(id)) {
list = moduleBuilderExtensions;
} else if (IServiceProviderExtensionPoint.ID.equals(id)) {
list = serviceProviderExtensions;
} else {
throw new IllegalArgumentException(id);
}
if (before == null) {
list.add(ext);
} else {
// find the extension to insert the item in front of
boolean inserted = false;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == before) {
resourceFactoryExtensions.add(i, ext);
inserted = true;
break;
}
}
if (!inserted) {
throw new IllegalArgumentException();
}
}
// If this is a service provider extension the register the specified service if
// one is indicated.
if (IServiceProviderExtensionPoint.ID.equals(id)) {
String interfaceName = ext.getAttribute(IServiceProviderExtensionPoint.SERVICE_ATTRIBUTE);
if (interfaceName != null) {
try {
Dictionary<String, String> props = new Hashtable<String, String>();
// Copy init-params from extension to service dictionary
Set<String> attributeNames = new HashSet<String>(ext.getAttributeNames());
attributeNames.removeAll(Arrays.asList(new String[]{"class", IServiceProviderExtensionPoint.SERVICE_ATTRIBUTE})); //$NON-NLS-1$
for (String propName : attributeNames) {
props.put(propName, ext.getAttribute(propName));
}
// Set name property to aggregator name
props.put("name", getName()); //$NON-NLS-1$
registrations.add(getPlatformServices().registerService(interfaceName, ext.getInstance(), props));
} catch (Exception e) {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.WARNING, e.getMessage(), e);
}
}
}
}
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
/**
* For each extension specified, call the extension's
* {@link IExtensionInitializer#initialize} method. Note that this
* can cause additional extensions to be registered though the
* {@link ExtensionRegistrar}.
*
* @param extensions The list of extensions to initialize
* @param reg The extension registrar.
*/
protected void callExtensionInitializers(Iterable<IAggregatorExtension> extensions, ExtensionRegistrar reg) {
final String sourceMethod = "callextensionInitializers"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{extensions, reg});
}
for (IAggregatorExtension extension : extensions) {
Object instance = extension.getInstance();
if (instance instanceof IExtensionInitializer) {
((IExtensionInitializer)instance).initialize(this, extension, reg);
}
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
}
// Instances of this class are NOT serializable
private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();
}
// Instances of this class are NOT serializable
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new NotSerializableException();
}
protected File initWorkingDirectory(File defaultLocation, Map<String, String> configMap, String versionString) throws FileNotFoundException {
return initWorkingDirectory(defaultLocation, configMap, versionString, Collections.<String>emptySet());
}
/**
* Returns the working directory for this aggregator.
* <p>
* This method is called during aggregator intialization. Subclasses may override this method to
* initialize the aggregator using a different working directory. Use the public
* {@link #getWorkingDirectory()} method to get the working directory from an initialized
* aggregator.
* <p>
* The working directory returned by this method will be located at
* <code><defaultLocation>/<versionString>/<aggregator name></code>
* <p>
* If the directory <code><defaultLocation>/<versionString></code> does not already
* exist when this method is called, then any files in <code>defaultLocation</code> and any
* subdirectories in <code>defaultLocation</code> that are not listed in
* <code>retaindedVersions</code> <strong>WILL BE DELETED</strong>.
*
* @param defaultLocation
* The default, unversioned, directory location. The aggregator assumes that it owns
* this directory and all the files in it.
* @param configMap
* the map of config name/value pairs
* @param versionString
* the version string to qualify the directory location
* @param retainedVersions
* collection of versions to retain when deleting stale version subdirectories.
*
* @return The {@code File} object for the working directory
* @throws FileNotFoundException
*/
protected File initWorkingDirectory(File defaultLocation, Map<String, String> configMap, String versionString, Collection<String> retainedVersions)
throws FileNotFoundException {
final String sourceMethod = "initWorkingDirectory"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{defaultLocation, configMap, versionString, retainedVersions});
}
String dirName = getOptions().getCacheDirectory();
File dirFile = null;
if (dirName == null) {
dirFile = defaultLocation;
} else {
// Make sure the path exists
dirFile = new File(dirName);
dirFile.mkdirs();
}
if (!dirFile.exists()) {
throw new FileNotFoundException(dirFile.toString());
}
if (versionString == null || versionString.length() == 0) {
versionString = "default"; //$NON-NLS-1$
}
// Create a directory using the alias name within the contributing bundle's working
// directory
File versionDir = new File(dirFile, versionString);
if (!versionDir.exists()) {
// Iterate through the default directory, deleting subdirectories who's names are not
// included in retainedVersions
File[] files = dirFile.listFiles();
for (File file : files) {
if (file.isDirectory()) {
if (!retainedVersions.contains(file.getName())) {
if (isTraceLogging) {
log.finer("deleting directory " + file.getAbsolutePath()); //$NON-NLS-1$
}
FileUtils.deleteQuietly(file);
}
} else {
// loose file in top level directory. Delete it
if (isTraceLogging) {
log.finer("Deleting file " + file.getAbsolutePath()); //$NON-NLS-1$
}
file.delete();
}
}
}
File servletDir = null;
try {
servletDir = new File(versionDir, URLEncoder.encode(getName(), "UTF-8")); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
// Should never happen
throw new RuntimeException(e);
}
servletDir.mkdirs();
if (!servletDir.exists()) {
throw new FileNotFoundException(servletDir.getAbsolutePath());
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, servletDir);
}
return servletDir;
}
/**
* Returns the name for this aggregator
* <p>
* This method is called during aggregator intialization. Subclasses may
* override this method to initialize the aggregator using a different
* name. Use the public {@link IAggregator#getName()} method
* to get the name of an initialized aggregator.
*
* @param configMap
* A Map having key-value pairs denoting configuration settings for the aggregator servlet
* @return The aggregator name
*/
protected String getAggregatorName(Map<String, String> configMap) {
// trim leading and trailing '/'
String alias = (String)configMap.get("alias"); //$NON-NLS-1$
while (alias.charAt(0) == '/')
alias = alias.substring(1);
while (alias.charAt(alias.length()-1) == '/')
alias = alias.substring(0, alias.length()-1);
return alias;
}
/**
* Instantiates a new dependencies object
* @param stamp
* the time stamp
* @return The new dependencies
*/
protected IDependencies newDependencies(long stamp) {
return new DependenciesImpl(this, stamp);
}
/**
* Instantiates a new config object
*
* @return The new config
* @throws IOException
*/
protected IConfig newConfig() throws IOException {
return new ConfigImpl(this);
}
/**
* Instantiates a new cache manager
* @param stamp
* the time stamp
* @return The new cache manager
* @throws IOException
*/
protected ICacheManager newCacheManager(long stamp) throws IOException {
return new CacheManagerImpl(this, stamp);
}
@Override
public abstract IOptions getOptions();
@Override
public abstract IExecutors getExecutors();
@Override
public IPlatformServices getPlatformServices() {
return platformServices;
}
/**
* This method does some initialization for the aggregator servlet. This method is called from platform
* dependent Aggregator implementation during its initialization.
*
* @throws Exception
*/
public void initialize()
throws Exception {
// create the config. Keep it local so it won't be seen by deps and cacheMgr
// until after we check for customization last-mods. Then we'll set the config
// in the instance data and call the config listeners.
IConfig config = newConfig();
// Check last-modified times of resources in the overrides folders. These resources
// are considered to be dynamic in a production environment and we want to
// detect new/changed resources in these folders on startup so that we can clear
// caches, etc.
OverrideFoldersTreeWalker walker = new OverrideFoldersTreeWalker(this, config);
walker.walkTree();
deps = newDependencies(walker.getLastModifiedJS());
cacheMgr = newCacheManager(walker.getLastModified());
resourcePaths = getPathsAndAliases(getInitParams());
this.config = config;
}
/**
* Returns a mapping of resource aliases to IResources defined in the init-params.
* If the IResource is null, then the alias is for the aggregator itself rather
* than a resource location.
*
* @param initParams
* The aggregator init-params
*
* @return Mapping of aliases to IResources
*/
protected Map<String, IResource> getPathsAndAliases(InitParams initParams) {
final String sourceMethod = "getPahtsAndAliases"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{initParams});
}
Map<String, IResource> resourcePaths = new HashMap<String, IResource>();
List<String> aliases = initParams.getValues(InitParams.ALIAS_INITPARAM);
for (String alias : aliases) {
addAlias(alias, null, "alias", resourcePaths); //$NON-NLS-1$
}
List<String> resourceIds = initParams.getValues(InitParams.RESOURCEID_INITPARAM);
for (String resourceId : resourceIds) {
aliases = initParams.getValues(resourceId + ":alias"); //$NON-NLS-1$
List<String> baseNames = initParams.getValues(resourceId + ":base-name"); //$NON-NLS-1$
if (aliases == null || aliases.size() != 1) {
throw new IllegalArgumentException(resourceId + ":aliases"); //$NON-NLS-1$
}
if (baseNames == null || baseNames.size() != 1) {
throw new IllegalArgumentException(resourceId + ":base-name"); //$NON-NLS-1$
}
String alias = aliases.get(0);
String baseName = baseNames.get(0);
// make sure not root path
boolean isPathComp = false;
for (String part : alias.split("/")) { //$NON-NLS-1$
if (part.length() > 0) {
isPathComp = true;
break;
}
}
if (!isPathComp) {
throw new IllegalArgumentException(resourceId + ":alias = " + alias); //$NON-NLS-1$
}
IResource res = newResource(URI.create(baseName));
if (res == null) {
throw new NullPointerException();
}
addAlias(alias, res, resourceId + ":alias", resourcePaths); //$NON-NLS-1$
}
if (isTraceLogging) {
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, resourcePaths);
}
return Collections.unmodifiableMap(resourcePaths);
}
protected void addAlias(String alias, IResource res, String initParamName, Map<String, IResource> map) {
final String sourceMethod = "addAlias"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{alias, res, initParamName, map});
}
String[] parts;
if (alias == null || (parts = alias.split("/")).length == 0) { //$NON-NLS-1$
throw new IllegalArgumentException(initParamName + " = " + alias); //$NON-NLS-1$
}
List<String> nonEmptyParts = new ArrayList<String>(parts.length);
for (String part : parts) {
if (part != null && part.length() > 0) {
nonEmptyParts.add(part);
}
}
alias = "/" + StringUtils.join(nonEmptyParts, "/"); //$NON-NLS-1$ //$NON-NLS-2$
// Make sure no overlapping alias paths
for (String test : map.keySet()) {
if (alias.equals(test)) {
throw new IllegalArgumentException("Duplicate alias path: " + alias); //$NON-NLS-1$
} else if (alias.startsWith(test + "/") || test.startsWith(alias + "/")) { //$NON-NLS-1$ //$NON-NLS-2$
throw new IllegalArgumentException("Overlapping alias paths: " + alias + ", " + test); //$NON-NLS-1$ //$NON-NLS-2$
}
}
map.put(alias, res);
log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
}
/**
* Implements the {@link IExtensionRegistrar} interface
*/
public class ExtensionRegistrar implements IExtensionRegistrar {
boolean open = true;
/* (non-Javadoc)
* @see com.ibm.jaggr.service.IExtensionInitializer.IExtensionRegistrar#registerExtension(java.lang.Object, java.util.Properties, InitParams, java.lang.String, java.lang.String)
*/
@Override
public void registerExtension(
Object impl,
Properties attributes,
InitParams initParams,
String extensionPointId,
String uniqueId,
IAggregatorExtension before) {
if (!open) {
throw new IllegalStateException("ExtensionRegistrar is closed"); //$NON-NLS-1$
}
IAggregatorExtension extension = new AggregatorExtension(
impl,
new Properties(attributes),
initParams,
extensionPointId,
uniqueId,
AbstractAggregatorImpl.this
);
AbstractAggregatorImpl.this.registerExtension(extension, before);
if (impl instanceof IExtensionInitializer) {
((IExtensionInitializer)impl).initialize(AbstractAggregatorImpl.this, extension, this);
}
}
public void closeRegistration() {
open = false;
}
}
/**
* Registers the layer listener
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void registerLayerListener() {
Dictionary dict = new Properties();
dict.put("name", getName()); //$NON-NLS-1$
registrations.add(getPlatformServices().registerService(
ILayerListener.class.getName(), new AggregatorLayerListener(this), dict));
}
}
|
Explicit initialization of MimetypesFileTypeMap using local
MTEA-INF/mime.types to avoid class loader issues on some platforms.
|
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/AbstractAggregatorImpl.java
|
Explicit initialization of MimetypesFileTypeMap using local MTEA-INF/mime.types to avoid class loader issues on some platforms.
|
|
Java
|
apache-2.0
|
823aaddb867f7a682206b20666598a157bed5db0
| 0
|
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.shardingproxy.runtime;
import com.google.common.base.Strings;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.core.constant.properties.ShardingProperties;
import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant;
import io.shardingsphere.core.constant.transaction.TransactionType;
import io.shardingsphere.core.event.ShardingEventBusInstance;
import io.shardingsphere.core.executor.ShardingExecuteEngine;
import io.shardingsphere.core.rule.Authentication;
import io.shardingsphere.core.rule.DataSourceParameter;
import io.shardingsphere.core.yaml.YamlRuleConfiguration;
import io.shardingsphere.core.yaml.other.YamlServerConfiguration;
import io.shardingsphere.orchestration.internal.event.config.ProxyConfigurationEventBusEvent;
import io.shardingsphere.orchestration.internal.event.state.CircuitStateEventBusEvent;
import io.shardingsphere.orchestration.internal.event.state.ProxyDisabledStateEventBusEvent;
import io.shardingsphere.shardingproxy.runtime.nio.BackendNIOConfiguration;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* Global registry.
*
* @author chenqingyang
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public final class GlobalRegistry {
private static final GlobalRegistry INSTANCE = new GlobalRegistry();
private List<String> schemaNames = new LinkedList<>();
private Map<String, ShardingSchema> shardingSchemas = new ConcurrentHashMap<>();
private Authentication authentication;
private boolean showSQL;
private int maxConnectionsSizePerQuery;
private int acceptorSize;
private int executorSize;
private TransactionType transactionType;
private boolean openTracingEnable;
private boolean useNIO;
private BackendNIOConfiguration backendNIOConfig;
private boolean isCircuitBreak;
/**
* Get instance of proxy context.
*
* @return instance of proxy context.
*/
public static GlobalRegistry getInstance() {
return INSTANCE;
}
/**
* Register listener.
*/
public void register() {
ShardingEventBusInstance.getInstance().register(this);
}
/**
* Initialize proxy context.
*
* @param serverConfig server configuration
* @param schemaDataSources data source map
* @param schemaRules schema rule map
*/
public void init(final YamlServerConfiguration serverConfig, final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final Map<String, YamlRuleConfiguration> schemaRules) {
init(serverConfig, schemaDataSources, schemaRules, false);
}
/**
* Initialize proxy context.
*
* @param serverConfig server configuration
* @param schemaDataSources data source map
* @param schemaRules schema rule map
* @param isUsingOrchestration is using orchestration or not
*/
public void init(final YamlServerConfiguration serverConfig, final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final Map<String, YamlRuleConfiguration> schemaRules, final boolean isUsingOrchestration) {
initServerConfiguration(serverConfig);
for (Entry<String, YamlRuleConfiguration> entry : schemaRules.entrySet()) {
String schemaName = entry.getKey();
schemaNames.add(schemaName);
shardingSchemas.put(schemaName, new ShardingSchema(schemaName, schemaDataSources.get(schemaName), entry.getValue(), isUsingOrchestration));
}
}
private void initServerConfiguration(final YamlServerConfiguration serverConfig) {
Properties properties = serverConfig.getProps();
ShardingProperties shardingProperties = new ShardingProperties(null == properties ? new Properties() : properties);
maxConnectionsSizePerQuery = shardingProperties.getValue(ShardingPropertiesConstant.MAX_CONNECTIONS_SIZE_PER_QUERY);
// TODO just config proxy.transaction.enable here, in future(3.1.0)
transactionType = shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_TRANSACTION_ENABLED) ? TransactionType.XA : TransactionType.LOCAL;
openTracingEnable = shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_OPENTRACING_ENABLED);
showSQL = shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW);
acceptorSize = shardingProperties.getValue(ShardingPropertiesConstant.ACCEPTOR_SIZE);
executorSize = shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE);
// TODO :jiaqi force off use NIO for backend, this feature is not complete yet
useNIO = false;
// boolean proxyBackendUseNio = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_USE_NIO);
int databaseConnectionCount = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_MAX_CONNECTIONS);
int connectionTimeoutSeconds = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_CONNECTION_TIMEOUT_SECONDS);
backendNIOConfig = new BackendNIOConfiguration(databaseConnectionCount, connectionTimeoutSeconds);
authentication = serverConfig.getAuthentication();
}
/**
* Initialize sharding meta data.
*
* @param executeEngine sharding execute engine
*/
public void initShardingMetaData(final ShardingExecuteEngine executeEngine) {
for (ShardingSchema each : shardingSchemas.values()) {
each.initShardingMetaData(executeEngine);
}
}
/**
* Check schema exists.
*
* @param schema schema
* @return schema exists or not
*/
public boolean schemaExists(final String schema) {
return schemaNames.contains(schema);
}
/**
* Get sharding schema.
*
* @param schemaName schema name
* @return sharding schema
*/
public ShardingSchema getShardingSchema(final String schemaName) {
return Strings.isNullOrEmpty(schemaName) ? null : shardingSchemas.get(schemaName);
}
/**
* Renew proxy configuration.
*
* @param proxyConfigurationEventBusEvent proxy event bus event.
*/
@Subscribe
public void renew(final ProxyConfigurationEventBusEvent proxyConfigurationEventBusEvent) {
initServerConfiguration(proxyConfigurationEventBusEvent.getServerConfiguration());
for (Entry<String, ShardingSchema> entry : shardingSchemas.entrySet()) {
entry.getValue().getBackendDataSource().close();
}
shardingSchemas.clear();
for (Entry<String, Map<String, DataSourceParameter>> entry : proxyConfigurationEventBusEvent.getSchemaDataSourceMap().entrySet()) {
String schemaName = entry.getKey();
shardingSchemas.put(schemaName, new ShardingSchema(schemaName, entry.getValue(), proxyConfigurationEventBusEvent.getSchemaRuleMap().get(schemaName), true));
}
}
/**
* Renew circuit breaker dataSource names.
*
* @param circuitStateEventBusEvent jdbc circuit event bus event
*/
@Subscribe
public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent circuitStateEventBusEvent) {
isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();
}
/**
* Renew disabled data source names.
*
* @param disabledStateEventBusEvent jdbc disabled event bus event
*/
@Subscribe
public void renewDisabledDataSourceNames(final ProxyDisabledStateEventBusEvent disabledStateEventBusEvent) {
for (Entry<String, ShardingSchema> entry : shardingSchemas.entrySet()) {
entry.getValue().getBackendDataSource().setAvailableDataSources(getDisabledDataSourceNames(disabledStateEventBusEvent.getDisabledSchemaDataSourceMap(), entry.getKey()));
}
}
private Collection<String> getDisabledDataSourceNames(final Map<String, Collection<String>> disabledSchemaDataSourceMap, final String shardingSchemaName) {
Collection<String> result = new LinkedList<>();
if (disabledSchemaDataSourceMap.containsKey(shardingSchemaName)) {
result.addAll(disabledSchemaDataSourceMap.get(shardingSchemaName));
}
return result;
}
}
|
sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java
|
/*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.shardingproxy.runtime;
import com.google.common.base.Strings;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.core.constant.properties.ShardingProperties;
import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant;
import io.shardingsphere.core.constant.transaction.TransactionType;
import io.shardingsphere.core.event.ShardingEventBusInstance;
import io.shardingsphere.core.executor.ShardingExecuteEngine;
import io.shardingsphere.core.rule.Authentication;
import io.shardingsphere.core.rule.DataSourceParameter;
import io.shardingsphere.core.yaml.YamlRuleConfiguration;
import io.shardingsphere.core.yaml.other.YamlServerConfiguration;
import io.shardingsphere.orchestration.internal.event.config.ProxyConfigurationEventBusEvent;
import io.shardingsphere.orchestration.internal.event.state.CircuitStateEventBusEvent;
import io.shardingsphere.orchestration.internal.event.state.ProxyDisabledStateEventBusEvent;
import io.shardingsphere.shardingproxy.runtime.nio.BackendNIOConfiguration;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* Global registry.
*
* @author chenqingyang
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public final class GlobalRegistry {
private static final GlobalRegistry INSTANCE = new GlobalRegistry();
private List<String> schemaNames = new LinkedList<>();
private Map<String, ShardingSchema> shardingSchemas = new ConcurrentHashMap<>();
private Authentication authentication;
private boolean showSQL;
private int maxConnectionsSizePerQuery;
private int acceptorSize;
private int executorSize;
private TransactionType transactionType;
private boolean openTracingEnable;
private boolean useNIO;
private BackendNIOConfiguration backendNIOConfig;
private boolean isCircuitBreak;
/**
* Get instance of proxy context.
*
* @return instance of proxy context.
*/
public static GlobalRegistry getInstance() {
return INSTANCE;
}
/**
* Register listener.
*/
public void register() {
ShardingEventBusInstance.getInstance().register(this);
}
/**
* Initialize proxy context.
*
* @param serverConfig server configuration
* @param schemaDataSources data source map
* @param schemaRules schema rule map
*/
public void init(final YamlServerConfiguration serverConfig, final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final Map<String, YamlRuleConfiguration> schemaRules) {
}
public void init(final YamlServerConfiguration serverConfig, final Map<String, Map<String, DataSourceParameter>> schemaDataSources, final Map<String, YamlRuleConfiguration> schemaRules, final boolean isUsingOrchestration) {
initServerConfiguration(serverConfig);
for (Entry<String, YamlRuleConfiguration> entry : schemaRules.entrySet()) {
String schemaName = entry.getKey();
schemaNames.add(schemaName);
shardingSchemas.put(schemaName, new ShardingSchema(schemaName, schemaDataSources.get(schemaName), entry.getValue(), isUsingOrchestration));
}
}
private void initServerConfiguration(final YamlServerConfiguration serverConfig) {
Properties properties = serverConfig.getProps();
ShardingProperties shardingProperties = new ShardingProperties(null == properties ? new Properties() : properties);
maxConnectionsSizePerQuery = shardingProperties.getValue(ShardingPropertiesConstant.MAX_CONNECTIONS_SIZE_PER_QUERY);
// TODO just config proxy.transaction.enable here, in future(3.1.0)
transactionType = shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_TRANSACTION_ENABLED) ? TransactionType.XA : TransactionType.LOCAL;
openTracingEnable = shardingProperties.<Boolean>getValue(ShardingPropertiesConstant.PROXY_OPENTRACING_ENABLED);
showSQL = shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW);
acceptorSize = shardingProperties.getValue(ShardingPropertiesConstant.ACCEPTOR_SIZE);
executorSize = shardingProperties.getValue(ShardingPropertiesConstant.EXECUTOR_SIZE);
// TODO :jiaqi force off use NIO for backend, this feature is not complete yet
useNIO = false;
// boolean proxyBackendUseNio = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_USE_NIO);
int databaseConnectionCount = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_MAX_CONNECTIONS);
int connectionTimeoutSeconds = shardingProperties.getValue(ShardingPropertiesConstant.PROXY_BACKEND_CONNECTION_TIMEOUT_SECONDS);
backendNIOConfig = new BackendNIOConfiguration(databaseConnectionCount, connectionTimeoutSeconds);
authentication = serverConfig.getAuthentication();
}
/**
* Initialize sharding meta data.
*
* @param executeEngine sharding execute engine
*/
public void initShardingMetaData(final ShardingExecuteEngine executeEngine) {
for (ShardingSchema each : shardingSchemas.values()) {
each.initShardingMetaData(executeEngine);
}
}
/**
* Check schema exists.
*
* @param schema schema
* @return schema exists or not
*/
public boolean schemaExists(final String schema) {
return schemaNames.contains(schema);
}
/**
* Get sharding schema.
*
* @param schemaName schema name
* @return sharding schema
*/
public ShardingSchema getShardingSchema(final String schemaName) {
return Strings.isNullOrEmpty(schemaName) ? null : shardingSchemas.get(schemaName);
}
/**
* Renew proxy configuration.
*
* @param proxyConfigurationEventBusEvent proxy event bus event.
*/
@Subscribe
public void renew(final ProxyConfigurationEventBusEvent proxyConfigurationEventBusEvent) {
initServerConfiguration(proxyConfigurationEventBusEvent.getServerConfiguration());
for (Entry<String, ShardingSchema> entry : shardingSchemas.entrySet()) {
entry.getValue().getBackendDataSource().close();
}
shardingSchemas.clear();
for (Entry<String, Map<String, DataSourceParameter>> entry : proxyConfigurationEventBusEvent.getSchemaDataSourceMap().entrySet()) {
String schemaName = entry.getKey();
shardingSchemas.put(schemaName, new ShardingSchema(schemaName, entry.getValue(), proxyConfigurationEventBusEvent.getSchemaRuleMap().get(schemaName)));
}
}
/**
* Renew circuit breaker dataSource names.
*
* @param circuitStateEventBusEvent jdbc circuit event bus event
*/
@Subscribe
public void renewCircuitBreakerDataSourceNames(final CircuitStateEventBusEvent circuitStateEventBusEvent) {
isCircuitBreak = circuitStateEventBusEvent.isCircuitBreak();
}
/**
* Renew disabled data source names.
*
* @param disabledStateEventBusEvent jdbc disabled event bus event
*/
@Subscribe
public void renewDisabledDataSourceNames(final ProxyDisabledStateEventBusEvent disabledStateEventBusEvent) {
for (Entry<String, ShardingSchema> entry : shardingSchemas.entrySet()) {
entry.getValue().getBackendDataSource().setAvailableDataSources(getDisabledDataSourceNames(disabledStateEventBusEvent.getDisabledSchemaDataSourceMap(), entry.getKey()));
}
}
private Collection<String> getDisabledDataSourceNames(final Map<String, Collection<String>> disabledSchemaDataSourceMap, final String shardingSchemaName) {
Collection<String> result = new LinkedList<>();
if (disabledSchemaDataSourceMap.containsKey(shardingSchemaName)) {
result.addAll(disabledSchemaDataSourceMap.get(shardingSchemaName));
}
return result;
}
}
|
modify renew()
|
sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java
|
modify renew()
|
|
Java
|
apache-2.0
|
2895dfa13e09a06cfcadce8eae48bb2bf1c72be4
| 0
|
Hocdoc/lettuce,mp911de/lettuce,pulse00/lettuce,lettuce-io/lettuce-core,pulse00/lettuce,taer/lettuce,taer/lettuce,lettuce-io/lettuce-core,lettuce-io/lettuce-core,Hocdoc/lettuce,mp911de/lettuce,lettuce-io/lettuce-core
|
package com.lambdaworks.redis.cluster;
import static com.lambdaworks.redis.cluster.ClusterTestUtil.*;
import static org.assertj.core.api.Assertions.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.*;
import com.google.code.tempusfugit.temporal.Condition;
import com.google.code.tempusfugit.temporal.Duration;
import com.google.code.tempusfugit.temporal.Timeout;
import com.google.code.tempusfugit.temporal.WaitFor;
import com.google.common.collect.ImmutableList;
import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.RedisClusterConnection;
import com.lambdaworks.redis.cluster.models.partitions.ClusterPartitionParser;
import com.lambdaworks.redis.cluster.models.partitions.Partitions;
import com.lambdaworks.redis.cluster.models.partitions.RedisClusterNode;
/**
* @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a>
* @since 3.0
*/
public class RedisClusterSetupTest {
public static final String host = "127.0.0.1";
public static final int port1 = 7383;
public static final int port2 = 7384;
private static RedisClient client1;
private static RedisClient client2;
private RedisClusterConnection<String, String> redis1;
private RedisClusterConnection<String, String> redis2;
@BeforeClass
public static void setupClient() {
client1 = new RedisClient(host, port1);
client2 = new RedisClient(host, port2);
}
@AfterClass
public static void shutdownClient() {
client1.shutdown(0, 0, TimeUnit.MILLISECONDS);
client2.shutdown(0, 0, TimeUnit.MILLISECONDS);
}
@Before
public void openConnection() throws Exception {
redis1 = (RedisClusterConnection) client1.connect();
redis1.flushall();
redis1.flushdb();
redis2 = (RedisClusterConnection) client2.connect();
redis2.flushall();
redis2.flushdb();
redis1.clusterReset(false);
redis2.clusterReset(false);
redis1.clusterReset(true);
redis2.clusterReset(true);
redis1.clusterFlushslots();
redis2.clusterFlushslots();
Thread.sleep(100);
}
@After
public void closeConnection() throws Exception {
redis1.close();
redis2.close();
}
@Test
public void clusterMeet() throws Exception {
Partitions partitionsBeforeMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
assertThat(partitionsBeforeMeet.getPartitions()).hasSize(1);
String result = redis1.clusterMeet(host, port2);
assertThat(result).isEqualTo("OK");
waitForCluster();
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
assertThat(partitionsAfterMeet.getPartitions()).hasSize(2);
}
@Test
public void clusterForget() throws Exception {
String result = redis1.clusterMeet(host, port2);
assertThat(result).isEqualTo("OK");
waitForCluster();
Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes());
for (RedisClusterNode redisClusterNode : partitions.getPartitions()) {
if (!redisClusterNode.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
redis1.clusterForget(redisClusterNode.getNodeId());
}
}
Thread.sleep(300);
Partitions partitionsAfterForget = ClusterPartitionParser.parse(redis1.clusterNodes());
assertThat(partitionsAfterForget.getPartitions()).hasSize(1);
}
private void waitForCluster() throws InterruptedException, TimeoutException {
WaitFor.waitOrTimeout(new Condition() {
@Override
public boolean isSatisfied() {
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
return partitionsAfterMeet.getPartitions().size() == 2;
}
}, Timeout.timeout(Duration.seconds(5)));
}
@Test
public void clusterAddDelSlots() throws Exception {
redis1.clusterMeet(host, port2);
waitForCluster();
for (int i = 1; i < 7; i++) {
redis1.clusterAddSlots(i);
}
for (int i = 7; i < 13; i++) {
redis2.clusterAddSlots(i);
}
waitForSlots();
Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes());
for (RedisClusterNode redisClusterNode : partitions.getPartitions()) {
if (redisClusterNode.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(1, 2, 3, 4, 5, 6));
} else {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(7, 8, 9, 10, 11, 12));
}
}
redis1.clusterDelSlots(1, 2, 3, 4, 5, 6);
redis2.clusterDelSlots(7, 8, 9, 10, 11, 12);
try {
WaitFor.waitOrTimeout(new Condition() {
@Override
public boolean isSatisfied() {
Partitions partitions = ClusterPartitionParser.parse(redis2.clusterNodes());
return partitions.getPartitions().size() == 2 && partitions.getPartitions().get(0).getSlots().isEmpty();
}
}, Timeout.timeout(Duration.seconds(5)));
} catch (Exception e) {
Partitions detail = ClusterPartitionParser.parse(redis2.clusterNodes());
String slotsOn1 = "";
if (detail.getPartitions().size() > 0) {
slotsOn1 = detail.getPartitions().get(0).getSlots().toString();
}
fail("Slots/Partitions not deleted. Partitions: " + detail.getPartitions().size() + ", Slots on (0):" + slotsOn1, e);
}
}
@Test
public void clusterSetSlots() throws Exception {
redis1.clusterMeet(host, port2);
waitForCluster();
for (int i = 1; i < 7; i++) {
redis1.clusterAddSlots(i);
}
for (int i = 7; i < 13; i++) {
redis2.clusterAddSlots(i);
}
waitForSlots();
redis1.clusterSetSlotNode(6, getNodeId(redis2));
waitForSlots();
Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes());
for (RedisClusterNode redisClusterNode : partitions.getPartitions()) {
if (redisClusterNode.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(1, 2, 3, 4, 5));
} else {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(6, 7, 8, 9, 10, 11, 12));
}
}
}
private void waitForSlots() throws InterruptedException, TimeoutException {
WaitFor.waitOrTimeout(new Condition() {
@Override
public boolean isSatisfied() {
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
return partitionsAfterMeet.getPartitions().size() == 2
&& !partitionsAfterMeet.getPartitions().get(0).getSlots().isEmpty()
&& !partitionsAfterMeet.getPartitions().get(1).getSlots().isEmpty();
}
}, Timeout.timeout(Duration.seconds(5)));
}
@Test
public void clusterSlotMigrationImport() throws Exception {
redis1.clusterMeet(host, port2);
waitForCluster();
for (int i = 1; i < 7; i++) {
redis1.clusterAddSlots(i);
}
for (int i = 7; i < 13; i++) {
redis2.clusterAddSlots(i);
}
waitForSlots();
String nodeId1 = getNodeId(redis1);
String nodeId2 = getNodeId(redis2);
assertThat(redis1.clusterSetSlotMigrating(6, nodeId2)).isEqualTo("OK");
assertThat(redis1.clusterSetSlotImporting(12, nodeId2)).isEqualTo("OK");
RedisClusterNode partition1 = getOwnPartition(redis1);
RedisClusterNode partition2 = getOwnPartition(redis2);
assertThat(partition1.getSlots()).hasSize(6);
assertThat(partition2.getSlots()).hasSize(6);
}
}
|
src/test/java/com/lambdaworks/redis/cluster/RedisClusterSetupTest.java
|
package com.lambdaworks.redis.cluster;
import static com.lambdaworks.redis.cluster.ClusterTestUtil.*;
import static org.assertj.core.api.Assertions.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.*;
import com.google.code.tempusfugit.temporal.Condition;
import com.google.code.tempusfugit.temporal.Duration;
import com.google.code.tempusfugit.temporal.Timeout;
import com.google.code.tempusfugit.temporal.WaitFor;
import com.google.common.collect.ImmutableList;
import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.RedisClusterConnection;
import com.lambdaworks.redis.cluster.models.partitions.ClusterPartitionParser;
import com.lambdaworks.redis.cluster.models.partitions.Partitions;
import com.lambdaworks.redis.cluster.models.partitions.RedisClusterNode;
/**
* @author <a href="mailto:mpaluch@paluch.biz">Mark Paluch</a>
* @since 3.0
*/
public class RedisClusterSetupTest {
public static final String host = "127.0.0.1";
public static final int port1 = 7383;
public static final int port2 = 7384;
private static RedisClient client1;
private static RedisClient client2;
private RedisClusterConnection<String, String> redis1;
private RedisClusterConnection<String, String> redis2;
@BeforeClass
public static void setupClient() {
client1 = new RedisClient(host, port1);
client2 = new RedisClient(host, port2);
}
@AfterClass
public static void shutdownClient() {
client1.shutdown(0, 0, TimeUnit.MILLISECONDS);
client2.shutdown(0, 0, TimeUnit.MILLISECONDS);
}
@Before
public void openConnection() throws Exception {
redis1 = (RedisClusterConnection) client1.connect();
redis1.flushall();
redis1.flushdb();
redis2 = (RedisClusterConnection) client2.connect();
redis2.flushall();
redis2.flushdb();
redis1.clusterReset(false);
redis2.clusterReset(false);
redis1.clusterReset(true);
redis2.clusterReset(true);
redis1.clusterFlushslots();
redis2.clusterFlushslots();
Thread.sleep(100);
}
@After
public void closeConnection() throws Exception {
redis1.close();
redis2.close();
}
@Test
public void clusterMeet() throws Exception {
Partitions partitionsBeforeMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
assertThat(partitionsBeforeMeet.getPartitions()).hasSize(1);
String result = redis1.clusterMeet(host, port2);
assertThat(result).isEqualTo("OK");
waitForCluster();
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
assertThat(partitionsAfterMeet.getPartitions()).hasSize(2);
}
@Test
public void clusterForget() throws Exception {
String result = redis1.clusterMeet(host, port2);
assertThat(result).isEqualTo("OK");
waitForCluster();
Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes());
for (RedisClusterNode redisClusterNode : partitions.getPartitions()) {
if (!redisClusterNode.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
redis1.clusterForget(redisClusterNode.getNodeId());
}
}
Thread.sleep(300);
Partitions partitionsAfterForget = ClusterPartitionParser.parse(redis1.clusterNodes());
assertThat(partitionsAfterForget.getPartitions()).hasSize(1);
}
private void waitForCluster() throws InterruptedException, TimeoutException {
WaitFor.waitOrTimeout(new Condition() {
@Override
public boolean isSatisfied() {
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
return partitionsAfterMeet.getPartitions().size() == 2;
}
}, Timeout.timeout(Duration.seconds(5)));
}
@Test
public void clusterAddDelSlots() throws Exception {
redis1.clusterMeet(host, port2);
waitForCluster();
for (int i = 1; i < 7; i++) {
redis1.clusterAddSlots(i);
}
for (int i = 7; i < 13; i++) {
redis2.clusterAddSlots(i);
}
waitForSlots();
Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes());
for (RedisClusterNode redisClusterNode : partitions.getPartitions()) {
if (redisClusterNode.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(1, 2, 3, 4, 5, 6));
} else {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(7, 8, 9, 10, 11, 12));
}
}
redis1.clusterDelSlots(1, 2, 3, 4, 5, 6);
redis2.clusterDelSlots(7, 8, 9, 10, 11, 12);
WaitFor.waitOrTimeout(new Condition() {
@Override
public boolean isSatisfied() {
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis2.clusterNodes());
return partitionsAfterMeet.getPartitions().size() == 2
&& partitionsAfterMeet.getPartitions().get(0).getSlots().isEmpty();
}
}, Timeout.timeout(Duration.seconds(5)));
}
@Test
public void clusterSetSlots() throws Exception {
redis1.clusterMeet(host, port2);
waitForCluster();
for (int i = 1; i < 7; i++) {
redis1.clusterAddSlots(i);
}
for (int i = 7; i < 13; i++) {
redis2.clusterAddSlots(i);
}
waitForSlots();
redis1.clusterSetSlotNode(6, getNodeId(redis2));
waitForSlots();
Partitions partitions = ClusterPartitionParser.parse(redis1.clusterNodes());
for (RedisClusterNode redisClusterNode : partitions.getPartitions()) {
if (redisClusterNode.getFlags().contains(RedisClusterNode.NodeFlag.MYSELF)) {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(1, 2, 3, 4, 5));
} else {
assertThat(redisClusterNode.getSlots()).isEqualTo(ImmutableList.of(6, 7, 8, 9, 10, 11, 12));
}
}
}
private void waitForSlots() throws InterruptedException, TimeoutException {
WaitFor.waitOrTimeout(new Condition() {
@Override
public boolean isSatisfied() {
Partitions partitionsAfterMeet = ClusterPartitionParser.parse(redis1.clusterNodes());
return partitionsAfterMeet.getPartitions().size() == 2
&& !partitionsAfterMeet.getPartitions().get(0).getSlots().isEmpty()
&& !partitionsAfterMeet.getPartitions().get(1).getSlots().isEmpty();
}
}, Timeout.timeout(Duration.seconds(5)));
}
@Test
public void clusterSlotMigrationImport() throws Exception {
redis1.clusterMeet(host, port2);
waitForCluster();
for (int i = 1; i < 7; i++) {
redis1.clusterAddSlots(i);
}
for (int i = 7; i < 13; i++) {
redis2.clusterAddSlots(i);
}
waitForSlots();
String nodeId1 = getNodeId(redis1);
String nodeId2 = getNodeId(redis2);
assertThat(redis1.clusterSetSlotMigrating(6, nodeId2)).isEqualTo("OK");
assertThat(redis1.clusterSetSlotImporting(12, nodeId2)).isEqualTo("OK");
RedisClusterNode partition1 = getOwnPartition(redis1);
RedisClusterNode partition2 = getOwnPartition(redis2);
assertThat(partition1.getSlots()).hasSize(6);
assertThat(partition2.getSlots()).hasSize(6);
}
}
|
Add more detail on cluster slots test
|
src/test/java/com/lambdaworks/redis/cluster/RedisClusterSetupTest.java
|
Add more detail on cluster slots test
|
|
Java
|
apache-2.0
|
1eae7997fda20b2b6b0df71759a824eb02beec01
| 0
|
strongbox/strongbox,strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox,sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox
|
package org.carlspring.strongbox.controllers.layout.npm;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.carlspring.strongbox.artifact.ArtifactTag;
import org.carlspring.strongbox.artifact.coordinates.NpmArtifactCoordinates;
import org.carlspring.strongbox.config.NpmLayoutProviderConfig.NpmObjectMapper;
import org.carlspring.strongbox.controllers.BaseArtifactController;
import org.carlspring.strongbox.data.criteria.Expression.ExpOperator;
import org.carlspring.strongbox.data.criteria.Paginator;
import org.carlspring.strongbox.data.criteria.Predicate;
import org.carlspring.strongbox.npm.NpmSearchRequest;
import org.carlspring.strongbox.npm.NpmViewRequest;
import org.carlspring.strongbox.npm.metadata.DistTags;
import org.carlspring.strongbox.npm.metadata.PackageFeed;
import org.carlspring.strongbox.npm.metadata.PackageVersion;
import org.carlspring.strongbox.npm.metadata.SearchResults;
import org.carlspring.strongbox.npm.metadata.Time;
import org.carlspring.strongbox.npm.metadata.Versions;
import org.carlspring.strongbox.providers.ProviderImplementationException;
import org.carlspring.strongbox.providers.io.RepositoryPath;
import org.carlspring.strongbox.providers.layout.NpmPackageDesc;
import org.carlspring.strongbox.providers.layout.NpmPackageSupplier;
import org.carlspring.strongbox.providers.layout.NpmSearchResultSupplier;
import org.carlspring.strongbox.providers.repository.RepositoryProvider;
import org.carlspring.strongbox.providers.repository.RepositoryProviderRegistry;
import org.carlspring.strongbox.repository.NpmRepositoryFeatures.SearchPackagesEventListener;
import org.carlspring.strongbox.repository.NpmRepositoryFeatures.ViewPackageEventListener;
import org.carlspring.strongbox.storage.repository.Repository;
import org.carlspring.strongbox.storage.validation.artifact.ArtifactCoordinatesValidationException;
import org.carlspring.strongbox.users.userdetails.SpringSecurityUser;
import org.carlspring.strongbox.web.LayoutRequestMapping;
import org.carlspring.strongbox.web.RepositoryMapping;
import org.javatuples.Pair;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* This Controller used to handle npm requests.
*
* @author Sergey Bespalov
*/
@RestController
@LayoutRequestMapping(NpmArtifactCoordinates.LAYOUT_NAME)
public class NpmArtifactController
extends BaseArtifactController
{
private static final String FIELD_NAME_LENGTH = "length";
private static final String FIELD_NAME_ATTACHMENTS = "_attachments";
private static final String FIELD_NAME_VERSION = "versions";
@Inject
@NpmObjectMapper
private ObjectMapper npmJacksonMapper;
@Inject
private RepositoryProviderRegistry repositoryProviderRegistry;
@Inject
private NpmPackageSupplier npmPackageSupplier;
@Inject
private NpmSearchResultSupplier npmSearchResultSupplier;
@Inject
private ViewPackageEventListener viewPackageEventListener;
@Inject
private SearchPackagesEventListener searcPackagesEventListener;
@GetMapping(path = { "{storageId}/{repositoryId}/npm" })
public ResponseEntity<String> greet()
{
// TODO: find out what NPM expect to receive here
return ResponseEntity.ok("");
}
@GetMapping(path = "{storageId}/{repositoryId}/-/v1/search")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void search(@RepositoryMapping Repository repository,
@RequestParam(name = "text") String text,
@RequestParam(name = "size", defaultValue = "20") Integer size,
HttpServletResponse response)
throws IOException
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
NpmSearchRequest npmSearchRequest = new NpmSearchRequest();
npmSearchRequest.setText(text);
npmSearchRequest.setSize(size);
searcPackagesEventListener.setNpmSearchRequest(npmSearchRequest);
RepositoryProvider provider = repositoryProviderRegistry.getProvider(repository.getType());
Predicate predicate = Predicate.empty();
predicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.extension", "tgz")));
predicate.and(Predicate.of(ExpOperator.CONTAINS.of("tagSet.name", ArtifactTag.LAST_VERSION)));
Predicate lkePredicate = Predicate.empty().nested();
lkePredicate.or(
Predicate.of(ExpOperator.LIKE.of("artifactCoordinates.coordinates.name.toLowerCase()", text + "%")));
lkePredicate.or(
Predicate.of(ExpOperator.LIKE.of("artifactCoordinates.coordinates.scope.toLowerCase()", text + "%")));
predicate.or(lkePredicate);
Paginator paginator = new Paginator();
paginator.setLimit(20);
List<Path> searchResult = provider.search(storageId, repositoryId, predicate, paginator);
SearchResults searchResults = new SearchResults();
searchResult.stream().map(npmSearchResultSupplier).forEach(p -> {
searchResults.getObjects().add(p);
});
Long count = provider.count(storageId, repositoryId, predicate);
searchResults.setTotal(count.intValue());
//Wed Oct 31 2018 05:01:19 GMT+0000 (UTC)
SimpleDateFormat format = new SimpleDateFormat(NpmSearchResultSupplier.SEARCH_DATE_FORMAT);
searchResults.setTime(format.format(new Date()));
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(npmJacksonMapper.writeValueAsBytes(searchResults));
}
@GetMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName:[^-].+}/{packageVersion}")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void viewPackageWithScope(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "packageVersion") String packageVersion,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
String packageId = NpmArtifactCoordinates.calculatePackageId(packageScope, packageName);
NpmArtifactCoordinates c = NpmArtifactCoordinates.of(packageId, packageVersion);
NpmViewRequest npmSearchRequest = new NpmViewRequest();
npmSearchRequest.setPackageId(packageId);
npmSearchRequest.setVersion(packageVersion);
viewPackageEventListener.setNpmSearchRequest(npmSearchRequest);
RepositoryPath repositoryPath = artifactResolutionService.resolvePath(storageId, repositoryId, c.toPath());
if (repositoryPath == null)
{
response.setStatus(HttpStatus.NOT_FOUND.value());
return;
}
NpmPackageDesc packageDesc = npmPackageSupplier.apply(repositoryPath);
PackageVersion npmPackage = packageDesc.getNpmPackage();
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(npmJacksonMapper.writeValueAsBytes(npmPackage));
}
@GetMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void viewPackageFeedWithScope(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
String packageId = NpmArtifactCoordinates.calculatePackageId(packageScope, packageName);
NpmViewRequest npmSearchRequest = new NpmViewRequest();
npmSearchRequest.setPackageId(packageId);
viewPackageEventListener.setNpmSearchRequest(npmSearchRequest);
PackageFeed packageFeed = new PackageFeed();
packageFeed.setName(packageId);
packageFeed.setAdditionalProperty("_id", packageId);
packageFeed.setAdditionalProperty("_rev", generateRevisionHashcode());
Predicate predicate = createSearchPredicate(packageScope, packageName);
RepositoryProvider provider = repositoryProviderRegistry.getProvider(repository.getType());
Paginator paginator = new Paginator();
paginator.setProperty("version");
List<Path> searchResult = provider.search(storageId, repositoryId, predicate, paginator);
Versions versions = new Versions();
packageFeed.setVersions(versions);
Time npmTime = new Time();
packageFeed.setTime(npmTime);
DistTags distTags = new DistTags();
packageFeed.setDistTags(distTags);
searchResult.stream().map(npmPackageSupplier).forEach(p -> {
PackageVersion npmPackage = p.getNpmPackage();
versions.setAdditionalProperty(npmPackage.getVersion(), npmPackage);
npmTime.setAdditionalProperty(npmPackage.getVersion(), p.getReleaseDate());
Date created = npmTime.getCreated();
npmTime.setCreated(created == null || created.before(p.getReleaseDate()) ? p.getReleaseDate() : created);
Date modified = npmTime.getModified();
npmTime.setModified(modified == null || modified.before(p.getReleaseDate()) ? p.getReleaseDate()
: modified);
if (p.isLastVersion())
{
distTags.setLatest(npmPackage.getVersion());
}
});
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(npmJacksonMapper.writeValueAsBytes(packageFeed));
}
private String generateRevisionHashcode()
{
return "36-b8d6f834569d63";
}
@GetMapping(path = "{storageId}/{repositoryId}/{packageName}")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void viewPackageFeed(@RepositoryMapping Repository repository,
@PathVariable(name = "packageName") String packageName,
HttpServletResponse response)
throws Exception
{
viewPackageFeedWithScope(repository, null, packageName, response);
}
private Predicate createSearchPredicate(String packageScope,
String packageName)
{
Predicate rootPredicate = Predicate.empty();
rootPredicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.extension", "tgz")));
rootPredicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.name", packageName)));
if (packageScope != null)
{
rootPredicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.scope", packageScope)));
}
return rootPredicate;
}
@PreAuthorize("hasAuthority('ARTIFACTS_RESOLVE')")
@RequestMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}/-/{packageNameWithVersion}.{packageExtension}",
method = { RequestMethod.GET,
RequestMethod.HEAD })
public void downloadPackageWithScope(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "packageNameWithVersion") String packageNameWithVersion,
@PathVariable(name = "packageExtension") String packageExtension,
@RequestHeader HttpHeaders httpHeaders,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
if (!packageNameWithVersion.startsWith(packageName + "-"))
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//Example of packageNameWithVersion core-9.0.1-next.8.tgz
final String packageVersion = getPackageVersion(packageNameWithVersion, packageName);
NpmArtifactCoordinates coordinates;
try
{
coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), packageVersion);
}
catch (IllegalArgumentException e)
{
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(e.getMessage());
return;
}
RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath());
provideArtifactDownloadResponse(request, response, httpHeaders, path);
}
@PreAuthorize("hasAuthority('ARTIFACTS_RESOLVE')")
@RequestMapping(path = "{storageId}/{repositoryId}/{packageName}/-/{packageNameWithVersion}.{packageExtension}",
method = { RequestMethod.GET,
RequestMethod.HEAD })
public void downloadPackage(@RepositoryMapping Repository repository,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "packageNameWithVersion") String packageNameWithVersion,
@PathVariable(name = "packageExtension") String packageExtension,
@RequestHeader HttpHeaders httpHeaders,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
if (!packageNameWithVersion.startsWith(packageName + "-"))
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//Example of packageNameWithVersion core-9.0.1-next.8.tgz
final String packageVersion = getPackageVersion(packageNameWithVersion, packageName);
NpmArtifactCoordinates coordinates;
try
{
coordinates = NpmArtifactCoordinates.of(packageName, packageVersion);
}
catch (IllegalArgumentException e)
{
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(e.getMessage());
return;
}
RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath());
provideArtifactDownloadResponse(request, response, httpHeaders, path);
}
@PreAuthorize("hasAuthority('ARTIFACTS_DEPLOY')")
@PutMapping(path = "{storageId}/{repositoryId}/{name:.+}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity publish(@RepositoryMapping Repository repository,
@PathVariable(name = "name") String name,
HttpServletRequest request)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
if (name.contains("/-rev/"))
{
logger.warn(
"Client executed npm unpublish a package with a specified version, PUT stage should be skipped!");
return ResponseEntity.status(HttpStatus.OK)
.body("");
}
logger.info("npm publish request for {}/{}/{}", storageId, repositoryId, name);
Pair<PackageVersion, Path> packageEntry;
try
{
packageEntry = extractPackage(name, request.getInputStream());
}
catch (IllegalArgumentException e)
{
logger.error("Failed to extract npm package data", e);
return ResponseEntity.badRequest().build();
}
PackageVersion packageJson = packageEntry.getValue0();
Path packageTgz = packageEntry.getValue1();
NpmArtifactCoordinates coordinates = NpmArtifactCoordinates.of(name, packageJson.getVersion());
storeNpmPackage(repository, coordinates, packageJson, packageTgz);
return ResponseEntity.ok("");
}
@PreAuthorize("hasAuthority('UI_LOGIN')")
@PutMapping(path = "{storageId}/{repositoryId}/-/user/org.couchdb.user:{username}",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity addUser(Authentication authentication)
{
if (authentication == null || !authentication.isAuthenticated())
{
throw new InsufficientAuthenticationException("unauthorized");
}
if (!(authentication instanceof UsernamePasswordAuthenticationToken))
{
return toResponseEntityError("Unsupported authentication class " + authentication.getClass().getName());
}
Object principal = authentication.getPrincipal();
if (!(principal instanceof SpringSecurityUser))
{
return toResponseEntityError(
"Unsupported authentication principal " + Optional.ofNullable(principal).orElse(null));
}
return ResponseEntity
.status(HttpStatus.CREATED)
.body("{\"ok\":\"user '" + authentication.getName() + "' created\"}");
}
@DeleteMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}/-rev/{rev}")
@PreAuthorize("hasAuthority('ARTIFACTS_DELETE')")
public ResponseEntity unpublishPackage(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "rev") String rev)
{
if (!repository.allowsUnpublish())
{
logger.warn(String.format("User tried to 'unpublish' a package [%s], but the feature is disabled",
packageName));
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Enable 'unpublish' at first");
}
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
Path packagePath = Paths.get(packageScope, packageName);
RepositoryPath path;
try
{
path = artifactResolutionService.resolvePath(storageId, repositoryId,
packagePath.toString());
}
catch (IOException e)
{
logger.error("Failed to resolve path: storageId:-[{}], repositoryId-[{}], packagePath-[{}]", storageId,
repositoryId, packagePath.toString());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
try
{
artifactManagementService.delete(path, false);
//deleteVersionDirectory(path);
}
catch (IOException e)
{
logger.error("Failed to process Npm unpublsh a package request: path-[{}]", path, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
logger.info("Npm unpublish succeeded: path-[{}]", path);
return ResponseEntity.status(HttpStatus.OK).build();
}
@DeleteMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}/-/{tarball}/-rev/{rev}")
@PreAuthorize("hasAuthority('ARTIFACTS_DELETE')")
public ResponseEntity unpublish(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "tarball") String tarball,
@PathVariable(name = "rev") String rev)
throws Exception
{
if (!repository.allowsUnpublish())
{
logger.warn(String.format("User tried to 'unpublish' a package [%s], but the feature is disabled",
packageName));
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Enable 'unpublish' at first");
}
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
final String version = getPackageVersion(tarball, packageName)
.replace(".tgz", "");
logger.info(
"Npm unpublish a single version request: storageId-[{}]; repositoryId-[{}]; packageName-[{}]; tarball-[{}]; revision-[{}];",
storageId, repositoryId, packageName, tarball, rev);
NpmArtifactCoordinates coordinates;
try
{
coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), version);
}
catch (IllegalArgumentException e)
{
logger.error("Illegal arg passed", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath());
try
{
artifactManagementService.delete(path, false);
deleteVersionDirectory(path);
}
catch (IOException e)
{
logger.error("Failed to process Npm unpublsh a single version request: path-[{}]", path, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
logger.info("Npm unpublish succeeded: path-[{}]", path);
return ResponseEntity.status(HttpStatus.OK).build();
}
private void storeNpmPackage(Repository repository,
NpmArtifactCoordinates coordinates,
PackageVersion packageDef,
Path packageTgzTmp)
throws IOException,
ProviderImplementationException,
NoSuchAlgorithmException,
ArtifactCoordinatesValidationException
{
RepositoryPath repositoryPath = repositoryPathResolver.resolve(repository, coordinates);
try (InputStream is = new BufferedInputStream(Files.newInputStream(packageTgzTmp)))
{
artifactManagementService.validateAndStore(repositoryPath, is);
}
Path packageJsonTmp = extractPackageJson(packageTgzTmp);
RepositoryPath packageJsonPath = repositoryPathResolver.resolve(repository,
repositoryPath.resolveSibling("package.json"));
try (InputStream is = new BufferedInputStream(Files.newInputStream(packageJsonTmp)))
{
artifactManagementService.validateAndStore(packageJsonPath, is);
}
String shasum = Optional.ofNullable(packageDef.getDist()).map(p -> p.getShasum()).orElse(null);
if (shasum == null)
{
logger.warn("No checksum provided for package [{}]", packageDef.getName());
return;
}
String packageFileName = repositoryPath.getFileName().toString();
RepositoryPath checksumPath = repositoryPath.resolveSibling(packageFileName + ".sha1");
artifactManagementService.validateAndStore(checksumPath,
new ByteArrayInputStream(shasum.getBytes(StandardCharsets.UTF_8)));
Files.delete(packageTgzTmp);
Files.delete(packageJsonTmp);
}
private Pair<PackageVersion, Path> extractPackage(String packageName,
ServletInputStream in)
throws IOException
{
Path packageSourceTmp = Files.createTempFile("package", "source");
Files.copy(in, packageSourceTmp, StandardCopyOption.REPLACE_EXISTING);
PackageVersion packageVersion = null;
Path packageTgzPath = null;
JsonFactory jfactory = new JsonFactory();
try (InputStream tmpIn = new BufferedInputStream(Files.newInputStream(packageSourceTmp));
JsonParser jp = jfactory.createParser(tmpIn);)
{
jp.setCodec(npmJacksonMapper);
Assert.isTrue(jp.nextToken() == JsonToken.START_OBJECT, "npm package source should be JSON object.");
while (jp.nextToken() != null)
{
String fieldName = jp.getCurrentName();
// read value
if (fieldName == null)
{
continue;
}
switch (fieldName)
{
case FIELD_NAME_VERSION:
jp.nextValue();
JsonNode node = jp.readValueAsTree();
Assert.isTrue(node.size() == 1, "npm package source should contain only one version.");
JsonNode packageJsonNode = node.iterator().next();
packageVersion = extractPackageVersion(packageName, packageJsonNode.toString());
break;
case FIELD_NAME_ATTACHMENTS:
Assert.isTrue(jp.nextToken() == JsonToken.START_OBJECT,
String.format(
"Failed to parse npm package source for illegal type [%s] of attachment.",
jp.currentToken().name()));
String packageAttachmentName = jp.nextFieldName();
logger.info(String.format("Found npm package attachment [%s]", packageAttachmentName));
moveToAttachment(jp, packageAttachmentName);
packageTgzPath = extractPackage(jp);
jp.nextToken();
jp.nextToken();
break;
}
}
}
Files.delete(packageSourceTmp);
if (packageVersion == null || packageTgzPath == null)
{
throw new IllegalArgumentException(
String.format("Failed to parse npm package source for [%s], attachment not found", packageName));
}
return Pair.with(packageVersion, packageTgzPath);
}
private void deleteVersionDirectory(Path path)
throws IOException
{
Path versionPath = path.getParent();
FileUtils.deleteDirectory(versionPath.toFile());
}
private Path extractPackage(JsonParser jp)
throws IOException
{
Path packageTgzTmp = Files.createTempFile("package", "tgz");
try (OutputStream packageTgzOut = new BufferedOutputStream(Files.newOutputStream(packageTgzTmp,
StandardOpenOption.TRUNCATE_EXISTING)))
{
jp.readBinaryValue(packageTgzOut);
}
long packageSize = Files.size(packageTgzTmp);
Assert.isTrue(FIELD_NAME_LENGTH.equals(jp.nextFieldName()), "Failed to validate package content length.");
jp.nextToken();
Assert.isTrue(packageSize == jp.getLongValue(), "Invalid package content length.");
jp.nextToken();
return packageTgzTmp;
}
private Path extractPackageJson(Path packageTgzTmp)
throws IOException
{
String packageJsonSource;
try (InputStream packageTgzIn = new BufferedInputStream(Files.newInputStream(packageTgzTmp)))
{
packageJsonSource = extrectPackageJson(packageTgzIn);
}
Path packageJsonTmp = Files.createTempFile("package", "json");
Files.write(packageJsonTmp, packageJsonSource.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
return packageJsonTmp;
}
private void moveToAttachment(JsonParser jp,
String packageAttachmentName)
throws IOException
{
Assert.isTrue(jp.nextToken() == JsonToken.START_OBJECT,
String.format(
"Failed to parse npm package source for [%s], illegal attachment content type [%s].",
packageAttachmentName, jp.currentToken().name()));
jp.nextToken();
String contentType = jp.nextTextValue();
Assert.isTrue(MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(contentType),
String.format("Failed to parse npm package source for [%s], unknown content type [%s]",
packageAttachmentName, contentType));
String dataFieldName = jp.nextFieldName();
Assert.isTrue("data".equals(dataFieldName),
String.format("Failed to parse npm package source for [%s], data not found",
packageAttachmentName));
jp.nextToken();
}
private PackageVersion extractPackageVersion(String packageName,
String packageJsonSource)
throws IOException
{
PackageVersion packageVersion;
try
{
packageVersion = npmJacksonMapper.readValue(packageJsonSource, PackageVersion.class);
}
catch (JsonProcessingException e)
{
throw new IllegalArgumentException(String.format("Failed to parse package.json info for [%s]", packageName),
e);
}
Assert.isTrue(packageName.equals(packageVersion.getName()),
String.format("Package name [%s] don't match with [%s].", packageVersion.getName(), packageName));
return packageVersion;
}
private String extrectPackageJson(InputStream in)
throws IOException
{
GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn))
{
TarArchiveEntry entry;
while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null)
{
if (!entry.getName().endsWith("package.json"))
{
continue;
}
StringWriter writer = new StringWriter();
IOUtils.copy(tarIn, writer, StandardCharsets.UTF_8);
return writer.toString();
}
return null;
}
}
private String getPackageVersion(String packageNameWithVersion,
String packageName)
{
return packageNameWithVersion.substring(packageName.length() + 1);
}
}
|
strongbox-web-core/src/main/java/org/carlspring/strongbox/controllers/layout/npm/NpmArtifactController.java
|
package org.carlspring.strongbox.controllers.layout.npm;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.carlspring.strongbox.artifact.ArtifactTag;
import org.carlspring.strongbox.artifact.coordinates.NpmArtifactCoordinates;
import org.carlspring.strongbox.config.NpmLayoutProviderConfig.NpmObjectMapper;
import org.carlspring.strongbox.controllers.BaseArtifactController;
import org.carlspring.strongbox.data.criteria.Expression.ExpOperator;
import org.carlspring.strongbox.data.criteria.Paginator;
import org.carlspring.strongbox.data.criteria.Predicate;
import org.carlspring.strongbox.npm.NpmSearchRequest;
import org.carlspring.strongbox.npm.NpmViewRequest;
import org.carlspring.strongbox.npm.metadata.DistTags;
import org.carlspring.strongbox.npm.metadata.PackageFeed;
import org.carlspring.strongbox.npm.metadata.PackageVersion;
import org.carlspring.strongbox.npm.metadata.SearchResults;
import org.carlspring.strongbox.npm.metadata.Time;
import org.carlspring.strongbox.npm.metadata.Versions;
import org.carlspring.strongbox.providers.ProviderImplementationException;
import org.carlspring.strongbox.providers.io.RepositoryPath;
import org.carlspring.strongbox.providers.layout.NpmPackageDesc;
import org.carlspring.strongbox.providers.layout.NpmPackageSupplier;
import org.carlspring.strongbox.providers.layout.NpmSearchResultSupplier;
import org.carlspring.strongbox.providers.repository.RepositoryProvider;
import org.carlspring.strongbox.providers.repository.RepositoryProviderRegistry;
import org.carlspring.strongbox.repository.NpmRepositoryFeatures.SearchPackagesEventListener;
import org.carlspring.strongbox.repository.NpmRepositoryFeatures.ViewPackageEventListener;
import org.carlspring.strongbox.storage.repository.Repository;
import org.carlspring.strongbox.storage.validation.artifact.ArtifactCoordinatesValidationException;
import org.carlspring.strongbox.users.userdetails.SpringSecurityUser;
import org.carlspring.strongbox.web.LayoutRequestMapping;
import org.carlspring.strongbox.web.RepositoryMapping;
import org.javatuples.Pair;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.Assert;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* This Controller used to handle npm requests.
*
* @author Sergey Bespalov
*/
@RestController
@LayoutRequestMapping(NpmArtifactCoordinates.LAYOUT_NAME)
public class NpmArtifactController
extends BaseArtifactController
{
private static final String FIELD_NAME_LENGTH = "length";
private static final String FIELD_NAME_ATTACHMENTS = "_attachments";
private static final String FIELD_NAME_VERSION = "versions";
@Inject
@NpmObjectMapper
private ObjectMapper npmJacksonMapper;
@Inject
private RepositoryProviderRegistry repositoryProviderRegistry;
@Inject
private NpmPackageSupplier npmPackageSupplier;
@Inject
private NpmSearchResultSupplier npmSearchResultSupplier;
@Inject
private ViewPackageEventListener viewPackageEventListener;
@Inject
private SearchPackagesEventListener searcPackagesEventListener;
@GetMapping(path = { "{storageId}/{repositoryId}/npm" })
public ResponseEntity<String> greet()
{
// TODO: find out what NPM expect to receive here
return ResponseEntity.ok("");
}
@GetMapping(path = "{storageId}/{repositoryId}/-/v1/search")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void search(@RepositoryMapping Repository repository,
@RequestParam(name = "text") String text,
@RequestParam(name = "size", defaultValue = "20") Integer size,
HttpServletResponse response)
throws IOException
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
NpmSearchRequest npmSearchRequest = new NpmSearchRequest();
npmSearchRequest.setText(text);
npmSearchRequest.setSize(size);
searcPackagesEventListener.setNpmSearchRequest(npmSearchRequest);
RepositoryProvider provider = repositoryProviderRegistry.getProvider(repository.getType());
Predicate predicate = Predicate.empty();
predicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.extension", "tgz")));
predicate.and(Predicate.of(ExpOperator.CONTAINS.of("tagSet.name", ArtifactTag.LAST_VERSION)));
Predicate lkePredicate = Predicate.empty().nested();
lkePredicate.or(
Predicate.of(ExpOperator.LIKE.of("artifactCoordinates.coordinates.name.toLowerCase()", text + "%")));
lkePredicate.or(
Predicate.of(ExpOperator.LIKE.of("artifactCoordinates.coordinates.scope.toLowerCase()", text + "%")));
predicate.or(lkePredicate);
Paginator paginator = new Paginator();
paginator.setLimit(20);
List<Path> searchResult = provider.search(storageId, repositoryId, predicate, paginator);
SearchResults searchResults = new SearchResults();
searchResult.stream().map(npmSearchResultSupplier).forEach(p -> {
searchResults.getObjects().add(p);
});
Long count = provider.count(storageId, repositoryId, predicate);
searchResults.setTotal(count.intValue());
//Wed Oct 31 2018 05:01:19 GMT+0000 (UTC)
SimpleDateFormat format = new SimpleDateFormat(NpmSearchResultSupplier.SEARCH_DATE_FORMAT);
searchResults.setTime(format.format(new Date()));
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(npmJacksonMapper.writeValueAsBytes(searchResults));
}
@GetMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName:[^-].+}/{packageVersion}")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void viewPackageWithScope(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "packageVersion") String packageVersion,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
String packageId = NpmArtifactCoordinates.calculatePackageId(packageScope, packageName);
NpmArtifactCoordinates c = NpmArtifactCoordinates.of(packageId, packageVersion);
NpmViewRequest npmSearchRequest = new NpmViewRequest();
npmSearchRequest.setPackageId(packageId);
npmSearchRequest.setVersion(packageVersion);
viewPackageEventListener.setNpmSearchRequest(npmSearchRequest);
RepositoryPath repositoryPath = artifactResolutionService.resolvePath(storageId, repositoryId, c.toPath());
if (repositoryPath == null)
{
response.setStatus(HttpStatus.NOT_FOUND.value());
return;
}
NpmPackageDesc packageDesc = npmPackageSupplier.apply(repositoryPath);
PackageVersion npmPackage = packageDesc.getNpmPackage();
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(npmJacksonMapper.writeValueAsBytes(npmPackage));
}
@GetMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void viewPackageFeedWithScope(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
String packageId = NpmArtifactCoordinates.calculatePackageId(packageScope, packageName);
NpmViewRequest npmSearchRequest = new NpmViewRequest();
npmSearchRequest.setPackageId(packageId);
viewPackageEventListener.setNpmSearchRequest(npmSearchRequest);
PackageFeed packageFeed = new PackageFeed();
packageFeed.setName(packageId);
packageFeed.setAdditionalProperty("_id", packageId);
packageFeed.setAdditionalProperty("_rev", generateRevisionHashcode());
Predicate predicate = createSearchPredicate(packageScope, packageName);
RepositoryProvider provider = repositoryProviderRegistry.getProvider(repository.getType());
Paginator paginator = new Paginator();
paginator.setProperty("version");
List<Path> searchResult = provider.search(storageId, repositoryId, predicate, paginator);
Versions versions = new Versions();
packageFeed.setVersions(versions);
Time npmTime = new Time();
packageFeed.setTime(npmTime);
DistTags distTags = new DistTags();
packageFeed.setDistTags(distTags);
searchResult.stream().map(npmPackageSupplier).forEach(p -> {
PackageVersion npmPackage = p.getNpmPackage();
versions.setAdditionalProperty(npmPackage.getVersion(), npmPackage);
npmTime.setAdditionalProperty(npmPackage.getVersion(), p.getReleaseDate());
Date created = npmTime.getCreated();
npmTime.setCreated(created == null || created.before(p.getReleaseDate()) ? p.getReleaseDate() : created);
Date modified = npmTime.getModified();
npmTime.setModified(modified == null || modified.before(p.getReleaseDate()) ? p.getReleaseDate()
: modified);
if (p.isLastVersion())
{
distTags.setLatest(npmPackage.getVersion());
}
});
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getOutputStream().write(npmJacksonMapper.writeValueAsBytes(packageFeed));
}
private String generateRevisionHashcode()
{
return "36-b8d6f834569d63";
}
@GetMapping(path = "{storageId}/{repositoryId}/{packageName}")
@PreAuthorize("hasAuthority('ARTIFACTS_VIEW')")
public void viewPackageFeed(@RepositoryMapping Repository repository,
@PathVariable(name = "packageName") String packageName,
HttpServletResponse response)
throws Exception
{
viewPackageFeedWithScope(repository, null, packageName, response);
}
private Predicate createSearchPredicate(String packageScope,
String packageName)
{
Predicate rootPredicate = Predicate.empty();
rootPredicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.extension", "tgz")));
rootPredicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.name", packageName)));
if (packageScope != null)
{
rootPredicate.and(Predicate.of(ExpOperator.EQ.of("artifactCoordinates.coordinates.scope", packageScope)));
}
return rootPredicate;
}
@PreAuthorize("hasAuthority('ARTIFACTS_RESOLVE')")
@RequestMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}/-/{packageNameWithVersion}.{packageExtension}",
method = { RequestMethod.GET,
RequestMethod.HEAD })
public void downloadPackageWithScope(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "packageNameWithVersion") String packageNameWithVersion,
@PathVariable(name = "packageExtension") String packageExtension,
@RequestHeader HttpHeaders httpHeaders,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
if (!packageNameWithVersion.startsWith(packageName + "-"))
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//Example of packageNameWithVersion core-9.0.1-next.8.tgz
final String packageVersion = getPackageVersion(packageNameWithVersion, packageName);
NpmArtifactCoordinates coordinates;
try
{
coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), packageVersion);
}
catch (IllegalArgumentException e)
{
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(e.getMessage());
return;
}
RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath());
provideArtifactDownloadResponse(request, response, httpHeaders, path);
}
@PreAuthorize("hasAuthority('ARTIFACTS_RESOLVE')")
@RequestMapping(path = "{storageId}/{repositoryId}/{packageName}/-/{packageNameWithVersion}.{packageExtension}",
method = { RequestMethod.GET,
RequestMethod.HEAD })
public void downloadPackage(@RepositoryMapping Repository repository,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "packageNameWithVersion") String packageNameWithVersion,
@PathVariable(name = "packageExtension") String packageExtension,
@RequestHeader HttpHeaders httpHeaders,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
if (!packageNameWithVersion.startsWith(packageName + "-"))
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//Example of packageNameWithVersion core-9.0.1-next.8.tgz
final String packageVersion = getPackageVersion(packageNameWithVersion, packageName);
NpmArtifactCoordinates coordinates;
try
{
coordinates = NpmArtifactCoordinates.of(packageName, packageVersion);
}
catch (IllegalArgumentException e)
{
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(e.getMessage());
return;
}
RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath());
provideArtifactDownloadResponse(request, response, httpHeaders, path);
}
@PreAuthorize("hasAuthority('ARTIFACTS_DEPLOY')")
@PutMapping(path = "{storageId}/{repositoryId}/{name:.+}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity publish(@RepositoryMapping Repository repository,
@PathVariable(name = "name") String name,
HttpServletRequest request)
throws Exception
{
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
if (name.contains("/-rev/"))
{
logger.warn(
"Client executed npm unpublish a package with a specified version, PUT stage should be skipped!");
return ResponseEntity.status(HttpStatus.OK)
.body("");
}
logger.info("npm publish request for {}/{}/{}", storageId, repositoryId, name);
Pair<PackageVersion, Path> packageEntry;
try
{
packageEntry = extractPackage(name, request.getInputStream());
}
catch (IllegalArgumentException e)
{
logger.error("Failed to extract npm package data", e);
return ResponseEntity.badRequest().build();
}
PackageVersion packageJson = packageEntry.getValue0();
Path packageTgz = packageEntry.getValue1();
NpmArtifactCoordinates coordinates = NpmArtifactCoordinates.of(name, packageJson.getVersion());
storeNpmPackage(repository, coordinates, packageJson, packageTgz);
return ResponseEntity.ok("");
}
@PreAuthorize("hasAuthority('UI_LOGIN')")
@PutMapping(path = "{storageId}/{repositoryId}/-/user/org.couchdb.user:{username}",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity addUser(Authentication authentication)
{
if (authentication == null || !authentication.isAuthenticated())
{
throw new InsufficientAuthenticationException("unauthorized");
}
if (!(authentication instanceof UsernamePasswordAuthenticationToken))
{
return toResponseEntityError("Unsupported authentication class " + authentication.getClass().getName());
}
Object principal = authentication.getPrincipal();
if (!(principal instanceof SpringSecurityUser))
{
return toResponseEntityError(
"Unsupported authentication principal " + Optional.ofNullable(principal).orElse(null));
}
return ResponseEntity
.status(HttpStatus.CREATED)
.body("{\"ok\":\"user '" + authentication.getName() + "' created\"}");
}
@DeleteMapping(path = "{storageId}/{repositoryId}/{packageScope}/{packageName}/-/{tarball}/-rev/{rev}")
@PreAuthorize("hasAuthority('ARTIFACTS_DELETE')")
public ResponseEntity unpublish(@RepositoryMapping Repository repository,
@PathVariable(name = "packageScope") String packageScope,
@PathVariable(name = "packageName") String packageName,
@PathVariable(name = "tarball") String tarball,
@PathVariable(name = "rev") String rev)
throws Exception
{
if (!repository.allowsUnpublish())
{
logger.warn(String.format("User tried to 'unpublish' a package [%s], but the feature is disabled",
packageName));
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Enable 'unpublish' at first");
}
final String storageId = repository.getStorage().getId();
final String repositoryId = repository.getId();
final String version = getPackageVersion(tarball, packageName)
.replace(".tgz", "");
logger.info(
"Npm delete request: storageId-[{}]; repositoryId-[{}]; packageName-[{}]; tarball-[{}]; revision-[{}];",
storageId, repositoryId, packageName, tarball, rev);
NpmArtifactCoordinates coordinates;
try
{
coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), version);
}
catch (IllegalArgumentException e)
{
logger.error("Illegal arg passed", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath());
try
{
artifactManagementService.delete(path, false);
deleteVersionDirectory(path);
}
catch (IOException e)
{
logger.error("Failed to process Npm delete request: path-[{}]", path, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
logger.info("'unpublish' operation succeeded!");
return ResponseEntity.status(HttpStatus.OK).build();
}
private void storeNpmPackage(Repository repository,
NpmArtifactCoordinates coordinates,
PackageVersion packageDef,
Path packageTgzTmp)
throws IOException,
ProviderImplementationException,
NoSuchAlgorithmException,
ArtifactCoordinatesValidationException
{
RepositoryPath repositoryPath = repositoryPathResolver.resolve(repository, coordinates);
try (InputStream is = new BufferedInputStream(Files.newInputStream(packageTgzTmp)))
{
artifactManagementService.validateAndStore(repositoryPath, is);
}
Path packageJsonTmp = extractPackageJson(packageTgzTmp);
RepositoryPath packageJsonPath = repositoryPathResolver.resolve(repository,
repositoryPath.resolveSibling("package.json"));
try (InputStream is = new BufferedInputStream(Files.newInputStream(packageJsonTmp)))
{
artifactManagementService.validateAndStore(packageJsonPath, is);
}
String shasum = Optional.ofNullable(packageDef.getDist()).map(p -> p.getShasum()).orElse(null);
if (shasum == null)
{
logger.warn("No checksum provided for package [{}]", packageDef.getName());
return;
}
String packageFileName = repositoryPath.getFileName().toString();
RepositoryPath checksumPath = repositoryPath.resolveSibling(packageFileName + ".sha1");
artifactManagementService.validateAndStore(checksumPath,
new ByteArrayInputStream(shasum.getBytes(StandardCharsets.UTF_8)));
Files.delete(packageTgzTmp);
Files.delete(packageJsonTmp);
}
private Pair<PackageVersion, Path> extractPackage(String packageName,
ServletInputStream in)
throws IOException
{
Path packageSourceTmp = Files.createTempFile("package", "source");
Files.copy(in, packageSourceTmp, StandardCopyOption.REPLACE_EXISTING);
PackageVersion packageVersion = null;
Path packageTgzPath = null;
JsonFactory jfactory = new JsonFactory();
try (InputStream tmpIn = new BufferedInputStream(Files.newInputStream(packageSourceTmp));
JsonParser jp = jfactory.createParser(tmpIn);)
{
jp.setCodec(npmJacksonMapper);
Assert.isTrue(jp.nextToken() == JsonToken.START_OBJECT, "npm package source should be JSON object.");
while (jp.nextToken() != null)
{
String fieldName = jp.getCurrentName();
// read value
if (fieldName == null)
{
continue;
}
switch (fieldName)
{
case FIELD_NAME_VERSION:
jp.nextValue();
JsonNode node = jp.readValueAsTree();
Assert.isTrue(node.size() == 1, "npm package source should contain only one version.");
JsonNode packageJsonNode = node.iterator().next();
packageVersion = extractPackageVersion(packageName, packageJsonNode.toString());
break;
case FIELD_NAME_ATTACHMENTS:
Assert.isTrue(jp.nextToken() == JsonToken.START_OBJECT,
String.format(
"Failed to parse npm package source for illegal type [%s] of attachment.",
jp.currentToken().name()));
String packageAttachmentName = jp.nextFieldName();
logger.info(String.format("Found npm package attachment [%s]", packageAttachmentName));
moveToAttachment(jp, packageAttachmentName);
packageTgzPath = extractPackage(jp);
jp.nextToken();
jp.nextToken();
break;
}
}
}
Files.delete(packageSourceTmp);
if (packageVersion == null || packageTgzPath == null)
{
throw new IllegalArgumentException(
String.format("Failed to parse npm package source for [%s], attachment not found", packageName));
}
return Pair.with(packageVersion, packageTgzPath);
}
private void deleteVersionDirectory(Path path)
throws IOException
{
Path versionPath = path.getParent();
FileUtils.deleteDirectory(versionPath.toFile());
}
private Path extractPackage(JsonParser jp)
throws IOException
{
Path packageTgzTmp = Files.createTempFile("package", "tgz");
try (OutputStream packageTgzOut = new BufferedOutputStream(Files.newOutputStream(packageTgzTmp,
StandardOpenOption.TRUNCATE_EXISTING)))
{
jp.readBinaryValue(packageTgzOut);
}
long packageSize = Files.size(packageTgzTmp);
Assert.isTrue(FIELD_NAME_LENGTH.equals(jp.nextFieldName()), "Failed to validate package content length.");
jp.nextToken();
Assert.isTrue(packageSize == jp.getLongValue(), "Invalid package content length.");
jp.nextToken();
return packageTgzTmp;
}
private Path extractPackageJson(Path packageTgzTmp)
throws IOException
{
String packageJsonSource;
try (InputStream packageTgzIn = new BufferedInputStream(Files.newInputStream(packageTgzTmp)))
{
packageJsonSource = extrectPackageJson(packageTgzIn);
}
Path packageJsonTmp = Files.createTempFile("package", "json");
Files.write(packageJsonTmp, packageJsonSource.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
return packageJsonTmp;
}
private void moveToAttachment(JsonParser jp,
String packageAttachmentName)
throws IOException
{
Assert.isTrue(jp.nextToken() == JsonToken.START_OBJECT,
String.format(
"Failed to parse npm package source for [%s], illegal attachment content type [%s].",
packageAttachmentName, jp.currentToken().name()));
jp.nextToken();
String contentType = jp.nextTextValue();
Assert.isTrue(MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(contentType),
String.format("Failed to parse npm package source for [%s], unknown content type [%s]",
packageAttachmentName, contentType));
String dataFieldName = jp.nextFieldName();
Assert.isTrue("data".equals(dataFieldName),
String.format("Failed to parse npm package source for [%s], data not found",
packageAttachmentName));
jp.nextToken();
}
private PackageVersion extractPackageVersion(String packageName,
String packageJsonSource)
throws IOException
{
PackageVersion packageVersion;
try
{
packageVersion = npmJacksonMapper.readValue(packageJsonSource, PackageVersion.class);
}
catch (JsonProcessingException e)
{
throw new IllegalArgumentException(String.format("Failed to parse package.json info for [%s]", packageName),
e);
}
Assert.isTrue(packageName.equals(packageVersion.getName()),
String.format("Package name [%s] don't match with [%s].", packageVersion.getName(), packageName));
return packageVersion;
}
private String extrectPackageJson(InputStream in)
throws IOException
{
GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn))
{
TarArchiveEntry entry;
while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null)
{
if (!entry.getName().endsWith("package.json"))
{
continue;
}
StringWriter writer = new StringWriter();
IOUtils.copy(tarIn, writer, StandardCharsets.UTF_8);
return writer.toString();
}
return null;
}
}
private String getPackageVersion(String packageNameWithVersion,
String packageName)
{
return packageNameWithVersion.substring(packageName.length() + 1);
}
}
|
Issue-1543 - impl npm unpublish a package
|
strongbox-web-core/src/main/java/org/carlspring/strongbox/controllers/layout/npm/NpmArtifactController.java
|
Issue-1543 - impl npm unpublish a package
|
|
Java
|
apache-2.0
|
c8934dfae7d5b911079430f2f9448bd91094ef9b
| 0
|
apiman/apiman-test,wermington/apiman-test,jsmolar/apiman-test
|
/*
* Copyright 2016 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.test.integration.runner.handlers.misc;
import io.apiman.test.integration.runner.annotations.misc.ApiKey;
import io.apiman.test.integration.runner.handlers.FieldAnnotationHandler;
import io.apiman.test.integration.runner.handlers.HandlerMap;
import io.apiman.test.integration.runner.restclients.version.ClientVersions;
import io.apiman.manager.api.beans.apis.ApiVersionBean;
import io.apiman.manager.api.beans.clients.ClientVersionBean;
import io.apiman.manager.api.beans.orgs.OrganizationBean;
import io.apiman.manager.api.beans.plans.PlanVersionBean;
import io.apiman.manager.api.beans.summary.ContractSummaryBean;
import java.lang.reflect.Field;
/**
* @author jcechace
*/
public class ApiKeyAnnotationHandler extends FieldAnnotationHandler<ApiKey, Void> {
public ApiKeyAnnotationHandler(Object instance, Class<ApiKey> annotationClass, HandlerMap handlerMap) {
super(instance, annotationClass, handlerMap);
}
@Override
public void processField(Field field, ApiKey annotation) throws ReflectiveOperationException {
ClientVersionBean vClient = getStoredEntity(ClientVersionBean.class, annotation.vClient(), field);
setField(field, String.class, vClient.getApikey());
}
@Override
public Void newBeanFromAnnotation(ApiKey annotation) {
throw new UnsupportedOperationException("Resource does not support POST requests");
}
}
|
apiman-it-commons/src/main/java/io/apiman/test/integration/runner/handlers/misc/ApiKeyAnnotationHandler.java
|
/*
* Copyright 2016 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.test.integration.runner.handlers.misc;
import io.apiman.test.integration.runner.annotations.misc.ApiKey;
import io.apiman.test.integration.runner.handlers.FieldAnnotationHandler;
import io.apiman.test.integration.runner.handlers.HandlerMap;
import io.apiman.test.integration.runner.restclients.version.ClientVersions;
import io.apiman.manager.api.beans.apis.ApiVersionBean;
import io.apiman.manager.api.beans.clients.ClientVersionBean;
import io.apiman.manager.api.beans.orgs.OrganizationBean;
import io.apiman.manager.api.beans.plans.PlanVersionBean;
import io.apiman.manager.api.beans.summary.ContractSummaryBean;
import java.lang.reflect.Field;
/**
* @author jcechace
*/
public class ApiKeyAnnotationHandler extends FieldAnnotationHandler<ApiKey, Void> {
public ApiKeyAnnotationHandler(Object instance, Class<ApiKey> annotationClass, HandlerMap handlerMap) {
super(instance, annotationClass, handlerMap);
}
@Override
public void processField(Field field, ApiKey annotation) throws ReflectiveOperationException {
ClientVersionBean vClient = getStoredEntity(ClientVersionBean.class, annotation.vClient(), field);
ClientVersions client =
(ClientVersions) new ClientVersions(vClient.getClient()).fetch(vClient.getVersion());
ApiVersionBean vApi = getStoredEntity(ApiVersionBean.class, annotation.vApi(), field);
PlanVersionBean vPlan = getStoredEntity(PlanVersionBean.class, annotation.vPlan(), field);
OrganizationBean org = vApi.getApi().getOrganization();
ContractSummaryBean contract = client.contracts().fetch(org, vApi, vPlan).getBean();
setField(field, String.class, contract.getApikey());
}
@Override
public Void newBeanFromAnnotation(ApiKey annotation) {
throw new UnsupportedOperationException("Resource does not support POST requests");
}
}
|
Fix apiKey retrieval
Api key was moved from Contract to client in Apiman
|
apiman-it-commons/src/main/java/io/apiman/test/integration/runner/handlers/misc/ApiKeyAnnotationHandler.java
|
Fix apiKey retrieval
|
|
Java
|
mit
|
ee0f2ae02702ee5104b3ab3bb9e98239dd3d1a30
| 0
|
Heliozoa/tdd-pingpong,tdd-pingis/tdd-pingpong,tdd-pingis/tdd-pingpong,Heliozoa/tdd-pingpong,Heliozoa/tdd-pingpong,tdd-pingis/tdd-pingpong,Heliozoa/tdd-pingpong,tdd-pingis/tdd-pingpong
|
package pingis.controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import pingis.config.SecurityDevConfig;
import pingis.entities.User;
import pingis.services.DataImporter.UserType;
import pingis.services.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(UserDevController.class)
@ContextConfiguration(classes = {UserDevController.class, SecurityDevConfig.class,
UserService.class})
@WebAppConfiguration
public class UserDevControllerTest {
private static final int TEST_USER_LEVEL = 200;
private static final User testUser = new User(UserType.TEST_USER.getId(),
UserType.TEST_USER.getLogin(),
TEST_USER_LEVEL);
@Autowired
WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
private MockMvc mvc;
private WithMockCustomUserSecurityContextFactory mockContext;
@MockBean
UserService userServiceMock;
@Before
public void setUp() {
mockContext = new WithMockCustomUserSecurityContextFactory();
this.mvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilter(springSecurityFilterChain)
.build();
}
@Test
public void testGivenProperPrincipalUserGetsAuthenticated() throws Exception {
// Expected outcomes
String expectedUsername = "user";
String expectedViewName = "user";
String testUrl = "/user";
when(userServiceMock.handleUserAuthenticationByName(Mockito.anyString())).thenReturn(testUser);
MvcResult result = mvc.perform(get(testUrl).with(securityContext(
mockContext.createSecurityContext(testUser))))
.andExpect(view().name(expectedViewName))
.andExpect(content().string(containsString(expectedUsername)))
.andReturn();
verify(userServiceMock).handleUserAuthenticationByName(UserType.TEST_USER.getLogin());
Mockito.verifyNoMoreInteractions(userServiceMock);
}
@Test
public void testLoginIsUnsuccessfulWithInvalidPassword() throws Exception {
// Expected outcomes
String expectedContent = "password";
String expectedViewName = "login";
MvcResult result = mvc.perform(formLogin().password("invalid"))
.andExpect(unauthenticated())
.andExpect(status().is3xxRedirection())
.andReturn();
}
@Test
public void testLoginIsSuccessfulWithAdmin() throws Exception {
// Expected outcomes
String expectedContent = "password";
mvc.perform(formLogin().user("admin"))
.andExpect(authenticated().withRoles("ADMIN"));
}
@Test
public void testLoginIsSuccessfulWithUser() throws Exception {
// Expected outcomes
String expectedContent = "frontpage";
String expectedViewName = "index";
mvc.perform(formLogin().user("user"))
.andExpect(authenticated().withRoles("USER"))
.andExpect(status().is3xxRedirection());
}
}
|
src/test/java/pingis/controllers/UserDevControllerTest.java
|
package pingis.controllers;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import pingis.config.SecurityDevConfig;
import pingis.entities.User;
import pingis.services.UserService;
import pingis.services.DataImporter.UserType;
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(UserDevController.class)
@ContextConfiguration(classes = {UserDevController.class, SecurityDevConfig.class,
UserService.class})
@WebAppConfiguration
public class UserDevControllerTest {
private static final int TEST_USER_LEVEL = 200;
private static final User testUser = new User(UserType.TEST_USER.getId(),
UserType.TEST_USER.getLogin(),
TEST_USER_LEVEL);
@Autowired
WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
private MockMvc mvc;
private WithMockCustomUserSecurityContextFactory mockContext;
@MockBean
UserService userServiceMock;
@Before
public void setUp() {
mockContext = new WithMockCustomUserSecurityContextFactory();
this.mvc = MockMvcBuilders
.webAppContextSetup(context)
.addFilter(springSecurityFilterChain)
.build();
}
@Test
public void testGivenProperPrincipalUserGetsAuthenticated() throws Exception {
// Expected outcomes
String expectedUsername = "user";
String expectedViewName = "user";
String testUrl = "/user";
when(userServiceMock.handleUserAuthenticationByName(Mockito.anyString())).thenReturn(testUser);
MvcResult result = mvc.perform(get(testUrl).with(securityContext(
mockContext.createSecurityContext(testUser))))
.andExpect(view().name(expectedViewName))
.andExpect(content().string(containsString(expectedUsername)))
.andReturn();
verify(userServiceMock).handleUserAuthenticationByName(UserType.TEST_USER.getLogin());
Mockito.verifyNoMoreInteractions(userServiceMock);
}
@Test
public void testLoginIsUnsuccessfulWithInvalidPassword() throws Exception {
// Expected outcomes
String expectedContent = "password";
String expectedViewName = "login";
MvcResult result = mvc.perform(formLogin().password("invalid"))
.andExpect(unauthenticated())
.andExpect(status().is3xxRedirection())
.andReturn();
}
@Test
public void testLoginIsSuccessfulWithAdmin() throws Exception {
// Expected outcomes
String expectedContent = "password";
mvc.perform(formLogin().user("admin"))
.andExpect(authenticated().withRoles("ADMIN"));
}
@Test
public void testLoginIsSuccessfulWithUser() throws Exception {
// Expected outcomes
String expectedContent = "frontpage";
String expectedViewName = "index";
mvc.perform(formLogin().user("user"))
.andExpect(authenticated().withRoles("USER"))
.andExpect(status().is3xxRedirection());
}
}
|
more fixes
|
src/test/java/pingis/controllers/UserDevControllerTest.java
|
more fixes
|
|
Java
|
mit
|
af2b9ce4a56572216e8aa830d60151d683386734
| 0
|
osiam/osiam,tkrille/osiam-osiam,osiam/osiam,osiam/osiam,fwilhe/osiam,tkrille/osiam-osiam,tkrille/osiam-osiam,fwilhe/osiam,fwilhe/osiam
|
/*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.resources.converter;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.ExtensionFieldType;
import org.osiam.storage.dao.ExtensionDao;
import org.osiam.storage.entities.ExtensionEntity;
import org.osiam.storage.entities.ExtensionFieldEntity;
import org.osiam.storage.entities.ExtensionFieldValueEntity;
import org.osiam.storage.helper.NumberPadder;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
@Service
public class ExtensionConverter implements Converter<Set<Extension>, Set<ExtensionFieldValueEntity>> {
@Inject
private ExtensionDao extensionDao;
@Inject
private NumberPadder numberPadder;
@Override
public Set<ExtensionFieldValueEntity> fromScim(Set<Extension> extensions) {
Set<ExtensionFieldValueEntity> result = new HashSet<>();
for (Extension extension : checkNotNull(extensions)) {
String urn = extension.getUrn();
ExtensionEntity extensionEntity = extensionDao.getExtensionByUrn(urn);
for (ExtensionFieldEntity field : extensionEntity.getFields()) {
if (extension.isFieldPresent(field.getName())) {
if (Strings.isNullOrEmpty(extension.getField(field.getName(), ExtensionFieldType.STRING))) {
continue;
}
ExtensionFieldValueEntity value = new ExtensionFieldValueEntity();
String typeCheckedStringValue = getTypeCheckedStringValue(field.getType(), field.getName(),
extension);
if (field.getType() == ExtensionFieldType.INTEGER || field.getType() == ExtensionFieldType.DECIMAL) {
typeCheckedStringValue = numberPadder.pad(typeCheckedStringValue);
}
value.setValue(typeCheckedStringValue);
value.setExtensionField(field);
result.add(value);
}
}
}
return result;
}
private <T> String getTypeCheckedStringValue(ExtensionFieldType<T> type, String fieldName, Extension extension) {
T value = extension.getField(fieldName, type);
return type.toString(value);
}
@Override
public Set<Extension> toScim(Set<ExtensionFieldValueEntity> entity) {
Map<String, Extension.Builder> extensionMap = new HashMap<>();
for (ExtensionFieldValueEntity fieldValueEntity : checkNotNull(entity)) {
String urn = fieldValueEntity.getExtensionField().getExtension().getUrn();
Extension.Builder extensionBuilder;
if (extensionMap.containsKey(urn)) {
extensionBuilder = extensionMap.get(urn);
} else {
extensionBuilder = new Extension.Builder(urn);
extensionMap.put(urn, extensionBuilder);
}
ExtensionFieldType<?> type = fieldValueEntity.getExtensionField().getType();
if (type == null) {
// If this is ever true, something went very, very wrong.
throw new IllegalArgumentException("The ExtensionField type can't be null");
}
String value = fieldValueEntity.getValue();
if (type == ExtensionFieldType.INTEGER || type == ExtensionFieldType.DECIMAL) {
value = numberPadder.unpad(value);
}
String name = fieldValueEntity.getExtensionField().getName();
addField(extensionBuilder, type, name, value);
}
HashSet<Extension> extensions = new HashSet<>();
for (Extension.Builder builder : extensionMap.values()) {
extensions.add(builder.build());
}
return extensions;
}
private <T> void addField(Extension.Builder extensionBuilder, ExtensionFieldType<T> type, String fieldName, String stringValue) {
extensionBuilder.setField(fieldName, type.fromString(stringValue), type);
}
}
|
resource-server/src/main/java/org/osiam/resources/converter/ExtensionConverter.java
|
/*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.resources.converter;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.ExtensionFieldType;
import org.osiam.storage.dao.ExtensionDao;
import org.osiam.storage.entities.ExtensionEntity;
import org.osiam.storage.entities.ExtensionFieldEntity;
import org.osiam.storage.entities.ExtensionFieldValueEntity;
import org.osiam.storage.helper.NumberPadder;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
@Service
public class ExtensionConverter implements Converter<Set<Extension>, Set<ExtensionFieldValueEntity>> {
@Inject
private ExtensionDao extensionDao;
@Inject
private NumberPadder numberPadder;
@Override
public Set<ExtensionFieldValueEntity> fromScim(Set<Extension> extensions) {
Set<ExtensionFieldValueEntity> result = new HashSet<>();
for (Extension extension : checkNotNull(extensions)) {
String urn = extension.getUrn();
ExtensionEntity extensionEntity = extensionDao.getExtensionByUrn(urn);
for (ExtensionFieldEntity field : extensionEntity.getFields()) {
if (extension.isFieldPresent(field.getName())) {
if (Strings.isNullOrEmpty(extension.getField(field.getName(), ExtensionFieldType.STRING))) {
continue;
}
ExtensionFieldValueEntity value = new ExtensionFieldValueEntity();
String typeCheckedStringValue = getTypeCheckedStringValue(field.getType(), field.getName(),
extension);
if (field.getType() == ExtensionFieldType.INTEGER || field.getType() == ExtensionFieldType.DECIMAL) {
typeCheckedStringValue = numberPadder.pad(typeCheckedStringValue);
}
value.setValue(typeCheckedStringValue);
value.setExtensionField(field);
result.add(value);
}
}
}
return result;
}
private <T> String getTypeCheckedStringValue(ExtensionFieldType<T> type, String fieldName, Extension extension) {
T value = extension.getField(fieldName, type);
return type.toString(value);
}
@Override
public Set<Extension> toScim(Set<ExtensionFieldValueEntity> entity) {
Map<String, Extension.Builder> extensionMap = new HashMap<>();
for (ExtensionFieldValueEntity fieldValueEntity : checkNotNull(entity)) {
String urn = fieldValueEntity.getExtensionField().getExtension().getUrn();
Extension.Builder extensionBuilder;
if (extensionMap.containsKey(urn)) {
extensionBuilder = extensionMap.get(urn);
} else {
extensionBuilder = new Extension.Builder(urn);
extensionMap.put(urn, extensionBuilder);
}
ExtensionFieldType<?> type = fieldValueEntity.getExtensionField().getType();
if (type == null) {
// If this is ever true, something went very, very wrong.
throw new IllegalArgumentException("The ExtensionField type can't be null");
}
String value = fieldValueEntity.getValue();
if (type == ExtensionFieldType.INTEGER || type == ExtensionFieldType.DECIMAL) {
value = numberPadder.unpad(value);
}
String name = fieldValueEntity.getExtensionField().getName();
addField(extensionBuilder, type, name, value);
}
HashSet<Extension> extensions = new HashSet<>();
for (Extension.Builder builder : extensionMap.values()) {
extensions.add(builder.build());
}
return extensions;
}
private <T> void addField(Extension.Builder extension, ExtensionFieldType<T> type, String fieldName, String stringValue) {
extension.setField(fieldName, type.fromString(stringValue), type);
}
}
|
[task] renamed variable
|
resource-server/src/main/java/org/osiam/resources/converter/ExtensionConverter.java
|
[task] renamed variable
|
|
Java
|
mit
|
3cdb67ac2628a9cb76d8593621f6a8c72154f611
| 0
|
xjy2061/NovaImageLoader,xjy2061/NovaImageLoader,facebook/fresco,xjy2061/NovaImageLoader,s1rius/fresco,s1rius/fresco,xjy2061/NovaImageLoader,facebook/fresco,s1rius/fresco,xjy2061/NovaImageLoader,facebook/fresco,s1rius/fresco,facebook/fresco,facebook/fresco,facebook/fresco
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.bitmaps;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import com.facebook.common.logging.FLog;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.references.CloseableReference;
import com.facebook.imageformat.DefaultImageFormats;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.platform.PlatformDecoder;
import javax.annotation.concurrent.ThreadSafe;
/**
* Factory implementation for Honeycomb through Kitkat
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@ThreadSafe
public class HoneycombBitmapFactory extends PlatformBitmapFactory {
private static final String TAG = HoneycombBitmapFactory.class.getSimpleName();
private final EmptyJpegGenerator mJpegGenerator;
private final PlatformDecoder mPurgeableDecoder;
private boolean mImmutableBitmapFallback;
public HoneycombBitmapFactory(
EmptyJpegGenerator jpegGenerator, PlatformDecoder purgeableDecoder) {
mJpegGenerator = jpegGenerator;
mPurgeableDecoder = purgeableDecoder;
}
/**
* Creates a bitmap of the specified width and height.
*
* @param width the width of the bitmap
* @param height the height of the bitmap
* @param bitmapConfig the {@link android.graphics.Bitmap.Config}
* used to create the decoded Bitmap
* @return a reference to the bitmap
* @throws TooManyBitmapsException if the pool is full
* @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public CloseableReference<Bitmap> createBitmapInternal(
int width,
int height,
Bitmap.Config bitmapConfig) {
if (mImmutableBitmapFallback) {
return createFallbackBitmap(width, height, bitmapConfig);
}
CloseableReference<PooledByteBuffer> jpgRef = mJpegGenerator.generate(
(short) width,
(short) height);
try {
EncodedImage encodedImage = new EncodedImage(jpgRef);
encodedImage.setImageFormat(DefaultImageFormats.JPEG);
try {
CloseableReference<Bitmap> bitmapRef =
mPurgeableDecoder.decodeJPEGFromEncodedImage(
encodedImage, bitmapConfig, null, jpgRef.get().size());
if (!bitmapRef.get().isMutable()) {
CloseableReference.closeSafely(bitmapRef);
mImmutableBitmapFallback = true;
FLog.wtf(TAG, "Immutable bitmap returned by decoder");
// On some devices (Samsung GT-S7580) the returned bitmap can be immutable, in that case
// let's jut use Bitmap.createBitmap() to hopefully create a mutable one.
return createFallbackBitmap(width, height, bitmapConfig);
}
bitmapRef.get().setHasAlpha(true);
bitmapRef.get().eraseColor(Color.TRANSPARENT);
return bitmapRef;
} finally {
EncodedImage.closeSafely(encodedImage);
}
} finally {
jpgRef.close();
}
}
private static CloseableReference<Bitmap> createFallbackBitmap(
int width, int height, Bitmap.Config bitmapConfig) {
return CloseableReference.of(
Bitmap.createBitmap(width, height, bitmapConfig), SimpleBitmapReleaser.getInstance());
}
}
|
imagepipeline/src/main/java/com/facebook/imagepipeline/bitmaps/HoneycombBitmapFactory.java
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.bitmaps;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.references.CloseableReference;
import com.facebook.imageformat.DefaultImageFormats;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.platform.PlatformDecoder;
import javax.annotation.concurrent.ThreadSafe;
/**
* Factory implementation for Honeycomb through Kitkat
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@ThreadSafe
public class HoneycombBitmapFactory extends PlatformBitmapFactory {
private final EmptyJpegGenerator mJpegGenerator;
private final PlatformDecoder mPurgeableDecoder;
public HoneycombBitmapFactory(EmptyJpegGenerator jpegGenerator,
PlatformDecoder purgeableDecoder) {
mJpegGenerator = jpegGenerator;
mPurgeableDecoder = purgeableDecoder;
}
/**
* Creates a bitmap of the specified width and height.
*
* @param width the width of the bitmap
* @param height the height of the bitmap
* @param bitmapConfig the {@link android.graphics.Bitmap.Config}
* used to create the decoded Bitmap
* @return a reference to the bitmap
* @throws TooManyBitmapsException if the pool is full
* @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public CloseableReference<Bitmap> createBitmapInternal(
int width,
int height,
Bitmap.Config bitmapConfig) {
CloseableReference<PooledByteBuffer> jpgRef = mJpegGenerator.generate(
(short) width,
(short) height);
try {
EncodedImage encodedImage = new EncodedImage(jpgRef);
encodedImage.setImageFormat(DefaultImageFormats.JPEG);
try {
CloseableReference<Bitmap> bitmapRef =
mPurgeableDecoder.decodeJPEGFromEncodedImage(
encodedImage, bitmapConfig, null, jpgRef.get().size());
bitmapRef.get().setHasAlpha(true);
bitmapRef.get().eraseColor(Color.TRANSPARENT);
return bitmapRef;
} finally {
EncodedImage.closeSafely(encodedImage);
}
} finally {
jpgRef.close();
}
}
}
|
Fall back to bitmap.createBitmap()
Reviewed By: oprisnik
Differential Revision: D7321946
fbshipit-source-id: 5fe96fe463295c85ba9333b298edd656335c18d0
|
imagepipeline/src/main/java/com/facebook/imagepipeline/bitmaps/HoneycombBitmapFactory.java
|
Fall back to bitmap.createBitmap()
|
|
Java
|
mit
|
be785dd208818b01a384eaa1885e07ff47a10812
| 0
|
bugsnag/bugsnag-java,loopj/bugsnag-java,bugsnag/bugsnag-java,madisp/bugsnag-java,cit-lab/bugsnag-java,bugsnag/bugsnag-java
|
package com.bugsnag;
import java.util.Arrays;
import java.util.List;
import org.json.JSONObject;
import com.bugsnag.utils.JSONUtils;
public class Configuration {
public class LockableValue<T> {
private T value;
private boolean locked = false;
LockableValue() {}
LockableValue(T initial) {
this.value = initial;
}
public void set(T value) {
if(!locked) this.value = value;
}
public void setLocked(T value) {
this.value = value;
locked = true;
}
public T get(T value) {
set(value);
return get();
}
public T get() {
return value;
}
}
protected static final String DEFAULT_ENDPOINT = "notify.bugsnag.com";
private static final String NOTIFIER_NAME = "Java Bugsnag Notifier";
private static final String NOTIFIER_VERSION = "1.2.1";
private static final String NOTIFIER_URL = "https://bugsnag.com";
// Notifier settings
String notifierName = NOTIFIER_NAME;
String notifierVersion = NOTIFIER_VERSION;
String notifierUrl = NOTIFIER_URL;
// Notification settings
String apiKey;
boolean autoNotify = true;
boolean useSSL = false;
String endpoint = DEFAULT_ENDPOINT;
String[] notifyReleaseStages = null;
String[] filters = new String[]{"password"};
String[] projectPackages;
String[] ignoreClasses;
// Error settings
LockableValue<String> context = new LockableValue<String>();
LockableValue<String> releaseStage = new LockableValue<String>("production");
LockableValue<String> appVersion = new LockableValue<String>();
LockableValue<String> osVersion = new LockableValue<String>();
MetaData metaData = new MetaData();
// User settings
public JSONObject user = new JSONObject();
// Logger
public Logger logger = new Logger();
public Configuration() {
}
public String getNotifyEndpoint() {
return String.format("%s://%s", getProtocol(), endpoint);
}
public String getMetricsEndpoint() {
return String.format("%s://%s/metrics", getProtocol(), endpoint);
}
public void addToTab(String tabName, String key, Object value) {
this.metaData.addToTab(tabName, key, value);
}
public void clearTab(String tabName){
this.metaData.clearTab(tabName);
}
public MetaData getMetaData() {
return this.metaData.duplicate();
}
public boolean shouldNotify() {
if(this.notifyReleaseStages == null)
return true;
List<String> stages = Arrays.asList(this.notifyReleaseStages);
return stages.contains(this.releaseStage.get());
}
public boolean shouldIgnore(String className) {
if(this.ignoreClasses == null)
return false;
List<String> classes = Arrays.asList(this.ignoreClasses);
return classes.contains(className);
}
private String getProtocol() {
return (this.useSSL ? "https" : "http");
}
public void setUser(String id, String email, String name) {
JSONUtils.safePutOpt(this.user, "id", id);
JSONUtils.safePutOpt(this.user, "email", email);
JSONUtils.safePutOpt(this.user, "name", name);
}
public LockableValue<String> getContext() {
return context;
}
public LockableValue<String> getOsVersion() {
return osVersion;
}
public LockableValue<String> getAppVersion() {
return appVersion;
}
public LockableValue<String> getReleaseStage() {
return releaseStage;
}
public void setNotifyReleaseStages(String... notifyReleaseStages) {
this.notifyReleaseStages = notifyReleaseStages;
}
public void setAutoNotify(boolean autoNotify) {
this.autoNotify = autoNotify;
}
public void setUseSSL(boolean useSSL) {
this.useSSL = useSSL;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public void setFilters(String... filters) {
this.filters = filters;
}
public void setProjectPackages(String... projectPackages) {
this.projectPackages = projectPackages;
}
public void setNotifierName(String notifierName) {
this.notifierName = notifierName;
}
public void setNotifierVersion(String notifierVersion) {
this.notifierVersion = notifierVersion;
}
public void setNotifierUrl(String notifierUrl) {
this.notifierUrl = notifierUrl;
}
public void setIgnoreClasses(String... ignoreClasses) {
this.ignoreClasses = ignoreClasses;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
}
|
src/main/java/com/bugsnag/Configuration.java
|
package com.bugsnag;
import java.util.Arrays;
import java.util.List;
import org.json.JSONObject;
import com.bugsnag.utils.JSONUtils;
public class Configuration {
public class LockableValue<T> {
private T value;
private boolean locked = false;
LockableValue() {}
LockableValue(T initial) {
this.value = initial;
}
public void set(T value) {
if(!locked) this.value = value;
}
public void setLocked(T value) {
this.value = value;
locked = true;
}
public T get(T value) {
set(value);
return get();
}
public T get() {
return value;
}
}
protected static final String DEFAULT_ENDPOINT = "notify.bugsnag.com";
private static final String NOTIFIER_NAME = "Java Bugsnag Notifier";
private static final String NOTIFIER_VERSION = "1.2.0";
private static final String NOTIFIER_URL = "https://bugsnag.com";
// Notifier settings
String notifierName = NOTIFIER_NAME;
String notifierVersion = NOTIFIER_VERSION;
String notifierUrl = NOTIFIER_URL;
// Notification settings
String apiKey;
boolean autoNotify = true;
boolean useSSL = false;
String endpoint = DEFAULT_ENDPOINT;
String[] notifyReleaseStages = null;
String[] filters = new String[]{"password"};
String[] projectPackages;
String[] ignoreClasses;
// Error settings
LockableValue<String> context = new LockableValue<String>();
LockableValue<String> releaseStage = new LockableValue<String>("production");
LockableValue<String> appVersion = new LockableValue<String>();
LockableValue<String> osVersion = new LockableValue<String>();
MetaData metaData = new MetaData();
// User settings
public JSONObject user = new JSONObject();
// Logger
public Logger logger = new Logger();
public Configuration() {
}
public String getNotifyEndpoint() {
return String.format("%s://%s", getProtocol(), endpoint);
}
public String getMetricsEndpoint() {
return String.format("%s://%s/metrics", getProtocol(), endpoint);
}
public void addToTab(String tabName, String key, Object value) {
this.metaData.addToTab(tabName, key, value);
}
public void clearTab(String tabName){
this.metaData.clearTab(tabName);
}
public MetaData getMetaData() {
return this.metaData.duplicate();
}
public boolean shouldNotify() {
if(this.notifyReleaseStages == null)
return true;
List<String> stages = Arrays.asList(this.notifyReleaseStages);
return stages.contains(this.releaseStage.get());
}
public boolean shouldIgnore(String className) {
if(this.ignoreClasses == null)
return false;
List<String> classes = Arrays.asList(this.ignoreClasses);
return classes.contains(className);
}
private String getProtocol() {
return (this.useSSL ? "https" : "http");
}
public void setUser(String id, String email, String name) {
JSONUtils.safePutOpt(this.user, "id", id);
JSONUtils.safePutOpt(this.user, "email", email);
JSONUtils.safePutOpt(this.user, "name", name);
}
public LockableValue<String> getContext() {
return context;
}
public LockableValue<String> getOsVersion() {
return osVersion;
}
public LockableValue<String> getAppVersion() {
return appVersion;
}
public LockableValue<String> getReleaseStage() {
return releaseStage;
}
public void setNotifyReleaseStages(String... notifyReleaseStages) {
this.notifyReleaseStages = notifyReleaseStages;
}
public void setAutoNotify(boolean autoNotify) {
this.autoNotify = autoNotify;
}
public void setUseSSL(boolean useSSL) {
this.useSSL = useSSL;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public void setFilters(String... filters) {
this.filters = filters;
}
public void setProjectPackages(String... projectPackages) {
this.projectPackages = projectPackages;
}
public void setNotifierName(String notifierName) {
this.notifierName = notifierName;
}
public void setNotifierVersion(String notifierVersion) {
this.notifierVersion = notifierVersion;
}
public void setNotifierUrl(String notifierUrl) {
this.notifierUrl = notifierUrl;
}
public void setIgnoreClasses(String... ignoreClasses) {
this.ignoreClasses = ignoreClasses;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
}
|
Bump notifier version
|
src/main/java/com/bugsnag/Configuration.java
|
Bump notifier version
|
|
Java
|
mit
|
error: pathspec 'src/HasPathSum.java' did not match any file(s) known to git
|
1656f7dca418a9b76be628f6a53bc75cbe90b4f4
| 1
|
rekbun/leetcode
|
/*
http://oj.leetcode.com/problems/path-sum/
*/
public class HasPathSum {
public boolean hasPathSum(TreeNode root,int key) {
if(root==null) {
return false;
}
return hasPathSumUtil(root,key);
}
public boolean hasPathSumUtil(TreeNode root,int key) {
if(root==null && key==0) {
return true;
}
if(root==null) {
return false;
}
return (root.left!=null?hasPathSumUtil(root.left, key-root.val):false)||(root.right!=null?hasPathSumUtil(root.right, key-root.val):((root.left==null && key-root.val==0)?true:false));
}
}
|
src/HasPathSum.java
|
http://oj.leetcode.com/problems/path-sum/
|
src/HasPathSum.java
|
http://oj.leetcode.com/problems/path-sum/
|
|
Java
|
mit
|
error: pathspec 'src/org/jmist/toolkit/tests/Point2Test.java' did not match any file(s) known to git
|
4fe047b7680271ce68be0188cda5bf424bf480f9
| 1
|
bwkimmel/jmist
|
/**
*
*/
package org.jmist.toolkit.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import org.jmist.toolkit.*;
import org.jmist.util.*;
/**
* Tests for {@link org.jmist.toolkit.Point2}.
* @author bkimmel
*/
public class Point2Test {
/**
* Test method for {@link org.jmist.toolkit.Point2#Point2(double, double)}.
*/
@Test
public final void testPoint2() {
Point2 p = new Point2(1.0, 2.0);
assertEquals(1.0, p.x());
assertEquals(2.0, p.y());
}
/**
* Test method for {@link org.jmist.toolkit.Point2#getX()}.
*/
@Test
public final void testGetX() {
Point2 p = new Point2(3.0, 4.0);
assertEquals(3.0, p.getX());
}
/**
* Test method for {@link org.jmist.toolkit.Point2#getY()}.
*/
@Test
public final void testGetY() {
Point2 p = new Point2(5.0, 6.0);
assertEquals(6.0, p.getY());
}
/**
* Test method for {@link org.jmist.toolkit.Point2#squaredDistanceTo(org.jmist.toolkit.Point2)}.
*/
@Test
public final void testSquaredDistanceTo() {
Point2 p = new Point2(1.0, 2.0);
Point2 q = new Point2(5.0, 8.0);
assertEquals((4.0 * 4.0) + (6.0 * 6.0), p.squaredDistanceTo(q), MathUtil.TINY_EPSILON);
assertEquals((4.0 * 4.0) + (6.0 * 6.0), q.squaredDistanceTo(p), MathUtil.TINY_EPSILON);
assertEquals(0.0, p.squaredDistanceTo(p), MathUtil.TINY_EPSILON);
}
/**
* Test method for {@link org.jmist.toolkit.Point2#distanceTo(org.jmist.toolkit.Point2)}.
*/
@Test
public final void testDistanceTo() {
Point2 p = new Point2(1.0, 2.0);
Point2 q = new Point2(-2.0, 6.0);
assertEquals(5.0, p.distanceTo(q), MathUtil.TINY_EPSILON);
assertEquals(5.0, q.distanceTo(p), MathUtil.TINY_EPSILON);
assertEquals(0.0, p.distanceTo(p), MathUtil.TINY_EPSILON);
}
/**
* Test method for {@link org.jmist.toolkit.Point2#vectorTo(org.jmist.toolkit.Point2)}.
*/
@Test
public final void testVectorTo() {
Point2 p = new Point2(1.0, 2.0);
Point2 q = new Point2(-2.0, 6.0);
Vector2 pq = p.vectorTo(q);
Vector2 qp = q.vectorTo(p);
assertEquals(-3.0, pq.x());
assertEquals(4.0, pq.y());
assertEquals(3.0, qp.x());
assertEquals(-4.0, qp.y());
}
/**
* Test method for {@link org.jmist.toolkit.Point2#vectorFrom(org.jmist.toolkit.Point2)}.
*/
@Test
public final void testVectorFrom() {
Point2 p = new Point2(1.0, 2.0);
Point2 q = new Point2(-2.0, 6.0);
Vector2 qp = p.vectorFrom(q);
Vector2 pq = q.vectorFrom(p);
assertEquals(-3.0, pq.x());
assertEquals(4.0, pq.y());
assertEquals(3.0, qp.x());
assertEquals(-4.0, qp.y());
}
/**
* Test method for {@link org.jmist.toolkit.Point2#plus(org.jmist.toolkit.Vector2)}.
*/
@Test
public final void testPlus() {
Point2 p = new Point2(2.0, -3.0);
Vector2 v = new Vector2(-2.0, 4.0);
Point2 q = p.plus(v);
assertEquals(0.0, q.x());
assertEquals(1.0, q.y());
}
/**
* Test method for {@link org.jmist.toolkit.Point2#minus(org.jmist.toolkit.Vector2)}.
*/
@Test
public final void testMinus() {
Point2 p = new Point2(2.0, -3.0);
Vector2 v = new Vector2(-2.0, 4.0);
Point2 q = p.minus(v);
assertEquals(4.0, q.x());
assertEquals(-7.0, q.y());
}
}
|
src/org/jmist/toolkit/tests/Point2Test.java
|
Adding the org.jmist.toolkit.tests package for unit tests.
Added a test class for Point2.
|
src/org/jmist/toolkit/tests/Point2Test.java
|
Adding the org.jmist.toolkit.tests package for unit tests. Added a test class for Point2.
|
|
Java
|
mit
|
error: pathspec 'java/thread/learn/CallableAndFutureDemo.java' did not match any file(s) known to git
|
c7dec9e2ec52bfe80bb22f75cc3b32dba3e16ffb
| 1
|
GenweiWu/Blog,GenweiWu/Blog,GenweiWu/Blog
|
package com.njust.test.learn;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableAndFutureDemo
{
public static void main(String[] args)
throws ExecutionException, InterruptedException
{
//test1();
//test2();
test3();
}
/**
* 3.批量执行
* --------------
* <pre>
* before result...
* future get result:gogo3507e92e-08fa-463a-b16f-7881609fd8d9
* future get result:gogo1f9d8192-c238-46c2-88ff-118343dbd791
* future get result:gogo582acb7b-7e9c-4bbd-b745-8a04763a513b
* future get result:gogo3a67e892-3012-4b3e-8b3a-e8b1b1d1ee08
* future get result:gogoc820b1c4-6369-4b0c-b403-dd6466c5d2e6
* future get result:gogo39e25228-773b-47c9-ab4a-fa01278db320
* future get result:gogo820f1cbe-da91-48d0-a665-5e50bf7fe64b
* future get result:gogo94ddd3ce-3987-484f-b4a0-afd8ded4a0e5
* future get result:gogo03a20494-f23b-483b-b8b4-4047a631cf0a
* future get result:gogo4397bed2-0e2e-45e5-9599-0463595f695d
* after result...
* </pre>
*/
private static void test3()
throws InterruptedException, ExecutionException
{
ExecutorService executorService = Executors.newFixedThreadPool(3);
ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
for (int i = 0; i < 10; i++)
{
completionService.submit(new Callable<String>()
{
@Override
public String call()
throws Exception
{
return "gogo" + UUID.randomUUID().toString();
}
});
}
System.out.println("before result...");
for (int i = 0; i < 10; i++)
{
System.out.println("future get result:" + completionService.take().get());
}
System.out.println("after result...");
}
/**
* 2.submit一个callable,支持返回值
* <pre>
* before result...
* future get result:hello:pool-1-thread-1
* after result...
* </pre>
*/
private static void test2()
throws ExecutionException, InterruptedException
{
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future<String> future = executorService.submit(new Callable<String>()
{
@Override
public String call()
throws Exception
{
sleepOneMoment(3000);
return "hello:" + Thread.currentThread().getName();
}
});
System.out.println("before result...");
System.out.println("future get result:" + future.get());
System.out.println("after result...");
}
/**
* 1.submit一个Runnable
* 由于Runnable返回值是void,所以无法设置返回值
* -------------------------
* <pre>
* before result...
* this will return null
* future1 get result:null
* this will return T
* future2 get result:ironMan
* after result...
* </pre>
*/
private static void test1()
throws ExecutionException, InterruptedException
{
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future future1 = executorService.submit(new Runnable()
{
@Override
public void run()
{
sleepOneMoment(1000);
System.out.println("this will return null");
}
});
Future<String> future2 = executorService.submit(new Runnable()
{
@Override
public void run()
{
sleepOneMoment(3000);
System.out.println("this will return ironMan");
}
}, "ironMan");
System.out.println("before result...");
System.out.println("future1 get result:" + future1.get());
System.out.println("future2 get result:" + future2.get());
System.out.println("after result...");
}
private static void sleepOneMoment(int n)
{
try
{
Thread.sleep(n);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
|
java/thread/learn/CallableAndFutureDemo.java
|
Create CallableAndFutureDemo.java
|
java/thread/learn/CallableAndFutureDemo.java
|
Create CallableAndFutureDemo.java
|
|
Java
|
mit
|
error: pathspec 'src/main/java/com/hackerrank/FindDigits.java' did not match any file(s) known to git
|
5f2ebcf12ad1dad9e019ef08ab053cd9c854cd95
| 1
|
iluu/algs-progfun,iluu/algs-progfun
|
package com.hackerrank;
import java.util.Scanner;
public class FindDigits {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
int number = in.nextInt();
System.out.println(divisibleDigits(number));
}
}
private static int divisibleDigits(int no) {
int iter = no;
int result = 0;
while (iter > 0) {
int digit = iter % 10;
if (digit != 0 && no % digit == 0) {
result++;
}
iter = iter / 10;
}
return result;
}
}
|
src/main/java/com/hackerrank/FindDigits.java
|
Find Digits - HR - E
|
src/main/java/com/hackerrank/FindDigits.java
|
Find Digits - HR - E
|
|
Java
|
mit
|
error: pathspec 'algorithms/sorting/RunningTimeOfAlgorithms.java' did not match any file(s) known to git
|
7306ff1f234323ba88e4cc885f6899b7304d082e
| 1
|
RCoon/HackerRank,RCoon/HackerRank,RCoon/HackerRank
|
package algorithms.sorting;
import java.util.*;
/*
* Problem Statement:
* In the previous challenges you created an Insertion Sort algorithm. It is a
* simple sorting algorithm that works well with small or mostly sorted data.
* However, it takes a long time to sort large unsorted data. To see why, we
* will analyze its running time.
*
* Challenge:
* Can you modify your previous Insertion Sort implementation to keep track of
* the number of shifts it makes while sorting? The only thing you should print
* is the number of shifts made by the algorithm to completely sort the array. A
* shift occurs when an element's position changes in the array. Do not shift an
* element if it is not necessary.
*
* Input Format:
* The first line contains N, the number of elements to be sorted. The next line
* contains N integers a[1], a[2], ..., a[N].
*
* Output Format:
* Output the number of shifts it takes to sort the array.
*
* Constraints:
* 1 <= N <= 1001
* -10000 <= x <= 10000, x is an element of a
*
* Sample Input:
* 5
* 2 1 3 1 2
*
* Sample Output:
* 4
*/
public class RunningTimeOfAlgorithms {
public static void insertIntoSorted(int[] ar) {
int numShifts = 0;
for (int top = 1; top < ar.length; top++) {
int temp = ar[top]; // copy that item into temp variable
int pos = top - 1;
while (pos >= 0 && ar[pos] > temp) {
// move items that are bigger than temp up one position
ar[pos+1] = ar[pos];
pos--;
numShifts++;
}
ar[pos + 1] = temp; // place temp into last vacated position
}
System.out.println(numShifts);
}
/* Tail starts here */
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertIntoSorted(ar);
in.close();
}
}
|
algorithms/sorting/RunningTimeOfAlgorithms.java
|
Add RunningTimeOfAlgorithms
|
algorithms/sorting/RunningTimeOfAlgorithms.java
|
Add RunningTimeOfAlgorithms
|
|
Java
|
mit
|
error: pathspec 'src/test/java/com/conveyal/r5/api/util/AnglesTest.java' did not match any file(s) known to git
|
26f1a3005d4574583cf27ccd5a5113ce52b23b7c
| 1
|
conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5
|
package com.conveyal.r5.api.util;
import com.conveyal.r5.common.DirectionUtils;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
/**
* Created by mabu on 1.6.2016.
*/
@RunWith(Parameterized.class)
public class AnglesTest {
private final double delta = 0.01;
private double angle;
private LineString lineString;
private LineString reverseLine;
private static WKTReader wktReader;
@Parameterized.Parameters(name="angle {0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
//Cheap ruler:
/* { -179 ," LINESTRING(15.6455 46.557611,15.645318121064939 46.550415296467214,15.645272651331172 46.54861637058402) "},
//{ -180 ," LINESTRING(15.6455 46.557611,15.6455 46.550414200359775,15.6455 46.548615000449715) "},
{ -165 ," LINESTRING(15.6455 46.557611,15.642802736876652 46.55065942536088,15.642128421095816 46.5489215317011) "},
{ -150 ," LINESTRING(15.6455 46.557611,15.640289287777723 46.55137838868561,15.638986609722153 46.54982023585702) "},
{ -135 ," LINESTRING(15.6455 46.557611,15.638130940105631 46.55252209417156,15.63628867513204 46.551249867714446) "},
{ -120 ," LINESTRING(15.6455 46.557611,15.636474781687395 46.55401260017989,15.634218477109243 46.55311300022486) "},
{ -105 ," LINESTRING(15.6455 46.557611,15.635433676982284 46.55574833118932,15.632917096227855 46.55528266398665) "},
{ -90 ," LINESTRING(15.6455 46.557611,15.635078575555445 46.557611,15.632473219444305 46.557611) "},
{ -75 ," LINESTRING(15.6455 46.557611,15.635433676982284 46.55947366881068,15.632917096227855 46.55993933601335) "},
{ -60 ," LINESTRING(15.6455 46.557611,15.636474781687395 46.561209399820115,15.634218477109243 46.56210899977514) "},
{ -45 ," LINESTRING(15.6455 46.557611,15.638130940105631 46.562699905828445,15.63628867513204 46.563972132285556) "},
{ -30 ," LINESTRING(15.6455 46.557611,15.640289287777723 46.56384361131439,15.638986609722153 46.56540176414298) "},
{ -15 ," LINESTRING(15.6455 46.557611,15.642802736876652 46.564562574639126,15.642128421095816 46.566300468298905) "},
{ 0 ," LINESTRING(15.6455 46.557611,15.6455 46.56480779964023,15.6455 46.56660699955029) "},
{ 15 ," LINESTRING(15.6455 46.557611,15.648197263123349 46.564562574639126,15.648871578904185 46.566300468298905) "},
{ 30 ," LINESTRING(15.6455 46.557611,15.650710712222278 46.56384361131439,15.652013390277848 46.56540176414298) "},
{ 45 ," LINESTRING(15.6455 46.557611,15.65286905989437 46.562699905828445,15.65471132486796 46.563972132285556) "},
{ 60 ," LINESTRING(15.6455 46.557611,15.654525218312605 46.561209399820115,15.656781522890757 46.56210899977514) "},
{ 75 ," LINESTRING(15.6455 46.557611,15.655566323017716 46.55947366881068,15.658082903772145 46.55993933601335) "},
{ 90 ," LINESTRING(15.6455 46.557611,15.655921424444555 46.557611,15.658526780555695 46.557611) "},
{ 105 ," LINESTRING(15.6455 46.557611,15.655566323017716 46.55574833118932,15.658082903772145 46.55528266398665) "},
{ 120 ," LINESTRING(15.6455 46.557611,15.654525218312605 46.55401260017989,15.656781522890757 46.55311300022486) "},
{ 135 ," LINESTRING(15.6455 46.557611,15.65286905989437 46.55252209417156,15.65471132486796 46.551249867714446) "},
{ 150 ," LINESTRING(15.6455 46.557611,15.650710712222278 46.55137838868561,15.652013390277848 46.54982023585702) "},
{ 165 ," LINESTRING(15.6455 46.557611,15.648197263123349 46.55065942536088,15.648871578904185 46.5489215317011) "},
{ 180 ," LINESTRING(15.6455 46.557611,15.6455 46.550414200359775,15.6455 46.548615000449715) "}, */
//Turf:
{ -179 ," LINESTRING(15.6455 46.557611,15.645317478134713 46.55041978026114,15.645271855225554 46.54862197528108) "},
//{ -180 ," LINESTRING(15.6455 46.557611,15.645500000000002 46.550418684981885,15.645500000000002 46.54862060622736) "},
{ -165 ," LINESTRING(15.6455 46.557611,15.642793190059745 46.55066372524829,15.642116595847229 46.54892689658591) "},
{ -150 ," LINESTRING(15.6455 46.557611,15.640270775520289 46.55138215333488,15.638963656945254 46.549824904441955) "},
{ -135 ," LINESTRING(15.6455 46.557611,15.638104604080235 46.55252502697691,15.636255971680814 46.55125345926329) "},
{ -120 ," LINESTRING(15.6455 46.557611,15.636442278176375 46.55401448502616,15.634178035314534 46.55311524458698) "},
{ -105 ," LINESTRING(15.6455 46.557611,15.635397101100212 46.55574904718423,15.632871484715526 46.55528342001593) "},
{ -90 ," LINESTRING(15.6455 46.557611,15.635040350609943 46.557610523339264,15.632425438305495 46.5576102552176) "},
{ -75 ," LINESTRING(15.6455 46.557611,15.6353964079014 46.55947206335472,15.632870401592394 46.55993719020118) "},
{ -60 ," LINESTRING(15.6455 46.557611,15.6364410775208 46.56120679998273,15.63417615929021 46.56210563823941) "},
{ -45 ," LINESTRING(15.6455 46.557611,15.638103217682579 46.56269649636235,15.636253805434473 46.5639677959543) "},
{ -30 ," LINESTRING(15.6455 46.557611,15.640269574864686 46.56383960833476,15.638961780920855 46.565396723166835) "},
{ -15 ," LINESTRING(15.6455 46.557611,15.642792496860903 46.56455821089129,15.642115512724018 46.56629500363218) "},
{ 0 ," LINESTRING(15.6455 46.557611,15.645500000000002 46.564803315018125,15.645500000000002 46.56660139377266) "},
{ 15 ," LINESTRING(15.6455 46.557611,15.648207503139101 46.56455821089129,15.648884487275986 46.56629500363218) "},
{ 30 ," LINESTRING(15.6455 46.557611,15.650730425135318 46.56383960833476,15.652038219079149 46.565396723166835) "},
{ 45 ," LINESTRING(15.6455 46.557611,15.652896782317425 46.56269649636235,15.654746194565531 46.5639677959543) "},
{ 60 ," LINESTRING(15.6455 46.557611,15.654558922479204 46.56120679998273,15.656823840709794 46.56210563823941) "},
{ 75 ," LINESTRING(15.6455 46.557611,15.655603592098604 46.55947206335472,15.65812959840761 46.55993719020118) "},
{ 90 ," LINESTRING(15.6455 46.557611,15.655959649390061 46.557610523339264,15.65857456169451 46.5576102552176) "},
{ 105 ," LINESTRING(15.6455 46.557611,15.655602898899792 46.55574904718423,15.658128515284478 46.55528342001593) "},
{ 120 ," LINESTRING(15.6455 46.557611,15.654557721823629 46.55401448502616,15.656821964685472 46.55311524458698) "},
{ 135 ," LINESTRING(15.6455 46.557611,15.652895395919769 46.55252502697691,15.65474402831919 46.55125345926329) "},
{ 150 ," LINESTRING(15.6455 46.557611,15.650729224479715 46.55138215333488,15.65203634305475 46.549824904441955) "},
{ 165 ," LINESTRING(15.6455 46.557611,15.648206809940259 46.55066372524829,15.648883404152777 46.54892689658591) "},
{ 180 ," LINESTRING(15.6455 46.557611,15.645500000000002 46.550418684981885,15.645500000000002 46.54862060622736) "},
});
}
@BeforeClass
public static void setUpClass() throws Exception {
wktReader = new WKTReader();
}
public AnglesTest(int angle, String wktlineString) throws ParseException {
this.angle = angle;
this.lineString = (LineString) wktReader.read(wktlineString);
this.reverseLine = (LineString) this.lineString.reverse();
}
@Test
public void testFirstAngle() throws Exception {
Assert.assertEquals(angle, DirectionUtils.getFirstAngle(lineString), delta);
//Assert.assertEquals(angle, 180+DirectionUtils.getLastAngle(reverseLine), delta);
}
@Test
public void testLastAngle() throws Exception {
Assert.assertEquals(angle, DirectionUtils.getLastAngle(lineString), delta);
}
}
|
src/test/java/com/conveyal/r5/api/util/AnglesTest.java
|
Add tests for angles
|
src/test/java/com/conveyal/r5/api/util/AnglesTest.java
|
Add tests for angles
|
|
Java
|
mit
|
error: pathspec 'src/ca/eandb/jmist/framework/display/CompositeDisplay.java' did not match any file(s) known to git
|
1414da213e7c5e81a4e53b5767a490b5a3d80785
| 1
|
bwkimmel/jmist
|
/**
*
*/
package ca.eandb.jmist.framework.display;
import java.util.ArrayList;
import java.util.List;
import ca.eandb.jmist.framework.Display;
import ca.eandb.jmist.framework.Raster;
import ca.eandb.jmist.framework.color.Color;
import ca.eandb.jmist.framework.color.ColorModel;
/**
* A <code>Display</code> that forwards methods to each of a collection of
* child <code>Display</code>s.
*
* @author Brad Kimmel
*/
public final class CompositeDisplay implements Display {
/** The <code>List</code> of child <code>Display</code>s to draw to. */
private final List<Display> children = new ArrayList<Display>();
/**
* Adds a new child <code>Display</code>.
* @param child The <code>Display</code> to add to the list.
* @return A reference to this <code>CompositeDisplay</code>.
*/
public CompositeDisplay addDisplay(Display child) {
children.add(child);
return this;
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.Display#fill(int, int, int, int, ca.eandb.jmist.framework.color.Color)
*/
public void fill(int x, int y, int w, int h, Color color) {
for (Display child : children) {
child.fill(x, y, w, h, color);
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.Display#finish()
*/
public void finish() {
for (Display child : children) {
child.finish();
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.Display#initialize(int, int, ca.eandb.jmist.framework.color.ColorModel)
*/
public void initialize(int w, int h, ColorModel colorModel) {
for (Display child : children) {
child.initialize(w, h, colorModel);
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.Display#setPixel(int, int, ca.eandb.jmist.framework.color.Color)
*/
public void setPixel(int x, int y, Color pixel) {
for (Display child : children) {
child.setPixel(x, y, pixel);
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.Display#setPixels(int, int, ca.eandb.jmist.framework.Raster)
*/
public void setPixels(int x, int y, Raster pixels) {
for (Display child : children) {
child.setPixels(x, y, pixels);
}
}
}
|
src/ca/eandb/jmist/framework/display/CompositeDisplay.java
|
Adding CompositeDisplay.
|
src/ca/eandb/jmist/framework/display/CompositeDisplay.java
|
Adding CompositeDisplay.
|
|
Java
|
mit
|
error: pathspec 'src/com/coderevisited/arrays/LargestSubArrayContiguous.java' did not match any file(s) known to git
|
bb77eeee78c51ae54061381957f0bb2e4c9a55ef
| 1
|
sureshsajja/CodeRevisited,sureshsajja/CodingProblems
|
package com.coderevisited.arrays;
/**
* Run two loops, i start from 0 to n-2, j start from i+1 to n-1
* Assume sub array starts at i and ends at j.
* for each iteration, update min and max in the sub array
* If max - min == j - i, that is the sub array with contiguous elements. Update maxLength
*/
public class LargestSubArrayContiguous
{
public static void main(String[] args)
{
int[] array = new int[]{1, 56, 58, 57, 90, 92, 94, 93, 91, 45};
int length = findMaxLengthSubArray(array);
System.out.println("Size Largest sub Array With contiguous elements " + length);
}
private static int findMaxLengthSubArray(int[] array)
{
int maxLength = 1;
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int max = array[i];
for (int j = i + 1; j < array.length; j++) {
if (min > array[j]) {
min = array[j];
}
if (max < array[j]) {
max = array[j];
}
if (max - min == j - i) {
if (j - i > maxLength)
maxLength = j - i + 1;
}
}
}
return maxLength;
}
}
|
src/com/coderevisited/arrays/LargestSubArrayContiguous.java
|
Largest sub array with contiguous elements
|
src/com/coderevisited/arrays/LargestSubArrayContiguous.java
|
Largest sub array with contiguous elements
|
|
Java
|
mit
|
error: pathspec 'src/android/com/google/android/gcm/GCMBroadcastReceiver.java' did not match any file(s) known to git
|
180271c794c1fc1f0765999e64a0c1c912dd2305
| 1
|
connectedhome/Plugin_NotifyPush,connectedhome/Plugin_NotifyPush,connectedhome/Plugin_NotifyPush
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.gcm;
import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* {@link BroadcastReceiver} that receives GCM messages and delivers them to
* an application-specific {@link GCMBaseIntentService} subclass.
* <p>
* By default, the {@link GCMBaseIntentService} class belongs to the application
* main package and is named
* {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class,
* the {@link #getGCMIntentServiceClassName(Context)} must be overridden.
*/
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "GCMBroadcastReceiver";
private static boolean mReceiverSet = false;
@Override
public final void onReceive(Context context, Intent intent) {
Log.v(TAG, "onReceive: " + intent.getAction());
// do a one-time check if app is using a custom GCMBroadcastReceiver
if (!mReceiverSet) {
mReceiverSet = true;
String myClass = getClass().getName();
if (!myClass.equals(GCMBroadcastReceiver.class.getName())) {
GCMRegistrar.setRetryReceiverClassName(myClass);
}
}
String className = getGCMIntentServiceClassName(context);
Log.v(TAG, "GCM IntentService class: " + className);
// Delegates to the application-specific intent service.
GCMBaseIntentService.runIntentInService(context, intent, className);
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
/**
* Gets the class name of the intent service that will handle GCM messages.
*/
protected String getGCMIntentServiceClassName(Context context) {
return getDefaultIntentServiceClassName(context);
}
/**
* Gets the default class name of the intent service that will handle GCM
* messages.
*/
static final String getDefaultIntentServiceClassName(Context context) {
String className = context.getPackageName() +
DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
}
|
src/android/com/google/android/gcm/GCMBroadcastReceiver.java
|
Create GCMBroadcastReceiver.java
Broadcasr Recceiver that receives GCM messages and delivers them to an application-specific {@link GCMBaseIntentService} subclass.
|
src/android/com/google/android/gcm/GCMBroadcastReceiver.java
|
Create GCMBroadcastReceiver.java
|
|
Java
|
mit
|
error: pathspec 'src/test/java/de/bmoth/modelchecker/ModelCheckerResultTest.java' did not match any file(s) known to git
|
a3f674111fa2b4e4a73885105c8d65544b041388
| 1
|
hhu-stups/bmoth
|
package de.bmoth.modelchecker;
import com.microsoft.z3.Expr;
import de.bmoth.TestUsingZ3;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ModelCheckerResultTest extends TestUsingZ3 {
State firstState;
State secondState;
State thirdState;
String correct = "correct";
String unknonw = "check-sat ...";
String invalid = "loremIpsum";
@Before
public void init() {
HashMap<String, Expr> firstMap = new HashMap<>();
HashMap<String, Expr> secondMap = new HashMap<>();
HashMap<String, Expr> thirdMap = new HashMap<>();
firstMap.put("x", z3Context.mkInt(10));
secondMap.put("x", z3Context.mkInt(11));
thirdMap.put("x", z3Context.mkInt(12));
thirdState = new State(null, thirdMap);
secondState = new State(thirdState, secondMap);
firstState = new State(secondState, firstMap);
}
@Test
public void testIsCorrect() {
ModelCheckingResult resultCorrect = new ModelCheckingResult(correct);
ModelCheckingResult resultIncorrectUnknown = new ModelCheckingResult(unknonw);
ModelCheckingResult resultIncorrectPath = new ModelCheckingResult(firstState);
assertTrue(resultCorrect.isCorrect());
assertFalse(resultIncorrectUnknown.isCorrect());
assertFalse(resultIncorrectPath.isCorrect());
}
@Test
public void testGetLastState() {
ModelCheckingResult resultIncorrectPath = new ModelCheckingResult(firstState);
assertEquals(firstState, resultIncorrectPath.getLastState());
}
@Test
public void testGetPath() {
assertEquals("[" + secondState + ", " + thirdState.toString() + "]", ModelCheckingResult.getPath(firstState).toString());
}
@Test
public void testGetMessage() {
ModelCheckingResult resultIncorrectUnknown = new ModelCheckingResult(unknonw);
ModelCheckingResult resultIncorrectInvaild = new ModelCheckingResult(invalid);
assertEquals(unknonw, resultIncorrectUnknown.getMessage());
assertEquals("", resultIncorrectInvaild.getMessage());
}
}
|
src/test/java/de/bmoth/modelchecker/ModelCheckerResultTest.java
|
added tests for ModelCheckingResult
|
src/test/java/de/bmoth/modelchecker/ModelCheckerResultTest.java
|
added tests for ModelCheckingResult
|
|
Java
|
mit
|
error: pathspec 'SwissAffinity/app/src/androidTest/java/ch/epfl/sweng/swissaffinity/utilities/network/users/UserClientExceptionTest.java' did not match any file(s) known to git
|
eb4c4943404820e90b67a53d8313adae3ecbbb07
| 1
|
furkansahin/team-heart-coders-public
|
package ch.epfl.sweng.swissaffinity.utilities.network.users;
import org.junit.Test;
/**
* Created by Lionel on 10/12/15.
*/
public class UserClientExceptionTest {
@Test(expected = UserClientException.class)
public void testDefaultConstructor() throws UserClientException {
throw new UserClientException("test");
}
@Test(expected = UserClientException.class)
public void testConstructor() throws UserClientException {
throw new UserClientException(new Exception());
}
}
|
SwissAffinity/app/src/androidTest/java/ch/epfl/sweng/swissaffinity/utilities/network/users/UserClientExceptionTest.java
|
add UserClientException Test
|
SwissAffinity/app/src/androidTest/java/ch/epfl/sweng/swissaffinity/utilities/network/users/UserClientExceptionTest.java
|
add UserClientException Test
|
|
Java
|
epl-1.0
|
error: pathspec 'core/plugins/org.csstudio.ui.util/src/org/csstudio/ui/util/PopupMenuUtil.java' did not match any file(s) known to git
|
07cafa4267d6dc98acc63ed07ada3ae23611354c
| 1
|
ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio
|
package org.csstudio.ui.util;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
/**
* Utility class to register context pop-up menus.
* <p>
* In Eclipse RCP, pop-up have to be independently defined and attached for each part.
* This class provides utility method to register the pop-ups so that it's
* easier and more consistent through-out CSS.
*
* @author carcassi
*/
public class PopupMenuUtil {
/**
* Use this to install a pop-up for a view where the contribution are all taken
* from the extension mechanism.
*
* @param control component that will host the pop-up menu
* @param viewSite the view site that hosts the view
* @param selectionProvider the selection used to create the context menu
*/
public static void installPopupForView(Control control, IWorkbenchPartSite viewSite,
ISelectionProvider selectionProvider) {
MenuManager menuMgr = new MenuManager();
menuMgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
Menu menu = menuMgr.createContextMenu(control);
control.setMenu(menu);
viewSite.registerContextMenu(menuMgr, selectionProvider);
viewSite.setSelectionProvider(selectionProvider);
}
}
|
core/plugins/org.csstudio.ui.util/src/org/csstudio/ui/util/PopupMenuUtil.java
|
o.c.ui.util: adding PopupMenuUtil
|
core/plugins/org.csstudio.ui.util/src/org/csstudio/ui/util/PopupMenuUtil.java
|
o.c.ui.util: adding PopupMenuUtil
|
|
Java
|
apache-2.0
|
7ecd1184ef08c07a1130f2949773a1760708b654
| 0
|
flowbywind/guava,Yijtx/guava,RoliMG/guava,mway08/guava,tli2/guava,thinker-fang/guava,xasx/guava,Akshay77/guava,mgalushka/guava,marstianna/guava,dnrajugade/guava-libraries,AnselQiao/guava,rcpoison/guava,VikingDen/guava,monokurobo/guava,npvincent/guava,allalizaki/guava-libraries,montycheese/guava,berndhopp/guava,weihungliu/guava,Xaerxess/guava,tailorlala/guava-libraries,chen870647924/guava-libraries,dushmis/guava,taoguan/guava,typetools/guava,cklsoft/guava,dushmis/guava,licheng-xd/guava,baratali/guava,mohanaraosv/guava,jsnchen/guava,10045125/guava,lijunhuayc/guava,cgdecker/guava,aiyanbo/guava,baratali/guava,sunbeansoft/guava,mengdiwang/guava-libraries,janus-project/guava.janusproject.io,njucslqq/guava,BollyCheng/guava,juneJuly/guava,gmaes/guava,rcpoison/guava,cklsoft/guava,yigubigu/guava,pwz3n0/guava,mosoft521/guava,VikingDen/guava,dpursehouse/guava,jiteshmohan/guava,GitHub4Lgfei/guava,huangsihuan/guava,sebadiaz/guava,yigubigu/guava,gvikei/guava-libraries,sensui/guava-libraries,EdwardLee03/guava,fengshao0907/guava,ChengLong/guava,kaoudis/guava,kingland/guava,tunzao/guava,liyazhou/guava,monokurobo/guava,dmi3aleks/guava,mkodekar/guava-libraries,codershamo/guava,tunzao/guava,GabrielNicolasAvellaneda/guava,XiWenRen/guava,leogong/guava,Xaerxess/guava,XiWenRen/guava,leesir/guava,manolama/guava,mbarbero/guava-libraries,Akshay77/guava,weihungliu/guava,KengoTODA/guava,norru/guava,allenprogram/guava,thinker-fang/guava,RoliMG/guava,google/guava,aditya-chaturvedi/guava,DavesMan/guava,Overruler/guava-libraries,0359xiaodong/guava,DucQuang1/guava,jedyang/guava,DavesMan/guava,jsnchen/guava,google/guava,maidh91/guava-libraries,r4-keisuke/guava,dnrajugade/guava-libraries,rob3ns/guava,Balzanka/guava-libraries,zcwease/guava-libraries,ningg/guava,jamesbrowder/guava-libraries,aditya-chaturvedi/guava,paplorinc/guava,fengshao0907/guava,sarvex/guava,yuan232007/guava,0359xiaodong/guava,elijah513/guava,disc99/guava,rob3ns/guava,tailorlala/guava-libraries,typetools/guava,5A68656E67/guava,uschindler/guava,licheng-xd/guava,lisb/guava,sander120786/guava-libraries,norru/guava,r4-keisuke/guava,AnselQiao/guava,BollyCheng/guava,nulakasatish/guava-libraries,qingsong-xu/guava,mosoft521/guava,lisb/guava,pwz3n0/guava,cogitate/guava-libraries,scr/guava,m3n78am/guava,yf0994/guava-libraries,Yijtx/guava,anigeorge/guava,hannespernpeintner/guava,mgedigian/guava-bloom-filter,GabrielNicolasAvellaneda/guava,Kevin2030/guava,1yvT0s/guava,zcwease/guava-libraries,m3n78am/guava,HarveyTvT/guava,kingland/guava,taoguan/guava,danielnorberg/guava-libraries,gmaes/guava,allenprogram/guava,DaveAKing/guava-libraries,leesir/guava,witekcc/guava,okaywit/guava-libraries,kucci/guava-libraries,HarveyTvT/guava,tli2/guava,npvincent/guava,mgalushka/guava,renchunxiao/guava,clcron/guava-libraries,levenhdu/guava,mohanaraosv/guava,witekcc/guava,SaintBacchus/guava,Balzanka/guava-libraries,sunbeansoft/guava,SyllaJay/guava,clcron/guava-libraries,SyllaJay/guava,fengshao0907/guava-libraries,kaoudis/guava,jayhetee/guava,jamesbrowder/guava-libraries,yanyongshan/guava,chen870647924/guava-libraries,KengoTODA/guava,jackyglony/guava,DucQuang1/guava,mosoft521/guava,Ranjodh-Singh/ranjodh87-guavalib,jedyang/guava,abel-von/guava,juneJuly/guava,jackyglony/guava,rgoldberg/guava,allalizaki/guava-libraries,ChengLong/guava,eidehua/guava,5A68656E67/guava,renchunxiao/guava,levenhdu/guava,dubu/guava-libraries,sensui/guava-libraries,DaveAKing/guava-libraries,lijunhuayc/guava,GitHub4Lgfei/guava,okaywit/guava-libraries,tobecrazy/guava,maidh91/guava-libraries,mbarbero/guava-libraries,njucslqq/guava,1yvT0s/guava,Ranjodh-Singh/ranjodh87-guavalib,sander120786/guava-libraries,ceosilvajr/guava,SaintBacchus/guava,nulakasatish/guava-libraries,mkodekar/guava-libraries,dubu/guava-libraries,elijah513/guava,easyfmxu/guava,ben-manes/guava,berndhopp/guava,jakubmalek/guava,Kevin2030/guava,janus-project/guava.janusproject.io,paddx01/guava-src,yuan232007/guava,jakubmalek/guava,tobecrazy/guava,seanli310/guava,huangsihuan/guava,xueyin87/guava-libraries,KengoTODA/guava-libraries,Overruler/guava-libraries,kucci/guava-libraries,aiyanbo/guava,disc99/guava,jankill/guava,yf0994/guava-libraries,EdwardLee03/guava,qingsong-xu/guava,binhvu7/guava,xueyin87/guava-libraries,ignaciotcrespo/guava,ignaciotcrespo/guava,leogong/guava,hannespernpeintner/guava,gvikei/guava-libraries,lgscofield/guava,marstianna/guava,paplorinc/guava,jiteshmohan/guava,Haus1/guava-libraries,paddx01/guava-src,easyfmxu/guava,yangxu998/guava-libraries,rgoldberg/guava,montycheese/guava,anigeorge/guava,manolama/guava,Haus1/guava-libraries,kgislsompo/guava-libraries,google/guava,fengshao0907/guava-libraries,scr/guava,mengdiwang/guava-libraries,codershamo/guava,seanli310/guava,abel-von/guava,mway08/guava,yangxu998/guava-libraries,KengoTODA/guava-libraries,Ariloum/guava,dpursehouse/guava,jayhetee/guava,liyazhou/guava,kgislsompo/guava-libraries,eidehua/guava,jankill/guava,cogitate/guava-libraries,flowbywind/guava,lgscofield/guava,xasx/guava,yanyongshan/guava,ningg/guava,sebadiaz/guava,Ariloum/guava
|
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* A synchronization abstraction supporting waiting on arbitrary boolean conditions.
*
* <p>This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor}
* is less error-prone and more readable than code using {@code ReentrantLock}, without significant
* performance loss. {@code Monitor} even has the potential for performance gain by optimizing the
* evaluation and signaling of conditions. Signaling is entirely
* <a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)#Implicit_signaling">
* implicit</a>.
* By eliminating explicit signaling, this class can guarantee that only one thread is awakened
* when a condition becomes true (no "signaling storms" due to use of {@link
* java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost
* (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal
* Condition.signal}).
*
* <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet
* <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also
* reentrant, so a thread may enter a monitor any number of times, and then must leave the same
* number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization
* semantics as the built-in Java language synchronization primitives.
*
* <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be
* followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the
* monitor cleanly: <pre> {@code
*
* monitor.enter();
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }}</pre>
*
* A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always appear as
* the condition of an <i>if</i> statement containing a <i>try/finally</i> block to ensure that the
* current thread leaves the monitor cleanly: <pre> {@code
*
* if (monitor.tryEnter()) {
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }
* } else {
* // do other things since the monitor was not available
* }}</pre>
*
* <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2>
*
* <p>The following examples show a simple threadsafe holder expressed using {@code synchronized},
* {@link ReentrantLock}, and {@code Monitor}.
*
* <h3>{@code synchronized}</h3>
*
* <p>This version is the fewest lines of code, largely because the synchronization mechanism used
* is built into the language and runtime. But the programmer has to remember to avoid a couple of
* common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and
* {@code notifyAll()} must be used instead of {@code notify()} because there are two different
* logical conditions being awaited. <pre> {@code
*
* public class SafeBox<V> {
* private V value;
*
* public synchronized V get() throws InterruptedException {
* while (value == null) {
* wait();
* }
* V result = value;
* value = null;
* notifyAll();
* return result;
* }
*
* public synchronized void set(V newValue) throws InterruptedException {
* while (value != null) {
* wait();
* }
* value = newValue;
* notifyAll();
* }
* }}</pre>
*
* <h3>{@code ReentrantLock}</h3>
*
* <p>This version is much more verbose than the {@code synchronized} version, and still suffers
* from the need for the programmer to remember to use {@code while} instead of {@code if}.
* However, one advantage is that we can introduce two separate {@code Condition} objects, which
* allows us to use {@code signal()} instead of {@code signalAll()}, which may be a performance
* benefit. <pre> {@code
*
* public class SafeBox<V> {
* private final ReentrantLock lock = new ReentrantLock();
* private final Condition valuePresent = lock.newCondition();
* private final Condition valueAbsent = lock.newCondition();
* private V value;
*
* public V get() throws InterruptedException {
* lock.lock();
* try {
* while (value == null) {
* valuePresent.await();
* }
* V result = value;
* value = null;
* valueAbsent.signal();
* return result;
* } finally {
* lock.unlock();
* }
* }
*
* public void set(V newValue) throws InterruptedException {
* lock.lock();
* try {
* while (value != null) {
* valueAbsent.await();
* }
* value = newValue;
* valuePresent.signal();
* } finally {
* lock.unlock();
* }
* }
* }}</pre>
*
* <h3>{@code Monitor}</h3>
*
* <p>This version adds some verbosity around the {@code Guard} objects, but removes that same
* verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the
* same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above.
* Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to
* remember to use {@code while} instead of {@code if}. <pre> {@code
*
* public class SafeBox<V> {
* private final Monitor monitor = new Monitor();
* private final Monitor.Guard valuePresent = new Monitor.Guard(monitor) {
* public boolean isSatisfied() {
* return value != null;
* }
* };
* private final Monitor.Guard valueAbsent = new Monitor.Guard(monitor) {
* public boolean isSatisfied() {
* return value == null;
* }
* };
* private V value;
*
* public V get() throws InterruptedException {
* monitor.enterWhen(valuePresent);
* try {
* V result = value;
* value = null;
* return result;
* } finally {
* monitor.leave();
* }
* }
*
* public void set(V newValue) throws InterruptedException {
* monitor.enterWhen(valueAbsent);
* try {
* value = newValue;
* } finally {
* monitor.leave();
* }
* }
* }}</pre>
*
* @author Justin T. Sampson
* @since 10.0
*/
@Beta
public final class Monitor {
// TODO: Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock.
/**
* A boolean condition for which a thread may wait. A {@code Guard} is associated with a single
* {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying
* the monitor, so code should not be written to rely on how often a guard might or might not be
* checked.
*
* <p>If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is
* associated with, an {@link IllegalMonitorStateException} is thrown.
*
* @since 10.0
*/
@Beta
public abstract static class Guard {
final Monitor monitor;
final Condition condition;
@GuardedBy("monitor.lock")
int waiterCount = 0;
protected Guard(Monitor monitor) {
this.monitor = checkNotNull(monitor, "monitor");
this.condition = monitor.lock.newCondition();
}
/**
* Evaluates this guard's boolean condition. This method is always called with the associated
* monitor already occupied. Implementations of this method must depend only on state protected
* by the associated monitor, and must not modify that state.
*/
public abstract boolean isSatisfied();
@Override
public final boolean equals(Object other) {
// Overridden as final to ensure identity semantics in Monitor.activeGuards.
return this == other;
}
@Override
public final int hashCode() {
// Overridden as final to ensure identity semantics in Monitor.activeGuards.
return super.hashCode();
}
}
/**
* Whether this monitor is fair.
*/
private final boolean fair;
/**
* The lock underlying this monitor.
*/
private final ReentrantLock lock;
/**
* The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}).
* This is an ArrayList rather than, say, a HashSet so that iteration and almost all adds don't
* incur any object allocation overhead.
*/
@GuardedBy("lock")
private final ArrayList<Guard> activeGuards = Lists.newArrayListWithCapacity(1);
/**
* Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code
* Monitor(false)}.
*/
public Monitor() {
this(false);
}
/**
* Creates a monitor with the given ordering policy.
*
* @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but
* fast) one
*/
public Monitor(boolean fair) {
this.fair = fair;
this.lock = new ReentrantLock(fair);
}
/**
* Enters this monitor. Blocks indefinitely.
*/
public void enter() {
lock.lock();
}
/**
* Enters this monitor. Blocks indefinitely, but may be interrupted.
*/
public void enterInterruptibly() throws InterruptedException {
lock.lockInterruptibly();
}
/**
* Enters this monitor. Blocks at most the given time.
*
* @return whether the monitor was entered
*/
public boolean enter(long time, TimeUnit unit) {
long timeoutNanos = unit.toNanos(time);
final ReentrantLock lock = this.lock;
if (!fair && lock.tryLock()) {
return true;
}
long startNanos = System.nanoTime();
long remainingNanos = timeoutNanos;
boolean interruptIgnored = false;
try {
while (true) {
try {
return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException ignored) {
interruptIgnored = true;
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
}
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
/**
* Enters this monitor. Blocks at most the given time, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
return lock.tryLock(time, unit);
}
/**
* Enters this monitor if it is possible to do so immediately. Does not block.
*
* <p><b>Note:</b> This method disregards the fairness setting of this monitor.
*
* @return whether the monitor was entered
*/
public boolean tryEnter() {
return lock.tryLock();
}
/**
* Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.
*/
public void enterWhen(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean success = false;
lock.lockInterruptibly();
try {
waitInterruptibly(guard, reentrant);
success = true;
} finally {
if (!success) {
lock.unlock();
}
}
}
/**
* Enters this monitor when the guard is satisfied. Blocks indefinitely.
*/
public void enterWhenUninterruptibly(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean success = false;
lock.lock();
try {
waitUninterruptibly(guard, reentrant);
success = true;
} finally {
if (!success) {
lock.unlock();
}
}
}
/**
* Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
* the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
* interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
long remainingNanos;
if (!fair && lock.tryLock()) {
remainingNanos = unit.toNanos(time);
} else {
long startNanos = System.nanoTime();
if (!lock.tryLock(time, unit)) {
return false;
}
remainingNanos = unit.toNanos(time) - (System.nanoTime() - startNanos);
}
boolean satisfied = false;
try {
satisfied = waitInterruptibly(guard, remainingNanos, reentrant);
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor when the guard is satisfied. Blocks at most the given time, including
* both the time to acquire the lock and the time to wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean interruptIgnored = false;
try {
long remainingNanos;
if (!fair && lock.tryLock()) {
remainingNanos = unit.toNanos(time);
} else {
long startNanos = System.nanoTime();
long timeoutNanos = unit.toNanos(time);
remainingNanos = timeoutNanos;
while (true) {
try {
if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
break;
} else {
return false;
}
} catch (InterruptedException ignored) {
interruptIgnored = true;
} finally {
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
}
}
boolean satisfied = false;
try {
satisfied = waitUninterruptibly(guard, remainingNanos, reentrant);
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
/**
* Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but
* does not wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterIf(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
lock.lock();
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
* not wait for the guard to be satisfied, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
* lock, but does not wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterIf(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!enter(time, unit)) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
* lock, but does not wait for the guard to be satisfied, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!lock.tryLock(time, unit)) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
* block acquiring the lock and does not wait for the guard to be satisfied.
*
* <p><b>Note:</b> This method disregards the fairness setting of this monitor.
*
* @return whether the monitor was entered
*/
public boolean tryEnterIf(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!lock.tryLock()) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be
* called only by a thread currently occupying this monitor.
*/
public void waitFor(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
waitInterruptibly(guard, true);
}
/**
* Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread
* currently occupying this monitor.
*/
public void waitForUninterruptibly(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
waitUninterruptibly(guard, true);
}
/**
* Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted.
* May be called only by a thread currently occupying this monitor.
*
* @return whether the guard is now satisfied
*/
public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
return waitInterruptibly(guard, unit.toNanos(time), true);
}
/**
* Waits for the guard to be satisfied. Waits at most the given time. May be called only by a
* thread currently occupying this monitor.
*
* @return whether the guard is now satisfied
*/
public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
return waitUninterruptibly(guard, unit.toNanos(time), true);
}
/**
* Leaves this monitor. May be called only by a thread currently occupying this monitor.
*/
public void leave() {
final ReentrantLock lock = this.lock;
try {
// No need to signal if we will still be holding the lock when we return
if (lock.getHoldCount() == 1) {
signalConditionsOfSatisfiedGuards(null);
}
} finally {
lock.unlock(); // Will throw IllegalMonitorStateException if not held
}
}
/**
* Returns whether this monitor is using a fair ordering policy.
*/
public boolean isFair() {
return lock.isFair();
}
/**
* Returns whether this monitor is occupied by any thread. This method is designed for use in
* monitoring of the system state, not for synchronization control.
*/
public boolean isOccupied() {
return lock.isLocked();
}
/**
* Returns whether the current thread is occupying this monitor (has entered more times than it
* has left).
*/
public boolean isOccupiedByCurrentThread() {
return lock.isHeldByCurrentThread();
}
/**
* Returns the number of times the current thread has entered this monitor in excess of the number
* of times it has left. Returns 0 if the current thread is not occupying this monitor.
*/
public int getOccupiedDepth() {
return lock.getHoldCount();
}
/**
* Returns an estimate of the number of threads waiting to enter this monitor. The value is only
* an estimate because the number of threads may change dynamically while this method traverses
* internal data structures. This method is designed for use in monitoring of the system state,
* not for synchronization control.
*/
public int getQueueLength() {
return lock.getQueueLength();
}
/**
* Returns whether any threads are waiting to enter this monitor. Note that because cancellations
* may occur at any time, a {@code true} return does not guarantee that any other thread will ever
* enter this monitor. This method is designed primarily for use in monitoring of the system
* state.
*/
public boolean hasQueuedThreads() {
return lock.hasQueuedThreads();
}
/**
* Queries whether the given thread is waiting to enter this monitor. Note that because
* cancellations may occur at any time, a {@code true} return does not guarantee that this thread
* will ever enter this monitor. This method is designed primarily for use in monitoring of the
* system state.
*/
public boolean hasQueuedThread(Thread thread) {
return lock.hasQueuedThread(thread);
}
/**
* Queries whether any threads are waiting for the given guard to become satisfied. Note that
* because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee
* that the guard becoming satisfied in the future will awaken any threads. This method is
* designed primarily for use in monitoring of the system state.
*/
public boolean hasWaiters(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
lock.lock();
try {
return guard.waiterCount > 0;
} finally {
lock.unlock();
}
}
/**
* Returns an estimate of the number of threads waiting for the given guard to become satisfied.
* Note that because timeouts and interrupts may occur at any time, the estimate serves only as an
* upper bound on the actual number of waiters. This method is designed for use in monitoring of
* the system state, not for synchronization control.
*/
public int getWaitQueueLength(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
lock.lock();
try {
return guard.waiterCount;
} finally {
lock.unlock();
}
}
@GuardedBy("lock")
private void signalConditionsOfSatisfiedGuards(@Nullable Guard interruptedGuard) {
final ArrayList<Guard> guards = this.activeGuards;
final int guardCount = guards.size();
try {
for (int i = 0; i < guardCount; i++) {
Guard guard = guards.get(i);
if ((guard == interruptedGuard) && (guard.waiterCount == 1)) {
// That one waiter was just interrupted and is throwing InterruptedException rather than
// paying attention to the guard being satisfied, so find another waiter on another guard.
continue;
}
if (guard.isSatisfied()) {
guard.condition.signal();
return;
}
}
} catch (Throwable throwable) {
for (int i = 0; i < guardCount; i++) {
Guard guard = guards.get(i);
guard.condition.signalAll();
}
throw Throwables.propagate(throwable);
}
}
@GuardedBy("lock")
private void incrementWaiters(Guard guard) {
int waiters = guard.waiterCount++;
if (waiters == 0) {
activeGuards.add(guard);
}
}
@GuardedBy("lock")
private void decrementWaiters(Guard guard) {
int waiters = --guard.waiterCount;
if (waiters == 0) {
activeGuards.remove(guard);
}
}
@GuardedBy("lock")
private void waitInterruptibly(Guard guard, boolean signalBeforeWaiting)
throws InterruptedException {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
try {
condition.await();
} catch (InterruptedException interrupt) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
throw interrupt;
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
}
@GuardedBy("lock")
private void waitUninterruptibly(Guard guard, boolean signalBeforeWaiting) {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
condition.awaitUninterruptibly();
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
}
@GuardedBy("lock")
private boolean waitInterruptibly(Guard guard, long remainingNanos, boolean signalBeforeWaiting)
throws InterruptedException {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
if (remainingNanos <= 0) {
return false;
}
try {
remainingNanos = condition.awaitNanos(remainingNanos);
} catch (InterruptedException interrupt) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
throw interrupt;
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
return true;
}
@GuardedBy("lock")
private boolean waitUninterruptibly(Guard guard, long timeoutNanos,
boolean signalBeforeWaiting) {
if (!guard.isSatisfied()) {
long startNanos = System.nanoTime();
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
boolean interruptIgnored = false;
try {
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
long remainingNanos = timeoutNanos;
do {
if (remainingNanos <= 0) {
return false;
}
try {
remainingNanos = condition.awaitNanos(remainingNanos);
} catch (InterruptedException ignored) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
interruptIgnored = true;
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
return true;
}
}
|
guava/src/com/google/common/util/concurrent/Monitor.java
|
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* A synchronization abstraction supporting waiting on arbitrary boolean conditions.
*
* <p>This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor}
* is less error-prone and more readable than code using {@code ReentrantLock}, without significant
* performance loss. {@code Monitor} even has the potential for performance gain by optimizing the
* evaluation and signaling of conditions. Signaling is entirely
* <a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)#Implicit_signaling">
* implicit</a>.
* By eliminating explicit signaling, this class can guarantee that only one thread is awakened
* when a condition becomes true (no "signaling storms" due to use of {@link
* java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost
* (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal
* Condition.signal}).
*
* <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet
* <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also
* reentrant, so a thread may enter a monitor any number of times, and then must leave the same
* number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization
* semantics as the built-in Java language synchronization primitives.
*
* <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be
* followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the
* monitor cleanly: <pre> {@code
*
* monitor.enter();
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }}</pre>
*
* A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always appear as
* the condition of an <i>if</i> statement containing a <i>try/finally</i> block to ensure that the
* current thread leaves the monitor cleanly: <pre> {@code
*
* if (monitor.tryEnter()) {
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }
* } else {
* // do other things since the monitor was not available
* }}</pre>
*
* <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2>
*
* <p>The following examples show a simple threadsafe holder expressed using {@code synchronized},
* {@link ReentrantLock}, and {@code Monitor}.
*
* <h3>{@code synchronized}</h3>
*
* <p>This version is the fewest lines of code, largely because the synchronization mechanism used
* is built into the language and runtime. But the programmer has to remember to avoid a couple of
* common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and
* {@code notifyAll()} must be used instead of {@code notify()} because there are two different
* logical conditions being awaited. <pre> {@code
*
* public class SafeBox<V> {
* private V value;
*
* public synchronized V get() throws InterruptedException {
* while (value == null) {
* wait();
* }
* V result = value;
* value = null;
* notifyAll();
* return result;
* }
*
* public synchronized void set(V newValue) throws InterruptedException {
* while (value != null) {
* wait();
* }
* value = newValue;
* notifyAll();
* }
* }}</pre>
*
* <h3>{@code ReentrantLock}</h3>
*
* <p>This version is much more verbose than the {@code synchronized} version, and still suffers
* from the need for the programmer to remember to use {@code while} instead of {@code if}.
* However, one advantage is that we can introduce two separate {@code Condition} objects, which
* allows us to use {@code signal()} instead of {@code signalAll()}, which may be a performance
* benefit. <pre> {@code
*
* public class SafeBox<V> {
* private final ReentrantLock lock = new ReentrantLock();
* private final Condition valuePresent = lock.newCondition();
* private final Condition valueAbsent = lock.newCondition();
* private V value;
*
* public V get() throws InterruptedException {
* lock.lock();
* try {
* while (value == null) {
* valuePresent.await();
* }
* V result = value;
* value = null;
* valueAbsent.signal();
* return result;
* } finally {
* lock.unlock();
* }
* }
*
* public void set(V newValue) throws InterruptedException {
* lock.lock();
* try {
* while (value != null) {
* valueAbsent.await();
* }
* value = newValue;
* valuePresent.signal();
* } finally {
* lock.unlock();
* }
* }
* }}</pre>
*
* <h3>{@code Monitor}</h3>
*
* <p>This version adds some verbosity around the {@code Guard} objects, but removes that same
* verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the
* same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above.
* Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to
* remember to use {@code while} instead of {@code if}. <pre> {@code
*
* public class SafeBox<V> {
* private final Monitor monitor = new Monitor();
* private final Monitor.Guard valuePresent = new Monitor.Guard(monitor) {
* public boolean isSatisfied() {
* return value != null;
* }
* };
* private final Monitor.Guard valueAbsent = new Monitor.Guard(monitor) {
* public boolean isSatisfied() {
* return value == null;
* }
* };
* private V value;
*
* public V get() throws InterruptedException {
* monitor.enterWhen(valuePresent);
* try {
* V result = value;
* value = null;
* return result;
* } finally {
* monitor.leave();
* }
* }
*
* public void set(V newValue) throws InterruptedException {
* monitor.enterWhen(valueAbsent);
* try {
* value = newValue;
* } finally {
* monitor.leave();
* }
* }
* }}</pre>
*
* @author Justin T. Sampson
* @since 10.0
*/
@Beta
public final class Monitor {
// TODO: Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock.
/**
* A boolean condition for which a thread may wait. A {@code Guard} is associated with a single
* {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying
* the monitor, so code should not be written to rely on how often a guard might or might not be
* checked.
*
* <p>If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is
* associated with, an {@link IllegalMonitorStateException} is thrown.
*
* @since 10.0
*/
@Beta
public abstract static class Guard {
final Monitor monitor;
final Condition condition;
@GuardedBy("monitor.lock")
int waiterCount = 0;
protected Guard(Monitor monitor) {
this.monitor = checkNotNull(monitor, "monitor");
this.condition = monitor.lock.newCondition();
}
/**
* Evaluates this guard's boolean condition. This method is always called with the associated
* monitor already occupied. Implementations of this method must depend only on state protected
* by the associated monitor, and must not modify that state.
*/
public abstract boolean isSatisfied();
@Override
public final boolean equals(Object other) {
// Overridden as final to ensure identity semantics in Monitor.activeGuards.
return this == other;
}
@Override
public final int hashCode() {
// Overridden as final to ensure identity semantics in Monitor.activeGuards.
return super.hashCode();
}
}
/**
* Whether this monitor is fair.
*/
private final boolean fair;
/**
* The lock underlying this monitor.
*/
private final ReentrantLock lock;
/**
* The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}).
* This is an ArrayList rather than, say, a HashSet so that iteration and almost all adds don't
* incur any object allocation overhead.
*/
@GuardedBy("lock")
private final ArrayList<Guard> activeGuards = Lists.newArrayListWithCapacity(1);
/**
* Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code
* Monitor(false)}.
*/
public Monitor() {
this(false);
}
/**
* Creates a monitor with the given ordering policy.
*
* @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but
* fast) one
*/
public Monitor(boolean fair) {
this.fair = fair;
this.lock = new ReentrantLock(fair);
}
/**
* Enters this monitor. Blocks indefinitely.
*/
public void enter() {
lock.lock();
}
/**
* Enters this monitor. Blocks indefinitely, but may be interrupted.
*/
public void enterInterruptibly() throws InterruptedException {
lock.lockInterruptibly();
}
/**
* Enters this monitor. Blocks at most the given time.
*
* @return whether the monitor was entered
*/
public boolean enter(long time, TimeUnit unit) {
final ReentrantLock lock = this.lock;
if (!fair && lock.tryLock()) {
return true;
}
long startNanos = System.nanoTime();
long timeoutNanos = unit.toNanos(time);
long remainingNanos = timeoutNanos;
boolean interruptIgnored = false;
try {
while (true) {
try {
return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException ignored) {
interruptIgnored = true;
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
}
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
/**
* Enters this monitor. Blocks at most the given time, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
return lock.tryLock(time, unit);
}
/**
* Enters this monitor if it is possible to do so immediately. Does not block.
*
* <p><b>Note:</b> This method disregards the fairness setting of this monitor.
*
* @return whether the monitor was entered
*/
public boolean tryEnter() {
return lock.tryLock();
}
/**
* Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.
*/
public void enterWhen(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean success = false;
lock.lockInterruptibly();
try {
waitInterruptibly(guard, reentrant);
success = true;
} finally {
if (!success) {
lock.unlock();
}
}
}
/**
* Enters this monitor when the guard is satisfied. Blocks indefinitely.
*/
public void enterWhenUninterruptibly(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean success = false;
lock.lock();
try {
waitUninterruptibly(guard, reentrant);
success = true;
} finally {
if (!success) {
lock.unlock();
}
}
}
/**
* Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
* the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
* interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
long remainingNanos;
if (!fair && lock.tryLock()) {
remainingNanos = unit.toNanos(time);
} else {
long startNanos = System.nanoTime();
if (!lock.tryLock(time, unit)) {
return false;
}
remainingNanos = unit.toNanos(time) - (System.nanoTime() - startNanos);
}
boolean satisfied = false;
try {
satisfied = waitInterruptibly(guard, remainingNanos, reentrant);
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor when the guard is satisfied. Blocks at most the given time, including
* both the time to acquire the lock and the time to wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean interruptIgnored = false;
try {
long remainingNanos;
if (!fair && lock.tryLock()) {
remainingNanos = unit.toNanos(time);
} else {
long startNanos = System.nanoTime();
long timeoutNanos = unit.toNanos(time);
remainingNanos = timeoutNanos;
while (true) {
try {
if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
break;
} else {
return false;
}
} catch (InterruptedException ignored) {
interruptIgnored = true;
} finally {
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
}
}
boolean satisfied = false;
try {
satisfied = waitUninterruptibly(guard, remainingNanos, reentrant);
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
/**
* Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but
* does not wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterIf(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
lock.lock();
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
* not wait for the guard to be satisfied, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
* lock, but does not wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterIf(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!enter(time, unit)) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
* lock, but does not wait for the guard to be satisfied, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!lock.tryLock(time, unit)) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
* block acquiring the lock and does not wait for the guard to be satisfied.
*
* <p><b>Note:</b> This method disregards the fairness setting of this monitor.
*
* @return whether the monitor was entered
*/
public boolean tryEnterIf(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!lock.tryLock()) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be
* called only by a thread currently occupying this monitor.
*/
public void waitFor(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
waitInterruptibly(guard, true);
}
/**
* Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread
* currently occupying this monitor.
*/
public void waitForUninterruptibly(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
waitUninterruptibly(guard, true);
}
/**
* Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted.
* May be called only by a thread currently occupying this monitor.
*
* @return whether the guard is now satisfied
*/
public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
return waitInterruptibly(guard, unit.toNanos(time), true);
}
/**
* Waits for the guard to be satisfied. Waits at most the given time. May be called only by a
* thread currently occupying this monitor.
*
* @return whether the guard is now satisfied
*/
public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
return waitUninterruptibly(guard, unit.toNanos(time), true);
}
/**
* Leaves this monitor. May be called only by a thread currently occupying this monitor.
*/
public void leave() {
final ReentrantLock lock = this.lock;
try {
// No need to signal if we will still be holding the lock when we return
if (lock.getHoldCount() == 1) {
signalConditionsOfSatisfiedGuards(null);
}
} finally {
lock.unlock(); // Will throw IllegalMonitorStateException if not held
}
}
/**
* Returns whether this monitor is using a fair ordering policy.
*/
public boolean isFair() {
return lock.isFair();
}
/**
* Returns whether this monitor is occupied by any thread. This method is designed for use in
* monitoring of the system state, not for synchronization control.
*/
public boolean isOccupied() {
return lock.isLocked();
}
/**
* Returns whether the current thread is occupying this monitor (has entered more times than it
* has left).
*/
public boolean isOccupiedByCurrentThread() {
return lock.isHeldByCurrentThread();
}
/**
* Returns the number of times the current thread has entered this monitor in excess of the number
* of times it has left. Returns 0 if the current thread is not occupying this monitor.
*/
public int getOccupiedDepth() {
return lock.getHoldCount();
}
/**
* Returns an estimate of the number of threads waiting to enter this monitor. The value is only
* an estimate because the number of threads may change dynamically while this method traverses
* internal data structures. This method is designed for use in monitoring of the system state,
* not for synchronization control.
*/
public int getQueueLength() {
return lock.getQueueLength();
}
/**
* Returns whether any threads are waiting to enter this monitor. Note that because cancellations
* may occur at any time, a {@code true} return does not guarantee that any other thread will ever
* enter this monitor. This method is designed primarily for use in monitoring of the system
* state.
*/
public boolean hasQueuedThreads() {
return lock.hasQueuedThreads();
}
/**
* Queries whether the given thread is waiting to enter this monitor. Note that because
* cancellations may occur at any time, a {@code true} return does not guarantee that this thread
* will ever enter this monitor. This method is designed primarily for use in monitoring of the
* system state.
*/
public boolean hasQueuedThread(Thread thread) {
return lock.hasQueuedThread(thread);
}
/**
* Queries whether any threads are waiting for the given guard to become satisfied. Note that
* because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee
* that the guard becoming satisfied in the future will awaken any threads. This method is
* designed primarily for use in monitoring of the system state.
*/
public boolean hasWaiters(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
lock.lock();
try {
return guard.waiterCount > 0;
} finally {
lock.unlock();
}
}
/**
* Returns an estimate of the number of threads waiting for the given guard to become satisfied.
* Note that because timeouts and interrupts may occur at any time, the estimate serves only as an
* upper bound on the actual number of waiters. This method is designed for use in monitoring of
* the system state, not for synchronization control.
*/
public int getWaitQueueLength(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
lock.lock();
try {
return guard.waiterCount;
} finally {
lock.unlock();
}
}
@GuardedBy("lock")
private void signalConditionsOfSatisfiedGuards(@Nullable Guard interruptedGuard) {
final ArrayList<Guard> guards = this.activeGuards;
final int guardCount = guards.size();
try {
for (int i = 0; i < guardCount; i++) {
Guard guard = guards.get(i);
if ((guard == interruptedGuard) && (guard.waiterCount == 1)) {
// That one waiter was just interrupted and is throwing InterruptedException rather than
// paying attention to the guard being satisfied, so find another waiter on another guard.
continue;
}
if (guard.isSatisfied()) {
guard.condition.signal();
return;
}
}
} catch (Throwable throwable) {
for (int i = 0; i < guardCount; i++) {
Guard guard = guards.get(i);
guard.condition.signalAll();
}
throw Throwables.propagate(throwable);
}
}
@GuardedBy("lock")
private void incrementWaiters(Guard guard) {
int waiters = guard.waiterCount++;
if (waiters == 0) {
activeGuards.add(guard);
}
}
@GuardedBy("lock")
private void decrementWaiters(Guard guard) {
int waiters = --guard.waiterCount;
if (waiters == 0) {
activeGuards.remove(guard);
}
}
@GuardedBy("lock")
private void waitInterruptibly(Guard guard, boolean signalBeforeWaiting)
throws InterruptedException {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
try {
condition.await();
} catch (InterruptedException interrupt) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
throw interrupt;
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
}
@GuardedBy("lock")
private void waitUninterruptibly(Guard guard, boolean signalBeforeWaiting) {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
condition.awaitUninterruptibly();
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
}
@GuardedBy("lock")
private boolean waitInterruptibly(Guard guard, long remainingNanos, boolean signalBeforeWaiting)
throws InterruptedException {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
if (remainingNanos <= 0) {
return false;
}
try {
remainingNanos = condition.awaitNanos(remainingNanos);
} catch (InterruptedException interrupt) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
throw interrupt;
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
return true;
}
@GuardedBy("lock")
private boolean waitUninterruptibly(Guard guard, long timeoutNanos,
boolean signalBeforeWaiting) {
if (!guard.isSatisfied()) {
long startNanos = System.nanoTime();
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
boolean interruptIgnored = false;
try {
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
long remainingNanos = timeoutNanos;
do {
if (remainingNanos <= 0) {
return false;
}
try {
remainingNanos = condition.awaitNanos(remainingNanos);
} catch (InterruptedException ignored) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
interruptIgnored = true;
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
return true;
}
}
|
Move timeout start to before tryLock().
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=41700665
|
guava/src/com/google/common/util/concurrent/Monitor.java
|
Move timeout start to before tryLock(). ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=41700665
|
|
Java
|
apache-2.0
|
48592e5493c265e6b492b8712ac9153724848189
| 0
|
apixandru/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ryano144/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,nicolargo/intellij-community,izonder/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,gnuhub/intellij-community,supersven/intellij-community,wreckJ/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,signed/intellij-community,allotria/intellij-community,clumsy/intellij-community,allotria/intellij-community,vladmm/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ibinti/intellij-community,ibinti/intellij-community,samthor/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,dslomov/intellij-community,clumsy/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,caot/intellij-community,signed/intellij-community,da1z/intellij-community,da1z/intellij-community,FHannes/intellij-community,kool79/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,robovm/robovm-studio,signed/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,blademainer/intellij-community,kool79/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,vladmm/intellij-community,jexp/idea2,fitermay/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,ernestp/consulo,Distrotech/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ernestp/consulo,petteyg/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kool79/intellij-community,gnuhub/intellij-community,da1z/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,consulo/consulo,mglukhikh/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,kool79/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,caot/intellij-community,semonte/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,da1z/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,amith01994/intellij-community,samthor/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,ernestp/consulo,Distrotech/intellij-community,supersven/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,asedunov/intellij-community,diorcety/intellij-community,izonder/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,caot/intellij-community,semonte/intellij-community,robovm/robovm-studio,joewalnes/idea-community,salguarnieri/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,fitermay/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,signed/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,diorcety/intellij-community,diorcety/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,xfournet/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,caot/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,ryano144/intellij-community,allotria/intellij-community,diorcety/intellij-community,signed/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,da1z/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,xfournet/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,jagguli/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,ryano144/intellij-community,diorcety/intellij-community,dslomov/intellij-community,caot/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,samthor/intellij-community,diorcety/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,kdwink/intellij-community,asedunov/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,izonder/intellij-community,signed/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,robovm/robovm-studio,hurricup/intellij-community,allotria/intellij-community,asedunov/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,slisson/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,holmes/intellij-community,ibinti/intellij-community,blademainer/intellij-community,supersven/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,ernestp/consulo,petteyg/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,apixandru/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,jexp/idea2,Lekanich/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ernestp/consulo,alphafoobar/intellij-community,jexp/idea2,hurricup/intellij-community,Distrotech/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,holmes/intellij-community,holmes/intellij-community,fitermay/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,retomerz/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ryano144/intellij-community,adedayo/intellij-community,da1z/intellij-community,petteyg/intellij-community,kdwink/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,jexp/idea2,wreckJ/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,jexp/idea2,supersven/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,vladmm/intellij-community,samthor/intellij-community,hurricup/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,clumsy/intellij-community,joewalnes/idea-community,kool79/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,da1z/intellij-community,da1z/intellij-community,retomerz/intellij-community,FHannes/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,dslomov/intellij-community,dslomov/intellij-community,slisson/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,ibinti/intellij-community,blademainer/intellij-community,kdwink/intellij-community,amith01994/intellij-community,jagguli/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ibinti/intellij-community,caot/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,samthor/intellij-community,jagguli/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,semonte/intellij-community,clumsy/intellij-community,izonder/intellij-community,petteyg/intellij-community,joewalnes/idea-community,retomerz/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ibinti/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,clumsy/intellij-community,izonder/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,kdwink/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,holmes/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,FHannes/intellij-community,holmes/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,consulo/consulo,joewalnes/idea-community,petteyg/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,holmes/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,joewalnes/idea-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,holmes/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,slisson/intellij-community,slisson/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,signed/intellij-community,kdwink/intellij-community,kool79/intellij-community,blademainer/intellij-community,allotria/intellij-community,holmes/intellij-community,izonder/intellij-community,kool79/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,slisson/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,kool79/intellij-community,caot/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,holmes/intellij-community,asedunov/intellij-community,amith01994/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,petteyg/intellij-community,kool79/intellij-community,semonte/intellij-community,kdwink/intellij-community,clumsy/intellij-community,izonder/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,asedunov/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,kdwink/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fitermay/intellij-community,fnouama/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,caot/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,signed/intellij-community,semonte/intellij-community,clumsy/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,caot/intellij-community,hurricup/intellij-community,consulo/consulo,samthor/intellij-community,da1z/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,diorcety/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,allotria/intellij-community,petteyg/intellij-community,fitermay/intellij-community,joewalnes/idea-community,retomerz/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,holmes/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,supersven/intellij-community,retomerz/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,semonte/intellij-community,clumsy/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,consulo/consulo,da1z/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,holmes/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,consulo/consulo,amith01994/intellij-community,fitermay/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,supersven/intellij-community,jexp/idea2,muntasirsyed/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,petteyg/intellij-community,dslomov/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,caot/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,slisson/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,diorcety/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,FHannes/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,amith01994/intellij-community
|
package com.intellij.psi.impl.source.parsing;
import com.intellij.lexer.FilterLexer;
import com.intellij.lexer.JavaLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.ParsingContext;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.CharTable;
public class Parsing implements Constants{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.parsing.Parsing");
public static /*final*/ boolean DEEP_PARSE_BLOCKS_IN_STATEMENTS = false;
protected final ParsingContext myContext;
public Parsing(ParsingContext context) {
myContext = context;
}
public static CompositeElement parseJavaCodeReferenceText(PsiManager manager, char[] buffer, CharTable table) {
return (CompositeElement)parseJavaCodeReferenceText(manager, buffer, 0, buffer.length, table, false);
}
//Since we are to parse greedily (up to the end), we are not guaranteed to return reference actually
public static TreeElement parseJavaCodeReferenceText(PsiManager manager,
char[] buffer,
int startOffset,
int endOffset,
CharTable table,
boolean eatAll) {
Lexer originalLexer = new JavaLexer(manager.getEffectiveLanguageLevel());
FilterLexer lexer = new FilterLexer(originalLexer, new FilterLexer.SetFilter(WHITE_SPACE_OR_COMMENT_BIT_SET));
lexer.start(buffer, startOffset, endOffset);
ParsingContext context = new ParsingContext(table);
CompositeElement ref = context.getStatementParsing().parseJavaCodeReference(lexer, false);
final FileElement dummyRoot = new DummyHolder(manager, null, table).getTreeElement();
if (ref == null) {
if (!eatAll) return null;
} else {
TreeUtil.addChildren(dummyRoot, ref);
}
if (lexer.getTokenType() != null) {
if (!eatAll) return null;
final CompositeElement errorElement = Factory.createErrorElement("Unexpected tokens");
while (lexer.getTokenType() != null) {
final TreeElement token = ParseUtil.createTokenElement(lexer, context.getCharTable());
TreeUtil.addChildren(errorElement, token);
lexer.advance();
}
TreeUtil.addChildren(dummyRoot, errorElement);
}
ParseUtil.insertMissingTokens(dummyRoot, originalLexer, startOffset, endOffset, ParseUtil.WhiteSpaceAndCommentsProcessor.INSTANCE, context);
return (TreeElement)dummyRoot.getFirstChildNode();
}
public CompositeElement parseJavaCodeReference(Lexer lexer, boolean allowIncomplete) {
if (lexer.getTokenType() != IDENTIFIER) return null;
TreeElement identifier = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
CompositeElement refElement = Factory.createCompositeElement(JAVA_CODE_REFERENCE);
TreeUtil.addChildren(refElement, identifier);
CompositeElement parameterList = parseReferenceParameterList(lexer, true);
TreeUtil.addChildren(refElement, parameterList);
while (lexer.getTokenType() == DOT) {
long dotPos = ParseUtil.savePosition(lexer);
TreeElement dot = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
if (lexer.getTokenType() == IDENTIFIER) {
identifier = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
}
else{
if (!allowIncomplete){
ParseUtil.restorePosition(lexer, dotPos);
return refElement;
}
identifier = null;
}
CompositeElement refElement1 = Factory.createCompositeElement(JAVA_CODE_REFERENCE);
TreeUtil.addChildren(refElement1, refElement);
TreeUtil.addChildren(refElement1, dot);
if (identifier == null){
TreeUtil.addChildren(refElement1, Factory.createErrorElement("Identifier expected"));
TreeUtil.addChildren(refElement1, Factory.createCompositeElement(REFERENCE_PARAMETER_LIST));
return refElement1;
}
TreeUtil.addChildren(refElement1, identifier);
CompositeElement parameterList1 = parseReferenceParameterList(lexer, true);
TreeUtil.addChildren(refElement1, parameterList1);
refElement = refElement1;
}
return refElement;
}
public CompositeElement parseReferenceParameterList(Lexer lexer, boolean allowWildcard) {
final CompositeElement list = Factory.createCompositeElement(REFERENCE_PARAMETER_LIST);
if (lexer.getTokenType() != LT) return list;
final TreeElement lt = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
TreeUtil.addChildren(list, lt);
lexer.advance();
while (true) {
final CompositeElement typeElement = parseType(lexer, true, allowWildcard);
if (typeElement != null) {
TreeUtil.addChildren(list, typeElement);
} else {
final CompositeElement errorElement = Factory.createErrorElement("Identifier expected");
TreeUtil.addChildren(list, errorElement);
}
if (lexer.getTokenType() == GT) {
final TreeElement gt = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
TreeUtil.addChildren(list, gt);
lexer.advance();
return list;
} else if (lexer.getTokenType() == COMMA) {
final TreeElement comma = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
TreeUtil.addChildren(list, comma);
lexer.advance();
} else {
final CompositeElement errorElement = Factory.createErrorElement("'>' or ',' expected.");
TreeUtil.addChildren(list, errorElement);
return list;
}
}
}
public static CompositeElement parseTypeText(PsiManager manager, char[] buffer, int startOffset, int endOffset, CharTable table) {
Lexer originalLexer = new JavaLexer(manager.getEffectiveLanguageLevel());
FilterLexer lexer = new FilterLexer(originalLexer, new FilterLexer.SetFilter(WHITE_SPACE_OR_COMMENT_BIT_SET));
lexer.start(buffer, startOffset, endOffset);
final ParsingContext context = new ParsingContext(table);
CompositeElement type = context.getStatementParsing().parseTypeWithEllipsis(lexer);
if (type == null) return null;
if (lexer.getTokenType() != null) return null;
ParseUtil.insertMissingTokens(type, originalLexer, startOffset, endOffset, ParseUtil.WhiteSpaceAndCommentsProcessor.INSTANCE, context);
return type;
}
public CompositeElement parseTypeWithEllipsis(Lexer lexer, boolean eatLastDot, boolean allowWilcard) {
CompositeElement type = parseType(lexer, eatLastDot, allowWilcard);
if (type == null) return null;
if (lexer.getTokenType() == ELLIPSIS) {
CompositeElement type1 = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type1, type);
TreeUtil.addChildren(type1, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
type = type1;
}
return type;
}
public CompositeElement parseTypeWithEllipsis(Lexer lexer) {
return parseTypeWithEllipsis(lexer, true, true);
}
public CompositeElement parseType(Lexer lexer){
return parseType(lexer, true, true);
}
public CompositeElement parseType(Lexer lexer, boolean eatLastDot, boolean allowWildcard){
IElementType tokenType = lexer.getTokenType();
TreeElement refElement;
if (tokenType == null){
return null;
}
else if (PRIMITIVE_TYPE_BIT_SET.isInSet(tokenType)){
refElement = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
}
else if (tokenType == IDENTIFIER){
refElement = parseJavaCodeReference(lexer, eatLastDot);
}
else if (allowWildcard && lexer.getTokenType() == QUEST) {
return parseWildcardType(lexer);
}
else{
return null;
}
CompositeElement type = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type, refElement);
while(lexer.getTokenType() == LBRACKET){
long lbracketPos = ParseUtil.savePosition(lexer);
TreeElement lbracket = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
if (lexer.getTokenType() != RBRACKET){
ParseUtil.restorePosition(lexer, lbracketPos);
break;
}
CompositeElement type1 = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type1, type);
TreeUtil.addChildren(type1, lbracket);
TreeUtil.addChildren(type1, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
type = type1;
}
return type;
}
private CompositeElement parseWildcardType(Lexer lexer) {
LOG.assertTrue(lexer.getTokenType() == QUEST);
CompositeElement type = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
if (lexer.getTokenType() == SUPER_KEYWORD || lexer.getTokenType() == EXTENDS_KEYWORD) {
TreeUtil.addChildren(type, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
CompositeElement boundType = parseType(lexer, true, false);
if (boundType != null) {
TreeUtil.addChildren(type, boundType);
}
else {
TreeUtil.addChildren(type, Factory.createErrorElement("Type expected"));
}
}
return type;
}
public static TreeElement parseTypeText(PsiManager manager,
Lexer lexer,
char[] buffer,
int startOffset,
int endOffset,
int state,
CharTable table) {
if (lexer == null){
lexer = new JavaLexer(manager.getEffectiveLanguageLevel());
}
FilterLexer filterLexer = new FilterLexer(lexer, new FilterLexer.SetFilter(WHITE_SPACE_OR_COMMENT_BIT_SET));
if (state < 0) filterLexer.start(buffer, startOffset, endOffset);
else filterLexer.start(buffer, startOffset, endOffset, state);
final ParsingContext context = new ParsingContext(table);
final FileElement dummyRoot = new DummyHolder(manager, null, context.getCharTable()).getTreeElement();
final CompositeElement root = context.getStatementParsing().parseType(filterLexer);
if (root != null) {
TreeUtil.addChildren(dummyRoot, root);
}
if (filterLexer.getTokenType() == ELLIPSIS) {
TreeUtil.addChildren(dummyRoot, ParseUtil.createTokenElement(filterLexer, context.getCharTable()));
filterLexer.advance();
}
if (filterLexer.getTokenType() != null) {
final CompositeElement errorElement = Factory.createErrorElement("Unexpected tokens");
while (filterLexer.getTokenType() != null) {
final TreeElement token = ParseUtil.createTokenElement(lexer, context.getCharTable());
TreeUtil.addChildren(errorElement, token);
filterLexer.advance();
}
TreeUtil.addChildren(dummyRoot, errorElement);
}
ParseUtil.insertMissingTokens(
dummyRoot,
lexer,
startOffset,
endOffset, state,
ParseUtil.WhiteSpaceAndCommentsProcessor.INSTANCE, context);
return (TreeElement)dummyRoot.getFirstChildNode();
}
}
|
source/com/intellij/psi/impl/source/parsing/Parsing.java
|
package com.intellij.psi.impl.source.parsing;
import com.intellij.lexer.FilterLexer;
import com.intellij.lexer.JavaLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.DummyHolder;
import com.intellij.psi.impl.source.ParsingContext;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.CharTable;
public class Parsing implements Constants{
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.parsing.Parsing");
public static /*final*/ boolean DEEP_PARSE_BLOCKS_IN_STATEMENTS = false;
protected final ParsingContext myContext;
public Parsing(ParsingContext context) {
myContext = context;
}
public static CompositeElement parseJavaCodeReferenceText(PsiManager manager, char[] buffer, CharTable table) {
return parseJavaCodeReferenceText(manager, buffer, 0, buffer.length, table, false);
}
public static CompositeElement parseJavaCodeReferenceText(PsiManager manager,
char[] buffer,
int startOffset,
int endOffset,
CharTable table,
boolean eatAll) {
Lexer originalLexer = new JavaLexer(manager.getEffectiveLanguageLevel());
FilterLexer lexer = new FilterLexer(originalLexer, new FilterLexer.SetFilter(WHITE_SPACE_OR_COMMENT_BIT_SET));
lexer.start(buffer, startOffset, endOffset);
ParsingContext context = new ParsingContext(table);
CompositeElement ref = context.getStatementParsing().parseJavaCodeReference(lexer, false);
if (ref == null) return null;
final FileElement dummyRoot = new DummyHolder(manager, ref, null, table).getTreeElement();
if (lexer.getTokenType() != null) {
if (!eatAll) return null;
final CompositeElement errorElement = Factory.createErrorElement("Unexpected tokens");
while (lexer.getTokenType() != null) {
final TreeElement token = ParseUtil.createTokenElement(lexer, context.getCharTable());
TreeUtil.addChildren(errorElement, token);
lexer.advance();
}
TreeUtil.addChildren(dummyRoot, errorElement);
}
ParseUtil.insertMissingTokens(dummyRoot, originalLexer, startOffset, endOffset, ParseUtil.WhiteSpaceAndCommentsProcessor.INSTANCE, context);
return (CompositeElement)dummyRoot.getFirstChildNode();
}
public CompositeElement parseJavaCodeReference(Lexer lexer, boolean allowIncomplete) {
if (lexer.getTokenType() != IDENTIFIER) return null;
TreeElement identifier = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
CompositeElement refElement = Factory.createCompositeElement(JAVA_CODE_REFERENCE);
TreeUtil.addChildren(refElement, identifier);
CompositeElement parameterList = parseReferenceParameterList(lexer, true);
TreeUtil.addChildren(refElement, parameterList);
while (lexer.getTokenType() == DOT) {
long dotPos = ParseUtil.savePosition(lexer);
TreeElement dot = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
if (lexer.getTokenType() == IDENTIFIER) {
identifier = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
}
else{
if (!allowIncomplete){
ParseUtil.restorePosition(lexer, dotPos);
return refElement;
}
identifier = null;
}
CompositeElement refElement1 = Factory.createCompositeElement(JAVA_CODE_REFERENCE);
TreeUtil.addChildren(refElement1, refElement);
TreeUtil.addChildren(refElement1, dot);
if (identifier == null){
TreeUtil.addChildren(refElement1, Factory.createErrorElement("Identifier expected"));
TreeUtil.addChildren(refElement1, Factory.createCompositeElement(REFERENCE_PARAMETER_LIST));
return refElement1;
}
TreeUtil.addChildren(refElement1, identifier);
CompositeElement parameterList1 = parseReferenceParameterList(lexer, true);
TreeUtil.addChildren(refElement1, parameterList1);
refElement = refElement1;
}
return refElement;
}
public CompositeElement parseReferenceParameterList(Lexer lexer, boolean allowWildcard) {
final CompositeElement list = Factory.createCompositeElement(REFERENCE_PARAMETER_LIST);
if (lexer.getTokenType() != LT) return list;
final TreeElement lt = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
TreeUtil.addChildren(list, lt);
lexer.advance();
while (true) {
final CompositeElement typeElement = parseType(lexer, true, allowWildcard);
if (typeElement != null) {
TreeUtil.addChildren(list, typeElement);
} else {
final CompositeElement errorElement = Factory.createErrorElement("Identifier expected");
TreeUtil.addChildren(list, errorElement);
}
if (lexer.getTokenType() == GT) {
final TreeElement gt = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
TreeUtil.addChildren(list, gt);
lexer.advance();
return list;
} else if (lexer.getTokenType() == COMMA) {
final TreeElement comma = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
TreeUtil.addChildren(list, comma);
lexer.advance();
} else {
final CompositeElement errorElement = Factory.createErrorElement("'>' or ',' expected.");
TreeUtil.addChildren(list, errorElement);
return list;
}
}
}
public static CompositeElement parseTypeText(PsiManager manager, char[] buffer, int startOffset, int endOffset, CharTable table) {
Lexer originalLexer = new JavaLexer(manager.getEffectiveLanguageLevel());
FilterLexer lexer = new FilterLexer(originalLexer, new FilterLexer.SetFilter(WHITE_SPACE_OR_COMMENT_BIT_SET));
lexer.start(buffer, startOffset, endOffset);
final ParsingContext context = new ParsingContext(table);
CompositeElement type = context.getStatementParsing().parseTypeWithEllipsis(lexer);
if (type == null) return null;
if (lexer.getTokenType() != null) return null;
ParseUtil.insertMissingTokens(type, originalLexer, startOffset, endOffset, ParseUtil.WhiteSpaceAndCommentsProcessor.INSTANCE, context);
return type;
}
public CompositeElement parseTypeWithEllipsis(Lexer lexer, boolean eatLastDot, boolean allowWilcard) {
CompositeElement type = parseType(lexer, eatLastDot, allowWilcard);
if (type == null) return null;
if (lexer.getTokenType() == ELLIPSIS) {
CompositeElement type1 = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type1, type);
TreeUtil.addChildren(type1, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
type = type1;
}
return type;
}
public CompositeElement parseTypeWithEllipsis(Lexer lexer) {
return parseTypeWithEllipsis(lexer, true, true);
}
public CompositeElement parseType(Lexer lexer){
return parseType(lexer, true, true);
}
public CompositeElement parseType(Lexer lexer, boolean eatLastDot, boolean allowWildcard){
IElementType tokenType = lexer.getTokenType();
TreeElement refElement;
if (tokenType == null){
return null;
}
else if (PRIMITIVE_TYPE_BIT_SET.isInSet(tokenType)){
refElement = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
}
else if (tokenType == IDENTIFIER){
refElement = parseJavaCodeReference(lexer, eatLastDot);
}
else if (allowWildcard && lexer.getTokenType() == QUEST) {
return parseWildcardType(lexer);
}
else{
return null;
}
CompositeElement type = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type, refElement);
while(lexer.getTokenType() == LBRACKET){
long lbracketPos = ParseUtil.savePosition(lexer);
TreeElement lbracket = ParseUtil.createTokenElement(lexer, myContext.getCharTable());
lexer.advance();
if (lexer.getTokenType() != RBRACKET){
ParseUtil.restorePosition(lexer, lbracketPos);
break;
}
CompositeElement type1 = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type1, type);
TreeUtil.addChildren(type1, lbracket);
TreeUtil.addChildren(type1, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
type = type1;
}
return type;
}
private CompositeElement parseWildcardType(Lexer lexer) {
LOG.assertTrue(lexer.getTokenType() == QUEST);
CompositeElement type = Factory.createCompositeElement(TYPE);
TreeUtil.addChildren(type, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
if (lexer.getTokenType() == SUPER_KEYWORD || lexer.getTokenType() == EXTENDS_KEYWORD) {
TreeUtil.addChildren(type, ParseUtil.createTokenElement(lexer, myContext.getCharTable()));
lexer.advance();
CompositeElement boundType = parseType(lexer, true, false);
if (boundType != null) {
TreeUtil.addChildren(type, boundType);
}
else {
TreeUtil.addChildren(type, Factory.createErrorElement("Type expected"));
}
}
return type;
}
public static TreeElement parseTypeText(PsiManager manager,
Lexer lexer,
char[] buffer,
int startOffset,
int endOffset,
int state,
CharTable table) {
if (lexer == null){
lexer = new JavaLexer(manager.getEffectiveLanguageLevel());
}
FilterLexer filterLexer = new FilterLexer(lexer, new FilterLexer.SetFilter(WHITE_SPACE_OR_COMMENT_BIT_SET));
if (state < 0) filterLexer.start(buffer, startOffset, endOffset);
else filterLexer.start(buffer, startOffset, endOffset, state);
final ParsingContext context = new ParsingContext(table);
final FileElement dummyRoot = new DummyHolder(manager, null, context.getCharTable()).getTreeElement();
final CompositeElement root = context.getStatementParsing().parseType(filterLexer);
if (root != null) {
TreeUtil.addChildren(dummyRoot, root);
}
if (filterLexer.getTokenType() == ELLIPSIS) {
TreeUtil.addChildren(dummyRoot, ParseUtil.createTokenElement(filterLexer, context.getCharTable()));
filterLexer.advance();
}
if (filterLexer.getTokenType() != null) {
final CompositeElement errorElement = Factory.createErrorElement("Unexpected tokens");
while (filterLexer.getTokenType() != null) {
final TreeElement token = ParseUtil.createTokenElement(lexer, context.getCharTable());
TreeUtil.addChildren(errorElement, token);
filterLexer.advance();
}
TreeUtil.addChildren(dummyRoot, errorElement);
}
ParseUtil.insertMissingTokens(
dummyRoot,
lexer,
startOffset,
endOffset, state,
ParseUtil.WhiteSpaceAndCommentsProcessor.INSTANCE, context);
return (TreeElement)dummyRoot.getFirstChildNode();
}
}
|
(no message)
|
source/com/intellij/psi/impl/source/parsing/Parsing.java
|
(no message)
|
|
Java
|
apache-2.0
|
4b40c6489189613834a572fb65454e5d1430668d
| 0
|
sunghyuk/azkaban,HappyRay/azkaban,HappyRay/azkaban,davidzchen/azkaban,hluu/azkaban2,nomorogbe/azkaban,erwa/azkaban,researchgate/azkaban,binhnv/azkaban,weikang2002/azkaban,cjyu/azkaban2,nomorogbe/azkaban,linearregression/azkaban,erwa/azkaban,Shopify/azkaban,inoviaazkaban/azkaban,davidzchen/azkaban,poporisil/azkaban3,evlstyle/azkaban,evlstyle/azkaban,hluu/azkaban2,backingwu/azkaban,binhnv/azkaban,azkaban/azkaban,logiclord/azkaban,shixin198642/azkaban2,shixin198642/azkaban2,chengren311/azkaban,binhnv/azkaban,davidzchen/azkaban,nomorogbe/azkaban,johnyu0520/azkaban,Shopify/azkaban,FelixGV/azkaban2,mradamlacey/azkaban,cjyu/azkaban2,sunghyuk/azkaban,jackrjli/azkaban,sunghyuk/azkaban,wangqiaoshi/azkaban,logiclord/azkaban,researchgate/azkaban,binhnv/azkaban,inoviaazkaban/azkaban,mradamlacey/azkaban,azkaban/azkaban,logiclord/azkaban,mradamlacey/azkaban,HappyRay/azkaban,kaneda/azkaban,sunghyuk/azkaban,mariacioffi/azkaban,sunghyuk/azkaban,linearregression/azkaban,Shopify/azkaban,azkaban/azkaban,johnyu0520/azkaban,erwa/azkaban,johnyu0520/azkaban,chengren311/azkaban,cjyu/azkaban2,kaneda/azkaban,erwa/azkaban,reallocf/azkaban,evlstyle/azkaban,backingwu/azkaban,reallocf/azkaban,relateiq/azkaban,FelixGV/azkaban2,inoviaazkaban/azkaban,chengren311/azkaban,gradleupdate/azkaban2,jackrjli/azkaban,davidzchen/azkaban,poporisil/azkaban3,logiclord/azkaban,poporisil/azkaban3,jackrjli/azkaban,weikang2002/azkaban,poporisil/azkaban3,mariacioffi/azkaban,mradamlacey/azkaban,gradleupdate/azkaban2,backingwu/azkaban,weikang2002/azkaban,HappyRay/azkaban,mradamlacey/azkaban,hluu/azkaban2,wangqiaoshi/azkaban,gradleupdate/azkaban2,binhnv/azkaban,HappyRay/azkaban,linearregression/azkaban,wangqiaoshi/azkaban,HappyRay/azkaban,mariacioffi/azkaban,kaneda/azkaban,chengren311/azkaban,researchgate/azkaban,FelixGV/azkaban2,johnyu0520/azkaban,relateiq/azkaban,relateiq/azkaban,evlstyle/azkaban,poporisil/azkaban3,jackrjli/azkaban,mariacioffi/azkaban,reallocf/azkaban,erwa/azkaban,shixin198642/azkaban2,jackrjli/azkaban,azkaban/azkaban,mariacioffi/azkaban,reallocf/azkaban,researchgate/azkaban,azkaban/azkaban,chengren311/azkaban,relateiq/azkaban,reallocf/azkaban,azkaban/azkaban
|
package azkaban.execapp;
/*
* Copyright 2012 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Collections;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import azkaban.execapp.event.BlockingStatus;
import azkaban.execapp.event.Event;
import azkaban.execapp.event.Event.Type;
import azkaban.execapp.event.EventHandler;
import azkaban.execapp.event.FlowWatcher;
import azkaban.executor.ExecutableNode;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.ExecutorManagerException;
import azkaban.executor.Status;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.AbstractProcessJob;
import azkaban.jobExecutor.Job;
import azkaban.jobtype.JobTypeManager;
import azkaban.jobtype.JobTypeManagerException;
import azkaban.utils.Props;
public class JobRunner extends EventHandler implements Runnable {
private static final Layout DEFAULT_LAYOUT = new PatternLayout("%d{dd-MM-yyyy HH:mm:ss z} %c{1} %p - %m\n");
private ExecutorLoader loader;
private Props props;
private Props outputProps;
private ExecutableNode node;
private File workingDir;
private Logger logger = null;
private Layout loggerLayout = DEFAULT_LAYOUT;
private Logger flowLogger = null;
private Appender jobAppender;
private File logFile;
private Job job;
private int executionId = -1;
private static final Object logCreatorLock = new Object();
private Object syncObject = new Object();
private final JobTypeManager jobtypeManager;
// Used by the job to watch and block against another flow
private Integer pipelineLevel = null;
private FlowWatcher watcher = null;
private Set<String> pipelineJobs = new HashSet<String>();
private Set<String> proxyUsers = null;
private String jobLogChunkSize;
private int jobLogBackupIndex;
private long delayStartMs = 0;
private boolean cancelled = false;
public JobRunner(ExecutableNode node, Props props, File workingDir, ExecutorLoader loader, JobTypeManager jobtypeManager) {
this.props = props;
this.node = node;
this.workingDir = workingDir;
this.executionId = node.getExecutionId();
this.loader = loader;
this.jobtypeManager = jobtypeManager;
}
public void setValidatedProxyUsers(Set<String> proxyUsers) {
this.proxyUsers = proxyUsers;
}
public void setLogSettings(Logger flowLogger, String logFileChuckSize, int numLogBackup ) {
this.flowLogger = flowLogger;
this.jobLogChunkSize = logFileChuckSize;
this.jobLogBackupIndex = numLogBackup;
}
public Props getProps() {
return props;
}
public void setPipeline(FlowWatcher watcher, int pipelineLevel) {
this.watcher = watcher;
this.pipelineLevel = pipelineLevel;
if (this.pipelineLevel == 1) {
pipelineJobs.add(node.getJobId());
}
else if (this.pipelineLevel == 2) {
pipelineJobs.add(node.getJobId());
pipelineJobs.addAll(node.getOutNodes());
}
}
public void setDelayStart(long delayMS) {
delayStartMs = delayMS;
}
public long getDelayStart() {
return delayStartMs;
}
public ExecutableNode getNode() {
return node;
}
public String getLogFilePath() {
return logFile == null ? null : logFile.getPath();
}
private void createLogger() {
// Create logger
synchronized (logCreatorLock) {
String loggerName = System.currentTimeMillis() + "." + executionId + "." + node.getJobId();
logger = Logger.getLogger(loggerName);
// Create file appender
String logName = createLogFileName(node.getExecutionId(), node.getJobId(), node.getAttempt());
logFile = new File(workingDir, logName);
String absolutePath = logFile.getAbsolutePath();
jobAppender = null;
try {
RollingFileAppender fileAppender = new RollingFileAppender(loggerLayout, absolutePath, true);
fileAppender.setMaxBackupIndex(jobLogBackupIndex);
fileAppender.setMaxFileSize(jobLogChunkSize);
jobAppender = fileAppender;
logger.addAppender(jobAppender);
} catch (IOException e) {
flowLogger.error("Could not open log file in " + workingDir + " for job " + node.getJobId(), e);
}
}
}
private void closeLogger() {
if (jobAppender != null) {
logger.removeAppender(jobAppender);
jobAppender.close();
}
}
private void writeStatus() {
try {
node.setUpdateTime(System.currentTimeMillis());
loader.updateExecutableNode(node);
} catch (ExecutorManagerException e) {
flowLogger.error("Could not update job properties in db for " + node.getJobId(), e);
}
}
@Override
public void run() {
Thread.currentThread().setName("JobRunner-" + node.getJobId() + "-" + executionId);
if (node.getStatus() == Status.DISABLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.SKIPPED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
} else if (this.cancelled) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.FAILED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
} else if (node.getStatus() == Status.FAILED || node.getStatus() == Status.KILLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
else {
createLogger();
node.setUpdateTime(System.currentTimeMillis());
// For pipelining of jobs. Will watch other jobs.
if (!pipelineJobs.isEmpty()) {
String blockedList = "";
ArrayList<BlockingStatus> blockingStatus = new ArrayList<BlockingStatus>();
for (String waitingJobId : pipelineJobs) {
Status status = watcher.peekStatus(waitingJobId);
if (status != null && !Status.isStatusFinished(status)) {
BlockingStatus block = watcher.getBlockingStatus(waitingJobId);
blockingStatus.add(block);
blockedList += waitingJobId + ",";
}
}
if (!blockingStatus.isEmpty()) {
logger.info("Pipeline job " + node.getJobId() + " waiting on " + blockedList + " in execution " + watcher.getExecId());
for(BlockingStatus bStatus: blockingStatus) {
logger.info("Waiting on pipelined job " + bStatus.getJobId());
bStatus.blockOnFinishedStatus();
logger.info("Pipelined job " + bStatus.getJobId() + " finished.");
}
}
if (watcher.isWatchCancelled()) {
logger.info("Job was cancelled while waiting on pipeline. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
node.setStatus(Status.FAILED);
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
long currentTime = System.currentTimeMillis();
if (delayStartMs > 0) {
logger.info("Delaying start of execution for " + delayStartMs + " milliseconds.");
synchronized(this) {
try {
this.wait(delayStartMs);
logger.info("Execution has been delayed for " + delayStartMs + " ms. Continuing with execution.");
} catch (InterruptedException e) {
logger.error("Job " + node.getJobId() + " was to be delayed for " + delayStartMs + ". Interrupted after " + (System.currentTimeMillis() - currentTime));
}
}
if (cancelled) {
logger.info("Job was cancelled while in delay. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
try {
loader.uploadExecutableNode(node, props);
} catch (ExecutorManagerException e1) {
logger.error("Error writing initial node properties");
}
if (prepareJob()) {
writeStatus();
fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false);
runJob();
}
else {
node.setStatus(Status.FAILED);
logError("Job run failed!");
}
node.setEndTime(System.currentTimeMillis());
logInfo("Finishing job " + node.getJobId() + " at " + node.getEndTime());
closeLogger();
writeStatus();
if (logFile != null) {
try {
File[] files = logFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(logFile.getName());
}
}
);
Arrays.sort(files, Collections.reverseOrder());
loader.uploadLogFile(executionId, node.getJobId(), node.getAttempt(), files);
} catch (ExecutorManagerException e) {
flowLogger.error("Error writing out logs for job " + node.getJobId(), e);
}
}
else {
flowLogger.info("Log file for job " + node.getJobId() + " is null");
}
}
fireEvent(Event.create(this, Type.JOB_FINISHED));
}
private void fireEvent(Event event) {
fireEvent(event, true);
}
private void fireEvent(Event event, boolean updateTime) {
if (updateTime) {
node.setUpdateTime(System.currentTimeMillis());
}
this.fireEventListeners(event);
}
private boolean prepareJob() throws RuntimeException {
// Check pre conditions
if (props == null || cancelled) {
logError("Failing job. The job properties don't exist");
return false;
}
synchronized(syncObject) {
if (node.getStatus() == Status.FAILED || cancelled) {
return false;
}
if (node.getAttempt() > 0) {
logInfo("Starting job " + node.getJobId() + " attempt " + node.getAttempt() + " at " + node.getStartTime());
}
else {
logInfo("Starting job " + node.getJobId() + " at " + node.getStartTime());
}
props.put(CommonJobProperties.JOB_ATTEMPT, node.getAttempt());
node.setStatus(Status.RUNNING);
// Ability to specify working directory
if (!props.containsKey(AbstractProcessJob.WORKING_DIR)) {
props.put(AbstractProcessJob.WORKING_DIR, workingDir.getAbsolutePath());
}
if(props.containsKey("user.to.proxy")) {
String jobProxyUser = props.getString("user.to.proxy");
if(proxyUsers != null && !proxyUsers.contains(jobProxyUser)) {
logger.error("User " + jobProxyUser + " has no permission to execute this job " + node.getJobId() + "!");
return false;
}
}
//job = JobWrappingFactory.getJobWrappingFactory().buildJobExecutor(node.getJobId(), props, logger);
try {
job = jobtypeManager.buildJobExecutor(node.getJobId(), props, logger);
}
catch (JobTypeManagerException e) {
logger.error("Failed to build job type, skipping this job");
return false;
}
}
return true;
}
private void runJob() {
try {
job.run();
} catch (Exception e) {
e.printStackTrace();
node.setStatus(Status.FAILED);
logError("Job run failed!");
logError(e.getMessage() + e.getCause());
return;
}
node.setStatus(Status.SUCCEEDED);
if (job != null) {
outputProps = job.getJobGeneratedProperties();
node.setOutputProps(outputProps);
}
}
public void cancel() {
synchronized (syncObject) {
logError("Cancel has been called.");
this.cancelled = true;
// Cancel code here
if (job == null) {
logError("Job hasn't started yet.");
// Just in case we're waiting on the delay
synchronized(this) {
this.notify();
}
return;
}
try {
job.cancel();
} catch (Exception e) {
logError(e.getMessage());
logError("Failed trying to cancel job. Maybe it hasn't started running yet or just finished.");
}
}
}
public boolean isCancelled() {
return cancelled;
}
public Status getStatus() {
return node.getStatus();
}
public Props getOutputProps() {
return outputProps;
}
private void logError(String message) {
if (logger != null) {
logger.error(message);
}
}
private void logInfo(String message) {
if (logger != null) {
logger.info(message);
}
}
public File getLogFile() {
return logFile;
}
public int getRetries() {
return props.getInt("retries", 0);
}
public long getRetryBackoff() {
return props.getLong("retry.backoff", 0);
}
public static String createLogFileName(int executionId, String jobId, int attempt) {
return attempt > 0 ? "_job." + executionId + "." + attempt + "." + jobId + ".log" : "_job." + executionId + "." + jobId + ".log";
}
}
|
src/java/azkaban/execapp/JobRunner.java
|
package azkaban.execapp;
/*
* Copyright 2012 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Collections;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import azkaban.execapp.event.BlockingStatus;
import azkaban.execapp.event.Event;
import azkaban.execapp.event.Event.Type;
import azkaban.execapp.event.EventHandler;
import azkaban.execapp.event.FlowWatcher;
import azkaban.executor.ExecutableNode;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.ExecutorManagerException;
import azkaban.executor.Status;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.AbstractProcessJob;
import azkaban.jobExecutor.Job;
import azkaban.jobtype.JobTypeManager;
import azkaban.jobtype.JobTypeManagerException;
import azkaban.utils.Props;
public class JobRunner extends EventHandler implements Runnable {
private static final Layout DEFAULT_LAYOUT = new PatternLayout("%d{dd-MM-yyyy HH:mm:ss z} %c{1} %p - %m\n");
private ExecutorLoader loader;
private Props props;
private Props outputProps;
private ExecutableNode node;
private File workingDir;
private Logger logger = null;
private Layout loggerLayout = DEFAULT_LAYOUT;
private Logger flowLogger = null;
private Appender jobAppender;
private File logFile;
private Job job;
private int executionId = -1;
private static final Object logCreatorLock = new Object();
private Object syncObject = new Object();
private final JobTypeManager jobtypeManager;
// Used by the job to watch and block against another flow
private Integer pipelineLevel = null;
private FlowWatcher watcher = null;
private Set<String> pipelineJobs = new HashSet<String>();
private Set<String> proxyUsers = null;
private String jobLogChunkSize;
private int jobLogBackupIndex;
private long delayStartMs = 0;
private boolean cancelled = false;
public JobRunner(ExecutableNode node, Props props, File workingDir, ExecutorLoader loader, JobTypeManager jobtypeManager) {
this.props = props;
this.node = node;
this.workingDir = workingDir;
this.executionId = node.getExecutionId();
this.loader = loader;
this.jobtypeManager = jobtypeManager;
}
public void setValidatedProxyUsers(Set<String> proxyUsers) {
this.proxyUsers = proxyUsers;
}
public void setLogSettings(Logger flowLogger, String logFileChuckSize, int numLogBackup ) {
this.flowLogger = flowLogger;
this.jobLogChunkSize = logFileChuckSize;
this.jobLogBackupIndex = numLogBackup;
}
public Props getProps() {
return props;
}
public void setPipeline(FlowWatcher watcher, int pipelineLevel) {
this.watcher = watcher;
this.pipelineLevel = pipelineLevel;
if (this.pipelineLevel == 1) {
pipelineJobs.add(node.getJobId());
}
else if (this.pipelineLevel == 2) {
pipelineJobs.add(node.getJobId());
pipelineJobs.addAll(node.getOutNodes());
}
}
public void setDelayStart(long delayMS) {
delayStartMs = delayMS;
}
public long getDelayStart() {
return delayStartMs;
}
public ExecutableNode getNode() {
return node;
}
public String getLogFilePath() {
return logFile == null ? null : logFile.getPath();
}
private void createLogger() {
// Create logger
synchronized (logCreatorLock) {
String loggerName = System.currentTimeMillis() + "." + executionId + "." + node.getJobId();
logger = Logger.getLogger(loggerName);
// Create file appender
String logName = createLogFileName(node.getExecutionId(), node.getJobId(), node.getAttempt());
logFile = new File(workingDir, logName);
String absolutePath = logFile.getAbsolutePath();
jobAppender = null;
try {
RollingFileAppender fileAppender = new RollingFileAppender(loggerLayout, absolutePath, true);
fileAppender.setMaxBackupIndex(jobLogBackupIndex);
fileAppender.setMaxFileSize(jobLogChunkSize);
jobAppender = fileAppender;
logger.addAppender(jobAppender);
} catch (IOException e) {
flowLogger.error("Could not open log file in " + workingDir + " for job " + node.getJobId(), e);
}
}
}
private void closeLogger() {
if (jobAppender != null) {
logger.removeAppender(jobAppender);
jobAppender.close();
}
}
private void writeStatus() {
try {
node.setUpdateTime(System.currentTimeMillis());
loader.updateExecutableNode(node);
} catch (ExecutorManagerException e) {
flowLogger.error("Could not update job properties in db for " + node.getJobId(), e);
}
}
@Override
public void run() {
Thread.currentThread().setName("JobRunner-" + node.getJobId() + "-" + executionId);
if (node.getStatus() == Status.DISABLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.SKIPPED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
} else if (this.cancelled) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setStatus(Status.FAILED);
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
} else if (node.getStatus() == Status.FAILED || node.getStatus() == Status.KILLED) {
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
else {
createLogger();
node.setUpdateTime(System.currentTimeMillis());
// For pipelining of jobs. Will watch other jobs.
if (!pipelineJobs.isEmpty()) {
String blockedList = "";
ArrayList<BlockingStatus> blockingStatus = new ArrayList<BlockingStatus>();
for (String waitingJobId : pipelineJobs) {
Status status = watcher.peekStatus(waitingJobId);
if (status != null && !Status.isStatusFinished(status)) {
BlockingStatus block = watcher.getBlockingStatus(waitingJobId);
blockingStatus.add(block);
blockedList += waitingJobId + ",";
}
}
if (!blockingStatus.isEmpty()) {
logger.info("Pipeline job " + node.getJobId() + " waiting on " + blockedList + " in execution " + watcher.getExecId());
for(BlockingStatus bStatus: blockingStatus) {
logger.info("Waiting on pipelined job " + bStatus.getJobId());
bStatus.blockOnFinishedStatus();
logger.info("Pipelined job " + bStatus.getJobId() + " finished.");
}
}
if (watcher.isWatchCancelled()) {
logger.info("Job was cancelled while waiting on pipeline. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
long currentTime = System.currentTimeMillis();
if (delayStartMs > 0) {
logger.info("Delaying start of execution for " + delayStartMs + " milliseconds.");
synchronized(this) {
try {
this.wait(delayStartMs);
logger.info("Execution has been delayed for " + delayStartMs + " ms. Continuing with execution.");
} catch (InterruptedException e) {
logger.error("Job " + node.getJobId() + " was to be delayed for " + delayStartMs + ". Interrupted after " + (System.currentTimeMillis() - currentTime));
}
}
if (cancelled) {
logger.info("Job was cancelled while in delay. Quiting.");
node.setStartTime(System.currentTimeMillis());
node.setEndTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_FINISHED));
return;
}
}
node.setStartTime(System.currentTimeMillis());
fireEvent(Event.create(this, Type.JOB_STARTED, null, false));
try {
loader.uploadExecutableNode(node, props);
} catch (ExecutorManagerException e1) {
logger.error("Error writing initial node properties");
}
if (prepareJob()) {
writeStatus();
fireEvent(Event.create(this, Type.JOB_STATUS_CHANGED), false);
runJob();
}
else {
node.setStatus(Status.FAILED);
logError("Job run failed!");
}
node.setEndTime(System.currentTimeMillis());
logInfo("Finishing job " + node.getJobId() + " at " + node.getEndTime());
closeLogger();
writeStatus();
if (logFile != null) {
try {
File[] files = logFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(logFile.getName());
}
}
);
Arrays.sort(files, Collections.reverseOrder());
loader.uploadLogFile(executionId, node.getJobId(), node.getAttempt(), files);
} catch (ExecutorManagerException e) {
flowLogger.error("Error writing out logs for job " + node.getJobId(), e);
}
}
else {
flowLogger.info("Log file for job " + node.getJobId() + " is null");
}
}
fireEvent(Event.create(this, Type.JOB_FINISHED));
}
private void fireEvent(Event event) {
fireEvent(event, true);
}
private void fireEvent(Event event, boolean updateTime) {
if (updateTime) {
node.setUpdateTime(System.currentTimeMillis());
}
this.fireEventListeners(event);
}
private boolean prepareJob() throws RuntimeException {
// Check pre conditions
if (props == null || cancelled) {
logError("Failing job. The job properties don't exist");
return false;
}
synchronized(syncObject) {
if (node.getStatus() == Status.FAILED || cancelled) {
return false;
}
if (node.getAttempt() > 0) {
logInfo("Starting job " + node.getJobId() + " attempt " + node.getAttempt() + " at " + node.getStartTime());
}
else {
logInfo("Starting job " + node.getJobId() + " at " + node.getStartTime());
}
props.put(CommonJobProperties.JOB_ATTEMPT, node.getAttempt());
node.setStatus(Status.RUNNING);
// Ability to specify working directory
if (!props.containsKey(AbstractProcessJob.WORKING_DIR)) {
props.put(AbstractProcessJob.WORKING_DIR, workingDir.getAbsolutePath());
}
if(props.containsKey("user.to.proxy")) {
String jobProxyUser = props.getString("user.to.proxy");
if(proxyUsers != null && !proxyUsers.contains(jobProxyUser)) {
logger.error("User " + jobProxyUser + " has no permission to execute this job " + node.getJobId() + "!");
return false;
}
}
//job = JobWrappingFactory.getJobWrappingFactory().buildJobExecutor(node.getJobId(), props, logger);
try {
job = jobtypeManager.buildJobExecutor(node.getJobId(), props, logger);
}
catch (JobTypeManagerException e) {
logger.error("Failed to build job type, skipping this job");
return false;
}
}
return true;
}
private void runJob() {
try {
job.run();
} catch (Exception e) {
e.printStackTrace();
node.setStatus(Status.FAILED);
logError("Job run failed!");
logError(e.getMessage() + e.getCause());
return;
}
node.setStatus(Status.SUCCEEDED);
if (job != null) {
outputProps = job.getJobGeneratedProperties();
node.setOutputProps(outputProps);
}
}
public void cancel() {
synchronized (syncObject) {
logError("Cancel has been called.");
this.cancelled = true;
// Cancel code here
if (job == null) {
logError("Job hasn't started yet.");
// Just in case we're waiting on the delay
synchronized(this) {
this.notify();
}
return;
}
try {
job.cancel();
} catch (Exception e) {
logError(e.getMessage());
logError("Failed trying to cancel job. Maybe it hasn't started running yet or just finished.");
}
}
}
public boolean isCancelled() {
return cancelled;
}
public Status getStatus() {
return node.getStatus();
}
public Props getOutputProps() {
return outputProps;
}
private void logError(String message) {
if (logger != null) {
logger.error(message);
}
}
private void logInfo(String message) {
if (logger != null) {
logger.info(message);
}
}
public File getLogFile() {
return logFile;
}
public int getRetries() {
return props.getInt("retries", 0);
}
public long getRetryBackoff() {
return props.getLong("retry.backoff", 0);
}
public static String createLogFileName(int executionId, String jobId, int attempt) {
return attempt > 0 ? "_job." + executionId + "." + attempt + "." + jobId + ".log" : "_job." + executionId + "." + jobId + ".log";
}
}
|
Fixing issue where cancelling a blocked job won't result in it getting killed properly.
|
src/java/azkaban/execapp/JobRunner.java
|
Fixing issue where cancelling a blocked job won't result in it getting killed properly.
|
|
Java
|
apache-2.0
|
317fd70bf33f6c0ff9efb45eee3abe270b23a5c9
| 0
|
way1989/v2ex,chowxiaojun/v2ex,taoliuh/v2ex,lizhangqu/v2ex
|
package com.sonaive.v2ex.ui;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import com.sonaive.v2ex.R;
import com.sonaive.v2ex.ui.widgets.DrawShadowFrameLayout;
import com.sonaive.v2ex.ui.widgets.OnQueryListener;
import com.sonaive.v2ex.ui.widgets.SimpleSearchView;
import com.sonaive.v2ex.util.UIUtils;
import static com.sonaive.v2ex.util.LogUtils.makeLogTag;
/**
* Created by liutao on 1/1/15.
*/
public class SearchActivity extends BaseActivity implements OnQueryListener {
private static final String TAG = makeLogTag(SearchActivity.class);
public static final int EXTRA_SEARCH_FEEDS = 1;
public static final int EXTRA_SEARCH_NODES = 2;
private static final String ARG_ACTION_SEARCH = "action_search";
private static final String ARG_SHOW_SEARCH_FRG = "show_search_frg";
/** The handler message for updating the search query. */
private static final int MESSAGE_QUERY_UPDATE = 1;
/** The delay before actual requerying in millisecs. */
private static final int QUERY_UPDATE_DELAY_MILLIS = 2000;
FragmentManager fm;
FeedsFragment mFeedsFragment = null;
NodesFragment mNodesFragment = null;
SearchFragment mSearchFragment = null;
SimpleSearchView searchView;
private DrawShadowFrameLayout mDrawShadowFrameLayout;
private FrameLayout feedsFrgContainer;
private FrameLayout nodesFrgContainer;
private FrameLayout searchFrgContainer;
private View mButterBar;
private boolean isShowSearchFragment = true;
private int actionSearch;
String mQuery = "";
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_QUERY_UPDATE) {
Bundle args = (Bundle) msg.obj;
if (args != null) {
String keyword = args.getString("keyword");
if (mSearchFragment == null) {
mSearchFragment = (SearchFragment) getFragmentManager().findFragmentByTag("search_fragment");
}
mSearchFragment.updateLocalRecords(keyword);
}
}
}
};
public static Intent getCallingIntent(Context context, int extra) {
Intent intent = new Intent(context, SearchActivity.class);
intent.putExtra(ARG_ACTION_SEARCH, extra);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
if (savedInstanceState != null) {
actionSearch = savedInstanceState.getInt(ARG_ACTION_SEARCH);
isShowSearchFragment = savedInstanceState.getBoolean(ARG_SHOW_SEARCH_FRG);
} else {
actionSearch = getIntent().getIntExtra(ARG_ACTION_SEARCH, 0);
}
Toolbar toolbar = getActionBarToolbar();
toolbar.setNavigationIcon(R.drawable.ic_up_grey);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mDrawShadowFrameLayout = (DrawShadowFrameLayout) findViewById(R.id.main_content);
feedsFrgContainer = (FrameLayout) findViewById(R.id.feeds_fragment_container);
nodesFrgContainer = (FrameLayout) findViewById(R.id.nodes_fragment_container);
searchFrgContainer = (FrameLayout) findViewById(R.id.search_fragment_container);
mButterBar = findViewById(R.id.butter_bar);
feedsFrgContainer.setVisibility(View.INVISIBLE);
nodesFrgContainer.setVisibility(View.INVISIBLE);
searchFrgContainer.setVisibility(View.VISIBLE);
fm = getFragmentManager();
String query = getIntent().getStringExtra(SearchManager.QUERY);
query = query == null ? "" : query;
mQuery = query;
overridePendingTransition(0, 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(ARG_ACTION_SEARCH, actionSearch);
outState.putBoolean(ARG_SHOW_SEARCH_FRG, isShowSearchFragment);
}
@Override
protected Toolbar getActionBarToolbar() {
Toolbar actionBarToolbar = super.getActionBarToolbar();
searchView = (SimpleSearchView) actionBarToolbar.findViewById(R.id.search_view);
if (searchView != null) {
searchView.setOnQueryListener(this);
if (actionSearch == EXTRA_SEARCH_FEEDS) {
searchView.setHint(R.string.hint_search_title);
} else {
searchView.setHint(R.string.hint_search_nodes);
}
}
return actionBarToolbar;
}
@Override
protected void onResume() {
super.onResume();
mFeedsFragment = (FeedsFragment) getFragmentManager().findFragmentById(R.id.feeds_fragment);
mNodesFragment = (NodesFragment) getFragmentManager().findFragmentById(R.id.nodes_fragment);
mSearchFragment = (SearchFragment) getFragmentManager().findFragmentById(R.id.search_fragment);
checkShowNoNetworkButterBar();
updateFragContentTopClearance();
}
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
overridePendingTransition(0, 0);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onNetworkChange() {
checkShowNoNetworkButterBar();
}
// Updates the Feeds fragment content top clearance to take our chrome into account
private void updateFragContentTopClearance() {
if (mSearchFragment == null || mFeedsFragment == null || mNodesFragment == null) {
return;
}
final boolean butterBarVisible = mButterBar != null
&& mButterBar.getVisibility() == View.VISIBLE;
int actionBarClearance = UIUtils.calculateActionBarSize(this);
int butterBarClearance = butterBarVisible
? getResources().getDimensionPixelSize(R.dimen.butter_bar_height) : 0;
mDrawShadowFrameLayout.setShadowTopOffset(actionBarClearance + butterBarClearance);
mFeedsFragment.setContentTopClearance(actionBarClearance + butterBarClearance, isActionBarShown());
mSearchFragment.setContentTopClearance(actionBarClearance + butterBarClearance);
mNodesFragment.setContentTopClearance(actionBarClearance + butterBarClearance);
}
private void onQuery(final String s) {
if (mSearchFragment == null || mFeedsFragment == null || mNodesFragment == null) {
mFeedsFragment = (FeedsFragment) getFragmentManager().findFragmentById(R.id.feeds_fragment);
mNodesFragment = (NodesFragment) getFragmentManager().findFragmentById(R.id.nodes_fragment);
mSearchFragment = (SearchFragment) getFragmentManager().findFragmentById(R.id.search_fragment);
}
if (s.trim().isEmpty()) {
if (actionSearch == EXTRA_SEARCH_FEEDS) {
fm.beginTransaction().show(mSearchFragment).hide(mFeedsFragment).commit();
feedsFrgContainer.setVisibility(View.INVISIBLE);
} else if (actionSearch == EXTRA_SEARCH_NODES) {
fm.beginTransaction().show(mSearchFragment).hide(mNodesFragment).commit();
nodesFrgContainer.setVisibility(View.INVISIBLE);
}
searchFrgContainer.setVisibility(View.VISIBLE);
isShowSearchFragment = true;
} else {
Bundle args = new Bundle();
args.putString("keyword", s);
args.putInt("menu", ITEM_SEARCH);
requestQueryUpdate(args);
if (actionSearch == EXTRA_SEARCH_FEEDS) {
if (mNodesFragment != null) {
fm.beginTransaction().show(mFeedsFragment).hide(mSearchFragment).remove(mNodesFragment).commit();
} else {
fm.beginTransaction().show(mFeedsFragment).hide(mSearchFragment).commit();
}
feedsFrgContainer.setVisibility(View.VISIBLE);
if (null != mFeedsFragment) {
mFeedsFragment.requestQueryUpdate(args);
}
} else if (actionSearch == EXTRA_SEARCH_NODES) {
if (mFeedsFragment != null) {
fm.beginTransaction().show(mNodesFragment).hide(mSearchFragment).remove(mFeedsFragment).commit();
} else {
fm.beginTransaction().show(mNodesFragment).hide(mSearchFragment).commit();
}
nodesFrgContainer.setVisibility(View.VISIBLE);
if (null != mNodesFragment) {
mNodesFragment.requestQueryUpdate(args);
}
}
searchFrgContainer.setVisibility(View.INVISIBLE);
isShowSearchFragment = false;
}
updateFragContentTopClearance();
}
void requestQueryUpdate(Bundle arguments) {
mHandler.removeMessages(MESSAGE_QUERY_UPDATE);
mHandler.sendMessageDelayed(Message.obtain(mHandler, MESSAGE_QUERY_UPDATE, arguments),
QUERY_UPDATE_DELAY_MILLIS);
}
private boolean checkShowNoNetworkButterBar() {
if (!isOnline()) {
UIUtils.setUpButterBar(mButterBar, getString(R.string.error_network_unavailable),
getString(R.string.close), new View.OnClickListener() {
@Override
public void onClick(View v) {
mButterBar.setVisibility(View.GONE);
updateFragContentTopClearance();
}
}
);
return true;
} else {
if (mButterBar.getVisibility() == View.VISIBLE) {
mButterBar.setVisibility(View.GONE);
updateFragContentTopClearance();
}
return false;
}
}
@Override
public void onSubmit(String s) {
onQuery(s);
}
@Override
public void onClear() {
onQuery("");
}
@Override
public void onQueryTextChange(String s) {
onQuery(s);
}
public void onEvent(String keyword) {
if (searchView != null) {
searchView.setText(keyword);
}
}
}
|
v2ex/src/main/java/com/sonaive/v2ex/ui/SearchActivity.java
|
package com.sonaive.v2ex.ui;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import com.sonaive.v2ex.R;
import com.sonaive.v2ex.ui.widgets.DrawShadowFrameLayout;
import com.sonaive.v2ex.ui.widgets.OnQueryListener;
import com.sonaive.v2ex.ui.widgets.SimpleSearchView;
import com.sonaive.v2ex.util.UIUtils;
import static com.sonaive.v2ex.util.LogUtils.makeLogTag;
/**
* Created by liutao on 1/1/15.
*/
public class SearchActivity extends BaseActivity implements OnQueryListener {
private static final String TAG = makeLogTag(SearchActivity.class);
public static final int EXTRA_SEARCH_FEEDS = 1;
public static final int EXTRA_SEARCH_NODES = 2;
private static final String ARG_ACTION_SEARCH = "action_search";
private static final String ARG_SHOW_SEARCH_FRG = "show_search_frg";
/** The handler message for updating the search query. */
private static final int MESSAGE_QUERY_UPDATE = 1;
/** The delay before actual requerying in millisecs. */
private static final int QUERY_UPDATE_DELAY_MILLIS = 2000;
FragmentManager fm;
FeedsFragment mFeedsFragment = null;
NodesFragment mNodesFragment = null;
SearchFragment mSearchFragment = null;
SimpleSearchView searchView;
private DrawShadowFrameLayout mDrawShadowFrameLayout;
private FrameLayout feedsFrgContainer;
private FrameLayout nodesFrgContainer;
private FrameLayout searchFrgContainer;
private View mButterBar;
private boolean isShowSearchFragment = true;
private int actionSearch;
String mQuery = "";
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_QUERY_UPDATE) {
Bundle args = (Bundle) msg.obj;
if (args != null) {
String keyword = args.getString("keyword");
if (mSearchFragment == null) {
mSearchFragment = (SearchFragment) getFragmentManager().findFragmentByTag("search_fragment");
}
mSearchFragment.updateLocalRecords(keyword);
}
}
}
};
public static Intent getCallingIntent(Context context, int extra) {
Intent intent = new Intent(context, SearchActivity.class);
intent.putExtra(ARG_ACTION_SEARCH, extra);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
if (savedInstanceState != null) {
actionSearch = savedInstanceState.getInt(ARG_ACTION_SEARCH);
isShowSearchFragment = savedInstanceState.getBoolean(ARG_SHOW_SEARCH_FRG);
} else {
actionSearch = getIntent().getIntExtra(ARG_ACTION_SEARCH, 0);
}
Toolbar toolbar = getActionBarToolbar();
toolbar.setNavigationIcon(R.drawable.ic_up_grey);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mDrawShadowFrameLayout = (DrawShadowFrameLayout) findViewById(R.id.main_content);
feedsFrgContainer = (FrameLayout) findViewById(R.id.feeds_fragment_container);
nodesFrgContainer = (FrameLayout) findViewById(R.id.nodes_fragment_container);
searchFrgContainer = (FrameLayout) findViewById(R.id.search_fragment_container);
mButterBar = findViewById(R.id.butter_bar);
feedsFrgContainer.setVisibility(View.INVISIBLE);
nodesFrgContainer.setVisibility(View.INVISIBLE);
searchFrgContainer.setVisibility(View.VISIBLE);
fm = getFragmentManager();
String query = getIntent().getStringExtra(SearchManager.QUERY);
query = query == null ? "" : query;
mQuery = query;
overridePendingTransition(0, 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(ARG_ACTION_SEARCH, actionSearch);
outState.putBoolean(ARG_SHOW_SEARCH_FRG, isShowSearchFragment);
}
@Override
protected Toolbar getActionBarToolbar() {
Toolbar actionBarToolbar = super.getActionBarToolbar();
searchView = (SimpleSearchView) actionBarToolbar.findViewById(R.id.search_view);
if (searchView != null) {
searchView.setOnQueryListener(this);
if (actionSearch == EXTRA_SEARCH_FEEDS) {
searchView.setHint(R.string.hint_search_title);
} else {
searchView.setHint(R.string.hint_search_nodes);
}
}
return actionBarToolbar;
}
@Override
protected void onResume() {
super.onResume();
mFeedsFragment = (FeedsFragment) getFragmentManager().findFragmentById(R.id.feeds_fragment);
mNodesFragment = (NodesFragment) getFragmentManager().findFragmentById(R.id.nodes_fragment);
mSearchFragment = (SearchFragment) getFragmentManager().findFragmentById(R.id.search_fragment);
checkShowNoNetworkButterBar();
updateFragContentTopClearance();
}
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
overridePendingTransition(0, 0);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onNetworkChange() {
checkShowNoNetworkButterBar();
}
// Updates the Feeds fragment content top clearance to take our chrome into account
private void updateFragContentTopClearance() {
if (mSearchFragment == null || mFeedsFragment == null || mNodesFragment == null) {
return;
}
final boolean butterBarVisible = mButterBar != null
&& mButterBar.getVisibility() == View.VISIBLE;
int actionBarClearance = UIUtils.calculateActionBarSize(this);
int butterBarClearance = butterBarVisible
? getResources().getDimensionPixelSize(R.dimen.butter_bar_height) : 0;
mDrawShadowFrameLayout.setShadowTopOffset(actionBarClearance + butterBarClearance);
mFeedsFragment.setContentTopClearance(actionBarClearance + butterBarClearance, isActionBarShown());
mSearchFragment.setContentTopClearance(actionBarClearance + butterBarClearance);
mNodesFragment.setContentTopClearance(actionBarClearance + butterBarClearance);
}
private void onQuery(final String s) {
if (mSearchFragment == null || mFeedsFragment == null || mNodesFragment == null) {
mFeedsFragment = (FeedsFragment) getFragmentManager().findFragmentById(R.id.feeds_fragment);
mNodesFragment = (NodesFragment) getFragmentManager().findFragmentById(R.id.nodes_fragment);
mSearchFragment = (SearchFragment) getFragmentManager().findFragmentById(R.id.search_fragment);
}
if (s.trim().isEmpty()) {
if (actionSearch == EXTRA_SEARCH_FEEDS) {
fm.beginTransaction().show(mSearchFragment).hide(mFeedsFragment).commit();
feedsFrgContainer.setVisibility(View.INVISIBLE);
} else if (actionSearch == EXTRA_SEARCH_NODES) {
fm.beginTransaction().show(mSearchFragment).hide(mNodesFragment).commit();
nodesFrgContainer.setVisibility(View.INVISIBLE);
}
searchFrgContainer.setVisibility(View.VISIBLE);
isShowSearchFragment = true;
} else {
Bundle args = new Bundle();
args.putString("keyword", s);
args.putInt("menu", ITEM_SEARCH);
requestQueryUpdate(args);
if (actionSearch == EXTRA_SEARCH_FEEDS) {
fm.beginTransaction().show(mFeedsFragment).hide(mSearchFragment).remove(mNodesFragment).commit();
feedsFrgContainer.setVisibility(View.VISIBLE);
if (null != mFeedsFragment) {
mFeedsFragment.requestQueryUpdate(args);
}
} else if (actionSearch == EXTRA_SEARCH_NODES) {
fm.beginTransaction().show(mNodesFragment).hide(mSearchFragment).remove(mFeedsFragment).commit();
nodesFrgContainer.setVisibility(View.VISIBLE);
if (null != mNodesFragment) {
mNodesFragment.requestQueryUpdate(args);
}
}
searchFrgContainer.setVisibility(View.INVISIBLE);
isShowSearchFragment = false;
}
updateFragContentTopClearance();
}
void requestQueryUpdate(Bundle arguments) {
mHandler.removeMessages(MESSAGE_QUERY_UPDATE);
mHandler.sendMessageDelayed(Message.obtain(mHandler, MESSAGE_QUERY_UPDATE, arguments),
QUERY_UPDATE_DELAY_MILLIS);
}
private boolean checkShowNoNetworkButterBar() {
if (!isOnline()) {
UIUtils.setUpButterBar(mButterBar, getString(R.string.error_network_unavailable),
getString(R.string.close), new View.OnClickListener() {
@Override
public void onClick(View v) {
mButterBar.setVisibility(View.GONE);
updateFragContentTopClearance();
}
}
);
return true;
} else {
if (mButterBar.getVisibility() == View.VISIBLE) {
mButterBar.setVisibility(View.GONE);
updateFragContentTopClearance();
}
return false;
}
}
@Override
public void onSubmit(String s) {
onQuery(s);
}
@Override
public void onClear() {
onQuery("");
}
@Override
public void onQueryTextChange(String s) {
onQuery(s);
}
public void onEvent(String keyword) {
if (searchView != null) {
searchView.setText(keyword);
}
}
}
|
fix crash.
|
v2ex/src/main/java/com/sonaive/v2ex/ui/SearchActivity.java
|
fix crash.
|
|
Java
|
apache-2.0
|
a65b9a49ed187b2f2a94b0e6086fc4165eaa2fb6
| 0
|
bither/bither-android,leerduo/bither-android,CryptArc/templecoin-bither,neurocis/bither-android
|
/*
* GridChart.java
* Android-Charts
*
* Created by limc on 2011/05/29.
*
* Copyright 2011 limc.cn All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.charts.view;
import java.util.List;
import net.bither.charts.event.ITouchEventResponse;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
*
* <p>
* GridChart is base type of all the charts that use a grid to display like
* line-chart stick-chart etc. GridChart implemented a simple grid with basic
* functions what can be used in it's inherited charts.
* </p>
* <p>
* GridChartは全部グリドチャートのベスクラスです、一部処理は共通化け実現した。
* </p>
* <p>
* GridChart是所有网格图表的基础类对象,它实现了基本的网格图表功能,这些功能将被它的继承类使用
* </p>
*
* @author limc
* @version v1.0 2011/05/30 14:19:50
*
*/
public class GridChart extends BaseChart {
public static final int AXIS_X_POSITION_BOTTOM = 1 << 0;
@Deprecated
public static final int AXIS_X_POSITION_TOP = 1 << 1;
public static final int AXIS_Y_POSITION_LEFT = 1 << 2;
public static final int AXIS_Y_POSITION_RIGHT = 1 << 3;
/**
* <p>
* default background color
* </p>
* <p>
* 背景の色のデフォルト値
* </p>
* <p>
* 默认背景色
* </p>
*/
public static final int DEFAULT_BACKGROUND_COLOR = Color.BLACK;
/**
* <p>
* default color of X axis
* </p>
* <p>
* X軸の色のデフォルト値
* </p>
* <p>
* 默认坐标轴X的显示颜色
* </p>
*/
public static final int DEFAULT_AXIS_X_COLOR = Color.TRANSPARENT;
/**
* <p>
* default color of Y axis
* </p>
* <p>
* Y軸の色のデフォルト値
* </p>
* <p>
* 默认坐标轴Y的显示颜色
* </p>
*/
public static final int DEFAULT_AXIS_Y_COLOR = Color.TRANSPARENT;
public static final float DEFAULT_AXIS_WIDTH = 1;
public static final int DEFAULT_AXIS_X_POSITION = AXIS_X_POSITION_BOTTOM;
public static final int DEFAULT_AXIS_Y_POSITION = AXIS_Y_POSITION_LEFT;
/**
* <p>
* default color of grid‘s longitude line
* </p>
* <p>
* 経線の色のデフォルト値
* </p>
* <p>
* 默认网格经线的显示颜色
* </p>
*/
public static final int DEFAULT_LONGITUDE_COLOR = Color.TRANSPARENT;
/**
* <p>
* default color of grid‘s latitude line
* </p>
* <p>
* 緯線の色のデフォルト値
* </p>
* <p>
* 默认网格纬线的显示颜色
* </p>
*/
public static final int DEFAULT_LAITUDE_COLOR = Color.TRANSPARENT;
/**
* <p>
* default margin of the axis to the left border
* </p>
* <p>
* 轴線より左枠線の距離のデフォルト値
* </p>
* <p>
* 默认轴线左边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_LEFT = 42f;
public static final float DEFAULT_AXIS_Y_TITLE_QUADRANT_WIDTH = 16f;
/**
* <p>
* default margin of the axis to the bottom border
* </p>
* <p>
* 轴線より下枠線の距離のデフォルト値
* </p>
* <p>
* 默认轴线下边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_BOTTOM = 16f;
public static final float DEFAULT_AXIS_X_TITLE_QUADRANT_HEIGHT = 16f;
/**
* <p>
* default margin of the axis to the top border
* </p>
* <p>
* 轴線より上枠線の距離のデフォルト値
* </p>
* <p>
* 默认轴线上边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_TOP = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_TOP = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_BOTTOM = 5f;
/**
* <p>
* default margin of the axis to the right border
* </p>
* <p>
* 轴線より右枠線の距離のデフォルト値
* </p>
* <p>
* 轴线右边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_RIGHT = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_LEFT = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_RIGHT = 5f;
/**
* <p>
* default numbers of grid‘s latitude line
* </p>
* <p>
* 緯線の数量のデフォルト値
* </p>
* <p>
* 网格纬线的数量
* </p>
*/
public static final int DEFAULT_LATITUDE_NUM = 4;
/**
* <p>
* default numbers of grid‘s longitude line
* </p>
* <p>
* 経線の数量のデフォルト値
* </p>
* <p>
* 网格经线的数量
* </p>
*/
public static final int DEFAULT_LONGITUDE_NUM = 3;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 経線を表示するか?
* </p>
* <p>
* 默认经线是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LONGITUDE = Boolean.TRUE;
/**
* <p>
* Should display longitude as dashed line?
* </p>
* <p>
* 経線を点線にするか?
* </p>
* <p>
* 默认经线是否显示为虚线
* </p>
*/
public static final boolean DEFAULT_DASH_LONGITUDE = Boolean.TRUE;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 緯線を表示するか?
* </p>
* <p>
* 纬线是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LATITUDE = Boolean.TRUE;
/**
* <p>
* Should display latitude as dashed line?
* </p>
* <p>
* 緯線を点線にするか?
* </p>
* <p>
* 纬线是否显示为虚线
* </p>
*/
public static final boolean DEFAULT_DASH_LATITUDE = Boolean.TRUE;
/**
* <p>
* Should display the degrees in X axis?
* </p>
* <p>
* X軸のタイトルを表示するか?
* </p>
* <p>
* X轴上的标题是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LONGITUDE_TITLE = Boolean.TRUE;
/**
* <p>
* Should display the degrees in Y axis?
* </p>
* <p>
* Y軸のタイトルを表示するか?
* </p>
* <p>
* 默认Y轴上的标题是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LATITUDE_TITLE = Boolean.TRUE;
/**
* <p>
* Should display the border?
* </p>
* <p>
* 枠を表示するか?
* </p>
* <p>
* 默认控件是否显示边框
* </p>
*/
public static final boolean DEFAULT_DISPLAY_BORDER = Boolean.TRUE;
/**
* <p>
* default color of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルの色のデフォルト値
* </p>
* <p>
* 默认经线刻度字体颜色
* </p>
*/
public static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
public static final float DEFAULT_BORDER_WIDTH = 1f;
/**
* <p>
* default color of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルの色のデフォルト値
* </p>
* <p>
* 经线刻度字体颜色
* </p>
*/
public static final int DEFAULT_LONGITUDE_FONT_COLOR = Color.WHITE;
/**
* <p>
* default font size of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルのフォントサイズのデフォルト値
* </p>
* <p>
* 经线刻度字体大小
* </p>
*/
public static final int DEFAULT_LONGITUDE_FONT_SIZE = 14;
/**
* <p>
* default color of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルの色のデフォルト値
* </p>
* <p>
* 纬线刻度字体颜色
* </p>
*/
public static final int DEFAULT_LATITUDE_FONT_COLOR = Color.RED;
/**
* <p>
* default font size of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルのフォントサイズのデフォルト値
* </p>
* <p>
* 默认纬线刻度字体大小
* </p>
*/
public static final int DEFAULT_LATITUDE_FONT_SIZE =14;
public static final int DEFAULT_CROSS_LINES_COLOR = Color.CYAN;
public static final int DEFAULT_CROSS_LINES_FONT_COLOR = Color.CYAN;
/**
* <p>
* default titles' max length for display of Y axis
* </p>
* <p>
* Y軸の表示用タイトルの最大文字長さのデフォルト値
* </p>
* <p>
* 默认Y轴标题最大文字长度
* </p>
*/
public static final int DEFAULT_LATITUDE_MAX_TITLE_LENGTH = 5;
/**
* <p>
* default dashed line type
* </p>
* <p>
* 点線タイプのデフォルト値
* </p>
* <p>
* 默认虚线效果
* </p>
*/
public static final PathEffect DEFAULT_DASH_EFFECT = new DashPathEffect(
new float[] { 3, 3, 3, 3 }, 1);
/**
* <p>
* Should display the Y cross line if grid is touched?
* </p>
* <p>
* タッチしたポイントがある場合、十字線の垂直線を表示するか?
* </p>
* <p>
* 默认在控件被点击时,显示十字竖线线
* </p>
*/
public static final boolean DEFAULT_DISPLAY_CROSS_X_ON_TOUCH = true;
/**
* <p>
* Should display the Y cross line if grid is touched?
* </p>
* <p>
* タッチしたポイントがある場合、十字線の水平線を表示するか?
* </p>
* <p>
* 默认在控件被点击时,显示十字横线线
* </p>
*/
public static final boolean DEFAULT_DISPLAY_CROSS_Y_ON_TOUCH = true;
/**
* <p>
* Color of X axis
* </p>
* <p>
* X軸の色
* </p>
* <p>
* 坐标轴X的显示颜色
* </p>
*/
private int axisXColor = DEFAULT_AXIS_X_COLOR;
/**
* <p>
* Color of Y axis
* </p>
* <p>
* Y軸の色
* </p>
* <p>
* 坐标轴Y的显示颜色
* </p>
*/
private int axisYColor = DEFAULT_AXIS_Y_COLOR;
private float axisWidth = DEFAULT_AXIS_WIDTH;
protected int axisXPosition = DEFAULT_AXIS_X_POSITION;
protected int axisYPosition = DEFAULT_AXIS_Y_POSITION;
/**
* <p>
* Color of grid‘s longitude line
* </p>
* <p>
* 経線の色
* </p>
* <p>
* 网格经线的显示颜色
* </p>
*/
private int longitudeColor = DEFAULT_LONGITUDE_COLOR;
private int graduation = 1;
/**
* <p>
* Color of grid‘s latitude line
* </p>
* <p>
* 緯線の色
* </p>
* <p>
* 网格纬线的显示颜色
* </p>
*/
private int latitudeColor = DEFAULT_LAITUDE_COLOR;
/**
* <p>
* Margin of the axis to the left border
* </p>
* <p>
* 轴線より左枠線の距離
* </p>
* <p>
* 轴线左边距
* </p>
*/
protected float axisYTitleQuadrantWidth = DEFAULT_AXIS_Y_TITLE_QUADRANT_WIDTH;
/**
* <p>
* Margin of the axis to the bottom border
* </p>
* <p>
* 轴線より下枠線の距離
* </p>
* <p>
* 轴线下边距
* </p>
*/
protected float axisXTitleQuadrantHeight = DEFAULT_AXIS_X_TITLE_QUADRANT_HEIGHT;
/**
* <p>
* Margin of the axis to the top border
* </p>
* <p>
* 轴線より上枠線の距離
* </p>
* <p>
* 轴线上边距
* </p>
*/
protected float dataQuadrantPaddingTop = DEFAULT_DATA_QUADRANT_PADDING_TOP;
/**
* <p>
* Margin of the axis to the right border
* </p>
* <p>
* 轴線より右枠線の距離
* </p>
* <p>
* 轴线右边距
* </p>
*/
protected float dataQuadrantPaddingLeft = DEFAULT_DATA_QUADRANT_PADDING_LEFT;
protected float dataQuadrantPaddingBottom = DEFAULT_DATA_QUADRANT_PADDING_BOTTOM;
/**
* <p>
* Margin of the axis to the right border
* </p>
* <p>
* 轴線より右枠線の距離
* </p>
* <p>
* 轴线右边距
* </p>
*/
protected float dataQuadrantPaddingRight = DEFAULT_DATA_QUADRANT_PADDING_RIGHT;
/**
* <p>
* Should display the degrees in X axis?
* </p>
* <p>
* X軸のタイトルを表示するか?
* </p>
* <p>
* X轴上的标题是否显示
* </p>
*/
private boolean displayLongitudeTitle = DEFAULT_DISPLAY_LONGITUDE_TITLE;
/**
* <p>
* Should display the degrees in Y axis?
* </p>
* <p>
* Y軸のタイトルを表示するか?
* </p>
* <p>
* Y轴上的标题是否显示
* </p>
*/
private boolean displayLatitudeTitle = DEFAULT_DISPLAY_LATITUDE_TITLE;
/**
* <p>
* Numbers of grid‘s latitude line
* </p>
* <p>
* 緯線の数量
* </p>
* <p>
* 网格纬线的数量
* </p>
*/
protected int latitudeNum = DEFAULT_LATITUDE_NUM;
/**
* <p>
* Numbers of grid‘s longitude line
* </p>
* <p>
* 経線の数量
* </p>
* <p>
* 网格经线的数量
* </p>
*/
protected int longitudeNum = DEFAULT_LONGITUDE_NUM;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 経線を表示するか?
* </p>
* <p>
* 经线是否显示
* </p>
*/
private boolean displayLongitude = DEFAULT_DISPLAY_LONGITUDE;
/**
* <p>
* Should display longitude as dashed line?
* </p>
* <p>
* 経線を点線にするか?
* </p>
* <p>
* 经线是否显示为虚线
* </p>
*/
private boolean dashLongitude = DEFAULT_DASH_LONGITUDE;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 緯線を表示するか?
* </p>
* <p>
* 纬线是否显示
* </p>
*/
private boolean displayLatitude = DEFAULT_DISPLAY_LATITUDE;
/**
* <p>
* Should display latitude as dashed line?
* </p>
* <p>
* 緯線を点線にするか?
* </p>
* <p>
* 纬线是否显示为虚线
* </p>
*/
private boolean dashLatitude = DEFAULT_DASH_LATITUDE;
/**
* <p>
* dashed line type
* </p>
* <p>
* 点線タイプ?
* </p>
* <p>
* 虚线效果
* </p>
*/
private PathEffect dashEffect = DEFAULT_DASH_EFFECT;
/**
* <p>
* Should display the border?
* </p>
* <p>
* 枠を表示するか?
* </p>
* <p>
* 控件是否显示边框
* </p>
*/
private boolean displayBorder = DEFAULT_DISPLAY_BORDER;
/**
* <p>
* Color of grid‘s border line
* </p>
* <p>
* 枠線の色
* </p>
* <p>
* 图边框的颜色
* </p>
*/
private int borderColor = DEFAULT_BORDER_COLOR;
protected float borderWidth = DEFAULT_BORDER_WIDTH;
/**
* <p>
* Color of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルの色
* </p>
* <p>
* 经线刻度字体颜色
* </p>
*/
private int longitudeFontColor = DEFAULT_LONGITUDE_FONT_COLOR;
/**
* <p>
* Font size of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルのフォントサイズ
* </p>
* <p>
* 经线刻度字体大小
* </p>
*/
private int longitudeFontSize = DEFAULT_LONGITUDE_FONT_SIZE;
/**
* <p>
* Color of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルの色
* </p>
* <p>
* 纬线刻度字体颜色
* </p>
*/
private int latitudeFontColor = DEFAULT_LATITUDE_FONT_COLOR;
/**
* <p>
* Font size of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルのフォントサイズ
* </p>
* <p>
* 纬线刻度字体大小
* </p>
*/
private int latitudeFontSize = DEFAULT_LATITUDE_FONT_SIZE;
/**
* <p>
* Color of cross line inside grid when touched
* </p>
* <p>
* タッチしたポイント表示用十字線の色
* </p>
* <p>
* 十字交叉线颜色
* </p>
*/
private int crossLinesColor = DEFAULT_CROSS_LINES_COLOR;
/**
* <p>
* Color of cross line degree text when touched
* </p>
* <p>
* タッチしたポイント表示用十字線度数文字の色
* </p>
* <p>
* 十字交叉线坐标轴字体颜色
* </p>
*/
private int crossLinesFontColor = DEFAULT_CROSS_LINES_FONT_COLOR;
/**
* <p>
* Titles Array for display of X axis
* </p>
* <p>
* X軸の表示用タイトル配列
* </p>
* <p>
* X轴标题数组
* </p>
*/
private List<String> longitudeTitles;
/**
* <p>
* Titles for display of Y axis
* </p>
* <p>
* Y軸の表示用タイトル配列
* </p>
* <p>
* Y轴标题数组
* </p>
*/
private List<String> latitudeTitles;
/**
* <p>
* Titles' max length for display of Y axis
* </p>
* <p>
* Y軸の表示用タイトルの最大文字長さ
* </p>
* <p>
* Y轴标题最大文字长度
* </p>
*/
private int latitudeMaxTitleLength = DEFAULT_LATITUDE_MAX_TITLE_LENGTH;
/**
* <p>
* Touched point inside of grid
* </p>
* <p>
* タッチしたポイント
* </p>
* <p>
* 单点触控的选中点
* </p>
*/
private PointF touchPoint;
/**
* <p>
* Touched point’s X value inside of grid
* </p>
* <p>
* タッチしたポイントのX
* </p>
* <p>
* 单点触控的选中点的X
* </p>
*/
private float clickPostX;
/**
* <p>
* Touched point’s Y value inside of grid
* </p>
* <p>
* タッチしたポイントのY
* </p>
* <p>
* 单点触控的选中点的Y
* </p>
*/
private float clickPostY;
private ITouchEventResponse iTouchEventResponse;
private float tounchPrepcentage = 0;
/*
* (non-Javadoc)
*
* @param context
*
* @see cn.limc.androidcharts.view.BaseChart#BaseChart(Context)
*/
public GridChart(Context context) {
super(context);
}
/*
* (non-Javadoc)
*
* @param context
*
* @param attrs
*
* @param defStyle
*
* @see cn.limc.androidcharts.view.BaseChart#BaseChart(Context,
* AttributeSet, int)
*/
public GridChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/*
* (non-Javadoc)
*
* @param context
*
* @param attrs
*
* @see cn.limc.androidcharts.view.BaseChart#BaseChart(Context,
* AttributeSet)
*/
public GridChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
/*
* (non-Javadoc)
*
* <p>Called when is going to draw this chart<p> <p>チャートを書く前、メソッドを呼ぶ<p>
* <p>绘制图表时调用<p>
*
* @param canvas
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawXAxis(canvas);
drawYAxis(canvas);
if (this.displayBorder) {
drawBorder(canvas);
}
if (displayLongitude || displayLongitudeTitle) {
drawLongitudeLine(canvas);
drawLongitudeTitle(canvas);
}
if (displayLatitude || displayLatitudeTitle) {
drawLatitudeLine(canvas);
drawLatitudeTitle(canvas);
}
if (clickPostX <= 0) {
return;
}
drawPointOfLine(canvas, clickPostX);
}
/*
* (non-Javadoc)
*
* <p>Called when chart is touched<p> <p>チャートをタッチしたら、メソッドを呼ぶ<p>
* <p>图表点击时调用<p>
*
* @param event
*
* @see android.view.View#onTouchEvent(MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getX() < getDataQuadrantPaddingStartX()
|| event.getX() > getDataQuadrantPaddingEndX()) {
return false;
}
if (event.getY() < getDataQuadrantPaddingStartY()
|| event.getY() > getDataQuadrantPaddingEndY()) {
return false;
}
// touched points, if touch point is only one
if (event.getPointerCount() == 1) {
// 获取点击坐标
clickPostX = event.getX();
clickPostY = event.getY();
PointF point = new PointF(clickPostX, clickPostY);
touchPoint = point;
beginRedrawOnTouch(clickPostX);
// redraw
super.invalidate();
} else if (event.getPointerCount() == 2) {
}
return super.onTouchEvent(event);
}
protected void beginRedrawOnTouch(float clickPostX) {
float prepcentage = getAxisXPrecentage(clickPostX);
setTounchPrepcentage(prepcentage);
}
protected float getDataQuadrantWidth() {
return super.getWidth() - axisYTitleQuadrantWidth - 2 * borderWidth
- axisWidth;
}
protected float getDataQuadrantHeight() {
return super.getHeight() - axisXTitleQuadrantHeight - 2 * borderWidth
- axisWidth;
}
protected float getDataQuadrantStartX() {
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
return borderWidth + axisYTitleQuadrantWidth + axisWidth;
} else {
return borderWidth;
}
}
protected float getDataQuadrantPaddingStartX() {
return getDataQuadrantStartX() + dataQuadrantPaddingLeft;
}
protected float getDataQuadrantEndX() {
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
return super.getWidth() - borderWidth;
} else {
return super.getWidth() - borderWidth - axisYTitleQuadrantWidth
- axisWidth;
}
}
protected float getDataQuadrantPaddingEndX() {
return getDataQuadrantEndX() - dataQuadrantPaddingRight;
}
protected float getDataQuadrantStartY() {
return borderWidth;
}
protected float getDataQuadrantPaddingStartY() {
return getDataQuadrantStartY() + dataQuadrantPaddingTop;
}
protected float getDataQuadrantEndY() {
return super.getHeight() - borderWidth - axisXTitleQuadrantHeight
- axisWidth;
}
protected float getDataQuadrantPaddingEndY() {
return getDataQuadrantEndY() - dataQuadrantPaddingBottom;
}
protected float getDataQuadrantPaddingWidth() {
return getDataQuadrantWidth() - dataQuadrantPaddingLeft
- dataQuadrantPaddingRight;
}
protected float getDataQuadrantPaddingHeight() {
return getDataQuadrantHeight() - dataQuadrantPaddingTop
- dataQuadrantPaddingBottom;
}
/**
* <p>
* calculate degree title on X axis
* </p>
* <p>
* X軸の目盛を計算する
* </p>
* <p>
* 计算X轴上显示的坐标值
* </p>
*
* @param value
* <p>
* value for calculate
* </p>
* <p>
* 計算有用データ
* </p>
* <p>
* 计算用数据
* </p>
*
* @return String
* <p>
* degree
* </p>
* <p>
* 目盛
* </p>
* <p>
* 坐标值
* </p>
*/
public String getAxisXGraduate(Object value) {
float valueLength = ((Float) value).floatValue()
- getDataQuadrantPaddingStartX();
return String.valueOf(valueLength / this.getDataQuadrantPaddingWidth());
}
/**
* <p>
* calculate degree title on Y axis
* </p>
* <p>
* Y軸の目盛を計算する
* </p>
* <p>
* 计算Y轴上显示的坐标值
* </p>
*
* @param value
* <p>
* value for calculate
* </p>
* <p>
* 計算有用データ
* </p>
* <p>
* 计算用数据
* </p>
*
* @return String
* <p>
* degree
* </p>
* <p>
* 目盛
* </p>
* <p>
* 坐标值
* </p>
*/
public String getAxisYGraduate(Object value) {
float valueLength = ((Float) value).floatValue()
- getDataQuadrantPaddingStartY();
return String
.valueOf(valueLength / this.getDataQuadrantPaddingHeight());
}
protected void drawPointOfLine(Canvas canvas, float clickPostX) {
}
/**
* <p>
* draw border
* </p>
* <p>
* グラプのボーダーを書く
* </p>
* <p>
* 绘制边框
* </p>
*
* @param canvas
*/
protected void drawBorder(Canvas canvas) {
Paint mPaint = new Paint();
mPaint.setColor(borderColor);
mPaint.setStrokeWidth(borderWidth);
mPaint.setStyle(Style.STROKE);
// draw a rectangle
canvas.drawRect(borderWidth / 2, borderWidth / 2, super.getWidth()
- borderWidth / 2, super.getHeight() - borderWidth / 2, mPaint);
}
/**
* <p>
* draw X Axis
* </p>
* <p>
* X軸を書く
* </p>
* <p>
* 绘制X轴
* </p>
*
* @param canvas
*/
protected void drawXAxis(Canvas canvas) {
float length = super.getWidth();
float postY;
if (axisXPosition == AXIS_X_POSITION_BOTTOM) {
postY = super.getHeight() - axisXTitleQuadrantHeight - borderWidth
- axisWidth / 2;
} else {
postY = super.getHeight() - borderWidth - axisWidth / 2;
}
Paint mPaint = new Paint();
mPaint.setColor(axisXColor);
mPaint.setStrokeWidth(axisWidth);
canvas.drawLine(borderWidth, postY, length, postY, mPaint);
}
/**
* <p>
* draw Y Axis
* </p>
* <p>
* Y軸を書く
* </p>
* <p>
* 绘制Y轴
* </p>
*
* @param canvas
*/
protected void drawYAxis(Canvas canvas) {
float length = super.getHeight() - axisXTitleQuadrantHeight
- borderWidth;
float postX;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
postX = borderWidth + axisYTitleQuadrantWidth + axisWidth / 2;
} else {
postX = super.getWidth() - borderWidth - axisYTitleQuadrantWidth
- axisWidth / 2;
}
Paint mPaint = new Paint();
mPaint.setColor(axisXColor);
mPaint.setStrokeWidth(axisWidth);
canvas.drawLine(postX, borderWidth, postX, length, mPaint);
}
/**
* <p>
* draw longitude lines
* </p>
* <p>
* 経線を書く
* </p>
* <p>
* 绘制经线
* </p>
*
* @param canvas
*/
protected void drawLongitudeLine(Canvas canvas) {
if (null == longitudeTitles) {
return;
}
if (!displayLongitude) {
return;
}
int counts = longitudeTitles.size();
float length = getDataQuadrantHeight();
Paint mPaintLine = new Paint();
mPaintLine.setColor(longitudeColor);
if (dashLongitude) {
mPaintLine.setPathEffect(dashEffect);
}
if (counts > 1) {
float postOffset = this.getDataQuadrantPaddingWidth()
/ (counts - 1);
float offset;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
offset = borderWidth + axisYTitleQuadrantWidth + axisWidth
+ dataQuadrantPaddingLeft;
} else {
offset = borderWidth + dataQuadrantPaddingLeft;
}
for (int i = 0; i < counts; i++) {
canvas.drawLine(offset + i * postOffset, borderWidth, offset
+ i * postOffset, length, mPaintLine);
}
}
}
/**
* <p>
* draw longitude lines
* </p>
* <p>
* 経線を書く
* </p>
* <p>
* 绘制经线
* </p>
*
* @param canvas
*/
protected void drawLongitudeTitle(Canvas canvas) {
if (null == longitudeTitles) {
return;
}
if (!displayLongitude) {
return;
}
if (!displayLongitudeTitle) {
return;
}
if (longitudeTitles.size() <= 1) {
return;
}
Paint mPaintFont = new Paint();
mPaintFont.setColor(longitudeFontColor);
mPaintFont.setTextSize(longitudeFontSize);
mPaintFont.setAntiAlias(true);
float postOffset = this.getDataQuadrantPaddingWidth()
/ (longitudeTitles.size() - 1);
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
float offset = borderWidth + axisYTitleQuadrantWidth + axisWidth
+ dataQuadrantPaddingLeft;
for (int i = 0; i < longitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(longitudeTitles.get(i), offset,
super.getHeight() - axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
} else {
canvas.drawText(longitudeTitles.get(i),
offset + postOffset * 0.2f + i * postOffset
- (longitudeTitles.get(i).length())
* longitudeFontSize / 2f, super.getHeight()
- axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
}
}
} else {
float offset = borderWidth + dataQuadrantPaddingLeft;
for (int i = 0; i < longitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(longitudeTitles.get(i), offset,
super.getHeight() - axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
} else {
canvas.drawText(longitudeTitles.get(i),
offset + postOffset * 0.2f + i * postOffset
- (longitudeTitles.get(i).length())
* longitudeFontSize / 2f, super.getHeight()
- axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
}
}
}
}
/**
* <p>
* draw latitude lines
* </p>
* <p>
* 緯線を書く
* </p>
* <p>
* 绘制纬线
* </p>
*
* @param canvas
*/
protected void drawLatitudeLine(Canvas canvas) {
if (null == latitudeTitles) {
return;
}
if (!displayLatitude) {
return;
}
if (!displayLatitudeTitle) {
return;
}
if (latitudeTitles.size() <= 1) {
return;
}
float length = getDataQuadrantWidth();
Paint mPaintLine = new Paint();
mPaintLine.setColor(latitudeColor);
if (dashLatitude) {
mPaintLine.setPathEffect(dashEffect);
}
Paint mPaintFont = new Paint();
mPaintFont.setColor(latitudeFontColor);
mPaintFont.setTextSize(latitudeFontSize);
mPaintFont.setAntiAlias(true);
float postOffset = this.getDataQuadrantPaddingHeight()
/ (latitudeTitles.size() - 1);
float offset = super.getHeight() - borderWidth
- axisXTitleQuadrantHeight - axisWidth
- dataQuadrantPaddingBottom;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
float startFrom = borderWidth + axisYTitleQuadrantWidth + axisWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
canvas.drawLine(startFrom, offset - i * postOffset, startFrom
+ length, offset - i * postOffset, mPaintLine);
}
} else {
float startFrom = borderWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
canvas.drawLine(startFrom, offset - i * postOffset, startFrom
+ length, offset - i * postOffset, mPaintLine);
}
}
}
/**
* <p>
* draw latitude lines
* </p>
* <p>
* 緯線を書く
* </p>
* <p>
* 绘制纬线
* </p>
*
* @param canvas
*/
protected void drawLatitudeTitle(Canvas canvas) {
if (null == latitudeTitles) {
return;
}
if (!displayLatitudeTitle) {
return;
}
if (latitudeTitles.size() <= 1) {
return;
}
Paint mPaintFont = new Paint();
mPaintFont.setColor(latitudeFontColor);
mPaintFont.setTextSize(latitudeFontSize);
mPaintFont.setAntiAlias(true);
float postOffset = this.getDataQuadrantPaddingHeight()
/ (latitudeTitles.size() - 1);
float offset = super.getHeight() - borderWidth
- axisXTitleQuadrantHeight - axisWidth
- dataQuadrantPaddingBottom;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
float startFrom = borderWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(latitudeTitles.get(i), startFrom,
super.getHeight() - this.axisXTitleQuadrantHeight
- borderWidth - axisWidth - 2f, mPaintFont);
} else {
canvas.drawText(latitudeTitles.get(i), startFrom, offset
- i * postOffset + latitudeFontSize / 2f,
mPaintFont);
}
}
} else {
float startFrom = super.getWidth() - borderWidth
- axisYTitleQuadrantWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(latitudeTitles.get(i), startFrom,
super.getHeight() - this.axisXTitleQuadrantHeight
- borderWidth - axisWidth - 2f, mPaintFont);
} else {
canvas.drawText(latitudeTitles.get(i), startFrom, offset
- i * postOffset + latitudeFontSize / 2f,
mPaintFont);
}
}
}
}
/**
* <p>
* Zoom in the graph
* </p>
* <p>
* 拡大表示する。
* </p>
* <p>
* 放大表示
* </p>
*/
protected void zoomIn() {
// DO NOTHING
}
/**
* <p>
* Zoom out the grid
* </p>
* <p>
* 縮小表示する。
* </p>
* <p>
* 缩小
* </p>
*/
protected void zoomOut() {
// DO NOTHING
}
/*
* (non-Javadoc)
*
* @param event
*
* @see
* cn.limc.androidcharts.event.ITouchEventResponse#notifyEvent(GridChart)
*/
public void notifyEvent(GridChart chart) {
PointF point = chart.getTouchPoint();
if (null != point) {
clickPostX = point.x;
clickPostY = point.y;
}
touchPoint = new PointF(clickPostX, clickPostY);
super.invalidate();
}
/**
* @return the axisXColor
*/
public int getAxisXColor() {
return axisXColor;
}
/**
* @param axisXColor
* the axisXColor to set
*/
public void setAxisXColor(int axisXColor) {
this.axisXColor = axisXColor;
}
/**
* @return the axisYColor
*/
public int getAxisYColor() {
return axisYColor;
}
/**
* @param axisYColor
* the axisYColor to set
*/
public void setAxisYColor(int axisYColor) {
this.axisYColor = axisYColor;
}
/**
* @return the axisWidth
*/
public float getAxisWidth() {
return axisWidth;
}
/**
* @param axisWidth
* the axisWidth to set
*/
public void setAxisWidth(float axisWidth) {
this.axisWidth = axisWidth;
}
/**
* @return the longitudeColor
*/
public int getLongitudeColor() {
return longitudeColor;
}
/**
* @param longitudeColor
* the longitudeColor to set
*/
public void setLongitudeColor(int longitudeColor) {
this.longitudeColor = longitudeColor;
}
/**
* @return the latitudeColor
*/
public int getLatitudeColor() {
return latitudeColor;
}
/**
* @param latitudeColor
* the latitudeColor to set
*/
public void setLatitudeColor(int latitudeColor) {
this.latitudeColor = latitudeColor;
}
/**
* @return the axisMarginLeft
*/
@Deprecated
public float getAxisMarginLeft() {
return axisYTitleQuadrantWidth;
}
/**
* @param axisMarginLeft
* the axisMarginLeft to set
*/
@Deprecated
public void setAxisMarginLeft(float axisMarginLeft) {
this.axisYTitleQuadrantWidth = axisMarginLeft;
}
/**
* @return the axisMarginLeft
*/
public float getAxisYTitleQuadrantWidth() {
return axisYTitleQuadrantWidth;
}
/**
* @param axisYTitleQuadrantWidth
* the axisYTitleQuadrantWidth to set
*/
public void setAxisYTitleQuadrantWidth(float axisYTitleQuadrantWidth) {
this.axisYTitleQuadrantWidth = axisYTitleQuadrantWidth;
}
/**
* @return the axisXTitleQuadrantHeight
*/
@Deprecated
public float getAxisMarginBottom() {
return axisXTitleQuadrantHeight;
}
/**
* @param axisXTitleQuadrantHeight
* the axisXTitleQuadrantHeight to set
*/
@Deprecated
public void setAxisMarginBottom(float axisXTitleQuadrantHeight) {
this.axisXTitleQuadrantHeight = axisXTitleQuadrantHeight;
}
/**
* @return the axisXTitleQuadrantHeight
*/
public float getAxisXTitleQuadrantHeight() {
return axisXTitleQuadrantHeight;
}
/**
* @param axisXTitleQuadrantHeight
* the axisXTitleQuadrantHeight to set
*/
public void setAxisXTitleQuadrantHeight(float axisXTitleQuadrantHeight) {
this.axisXTitleQuadrantHeight = axisXTitleQuadrantHeight;
}
/**
* @return the dataQuadrantPaddingTop
*/
@Deprecated
public float getAxisMarginTop() {
return dataQuadrantPaddingTop;
}
/**
* @param axisMarginTop
* the axisMarginTop to set
*/
@Deprecated
public void setAxisMarginTop(float axisMarginTop) {
this.dataQuadrantPaddingTop = axisMarginTop;
this.dataQuadrantPaddingBottom = axisMarginTop;
}
/**
* @return the dataQuadrantPaddingRight
*/
@Deprecated
public float getAxisMarginRight() {
return dataQuadrantPaddingRight;
}
/**
* @param axisMarginRight
* the axisMarginRight to set
*/
@Deprecated
public void setAxisMarginRight(float axisMarginRight) {
this.dataQuadrantPaddingRight = axisMarginRight;
this.dataQuadrantPaddingLeft = axisMarginRight;
}
/**
* @return the dataQuadrantPaddingTop
*/
public float getDataQuadrantPaddingTop() {
return dataQuadrantPaddingTop;
}
/**
* @param dataQuadrantPaddingTop
* the dataQuadrantPaddingTop to set
*/
public void setDataQuadrantPaddingTop(float dataQuadrantPaddingTop) {
this.dataQuadrantPaddingTop = dataQuadrantPaddingTop;
}
/**
* @return the dataQuadrantPaddingLeft
*/
public float getDataQuadrantPaddingLeft() {
return dataQuadrantPaddingLeft;
}
/**
* @param dataQuadrantPaddingLeft
* the dataQuadrantPaddingLeft to set
*/
public void setDataQuadrantPaddingLeft(float dataQuadrantPaddingLeft) {
this.dataQuadrantPaddingLeft = dataQuadrantPaddingLeft;
}
/**
* @return the dataQuadrantPaddingBottom
*/
public float getDataQuadrantPaddingBottom() {
return dataQuadrantPaddingBottom;
}
/**
* @param dataQuadrantPaddingBottom
* the dataQuadrantPaddingBottom to set
*/
public void setDataQuadrantPaddingBottom(float dataQuadrantPaddingBottom) {
this.dataQuadrantPaddingBottom = dataQuadrantPaddingBottom;
}
/**
* @return the dataQuadrantPaddingRight
*/
public float getDataQuadrantPaddingRight() {
return dataQuadrantPaddingRight;
}
/**
* @param dataQuadrantPaddingRight
* the dataQuadrantPaddingRight to set
*/
public void setDataQuadrantPaddingRight(float dataQuadrantPaddingRight) {
this.dataQuadrantPaddingRight = dataQuadrantPaddingRight;
}
/**
* @param padding
* the dataQuadrantPaddingTop dataQuadrantPaddingBottom
* dataQuadrantPaddingLeft dataQuadrantPaddingRight to set
*
*/
public void setDataQuadrantPadding(float padding) {
this.dataQuadrantPaddingTop = padding;
this.dataQuadrantPaddingLeft = padding;
this.dataQuadrantPaddingBottom = padding;
this.dataQuadrantPaddingRight = padding;
}
/**
* @param topnbottom
* the dataQuadrantPaddingTop dataQuadrantPaddingBottom to set
* @param leftnright
* the dataQuadrantPaddingLeft dataQuadrantPaddingRight to set
*
*/
public void setDataQuadrantPadding(float topnbottom, float leftnright) {
this.dataQuadrantPaddingTop = topnbottom;
this.dataQuadrantPaddingLeft = leftnright;
this.dataQuadrantPaddingBottom = topnbottom;
this.dataQuadrantPaddingRight = leftnright;
}
/**
* @param top
* the dataQuadrantPaddingTop to set
* @param right
* the dataQuadrantPaddingLeft to set
* @param bottom
* the dataQuadrantPaddingBottom to set
* @param left
* the dataQuadrantPaddingRight to set
*
*/
public void setDataQuadrantPadding(float top, float right, float bottom,
float left) {
this.dataQuadrantPaddingTop = top;
this.dataQuadrantPaddingLeft = right;
this.dataQuadrantPaddingBottom = bottom;
this.dataQuadrantPaddingRight = left;
}
/**
* @return the displayLongitudeTitle
*/
public boolean isDisplayLongitudeTitle() {
return displayLongitudeTitle;
}
/**
* @param displayLongitudeTitle
* the displayLongitudeTitle to set
*/
public void setDisplayLongitudeTitle(boolean displayLongitudeTitle) {
this.displayLongitudeTitle = displayLongitudeTitle;
}
/**
* @return the displayAxisYTitle
*/
public boolean isDisplayLatitudeTitle() {
return displayLatitudeTitle;
}
/**
* @param displayLatitudeTitle
* the displayLatitudeTitle to set
*/
public void setDisplayLatitudeTitle(boolean displayLatitudeTitle) {
this.displayLatitudeTitle = displayLatitudeTitle;
}
/**
* @return the latitudeNum
*/
public int getLatitudeNum() {
return latitudeNum;
}
/**
* @param latitudeNum
* the latitudeNum to set
*/
public void setLatitudeNum(int latitudeNum) {
this.latitudeNum = latitudeNum;
}
/**
* @return the longitudeNum
*/
public int getLongitudeNum() {
return longitudeNum;
}
/**
* @param longitudeNum
* the longitudeNum to set
*/
public void setLongitudeNum(int longitudeNum) {
this.longitudeNum = longitudeNum;
}
/**
* @return the displayLongitude
*/
public boolean isDisplayLongitude() {
return displayLongitude;
}
/**
* @param displayLongitude
* the displayLongitude to set
*/
public void setDisplayLongitude(boolean displayLongitude) {
this.displayLongitude = displayLongitude;
}
/**
* @return the dashLongitude
*/
public boolean isDashLongitude() {
return dashLongitude;
}
/**
* @param dashLongitude
* the dashLongitude to set
*/
public void setDashLongitude(boolean dashLongitude) {
this.dashLongitude = dashLongitude;
}
/**
* @return the displayLatitude
*/
public boolean isDisplayLatitude() {
return displayLatitude;
}
/**
* @param displayLatitude
* the displayLatitude to set
*/
public void setDisplayLatitude(boolean displayLatitude) {
this.displayLatitude = displayLatitude;
}
/**
* @return the dashLatitude
*/
public boolean isDashLatitude() {
return dashLatitude;
}
/**
* @param dashLatitude
* the dashLatitude to set
*/
public void setDashLatitude(boolean dashLatitude) {
this.dashLatitude = dashLatitude;
}
/**
* @return the dashEffect
*/
public PathEffect getDashEffect() {
return dashEffect;
}
/**
* @param dashEffect
* the dashEffect to set
*/
public void setDashEffect(PathEffect dashEffect) {
this.dashEffect = dashEffect;
}
/**
* @return the displayBorder
*/
public boolean isDisplayBorder() {
return displayBorder;
}
/**
* @param displayBorder
* the displayBorder to set
*/
public void setDisplayBorder(boolean displayBorder) {
this.displayBorder = displayBorder;
}
/**
* @return the borderColor
*/
public int getBorderColor() {
return borderColor;
}
/**
* @param borderColor
* the borderColor to set
*/
public void setBorderColor(int borderColor) {
this.borderColor = borderColor;
}
/**
* @return the borderWidth
*/
public float getBorderWidth() {
return borderWidth;
}
/**
* @param borderWidth
* the borderWidth to set
*/
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
/**
* @return the longitudeFontColor
*/
public int getLongitudeFontColor() {
return longitudeFontColor;
}
/**
* @param longitudeFontColor
* the longitudeFontColor to set
*/
public void setLongitudeFontColor(int longitudeFontColor) {
this.longitudeFontColor = longitudeFontColor;
}
/**
* @return the longitudeFontSize
*/
public int getLongitudeFontSize() {
return longitudeFontSize;
}
/**
* @param longitudeFontSize
* the longitudeFontSize to set
*/
public void setLongitudeFontSize(int longitudeFontSize) {
this.longitudeFontSize = longitudeFontSize;
}
/**
* @return the latitudeFontColor
*/
public int getLatitudeFontColor() {
return latitudeFontColor;
}
/**
* @param latitudeFontColor
* the latitudeFontColor to set
*/
public void setLatitudeFontColor(int latitudeFontColor) {
this.latitudeFontColor = latitudeFontColor;
}
/**
* @return the latitudeFontSize
*/
public int getLatitudeFontSize() {
return latitudeFontSize;
}
/**
* @param latitudeFontSize
* the latitudeFontSize to set
*/
public void setLatitudeFontSize(int latitudeFontSize) {
this.latitudeFontSize = latitudeFontSize;
}
/**
* @return the crossLinesColor
*/
public int getCrossLinesColor() {
return crossLinesColor;
}
/**
* @param crossLinesColor
* the crossLinesColor to set
*/
public void setCrossLinesColor(int crossLinesColor) {
this.crossLinesColor = crossLinesColor;
}
/**
* @return the crossLinesFontColor
*/
public int getCrossLinesFontColor() {
return crossLinesFontColor;
}
/**
* @param crossLinesFontColor
* the crossLinesFontColor to set
*/
public void setCrossLinesFontColor(int crossLinesFontColor) {
this.crossLinesFontColor = crossLinesFontColor;
}
/**
* @return the longitudeTitles
*/
public List<String> getLongitudeTitles() {
return longitudeTitles;
}
/**
* @param longitudeTitles
* the longitudeTitles to set
*/
public void setLongitudeTitles(List<String> longitudeTitles) {
this.longitudeTitles = longitudeTitles;
}
/**
* @return the latitudeTitles
*/
public List<String> getLatitudeTitles() {
return latitudeTitles;
}
/**
* @param latitudeTitles
* the latitudeTitles to set
*/
public void setLatitudeTitles(List<String> latitudeTitles) {
this.latitudeTitles = latitudeTitles;
}
/**
* @return the latitudeMaxTitleLength
*/
public int getLatitudeMaxTitleLength() {
return latitudeMaxTitleLength;
}
/**
* @param latitudeMaxTitleLength
* the latitudeMaxTitleLength to set
*/
public void setLatitudeMaxTitleLength(int latitudeMaxTitleLength) {
this.latitudeMaxTitleLength = latitudeMaxTitleLength;
}
/**
* @return the clickPostX
*/
public float getClickPostX() {
return clickPostX;
}
/**
* @param clickPostX
* the clickPostX to set
*/
public void setClickPostX(float clickPostX) {
this.clickPostX = clickPostX;
}
/**
* @return the clickPostY
*/
public float getClickPostY() {
return clickPostY;
}
/**
* @param clickPostY
* the clickPostY to set
*/
public void setClickPostY(float clickPostY) {
this.clickPostY = clickPostY;
}
/**
* @return the touchPoint
*/
public PointF getTouchPoint() {
return touchPoint;
}
/**
* @param touchPoint
* the touchPoint to set
*/
public void setTouchPoint(PointF touchPoint) {
this.touchPoint = touchPoint;
}
/**
* @return the axisXPosition
*/
public int getAxisXPosition() {
return axisXPosition;
}
/**
* @param axisXPosition
* the axisXPosition to set
*/
public void setAxisXPosition(int axisXPosition) {
this.axisXPosition = axisXPosition;
}
/**
* @return the axisYPosition
*/
public int getAxisYPosition() {
return axisYPosition;
}
/**
* @param axisYPosition
* the axisYPosition to set
*/
public void setAxisYPosition(int axisYPosition) {
this.axisYPosition = axisYPosition;
}
public int getGraduation() {
return graduation;
}
public void setGraduation(int graduation) {
this.graduation = graduation;
}
public ITouchEventResponse getTouchEventResponse() {
return iTouchEventResponse;
}
public void setTouchEventResponse(
ITouchEventResponse iViewTouchEventResponse) {
this.iTouchEventResponse = iViewTouchEventResponse;
}
protected float getAxisXPrecentage(float clickPostX) {
float valueLength = clickPostX - getDataQuadrantPaddingStartX();
return valueLength / this.getDataQuadrantPaddingWidth();
}
// TODO Do not move view when onDraw
public void clearTounch() {
this.clickPostX = 0;
if (getTouchEventResponse() != null) {
getTouchEventResponse().clearTounchPoint();
}
}
public float getTounchPrepcentage() {
return tounchPrepcentage;
}
public void setTounchPrepcentage(float tounchPrepcentage) {
this.tounchPrepcentage = tounchPrepcentage;
}
}
|
android-charts/src/net/bither/charts/view/GridChart.java
|
/*
* GridChart.java
* Android-Charts
*
* Created by limc on 2011/05/29.
*
* Copyright 2011 limc.cn All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.charts.view;
import java.util.List;
import net.bither.charts.event.ITouchEventResponse;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
*
* <p>
* GridChart is base type of all the charts that use a grid to display like
* line-chart stick-chart etc. GridChart implemented a simple grid with basic
* functions what can be used in it's inherited charts.
* </p>
* <p>
* GridChartは全部グリドチャートのベスクラスです、一部処理は共通化け実現した。
* </p>
* <p>
* GridChart是所有网格图表的基础类对象,它实现了基本的网格图表功能,这些功能将被它的继承类使用
* </p>
*
* @author limc
* @version v1.0 2011/05/30 14:19:50
*
*/
public class GridChart extends BaseChart {
public static final int AXIS_X_POSITION_BOTTOM = 1 << 0;
@Deprecated
public static final int AXIS_X_POSITION_TOP = 1 << 1;
public static final int AXIS_Y_POSITION_LEFT = 1 << 2;
public static final int AXIS_Y_POSITION_RIGHT = 1 << 3;
/**
* <p>
* default background color
* </p>
* <p>
* 背景の色のデフォルト値
* </p>
* <p>
* 默认背景色
* </p>
*/
public static final int DEFAULT_BACKGROUND_COLOR = Color.BLACK;
/**
* <p>
* default color of X axis
* </p>
* <p>
* X軸の色のデフォルト値
* </p>
* <p>
* 默认坐标轴X的显示颜色
* </p>
*/
public static final int DEFAULT_AXIS_X_COLOR = Color.TRANSPARENT;
/**
* <p>
* default color of Y axis
* </p>
* <p>
* Y軸の色のデフォルト値
* </p>
* <p>
* 默认坐标轴Y的显示颜色
* </p>
*/
public static final int DEFAULT_AXIS_Y_COLOR = Color.TRANSPARENT;
public static final float DEFAULT_AXIS_WIDTH = 1;
public static final int DEFAULT_AXIS_X_POSITION = AXIS_X_POSITION_BOTTOM;
public static final int DEFAULT_AXIS_Y_POSITION = AXIS_Y_POSITION_LEFT;
/**
* <p>
* default color of grid‘s longitude line
* </p>
* <p>
* 経線の色のデフォルト値
* </p>
* <p>
* 默认网格经线的显示颜色
* </p>
*/
public static final int DEFAULT_LONGITUDE_COLOR = Color.TRANSPARENT;
/**
* <p>
* default color of grid‘s latitude line
* </p>
* <p>
* 緯線の色のデフォルト値
* </p>
* <p>
* 默认网格纬线的显示颜色
* </p>
*/
public static final int DEFAULT_LAITUDE_COLOR = Color.TRANSPARENT;
/**
* <p>
* default margin of the axis to the left border
* </p>
* <p>
* 轴線より左枠線の距離のデフォルト値
* </p>
* <p>
* 默认轴线左边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_LEFT = 42f;
public static final float DEFAULT_AXIS_Y_TITLE_QUADRANT_WIDTH = 16f;
/**
* <p>
* default margin of the axis to the bottom border
* </p>
* <p>
* 轴線より下枠線の距離のデフォルト値
* </p>
* <p>
* 默认轴线下边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_BOTTOM = 16f;
public static final float DEFAULT_AXIS_X_TITLE_QUADRANT_HEIGHT = 16f;
/**
* <p>
* default margin of the axis to the top border
* </p>
* <p>
* 轴線より上枠線の距離のデフォルト値
* </p>
* <p>
* 默认轴线上边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_TOP = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_TOP = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_BOTTOM = 5f;
/**
* <p>
* default margin of the axis to the right border
* </p>
* <p>
* 轴線より右枠線の距離のデフォルト値
* </p>
* <p>
* 轴线右边距
* </p>
*/
@Deprecated
public static final float DEFAULT_AXIS_MARGIN_RIGHT = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_LEFT = 5f;
public static final float DEFAULT_DATA_QUADRANT_PADDING_RIGHT = 5f;
/**
* <p>
* default numbers of grid‘s latitude line
* </p>
* <p>
* 緯線の数量のデフォルト値
* </p>
* <p>
* 网格纬线的数量
* </p>
*/
public static final int DEFAULT_LATITUDE_NUM = 4;
/**
* <p>
* default numbers of grid‘s longitude line
* </p>
* <p>
* 経線の数量のデフォルト値
* </p>
* <p>
* 网格经线的数量
* </p>
*/
public static final int DEFAULT_LONGITUDE_NUM = 3;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 経線を表示するか?
* </p>
* <p>
* 默认经线是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LONGITUDE = Boolean.TRUE;
/**
* <p>
* Should display longitude as dashed line?
* </p>
* <p>
* 経線を点線にするか?
* </p>
* <p>
* 默认经线是否显示为虚线
* </p>
*/
public static final boolean DEFAULT_DASH_LONGITUDE = Boolean.TRUE;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 緯線を表示するか?
* </p>
* <p>
* 纬线是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LATITUDE = Boolean.TRUE;
/**
* <p>
* Should display latitude as dashed line?
* </p>
* <p>
* 緯線を点線にするか?
* </p>
* <p>
* 纬线是否显示为虚线
* </p>
*/
public static final boolean DEFAULT_DASH_LATITUDE = Boolean.TRUE;
/**
* <p>
* Should display the degrees in X axis?
* </p>
* <p>
* X軸のタイトルを表示するか?
* </p>
* <p>
* X轴上的标题是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LONGITUDE_TITLE = Boolean.TRUE;
/**
* <p>
* Should display the degrees in Y axis?
* </p>
* <p>
* Y軸のタイトルを表示するか?
* </p>
* <p>
* 默认Y轴上的标题是否显示
* </p>
*/
public static final boolean DEFAULT_DISPLAY_LATITUDE_TITLE = Boolean.TRUE;
/**
* <p>
* Should display the border?
* </p>
* <p>
* 枠を表示するか?
* </p>
* <p>
* 默认控件是否显示边框
* </p>
*/
public static final boolean DEFAULT_DISPLAY_BORDER = Boolean.TRUE;
/**
* <p>
* default color of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルの色のデフォルト値
* </p>
* <p>
* 默认经线刻度字体颜色
* </p>
*/
public static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
public static final float DEFAULT_BORDER_WIDTH = 1f;
/**
* <p>
* default color of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルの色のデフォルト値
* </p>
* <p>
* 经线刻度字体颜色
* </p>
*/
public static final int DEFAULT_LONGITUDE_FONT_COLOR = Color.WHITE;
/**
* <p>
* default font size of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルのフォントサイズのデフォルト値
* </p>
* <p>
* 经线刻度字体大小
* </p>
*/
public static final int DEFAULT_LONGITUDE_FONT_SIZE = 12;
/**
* <p>
* default color of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルの色のデフォルト値
* </p>
* <p>
* 纬线刻度字体颜色
* </p>
*/
public static final int DEFAULT_LATITUDE_FONT_COLOR = Color.RED;
/**
* <p>
* default font size of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルのフォントサイズのデフォルト値
* </p>
* <p>
* 默认纬线刻度字体大小
* </p>
*/
public static final int DEFAULT_LATITUDE_FONT_SIZE = 12;
public static final int DEFAULT_CROSS_LINES_COLOR = Color.CYAN;
public static final int DEFAULT_CROSS_LINES_FONT_COLOR = Color.CYAN;
/**
* <p>
* default titles' max length for display of Y axis
* </p>
* <p>
* Y軸の表示用タイトルの最大文字長さのデフォルト値
* </p>
* <p>
* 默认Y轴标题最大文字长度
* </p>
*/
public static final int DEFAULT_LATITUDE_MAX_TITLE_LENGTH = 5;
/**
* <p>
* default dashed line type
* </p>
* <p>
* 点線タイプのデフォルト値
* </p>
* <p>
* 默认虚线效果
* </p>
*/
public static final PathEffect DEFAULT_DASH_EFFECT = new DashPathEffect(
new float[] { 3, 3, 3, 3 }, 1);
/**
* <p>
* Should display the Y cross line if grid is touched?
* </p>
* <p>
* タッチしたポイントがある場合、十字線の垂直線を表示するか?
* </p>
* <p>
* 默认在控件被点击时,显示十字竖线线
* </p>
*/
public static final boolean DEFAULT_DISPLAY_CROSS_X_ON_TOUCH = true;
/**
* <p>
* Should display the Y cross line if grid is touched?
* </p>
* <p>
* タッチしたポイントがある場合、十字線の水平線を表示するか?
* </p>
* <p>
* 默认在控件被点击时,显示十字横线线
* </p>
*/
public static final boolean DEFAULT_DISPLAY_CROSS_Y_ON_TOUCH = true;
/**
* <p>
* Color of X axis
* </p>
* <p>
* X軸の色
* </p>
* <p>
* 坐标轴X的显示颜色
* </p>
*/
private int axisXColor = DEFAULT_AXIS_X_COLOR;
/**
* <p>
* Color of Y axis
* </p>
* <p>
* Y軸の色
* </p>
* <p>
* 坐标轴Y的显示颜色
* </p>
*/
private int axisYColor = DEFAULT_AXIS_Y_COLOR;
private float axisWidth = DEFAULT_AXIS_WIDTH;
protected int axisXPosition = DEFAULT_AXIS_X_POSITION;
protected int axisYPosition = DEFAULT_AXIS_Y_POSITION;
/**
* <p>
* Color of grid‘s longitude line
* </p>
* <p>
* 経線の色
* </p>
* <p>
* 网格经线的显示颜色
* </p>
*/
private int longitudeColor = DEFAULT_LONGITUDE_COLOR;
private int graduation = 1;
/**
* <p>
* Color of grid‘s latitude line
* </p>
* <p>
* 緯線の色
* </p>
* <p>
* 网格纬线的显示颜色
* </p>
*/
private int latitudeColor = DEFAULT_LAITUDE_COLOR;
/**
* <p>
* Margin of the axis to the left border
* </p>
* <p>
* 轴線より左枠線の距離
* </p>
* <p>
* 轴线左边距
* </p>
*/
protected float axisYTitleQuadrantWidth = DEFAULT_AXIS_Y_TITLE_QUADRANT_WIDTH;
/**
* <p>
* Margin of the axis to the bottom border
* </p>
* <p>
* 轴線より下枠線の距離
* </p>
* <p>
* 轴线下边距
* </p>
*/
protected float axisXTitleQuadrantHeight = DEFAULT_AXIS_X_TITLE_QUADRANT_HEIGHT;
/**
* <p>
* Margin of the axis to the top border
* </p>
* <p>
* 轴線より上枠線の距離
* </p>
* <p>
* 轴线上边距
* </p>
*/
protected float dataQuadrantPaddingTop = DEFAULT_DATA_QUADRANT_PADDING_TOP;
/**
* <p>
* Margin of the axis to the right border
* </p>
* <p>
* 轴線より右枠線の距離
* </p>
* <p>
* 轴线右边距
* </p>
*/
protected float dataQuadrantPaddingLeft = DEFAULT_DATA_QUADRANT_PADDING_LEFT;
protected float dataQuadrantPaddingBottom = DEFAULT_DATA_QUADRANT_PADDING_BOTTOM;
/**
* <p>
* Margin of the axis to the right border
* </p>
* <p>
* 轴線より右枠線の距離
* </p>
* <p>
* 轴线右边距
* </p>
*/
protected float dataQuadrantPaddingRight = DEFAULT_DATA_QUADRANT_PADDING_RIGHT;
/**
* <p>
* Should display the degrees in X axis?
* </p>
* <p>
* X軸のタイトルを表示するか?
* </p>
* <p>
* X轴上的标题是否显示
* </p>
*/
private boolean displayLongitudeTitle = DEFAULT_DISPLAY_LONGITUDE_TITLE;
/**
* <p>
* Should display the degrees in Y axis?
* </p>
* <p>
* Y軸のタイトルを表示するか?
* </p>
* <p>
* Y轴上的标题是否显示
* </p>
*/
private boolean displayLatitudeTitle = DEFAULT_DISPLAY_LATITUDE_TITLE;
/**
* <p>
* Numbers of grid‘s latitude line
* </p>
* <p>
* 緯線の数量
* </p>
* <p>
* 网格纬线的数量
* </p>
*/
protected int latitudeNum = DEFAULT_LATITUDE_NUM;
/**
* <p>
* Numbers of grid‘s longitude line
* </p>
* <p>
* 経線の数量
* </p>
* <p>
* 网格经线的数量
* </p>
*/
protected int longitudeNum = DEFAULT_LONGITUDE_NUM;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 経線を表示するか?
* </p>
* <p>
* 经线是否显示
* </p>
*/
private boolean displayLongitude = DEFAULT_DISPLAY_LONGITUDE;
/**
* <p>
* Should display longitude as dashed line?
* </p>
* <p>
* 経線を点線にするか?
* </p>
* <p>
* 经线是否显示为虚线
* </p>
*/
private boolean dashLongitude = DEFAULT_DASH_LONGITUDE;
/**
* <p>
* Should display longitude line?
* </p>
* <p>
* 緯線を表示するか?
* </p>
* <p>
* 纬线是否显示
* </p>
*/
private boolean displayLatitude = DEFAULT_DISPLAY_LATITUDE;
/**
* <p>
* Should display latitude as dashed line?
* </p>
* <p>
* 緯線を点線にするか?
* </p>
* <p>
* 纬线是否显示为虚线
* </p>
*/
private boolean dashLatitude = DEFAULT_DASH_LATITUDE;
/**
* <p>
* dashed line type
* </p>
* <p>
* 点線タイプ?
* </p>
* <p>
* 虚线效果
* </p>
*/
private PathEffect dashEffect = DEFAULT_DASH_EFFECT;
/**
* <p>
* Should display the border?
* </p>
* <p>
* 枠を表示するか?
* </p>
* <p>
* 控件是否显示边框
* </p>
*/
private boolean displayBorder = DEFAULT_DISPLAY_BORDER;
/**
* <p>
* Color of grid‘s border line
* </p>
* <p>
* 枠線の色
* </p>
* <p>
* 图边框的颜色
* </p>
*/
private int borderColor = DEFAULT_BORDER_COLOR;
protected float borderWidth = DEFAULT_BORDER_WIDTH;
/**
* <p>
* Color of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルの色
* </p>
* <p>
* 经线刻度字体颜色
* </p>
*/
private int longitudeFontColor = DEFAULT_LONGITUDE_FONT_COLOR;
/**
* <p>
* Font size of text for the longitude degrees display
* </p>
* <p>
* 経度のタイトルのフォントサイズ
* </p>
* <p>
* 经线刻度字体大小
* </p>
*/
private int longitudeFontSize = DEFAULT_LONGITUDE_FONT_SIZE;
/**
* <p>
* Color of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルの色
* </p>
* <p>
* 纬线刻度字体颜色
* </p>
*/
private int latitudeFontColor = DEFAULT_LATITUDE_FONT_COLOR;
/**
* <p>
* Font size of text for the latitude degrees display
* </p>
* <p>
* 緯度のタイトルのフォントサイズ
* </p>
* <p>
* 纬线刻度字体大小
* </p>
*/
private int latitudeFontSize = DEFAULT_LATITUDE_FONT_SIZE;
/**
* <p>
* Color of cross line inside grid when touched
* </p>
* <p>
* タッチしたポイント表示用十字線の色
* </p>
* <p>
* 十字交叉线颜色
* </p>
*/
private int crossLinesColor = DEFAULT_CROSS_LINES_COLOR;
/**
* <p>
* Color of cross line degree text when touched
* </p>
* <p>
* タッチしたポイント表示用十字線度数文字の色
* </p>
* <p>
* 十字交叉线坐标轴字体颜色
* </p>
*/
private int crossLinesFontColor = DEFAULT_CROSS_LINES_FONT_COLOR;
/**
* <p>
* Titles Array for display of X axis
* </p>
* <p>
* X軸の表示用タイトル配列
* </p>
* <p>
* X轴标题数组
* </p>
*/
private List<String> longitudeTitles;
/**
* <p>
* Titles for display of Y axis
* </p>
* <p>
* Y軸の表示用タイトル配列
* </p>
* <p>
* Y轴标题数组
* </p>
*/
private List<String> latitudeTitles;
/**
* <p>
* Titles' max length for display of Y axis
* </p>
* <p>
* Y軸の表示用タイトルの最大文字長さ
* </p>
* <p>
* Y轴标题最大文字长度
* </p>
*/
private int latitudeMaxTitleLength = DEFAULT_LATITUDE_MAX_TITLE_LENGTH;
/**
* <p>
* Touched point inside of grid
* </p>
* <p>
* タッチしたポイント
* </p>
* <p>
* 单点触控的选中点
* </p>
*/
private PointF touchPoint;
/**
* <p>
* Touched point’s X value inside of grid
* </p>
* <p>
* タッチしたポイントのX
* </p>
* <p>
* 单点触控的选中点的X
* </p>
*/
private float clickPostX;
/**
* <p>
* Touched point’s Y value inside of grid
* </p>
* <p>
* タッチしたポイントのY
* </p>
* <p>
* 单点触控的选中点的Y
* </p>
*/
private float clickPostY;
private ITouchEventResponse iTouchEventResponse;
private float tounchPrepcentage = 0;
/*
* (non-Javadoc)
*
* @param context
*
* @see cn.limc.androidcharts.view.BaseChart#BaseChart(Context)
*/
public GridChart(Context context) {
super(context);
}
/*
* (non-Javadoc)
*
* @param context
*
* @param attrs
*
* @param defStyle
*
* @see cn.limc.androidcharts.view.BaseChart#BaseChart(Context,
* AttributeSet, int)
*/
public GridChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/*
* (non-Javadoc)
*
* @param context
*
* @param attrs
*
* @see cn.limc.androidcharts.view.BaseChart#BaseChart(Context,
* AttributeSet)
*/
public GridChart(Context context, AttributeSet attrs) {
super(context, attrs);
}
/*
* (non-Javadoc)
*
* <p>Called when is going to draw this chart<p> <p>チャートを書く前、メソッドを呼ぶ<p>
* <p>绘制图表时调用<p>
*
* @param canvas
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawXAxis(canvas);
drawYAxis(canvas);
if (this.displayBorder) {
drawBorder(canvas);
}
if (displayLongitude || displayLongitudeTitle) {
drawLongitudeLine(canvas);
drawLongitudeTitle(canvas);
}
if (displayLatitude || displayLatitudeTitle) {
drawLatitudeLine(canvas);
drawLatitudeTitle(canvas);
}
if (clickPostX <= 0) {
return;
}
drawPointOfLine(canvas, clickPostX);
}
/*
* (non-Javadoc)
*
* <p>Called when chart is touched<p> <p>チャートをタッチしたら、メソッドを呼ぶ<p>
* <p>图表点击时调用<p>
*
* @param event
*
* @see android.view.View#onTouchEvent(MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getX() < getDataQuadrantPaddingStartX()
|| event.getX() > getDataQuadrantPaddingEndX()) {
return false;
}
if (event.getY() < getDataQuadrantPaddingStartY()
|| event.getY() > getDataQuadrantPaddingEndY()) {
return false;
}
// touched points, if touch point is only one
if (event.getPointerCount() == 1) {
// 获取点击坐标
clickPostX = event.getX();
clickPostY = event.getY();
PointF point = new PointF(clickPostX, clickPostY);
touchPoint = point;
beginRedrawOnTouch(clickPostX);
// redraw
super.invalidate();
} else if (event.getPointerCount() == 2) {
}
return super.onTouchEvent(event);
}
protected void beginRedrawOnTouch(float clickPostX) {
float prepcentage = getAxisXPrecentage(clickPostX);
setTounchPrepcentage(prepcentage);
}
protected float getDataQuadrantWidth() {
return super.getWidth() - axisYTitleQuadrantWidth - 2 * borderWidth
- axisWidth;
}
protected float getDataQuadrantHeight() {
return super.getHeight() - axisXTitleQuadrantHeight - 2 * borderWidth
- axisWidth;
}
protected float getDataQuadrantStartX() {
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
return borderWidth + axisYTitleQuadrantWidth + axisWidth;
} else {
return borderWidth;
}
}
protected float getDataQuadrantPaddingStartX() {
return getDataQuadrantStartX() + dataQuadrantPaddingLeft;
}
protected float getDataQuadrantEndX() {
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
return super.getWidth() - borderWidth;
} else {
return super.getWidth() - borderWidth - axisYTitleQuadrantWidth
- axisWidth;
}
}
protected float getDataQuadrantPaddingEndX() {
return getDataQuadrantEndX() - dataQuadrantPaddingRight;
}
protected float getDataQuadrantStartY() {
return borderWidth;
}
protected float getDataQuadrantPaddingStartY() {
return getDataQuadrantStartY() + dataQuadrantPaddingTop;
}
protected float getDataQuadrantEndY() {
return super.getHeight() - borderWidth - axisXTitleQuadrantHeight
- axisWidth;
}
protected float getDataQuadrantPaddingEndY() {
return getDataQuadrantEndY() - dataQuadrantPaddingBottom;
}
protected float getDataQuadrantPaddingWidth() {
return getDataQuadrantWidth() - dataQuadrantPaddingLeft
- dataQuadrantPaddingRight;
}
protected float getDataQuadrantPaddingHeight() {
return getDataQuadrantHeight() - dataQuadrantPaddingTop
- dataQuadrantPaddingBottom;
}
/**
* <p>
* calculate degree title on X axis
* </p>
* <p>
* X軸の目盛を計算する
* </p>
* <p>
* 计算X轴上显示的坐标值
* </p>
*
* @param value
* <p>
* value for calculate
* </p>
* <p>
* 計算有用データ
* </p>
* <p>
* 计算用数据
* </p>
*
* @return String
* <p>
* degree
* </p>
* <p>
* 目盛
* </p>
* <p>
* 坐标值
* </p>
*/
public String getAxisXGraduate(Object value) {
float valueLength = ((Float) value).floatValue()
- getDataQuadrantPaddingStartX();
return String.valueOf(valueLength / this.getDataQuadrantPaddingWidth());
}
/**
* <p>
* calculate degree title on Y axis
* </p>
* <p>
* Y軸の目盛を計算する
* </p>
* <p>
* 计算Y轴上显示的坐标值
* </p>
*
* @param value
* <p>
* value for calculate
* </p>
* <p>
* 計算有用データ
* </p>
* <p>
* 计算用数据
* </p>
*
* @return String
* <p>
* degree
* </p>
* <p>
* 目盛
* </p>
* <p>
* 坐标值
* </p>
*/
public String getAxisYGraduate(Object value) {
float valueLength = ((Float) value).floatValue()
- getDataQuadrantPaddingStartY();
return String
.valueOf(valueLength / this.getDataQuadrantPaddingHeight());
}
protected void drawPointOfLine(Canvas canvas, float clickPostX) {
}
/**
* <p>
* draw border
* </p>
* <p>
* グラプのボーダーを書く
* </p>
* <p>
* 绘制边框
* </p>
*
* @param canvas
*/
protected void drawBorder(Canvas canvas) {
Paint mPaint = new Paint();
mPaint.setColor(borderColor);
mPaint.setStrokeWidth(borderWidth);
mPaint.setStyle(Style.STROKE);
// draw a rectangle
canvas.drawRect(borderWidth / 2, borderWidth / 2, super.getWidth()
- borderWidth / 2, super.getHeight() - borderWidth / 2, mPaint);
}
/**
* <p>
* draw X Axis
* </p>
* <p>
* X軸を書く
* </p>
* <p>
* 绘制X轴
* </p>
*
* @param canvas
*/
protected void drawXAxis(Canvas canvas) {
float length = super.getWidth();
float postY;
if (axisXPosition == AXIS_X_POSITION_BOTTOM) {
postY = super.getHeight() - axisXTitleQuadrantHeight - borderWidth
- axisWidth / 2;
} else {
postY = super.getHeight() - borderWidth - axisWidth / 2;
}
Paint mPaint = new Paint();
mPaint.setColor(axisXColor);
mPaint.setStrokeWidth(axisWidth);
canvas.drawLine(borderWidth, postY, length, postY, mPaint);
}
/**
* <p>
* draw Y Axis
* </p>
* <p>
* Y軸を書く
* </p>
* <p>
* 绘制Y轴
* </p>
*
* @param canvas
*/
protected void drawYAxis(Canvas canvas) {
float length = super.getHeight() - axisXTitleQuadrantHeight
- borderWidth;
float postX;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
postX = borderWidth + axisYTitleQuadrantWidth + axisWidth / 2;
} else {
postX = super.getWidth() - borderWidth - axisYTitleQuadrantWidth
- axisWidth / 2;
}
Paint mPaint = new Paint();
mPaint.setColor(axisXColor);
mPaint.setStrokeWidth(axisWidth);
canvas.drawLine(postX, borderWidth, postX, length, mPaint);
}
/**
* <p>
* draw longitude lines
* </p>
* <p>
* 経線を書く
* </p>
* <p>
* 绘制经线
* </p>
*
* @param canvas
*/
protected void drawLongitudeLine(Canvas canvas) {
if (null == longitudeTitles) {
return;
}
if (!displayLongitude) {
return;
}
int counts = longitudeTitles.size();
float length = getDataQuadrantHeight();
Paint mPaintLine = new Paint();
mPaintLine.setColor(longitudeColor);
if (dashLongitude) {
mPaintLine.setPathEffect(dashEffect);
}
if (counts > 1) {
float postOffset = this.getDataQuadrantPaddingWidth()
/ (counts - 1);
float offset;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
offset = borderWidth + axisYTitleQuadrantWidth + axisWidth
+ dataQuadrantPaddingLeft;
} else {
offset = borderWidth + dataQuadrantPaddingLeft;
}
for (int i = 0; i < counts; i++) {
canvas.drawLine(offset + i * postOffset, borderWidth, offset
+ i * postOffset, length, mPaintLine);
}
}
}
/**
* <p>
* draw longitude lines
* </p>
* <p>
* 経線を書く
* </p>
* <p>
* 绘制经线
* </p>
*
* @param canvas
*/
protected void drawLongitudeTitle(Canvas canvas) {
if (null == longitudeTitles) {
return;
}
if (!displayLongitude) {
return;
}
if (!displayLongitudeTitle) {
return;
}
if (longitudeTitles.size() <= 1) {
return;
}
Paint mPaintFont = new Paint();
mPaintFont.setColor(longitudeFontColor);
mPaintFont.setTextSize(longitudeFontSize);
mPaintFont.setAntiAlias(true);
float postOffset = this.getDataQuadrantPaddingWidth()
/ (longitudeTitles.size() - 1);
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
float offset = borderWidth + axisYTitleQuadrantWidth + axisWidth
+ dataQuadrantPaddingLeft;
for (int i = 0; i < longitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(longitudeTitles.get(i), offset,
super.getHeight() - axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
} else {
canvas.drawText(longitudeTitles.get(i),
offset + postOffset * 0.2f + i * postOffset
- (longitudeTitles.get(i).length())
* longitudeFontSize / 2f, super.getHeight()
- axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
}
}
} else {
float offset = borderWidth + dataQuadrantPaddingLeft;
for (int i = 0; i < longitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(longitudeTitles.get(i), offset,
super.getHeight() - axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
} else {
canvas.drawText(longitudeTitles.get(i),
offset + postOffset * 0.2f + i * postOffset
- (longitudeTitles.get(i).length())
* longitudeFontSize / 2f, super.getHeight()
- axisXTitleQuadrantHeight
+ longitudeFontSize, mPaintFont);
}
}
}
}
/**
* <p>
* draw latitude lines
* </p>
* <p>
* 緯線を書く
* </p>
* <p>
* 绘制纬线
* </p>
*
* @param canvas
*/
protected void drawLatitudeLine(Canvas canvas) {
if (null == latitudeTitles) {
return;
}
if (!displayLatitude) {
return;
}
if (!displayLatitudeTitle) {
return;
}
if (latitudeTitles.size() <= 1) {
return;
}
float length = getDataQuadrantWidth();
Paint mPaintLine = new Paint();
mPaintLine.setColor(latitudeColor);
if (dashLatitude) {
mPaintLine.setPathEffect(dashEffect);
}
Paint mPaintFont = new Paint();
mPaintFont.setColor(latitudeFontColor);
mPaintFont.setTextSize(latitudeFontSize);
mPaintFont.setAntiAlias(true);
float postOffset = this.getDataQuadrantPaddingHeight()
/ (latitudeTitles.size() - 1);
float offset = super.getHeight() - borderWidth
- axisXTitleQuadrantHeight - axisWidth
- dataQuadrantPaddingBottom;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
float startFrom = borderWidth + axisYTitleQuadrantWidth + axisWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
canvas.drawLine(startFrom, offset - i * postOffset, startFrom
+ length, offset - i * postOffset, mPaintLine);
}
} else {
float startFrom = borderWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
canvas.drawLine(startFrom, offset - i * postOffset, startFrom
+ length, offset - i * postOffset, mPaintLine);
}
}
}
/**
* <p>
* draw latitude lines
* </p>
* <p>
* 緯線を書く
* </p>
* <p>
* 绘制纬线
* </p>
*
* @param canvas
*/
protected void drawLatitudeTitle(Canvas canvas) {
if (null == latitudeTitles) {
return;
}
if (!displayLatitudeTitle) {
return;
}
if (latitudeTitles.size() <= 1) {
return;
}
Paint mPaintFont = new Paint();
mPaintFont.setColor(latitudeFontColor);
mPaintFont.setTextSize(latitudeFontSize);
mPaintFont.setAntiAlias(true);
float postOffset = this.getDataQuadrantPaddingHeight()
/ (latitudeTitles.size() - 1);
float offset = super.getHeight() - borderWidth
- axisXTitleQuadrantHeight - axisWidth
- dataQuadrantPaddingBottom;
if (axisYPosition == AXIS_Y_POSITION_LEFT) {
float startFrom = borderWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(latitudeTitles.get(i), startFrom,
super.getHeight() - this.axisXTitleQuadrantHeight
- borderWidth - axisWidth - 2f, mPaintFont);
} else {
canvas.drawText(latitudeTitles.get(i), startFrom, offset
- i * postOffset + latitudeFontSize / 2f,
mPaintFont);
}
}
} else {
float startFrom = super.getWidth() - borderWidth
- axisYTitleQuadrantWidth;
for (int i = 0; i < latitudeTitles.size(); i++) {
if (0 == i) {
canvas.drawText(latitudeTitles.get(i), startFrom,
super.getHeight() - this.axisXTitleQuadrantHeight
- borderWidth - axisWidth - 2f, mPaintFont);
} else {
canvas.drawText(latitudeTitles.get(i), startFrom, offset
- i * postOffset + latitudeFontSize / 2f,
mPaintFont);
}
}
}
}
/**
* <p>
* Zoom in the graph
* </p>
* <p>
* 拡大表示する。
* </p>
* <p>
* 放大表示
* </p>
*/
protected void zoomIn() {
// DO NOTHING
}
/**
* <p>
* Zoom out the grid
* </p>
* <p>
* 縮小表示する。
* </p>
* <p>
* 缩小
* </p>
*/
protected void zoomOut() {
// DO NOTHING
}
/*
* (non-Javadoc)
*
* @param event
*
* @see
* cn.limc.androidcharts.event.ITouchEventResponse#notifyEvent(GridChart)
*/
public void notifyEvent(GridChart chart) {
PointF point = chart.getTouchPoint();
if (null != point) {
clickPostX = point.x;
clickPostY = point.y;
}
touchPoint = new PointF(clickPostX, clickPostY);
super.invalidate();
}
/**
* @return the axisXColor
*/
public int getAxisXColor() {
return axisXColor;
}
/**
* @param axisXColor
* the axisXColor to set
*/
public void setAxisXColor(int axisXColor) {
this.axisXColor = axisXColor;
}
/**
* @return the axisYColor
*/
public int getAxisYColor() {
return axisYColor;
}
/**
* @param axisYColor
* the axisYColor to set
*/
public void setAxisYColor(int axisYColor) {
this.axisYColor = axisYColor;
}
/**
* @return the axisWidth
*/
public float getAxisWidth() {
return axisWidth;
}
/**
* @param axisWidth
* the axisWidth to set
*/
public void setAxisWidth(float axisWidth) {
this.axisWidth = axisWidth;
}
/**
* @return the longitudeColor
*/
public int getLongitudeColor() {
return longitudeColor;
}
/**
* @param longitudeColor
* the longitudeColor to set
*/
public void setLongitudeColor(int longitudeColor) {
this.longitudeColor = longitudeColor;
}
/**
* @return the latitudeColor
*/
public int getLatitudeColor() {
return latitudeColor;
}
/**
* @param latitudeColor
* the latitudeColor to set
*/
public void setLatitudeColor(int latitudeColor) {
this.latitudeColor = latitudeColor;
}
/**
* @return the axisMarginLeft
*/
@Deprecated
public float getAxisMarginLeft() {
return axisYTitleQuadrantWidth;
}
/**
* @param axisMarginLeft
* the axisMarginLeft to set
*/
@Deprecated
public void setAxisMarginLeft(float axisMarginLeft) {
this.axisYTitleQuadrantWidth = axisMarginLeft;
}
/**
* @return the axisMarginLeft
*/
public float getAxisYTitleQuadrantWidth() {
return axisYTitleQuadrantWidth;
}
/**
* @param axisYTitleQuadrantWidth
* the axisYTitleQuadrantWidth to set
*/
public void setAxisYTitleQuadrantWidth(float axisYTitleQuadrantWidth) {
this.axisYTitleQuadrantWidth = axisYTitleQuadrantWidth;
}
/**
* @return the axisXTitleQuadrantHeight
*/
@Deprecated
public float getAxisMarginBottom() {
return axisXTitleQuadrantHeight;
}
/**
* @param axisXTitleQuadrantHeight
* the axisXTitleQuadrantHeight to set
*/
@Deprecated
public void setAxisMarginBottom(float axisXTitleQuadrantHeight) {
this.axisXTitleQuadrantHeight = axisXTitleQuadrantHeight;
}
/**
* @return the axisXTitleQuadrantHeight
*/
public float getAxisXTitleQuadrantHeight() {
return axisXTitleQuadrantHeight;
}
/**
* @param axisXTitleQuadrantHeight
* the axisXTitleQuadrantHeight to set
*/
public void setAxisXTitleQuadrantHeight(float axisXTitleQuadrantHeight) {
this.axisXTitleQuadrantHeight = axisXTitleQuadrantHeight;
}
/**
* @return the dataQuadrantPaddingTop
*/
@Deprecated
public float getAxisMarginTop() {
return dataQuadrantPaddingTop;
}
/**
* @param axisMarginTop
* the axisMarginTop to set
*/
@Deprecated
public void setAxisMarginTop(float axisMarginTop) {
this.dataQuadrantPaddingTop = axisMarginTop;
this.dataQuadrantPaddingBottom = axisMarginTop;
}
/**
* @return the dataQuadrantPaddingRight
*/
@Deprecated
public float getAxisMarginRight() {
return dataQuadrantPaddingRight;
}
/**
* @param axisMarginRight
* the axisMarginRight to set
*/
@Deprecated
public void setAxisMarginRight(float axisMarginRight) {
this.dataQuadrantPaddingRight = axisMarginRight;
this.dataQuadrantPaddingLeft = axisMarginRight;
}
/**
* @return the dataQuadrantPaddingTop
*/
public float getDataQuadrantPaddingTop() {
return dataQuadrantPaddingTop;
}
/**
* @param dataQuadrantPaddingTop
* the dataQuadrantPaddingTop to set
*/
public void setDataQuadrantPaddingTop(float dataQuadrantPaddingTop) {
this.dataQuadrantPaddingTop = dataQuadrantPaddingTop;
}
/**
* @return the dataQuadrantPaddingLeft
*/
public float getDataQuadrantPaddingLeft() {
return dataQuadrantPaddingLeft;
}
/**
* @param dataQuadrantPaddingLeft
* the dataQuadrantPaddingLeft to set
*/
public void setDataQuadrantPaddingLeft(float dataQuadrantPaddingLeft) {
this.dataQuadrantPaddingLeft = dataQuadrantPaddingLeft;
}
/**
* @return the dataQuadrantPaddingBottom
*/
public float getDataQuadrantPaddingBottom() {
return dataQuadrantPaddingBottom;
}
/**
* @param dataQuadrantPaddingBottom
* the dataQuadrantPaddingBottom to set
*/
public void setDataQuadrantPaddingBottom(float dataQuadrantPaddingBottom) {
this.dataQuadrantPaddingBottom = dataQuadrantPaddingBottom;
}
/**
* @return the dataQuadrantPaddingRight
*/
public float getDataQuadrantPaddingRight() {
return dataQuadrantPaddingRight;
}
/**
* @param dataQuadrantPaddingRight
* the dataQuadrantPaddingRight to set
*/
public void setDataQuadrantPaddingRight(float dataQuadrantPaddingRight) {
this.dataQuadrantPaddingRight = dataQuadrantPaddingRight;
}
/**
* @param padding
* the dataQuadrantPaddingTop dataQuadrantPaddingBottom
* dataQuadrantPaddingLeft dataQuadrantPaddingRight to set
*
*/
public void setDataQuadrantPadding(float padding) {
this.dataQuadrantPaddingTop = padding;
this.dataQuadrantPaddingLeft = padding;
this.dataQuadrantPaddingBottom = padding;
this.dataQuadrantPaddingRight = padding;
}
/**
* @param topnbottom
* the dataQuadrantPaddingTop dataQuadrantPaddingBottom to set
* @param leftnright
* the dataQuadrantPaddingLeft dataQuadrantPaddingRight to set
*
*/
public void setDataQuadrantPadding(float topnbottom, float leftnright) {
this.dataQuadrantPaddingTop = topnbottom;
this.dataQuadrantPaddingLeft = leftnright;
this.dataQuadrantPaddingBottom = topnbottom;
this.dataQuadrantPaddingRight = leftnright;
}
/**
* @param top
* the dataQuadrantPaddingTop to set
* @param right
* the dataQuadrantPaddingLeft to set
* @param bottom
* the dataQuadrantPaddingBottom to set
* @param left
* the dataQuadrantPaddingRight to set
*
*/
public void setDataQuadrantPadding(float top, float right, float bottom,
float left) {
this.dataQuadrantPaddingTop = top;
this.dataQuadrantPaddingLeft = right;
this.dataQuadrantPaddingBottom = bottom;
this.dataQuadrantPaddingRight = left;
}
/**
* @return the displayLongitudeTitle
*/
public boolean isDisplayLongitudeTitle() {
return displayLongitudeTitle;
}
/**
* @param displayLongitudeTitle
* the displayLongitudeTitle to set
*/
public void setDisplayLongitudeTitle(boolean displayLongitudeTitle) {
this.displayLongitudeTitle = displayLongitudeTitle;
}
/**
* @return the displayAxisYTitle
*/
public boolean isDisplayLatitudeTitle() {
return displayLatitudeTitle;
}
/**
* @param displayLatitudeTitle
* the displayLatitudeTitle to set
*/
public void setDisplayLatitudeTitle(boolean displayLatitudeTitle) {
this.displayLatitudeTitle = displayLatitudeTitle;
}
/**
* @return the latitudeNum
*/
public int getLatitudeNum() {
return latitudeNum;
}
/**
* @param latitudeNum
* the latitudeNum to set
*/
public void setLatitudeNum(int latitudeNum) {
this.latitudeNum = latitudeNum;
}
/**
* @return the longitudeNum
*/
public int getLongitudeNum() {
return longitudeNum;
}
/**
* @param longitudeNum
* the longitudeNum to set
*/
public void setLongitudeNum(int longitudeNum) {
this.longitudeNum = longitudeNum;
}
/**
* @return the displayLongitude
*/
public boolean isDisplayLongitude() {
return displayLongitude;
}
/**
* @param displayLongitude
* the displayLongitude to set
*/
public void setDisplayLongitude(boolean displayLongitude) {
this.displayLongitude = displayLongitude;
}
/**
* @return the dashLongitude
*/
public boolean isDashLongitude() {
return dashLongitude;
}
/**
* @param dashLongitude
* the dashLongitude to set
*/
public void setDashLongitude(boolean dashLongitude) {
this.dashLongitude = dashLongitude;
}
/**
* @return the displayLatitude
*/
public boolean isDisplayLatitude() {
return displayLatitude;
}
/**
* @param displayLatitude
* the displayLatitude to set
*/
public void setDisplayLatitude(boolean displayLatitude) {
this.displayLatitude = displayLatitude;
}
/**
* @return the dashLatitude
*/
public boolean isDashLatitude() {
return dashLatitude;
}
/**
* @param dashLatitude
* the dashLatitude to set
*/
public void setDashLatitude(boolean dashLatitude) {
this.dashLatitude = dashLatitude;
}
/**
* @return the dashEffect
*/
public PathEffect getDashEffect() {
return dashEffect;
}
/**
* @param dashEffect
* the dashEffect to set
*/
public void setDashEffect(PathEffect dashEffect) {
this.dashEffect = dashEffect;
}
/**
* @return the displayBorder
*/
public boolean isDisplayBorder() {
return displayBorder;
}
/**
* @param displayBorder
* the displayBorder to set
*/
public void setDisplayBorder(boolean displayBorder) {
this.displayBorder = displayBorder;
}
/**
* @return the borderColor
*/
public int getBorderColor() {
return borderColor;
}
/**
* @param borderColor
* the borderColor to set
*/
public void setBorderColor(int borderColor) {
this.borderColor = borderColor;
}
/**
* @return the borderWidth
*/
public float getBorderWidth() {
return borderWidth;
}
/**
* @param borderWidth
* the borderWidth to set
*/
public void setBorderWidth(float borderWidth) {
this.borderWidth = borderWidth;
}
/**
* @return the longitudeFontColor
*/
public int getLongitudeFontColor() {
return longitudeFontColor;
}
/**
* @param longitudeFontColor
* the longitudeFontColor to set
*/
public void setLongitudeFontColor(int longitudeFontColor) {
this.longitudeFontColor = longitudeFontColor;
}
/**
* @return the longitudeFontSize
*/
public int getLongitudeFontSize() {
return longitudeFontSize;
}
/**
* @param longitudeFontSize
* the longitudeFontSize to set
*/
public void setLongitudeFontSize(int longitudeFontSize) {
this.longitudeFontSize = longitudeFontSize;
}
/**
* @return the latitudeFontColor
*/
public int getLatitudeFontColor() {
return latitudeFontColor;
}
/**
* @param latitudeFontColor
* the latitudeFontColor to set
*/
public void setLatitudeFontColor(int latitudeFontColor) {
this.latitudeFontColor = latitudeFontColor;
}
/**
* @return the latitudeFontSize
*/
public int getLatitudeFontSize() {
return latitudeFontSize;
}
/**
* @param latitudeFontSize
* the latitudeFontSize to set
*/
public void setLatitudeFontSize(int latitudeFontSize) {
this.latitudeFontSize = latitudeFontSize;
}
/**
* @return the crossLinesColor
*/
public int getCrossLinesColor() {
return crossLinesColor;
}
/**
* @param crossLinesColor
* the crossLinesColor to set
*/
public void setCrossLinesColor(int crossLinesColor) {
this.crossLinesColor = crossLinesColor;
}
/**
* @return the crossLinesFontColor
*/
public int getCrossLinesFontColor() {
return crossLinesFontColor;
}
/**
* @param crossLinesFontColor
* the crossLinesFontColor to set
*/
public void setCrossLinesFontColor(int crossLinesFontColor) {
this.crossLinesFontColor = crossLinesFontColor;
}
/**
* @return the longitudeTitles
*/
public List<String> getLongitudeTitles() {
return longitudeTitles;
}
/**
* @param longitudeTitles
* the longitudeTitles to set
*/
public void setLongitudeTitles(List<String> longitudeTitles) {
this.longitudeTitles = longitudeTitles;
}
/**
* @return the latitudeTitles
*/
public List<String> getLatitudeTitles() {
return latitudeTitles;
}
/**
* @param latitudeTitles
* the latitudeTitles to set
*/
public void setLatitudeTitles(List<String> latitudeTitles) {
this.latitudeTitles = latitudeTitles;
}
/**
* @return the latitudeMaxTitleLength
*/
public int getLatitudeMaxTitleLength() {
return latitudeMaxTitleLength;
}
/**
* @param latitudeMaxTitleLength
* the latitudeMaxTitleLength to set
*/
public void setLatitudeMaxTitleLength(int latitudeMaxTitleLength) {
this.latitudeMaxTitleLength = latitudeMaxTitleLength;
}
/**
* @return the clickPostX
*/
public float getClickPostX() {
return clickPostX;
}
/**
* @param clickPostX
* the clickPostX to set
*/
public void setClickPostX(float clickPostX) {
this.clickPostX = clickPostX;
}
/**
* @return the clickPostY
*/
public float getClickPostY() {
return clickPostY;
}
/**
* @param clickPostY
* the clickPostY to set
*/
public void setClickPostY(float clickPostY) {
this.clickPostY = clickPostY;
}
/**
* @return the touchPoint
*/
public PointF getTouchPoint() {
return touchPoint;
}
/**
* @param touchPoint
* the touchPoint to set
*/
public void setTouchPoint(PointF touchPoint) {
this.touchPoint = touchPoint;
}
/**
* @return the axisXPosition
*/
public int getAxisXPosition() {
return axisXPosition;
}
/**
* @param axisXPosition
* the axisXPosition to set
*/
public void setAxisXPosition(int axisXPosition) {
this.axisXPosition = axisXPosition;
}
/**
* @return the axisYPosition
*/
public int getAxisYPosition() {
return axisYPosition;
}
/**
* @param axisYPosition
* the axisYPosition to set
*/
public void setAxisYPosition(int axisYPosition) {
this.axisYPosition = axisYPosition;
}
public int getGraduation() {
return graduation;
}
public void setGraduation(int graduation) {
this.graduation = graduation;
}
public ITouchEventResponse getTouchEventResponse() {
return iTouchEventResponse;
}
public void setTouchEventResponse(
ITouchEventResponse iViewTouchEventResponse) {
this.iTouchEventResponse = iViewTouchEventResponse;
}
protected float getAxisXPrecentage(float clickPostX) {
float valueLength = clickPostX - getDataQuadrantPaddingStartX();
return valueLength / this.getDataQuadrantPaddingWidth();
}
// TODO Do not move view when onDraw
public void clearTounch() {
this.clickPostX = 0;
if (getTouchEventResponse() != null) {
getTouchEventResponse().clearTounchPoint();
}
}
public float getTounchPrepcentage() {
return tounchPrepcentage;
}
public void setTounchPrepcentage(float tounchPrepcentage) {
this.tounchPrepcentage = tounchPrepcentage;
}
}
|
12 ->14
|
android-charts/src/net/bither/charts/view/GridChart.java
|
12 ->14
|
|
Java
|
apache-2.0
|
6aaa7b811dd384e248d0d5ef3d39c99da1f0ffda
| 0
|
fnouama/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,jagguli/intellij-community,caot/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,slisson/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,izonder/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,holmes/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,dslomov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,caot/intellij-community,petteyg/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,supersven/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,slisson/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ryano144/intellij-community,xfournet/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,signed/intellij-community,hurricup/intellij-community,jagguli/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,da1z/intellij-community,clumsy/intellij-community,signed/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,semonte/intellij-community,allotria/intellij-community,adedayo/intellij-community,asedunov/intellij-community,clumsy/intellij-community,semonte/intellij-community,adedayo/intellij-community,samthor/intellij-community,kool79/intellij-community,da1z/intellij-community,samthor/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,allotria/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,semonte/intellij-community,dslomov/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,slisson/intellij-community,orekyuu/intellij-community,supersven/intellij-community,vvv1559/intellij-community,kool79/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,clumsy/intellij-community,robovm/robovm-studio,izonder/intellij-community,caot/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,allotria/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,semonte/intellij-community,adedayo/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,apixandru/intellij-community,samthor/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,signed/intellij-community,slisson/intellij-community,retomerz/intellij-community,samthor/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,dslomov/intellij-community,semonte/intellij-community,fnouama/intellij-community,supersven/intellij-community,ryano144/intellij-community,izonder/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vladmm/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,Lekanich/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,jagguli/intellij-community,izonder/intellij-community,hurricup/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,fnouama/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,slisson/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,pwoodworth/intellij-community,caot/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ryano144/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,xfournet/intellij-community,signed/intellij-community,jagguli/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,adedayo/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,kool79/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,jagguli/intellij-community,jagguli/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,tmpgit/intellij-community,izonder/intellij-community,petteyg/intellij-community,diorcety/intellij-community,fitermay/intellij-community,diorcety/intellij-community,FHannes/intellij-community,dslomov/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,caot/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,suncycheng/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,kool79/intellij-community,clumsy/intellij-community,blademainer/intellij-community,ryano144/intellij-community,fnouama/intellij-community,xfournet/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,ibinti/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,caot/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,petteyg/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,allotria/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,adedayo/intellij-community,diorcety/intellij-community,da1z/intellij-community,diorcety/intellij-community,samthor/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,signed/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,signed/intellij-community,jagguli/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,izonder/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,asedunov/intellij-community,supersven/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,asedunov/intellij-community,hurricup/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,kool79/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,fnouama/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,semonte/intellij-community,kool79/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,fitermay/intellij-community,apixandru/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,amith01994/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,allotria/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,supersven/intellij-community,samthor/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,vladmm/intellij-community,kool79/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,holmes/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,fitermay/intellij-community,ibinti/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,nicolargo/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,samthor/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,apixandru/intellij-community,slisson/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,caot/intellij-community,apixandru/intellij-community,petteyg/intellij-community,amith01994/intellij-community,kool79/intellij-community,dslomov/intellij-community,holmes/intellij-community,FHannes/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,allotria/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,orekyuu/intellij-community,holmes/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,da1z/intellij-community,da1z/intellij-community,blademainer/intellij-community,samthor/intellij-community,fitermay/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,signed/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,caot/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ryano144/intellij-community,kool79/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,signed/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,vvv1559/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,holmes/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,clumsy/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diagnostic;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* @author yole
*/
public class ThreadDumper {
private ThreadDumper() {
}
public static String dumpThreadsToString() {
StringWriter writer = new StringWriter();
dumpThreadsToFile(ManagementFactory.getThreadMXBean(), writer);
return writer.toString();
}
@Nullable
static StackTraceElement[] dumpThreadsToFile(final ThreadMXBean threadMXBean, final Writer f) {
StackTraceElement[] edtStack = null;
boolean dumpSuccessful = false;
try {
ThreadInfo[] threads = sort(threadMXBean.dumpAllThreads(false, false));
for(ThreadInfo info: threads) {
if (info != null) {
if (info.getThreadName().equals("AWT-EventQueue-1")) {
edtStack = info.getStackTrace();
}
dumpThreadInfo(info, f);
}
}
dumpSuccessful = true;
}
catch (Exception ignored) {
}
if (!dumpSuccessful) {
final long[] threadIds = threadMXBean.getAllThreadIds();
final ThreadInfo[] threadInfo = sort(threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE));
for (ThreadInfo info : threadInfo) {
if (info != null) {
if (info.getThreadName().equals("AWT-EventQueue-1")) {
edtStack = info.getStackTrace();
}
dumpThreadInfo(info, f);
}
}
}
return edtStack;
}
private static ThreadInfo[] sort(ThreadInfo[] threads) {
int edtIndex = -1;
for (int i = 0; i < threads.length; i++) {
if (threads[i].getThreadName().startsWith("AWT-EventQueue")) {
edtIndex = i;
break;
}
}
if (edtIndex > 0) {
ThreadInfo edt = threads[edtIndex];
System.arraycopy(threads, 0, threads, 1, edtIndex);
threads[0] = edt;
}
return threads;
}
private static void dumpThreadInfo(final ThreadInfo info, final Writer f) {
dumpCallStack(info, f, info.getStackTrace());
}
private static void dumpCallStack(final ThreadInfo info, final Writer f, final StackTraceElement[] stackTraceElements) {
try {
@NonNls StringBuilder sb = new StringBuilder("\"").append(info.getThreadName()).append("\"");
sb.append(" prio=0 tid=0x0 nid=0x0 ").append(getReadableState(info.getThreadState())).append("\n");
sb.append(" java.lang.Thread.State: ").append(info.getThreadState()).append("\n");
if (info.getLockName() != null) {
sb.append(" on ").append(info.getLockName());
}
if (info.getLockOwnerName() != null) {
sb.append(" owned by \"").append(info.getLockOwnerName()).append("\" Id=").append(info.getLockOwnerId());
}
if (info.isSuspended()) {
sb.append(" (suspended)");
}
if (info.isInNative()) {
sb.append(" (in native)");
}
f.write(sb + "\n");
for (StackTraceElement element : stackTraceElements) {
f.write("\tat " + element.toString() + "\n");
}
f.write("\n");
}
catch (IOException e) {
e.printStackTrace();
}
}
private static String getReadableState(Thread.State state) {
switch (state) {
case BLOCKED: return "blocked";
case TIMED_WAITING:
case WAITING: return "waiting on condition";
case RUNNABLE: return "runnable";
case NEW: return "new";
case TERMINATED: return "terminated";
}
return null;
}
}
|
platform/util/src/com/intellij/diagnostic/ThreadDumper.java
|
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diagnostic;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* @author yole
*/
public class ThreadDumper {
private ThreadDumper() {
}
public static String dumpThreadsToString() {
StringWriter writer = new StringWriter();
dumpThreadsToFile(ManagementFactory.getThreadMXBean(), writer);
return writer.toString();
}
@Nullable
static StackTraceElement[] dumpThreadsToFile(final ThreadMXBean threadMXBean, final Writer f) {
StackTraceElement[] edtStack = null;
boolean dumpSuccessful = false;
try {
ThreadInfo[] threads = threadMXBean.dumpAllThreads(false, false);
for(ThreadInfo info: threads) {
if (info != null) {
if (info.getThreadName().equals("AWT-EventQueue-1")) {
edtStack = info.getStackTrace();
}
dumpThreadInfo(info, f);
}
}
dumpSuccessful = true;
}
catch (Exception ignored) {
}
if (!dumpSuccessful) {
final long[] threadIds = threadMXBean.getAllThreadIds();
final ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
for (ThreadInfo info : threadInfo) {
if (info != null) {
if (info.getThreadName().equals("AWT-EventQueue-1")) {
edtStack = info.getStackTrace();
}
dumpThreadInfo(info, f);
}
}
}
return edtStack;
}
private static void dumpThreadInfo(final ThreadInfo info, final Writer f) {
dumpCallStack(info, f, info.getStackTrace());
}
private static void dumpCallStack(final ThreadInfo info, final Writer f, final StackTraceElement[] stackTraceElements) {
try {
@NonNls StringBuilder sb = new StringBuilder("\"").append(info.getThreadName()).append("\"");
sb.append(" prio=0 tid=0x0 nid=0x0 ").append(getReadableState(info.getThreadState())).append("\n");
sb.append(" java.lang.Thread.State: ").append(info.getThreadState()).append("\n");
if (info.getLockName() != null) {
sb.append(" on ").append(info.getLockName());
}
if (info.getLockOwnerName() != null) {
sb.append(" owned by \"").append(info.getLockOwnerName()).append("\" Id=").append(info.getLockOwnerId());
}
if (info.isSuspended()) {
sb.append(" (suspended)");
}
if (info.isInNative()) {
sb.append(" (in native)");
}
f.write(sb + "\n");
for (StackTraceElement element : stackTraceElements) {
f.write("\tat " + element.toString() + "\n");
}
f.write("\n");
}
catch (IOException e) {
e.printStackTrace();
}
}
private static String getReadableState(Thread.State state) {
switch (state) {
case BLOCKED: return "blocked";
case TIMED_WAITING:
case WAITING: return "waiting on condition";
case RUNNABLE: return "runnable";
case NEW: return "new";
case TERMINATED: return "terminated";
}
return null;
}
}
|
dump EDT always on top
|
platform/util/src/com/intellij/diagnostic/ThreadDumper.java
|
dump EDT always on top
|
|
Java
|
apache-2.0
|
a66d7a0b5627bcd92b841bc0da001e949545cd24
| 0
|
ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,allotria/intellij-community,semonte/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,signed/intellij-community,semonte/intellij-community,apixandru/intellij-community,semonte/intellij-community,suncycheng/intellij-community,allotria/intellij-community,asedunov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,signed/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,allotria/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,signed/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,allotria/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,FHannes/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,signed/intellij-community,allotria/intellij-community,suncycheng/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,semonte/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,signed/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,allotria/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,signed/intellij-community,mglukhikh/intellij-community
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.lang.properties;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.lang.properties.psi.Property;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
/**
* @author cdr
*/
class RemovePropertyFix implements IntentionAction {
private final SmartPsiElementPointer<Property> myProperty;
RemovePropertyFix(@NotNull final Property origProperty) {
myProperty = SmartPointerManager.getInstance(origProperty.getProject()).createSmartPsiElementPointer(origProperty);
}
@Override
@NotNull
public String getText() {
return PropertiesBundle.message("remove.property.intention.text");
}
@Override
@NotNull
public String getFamilyName() {
return getText();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return file != null &&
file.isValid() &&
PsiManager.getInstance(project).isInProject(file) &&
myProperty.getElement() != null;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
ObjectUtils.notNull(myProperty.getElement()).delete();
}
@Override
public boolean startInWriteAction() {
return true;
}
}
|
plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/RemovePropertyFix.java
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.lang.properties;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.lang.properties.psi.Property;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
/**
* @author cdr
*/
class RemovePropertyFix implements IntentionAction {
private final Property myProperty;
RemovePropertyFix(@NotNull final Property origProperty) {
myProperty = origProperty;
}
@Override
@NotNull
public String getText() {
return PropertiesBundle.message("remove.property.intention.text");
}
@Override
@NotNull
public String getFamilyName() {
return getText();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return file != null &&
file.isValid() &&
myProperty.isValid() &&
PsiManager.getInstance(project).isInProject(myProperty);
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
myProperty.delete();
}
@Override
public boolean startInWriteAction() {
return true;
}
}
|
properties: wrap remove property quick fix field with smart pointer
|
plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/RemovePropertyFix.java
|
properties: wrap remove property quick fix field with smart pointer
|
|
Java
|
apache-2.0
|
393bdc0d4e4a570683570f33b08aed995767f0ca
| 0
|
fitermay/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,retomerz/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,clumsy/intellij-community,retomerz/intellij-community,signed/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,allotria/intellij-community,retomerz/intellij-community,clumsy/intellij-community,FHannes/intellij-community,allotria/intellij-community,vladmm/intellij-community,fitermay/intellij-community,allotria/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,kdwink/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,FHannes/intellij-community,allotria/intellij-community,hurricup/intellij-community,apixandru/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,hurricup/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,signed/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,vladmm/intellij-community,signed/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,semonte/intellij-community,suncycheng/intellij-community,signed/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fitermay/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,kdwink/intellij-community,FHannes/intellij-community,retomerz/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,fitermay/intellij-community,apixandru/intellij-community,kdwink/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vladmm/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,hurricup/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,hurricup/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,kdwink/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,fitermay/intellij-community,allotria/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,xfournet/intellij-community,apixandru/intellij-community,semonte/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,semonte/intellij-community,fitermay/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,signed/intellij-community,semonte/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,retomerz/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,retomerz/intellij-community,vladmm/intellij-community,signed/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,vladmm/intellij-community,allotria/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,da1z/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,FHannes/intellij-community,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,signed/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ibinti/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community
|
package org.testng;
import com.intellij.rt.execution.junit.ComparisonFailureData;
import org.testng.internal.IResultListener;
import org.testng.xml.XmlTest;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
/**
* User: anna
* Date: 5/22/13
*/
public class IDEATestNGRemoteListener implements ISuiteListener, IResultListener {
private final PrintStream myPrintStream;
private final List<String> myCurrentSuites = new ArrayList<String>();
private final Map<String, Integer> myInvocationCounts = new HashMap<String, Integer>();
private final Map<ExposedTestResult, String> myParamsMap = new HashMap<ExposedTestResult, String>();
public IDEATestNGRemoteListener() {
this(System.out);
}
public IDEATestNGRemoteListener(PrintStream printStream) {
myPrintStream = printStream;
myPrintStream.println("##teamcity[enteredTheMatrix]");
}
public synchronized void onStart(final ISuite suite) {
if (suite != null) {
try {
final List<ITestNGMethod> allMethods = suite.getAllMethods();
if (allMethods != null) {
int count = 0;
for (ITestNGMethod method : allMethods) {
if (method.isTest()) count += method.getInvocationCount();
}
myPrintStream.println("##teamcity[testCount count = \'" + count + "\']");
}
}
catch (NoSuchMethodError ignore) {}
myPrintStream.println("##teamcity[rootName name = '" + suite.getName() + "' location = 'file://" + suite.getXmlSuite().getFileName() + "']");
}
}
public synchronized void onFinish(ISuite suite) {
try {
if (suite != null && suite.getAllInvokedMethods().size() < suite.getAllMethods().size()) {
for (ITestNGMethod method : suite.getAllMethods()) {
if (method.isTest()) {
boolean found = false;
for (IInvokedMethod invokedMethod : suite.getAllInvokedMethods()) {
if (invokedMethod.getTestMethod() == method) {
found = true;
break;
}
}
if (!found) {
final String fullEscapedMethodName = escapeName(getShortName(method.getTestClass().getName()) + "." + method.getMethodName());
myPrintStream.println("##teamcity[testStarted name=\'" + fullEscapedMethodName + "\']");
myPrintStream.println("##teamcity[testIgnored name=\'" + fullEscapedMethodName + "\']");
myPrintStream.println("##teamcity[testFinished name=\'" + fullEscapedMethodName + "\']");
break;
}
}
}
}
}
catch (NoSuchMethodError ignored) {}
for (int i = myCurrentSuites.size() - 1; i >= 0; i--) {
onSuiteFinish(myCurrentSuites.remove(i));
}
myCurrentSuites.clear();
}
public synchronized void onConfigurationSuccess(ITestResult result) {
final DelegatedResult delegatedResult = new DelegatedResult(result);
onConfigurationStart(delegatedResult);
onConfigurationSuccess(delegatedResult);
}
public synchronized void onConfigurationFailure(ITestResult result) {
final DelegatedResult delegatedResult = new DelegatedResult(result);
onConfigurationStart(delegatedResult);
onConfigurationFailure(delegatedResult);
}
public synchronized void onConfigurationSkip(ITestResult itr) {}
public synchronized void onTestStart(ITestResult result) {
onTestStart(new DelegatedResult(result));
}
public synchronized void onTestSuccess(ITestResult result) {
onTestFinished(new DelegatedResult(result));
}
public synchronized void onTestFailure(ITestResult result) {
onTestFailure(new DelegatedResult(result));
}
public synchronized void onTestSkipped(ITestResult result) {
onTestSkipped(new DelegatedResult(result));
}
public synchronized void onTestFailedButWithinSuccessPercentage(ITestResult result) {
final Throwable throwable = result.getThrowable();
if (throwable != null) {
throwable.printStackTrace();
}
onTestSuccess(result);
}
public synchronized void onStart(ITestContext context) {}
public synchronized void onFinish(ITestContext context) {}
public void onTestStart(ExposedTestResult result) {
final Object[] parameters = result.getParameters();
final String qualifiedName = result.getClassName() + result.getMethodName();
Integer invocationCount = myInvocationCounts.get(qualifiedName);
if (invocationCount == null) {
invocationCount = 0;
}
final String paramString = getParamsString(parameters, invocationCount);
onTestStart(result, paramString, invocationCount, false);
myInvocationCounts.put(qualifiedName, invocationCount + 1);
}
public void onConfigurationStart(ExposedTestResult result) {
onTestStart(result, null, -1, true);
}
public void onConfigurationSuccess(ExposedTestResult result) {
onTestFinished(result);
}
public void onConfigurationFailure(ExposedTestResult result) {
onTestFailure(result);
}
public boolean onSuiteStart(String classFQName, boolean provideLocation) {
return onSuiteStart(Collections.singletonList(classFQName), null, provideLocation);
}
public boolean onSuiteStart(List<String> parentsHierarchy, ExposedTestResult result, boolean provideLocation) {
int idx = 0;
String currentClass;
String currentParent;
while (idx < myCurrentSuites.size() && idx < parentsHierarchy.size()) {
currentClass = myCurrentSuites.get(idx);
currentParent =parentsHierarchy.get(parentsHierarchy.size() - 1 - idx);
if (!currentClass.equals(getShortName(currentParent))) break;
idx++;
}
for (int i = myCurrentSuites.size() - 1; i >= idx; i--) {
currentClass = myCurrentSuites.remove(i);
myPrintStream.println("##teamcity[testSuiteFinished name=\'" + escapeName(currentClass) + "\']");
}
for (int i = idx; i < parentsHierarchy.size(); i++) {
String fqName = parentsHierarchy.get(parentsHierarchy.size() - 1 - i);
String currentClassName = getShortName(fqName);
String location = "java:suite://" + escapeName(fqName);
if (result != null) {
final String testName = result.getXmlTestName();
if (fqName.equals(testName)) {
final String fileName = result.getFileName();
if (fileName != null) {
location = "file://" + fileName;
}
}
}
myPrintStream.println("\n##teamcity[testSuiteStarted name =\'" + escapeName(currentClassName) +
(provideLocation ? "\' locationHint = \'" + location : "") + "\']");
myCurrentSuites.add(currentClassName);
}
return false;
}
public void onSuiteFinish(String suiteName) {
myPrintStream.println("##teamcity[testSuiteFinished name=\'" + escapeName(suiteName) + "\']");
}
private void onTestStart(ExposedTestResult result, String paramString, Integer invocationCount, boolean config) {
myParamsMap.put(result, paramString);
onSuiteStart(result.getTestHierarchy(), result, true);
final String className = result.getClassName();
final String methodName = result.getMethodName();
final String location = className + "." + methodName + (invocationCount >= 0 ? "[" + invocationCount + "]" : "");
myPrintStream.println("\n##teamcity[testStarted name=\'" + escapeName(getShortName(className) + "." + methodName + (paramString != null ? paramString : "")) +
"\' locationHint=\'java:test://" + escapeName(location) + (config ? "\' config=\'true" : "") + "\']");
}
public void onTestFailure(ExposedTestResult result) {
if (!myParamsMap.containsKey(result)) {
onTestStart(result);
}
Throwable ex = result.getThrowable();
String methodName = getTestMethodNameWithParams(result);
final Map<String, String> attrs = new HashMap<String, String>();
attrs.put("name", methodName);
final String failureMessage = ex.getMessage();
ComparisonFailureData notification;
try {
notification = TestNGExpectedPatterns.createExceptionNotification(failureMessage);
}
catch (Throwable e) {
notification = null;
}
ComparisonFailureData.registerSMAttributes(notification, getTrace(ex), failureMessage, attrs, ex);
myPrintStream.println(MapSerializerUtil.asString("testFailed", attrs));
onTestFinished(result);
}
public void onTestSkipped(ExposedTestResult result) {
if (!myParamsMap.containsKey(result)) {
onTestStart(result);
}
myPrintStream.println("\n##teamcity[testIgnored name=\'" + escapeName(getTestMethodNameWithParams(result)) + "\']");
onTestFinished(result);
}
public void onTestFinished(ExposedTestResult result) {
final long duration = result.getDuration();
myPrintStream.println("\n##teamcity[testFinished name=\'" +
escapeName(getTestMethodNameWithParams(result)) +
(duration > 0 ? "\' duration=\'" + Long.toString(duration) : "") +
"\']");
}
private synchronized String getTestMethodNameWithParams(ExposedTestResult result) {
String methodName = getShortName(result.getClassName()) + "." + result.getMethodName();
String paramString = myParamsMap.get(result);
if (paramString != null) {
methodName += paramString;
}
return methodName;
}
private static String getParamsString(Object[] parameters, int invocationCount) {
String paramString = "";
if (parameters.length > 0) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < parameters.length; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(parameters[i]);
}
paramString = "[" + buf.toString() + "]";
}
if (invocationCount > 0) {
paramString += " (" + invocationCount + ")";
}
return paramString.length() > 0 ? paramString : null;
}
protected String getTrace(Throwable tr) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
tr.printStackTrace(writer);
StringBuffer buffer = stringWriter.getBuffer();
return buffer.toString();
}
protected static String getShortName(String fqName) {
int lastPointIdx = fqName.lastIndexOf('.');
if (lastPointIdx >= 0) {
return fqName.substring(lastPointIdx + 1);
}
return fqName;
}
private static String escapeName(String str) {
return MapSerializerUtil.escapeStr(str, MapSerializerUtil.STD_ESCAPER);
}
public interface ExposedTestResult {
Object[] getParameters();
String getMethodName();
String getClassName();
long getDuration();
List<String> getTestHierarchy();
String getFileName();
String getXmlTestName();
Throwable getThrowable();
}
protected static class DelegatedResult implements ExposedTestResult {
private final ITestResult myResult;
public DelegatedResult(ITestResult result) {
myResult = result;
}
public Object[] getParameters() {
return myResult.getParameters();
}
public String getMethodName() {
return myResult.getMethod().getMethodName();
}
public String getClassName() {
return myResult.getMethod().getTestClass().getName();
}
public long getDuration() {
return myResult.getEndMillis() - myResult.getStartMillis();
}
public List<String> getTestHierarchy() {
final List<String> hierarchy;
final XmlTest xmlTest = myResult.getTestClass().getXmlTest();
if (xmlTest != null) {
hierarchy = Arrays.asList(getClassName(), xmlTest.getName());
} else {
hierarchy = Collections.singletonList(getClassName());
}
return hierarchy;
}
public String getFileName() {
final XmlTest xmlTest = myResult.getTestClass().getXmlTest();
return xmlTest != null ? xmlTest.getSuite().getFileName() : null;
}
public String getXmlTestName() {
final XmlTest xmlTest = myResult.getTestClass().getXmlTest();
return xmlTest != null ? xmlTest.getName() : null;
}
public Throwable getThrowable() {
return myResult.getThrowable();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return myResult.equals(((DelegatedResult)o).myResult);
}
@Override
public int hashCode() {
return myResult.hashCode();
}
}
}
|
plugins/testng_rt/src/org/testng/IDEATestNGRemoteListener.java
|
package org.testng;
import com.intellij.rt.execution.junit.ComparisonFailureData;
import org.testng.internal.IResultListener;
import org.testng.xml.XmlTest;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
/**
* User: anna
* Date: 5/22/13
*/
public class IDEATestNGRemoteListener implements ISuiteListener, IResultListener {
private final PrintStream myPrintStream;
private final List<String> myCurrentSuites = new ArrayList<String>();
private final Map<String, Integer> myInvocationCounts = new HashMap<String, Integer>();
private final Map<ExposedTestResult, String> myParamsMap = new HashMap<ExposedTestResult, String>();
public IDEATestNGRemoteListener() {
this(System.out);
}
public IDEATestNGRemoteListener(PrintStream printStream) {
myPrintStream = printStream;
myPrintStream.println("##teamcity[enteredTheMatrix]");
}
public synchronized void onStart(final ISuite suite) {
if (suite != null) {
final List<ITestNGMethod> allMethods = suite.getAllMethods();
if (allMethods != null) {
int count = 0;
for (ITestNGMethod method : allMethods) {
if (method.isTest()) count += method.getInvocationCount();
}
myPrintStream.println("##teamcity[testCount count = \'" + count + "\']");
}
myPrintStream.println("##teamcity[rootName name = '" + suite.getName() + "' location = 'file://" + suite.getXmlSuite().getFileName() + "']");
}
}
public synchronized void onFinish(ISuite suite) {
if (suite != null && suite.getAllInvokedMethods().size() < suite.getAllMethods().size()) {
for (ITestNGMethod method : suite.getAllMethods()) {
if (method.isTest()) {
boolean found = false;
for (IInvokedMethod invokedMethod : suite.getAllInvokedMethods()) {
if (invokedMethod.getTestMethod() == method) {
found = true;
break;
}
}
if (!found) {
final String fullEscapedMethodName = escapeName(getShortName(method.getTestClass().getName()) + "." + method.getMethodName());
myPrintStream.println("##teamcity[testStarted name=\'" + fullEscapedMethodName + "\']");
myPrintStream.println("##teamcity[testIgnored name=\'" + fullEscapedMethodName + "\']");
myPrintStream.println("##teamcity[testFinished name=\'" + fullEscapedMethodName + "\']");
break;
}
}
}
}
for (int i = myCurrentSuites.size() - 1; i >= 0; i--) {
onSuiteFinish(myCurrentSuites.remove(i));
}
myCurrentSuites.clear();
}
public synchronized void onConfigurationSuccess(ITestResult result) {
final DelegatedResult delegatedResult = new DelegatedResult(result);
onConfigurationStart(delegatedResult);
onConfigurationSuccess(delegatedResult);
}
public synchronized void onConfigurationFailure(ITestResult result) {
final DelegatedResult delegatedResult = new DelegatedResult(result);
onConfigurationStart(delegatedResult);
onConfigurationFailure(delegatedResult);
}
public synchronized void onConfigurationSkip(ITestResult itr) {}
public synchronized void onTestStart(ITestResult result) {
onTestStart(new DelegatedResult(result));
}
public synchronized void onTestSuccess(ITestResult result) {
onTestFinished(new DelegatedResult(result));
}
public synchronized void onTestFailure(ITestResult result) {
onTestFailure(new DelegatedResult(result));
}
public synchronized void onTestSkipped(ITestResult result) {
onTestSkipped(new DelegatedResult(result));
}
public synchronized void onTestFailedButWithinSuccessPercentage(ITestResult result) {
final Throwable throwable = result.getThrowable();
if (throwable != null) {
throwable.printStackTrace();
}
onTestSuccess(result);
}
public synchronized void onStart(ITestContext context) {}
public synchronized void onFinish(ITestContext context) {}
public void onTestStart(ExposedTestResult result) {
final Object[] parameters = result.getParameters();
final String qualifiedName = result.getClassName() + result.getMethodName();
Integer invocationCount = myInvocationCounts.get(qualifiedName);
if (invocationCount == null) {
invocationCount = 0;
}
final String paramString = getParamsString(parameters, invocationCount);
onTestStart(result, paramString, invocationCount, false);
myInvocationCounts.put(qualifiedName, invocationCount + 1);
}
public void onConfigurationStart(ExposedTestResult result) {
onTestStart(result, null, -1, true);
}
public void onConfigurationSuccess(ExposedTestResult result) {
onTestFinished(result);
}
public void onConfigurationFailure(ExposedTestResult result) {
onTestFailure(result);
}
public boolean onSuiteStart(String classFQName, boolean provideLocation) {
return onSuiteStart(Collections.singletonList(classFQName), null, provideLocation);
}
public boolean onSuiteStart(List<String> parentsHierarchy, ExposedTestResult result, boolean provideLocation) {
int idx = 0;
String currentClass;
String currentParent;
while (idx < myCurrentSuites.size() && idx < parentsHierarchy.size()) {
currentClass = myCurrentSuites.get(idx);
currentParent =parentsHierarchy.get(parentsHierarchy.size() - 1 - idx);
if (!currentClass.equals(getShortName(currentParent))) break;
idx++;
}
for (int i = myCurrentSuites.size() - 1; i >= idx; i--) {
currentClass = myCurrentSuites.remove(i);
myPrintStream.println("##teamcity[testSuiteFinished name=\'" + escapeName(currentClass) + "\']");
}
for (int i = idx; i < parentsHierarchy.size(); i++) {
String fqName = parentsHierarchy.get(parentsHierarchy.size() - 1 - i);
String currentClassName = getShortName(fqName);
String location = "java:suite://" + escapeName(fqName);
if (result != null) {
final String testName = result.getXmlTestName();
if (fqName.equals(testName)) {
final String fileName = result.getFileName();
if (fileName != null) {
location = "file://" + fileName;
}
}
}
myPrintStream.println("\n##teamcity[testSuiteStarted name =\'" + escapeName(currentClassName) +
(provideLocation ? "\' locationHint = \'" + location : "") + "\']");
myCurrentSuites.add(currentClassName);
}
return false;
}
public void onSuiteFinish(String suiteName) {
myPrintStream.println("##teamcity[testSuiteFinished name=\'" + escapeName(suiteName) + "\']");
}
private void onTestStart(ExposedTestResult result, String paramString, Integer invocationCount, boolean config) {
myParamsMap.put(result, paramString);
onSuiteStart(result.getTestHierarchy(), result, true);
final String className = result.getClassName();
final String methodName = result.getMethodName();
final String location = className + "." + methodName + (invocationCount >= 0 ? "[" + invocationCount + "]" : "");
myPrintStream.println("\n##teamcity[testStarted name=\'" + escapeName(getShortName(className) + "." + methodName + (paramString != null ? paramString : "")) +
"\' locationHint=\'java:test://" + escapeName(location) + (config ? "\' config=\'true" : "") + "\']");
}
public void onTestFailure(ExposedTestResult result) {
if (!myParamsMap.containsKey(result)) {
onTestStart(result);
}
Throwable ex = result.getThrowable();
String methodName = getTestMethodNameWithParams(result);
final Map<String, String> attrs = new HashMap<String, String>();
attrs.put("name", methodName);
final String failureMessage = ex.getMessage();
ComparisonFailureData notification;
try {
notification = TestNGExpectedPatterns.createExceptionNotification(failureMessage);
}
catch (Throwable e) {
notification = null;
}
ComparisonFailureData.registerSMAttributes(notification, getTrace(ex), failureMessage, attrs, ex);
myPrintStream.println(MapSerializerUtil.asString("testFailed", attrs));
onTestFinished(result);
}
public void onTestSkipped(ExposedTestResult result) {
if (!myParamsMap.containsKey(result)) {
onTestStart(result);
}
myPrintStream.println("\n##teamcity[testIgnored name=\'" + escapeName(getTestMethodNameWithParams(result)) + "\']");
onTestFinished(result);
}
public void onTestFinished(ExposedTestResult result) {
final long duration = result.getDuration();
myPrintStream.println("\n##teamcity[testFinished name=\'" +
escapeName(getTestMethodNameWithParams(result)) +
(duration > 0 ? "\' duration=\'" + Long.toString(duration) : "") +
"\']");
}
private synchronized String getTestMethodNameWithParams(ExposedTestResult result) {
String methodName = getShortName(result.getClassName()) + "." + result.getMethodName();
String paramString = myParamsMap.get(result);
if (paramString != null) {
methodName += paramString;
}
return methodName;
}
private static String getParamsString(Object[] parameters, int invocationCount) {
String paramString = "";
if (parameters.length > 0) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < parameters.length; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(parameters[i]);
}
paramString = "[" + buf.toString() + "]";
}
if (invocationCount > 0) {
paramString += " (" + invocationCount + ")";
}
return paramString.length() > 0 ? paramString : null;
}
protected String getTrace(Throwable tr) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
tr.printStackTrace(writer);
StringBuffer buffer = stringWriter.getBuffer();
return buffer.toString();
}
protected static String getShortName(String fqName) {
int lastPointIdx = fqName.lastIndexOf('.');
if (lastPointIdx >= 0) {
return fqName.substring(lastPointIdx + 1);
}
return fqName;
}
private static String escapeName(String str) {
return MapSerializerUtil.escapeStr(str, MapSerializerUtil.STD_ESCAPER);
}
public interface ExposedTestResult {
Object[] getParameters();
String getMethodName();
String getClassName();
long getDuration();
List<String> getTestHierarchy();
String getFileName();
String getXmlTestName();
Throwable getThrowable();
}
protected static class DelegatedResult implements ExposedTestResult {
private final ITestResult myResult;
public DelegatedResult(ITestResult result) {
myResult = result;
}
public Object[] getParameters() {
return myResult.getParameters();
}
public String getMethodName() {
return myResult.getMethod().getMethodName();
}
public String getClassName() {
return myResult.getMethod().getTestClass().getName();
}
public long getDuration() {
return myResult.getEndMillis() - myResult.getStartMillis();
}
public List<String> getTestHierarchy() {
final List<String> hierarchy;
final XmlTest xmlTest = myResult.getTestClass().getXmlTest();
if (xmlTest != null) {
hierarchy = Arrays.asList(getClassName(), xmlTest.getName());
} else {
hierarchy = Collections.singletonList(getClassName());
}
return hierarchy;
}
public String getFileName() {
final XmlTest xmlTest = myResult.getTestClass().getXmlTest();
return xmlTest != null ? xmlTest.getSuite().getFileName() : null;
}
public String getXmlTestName() {
final XmlTest xmlTest = myResult.getTestClass().getXmlTest();
return xmlTest != null ? xmlTest.getName() : null;
}
public Throwable getThrowable() {
return myResult.getThrowable();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return myResult.equals(((DelegatedResult)o).myResult);
}
@Override
public int hashCode() {
return myResult.hashCode();
}
}
}
|
catch NoSuchMethodError in case old testng version is used
|
plugins/testng_rt/src/org/testng/IDEATestNGRemoteListener.java
|
catch NoSuchMethodError in case old testng version is used
|
|
Java
|
apache-2.0
|
c5d0d5eafffc953c3e963f38d6b74529999fb72d
| 0
|
jagguli/intellij-community,allotria/intellij-community,fnouama/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,caot/intellij-community,apixandru/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,semonte/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,allotria/intellij-community,signed/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,holmes/intellij-community,allotria/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,caot/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,kool79/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,kool79/intellij-community,Lekanich/intellij-community,izonder/intellij-community,da1z/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,slisson/intellij-community,fnouama/intellij-community,ibinti/intellij-community,dslomov/intellij-community,signed/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,semonte/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,caot/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,signed/intellij-community,ryano144/intellij-community,samthor/intellij-community,supersven/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,petteyg/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,caot/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,supersven/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,allotria/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,fnouama/intellij-community,ryano144/intellij-community,slisson/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,da1z/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,slisson/intellij-community,supersven/intellij-community,vladmm/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,dslomov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,signed/intellij-community,Lekanich/intellij-community,izonder/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ahb0327/intellij-community,signed/intellij-community,hurricup/intellij-community,ibinti/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,xfournet/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,caot/intellij-community,allotria/intellij-community,fnouama/intellij-community,fitermay/intellij-community,slisson/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,robovm/robovm-studio,diorcety/intellij-community,caot/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,clumsy/intellij-community,semonte/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,supersven/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,kdwink/intellij-community,semonte/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,amith01994/intellij-community,jagguli/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ryano144/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,supersven/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,da1z/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,xfournet/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,signed/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,slisson/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ibinti/intellij-community,allotria/intellij-community,samthor/intellij-community,apixandru/intellij-community,robovm/robovm-studio,caot/intellij-community,holmes/intellij-community,jagguli/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,adedayo/intellij-community,supersven/intellij-community,semonte/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,caot/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,da1z/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,hurricup/intellij-community,da1z/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,diorcety/intellij-community,FHannes/intellij-community,vladmm/intellij-community,kdwink/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,petteyg/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,amith01994/intellij-community,holmes/intellij-community,clumsy/intellij-community,slisson/intellij-community,kdwink/intellij-community,signed/intellij-community,supersven/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,izonder/intellij-community,retomerz/intellij-community,vladmm/intellij-community,semonte/intellij-community,allotria/intellij-community,kool79/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,caot/intellij-community,da1z/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,holmes/intellij-community,signed/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,samthor/intellij-community,asedunov/intellij-community,hurricup/intellij-community,diorcety/intellij-community,FHannes/intellij-community,fnouama/intellij-community,diorcety/intellij-community,dslomov/intellij-community,FHannes/intellij-community,petteyg/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,apixandru/intellij-community,supersven/intellij-community,izonder/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,signed/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,izonder/intellij-community,fitermay/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,jagguli/intellij-community,samthor/intellij-community,petteyg/intellij-community,caot/intellij-community,FHannes/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,slisson/intellij-community,slisson/intellij-community,gnuhub/intellij-community,caot/intellij-community,fnouama/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,holmes/intellij-community,samthor/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,fnouama/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,semonte/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,da1z/intellij-community,kool79/intellij-community,orekyuu/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,signed/intellij-community,semonte/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,kool79/intellij-community,FHannes/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,hurricup/intellij-community,apixandru/intellij-community,xfournet/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,asedunov/intellij-community,fnouama/intellij-community,diorcety/intellij-community,amith01994/intellij-community,clumsy/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,supersven/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,samthor/intellij-community,blademainer/intellij-community,hurricup/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,fitermay/intellij-community,semonte/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ryano144/intellij-community,holmes/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,caot/intellij-community,izonder/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,kool79/intellij-community,xfournet/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,adedayo/intellij-community,dslomov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.actionSystem;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ActionGroupUtil {
private static Presentation getPresentation(AnAction action, Map<AnAction, Presentation> action2presentation) {
Presentation presentation = action2presentation.get(action);
if (presentation == null) {
presentation = action.getTemplatePresentation().clone();
action2presentation.put(action, presentation);
}
return presentation;
}
public static boolean isGroupEmpty(@NotNull ActionGroup actionGroup, @NotNull AnActionEvent e) {
return isGroupEmpty(actionGroup, e, new HashMap<AnAction, Presentation>());
}
private static boolean isGroupEmpty(@NotNull ActionGroup actionGroup,
@NotNull AnActionEvent e,
@NotNull Map<AnAction, Presentation> action2presentation) {
AnAction[] actions = actionGroup.getChildren(e);
for (AnAction action : actions) {
if (action instanceof Separator) continue;
if (isActionEnabledAndVisible(e, action2presentation, action)) {
if (action instanceof ActionGroup) {
return isGroupEmpty((ActionGroup)action, e, action2presentation);
}
else {
return false;
}
}
}
return true;
}
@Nullable
public static AnAction getSingleActiveAction(@NotNull ActionGroup actionGroup, @NotNull AnActionEvent e) {
List<AnAction> children = getEnabledChildren(actionGroup, e, new HashMap<AnAction, Presentation>());
if (children.size() == 1) {
return children.get(0);
}
return null;
}
private static List<AnAction> getEnabledChildren(@NotNull ActionGroup actionGroup,
@NotNull AnActionEvent e,
@NotNull Map<AnAction, Presentation> action2presentation) {
List<AnAction> result = new ArrayList<AnAction>();
AnAction[] actions = actionGroup.getChildren(e);
for (AnAction action : actions) {
if (action instanceof ActionGroup) {
if (isActionEnabledAndVisible(e, action2presentation, action)) {
result.addAll(getEnabledChildren((ActionGroup)action, e, action2presentation));
}
}
else if (!(action instanceof Separator)) {
if (isActionEnabledAndVisible(e, action2presentation, action)) {
result.add(action);
}
}
}
return result;
}
private static boolean isActionEnabledAndVisible(@NotNull final AnActionEvent e,
@NotNull final Map<AnAction, Presentation> action2presentation,
@NotNull final AnAction action) {
Presentation presentation = getPresentation(action, action2presentation);
AnActionEvent event = new AnActionEvent(e.getInputEvent(),
e.getDataContext(),
ActionPlaces.UNKNOWN,
presentation,
ActionManager.getInstance(),
e.getModifiers());
event.setInjectedContext(action.isInInjectedContext());
ActionUtil.performDumbAwareUpdate(action, event, false);
return presentation.isEnabled() && presentation.isVisible();
}
}
|
platform/platform-api/src/com/intellij/openapi/actionSystem/ActionGroupUtil.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.actionSystem;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ActionGroupUtil {
private static Presentation getPresentation(AnAction action, Map<AnAction, Presentation> action2presentation) {
Presentation presentation = action2presentation.get(action);
if (presentation == null) {
presentation = action.getTemplatePresentation().clone();
action2presentation.put(action, presentation);
}
return presentation;
}
public static boolean isGroupEmpty(@NotNull ActionGroup actionGroup, @NotNull AnActionEvent e) {
return isGroupEmpty(actionGroup, e, new HashMap<AnAction, Presentation>());
}
private static boolean isGroupEmpty(@NotNull ActionGroup actionGroup,
@NotNull AnActionEvent e,
@NotNull Map<AnAction, Presentation> action2presentation) {
AnAction[] actions = actionGroup.getChildren(e);
for (AnAction action : actions) {
if (action instanceof ActionGroup) {
if (!isGroupEmpty((ActionGroup)action, e, action2presentation)) {
return false;
}
}
else if (!(action instanceof Separator) && isActionEnabledAndVisible(e, action2presentation, action)) {
return false;
}
}
return true;
}
@Nullable
public static AnAction getSingleActiveAction(@NotNull ActionGroup actionGroup, @NotNull AnActionEvent e) {
List<AnAction> children = getEnabledChildren(actionGroup, e, new HashMap<AnAction, Presentation>());
if (children.size() == 1) {
return children.get(0);
}
return null;
}
private static List<AnAction> getEnabledChildren(@NotNull ActionGroup actionGroup,
@NotNull AnActionEvent e,
@NotNull Map<AnAction, Presentation> action2presentation) {
List<AnAction> result = new ArrayList<AnAction>();
AnAction[] actions = actionGroup.getChildren(e);
for (AnAction action : actions) {
if (action instanceof ActionGroup) {
if (isActionEnabledAndVisible(e, action2presentation, action)) {
result.addAll(getEnabledChildren((ActionGroup)action, e, action2presentation));
}
}
else if (!(action instanceof Separator)) {
if (isActionEnabledAndVisible(e, action2presentation, action)) {
result.add(action);
}
}
}
return result;
}
private static boolean isActionEnabledAndVisible(@NotNull final AnActionEvent e,
@NotNull final Map<AnAction, Presentation> action2presentation,
@NotNull final AnAction action) {
Presentation presentation = getPresentation(action, action2presentation);
AnActionEvent event = new AnActionEvent(e.getInputEvent(),
e.getDataContext(),
ActionPlaces.UNKNOWN,
presentation,
ActionManager.getInstance(),
e.getModifiers());
event.setInjectedContext(action.isInInjectedContext());
ActionUtil.performDumbAwareUpdate(action, event, false);
return presentation.isEnabled() && presentation.isVisible();
}
}
|
handle hidden groups correctly
|
platform/platform-api/src/com/intellij/openapi/actionSystem/ActionGroupUtil.java
|
handle hidden groups correctly
|
|
Java
|
apache-2.0
|
ec27ccf2826271cd1f4113e736df67802648b920
| 0
|
akosyakov/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,semonte/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,xfournet/intellij-community,apixandru/intellij-community,dslomov/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,caot/intellij-community,apixandru/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,fitermay/intellij-community,izonder/intellij-community,ryano144/intellij-community,samthor/intellij-community,amith01994/intellij-community,FHannes/intellij-community,da1z/intellij-community,fnouama/intellij-community,kool79/intellij-community,caot/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,da1z/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ibinti/intellij-community,kool79/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,jagguli/intellij-community,adedayo/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,amith01994/intellij-community,diorcety/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,petteyg/intellij-community,holmes/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,petteyg/intellij-community,hurricup/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,izonder/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,petteyg/intellij-community,robovm/robovm-studio,signed/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,ibinti/intellij-community,hurricup/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,semonte/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,diorcety/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,samthor/intellij-community,xfournet/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,amith01994/intellij-community,kool79/intellij-community,signed/intellij-community,semonte/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,FHannes/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,diorcety/intellij-community,kool79/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,caot/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,dslomov/intellij-community,fitermay/intellij-community,asedunov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,signed/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,amith01994/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ryano144/intellij-community,fnouama/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,fitermay/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,kool79/intellij-community,hurricup/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,wreckJ/intellij-community,semonte/intellij-community,clumsy/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,fitermay/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,signed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,caot/intellij-community,slisson/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,diorcety/intellij-community,FHannes/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,robovm/robovm-studio,allotria/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,signed/intellij-community,allotria/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,slisson/intellij-community,Lekanich/intellij-community,izonder/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,izonder/intellij-community,vvv1559/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,jagguli/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,slisson/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,petteyg/intellij-community,fnouama/intellij-community,kdwink/intellij-community,asedunov/intellij-community,samthor/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,allotria/intellij-community,akosyakov/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,diorcety/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,diorcety/intellij-community,jagguli/intellij-community,dslomov/intellij-community,samthor/intellij-community,diorcety/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,supersven/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,FHannes/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,izonder/intellij-community,samthor/intellij-community,ahb0327/intellij-community,da1z/intellij-community,ahb0327/intellij-community,signed/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,kool79/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,caot/intellij-community,slisson/intellij-community,supersven/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ryano144/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,caot/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,signed/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,amith01994/intellij-community,caot/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,izonder/intellij-community,supersven/intellij-community,da1z/intellij-community,vladmm/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,izonder/intellij-community,samthor/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,adedayo/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,jagguli/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,vladmm/intellij-community,vladmm/intellij-community,holmes/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,allotria/intellij-community,retomerz/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,petteyg/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,semonte/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,tmpgit/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,kdwink/intellij-community,asedunov/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,asedunov/intellij-community,signed/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,caot/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,da1z/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ibinti/intellij-community,hurricup/intellij-community,holmes/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,kool79/intellij-community,vladmm/intellij-community,caot/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,slisson/intellij-community,clumsy/intellij-community,asedunov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,dslomov/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,signed/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,apixandru/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,vladmm/intellij-community,izonder/intellij-community,semonte/intellij-community,slisson/intellij-community,da1z/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,signed/intellij-community,signed/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,supersven/intellij-community,slisson/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,da1z/intellij-community,blademainer/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ibinti/intellij-community
|
/*
* User: anna
* Date: 20-May-2008
*/
package com.intellij.coverage;
import com.intellij.CommonBundle;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.ClassUtil;
import com.intellij.rt.coverage.data.ProjectData;
import com.intellij.rt.coverage.util.ProjectDataLoader;
import com.intellij.util.PathUtil;
import jetbrains.coverage.report.ReportBuilderFactory;
import jetbrains.coverage.report.ReportGenerationFailedException;
import jetbrains.coverage.report.SourceCodeProvider;
import jetbrains.coverage.report.html.HTMLReportBuilder;
import jetbrains.coverage.report.idea.IDEACoverageData;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
public class IDEACoverageRunner extends CoverageRunner {
private static final Logger LOG = Logger.getInstance("#" + IDEACoverageRunner.class.getName());
public ProjectData loadCoverageData(final File sessionDataFile) {
return ProjectDataLoader.load(sessionDataFile);
}
public void appendCoverageArgument(final String sessionDataFilePath, final String[] patterns, final JavaParameters javaParameters,
final boolean collectLineInfo, final boolean isSampling) {
StringBuffer argument = new StringBuffer("-javaagent:");
argument.append(PathUtil.getJarPathForClass(ProjectData.class));
argument.append("=");
if (SystemInfo.isWindows) {
argument.append("\\\"").append(sessionDataFilePath).append("\\\"");
}
else {
argument.append(sessionDataFilePath);
}
argument.append(" ").append(String.valueOf(collectLineInfo));
argument.append(" ").append(Boolean.FALSE.toString()); //append unloaded
argument.append(" ").append(Boolean.FALSE.toString()); //merge with existing
argument.append(" ").append(String.valueOf(isSampling));
if (patterns != null && patterns.length > 0) {
argument.append(" ");
for (String coveragePattern : patterns) {
coveragePattern = coveragePattern.replace("$", "\\$").replace(".", "\\.").replaceAll("\\*", ".*");
if (!coveragePattern.endsWith(".*")) { //include inner classes
coveragePattern += "(\\$.*)*";
}
argument.append(coveragePattern).append(" ");
}
}
javaParameters.getVMParametersList().add(argument.toString());
}
@Override
public boolean isHTMLReportSupported() {
return true;
}
@Override
public void generateReport(final Project project, final String coverageDataFileName, final String outputDir, final boolean openInBrowser) {
ProgressManager.getInstance().run(new Task.Backgroundable(project, "Generating coverage report ...") {
final Exception[] myExceptions = new Exception[1];
public void run(@NotNull final ProgressIndicator indicator) {
try {
final HTMLReportBuilder builder = ReportBuilderFactory.createHTMLReportBuilder();
builder.setReportDir(new File(outputDir));
builder.generateReport(new IDEACoverageData(coverageDataFileName, new SourceCodeProvider() {
public String getSourceCode(@NotNull final String classname) throws IOException {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
final PsiClass psiClass = ClassUtil.findPsiClassByJVMName(PsiManager.getInstance(project), classname);
return psiClass != null ? psiClass.getContainingFile().getText() : "";
}
});
}
}));
}
catch (IOException e) {
LOG.error(e);
}
catch (ReportGenerationFailedException e) {
myExceptions[0] = e;
}
}
@Override
public void onSuccess() {
if (myExceptions[0] != null) {
Messages.showErrorDialog(project, myExceptions[0].getMessage(), CommonBundle.getErrorTitle());
return;
}
if (openInBrowser) BrowserUtil.launchBrowser(VfsUtil.pathToUrl(outputDir + "/index.html"));
}
});
}
public String getPresentableName() {
return "IDEA";
}
public String getId() {
return "idea";
}
public String getDataFileExtension() {
return "ic";
}
@Override
public boolean isCoverageByTestApplicable() {
return true;
}
}
|
plugins/coverage/src/com/intellij/coverage/IDEACoverageRunner.java
|
/*
* User: anna
* Date: 20-May-2008
*/
package com.intellij.coverage;
import com.intellij.CommonBundle;
import com.intellij.execution.configurations.JavaParameters;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.ClassUtil;
import com.intellij.rt.coverage.data.ProjectData;
import com.intellij.rt.coverage.util.ProjectDataLoader;
import com.intellij.util.PathUtil;
import jetbrains.coverage.report.ReportBuilderFactory;
import jetbrains.coverage.report.ReportGenerationFailedException;
import jetbrains.coverage.report.SourceCodeProvider;
import jetbrains.coverage.report.html.HTMLReportBuilder;
import jetbrains.coverage.report.idea.IDEACoverageData;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
public class IDEACoverageRunner extends CoverageRunner {
private static final Logger LOG = Logger.getInstance("#" + IDEACoverageRunner.class.getName());
public ProjectData loadCoverageData(final File sessionDataFile) {
return ProjectDataLoader.load(sessionDataFile);
}
public void appendCoverageArgument(final String sessionDataFilePath, final String[] patterns, final JavaParameters javaParameters,
final boolean collectLineInfo, final boolean isSampling) {
StringBuffer argument = new StringBuffer("-javaagent:");
argument.append(PathUtil.getJarPathForClass(ProjectData.class));
argument.append("=");
if (SystemInfo.isWindows) {
argument.append("\\\"").append(sessionDataFilePath).append("\\\"");
}
else {
argument.append(sessionDataFilePath);
}
argument.append(" ").append(String.valueOf(collectLineInfo));
argument.append(" ").append(Boolean.FALSE.toString()); //append unloaded
argument.append(" ").append(Boolean.FALSE.toString()); //merge with existing
argument.append(" ").append(String.valueOf(isSampling));
if (patterns != null && patterns.length > 0) {
argument.append(" ");
for (String coveragePattern : patterns) {
coveragePattern = coveragePattern.replace("$", "\\$").replace(".", "\\.").replaceAll("\\*", ".*");
if (!coveragePattern.endsWith(".*")) { //include inner classes
coveragePattern += "(\\$.*)*";
}
argument.append(coveragePattern).append(" ");
}
}
javaParameters.getVMParametersList().add(argument.toString());
}
@Override
public boolean isHTMLReportSupported() {
return true;
}
@Override
public void generateReport(final Project project, final String coverageDataFileName, final String outputDir, final boolean openInBrowser) {
ProgressManager.getInstance().run(new Task.Backgroundable(project, "Generating coverage report ...") {
final Exception[] myExceptions = new Exception[1];
@Override
public void run(@NotNull final ProgressIndicator indicator) {
try {
final HTMLReportBuilder builder = ReportBuilderFactory.createHTMLReportBuilder();
builder.setReportDir(new File(outputDir));
builder.generateReport(new IDEACoverageData(coverageDataFileName, new SourceCodeProvider() {
public String getSourceCode(@NotNull final String classname) throws IOException {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
final PsiClass psiClass = ClassUtil.findPsiClassByJVMName(PsiManager.getInstance(project), classname);
return psiClass != null ? psiClass.getContainingFile().getText() : "";
}
});
}
}));
}
catch (IOException e) {
LOG.error(e);
}
catch (ReportGenerationFailedException e) {
myExceptions[0] = e;
}
}
@Override
public void onSuccess() {
if (myExceptions[0] != null) {
Messages.showErrorDialog(project, myExceptions[0].getMessage(), CommonBundle.getErrorTitle());
return;
}
if (openInBrowser) BrowserUtil.launchBrowser(VfsUtil.pathToUrl(outputDir + "/index.html"));
}
});
}
public String getPresentableName() {
return "IDEA";
}
public String getId() {
return "idea";
}
public String getDataFileExtension() {
return "ic";
}
@Override
public boolean isCoverageByTestApplicable() {
return true;
}
}
|
fix compilation using jdk 1.5: remove @Override usages on methods implementing an interface method
|
plugins/coverage/src/com/intellij/coverage/IDEACoverageRunner.java
|
fix compilation using jdk 1.5: remove @Override usages on methods implementing an interface method
|
|
Java
|
apache-2.0
|
5071cd53f4b14ad67c024c2009253d8b60f3ddf8
| 0
|
jaehong-kim/pinpoint,sbcoba/pinpoint,eBaoTech/pinpoint,naver/pinpoint,gspandy/pinpoint,KimTaehee/pinpoint,lioolli/pinpoint,nstopkimsk/pinpoint,denzelsN/pinpoint,denzelsN/pinpoint,KimTaehee/pinpoint,krishnakanthpps/pinpoint,KRDeNaT/pinpoint,philipz/pinpoint,naver/pinpoint,hcapitaine/pinpoint,naver/pinpoint,shuvigoss/pinpoint,shuvigoss/pinpoint,KRDeNaT/pinpoint,hcapitaine/pinpoint,hcapitaine/pinpoint,wziyong/pinpoint,masonmei/pinpoint,majinkai/pinpoint,eBaoTech/pinpoint,coupang/pinpoint,dawidmalina/pinpoint,koo-taejin/pinpoint,Allive1/pinpoint,barneykim/pinpoint,barneykim/pinpoint,gspandy/pinpoint,breadval/pinpoint,philipz/pinpoint,sbcoba/pinpoint,masonmei/pinpoint,nstopkimsk/pinpoint,carpedm20/pinpoint,hcapitaine/pinpoint,sjmittal/pinpoint,nstopkimsk/pinpoint,denzelsN/pinpoint,KimTaehee/pinpoint,emeroad/pinpoint,andyspan/pinpoint,wziyong/pinpoint,cijung/pinpoint,minwoo-jung/pinpoint,barneykim/pinpoint,majinkai/pinpoint,denzelsN/pinpoint,Xylus/pinpoint,Xylus/pinpoint,hcapitaine/pinpoint,lioolli/pinpoint,Allive1/pinpoint,lioolli/pinpoint,Skkeem/pinpoint,wziyong/pinpoint,barneykim/pinpoint,sjmittal/pinpoint,tsyma/pinpoint,sjmittal/pinpoint,andyspan/pinpoint,andyspan/pinpoint,sbcoba/pinpoint,krishnakanthpps/pinpoint,nstopkimsk/pinpoint,Skkeem/pinpoint,suraj-raturi/pinpoint,krishnakanthpps/pinpoint,cijung/pinpoint,masonmei/pinpoint,jiaqifeng/pinpoint,sjmittal/pinpoint,cijung/pinpoint,eBaoTech/pinpoint,krishnakanthpps/pinpoint,gspandy/pinpoint,InfomediaLtd/pinpoint,emeroad/pinpoint,KRDeNaT/pinpoint,cijung/pinpoint,Skkeem/pinpoint,gspandy/pinpoint,suraj-raturi/pinpoint,Xylus/pinpoint,sjmittal/pinpoint,chenguoxi1985/pinpoint,dawidmalina/pinpoint,InfomediaLtd/pinpoint,breadval/pinpoint,PerfGeeks/pinpoint,breadval/pinpoint,cit-lab/pinpoint,citywander/pinpoint,Allive1/pinpoint,carpedm20/pinpoint,barneykim/pinpoint,eBaoTech/pinpoint,87439247/pinpoint,nstopkimsk/pinpoint,minwoo-jung/pinpoint,suraj-raturi/pinpoint,dawidmalina/pinpoint,masonmei/pinpoint,gspandy/pinpoint,andyspan/pinpoint,jaehong-kim/pinpoint,jiaqifeng/pinpoint,majinkai/pinpoint,chenguoxi1985/pinpoint,minwoo-jung/pinpoint,cijung/pinpoint,tsyma/pinpoint,carpedm20/pinpoint,nstopkimsk/pinpoint,Xylus/pinpoint,PerfGeeks/pinpoint,koo-taejin/pinpoint,wziyong/pinpoint,denzelsN/pinpoint,emeroad/pinpoint,citywander/pinpoint,jaehong-kim/pinpoint,suraj-raturi/pinpoint,breadval/pinpoint,87439247/pinpoint,dawidmalina/pinpoint,sbcoba/pinpoint,majinkai/pinpoint,87439247/pinpoint,jiaqifeng/pinpoint,jiaqifeng/pinpoint,emeroad/pinpoint,jiaqifeng/pinpoint,Allive1/pinpoint,wziyong/pinpoint,philipz/pinpoint,denzelsN/pinpoint,eBaoTech/pinpoint,InfomediaLtd/pinpoint,tsyma/pinpoint,shuvigoss/pinpoint,jaehong-kim/pinpoint,dawidmalina/pinpoint,Allive1/pinpoint,chenguoxi1985/pinpoint,emeroad/pinpoint,citywander/pinpoint,shuvigoss/pinpoint,wziyong/pinpoint,PerfGeeks/pinpoint,cit-lab/pinpoint,cit-lab/pinpoint,hcapitaine/pinpoint,chenguoxi1985/pinpoint,krishnakanthpps/pinpoint,KimTaehee/pinpoint,shuvigoss/pinpoint,breadval/pinpoint,tsyma/pinpoint,philipz/pinpoint,gspandy/pinpoint,coupang/pinpoint,naver/pinpoint,PerfGeeks/pinpoint,coupang/pinpoint,barneykim/pinpoint,InfomediaLtd/pinpoint,Allive1/pinpoint,citywander/pinpoint,majinkai/pinpoint,jaehong-kim/pinpoint,Skkeem/pinpoint,masonmei/pinpoint,lioolli/pinpoint,citywander/pinpoint,koo-taejin/pinpoint,suraj-raturi/pinpoint,KRDeNaT/pinpoint,sbcoba/pinpoint,chenguoxi1985/pinpoint,sbcoba/pinpoint,coupang/pinpoint,dawidmalina/pinpoint,philipz/pinpoint,Skkeem/pinpoint,cit-lab/pinpoint,minwoo-jung/pinpoint,majinkai/pinpoint,Skkeem/pinpoint,jiaqifeng/pinpoint,breadval/pinpoint,jaehong-kim/pinpoint,cit-lab/pinpoint,Xylus/pinpoint,KRDeNaT/pinpoint,minwoo-jung/pinpoint,shuvigoss/pinpoint,PerfGeeks/pinpoint,87439247/pinpoint,KimTaehee/pinpoint,InfomediaLtd/pinpoint,lioolli/pinpoint,tsyma/pinpoint,barneykim/pinpoint,KRDeNaT/pinpoint,masonmei/pinpoint,andyspan/pinpoint,InfomediaLtd/pinpoint,Xylus/pinpoint,citywander/pinpoint,koo-taejin/pinpoint,lioolli/pinpoint,sjmittal/pinpoint,denzelsN/pinpoint,eBaoTech/pinpoint,PerfGeeks/pinpoint,naver/pinpoint,krishnakanthpps/pinpoint,chenguoxi1985/pinpoint,tsyma/pinpoint,koo-taejin/pinpoint,koo-taejin/pinpoint,emeroad/pinpoint,cijung/pinpoint,87439247/pinpoint,carpedm20/pinpoint,minwoo-jung/pinpoint,Xylus/pinpoint,carpedm20/pinpoint,coupang/pinpoint,KimTaehee/pinpoint,cit-lab/pinpoint,87439247/pinpoint,coupang/pinpoint,andyspan/pinpoint,philipz/pinpoint,suraj-raturi/pinpoint
|
package com.nhn.pinpoint.profiler.context;
import com.nhn.pinpoint.common.AnnotationKey;
import com.nhn.pinpoint.common.ServiceType;
import com.nhn.pinpoint.common.util.ParsingResult;
import com.nhn.pinpoint.profiler.interceptor.MethodDescriptor;
import com.nhn.pinpoint.profiler.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* @author netspider
*/
public final class DefaultTrace implements Trace {
private static final Logger logger = LoggerFactory.getLogger(DefaultTrace.class.getName());
private static final boolean isDebug = logger.isDebugEnabled();
private static final boolean isTrace = logger.isTraceEnabled();
private short sequence;
private boolean sampling = true;
private CallStack callStack;
private Storage storage;
private TraceContext traceContext;
// use for calculating depth of each Span.
private int latestStackIndex = -1;
private StackFrame currentStackFrame;
public DefaultTrace(String agentId, long agentStartTime, long transactionId) {
TraceId traceId = new DefaultTraceId(agentId, agentStartTime, transactionId);
this.callStack = new CallStack(traceId);
latestStackIndex = this.callStack.push();
StackFrame stackFrame = createSpanStackFrame(ROOT_STACKID, callStack.getSpan());
this.callStack.setStackFrame(stackFrame);
this.currentStackFrame = stackFrame;
}
public DefaultTrace(TraceId continueTraceID) {
if (continueTraceID == null) {
throw new NullPointerException("continueTraceID must not be null");
}
this.callStack = new CallStack(continueTraceID);
latestStackIndex = this.callStack.push();
StackFrame stackFrame = createSpanStackFrame(ROOT_STACKID, callStack.getSpan());
this.callStack.setStackFrame(stackFrame);
this.currentStackFrame = stackFrame;
}
public CallStack getCallStack() {
return callStack;
}
public void setStorage(Storage storage) {
this.storage = storage;
}
public short getSequence() {
return sequence++;
}
public int getCallStackDepth() {
return this.callStack.getIndex();
}
@Override
public AsyncTrace createAsyncTrace() {
// 경우에 따라 별도 timeout 처리가 있어야 될수도 있음.
SpanEvent spanEvent = new SpanEvent(callStack.getSpan());
spanEvent.setSequence(getSequence());
DefaultAsyncTrace asyncTrace = new DefaultAsyncTrace(spanEvent);
// asyncTrace.setDataSender(this.getDataSender());
asyncTrace.setStorage(this.storage);
return asyncTrace;
}
private StackFrame createSpanEventStackFrame(int stackId) {
SpanEvent spanEvent = new SpanEvent(callStack.getSpan());
SpanEventStackFrame stackFrame = new SpanEventStackFrame(spanEvent);
stackFrame.setStackFrameId(stackId);
stackFrame.setSequence(getSequence());
return stackFrame;
}
private StackFrame createSpanStackFrame(int stackId, Span span) {
RootStackFrame stackFrame = new RootStackFrame(span);
stackFrame.setStackFrameId(stackId);
stackFrame.setSpan(span);
stackFrame.setStackFrameId(ROOT_STACKID);
return stackFrame;
}
@Override
public void traceBlockBegin() {
traceBlockBegin(NOCHECK_STACKID);
}
@Override
public void markBeforeTime() {
this.currentStackFrame.markBeforeTime();
}
@Override
public long getBeforeTime() {
return this.currentStackFrame.getBeforeTime();
}
@Override
public void markAfterTime() {
this.currentStackFrame.markAfterTime();
}
@Override
public long getAfterTime() {
return this.currentStackFrame.getAfterTime();
}
@Override
public void traceBlockBegin(final int stackId) {
final int currentStackIndex = callStack.push();
final StackFrame stackFrame = createSpanEventStackFrame(stackId);
if (latestStackIndex != currentStackIndex) {
latestStackIndex = currentStackIndex;
SpanEvent spanEvent = ((SpanEventStackFrame) stackFrame).getSpanEvent();
spanEvent.setDepth(latestStackIndex);
}
callStack.setStackFrame(stackFrame);
this.currentStackFrame = stackFrame;
}
@Override
public void traceRootBlockEnd() {
pop(ROOT_STACKID);
callStack.popRoot();
// 잘못된 stack 조작시 다음부터 그냥 nullPointerException이 발생할건데 괜찮은가?
this.currentStackFrame = null;
}
@Override
public void traceBlockEnd() {
traceBlockEnd(NOCHECK_STACKID);
}
@Override
public void traceBlockEnd(int stackId) {
pop(stackId);
StackFrame popStackFrame = callStack.pop();
// pop 할때 frame위치를 원복해야 한다.
this.currentStackFrame = popStackFrame;
}
private void pop(int stackId) {
final StackFrame currentStackFrame = this.currentStackFrame;
int stackFrameId = currentStackFrame.getStackFrameId();
if (stackFrameId != stackId) {
// 자체 stack dump를 하면 오류발견이 쉬울것으로 생각됨
if (logger.isWarnEnabled()) {
logger.warn("Corrupted CallStack found. StackId not matched. expected:{} current:{}", stackId, stackFrameId);
}
}
if (currentStackFrame instanceof RootStackFrame) {
logSpan(((RootStackFrame) currentStackFrame).getSpan());
} else {
logSpan(((SpanEventStackFrame) currentStackFrame).getSpanEvent());
}
}
public StackFrame getCurrentStackFrame() {
return callStack.getCurrentStackFrame();
}
/**
* Get current TraceID. If it was not set this will return null.
*
* @return
*/
@Override
public TraceId getTraceId() {
return callStack.getSpan().getTraceID();
}
public boolean canSampled() {
return this.sampling;
}
public void setSampling(boolean sampling) {
this.sampling = sampling;
}
void logSpan(SpanEvent spanEvent) {
if (isTrace) {
Thread th = Thread.currentThread();
logger.trace("[WRITE SpanEvent]" + spanEvent + ", Thread ID=" + th.getId() + " Name=" + th.getName());
}
this.storage.store(spanEvent);
}
void logSpan(Span span) {
if (isTrace) {
Thread th = Thread.currentThread();
logger.trace("[WRITE SPAN]" + span + ", Thread ID=" + th.getId() + " Name=" + th.getName());
}
this.storage.store(span);
}
@Override
public void recordException(Object result) {
if (result instanceof Throwable) {
Throwable th = (Throwable) result;
String drop = StringUtils.drop(th.getMessage(), 256);
recordAttribute(AnnotationKey.EXCEPTION, drop);
Span span = getCallStack().getSpan();
if (span.getException() == 0) {
span.setException(1);
}
}
}
@Override
public void recordApi(MethodDescriptor methodDescriptor) {
if (methodDescriptor == null) {
return;
}
if (methodDescriptor.getApiId() == 0) {
recordAttribute(AnnotationKey.API, methodDescriptor.getFullName());
} else {
recordAttribute(AnnotationKey.API_DID, methodDescriptor.getApiId());
}
}
@Override
public void recordApi(MethodDescriptor methodDescriptor, Object[] args) {
// API 저장 방법의 개선 필요.
recordApi(methodDescriptor);
recocordArgs(args);
}
@Override
public void recordApi(int apiId) {
recordAttribute(AnnotationKey.API_ID, apiId);
}
@Override
public void recordApi(int apiId, Object[] args) {
recordAttribute(AnnotationKey.API_ID, apiId);
recocordArgs(args);
}
private void recocordArgs(Object[] args) {
if (args != null) {
int min = Math.min(args.length, AnnotationKey.MAX_ARGS_SIZE);
for (int i = 0; i < min; i++) {
recordAttribute(AnnotationKey.getArgs(i), args[i]);
}
// TODO MAX 사이즈를 넘는건 마크만 해줘야 하나?
}
}
@Override
public void recordAttribute(final AnnotationKey key, final String value) {
recordAttribute(key, (Object) value);
}
@Override
public ParsingResult recordSqlInfo(String sql) {
if (sql == null) {
return null;
}
ParsingResult parsingResult = traceContext.parseSql(sql);
recordSqlParsingResult(parsingResult);
return parsingResult;
}
@Override
public void recordSqlParsingResult(ParsingResult parsingResult) {
if (parsingResult == null) {
return;
}
String sql = parsingResult.getSql();
recordAttribute(AnnotationKey.SQL_ID, sql.hashCode());
String output = parsingResult.getOutput();
if (output != null && output.length() != 0) {
recordAttribute(AnnotationKey.SQL_PARAM, output);
}
}
@Override
public void recordAttribute(final AnnotationKey key, final Object value) {
// TODO API 단일화 필요.
final StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.addAnnotation(new TraceAnnotation(key, value));
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.addAnnotation(new TraceAnnotation(key, value));
}
}
@Override
public void recordServiceType(final ServiceType serviceType) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setServiceType(serviceType);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setServiceType(serviceType);
}
}
@Override
public void recordRpcName(final String rpc) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setRpc(rpc);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setRpc(rpc);
}
}
@Override
public void recordDestinationId(final String destinationId) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof SpanEventStackFrame) {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setDestionationId(destinationId);
}
}
@Override
public void recordDestinationAddress(List<String> address) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof SpanEventStackFrame) {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setDestinationAddress();
}
}
@Override
public void recordDestinationAddressList(List<String> addressList) {
//To change body of created methods use File | Settings | File Templates.
}
@Override
public void recordEndPoint(final String endPoint) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setEndPoint(endPoint);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setEndPoint(endPoint);
}
}
@Override
public void recordRemoteAddr(final String remoteAddr) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setRemoteAddr(remoteAddr);
} else {
// do nothing.
}
}
@Override
public void recordNextSpanId(int spanId) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
logger.warn("OMG. Something's going wrong. Current stackframe is root Span. nextSpanId={}", spanId);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setNextSpanId(spanId);
}
}
private void annotate(final AnnotationKey key) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.addAnnotation(new TraceAnnotation(key));
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.addAnnotation(new TraceAnnotation(key));
}
}
@Override
public void setTraceContext(TraceContext traceContext) {
this.traceContext = traceContext;
}
@Override
public void recordParentApplication(String parentApplicationName, short parentApplicationType) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setParentApplicationName(parentApplicationName);
span.setParentApplicationType(parentApplicationType);
if (isDebug) {
logger.debug("ParentApplicationName marked. parentApplicationName={}", parentApplicationName);
}
} else {
// do nothing.
}
}
@Override
public void recordAcceptorHost(String host) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setAcceptorHost(host); // me
if (isDebug) {
logger.debug("Acceptor host received. host={}", host);
}
} else {
// do nothing.
}
}
@Override
public int getStackFrameId() {
return this.getCurrentStackFrame().getStackFrameId();
}
}
|
src/main/java/com/nhn/pinpoint/profiler/context/DefaultTrace.java
|
package com.nhn.pinpoint.profiler.context;
import com.nhn.pinpoint.common.AnnotationKey;
import com.nhn.pinpoint.common.ServiceType;
import com.nhn.pinpoint.common.util.ParsingResult;
import com.nhn.pinpoint.profiler.interceptor.MethodDescriptor;
import com.nhn.pinpoint.profiler.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* @author netspider
*/
public final class DefaultTrace implements Trace {
private static final Logger logger = LoggerFactory.getLogger(DefaultTrace.class.getName());
private static final boolean isDebug = logger.isDebugEnabled();
private static final boolean isTrace = logger.isTraceEnabled();
private short sequence;
private boolean sampling = true;
private CallStack callStack;
private Storage storage;
private TraceContext traceContext;
// use for calculating depth of each Span.
private int latestStackIndex = -1;
private StackFrame currentStackFrame;
public DefaultTrace(String agentId, long agentStartTime, long transactionId) {
TraceId traceId = new DefaultTraceId(agentId, agentStartTime, transactionId);
this.callStack = new CallStack(traceId);
latestStackIndex = this.callStack.push();
StackFrame stackFrame = createSpanStackFrame(ROOT_STACKID, callStack.getSpan());
this.callStack.setStackFrame(stackFrame);
this.currentStackFrame = stackFrame;
}
public DefaultTrace(TraceId continueTraceID) {
// this.root = continueRoot;
this.callStack = new CallStack(continueTraceID);
latestStackIndex = this.callStack.push();
StackFrame stackFrame = createSpanStackFrame(ROOT_STACKID, callStack.getSpan());
this.callStack.setStackFrame(stackFrame);
this.currentStackFrame = stackFrame;
}
public CallStack getCallStack() {
return callStack;
}
public void setStorage(Storage storage) {
this.storage = storage;
}
public short getSequence() {
return sequence++;
}
public int getCallStackDepth() {
return this.callStack.getIndex();
}
@Override
public AsyncTrace createAsyncTrace() {
// 경우에 따라 별도 timeout 처리가 있어야 될수도 있음.
SpanEvent spanEvent = new SpanEvent(callStack.getSpan());
spanEvent.setSequence(getSequence());
DefaultAsyncTrace asyncTrace = new DefaultAsyncTrace(spanEvent);
// asyncTrace.setDataSender(this.getDataSender());
asyncTrace.setStorage(this.storage);
return asyncTrace;
}
private StackFrame createSpanEventStackFrame(int stackId) {
SpanEvent spanEvent = new SpanEvent(callStack.getSpan());
SpanEventStackFrame stackFrame = new SpanEventStackFrame(spanEvent);
stackFrame.setStackFrameId(stackId);
stackFrame.setSequence(getSequence());
return stackFrame;
}
private StackFrame createSpanStackFrame(int stackId, Span span) {
RootStackFrame stackFrame = new RootStackFrame(span);
stackFrame.setStackFrameId(stackId);
stackFrame.setSpan(span);
stackFrame.setStackFrameId(ROOT_STACKID);
return stackFrame;
}
@Override
public void traceBlockBegin() {
traceBlockBegin(NOCHECK_STACKID);
}
@Override
public void markBeforeTime() {
this.currentStackFrame.markBeforeTime();
}
@Override
public long getBeforeTime() {
return this.currentStackFrame.getBeforeTime();
}
@Override
public void markAfterTime() {
this.currentStackFrame.markAfterTime();
}
@Override
public long getAfterTime() {
return this.currentStackFrame.getAfterTime();
}
@Override
public void traceBlockBegin(final int stackId) {
final int currentStackIndex = callStack.push();
final StackFrame stackFrame = createSpanEventStackFrame(stackId);
if (latestStackIndex != currentStackIndex) {
latestStackIndex = currentStackIndex;
SpanEvent spanEvent = ((SpanEventStackFrame) stackFrame).getSpanEvent();
spanEvent.setDepth(latestStackIndex);
}
callStack.setStackFrame(stackFrame);
this.currentStackFrame = stackFrame;
}
@Override
public void traceRootBlockEnd() {
pop(ROOT_STACKID);
callStack.popRoot();
// 잘못된 stack 조작시 다음부터 그냥 nullPointerException이 발생할건데 괜찮은가?
this.currentStackFrame = null;
}
@Override
public void traceBlockEnd() {
traceBlockEnd(NOCHECK_STACKID);
}
@Override
public void traceBlockEnd(int stackId) {
pop(stackId);
StackFrame popStackFrame = callStack.pop();
// pop 할때 frame위치를 원복해야 한다.
this.currentStackFrame = popStackFrame;
}
private void pop(int stackId) {
final StackFrame currentStackFrame = this.currentStackFrame;
int stackFrameId = currentStackFrame.getStackFrameId();
if (stackFrameId != stackId) {
// 자체 stack dump를 하면 오류발견이 쉬울것으로 생각됨
if (logger.isWarnEnabled()) {
logger.warn("Corrupted CallStack found. StackId not matched. expected:{} current:{}", stackId, stackFrameId);
}
}
if (currentStackFrame instanceof RootStackFrame) {
logSpan(((RootStackFrame) currentStackFrame).getSpan());
} else {
logSpan(((SpanEventStackFrame) currentStackFrame).getSpanEvent());
}
}
public StackFrame getCurrentStackFrame() {
return callStack.getCurrentStackFrame();
}
/**
* Get current TraceID. If it was not set this will return null.
*
* @return
*/
@Override
public TraceId getTraceId() {
return callStack.getSpan().getTraceID();
}
public boolean canSampled() {
return this.sampling;
}
public void setSampling(boolean sampling) {
this.sampling = sampling;
}
void logSpan(SpanEvent spanEvent) {
if (isTrace) {
Thread th = Thread.currentThread();
logger.trace("[WRITE SpanEvent]" + spanEvent + ", Thread ID=" + th.getId() + " Name=" + th.getName());
}
this.storage.store(spanEvent);
}
void logSpan(Span span) {
if (isTrace) {
Thread th = Thread.currentThread();
logger.trace("[WRITE SPAN]" + span + ", Thread ID=" + th.getId() + " Name=" + th.getName());
}
this.storage.store(span);
}
@Override
public void recordException(Object result) {
if (result instanceof Throwable) {
Throwable th = (Throwable) result;
String drop = StringUtils.drop(th.getMessage(), 256);
recordAttribute(AnnotationKey.EXCEPTION, drop);
Span span = getCallStack().getSpan();
if (span.getException() == 0) {
span.setException(1);
}
}
}
@Override
public void recordApi(MethodDescriptor methodDescriptor) {
if (methodDescriptor == null) {
return;
}
if (methodDescriptor.getApiId() == 0) {
recordAttribute(AnnotationKey.API, methodDescriptor.getFullName());
} else {
recordAttribute(AnnotationKey.API_DID, methodDescriptor.getApiId());
}
}
@Override
public void recordApi(MethodDescriptor methodDescriptor, Object[] args) {
// API 저장 방법의 개선 필요.
recordApi(methodDescriptor);
recocordArgs(args);
}
@Override
public void recordApi(int apiId) {
recordAttribute(AnnotationKey.API_ID, apiId);
}
@Override
public void recordApi(int apiId, Object[] args) {
recordAttribute(AnnotationKey.API_ID, apiId);
recocordArgs(args);
}
private void recocordArgs(Object[] args) {
if (args != null) {
int min = Math.min(args.length, AnnotationKey.MAX_ARGS_SIZE);
for (int i = 0; i < min; i++) {
recordAttribute(AnnotationKey.getArgs(i), args[i]);
}
// TODO MAX 사이즈를 넘는건 마크만 해줘야 하나?
}
}
@Override
public void recordAttribute(final AnnotationKey key, final String value) {
recordAttribute(key, (Object) value);
}
@Override
public ParsingResult recordSqlInfo(String sql) {
if (sql == null) {
return null;
}
ParsingResult parsingResult = traceContext.parseSql(sql);
recordSqlParsingResult(parsingResult);
return parsingResult;
}
@Override
public void recordSqlParsingResult(ParsingResult parsingResult) {
if (parsingResult == null) {
return;
}
String sql = parsingResult.getSql();
recordAttribute(AnnotationKey.SQL_ID, sql.hashCode());
String output = parsingResult.getOutput();
if (output != null && output.length() != 0) {
recordAttribute(AnnotationKey.SQL_PARAM, output);
}
}
@Override
public void recordAttribute(final AnnotationKey key, final Object value) {
// TODO API 단일화 필요.
final StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.addAnnotation(new TraceAnnotation(key, value));
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.addAnnotation(new TraceAnnotation(key, value));
}
}
@Override
public void recordServiceType(final ServiceType serviceType) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setServiceType(serviceType);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setServiceType(serviceType);
}
}
@Override
public void recordRpcName(final String rpc) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setRpc(rpc);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setRpc(rpc);
}
}
@Override
public void recordDestinationId(final String destinationId) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof SpanEventStackFrame) {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setDestionationId(destinationId);
}
}
@Override
public void recordDestinationAddress(List<String> address) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof SpanEventStackFrame) {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setDestinationAddress();
}
}
@Override
public void recordDestinationAddressList(List<String> addressList) {
//To change body of created methods use File | Settings | File Templates.
}
@Override
public void recordEndPoint(final String endPoint) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setEndPoint(endPoint);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setEndPoint(endPoint);
}
}
@Override
public void recordRemoteAddr(final String remoteAddr) {
// TODO API 단일화 필요.
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setRemoteAddr(remoteAddr);
} else {
// do nothing.
}
}
@Override
public void recordNextSpanId(int spanId) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
logger.warn("OMG. Something's going wrong. Current stackframe is root Span. nextSpanId={}", spanId);
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.setNextSpanId(spanId);
}
}
private void annotate(final AnnotationKey key) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.addAnnotation(new TraceAnnotation(key));
} else {
SpanEvent spanEvent = ((SpanEventStackFrame) currentStackFrame).getSpanEvent();
spanEvent.addAnnotation(new TraceAnnotation(key));
}
}
@Override
public void setTraceContext(TraceContext traceContext) {
this.traceContext = traceContext;
}
@Override
public void recordParentApplication(String parentApplicationName, short parentApplicationType) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setParentApplicationName(parentApplicationName);
span.setParentApplicationType(parentApplicationType);
if (isDebug) {
logger.debug("ParentApplicationName marked. parentApplicationName={}", parentApplicationName);
}
} else {
// do nothing.
}
}
@Override
public void recordAcceptorHost(String host) {
StackFrame currentStackFrame = this.currentStackFrame;
if (currentStackFrame instanceof RootStackFrame) {
Span span = ((RootStackFrame) currentStackFrame).getSpan();
span.setAcceptorHost(host); // me
if (isDebug) {
logger.debug("Acceptor host received. host={}", host);
}
} else {
// do nothing.
}
}
@Override
public int getStackFrameId() {
return this.getCurrentStackFrame().getStackFrameId();
}
}
|
[강운덕] [LUCYSUS-1744] 변경안된 부분이 있어 commit
git-svn-id: 0b0b9d2345dd6c69dda6a7bc6c9d6f99a5385c2e@2337 84d0f5b1-2673-498c-a247-62c4ff18d310
|
src/main/java/com/nhn/pinpoint/profiler/context/DefaultTrace.java
|
[강운덕] [LUCYSUS-1744] 변경안된 부분이 있어 commit
|
|
Java
|
apache-2.0
|
126d161f1f8ac8fe273c6cc001cd664fbf4ebbba
| 0
|
HelioGuilherme66/jitsi,ringdna/jitsi,laborautonomo/jitsi,laborautonomo/jitsi,ibauersachs/jitsi,ringdna/jitsi,procandi/jitsi,tuijldert/jitsi,laborautonomo/jitsi,laborautonomo/jitsi,dkcreinoso/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,bhatvv/jitsi,459below/jitsi,ibauersachs/jitsi,level7systems/jitsi,damencho/jitsi,pplatek/jitsi,damencho/jitsi,dkcreinoso/jitsi,HelioGuilherme66/jitsi,459below/jitsi,mckayclarey/jitsi,pplatek/jitsi,bebo/jitsi,martin7890/jitsi,pplatek/jitsi,ibauersachs/jitsi,pplatek/jitsi,jitsi/jitsi,jitsi/jitsi,procandi/jitsi,jitsi/jitsi,dkcreinoso/jitsi,level7systems/jitsi,iant-gmbh/jitsi,bhatvv/jitsi,procandi/jitsi,level7systems/jitsi,459below/jitsi,tuijldert/jitsi,Metaswitch/jitsi,mckayclarey/jitsi,procandi/jitsi,cobratbq/jitsi,bebo/jitsi,martin7890/jitsi,martin7890/jitsi,damencho/jitsi,iant-gmbh/jitsi,gpolitis/jitsi,jibaro/jitsi,cobratbq/jitsi,bebo/jitsi,bhatvv/jitsi,damencho/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,gpolitis/jitsi,mckayclarey/jitsi,iant-gmbh/jitsi,pplatek/jitsi,ringdna/jitsi,459below/jitsi,Metaswitch/jitsi,marclaporte/jitsi,ringdna/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,Metaswitch/jitsi,marclaporte/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,dkcreinoso/jitsi,damencho/jitsi,cobratbq/jitsi,459below/jitsi,bebo/jitsi,gpolitis/jitsi,marclaporte/jitsi,bebo/jitsi,jibaro/jitsi,laborautonomo/jitsi,cobratbq/jitsi,jitsi/jitsi,martin7890/jitsi,tuijldert/jitsi,jibaro/jitsi,jitsi/jitsi,mckayclarey/jitsi,ibauersachs/jitsi,jibaro/jitsi,bhatvv/jitsi,dkcreinoso/jitsi,martin7890/jitsi,gpolitis/jitsi,procandi/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,tuijldert/jitsi,mckayclarey/jitsi,ibauersachs/jitsi,ringdna/jitsi,Metaswitch/jitsi,bhatvv/jitsi,gpolitis/jitsi,tuijldert/jitsi,jibaro/jitsi
|
package net.java.sip.communicator.impl.protocol.icq;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.icqconstants.*;
import net.kano.joustsim.oscar.oscar.service.ssi.*;
/**
* The ICQ implementation of the service.protocol.Contact interface.
* @author Emil Ivov
*/
public class ContactIcqImpl
implements Contact
{
Buddy joustSimBuddy = null;
private boolean isLocal = false;
private byte[] image = null;
private PresenceStatus icqStatus = IcqStatusEnum.OFFLINE;
private ServerStoredContactListIcqImpl ssclCallback = null;
private boolean isPersistent = false;
private boolean isResolved = false;
private String nickName = null;
/**
* Creates an IcqContactImpl
* @param buddy the JoustSIM object that we will be encapsulating.
* @param ssclCallback a reference to the ServerStoredContactListIcqImpl
* instance that created us.
* @param isPersistent determines whether this contact is persistent or not.
* @param isResolved specifies whether the contact has been resolved against
* the server contact list
*/
ContactIcqImpl(Buddy buddy,
ServerStoredContactListIcqImpl ssclCallback,
boolean isPersistent,
boolean isResolved)
{
this.joustSimBuddy = buddy;
this.isLocal = isLocal;
this.ssclCallback = ssclCallback;
this.isPersistent = isPersistent;
this.isResolved = isResolved;
}
/**
* Returns the ICQ uin (or AIM screen name)of this contact
* @return the ICQ uin (or AIM screen name)of this contact
*/
public String getUIN()
{
return joustSimBuddy.getScreenname().getFormatted();
}
/**
* Returns the ICQ uin (or AIM screen name)of this contact
* @return the ICQ uin (or AIM screen name)of this contact
*/
public String getAddress(){
return getUIN();
}
/**
* Determines whether or not this Contact instance represents the user used
* by this protocol provider to connect to the service.
*
* @return true if this Contact represents us (the local user) and false
* otherwise.
*/
public boolean isLocal()
{
return isLocal;
}
public byte[] getImage()
{
return image;
}
/**
* Returns a hashCode for this contact. The returned hashcode is actually
* that of the Contact's UIN
* @return the hashcode of this Contact
*/
public int hashCode()
{
return getUIN().hashCode();
}
/**
* Indicates whether some other object is "equal to" this one.
* <p>
*
* @param obj the reference object with which to compare.
* @return <tt>true</tt> if this object is the same as the obj
* argument; <tt>false</tt> otherwise.
*/
public boolean equals(Object obj)
{
if (obj == null
|| !(obj instanceof ContactIcqImpl)
|| !(((ContactIcqImpl)obj).getAddress().equals(getAddress())
&& ((ContactIcqImpl)obj).getProtocolProvider()
== getProtocolProvider()))
return false;
return true;
}
/**
* Returns the joust sim buddy that this Contact is encapsulating.
* @return Buddy
*/
Buddy getJoustSimBuddy()
{
return joustSimBuddy;
}
/**
* Returns a string representation of this contact, containing most of its
* representative details.
*
* @return a string representation of this contact.
*/
public String toString()
{
StringBuffer buff = new StringBuffer("IcqContact[ uin=");
buff.append(getAddress()).append(", alias=")
.append(getJoustSimBuddy().getAlias()).append("]");
return buff.toString();
}
/**
* Changes the buddy encapsulated by this method to be <tt>newBuddy</tt>.
* This method is to be used _only_ when converting a non-persistent buddy
* into a normal one.
* @param newBuddy the new <tt>Buddy</tt> reference that this contact will
* encapsulate.
*/
void setJoustSimBuddy(Buddy newBuddy)
{
this.joustSimBuddy = newBuddy;
}
/**
* Sets the status that this contact is currently in. The method is to
* only be called as a result of a status update received from the AIM
* server.
*
* @param status the IcqStatusEnum that this contact is currently in.
*/
void updatePresenceStatus(PresenceStatus status)
{
this.icqStatus = status;
}
/**
* Returns the status of the contact as per the last status update we've
* received for it. Note that this method is not to perform any network
* operations and will simply return the status received in the last
* status update message. If you want a reliable way of retrieving someone's
* status, you should use the <tt>queryContactStatus()</tt> method in
* <tt>OperationSetPresence</tt>.
* @return the PresenceStatus that we've received in the last status update
* pertaining to this contact.
*/
public PresenceStatus getPresenceStatus()
{
return icqStatus;
}
/**
* Returns a String that could be used by any user interacting modules for
* referring to this contact. An alias is not necessarily unique but is
* often more human readable than an address (or id).
* @return a String that can be used for referring to this contact when
* interacting with the user.
*/
public String getDisplayName()
{
String alias = joustSimBuddy.getAlias();
if(alias != null)
return alias;
else if (nickName != null)
return nickName;
else
{
// if there is no alias we put this contact
// for future update, as we may be not registered yet
ssclCallback.addContactForUpdate(this);
return getUIN();
}
}
/**
* Used to set the nickname of the contact if it is update
* in the ContactList
*
* @param nickname String the value
*/
protected void setNickname(String nickname)
{
this.nickName = nickname;
}
/**
* Returns a reference to the contact group that this contact is currently
* a child of or null if the underlying protocol does not suppord persistent
* presence.
* @return a reference to the contact group that this contact is currently
* a child of or null if the underlying protocol does not suppord persistent
* presence.
*/
public ContactGroup getParentContactGroup()
{
return ssclCallback.findContactGroup(this);
}
/**
* Returns a reference to the protocol provider that created the contact.
* @return a refererence to an instance of the ProtocolProviderService
*/
public ProtocolProviderService getProtocolProvider()
{
return ssclCallback.getParentProvider();
}
/**
* Determines whether or not this contact is being stored by the server.
* Non persistent contacts are common in the case of simple, non-persistent
* presence operation sets. They could however also be seen in persistent
* presence operation sets when for example we have received an event
* from someone not on our contact list. Non persistent contacts are
* volatile even when coming from a persistent presence op. set. They would
* only exist until the application is closed and will not be there next
* time it is loaded.
* @return true if the contact is persistent and false otherwise.
*/
public boolean isPersistent()
{
return isPersistent;
}
/**
* Specifies whether this contact is to be considered persistent or not. The
* method is to be used _only_ when a non-persistent contact has been added
* to the contact list and its encapsulated VolatileBuddy has been repalced
* with a standard joustsim buddy.
* @param persistent true if the buddy is to be considered persistent and
* false for volatile.
*/
void setPersistent(boolean persistent)
{
this.isPersistent = persistent;
}
/**
* Specifies whether this contact has been resolved, or in other words that
* its presence in the server stored contact list has been confirmed.
* Unresolved contacts are created by services which need to quickly obtain
* a reference to the contact corresponding to a specific address possibly
* even before logging on the net.
* @param resolved true if the buddy is resolved against the server stored
* contact list and false otherwise.
*/
void setResolved(boolean resolved)
{
this.isResolved = resolved;
}
/**
* Returns the persistent data - for now only the nickname is needed
* for restoring the contact data. Fields are properties separated by ;
* <p>
* @return the persistent data
*/
public String getPersistentData()
{
// to store data only when nick is set
if(nickName != null)
return "nickname=" + nickName + ";";
else
return null;
}
/**
* Determines whether or not this contact has been resolved against the
* server. Unresolved contacts are used when initially loading a contact
* list that has been stored in a local file until the presence operation
* set has managed to retrieve all the contact list from the server and has
* properly mapped contacts to their on-line buddies.
* @return true if the contact has been resolved (mapped against a buddy)
* and false otherwise.
*/
public boolean isResolved()
{
return isResolved;
}
public void setPersistentData(String persistentData)
{
if(persistentData == null)
{
return;
}
StringTokenizer dataToks = new StringTokenizer(persistentData, ";");
while(dataToks.hasMoreTokens())
{
String data[] = dataToks.nextToken().split("=");
if(data[0].equals("nickname"))
{
nickName = data[1];
}
}
}
}
|
src/net/java/sip/communicator/impl/protocol/icq/ContactIcqImpl.java
|
package net.java.sip.communicator.impl.protocol.icq;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.icqconstants.*;
import net.kano.joustsim.oscar.oscar.service.ssi.*;
/**
* The ICQ implementation of the service.protocol.Contact interface.
* @author Emil Ivov
*/
public class ContactIcqImpl
implements Contact
{
Buddy joustSimBuddy = null;
private boolean isLocal = false;
private byte[] image = null;
private PresenceStatus icqStatus = IcqStatusEnum.OFFLINE;
private ServerStoredContactListIcqImpl ssclCallback = null;
private boolean isPersistent = false;
private boolean isResolved = false;
private String nickName = null;
/**
* Creates an IcqContactImpl
* @param buddy the JoustSIM object that we will be encapsulating.
* @param ssclCallback a reference to the ServerStoredContactListIcqImpl
* instance that created us.
* @param isPersistent determines whether this contact is persistent or not.
* @param isResolved specifies whether the contact has been resolved against
* the server contact list
*/
ContactIcqImpl(Buddy buddy,
ServerStoredContactListIcqImpl ssclCallback,
boolean isPersistent,
boolean isResolved)
{
this.joustSimBuddy = buddy;
this.isLocal = isLocal;
this.ssclCallback = ssclCallback;
this.isPersistent = isPersistent;
this.isResolved = isResolved;
}
/**
* Returns the ICQ uin (or AIM screen name)of this contact
* @return the ICQ uin (or AIM screen name)of this contact
*/
public String getUIN()
{
return joustSimBuddy.getScreenname().getFormatted();
}
/**
* Returns the ICQ uin (or AIM screen name)of this contact
* @return the ICQ uin (or AIM screen name)of this contact
*/
public String getAddress(){
return getUIN();
}
/**
* Determines whether or not this Contact instance represents the user used
* by this protocol provider to connect to the service.
*
* @return true if this Contact represents us (the local user) and false
* otherwise.
*/
public boolean isLocal()
{
return isLocal;
}
public byte[] getImage()
{
return image;
}
/**
* Returns a hashCode for this contact. The returned hashcode is actually
* that of the Contact's UIN
* @return the hashcode of this Contact
*/
public int hashCode()
{
return getUIN().hashCode();
}
/**
* Indicates whether some other object is "equal to" this one.
* <p>
*
* @param obj the reference object with which to compare.
* @return <tt>true</tt> if this object is the same as the obj
* argument; <tt>false</tt> otherwise.
*/
public boolean equals(Object obj)
{
if (obj == null
|| !(obj instanceof ContactIcqImpl)
|| !((ContactIcqImpl)obj).getUIN().equals(getUIN()))
return false;
return true;
}
/**
* Returns the joust sim buddy that this Contact is encapsulating.
* @return Buddy
*/
Buddy getJoustSimBuddy()
{
return joustSimBuddy;
}
/**
* Returns a string representation of this contact, containing most of its
* representative details.
*
* @return a string representation of this contact.
*/
public String toString()
{
StringBuffer buff = new StringBuffer("IcqContact[ uin=");
buff.append(getAddress()).append(", alias=")
.append(getJoustSimBuddy().getAlias()).append("]");
return buff.toString();
}
/**
* Changes the buddy encapsulated by this method to be <tt>newBuddy</tt>.
* This method is to be used _only_ when converting a non-persistent buddy
* into a normal one.
* @param newBuddy the new <tt>Buddy</tt> reference that this contact will
* encapsulate.
*/
void setJoustSimBuddy(Buddy newBuddy)
{
this.joustSimBuddy = newBuddy;
}
/**
* Sets the status that this contact is currently in. The method is to
* only be called as a result of a status update received from the AIM
* server.
*
* @param status the IcqStatusEnum that this contact is currently in.
*/
void updatePresenceStatus(PresenceStatus status)
{
this.icqStatus = status;
}
/**
* Returns the status of the contact as per the last status update we've
* received for it. Note that this method is not to perform any network
* operations and will simply return the status received in the last
* status update message. If you want a reliable way of retrieving someone's
* status, you should use the <tt>queryContactStatus()</tt> method in
* <tt>OperationSetPresence</tt>.
* @return the PresenceStatus that we've received in the last status update
* pertaining to this contact.
*/
public PresenceStatus getPresenceStatus()
{
return icqStatus;
}
/**
* Returns a String that could be used by any user interacting modules for
* referring to this contact. An alias is not necessarily unique but is
* often more human readable than an address (or id).
* @return a String that can be used for referring to this contact when
* interacting with the user.
*/
public String getDisplayName()
{
String alias = joustSimBuddy.getAlias();
if(alias != null)
return alias;
else if (nickName != null)
return nickName;
else
{
// if there is no alias we put this contact
// for future update, as we may be not registered yet
ssclCallback.addContactForUpdate(this);
return getUIN();
}
}
/**
* Used to set the nickname of the contact if it is update
* in the ContactList
*
* @param nickname String the value
*/
protected void setNickname(String nickname)
{
this.nickName = nickname;
}
/**
* Returns a reference to the contact group that this contact is currently
* a child of or null if the underlying protocol does not suppord persistent
* presence.
* @return a reference to the contact group that this contact is currently
* a child of or null if the underlying protocol does not suppord persistent
* presence.
*/
public ContactGroup getParentContactGroup()
{
return ssclCallback.findContactGroup(this);
}
/**
* Returns a reference to the protocol provider that created the contact.
* @return a refererence to an instance of the ProtocolProviderService
*/
public ProtocolProviderService getProtocolProvider()
{
return ssclCallback.getParentProvider();
}
/**
* Determines whether or not this contact is being stored by the server.
* Non persistent contacts are common in the case of simple, non-persistent
* presence operation sets. They could however also be seen in persistent
* presence operation sets when for example we have received an event
* from someone not on our contact list. Non persistent contacts are
* volatile even when coming from a persistent presence op. set. They would
* only exist until the application is closed and will not be there next
* time it is loaded.
* @return true if the contact is persistent and false otherwise.
*/
public boolean isPersistent()
{
return isPersistent;
}
/**
* Specifies whether this contact is to be considered persistent or not. The
* method is to be used _only_ when a non-persistent contact has been added
* to the contact list and its encapsulated VolatileBuddy has been repalced
* with a standard joustsim buddy.
* @param persistent true if the buddy is to be considered persistent and
* false for volatile.
*/
void setPersistent(boolean persistent)
{
this.isPersistent = persistent;
}
/**
* Specifies whether this contact has been resolved, or in other words that
* its presence in the server stored contact list has been confirmed.
* Unresolved contacts are created by services which need to quickly obtain
* a reference to the contact corresponding to a specific address possibly
* even before logging on the net.
* @param resolved true if the buddy is resolved against the server stored
* contact list and false otherwise.
*/
void setResolved(boolean resolved)
{
this.isResolved = resolved;
}
/**
* Returns the persistent data - for now only the nickname is needed
* for restoring the contact data. Fields are properties separated by ;
* <p>
* @return the persistent data
*/
public String getPersistentData()
{
// to store data only when nick is set
if(nickName != null)
return "nickname=" + nickName + ";";
else
return null;
}
/**
* Determines whether or not this contact has been resolved against the
* server. Unresolved contacts are used when initially loading a contact
* list that has been stored in a local file until the presence operation
* set has managed to retrieve all the contact list from the server and has
* properly mapped contacts to their on-line buddies.
* @return true if the contact has been resolved (mapped against a buddy)
* and false otherwise.
*/
public boolean isResolved()
{
return isResolved;
}
public void setPersistentData(String persistentData)
{
if(persistentData == null)
{
return;
}
StringTokenizer dataToks = new StringTokenizer(persistentData, ";");
while(dataToks.hasMoreTokens())
{
String data[] = dataToks.nextToken().split("=");
if(data[0].equals("nickname"))
{
nickName = data[1];
}
}
}
}
|
Working on the JMF implementation of the media service.
more sophisticated equals method
|
src/net/java/sip/communicator/impl/protocol/icq/ContactIcqImpl.java
|
Working on the JMF implementation of the media service.
|
|
Java
|
apache-2.0
|
35b4cc1e48f3ad4f46b058300821f69bea9f5687
| 0
|
salguarnieri/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,blademainer/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,slisson/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,kool79/intellij-community,asedunov/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,retomerz/intellij-community,izonder/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,caot/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,caot/intellij-community,apixandru/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ryano144/intellij-community,xfournet/intellij-community,signed/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,signed/intellij-community,vvv1559/intellij-community,consulo/consulo,orekyuu/intellij-community,petteyg/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,ryano144/intellij-community,hurricup/intellij-community,da1z/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,allotria/intellij-community,dslomov/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,samthor/intellij-community,clumsy/intellij-community,FHannes/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fitermay/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,slisson/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,gnuhub/intellij-community,signed/intellij-community,petteyg/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,vladmm/intellij-community,da1z/intellij-community,caot/intellij-community,ahb0327/intellij-community,allotria/intellij-community,signed/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,caot/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,supersven/intellij-community,petteyg/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,dslomov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,izonder/intellij-community,kool79/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,semonte/intellij-community,wreckJ/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,samthor/intellij-community,signed/intellij-community,ryano144/intellij-community,amith01994/intellij-community,fnouama/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,caot/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,signed/intellij-community,supersven/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,signed/intellij-community,samthor/intellij-community,robovm/robovm-studio,petteyg/intellij-community,holmes/intellij-community,semonte/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,ernestp/consulo,TangHao1987/intellij-community,kool79/intellij-community,retomerz/intellij-community,caot/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,izonder/intellij-community,ernestp/consulo,mglukhikh/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,jagguli/intellij-community,semonte/intellij-community,FHannes/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ernestp/consulo,blademainer/intellij-community,lucafavatella/intellij-community,caot/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,semonte/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,robovm/robovm-studio,asedunov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,slisson/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,diorcety/intellij-community,robovm/robovm-studio,apixandru/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,dslomov/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,petteyg/intellij-community,caot/intellij-community,signed/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,consulo/consulo,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,izonder/intellij-community,petteyg/intellij-community,holmes/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,xfournet/intellij-community,kdwink/intellij-community,kool79/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,fnouama/intellij-community,clumsy/intellij-community,holmes/intellij-community,da1z/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,fnouama/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,fnouama/intellij-community,da1z/intellij-community,allotria/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,allotria/intellij-community,vvv1559/intellij-community,kool79/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,diorcety/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,amith01994/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,jagguli/intellij-community,robovm/robovm-studio,supersven/intellij-community,semonte/intellij-community,supersven/intellij-community,kdwink/intellij-community,kool79/intellij-community,ibinti/intellij-community,FHannes/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,amith01994/intellij-community,consulo/consulo,apixandru/intellij-community,blademainer/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,izonder/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,da1z/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,izonder/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,vladmm/intellij-community,blademainer/intellij-community,ryano144/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,semonte/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,fitermay/intellij-community,hurricup/intellij-community,caot/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,izonder/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,signed/intellij-community,apixandru/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,consulo/consulo,TangHao1987/intellij-community,fitermay/intellij-community,signed/intellij-community,caot/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,da1z/intellij-community,samthor/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,fitermay/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,blademainer/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,da1z/intellij-community,holmes/intellij-community,supersven/intellij-community,dslomov/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,slisson/intellij-community,da1z/intellij-community,asedunov/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,vladmm/intellij-community,allotria/intellij-community,ibinti/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,hurricup/intellij-community,semonte/intellij-community,kool79/intellij-community,asedunov/intellij-community,fnouama/intellij-community,samthor/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,signed/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vladmm/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,samthor/intellij-community,youdonghai/intellij-community,holmes/intellij-community,supersven/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community
|
package org.jetbrains.jps.incremental;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.concurrency.BoundedTaskExecutor;
import com.intellij.util.containers.ConcurrentHashSet;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.MultiMapBasedOnSet;
import com.intellij.util.io.MappingFailedException;
import com.intellij.util.io.PersistentEnumerator;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.ProjectPaths;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.api.GlobalOptions;
import org.jetbrains.jps.api.RequestFuture;
import org.jetbrains.jps.builders.*;
import org.jetbrains.jps.builders.impl.BuildTargetChunk;
import org.jetbrains.jps.builders.java.JavaBuilderUtil;
import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType;
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor;
import org.jetbrains.jps.builders.java.dependencyView.Callbacks;
import org.jetbrains.jps.builders.storage.SourceToOutputMapping;
import org.jetbrains.jps.cmdline.BuildRunner;
import org.jetbrains.jps.cmdline.ProjectDescriptor;
import org.jetbrains.jps.incremental.fs.BuildFSState;
import org.jetbrains.jps.incremental.java.ExternalJavacDescriptor;
import org.jetbrains.jps.incremental.java.JavaBuilder;
import org.jetbrains.jps.incremental.messages.*;
import org.jetbrains.jps.incremental.storage.*;
import org.jetbrains.jps.model.java.JpsJavaExtensionService;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration;
import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile;
import org.jetbrains.jps.service.SharedThreadPool;
import org.jetbrains.jps.util.JpsPathUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author Eugene Zhuravlev
* Date: 9/17/11
*/
public class IncProjectBuilder {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.IncProjectBuilder");
public static final String BUILD_NAME = "EXTERNAL BUILD";
private static final String CLASSPATH_INDEX_FINE_NAME = "classpath.index";
private static final boolean GENERATE_CLASSPATH_INDEX = Boolean.parseBoolean(System.getProperty(GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION, "false"));
private static final int MAX_BUILDER_THREADS;
static {
int maxThreads = 4;
try {
maxThreads = Math.max(2, Integer.parseInt(System.getProperty(GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION, "4")));
}
catch (NumberFormatException ignored) {
}
MAX_BUILDER_THREADS = maxThreads;
}
private final BoundedTaskExecutor myParallelBuildExecutor = new BoundedTaskExecutor(SharedThreadPool.getInstance(), Math.min(MAX_BUILDER_THREADS, Math.max(2, Runtime.getRuntime().availableProcessors())));
private final ProjectDescriptor myProjectDescriptor;
private final BuilderRegistry myBuilderRegistry;
private final Map<String, String> myBuilderParams;
private final CanceledStatus myCancelStatus;
@Nullable private final Callbacks.ConstantAffectionResolver myConstantSearch;
private final List<MessageHandler> myMessageHandlers = new ArrayList<MessageHandler>();
private final MessageHandler myMessageDispatcher = new MessageHandler() {
public void processMessage(BuildMessage msg) {
for (MessageHandler h : myMessageHandlers) {
h.processMessage(msg);
}
}
};
private volatile float myTargetsProcessed = 0.0f;
private final float myTotalTargetsWork;
private final int myTotalModuleLevelBuilderCount;
private final List<Future> myAsyncTasks = new ArrayList<Future>();
public IncProjectBuilder(ProjectDescriptor pd, BuilderRegistry builderRegistry, Map<String, String> builderParams, CanceledStatus cs,
@Nullable Callbacks.ConstantAffectionResolver constantSearch) {
myProjectDescriptor = pd;
myBuilderRegistry = builderRegistry;
myBuilderParams = builderParams;
myCancelStatus = cs;
myConstantSearch = constantSearch;
myTotalTargetsWork = pd.getBuildTargetIndex().getAllTargets().size();
myTotalModuleLevelBuilderCount = builderRegistry.getModuleLevelBuilderCount();
}
public void addMessageHandler(MessageHandler handler) {
myMessageHandlers.add(handler);
}
public void build(CompileScope scope, final boolean isMake, final boolean isProjectRebuild, boolean forceCleanCaches)
throws RebuildRequestedException {
final LowMemoryWatcher memWatcher = LowMemoryWatcher.register(new Runnable() {
@Override
public void run() {
myProjectDescriptor.dataManager.flush(false);
myProjectDescriptor.timestamps.getStorage().force();
}
});
CompileContextImpl context = null;
try {
context = createContext(scope, isMake, isProjectRebuild);
runBuild(context, forceCleanCaches);
myProjectDescriptor.dataManager.saveVersion();
}
catch (ProjectBuildException e) {
final Throwable cause = e.getCause();
if (cause instanceof PersistentEnumerator.CorruptedException ||
cause instanceof MappingFailedException ||
cause instanceof IOException) {
myMessageDispatcher.processMessage(new CompilerMessage(
BUILD_NAME, BuildMessage.Kind.INFO,
"Internal caches are corrupted or have outdated format, forcing project rebuild: " +
e.getMessage())
);
throw new RebuildRequestedException(cause);
}
else {
if (cause == null) {
final String msg = e.getMessage();
if (!StringUtil.isEmpty(msg)) {
myMessageDispatcher.processMessage(new ProgressMessage(msg));
}
}
else {
myMessageDispatcher.processMessage(new CompilerMessage(BUILD_NAME, cause));
}
}
}
finally {
memWatcher.stop();
flushContext(context);
// wait for the async tasks
for (Future task : myAsyncTasks) {
try {
task.get();
}
catch (Throwable th) {
LOG.info(th);
}
}
}
}
private static void flushContext(CompileContext context) {
if (context != null) {
final ProjectDescriptor pd = context.getProjectDescriptor();
pd.timestamps.getStorage().force();
pd.dataManager.flush(false);
}
final ExternalJavacDescriptor descriptor = ExternalJavacDescriptor.KEY.get(context);
if (descriptor != null) {
try {
final RequestFuture future = descriptor.client.sendShutdownRequest();
future.waitFor(500L, TimeUnit.MILLISECONDS);
}
finally {
// ensure process is not running
descriptor.process.destroyProcess();
}
ExternalJavacDescriptor.KEY.set(context, null);
}
//cleanupJavacNameTable();
}
private static boolean ourClenupFailed = false;
private static void cleanupJavacNameTable() {
try {
if (JavaBuilder.USE_EMBEDDED_JAVAC && !ourClenupFailed) {
final Field freelistField = Class.forName("com.sun.tools.javac.util.Name$Table").getDeclaredField("freelist");
freelistField.setAccessible(true);
freelistField.set(null, com.sun.tools.javac.util.List.nil());
}
}
catch (Throwable e) {
ourClenupFailed = true;
//LOG.info(e);
}
}
private void runBuild(CompileContextImpl context, boolean forceCleanCaches) throws ProjectBuildException {
context.setDone(0.0f);
LOG.info("Building project; isRebuild:" + context.isProjectRebuild() + "; isMake:" + context.isMake() + " parallel compilation:" + BuildRunner.PARALLEL_BUILD_ENABLED);
for (TargetBuilder builder : myBuilderRegistry.getTargetBuilders()) {
builder.buildStarted(context);
}
for (ModuleLevelBuilder builder : myBuilderRegistry.getModuleLevelBuilders()) {
builder.buildStarted(context);
}
try {
if (context.isProjectRebuild() || forceCleanCaches) {
cleanOutputRoots(context);
}
context.processMessage(new ProgressMessage("Running 'before' tasks"));
runTasks(context, myBuilderRegistry.getBeforeTasks());
context.processMessage(new ProgressMessage("Checking sources"));
buildChunks(context);
context.processMessage(new ProgressMessage("Running 'after' tasks"));
runTasks(context, myBuilderRegistry.getAfterTasks());
// cleanup output roots layout, commented for efficiency
//final ModuleOutputRootsLayout outputRootsLayout = context.getDataManager().getOutputRootsLayout();
//try {
// final Iterator<String> keysIterator = outputRootsLayout.getKeysIterator();
// final Map<String, JpsModule> modules = myProjectDescriptor.project.getModules();
// while (keysIterator.hasNext()) {
// final String moduleName = keysIterator.next();
// if (modules.containsKey(moduleName)) {
// outputRootsLayout.remove(moduleName);
// }
// }
//}
//catch (IOException e) {
// throw new ProjectBuildException(e);
//}
}
finally {
for (TargetBuilder builder : myBuilderRegistry.getTargetBuilders()) {
builder.buildFinished(context);
}
for (ModuleLevelBuilder builder : myBuilderRegistry.getModuleLevelBuilders()) {
builder.buildFinished(context);
}
context.processMessage(new ProgressMessage("Finished, saving caches..."));
}
}
private CompileContextImpl createContext(CompileScope scope, boolean isMake, final boolean isProjectRebuild) throws ProjectBuildException {
final CompileContextImpl context = new CompileContextImpl(scope, myProjectDescriptor, isMake, isProjectRebuild, myMessageDispatcher,
myBuilderParams, myCancelStatus
);
JavaBuilderUtil.CONSTANT_SEARCH_SERVICE.set(context, myConstantSearch);
return context;
}
private void cleanOutputRoots(CompileContext context) throws ProjectBuildException {
// whole project is affected
ProjectDescriptor projectDescriptor = context.getProjectDescriptor();
JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(projectDescriptor.getProject());
final boolean shouldClear = configuration.isClearOutputDirectoryOnRebuild();
try {
if (shouldClear) {
clearOutputs(context);
}
else {
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets()) {
clearOutputFiles(context, target);
}
}
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning output files", e);
}
try {
projectDescriptor.timestamps.getStorage().clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning timestamps storage", e);
}
try {
projectDescriptor.dataManager.clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning compiler storages", e);
}
myProjectDescriptor.fsState.clearAll();
}
public static void clearOutputFiles(CompileContext context, BuildTarget<?> target) throws IOException {
final SourceToOutputMapping map = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target);
for (String srcPath : map.getSources()) {
final Collection<String> outs = map.getOutputs(srcPath);
if (outs != null && !outs.isEmpty()) {
for (String out : outs) {
new File(out).delete();
}
context.processMessage(new FileDeletedEvent(outs));
}
}
}
private void clearOutputs(CompileContext context) throws ProjectBuildException, IOException {
final MultiMap<File, BuildTarget<?>> rootsToDelete = new MultiMapBasedOnSet<File,BuildTarget<?>>();
final Set<File> allSourceRoots = new HashSet<File>();
final ProjectPaths paths = context.getProjectPaths();
ProjectDescriptor projectDescriptor = context.getProjectDescriptor();
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets()) {
File outputDir = target.getOutputDir(projectDescriptor.dataManager.getDataPaths());
if (outputDir != null) {
rootsToDelete.putValue(outputDir, target);
}
}
for (BuildTargetType<?> type : JavaModuleBuildTargetType.ALL_TYPES) {
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets(type)) {
for (BuildRootDescriptor descriptor : projectDescriptor.getBuildRootIndex().getTargetRoots(target, context)) {
allSourceRoots.add(descriptor.getRootFile());
}
}
}
// check that output and source roots are not overlapping
final List<File> filesToDelete = new ArrayList<File>();
for (Map.Entry<File, Collection<BuildTarget<?>>> entry : rootsToDelete.entrySet()) {
context.checkCanceled();
boolean okToDelete = true;
final File outputRoot = entry.getKey();
if (JpsPathUtil.isUnder(allSourceRoots, outputRoot)) {
okToDelete = false;
}
else {
final Set<File> _outRoot = Collections.singleton(outputRoot);
for (File srcRoot : allSourceRoots) {
if (JpsPathUtil.isUnder(_outRoot, srcRoot)) {
okToDelete = false;
break;
}
}
}
if (okToDelete) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = outputRoot.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
}
else {
context.processMessage(new CompilerMessage(BUILD_NAME, BuildMessage.Kind.WARNING, "Output path " + outputRoot.getPath() + " intersects with a source root. The output cannot be cleaned."));
// clean only those files we are aware of
for (BuildTarget<?> target : entry.getValue()) {
clearOutputFiles(context, target);
}
}
}
final Set<File> annotationOutputs = new HashSet<File>(); // separate collection because no root intersection checks needed for annotation generated sources
for (JavaModuleBuildTargetType type : JavaModuleBuildTargetType.ALL_TYPES) {
for (ModuleBuildTarget target : projectDescriptor.getBuildTargetIndex().getAllTargets(type)) {
final ProcessorConfigProfile profile = context.getAnnotationProcessingProfile(target.getModule());
if (profile.isEnabled()) {
File annotationOut = paths.getAnnotationProcessorGeneratedSourcesOutputDir(target.getModule(), target.isTests(), profile.getGeneratedSourcesDirectoryName());
if (annotationOut != null) {
annotationOutputs.add(annotationOut);
}
}
}
}
for (File annotationOutput : annotationOutputs) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = annotationOutput.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
}
context.processMessage(new ProgressMessage("Cleaning output directories..."));
myAsyncTasks.add(
FileUtil.asyncDelete(filesToDelete)
);
}
private static void runTasks(CompileContext context, final List<BuildTask> tasks) throws ProjectBuildException {
for (BuildTask task : tasks) {
task.build(context);
}
}
private void buildChunks(final CompileContextImpl context) throws ProjectBuildException {
final CompileScope scope = context.getScope();
final ProjectDescriptor pd = context.getProjectDescriptor();
BuildTargetIndex targetIndex = pd.getBuildTargetIndex();
try {
if (BuildRunner.PARALLEL_BUILD_ENABLED) {
final List<ChunkGroup> chunkGroups = buildChunkGroups(targetIndex);
for (ChunkGroup group : chunkGroups) {
final List<BuildTargetChunk> groupChunks = group.getChunks();
final int chunkCount = groupChunks.size();
if (chunkCount == 0) {
continue;
}
try {
if (chunkCount == 1) {
buildChunkIfAffected(createContextWrapper(context), scope, groupChunks.iterator().next());
}
else {
final CountDownLatch latch = new CountDownLatch(chunkCount);
final Ref<Throwable> exRef = new Ref<Throwable>(null);
if (LOG.isDebugEnabled()) {
final StringBuilder logBuilder = new StringBuilder("Building chunks in parallel: ");
for (BuildTargetChunk chunk : groupChunks) {
logBuilder.append(chunk.toString()).append("; ");
}
LOG.debug(logBuilder.toString());
}
for (final BuildTargetChunk chunk : groupChunks) {
final CompileContext chunkLocalContext = createContextWrapper(context);
myParallelBuildExecutor.execute(new Runnable() {
@Override
public void run() {
try {
buildChunkIfAffected(chunkLocalContext, scope, chunk);
}
catch (Throwable e) {
synchronized (exRef) {
if (exRef.isNull()) {
exRef.set(e);
}
}
LOG.info(e);
}
finally {
latch.countDown();
}
}
});
}
try {
latch.await();
}
catch (InterruptedException e) {
LOG.info(e);
}
final Throwable exception = exRef.get();
if (exception != null) {
if (exception instanceof ProjectBuildException) {
throw (ProjectBuildException)exception;
}
else {
throw new ProjectBuildException(exception);
}
}
}
}
finally {
pd.dataManager.closeSourceToOutputStorages(groupChunks);
pd.dataManager.flush(true);
}
}
}
else {
// non-parallel build
for (BuildTargetChunk chunk : targetIndex.getSortedTargetChunks()) {
try {
buildChunkIfAffected(context, scope, chunk);
}
finally {
pd.dataManager.closeSourceToOutputStorages(Collections.singleton(chunk));
pd.dataManager.flush(true);
}
}
}
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
private void buildChunkIfAffected(CompileContext context, CompileScope scope, BuildTargetChunk chunk) throws ProjectBuildException {
if (isAffected(scope, chunk)) {
buildTargetsChunk(context, chunk);
}
else {
updateDoneFraction(context, chunk.getTargets().size());
}
}
private static boolean isAffected(CompileScope scope, BuildTargetChunk chunk) {
for (BuildTarget<?> target : chunk.getTargets()) {
if (scope.isAffected(target)) {
return true;
}
}
return false;
}
private boolean runBuildersForChunk(CompileContext context, final BuildTargetChunk chunk) throws ProjectBuildException {
Set<? extends BuildTarget<?>> targets = chunk.getTargets();
if (targets.size() > 1) {
Set<ModuleBuildTarget> moduleTargets = new HashSet<ModuleBuildTarget>();
for (BuildTarget<?> target : targets) {
if (target instanceof ModuleBuildTarget) {
moduleTargets.add((ModuleBuildTarget)target);
}
else {
context.processMessage(new CompilerMessage(BUILD_NAME, BuildMessage.Kind.ERROR, "Cannot build " + target.getPresentableName() + " because it is included into a circular dependency"));
return false;
}
}
return runModuleLevelBuilders(context, new ModuleChunk(moduleTargets));
}
BuildTarget<?> target = targets.iterator().next();
if (target instanceof ModuleBuildTarget) {
ModuleBuildTarget moduleBuildTarget = (ModuleBuildTarget)target;
return runModuleLevelBuilders(context, new ModuleChunk(Collections.singleton(moduleBuildTarget)));
}
else {
try {
return runTargetBuilders(target, context);
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
}
private boolean runTargetBuilders(BuildTarget<?> target, CompileContext context) throws ProjectBuildException, IOException {
List<TargetBuilder<?,?>> builders = BuilderRegistry.getInstance().getTargetBuilders();
for (TargetBuilder<?,?> builder : builders) {
buildTarget(target, context, builder);
updateDoneFraction(context, 1.0f / builders.size());
}
return true;
}
private void updateDoneFraction(CompileContext context, final float delta) {
myTargetsProcessed += delta;
float processed = myTargetsProcessed;
context.setDone(processed / myTotalTargetsWork);
}
private static <R extends BuildRootDescriptor, T extends BuildTarget<R>> void buildTarget(final T target, final CompileContext context, TargetBuilder<?,?> builder)
throws ProjectBuildException, IOException {
if (builder.getTargetTypes().contains(target.getTargetType())) {
DirtyFilesHolder<R, T> holder = new DirtyFilesHolder<R, T>() {
@Override
public void processDirtyFiles(@NotNull FileProcessor<R, T> processor) throws IOException {
context.getProjectDescriptor().fsState.processFilesToRecompile(context, target, processor);
}
};
//noinspection unchecked
((TargetBuilder<R,T>)builder).build(target, context, holder);
context.checkCanceled();
}
}
private void buildTargetsChunk(CompileContext context, final BuildTargetChunk chunk) throws ProjectBuildException {
boolean doneSomething = false;
try {
Utils.ERRORS_DETECTED_KEY.set(context, Boolean.FALSE);
ensureFSStateInitialized(context, chunk);
if (context.isMake()) {
processDeletedPaths(context, chunk.getTargets());
doneSomething |= Utils.hasRemovedSources(context);
}
myProjectDescriptor.fsState.beforeChunkBuildStart(context, chunk);
doneSomething = runBuildersForChunk(context, chunk);
}
catch (ProjectBuildException e) {
throw e;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
try {
onChunkBuildComplete(context, chunk);
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
for (BuildRootDescriptor rd : context.getProjectDescriptor().getBuildRootIndex().clearTempRoots(context)) {
context.getProjectDescriptor().fsState.clearRecompile(rd);
}
try {
// restore deleted paths that were not procesesd by 'integrate'
final Map<BuildTarget<?>, Collection<String>> map = Utils.REMOVED_SOURCES_KEY.get(context);
if (map != null) {
for (Map.Entry<BuildTarget<?>, Collection<String>> entry : map.entrySet()) {
final BuildTarget<?> target = entry.getKey();
final Collection<String> paths = entry.getValue();
if (paths != null) {
for (String path : paths) {
myProjectDescriptor.fsState.registerDeleted(target, new File(path), null);
}
}
}
}
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
Utils.REMOVED_SOURCES_KEY.set(context, null);
if (doneSomething && GENERATE_CLASSPATH_INDEX) {
final Future<?> future = SharedThreadPool.getInstance().executeOnPooledThread(new Runnable() {
@Override
public void run() {
createClasspathIndex(chunk);
}
});
myAsyncTasks.add(future);
}
}
}
}
private static void createClasspathIndex(final BuildTargetChunk chunk) {
final Set<File> outputDirs = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY);
for (BuildTarget<?> target : chunk.getTargets()) {
if (target instanceof ModuleBuildTarget) {
File outputDir = ((ModuleBuildTarget)target).getOutputDir();
if (outputDir != null && outputDirs.add(outputDir)) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputDir, CLASSPATH_INDEX_FINE_NAME)));
try {
writeIndex(writer, outputDir, "");
}
finally {
writer.close();
}
}
catch (IOException e) {
// Ignore. Failed to create optional classpath index
}
}
}
}
}
private static void writeIndex(final BufferedWriter writer, final File file, final String path) throws IOException {
writer.write(path);
writer.write('\n');
final File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
final String _path = path.isEmpty() ? child.getName() : path + "/" + child.getName();
writeIndex(writer, child, _path);
}
}
}
private void processDeletedPaths(CompileContext context, final Set<? extends BuildTarget<?>> targets) throws ProjectBuildException {
try {
// cleanup outputs
final Map<BuildTarget<?>, Collection<String>> removedSources = new HashMap<BuildTarget<?>, Collection<String>>();
for (BuildTarget<?> target : targets) {
final Collection<String> deletedPaths = myProjectDescriptor.fsState.getAndClearDeletedPaths(target);
if (deletedPaths.isEmpty()) {
continue;
}
removedSources.put(target, deletedPaths);
final SourceToOutputMapping sourceToOutputStorage = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target);
// actually delete outputs associated with removed paths
for (String deletedSource : deletedPaths) {
// deleting outputs corresponding to non-existing source
final Collection<String> outputs = sourceToOutputStorage.getOutputs(deletedSource);
if (outputs != null && !outputs.isEmpty()) {
final ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger();
if (logger.isEnabled()) {
logger.logDeletedFiles(outputs);
}
for (String output : outputs) {
new File(output).delete();
}
context.processMessage(new FileDeletedEvent(outputs));
}
if (target instanceof ModuleBuildTarget) {
// check if deleted source was associated with a form
final SourceToFormMapping sourceToFormMap = context.getProjectDescriptor().dataManager.getSourceToFormMap();
final String formPath = sourceToFormMap.getState(deletedSource);
if (formPath != null) {
final File formFile = new File(formPath);
if (formFile.exists()) {
FSOperations.markDirty(context, formFile);
}
sourceToFormMap.remove(deletedSource);
}
}
}
}
if (!removedSources.isEmpty()) {
final Map<BuildTarget<?>, Collection<String>> existing = Utils.REMOVED_SOURCES_KEY.get(context);
if (existing != null) {
for (Map.Entry<BuildTarget<?>, Collection<String>> entry : existing.entrySet()) {
final Collection<String> paths = removedSources.get(entry.getKey());
if (paths != null) {
paths.addAll(entry.getValue());
}
else {
removedSources.put(entry.getKey(), entry.getValue());
}
}
}
Utils.REMOVED_SOURCES_KEY.set(context, removedSources);
}
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
// return true if changed something, false otherwise
private boolean runModuleLevelBuilders(final CompileContext context, final ModuleChunk chunk) throws ProjectBuildException {
boolean doneSomething = false;
boolean rebuildFromScratchRequested = false;
float stageCount = myTotalModuleLevelBuilderCount;
final int modulesInChunk = chunk.getModules().size();
int buildersPassed = 0;
boolean nextPassRequired;
try {
do {
nextPassRequired = false;
myProjectDescriptor.fsState.beforeNextRoundStart(context, chunk);
DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder = new DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>() {
@Override
public void processDirtyFiles(@NotNull FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget> processor) throws IOException {
FSOperations.processFilesToRecompile(context, chunk, processor);
}
};
if (!context.isProjectRebuild()) {
deleteOutputsOfDirtyFiles(context, dirtyFilesHolder);
}
BUILDER_CATEGORY_LOOP:
for (BuilderCategory category : BuilderCategory.values()) {
final List<ModuleLevelBuilder> builders = myBuilderRegistry.getBuilders(category);
if (builders.isEmpty()) {
continue;
}
for (ModuleLevelBuilder builder : builders) {
if (context.isMake()) {
processDeletedPaths(context, chunk.getTargets());
}
final ModuleLevelBuilder.ExitCode buildResult = builder.build(context, chunk, dirtyFilesHolder);
doneSomething |= (buildResult != ModuleLevelBuilder.ExitCode.NOTHING_DONE);
if (buildResult == ModuleLevelBuilder.ExitCode.ABORT) {
throw new ProjectBuildException("Builder " + builder.getDescription() + " requested build stop");
}
context.checkCanceled();
if (buildResult == ModuleLevelBuilder.ExitCode.ADDITIONAL_PASS_REQUIRED) {
if (!nextPassRequired) {
// recalculate basis
myTargetsProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount += myTotalModuleLevelBuilderCount;
myTargetsProcessed += (buildersPassed * modulesInChunk) / stageCount;
}
nextPassRequired = true;
}
else if (buildResult == ModuleLevelBuilder.ExitCode.CHUNK_REBUILD_REQUIRED) {
if (!rebuildFromScratchRequested && !context.isProjectRebuild()) {
LOG.info("Builder " + builder.getDescription() + " requested rebuild of module chunk " + chunk.getName());
// allow rebuild from scratch only once per chunk
rebuildFromScratchRequested = true;
try {
// forcibly mark all files in the chunk dirty
FSOperations.markDirty(context, chunk);
// reverting to the beginning
myTargetsProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount = myTotalModuleLevelBuilderCount;
buildersPassed = 0;
nextPassRequired = true;
break BUILDER_CATEGORY_LOOP;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
else {
LOG.debug("Builder " + builder.getDescription() + " requested second chunk rebuild");
}
}
buildersPassed++;
updateDoneFraction(context, modulesInChunk / (stageCount));
}
}
}
while (nextPassRequired);
}
finally {
for (BuilderCategory category : BuilderCategory.values()) {
for (ModuleLevelBuilder builder : myBuilderRegistry.getBuilders(category)) {
builder.cleanupChunkResources(context);
}
}
}
return doneSomething;
}
private static <R extends BuildRootDescriptor,T extends BuildTarget<R>>
void deleteOutputsOfDirtyFiles(final CompileContext context, DirtyFilesHolder<R, T> dirtyFilesHolder) throws ProjectBuildException {
final BuildDataManager dataManager = context.getProjectDescriptor().dataManager;
try {
ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger();
final Collection<String> outputsToLog = logger.isEnabled() ? new LinkedList<String>() : null;
dirtyFilesHolder.processDirtyFiles(new FileProcessor<R, T>() {
private final Map<T, SourceToOutputMapping> storageMap = new HashMap<T, SourceToOutputMapping>();
@Override
public boolean apply(T target, File file, R sourceRoot) throws IOException {
SourceToOutputMapping srcToOut = storageMap.get(target);
if (srcToOut == null) {
srcToOut = dataManager.getSourceToOutputMap(target);
storageMap.put(target, srcToOut);
}
final String srcPath = FileUtil.toSystemIndependentName(file.getPath());
final Collection<String> outputs = srcToOut.getOutputs(srcPath);
if (outputs != null) {
for (String output : outputs) {
if (outputsToLog != null) {
outputsToLog.add(output);
}
new File(output).delete();
}
if (!outputs.isEmpty()) {
context.processMessage(new FileDeletedEvent(outputs));
}
srcToOut.setOutputs(srcPath, Collections.<String>emptyList());
}
return true;
}
});
if (outputsToLog != null && context.isMake()) {
logger.logDeletedFiles(outputsToLog);
}
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
private static List<ChunkGroup> buildChunkGroups(BuildTargetIndex index) {
final List<BuildTargetChunk> allChunks = index.getSortedTargetChunks();
// building aux dependencies map
final Map<BuildTarget<?>, Set<BuildTarget<?>>> depsMap = new HashMap<BuildTarget<?>, Set<BuildTarget<?>>>();
for (BuildTarget target : index.getAllTargets()) {
depsMap.put(target, index.getDependenciesRecursively(target));
}
final List<ChunkGroup> groups = new ArrayList<ChunkGroup>();
ChunkGroup currentGroup = new ChunkGroup();
groups.add(currentGroup);
for (BuildTargetChunk chunk : allChunks) {
if (dependsOnGroup(chunk, currentGroup, depsMap)) {
currentGroup = new ChunkGroup();
groups.add(currentGroup);
}
currentGroup.addChunk(chunk);
}
return groups;
}
private static boolean dependsOnGroup(BuildTargetChunk chunk, ChunkGroup group, Map<BuildTarget<?>, Set<BuildTarget<?>>> depsMap) {
for (BuildTargetChunk groupChunk : group.getChunks()) {
final Set<? extends BuildTarget<?>> groupChunkTargets = groupChunk.getTargets();
for (BuildTarget<?> target : chunk.getTargets()) {
if (ContainerUtil.intersects(depsMap.get(target), groupChunkTargets)) {
return true;
}
}
}
return false;
}
private static void onChunkBuildComplete(CompileContext context, @NotNull BuildTargetChunk chunk) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final BuildFSState fsState = pd.fsState;
fsState.clearContextRoundData(context);
fsState.clearContextChunk(context);
if (!Utils.errorsDetected(context) && !context.getCancelStatus().isCanceled()) {
boolean marked = false;
for (BuildTarget<?> target : chunk.getTargets()) {
if (context.isMake() && target instanceof ModuleBuildTarget) {
// ensure non-incremental flag cleared
context.clearNonIncrementalMark((ModuleBuildTarget)target);
}
if (context.isProjectRebuild()) {
fsState.markInitialScanPerformed(target);
}
final Timestamps timestamps = pd.timestamps.getStorage();
for (BuildRootDescriptor rd : pd.getBuildRootIndex().getTargetRoots(target, context)) {
marked |= fsState.markAllUpToDate(context, rd, timestamps);
}
}
if (marked) {
context.processMessage(UptoDateFilesSavedEvent.INSTANCE);
}
}
}
private static void ensureFSStateInitialized(CompileContext context, BuildTargetChunk chunk) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final Timestamps timestamps = pd.timestamps.getStorage();
for (BuildTarget<?> target : chunk.getTargets()) {
final BuildTargetConfiguration configuration = pd.getTargetsState().getTargetConfiguration(target);
if (target instanceof ModuleBuildTarget) {
ensureFSStateInitialized(context, pd, timestamps, configuration, (ModuleBuildTarget)target);
}
else {
ensureFSStateInitialized(context, target);
}
}
}
private static void ensureFSStateInitialized(CompileContext context, BuildTarget<?> target) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final Timestamps timestamps = pd.timestamps.getStorage();
final BuildTargetConfiguration configuration = pd.getTargetsState().getTargetConfiguration(target);
if (context.isProjectRebuild() || configuration.isTargetDirty() || context.getScope().isRecompilationForced(target)) {
FSOperations.markDirtyFiles(context, target, timestamps, true, null, Collections.<File>emptySet());
configuration.save();
}
else if (context.isMake()) {
if (pd.fsState.markInitialScanPerformed(target)) {
FSOperations.markDirtyFiles(context, target, timestamps, false, null, Collections.<File>emptySet());
}
}
}
private static void ensureFSStateInitialized(CompileContext context,
ProjectDescriptor pd,
Timestamps timestamps,
BuildTargetConfiguration configuration, ModuleBuildTarget target) throws IOException {
if (context.isProjectRebuild() || configuration.isTargetDirty()) {
FSOperations.markDirtyFiles(context, target, timestamps, true, null);
updateOutputRootsLayout(context, target);
configuration.save();
}
else {
if (context.isMake()) {
if (pd.fsState.markInitialScanPerformed(target)) {
boolean forceMarkDirty = false;
final File currentOutput = target.getOutputDir();
if (currentOutput != null) {
final Pair<String, String> outputsPair = pd.dataManager.getOutputRootsLayout().getState(target.getModuleName());
if (outputsPair != null) {
final String previousPath = target.isTests() ? outputsPair.second : outputsPair.first;
forceMarkDirty = StringUtil.isEmpty(previousPath) || !FileUtil.filesEqual(currentOutput, new File(previousPath));
}
else {
forceMarkDirty = true;
}
}
initModuleFSState(context, target, forceMarkDirty);
}
}
else {
// forced compilation mode
if (context.getScope().isRecompilationForced(target)) {
initModuleFSState(context, target, true);
}
}
}
}
private static void initModuleFSState(CompileContext context, ModuleBuildTarget target, final boolean forceMarkDirty) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final Timestamps timestamps = pd.timestamps.getStorage();
final THashSet<File> currentFiles = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY);
FSOperations.markDirtyFiles(context, target, timestamps, forceMarkDirty, currentFiles);
// handle deleted paths
final BuildFSState fsState = pd.fsState;
fsState.clearDeletedPaths(target);
final SourceToOutputMapping sourceToOutputMap = pd.dataManager.getSourceToOutputMap(target);
for (final Iterator<String> it = sourceToOutputMap.getSourcesIterator(); it.hasNext();) {
final String path = it.next();
// can check if the file exists
final File file = new File(path);
if (!currentFiles.contains(file)) {
fsState.registerDeleted(target, file, timestamps);
}
}
updateOutputRootsLayout(context, target);
}
private static void updateOutputRootsLayout(CompileContext context, ModuleBuildTarget target) throws IOException {
final File currentOutput = target.getOutputDir();
if (currentOutput == null) {
return;
}
final ModuleOutputRootsLayout outputRootsLayout = context.getProjectDescriptor().dataManager.getOutputRootsLayout();
Pair<String, String> outputsPair = outputRootsLayout.getState(target.getModuleName());
// update data
final String productionPath;
final String testPath;
if (target.isTests()) {
productionPath = outputsPair != null? outputsPair.first : "";
testPath = FileUtil.toSystemIndependentName(currentOutput.getPath());
}
else {
productionPath = FileUtil.toSystemIndependentName(currentOutput.getPath());
testPath = outputsPair != null? outputsPair.second : "";
}
outputRootsLayout.update(target.getModuleName(), Pair.create(productionPath, testPath));
}
private static class ChunkGroup {
private final List<BuildTargetChunk> myChunks = new ArrayList<BuildTargetChunk>();
public void addChunk(BuildTargetChunk chunk) {
myChunks.add(chunk);
}
public List<BuildTargetChunk> getChunks() {
return myChunks;
}
}
private static final Set<Key> GLOBAL_CONTEXT_KEYS = new HashSet<Key>();
static {
// keys for data that must be visible to all threads
GLOBAL_CONTEXT_KEYS.add(ExternalJavacDescriptor.KEY);
}
private static CompileContext createContextWrapper(final CompileContext delegate) {
final ClassLoader loader = delegate.getClass().getClassLoader();
final UserDataHolderBase localDataHolder = new UserDataHolderBase();
final Set deletedKeysSet = new ConcurrentHashSet();
final Class<UserDataHolder> dataHolderinterface = UserDataHolder.class;
final Class<MessageHandler> messageHandlerinterface = MessageHandler.class;
return (CompileContext)Proxy.newProxyInstance(loader, new Class[] {CompileContext.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final Class<?> declaringClass = method.getDeclaringClass();
if (dataHolderinterface.equals(declaringClass)) {
final Object firstArgument = args[0];
final boolean isGlobalContextKey = firstArgument instanceof Key && GLOBAL_CONTEXT_KEYS.contains((Key)firstArgument);
if (!isGlobalContextKey) {
final boolean isWriteOperation = args.length == 2 /*&& void.class.equals(method.getReturnType())*/;
if (isWriteOperation) {
if (args[1] == null) {
deletedKeysSet.add(firstArgument);
}
else {
deletedKeysSet.remove(firstArgument);
}
}
else {
if (deletedKeysSet.contains(firstArgument)) {
return null;
}
}
final Object result = method.invoke(localDataHolder, args);
if (isWriteOperation || result != null) {
return result;
}
}
}
else if (messageHandlerinterface.equals(declaringClass)) {
final BuildMessage msg = (BuildMessage)args[0];
if (msg.getKind() == BuildMessage.Kind.ERROR) {
Utils.ERRORS_DETECTED_KEY.set(localDataHolder, Boolean.TRUE);
}
}
try {
return method.invoke(delegate, args);
}
catch (InvocationTargetException e) {
final Throwable targetEx = e.getTargetException();
if (targetEx instanceof ProjectBuildException) {
throw targetEx;
}
throw e;
}
}
});
}
}
|
jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
|
package org.jetbrains.jps.incremental;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.concurrency.BoundedTaskExecutor;
import com.intellij.util.containers.ConcurrentHashSet;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.MultiMapBasedOnSet;
import com.intellij.util.io.MappingFailedException;
import com.intellij.util.io.PersistentEnumerator;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.ProjectPaths;
import org.jetbrains.jps.api.CanceledStatus;
import org.jetbrains.jps.api.GlobalOptions;
import org.jetbrains.jps.api.RequestFuture;
import org.jetbrains.jps.builders.*;
import org.jetbrains.jps.builders.impl.BuildTargetChunk;
import org.jetbrains.jps.builders.java.JavaBuilderUtil;
import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType;
import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor;
import org.jetbrains.jps.builders.java.dependencyView.Callbacks;
import org.jetbrains.jps.builders.storage.SourceToOutputMapping;
import org.jetbrains.jps.cmdline.BuildRunner;
import org.jetbrains.jps.cmdline.ProjectDescriptor;
import org.jetbrains.jps.incremental.fs.BuildFSState;
import org.jetbrains.jps.incremental.java.ExternalJavacDescriptor;
import org.jetbrains.jps.incremental.java.JavaBuilder;
import org.jetbrains.jps.incremental.messages.*;
import org.jetbrains.jps.incremental.storage.*;
import org.jetbrains.jps.model.java.JpsJavaExtensionService;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration;
import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile;
import org.jetbrains.jps.service.SharedThreadPool;
import org.jetbrains.jps.util.JpsPathUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author Eugene Zhuravlev
* Date: 9/17/11
*/
public class IncProjectBuilder {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.IncProjectBuilder");
public static final String BUILD_NAME = "EXTERNAL BUILD";
private static final String CLASSPATH_INDEX_FINE_NAME = "classpath.index";
private static final boolean GENERATE_CLASSPATH_INDEX = Boolean.parseBoolean(System.getProperty(GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION, "false"));
private static final int MAX_BUILDER_THREADS;
static {
int maxThreads = 4;
try {
maxThreads = Math.max(2, Integer.parseInt(System.getProperty(GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION, "4")));
}
catch (NumberFormatException ignored) {
}
MAX_BUILDER_THREADS = maxThreads;
}
private final BoundedTaskExecutor myParallelBuildExecutor = new BoundedTaskExecutor(SharedThreadPool.getInstance(), Math.min(MAX_BUILDER_THREADS, Math.max(2, Runtime.getRuntime().availableProcessors())));
private final ProjectDescriptor myProjectDescriptor;
private final BuilderRegistry myBuilderRegistry;
private final Map<String, String> myBuilderParams;
private final CanceledStatus myCancelStatus;
@Nullable private final Callbacks.ConstantAffectionResolver myConstantSearch;
private final List<MessageHandler> myMessageHandlers = new ArrayList<MessageHandler>();
private final MessageHandler myMessageDispatcher = new MessageHandler() {
public void processMessage(BuildMessage msg) {
for (MessageHandler h : myMessageHandlers) {
h.processMessage(msg);
}
}
};
private volatile float myTargetsProcessed = 0.0f;
private final float myTotalTargetsWork;
private final int myTotalModuleLevelBuilderCount;
private final List<Future> myAsyncTasks = new ArrayList<Future>();
public IncProjectBuilder(ProjectDescriptor pd, BuilderRegistry builderRegistry, Map<String, String> builderParams, CanceledStatus cs,
@Nullable Callbacks.ConstantAffectionResolver constantSearch) {
myProjectDescriptor = pd;
myBuilderRegistry = builderRegistry;
myBuilderParams = builderParams;
myCancelStatus = cs;
myConstantSearch = constantSearch;
myTotalTargetsWork = pd.getBuildTargetIndex().getAllTargets().size();
myTotalModuleLevelBuilderCount = builderRegistry.getModuleLevelBuilderCount();
}
public void addMessageHandler(MessageHandler handler) {
myMessageHandlers.add(handler);
}
public void build(CompileScope scope, final boolean isMake, final boolean isProjectRebuild, boolean forceCleanCaches)
throws RebuildRequestedException {
final LowMemoryWatcher memWatcher = LowMemoryWatcher.register(new Runnable() {
@Override
public void run() {
myProjectDescriptor.dataManager.flush(false);
myProjectDescriptor.timestamps.getStorage().force();
}
});
CompileContextImpl context = null;
try {
context = createContext(scope, isMake, isProjectRebuild);
runBuild(context, forceCleanCaches);
myProjectDescriptor.dataManager.saveVersion();
}
catch (ProjectBuildException e) {
final Throwable cause = e.getCause();
if (cause instanceof PersistentEnumerator.CorruptedException ||
cause instanceof MappingFailedException ||
cause instanceof IOException) {
myMessageDispatcher.processMessage(new CompilerMessage(
BUILD_NAME, BuildMessage.Kind.INFO,
"Internal caches are corrupted or have outdated format, forcing project rebuild: " +
e.getMessage())
);
throw new RebuildRequestedException(cause);
}
else {
if (cause == null) {
final String msg = e.getMessage();
if (!StringUtil.isEmpty(msg)) {
myMessageDispatcher.processMessage(new ProgressMessage(msg));
}
}
else {
myMessageDispatcher.processMessage(new CompilerMessage(BUILD_NAME, cause));
}
}
}
finally {
memWatcher.stop();
flushContext(context);
// wait for the async tasks
for (Future task : myAsyncTasks) {
try {
task.get();
}
catch (Throwable th) {
LOG.info(th);
}
}
}
}
private static void flushContext(CompileContext context) {
if (context != null) {
final ProjectDescriptor pd = context.getProjectDescriptor();
pd.timestamps.getStorage().force();
pd.dataManager.flush(false);
}
final ExternalJavacDescriptor descriptor = ExternalJavacDescriptor.KEY.get(context);
if (descriptor != null) {
try {
final RequestFuture future = descriptor.client.sendShutdownRequest();
future.waitFor(500L, TimeUnit.MILLISECONDS);
}
finally {
// ensure process is not running
descriptor.process.destroyProcess();
}
ExternalJavacDescriptor.KEY.set(context, null);
}
//cleanupJavacNameTable();
}
private static boolean ourClenupFailed = false;
private static void cleanupJavacNameTable() {
try {
if (JavaBuilder.USE_EMBEDDED_JAVAC && !ourClenupFailed) {
final Field freelistField = Class.forName("com.sun.tools.javac.util.Name$Table").getDeclaredField("freelist");
freelistField.setAccessible(true);
freelistField.set(null, com.sun.tools.javac.util.List.nil());
}
}
catch (Throwable e) {
ourClenupFailed = true;
//LOG.info(e);
}
}
private void runBuild(CompileContextImpl context, boolean forceCleanCaches) throws ProjectBuildException {
context.setDone(0.0f);
LOG.info("Building project; isRebuild:" + context.isProjectRebuild() + "; isMake:" + context.isMake() + " parallel compilation:" + BuildRunner.PARALLEL_BUILD_ENABLED);
for (TargetBuilder builder : myBuilderRegistry.getTargetBuilders()) {
builder.buildStarted(context);
}
for (ModuleLevelBuilder builder : myBuilderRegistry.getModuleLevelBuilders()) {
builder.buildStarted(context);
}
try {
if (context.isProjectRebuild() || forceCleanCaches) {
cleanOutputRoots(context);
}
context.processMessage(new ProgressMessage("Running 'before' tasks"));
runTasks(context, myBuilderRegistry.getBeforeTasks());
context.processMessage(new ProgressMessage("Checking sources"));
buildChunks(context);
context.processMessage(new ProgressMessage("Running 'after' tasks"));
runTasks(context, myBuilderRegistry.getAfterTasks());
// cleanup output roots layout, commented for efficiency
//final ModuleOutputRootsLayout outputRootsLayout = context.getDataManager().getOutputRootsLayout();
//try {
// final Iterator<String> keysIterator = outputRootsLayout.getKeysIterator();
// final Map<String, JpsModule> modules = myProjectDescriptor.project.getModules();
// while (keysIterator.hasNext()) {
// final String moduleName = keysIterator.next();
// if (modules.containsKey(moduleName)) {
// outputRootsLayout.remove(moduleName);
// }
// }
//}
//catch (IOException e) {
// throw new ProjectBuildException(e);
//}
}
finally {
for (TargetBuilder builder : myBuilderRegistry.getTargetBuilders()) {
builder.buildFinished(context);
}
for (ModuleLevelBuilder builder : myBuilderRegistry.getModuleLevelBuilders()) {
builder.buildFinished(context);
}
context.processMessage(new ProgressMessage("Finished, saving caches..."));
}
}
private CompileContextImpl createContext(CompileScope scope, boolean isMake, final boolean isProjectRebuild) throws ProjectBuildException {
final CompileContextImpl context = new CompileContextImpl(scope, myProjectDescriptor, isMake, isProjectRebuild, myMessageDispatcher,
myBuilderParams, myCancelStatus
);
JavaBuilderUtil.CONSTANT_SEARCH_SERVICE.set(context, myConstantSearch);
return context;
}
private void cleanOutputRoots(CompileContext context) throws ProjectBuildException {
// whole project is affected
ProjectDescriptor projectDescriptor = context.getProjectDescriptor();
JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(projectDescriptor.getProject());
final boolean shouldClear = configuration.isClearOutputDirectoryOnRebuild();
try {
if (shouldClear) {
clearOutputs(context);
}
else {
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets()) {
clearOutputFiles(context, target);
}
}
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning output files", e);
}
try {
projectDescriptor.timestamps.getStorage().clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning timestamps storage", e);
}
try {
projectDescriptor.dataManager.clean();
}
catch (IOException e) {
throw new ProjectBuildException("Error cleaning compiler storages", e);
}
myProjectDescriptor.fsState.clearAll();
}
public static void clearOutputFiles(CompileContext context, BuildTarget<?> target) throws IOException {
final SourceToOutputMapping map = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target);
for (String srcPath : map.getSources()) {
final Collection<String> outs = map.getOutputs(srcPath);
if (outs != null && !outs.isEmpty()) {
for (String out : outs) {
new File(out).delete();
}
context.processMessage(new FileDeletedEvent(outs));
}
}
}
private void clearOutputs(CompileContext context) throws ProjectBuildException, IOException {
final MultiMap<File, BuildTarget<?>> rootsToDelete = new MultiMapBasedOnSet<File,BuildTarget<?>>();
final Set<File> allSourceRoots = new HashSet<File>();
final ProjectPaths paths = context.getProjectPaths();
ProjectDescriptor projectDescriptor = context.getProjectDescriptor();
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets()) {
File outputDir = target.getOutputDir(projectDescriptor.dataManager.getDataPaths());
if (outputDir != null) {
rootsToDelete.putValue(outputDir, target);
}
}
for (BuildTargetType<?> type : JavaModuleBuildTargetType.ALL_TYPES) {
for (BuildTarget<?> target : projectDescriptor.getBuildTargetIndex().getAllTargets(type)) {
for (BuildRootDescriptor descriptor : projectDescriptor.getBuildRootIndex().getTargetRoots(target, context)) {
allSourceRoots.add(descriptor.getRootFile());
}
}
}
// check that output and source roots are not overlapping
final List<File> filesToDelete = new ArrayList<File>();
for (Map.Entry<File, Collection<BuildTarget<?>>> entry : rootsToDelete.entrySet()) {
context.checkCanceled();
boolean okToDelete = true;
final File outputRoot = entry.getKey();
if (JpsPathUtil.isUnder(allSourceRoots, outputRoot)) {
okToDelete = false;
}
else {
final Set<File> _outRoot = Collections.singleton(outputRoot);
for (File srcRoot : allSourceRoots) {
if (JpsPathUtil.isUnder(_outRoot, srcRoot)) {
okToDelete = false;
break;
}
}
}
if (okToDelete) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = outputRoot.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
}
else {
context.processMessage(new CompilerMessage(BUILD_NAME, BuildMessage.Kind.WARNING, "Output path " + outputRoot.getPath() + " intersects with a source root. The output cannot be cleaned."));
// clean only those files we are aware of
for (BuildTarget<?> target : entry.getValue()) {
clearOutputFiles(context, target);
}
}
}
final Set<File> annotationOutputs = new HashSet<File>(); // separate collection because no root intersection checks needed for annotation generated sources
for (JavaModuleBuildTargetType type : JavaModuleBuildTargetType.ALL_TYPES) {
for (ModuleBuildTarget target : projectDescriptor.getBuildTargetIndex().getAllTargets(type)) {
final ProcessorConfigProfile profile = context.getAnnotationProcessingProfile(target.getModule());
if (profile.isEnabled()) {
File annotationOut = paths.getAnnotationProcessorGeneratedSourcesOutputDir(target.getModule(), target.isTests(), profile.getGeneratedSourcesDirectoryName());
if (annotationOut != null) {
annotationOutputs.add(annotationOut);
}
}
}
}
for (File annotationOutput : annotationOutputs) {
// do not delete output root itself to avoid lots of unnecessary "roots_changed" events in IDEA
final File[] children = annotationOutput.listFiles();
if (children != null) {
filesToDelete.addAll(Arrays.asList(children));
}
}
context.processMessage(new ProgressMessage("Cleaning output directories..."));
myAsyncTasks.add(
FileUtil.asyncDelete(filesToDelete)
);
}
private static void runTasks(CompileContext context, final List<BuildTask> tasks) throws ProjectBuildException {
for (BuildTask task : tasks) {
task.build(context);
}
}
private void buildChunks(final CompileContextImpl context) throws ProjectBuildException {
final CompileScope scope = context.getScope();
final ProjectDescriptor pd = context.getProjectDescriptor();
BuildTargetIndex targetIndex = pd.getBuildTargetIndex();
try {
if (BuildRunner.PARALLEL_BUILD_ENABLED) {
final List<ChunkGroup> chunkGroups = buildChunkGroups(targetIndex);
for (ChunkGroup group : chunkGroups) {
final List<BuildTargetChunk> groupChunks = group.getChunks();
final int chunkCount = groupChunks.size();
if (chunkCount == 0) {
continue;
}
try {
if (chunkCount == 1) {
buildChunkIfAffected(createContextWrapper(context), scope, groupChunks.iterator().next());
}
else {
final CountDownLatch latch = new CountDownLatch(chunkCount);
final Ref<Throwable> exRef = new Ref<Throwable>(null);
if (LOG.isDebugEnabled()) {
final StringBuilder logBuilder = new StringBuilder("Building chunks in parallel: ");
for (BuildTargetChunk chunk : groupChunks) {
logBuilder.append(chunk.toString()).append("; ");
}
LOG.debug(logBuilder.toString());
}
for (final BuildTargetChunk chunk : groupChunks) {
final CompileContext chunkLocalContext = createContextWrapper(context);
myParallelBuildExecutor.execute(new Runnable() {
@Override
public void run() {
try {
buildChunkIfAffected(chunkLocalContext, scope, chunk);
}
catch (Throwable e) {
synchronized (exRef) {
if (exRef.isNull()) {
exRef.set(e);
}
}
LOG.info(e);
}
finally {
latch.countDown();
}
}
});
}
try {
latch.await();
}
catch (InterruptedException e) {
LOG.info(e);
}
final Throwable exception = exRef.get();
if (exception != null) {
if (exception instanceof ProjectBuildException) {
throw (ProjectBuildException)exception;
}
else {
throw new ProjectBuildException(exception);
}
}
}
}
finally {
pd.dataManager.closeSourceToOutputStorages(groupChunks);
pd.dataManager.flush(true);
}
}
}
else {
// non-parallel build
for (BuildTargetChunk chunk : targetIndex.getSortedTargetChunks()) {
try {
buildChunkIfAffected(context, scope, chunk);
}
finally {
pd.dataManager.closeSourceToOutputStorages(Collections.singleton(chunk));
pd.dataManager.flush(true);
}
}
}
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
private void buildChunkIfAffected(CompileContext context, CompileScope scope, BuildTargetChunk chunk) throws ProjectBuildException {
if (isAffected(scope, chunk)) {
buildTargetsChunk(context, chunk);
}
else {
updateDoneFraction(context, chunk.getTargets().size());
}
}
private static boolean isAffected(CompileScope scope, BuildTargetChunk chunk) {
for (BuildTarget<?> target : chunk.getTargets()) {
if (scope.isAffected(target)) {
return true;
}
}
return false;
}
private boolean runBuildersForChunk(CompileContext context, final BuildTargetChunk chunk) throws ProjectBuildException {
Set<? extends BuildTarget<?>> targets = chunk.getTargets();
if (targets.size() > 1) {
Set<ModuleBuildTarget> moduleTargets = new HashSet<ModuleBuildTarget>();
for (BuildTarget<?> target : targets) {
if (target instanceof ModuleBuildTarget) {
moduleTargets.add((ModuleBuildTarget)target);
}
else {
context.processMessage(new CompilerMessage(BUILD_NAME, BuildMessage.Kind.ERROR, "Cannot build " + target.getPresentableName() + " because it is included into a circular dependency"));
return false;
}
}
return runModuleLevelBuilders(context, new ModuleChunk(moduleTargets));
}
BuildTarget<?> target = targets.iterator().next();
if (target instanceof ModuleBuildTarget) {
ModuleBuildTarget moduleBuildTarget = (ModuleBuildTarget)target;
return runModuleLevelBuilders(context, new ModuleChunk(Collections.singleton(moduleBuildTarget)));
}
else {
try {
return runTargetBuilders(target, context);
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
}
private boolean runTargetBuilders(BuildTarget<?> target, CompileContext context) throws ProjectBuildException, IOException {
List<TargetBuilder<?,?>> builders = BuilderRegistry.getInstance().getTargetBuilders();
for (TargetBuilder<?,?> builder : builders) {
buildTarget(target, context, builder);
updateDoneFraction(context, 1.0f / builders.size());
}
return true;
}
private void updateDoneFraction(CompileContext context, final float delta) {
myTargetsProcessed += delta;
float processed = myTargetsProcessed;
context.setDone(processed / myTotalTargetsWork);
}
private static <R extends BuildRootDescriptor, T extends BuildTarget<R>> void buildTarget(final T target, final CompileContext context, TargetBuilder<?,?> builder)
throws ProjectBuildException, IOException {
if (builder.getTargetTypes().contains(target.getTargetType())) {
DirtyFilesHolder<R, T> holder = new DirtyFilesHolder<R, T>() {
@Override
public void processDirtyFiles(@NotNull FileProcessor<R, T> processor) throws IOException {
context.getProjectDescriptor().fsState.processFilesToRecompile(context, target, processor);
}
};
//noinspection unchecked
((TargetBuilder<R,T>)builder).build(target, context, holder);
context.checkCanceled();
}
}
private void buildTargetsChunk(CompileContext context, final BuildTargetChunk chunk) throws ProjectBuildException {
boolean doneSomething = false;
try {
Utils.ERRORS_DETECTED_KEY.set(context, Boolean.FALSE);
ensureFSStateInitialized(context, chunk);
if (context.isMake()) {
processDeletedPaths(context, chunk.getTargets());
doneSomething |= Utils.hasRemovedSources(context);
}
myProjectDescriptor.fsState.beforeChunkBuildStart(context, chunk);
doneSomething = runBuildersForChunk(context, chunk);
}
catch (ProjectBuildException e) {
throw e;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
try {
onChunkBuildComplete(context, chunk);
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
finally {
final Collection<? extends BuildRootDescriptor> tempRoots = context.getProjectDescriptor().getBuildRootIndex().clearTempRoots(context);
if (!tempRoots.isEmpty()) {
final Set<File> rootFiles = new HashSet<File>();
for (BuildRootDescriptor rd : tempRoots) {
rootFiles.add(rd.getRootFile());
context.getProjectDescriptor().fsState.clearRecompile(rd);
}
myAsyncTasks.add(FileUtil.asyncDelete(rootFiles));
}
try {
// restore deleted paths that were not procesesd by 'integrate'
final Map<BuildTarget<?>, Collection<String>> map = Utils.REMOVED_SOURCES_KEY.get(context);
if (map != null) {
for (Map.Entry<BuildTarget<?>, Collection<String>> entry : map.entrySet()) {
final BuildTarget<?> target = entry.getKey();
final Collection<String> paths = entry.getValue();
if (paths != null) {
for (String path : paths) {
myProjectDescriptor.fsState.registerDeleted(target, new File(path), null);
}
}
}
}
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
Utils.REMOVED_SOURCES_KEY.set(context, null);
if (doneSomething && GENERATE_CLASSPATH_INDEX) {
final Future<?> future = SharedThreadPool.getInstance().executeOnPooledThread(new Runnable() {
@Override
public void run() {
createClasspathIndex(chunk);
}
});
myAsyncTasks.add(future);
}
}
}
}
private static void createClasspathIndex(final BuildTargetChunk chunk) {
final Set<File> outputDirs = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY);
for (BuildTarget<?> target : chunk.getTargets()) {
if (target instanceof ModuleBuildTarget) {
File outputDir = ((ModuleBuildTarget)target).getOutputDir();
if (outputDir != null && outputDirs.add(outputDir)) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputDir, CLASSPATH_INDEX_FINE_NAME)));
try {
writeIndex(writer, outputDir, "");
}
finally {
writer.close();
}
}
catch (IOException e) {
// Ignore. Failed to create optional classpath index
}
}
}
}
}
private static void writeIndex(final BufferedWriter writer, final File file, final String path) throws IOException {
writer.write(path);
writer.write('\n');
final File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
final String _path = path.isEmpty() ? child.getName() : path + "/" + child.getName();
writeIndex(writer, child, _path);
}
}
}
private void processDeletedPaths(CompileContext context, final Set<? extends BuildTarget<?>> targets) throws ProjectBuildException {
try {
// cleanup outputs
final Map<BuildTarget<?>, Collection<String>> removedSources = new HashMap<BuildTarget<?>, Collection<String>>();
for (BuildTarget<?> target : targets) {
final Collection<String> deletedPaths = myProjectDescriptor.fsState.getAndClearDeletedPaths(target);
if (deletedPaths.isEmpty()) {
continue;
}
removedSources.put(target, deletedPaths);
final SourceToOutputMapping sourceToOutputStorage = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target);
// actually delete outputs associated with removed paths
for (String deletedSource : deletedPaths) {
// deleting outputs corresponding to non-existing source
final Collection<String> outputs = sourceToOutputStorage.getOutputs(deletedSource);
if (outputs != null && !outputs.isEmpty()) {
final ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger();
if (logger.isEnabled()) {
logger.logDeletedFiles(outputs);
}
for (String output : outputs) {
new File(output).delete();
}
context.processMessage(new FileDeletedEvent(outputs));
}
if (target instanceof ModuleBuildTarget) {
// check if deleted source was associated with a form
final SourceToFormMapping sourceToFormMap = context.getProjectDescriptor().dataManager.getSourceToFormMap();
final String formPath = sourceToFormMap.getState(deletedSource);
if (formPath != null) {
final File formFile = new File(formPath);
if (formFile.exists()) {
FSOperations.markDirty(context, formFile);
}
sourceToFormMap.remove(deletedSource);
}
}
}
}
if (!removedSources.isEmpty()) {
final Map<BuildTarget<?>, Collection<String>> existing = Utils.REMOVED_SOURCES_KEY.get(context);
if (existing != null) {
for (Map.Entry<BuildTarget<?>, Collection<String>> entry : existing.entrySet()) {
final Collection<String> paths = removedSources.get(entry.getKey());
if (paths != null) {
paths.addAll(entry.getValue());
}
else {
removedSources.put(entry.getKey(), entry.getValue());
}
}
}
Utils.REMOVED_SOURCES_KEY.set(context, removedSources);
}
}
catch (IOException e) {
throw new ProjectBuildException(e);
}
}
// return true if changed something, false otherwise
private boolean runModuleLevelBuilders(final CompileContext context, final ModuleChunk chunk) throws ProjectBuildException {
boolean doneSomething = false;
boolean rebuildFromScratchRequested = false;
float stageCount = myTotalModuleLevelBuilderCount;
final int modulesInChunk = chunk.getModules().size();
int buildersPassed = 0;
boolean nextPassRequired;
try {
do {
nextPassRequired = false;
myProjectDescriptor.fsState.beforeNextRoundStart(context, chunk);
DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder = new DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget>() {
@Override
public void processDirtyFiles(@NotNull FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget> processor) throws IOException {
FSOperations.processFilesToRecompile(context, chunk, processor);
}
};
if (!context.isProjectRebuild()) {
deleteOutputsOfDirtyFiles(context, dirtyFilesHolder);
}
BUILDER_CATEGORY_LOOP:
for (BuilderCategory category : BuilderCategory.values()) {
final List<ModuleLevelBuilder> builders = myBuilderRegistry.getBuilders(category);
if (builders.isEmpty()) {
continue;
}
for (ModuleLevelBuilder builder : builders) {
if (context.isMake()) {
processDeletedPaths(context, chunk.getTargets());
}
final ModuleLevelBuilder.ExitCode buildResult = builder.build(context, chunk, dirtyFilesHolder);
doneSomething |= (buildResult != ModuleLevelBuilder.ExitCode.NOTHING_DONE);
if (buildResult == ModuleLevelBuilder.ExitCode.ABORT) {
throw new ProjectBuildException("Builder " + builder.getDescription() + " requested build stop");
}
context.checkCanceled();
if (buildResult == ModuleLevelBuilder.ExitCode.ADDITIONAL_PASS_REQUIRED) {
if (!nextPassRequired) {
// recalculate basis
myTargetsProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount += myTotalModuleLevelBuilderCount;
myTargetsProcessed += (buildersPassed * modulesInChunk) / stageCount;
}
nextPassRequired = true;
}
else if (buildResult == ModuleLevelBuilder.ExitCode.CHUNK_REBUILD_REQUIRED) {
if (!rebuildFromScratchRequested && !context.isProjectRebuild()) {
LOG.info("Builder " + builder.getDescription() + " requested rebuild of module chunk " + chunk.getName());
// allow rebuild from scratch only once per chunk
rebuildFromScratchRequested = true;
try {
// forcibly mark all files in the chunk dirty
FSOperations.markDirty(context, chunk);
// reverting to the beginning
myTargetsProcessed -= (buildersPassed * modulesInChunk) / stageCount;
stageCount = myTotalModuleLevelBuilderCount;
buildersPassed = 0;
nextPassRequired = true;
break BUILDER_CATEGORY_LOOP;
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
else {
LOG.debug("Builder " + builder.getDescription() + " requested second chunk rebuild");
}
}
buildersPassed++;
updateDoneFraction(context, modulesInChunk / (stageCount));
}
}
}
while (nextPassRequired);
}
finally {
for (BuilderCategory category : BuilderCategory.values()) {
for (ModuleLevelBuilder builder : myBuilderRegistry.getBuilders(category)) {
builder.cleanupChunkResources(context);
}
}
}
return doneSomething;
}
private static <R extends BuildRootDescriptor,T extends BuildTarget<R>>
void deleteOutputsOfDirtyFiles(final CompileContext context, DirtyFilesHolder<R, T> dirtyFilesHolder) throws ProjectBuildException {
final BuildDataManager dataManager = context.getProjectDescriptor().dataManager;
try {
ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger();
final Collection<String> outputsToLog = logger.isEnabled() ? new LinkedList<String>() : null;
dirtyFilesHolder.processDirtyFiles(new FileProcessor<R, T>() {
private final Map<T, SourceToOutputMapping> storageMap = new HashMap<T, SourceToOutputMapping>();
@Override
public boolean apply(T target, File file, R sourceRoot) throws IOException {
SourceToOutputMapping srcToOut = storageMap.get(target);
if (srcToOut == null) {
srcToOut = dataManager.getSourceToOutputMap(target);
storageMap.put(target, srcToOut);
}
final String srcPath = FileUtil.toSystemIndependentName(file.getPath());
final Collection<String> outputs = srcToOut.getOutputs(srcPath);
if (outputs != null) {
for (String output : outputs) {
if (outputsToLog != null) {
outputsToLog.add(output);
}
new File(output).delete();
}
if (!outputs.isEmpty()) {
context.processMessage(new FileDeletedEvent(outputs));
}
srcToOut.setOutputs(srcPath, Collections.<String>emptyList());
}
return true;
}
});
if (outputsToLog != null && context.isMake()) {
logger.logDeletedFiles(outputsToLog);
}
}
catch (Exception e) {
throw new ProjectBuildException(e);
}
}
private static List<ChunkGroup> buildChunkGroups(BuildTargetIndex index) {
final List<BuildTargetChunk> allChunks = index.getSortedTargetChunks();
// building aux dependencies map
final Map<BuildTarget<?>, Set<BuildTarget<?>>> depsMap = new HashMap<BuildTarget<?>, Set<BuildTarget<?>>>();
for (BuildTarget target : index.getAllTargets()) {
depsMap.put(target, index.getDependenciesRecursively(target));
}
final List<ChunkGroup> groups = new ArrayList<ChunkGroup>();
ChunkGroup currentGroup = new ChunkGroup();
groups.add(currentGroup);
for (BuildTargetChunk chunk : allChunks) {
if (dependsOnGroup(chunk, currentGroup, depsMap)) {
currentGroup = new ChunkGroup();
groups.add(currentGroup);
}
currentGroup.addChunk(chunk);
}
return groups;
}
private static boolean dependsOnGroup(BuildTargetChunk chunk, ChunkGroup group, Map<BuildTarget<?>, Set<BuildTarget<?>>> depsMap) {
for (BuildTargetChunk groupChunk : group.getChunks()) {
final Set<? extends BuildTarget<?>> groupChunkTargets = groupChunk.getTargets();
for (BuildTarget<?> target : chunk.getTargets()) {
if (ContainerUtil.intersects(depsMap.get(target), groupChunkTargets)) {
return true;
}
}
}
return false;
}
private static void onChunkBuildComplete(CompileContext context, @NotNull BuildTargetChunk chunk) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final BuildFSState fsState = pd.fsState;
fsState.clearContextRoundData(context);
fsState.clearContextChunk(context);
if (!Utils.errorsDetected(context) && !context.getCancelStatus().isCanceled()) {
boolean marked = false;
for (BuildTarget<?> target : chunk.getTargets()) {
if (context.isMake() && target instanceof ModuleBuildTarget) {
// ensure non-incremental flag cleared
context.clearNonIncrementalMark((ModuleBuildTarget)target);
}
if (context.isProjectRebuild()) {
fsState.markInitialScanPerformed(target);
}
final Timestamps timestamps = pd.timestamps.getStorage();
for (BuildRootDescriptor rd : pd.getBuildRootIndex().getTargetRoots(target, context)) {
marked |= fsState.markAllUpToDate(context, rd, timestamps);
}
}
if (marked) {
context.processMessage(UptoDateFilesSavedEvent.INSTANCE);
}
}
}
private static void ensureFSStateInitialized(CompileContext context, BuildTargetChunk chunk) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final Timestamps timestamps = pd.timestamps.getStorage();
for (BuildTarget<?> target : chunk.getTargets()) {
final BuildTargetConfiguration configuration = pd.getTargetsState().getTargetConfiguration(target);
if (target instanceof ModuleBuildTarget) {
ensureFSStateInitialized(context, pd, timestamps, configuration, (ModuleBuildTarget)target);
}
else {
ensureFSStateInitialized(context, target);
}
}
}
private static void ensureFSStateInitialized(CompileContext context, BuildTarget<?> target) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final Timestamps timestamps = pd.timestamps.getStorage();
final BuildTargetConfiguration configuration = pd.getTargetsState().getTargetConfiguration(target);
if (context.isProjectRebuild() || configuration.isTargetDirty() || context.getScope().isRecompilationForced(target)) {
FSOperations.markDirtyFiles(context, target, timestamps, true, null, Collections.<File>emptySet());
configuration.save();
}
else if (context.isMake()) {
if (pd.fsState.markInitialScanPerformed(target)) {
FSOperations.markDirtyFiles(context, target, timestamps, false, null, Collections.<File>emptySet());
}
}
}
private static void ensureFSStateInitialized(CompileContext context,
ProjectDescriptor pd,
Timestamps timestamps,
BuildTargetConfiguration configuration, ModuleBuildTarget target) throws IOException {
if (context.isProjectRebuild() || configuration.isTargetDirty()) {
FSOperations.markDirtyFiles(context, target, timestamps, true, null);
updateOutputRootsLayout(context, target);
configuration.save();
}
else {
if (context.isMake()) {
if (pd.fsState.markInitialScanPerformed(target)) {
boolean forceMarkDirty = false;
final File currentOutput = target.getOutputDir();
if (currentOutput != null) {
final Pair<String, String> outputsPair = pd.dataManager.getOutputRootsLayout().getState(target.getModuleName());
if (outputsPair != null) {
final String previousPath = target.isTests() ? outputsPair.second : outputsPair.first;
forceMarkDirty = StringUtil.isEmpty(previousPath) || !FileUtil.filesEqual(currentOutput, new File(previousPath));
}
else {
forceMarkDirty = true;
}
}
initModuleFSState(context, target, forceMarkDirty);
}
}
else {
// forced compilation mode
if (context.getScope().isRecompilationForced(target)) {
initModuleFSState(context, target, true);
}
}
}
}
private static void initModuleFSState(CompileContext context, ModuleBuildTarget target, final boolean forceMarkDirty) throws IOException {
final ProjectDescriptor pd = context.getProjectDescriptor();
final Timestamps timestamps = pd.timestamps.getStorage();
final THashSet<File> currentFiles = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY);
FSOperations.markDirtyFiles(context, target, timestamps, forceMarkDirty, currentFiles);
// handle deleted paths
final BuildFSState fsState = pd.fsState;
fsState.clearDeletedPaths(target);
final SourceToOutputMapping sourceToOutputMap = pd.dataManager.getSourceToOutputMap(target);
for (final Iterator<String> it = sourceToOutputMap.getSourcesIterator(); it.hasNext();) {
final String path = it.next();
// can check if the file exists
final File file = new File(path);
if (!currentFiles.contains(file)) {
fsState.registerDeleted(target, file, timestamps);
}
}
updateOutputRootsLayout(context, target);
}
private static void updateOutputRootsLayout(CompileContext context, ModuleBuildTarget target) throws IOException {
final File currentOutput = target.getOutputDir();
if (currentOutput == null) {
return;
}
final ModuleOutputRootsLayout outputRootsLayout = context.getProjectDescriptor().dataManager.getOutputRootsLayout();
Pair<String, String> outputsPair = outputRootsLayout.getState(target.getModuleName());
// update data
final String productionPath;
final String testPath;
if (target.isTests()) {
productionPath = outputsPair != null? outputsPair.first : "";
testPath = FileUtil.toSystemIndependentName(currentOutput.getPath());
}
else {
productionPath = FileUtil.toSystemIndependentName(currentOutput.getPath());
testPath = outputsPair != null? outputsPair.second : "";
}
outputRootsLayout.update(target.getModuleName(), Pair.create(productionPath, testPath));
}
private static class ChunkGroup {
private final List<BuildTargetChunk> myChunks = new ArrayList<BuildTargetChunk>();
public void addChunk(BuildTargetChunk chunk) {
myChunks.add(chunk);
}
public List<BuildTargetChunk> getChunks() {
return myChunks;
}
}
private static final Set<Key> GLOBAL_CONTEXT_KEYS = new HashSet<Key>();
static {
// keys for data that must be visible to all threads
GLOBAL_CONTEXT_KEYS.add(ExternalJavacDescriptor.KEY);
}
private static CompileContext createContextWrapper(final CompileContext delegate) {
final ClassLoader loader = delegate.getClass().getClassLoader();
final UserDataHolderBase localDataHolder = new UserDataHolderBase();
final Set deletedKeysSet = new ConcurrentHashSet();
final Class<UserDataHolder> dataHolderinterface = UserDataHolder.class;
final Class<MessageHandler> messageHandlerinterface = MessageHandler.class;
return (CompileContext)Proxy.newProxyInstance(loader, new Class[] {CompileContext.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final Class<?> declaringClass = method.getDeclaringClass();
if (dataHolderinterface.equals(declaringClass)) {
final Object firstArgument = args[0];
final boolean isGlobalContextKey = firstArgument instanceof Key && GLOBAL_CONTEXT_KEYS.contains((Key)firstArgument);
if (!isGlobalContextKey) {
final boolean isWriteOperation = args.length == 2 /*&& void.class.equals(method.getReturnType())*/;
if (isWriteOperation) {
if (args[1] == null) {
deletedKeysSet.add(firstArgument);
}
else {
deletedKeysSet.remove(firstArgument);
}
}
else {
if (deletedKeysSet.contains(firstArgument)) {
return null;
}
}
final Object result = method.invoke(localDataHolder, args);
if (isWriteOperation || result != null) {
return result;
}
}
}
else if (messageHandlerinterface.equals(declaringClass)) {
final BuildMessage msg = (BuildMessage)args[0];
if (msg.getKind() == BuildMessage.Kind.ERROR) {
Utils.ERRORS_DETECTED_KEY.set(localDataHolder, Boolean.TRUE);
}
}
try {
return method.invoke(delegate, args);
}
catch (InvocationTargetException e) {
final Throwable targetEx = e.getTargetException();
if (targetEx instanceof ProjectBuildException) {
throw targetEx;
}
throw e;
}
}
});
}
}
|
fixed incomplete merge
|
jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
|
fixed incomplete merge
|
|
Java
|
apache-2.0
|
b8bd28affbd5c27365e51bc847f900293735d165
| 0
|
youdonghai/intellij-community,ibinti/intellij-community,kool79/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,slisson/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,allotria/intellij-community,amith01994/intellij-community,jagguli/intellij-community,fitermay/intellij-community,kdwink/intellij-community,supersven/intellij-community,hurricup/intellij-community,diorcety/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,dslomov/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,gnuhub/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,izonder/intellij-community,allotria/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,jagguli/intellij-community,petteyg/intellij-community,hurricup/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,supersven/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,asedunov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,allotria/intellij-community,adedayo/intellij-community,slisson/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,signed/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,caot/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,petteyg/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,semonte/intellij-community,slisson/intellij-community,petteyg/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,asedunov/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,slisson/intellij-community,supersven/intellij-community,xfournet/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,izonder/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,petteyg/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,diorcety/intellij-community,caot/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,hurricup/intellij-community,da1z/intellij-community,fnouama/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,adedayo/intellij-community,signed/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,retomerz/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,semonte/intellij-community,izonder/intellij-community,Lekanich/intellij-community,signed/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,vvv1559/intellij-community,caot/intellij-community,asedunov/intellij-community,kool79/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,supersven/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,allotria/intellij-community,fnouama/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,da1z/intellij-community,caot/intellij-community,nicolargo/intellij-community,signed/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,fitermay/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,samthor/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,kool79/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,allotria/intellij-community,fitermay/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ryano144/intellij-community,samthor/intellij-community,xfournet/intellij-community,diorcety/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,samthor/intellij-community,semonte/intellij-community,caot/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,kdwink/intellij-community,fnouama/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,holmes/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,holmes/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,signed/intellij-community,kool79/intellij-community,FHannes/intellij-community,amith01994/intellij-community,fnouama/intellij-community,robovm/robovm-studio,FHannes/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,retomerz/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,adedayo/intellij-community,slisson/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,ryano144/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,supersven/intellij-community,supersven/intellij-community,signed/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,FHannes/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,caot/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,apixandru/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,caot/intellij-community,holmes/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,retomerz/intellij-community,ibinti/intellij-community,kdwink/intellij-community,caot/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,allotria/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,petteyg/intellij-community,da1z/intellij-community,xfournet/intellij-community,supersven/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,samthor/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,da1z/intellij-community,supersven/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,apixandru/intellij-community,fnouama/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,hurricup/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,akosyakov/intellij-community,allotria/intellij-community,asedunov/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,clumsy/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,holmes/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,signed/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,da1z/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,ryano144/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,allotria/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,jagguli/intellij-community,retomerz/intellij-community,vladmm/intellij-community,blademainer/intellij-community,signed/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,da1z/intellij-community,amith01994/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,tmpgit/intellij-community,samthor/intellij-community,ibinti/intellij-community,FHannes/intellij-community,kool79/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,kool79/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ryano144/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,apixandru/intellij-community,da1z/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,izonder/intellij-community,ryano144/intellij-community,semonte/intellij-community,diorcety/intellij-community,kool79/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,allotria/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,fitermay/intellij-community,da1z/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,fnouama/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,apixandru/intellij-community,amith01994/intellij-community,apixandru/intellij-community,jagguli/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,signed/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community
|
package org.jetbrains.plugins.github.tasks;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.PasswordUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tasks.Comment;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepository;
import com.intellij.tasks.TaskType;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.Transient;
import icons.TasksIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.github.api.GithubApiUtil;
import org.jetbrains.plugins.github.GithubAuthData;
import org.jetbrains.plugins.github.GithubUtil;
import org.jetbrains.plugins.github.api.GithubIssue;
import org.jetbrains.plugins.github.api.GithubIssueComment;
import javax.swing.*;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Dennis.Ushakov
*/
@Tag("GitHub")
public class GithubRepository extends BaseRepositoryImpl {
private static final Logger LOG = GithubUtil.LOG;
private Pattern myPattern = Pattern.compile("($^)");
@NotNull private String myRepoAuthor = "";
@NotNull private String myRepoName = "";
@NotNull private String myUser = "";
@NotNull private String myToken = "";
{
setUrl(GithubApiUtil.DEFAULT_GITHUB_HOST);
}
@SuppressWarnings({"UnusedDeclaration"})
public GithubRepository() {}
public GithubRepository(GithubRepository other) {
super(other);
setRepoName(other.myRepoName);
setRepoAuthor(other.myRepoAuthor);
setToken(other.myToken);
}
public GithubRepository(GithubRepositoryType type) {
super(type);
}
@Override
public void testConnection() throws Exception {
getIssues("", 10, 0);
}
@Override
public boolean isConfigured() {
return super.isConfigured() &&
StringUtil.isNotEmpty(getRepoName());
}
@Override
public String getPresentableName() {
final String name = super.getPresentableName();
return name +
(!StringUtil.isEmpty(getRepoAuthor()) ? "/" + getRepoAuthor() : "") +
(!StringUtil.isEmpty(getRepoName()) ? "/" + getRepoName() : "");
}
@Override
public Task[] getIssues(@Nullable String query, int max, long since) throws Exception {
return getIssues(query);
}
@NotNull
private Task[] getIssues(@Nullable String query) throws Exception {
List<GithubIssue> issues;
if (StringUtil.isEmptyOrSpaces(query)) {
if (StringUtil.isEmptyOrSpaces(myUser)) {
myUser = GithubApiUtil.getCurrentUser(getAuthData()).getLogin();
}
issues = GithubApiUtil.getIssuesAssigned(getAuthData(), getRepoAuthor(), getRepoName(), myUser);
}
else {
issues = GithubApiUtil.getIssuesQueried(getAuthData(), getRepoAuthor(), getRepoName(), query);
}
return ContainerUtil.map2Array(issues, Task.class, new Function<GithubIssue, Task>() {
@Override
public Task fun(GithubIssue issue) {
return createTask(issue);
}
});
}
@NotNull
private Task createTask(final GithubIssue issue) {
return new Task() {
@NotNull String myRepoName = getRepoName();
@Override
public boolean isIssue() {
return true;
}
@Override
public String getIssueUrl() {
return issue.getHtmlUrl();
}
@NotNull
@Override
public String getId() {
return myRepoName + "-" + issue.getNumber();
}
@NotNull
@Override
public String getSummary() {
return issue.getTitle();
}
public String getDescription() {
return issue.getBody();
}
@NotNull
@Override
public Comment[] getComments() {
try {
return fetchComments(issue.getNumber());
}
catch (Exception e) {
LOG.warn("Error fetching comments for " + issue.getNumber(), e);
return Comment.EMPTY_ARRAY;
}
}
@NotNull
@Override
public Icon getIcon() {
return TasksIcons.Github;
}
@NotNull
@Override
public TaskType getType() {
return TaskType.BUG;
}
@Override
public Date getUpdated() {
return issue.getUpdatedAt();
}
@Override
public Date getCreated() {
return issue.getCreatedAt();
}
@Override
public boolean isClosed() {
return !"open".equals(issue.getState());
}
@Override
public TaskRepository getRepository() {
return GithubRepository.this;
}
@Override
public String getPresentableName() {
return getId() + ": " + getSummary();
}
};
}
private Comment[] fetchComments(final long id) throws Exception {
List<GithubIssueComment> result = GithubApiUtil.getIssueComments(getAuthData(), getRepoAuthor(), getRepoName(), id);
return ContainerUtil.map2Array(result, Comment.class, new Function<GithubIssueComment, Comment>() {
@Override
public Comment fun(GithubIssueComment comment) {
return new GithubComment(comment.getCreatedAt(), comment.getUser().getLogin(), comment.getBodyHtml(), comment.getUser().getGravatarId(),
comment.getUser().getHtmlUrl());
}
});
}
@Nullable
public String extractId(String taskName) {
Matcher matcher = myPattern.matcher(taskName);
return matcher.find() ? matcher.group(1) : null;
}
@Nullable
@Override
public Task findTask(String id) throws Exception {
return createTask(GithubApiUtil.getIssue(getAuthData(), getRepoAuthor(), getRepoName(), id));
}
@Override
public BaseRepository clone() {
return new GithubRepository(this);
}
@NotNull
public String getRepoName() {
return myRepoName;
}
public void setRepoName(@NotNull String repoName) {
myRepoName = repoName;
myPattern = Pattern.compile("(" + StringUtil.escapeToRegexp(repoName) + "\\-\\d+):\\s+");
}
@NotNull
public String getRepoAuthor() {
return !StringUtil.isEmpty(myRepoAuthor) ? myRepoAuthor : getUsername();
}
public void setRepoAuthor(@NotNull String repoAuthor) {
myRepoAuthor = repoAuthor;
}
@NotNull
public String getUser() {
return myUser;
}
public void setUser(@NotNull String user) {
myUser = user;
}
@Transient
@NotNull
public String getToken() {
return myToken;
}
public void setToken(@NotNull String token) {
myToken = token;
}
@Tag("token")
public String getEncodedToken() {
return PasswordUtil.encodePassword(getToken());
}
public void setEncodedToken(String password) {
try {
setToken(PasswordUtil.decodePassword(password));
}
catch (NumberFormatException e) {
LOG.warn("Can't decode token", e);
}
}
private GithubAuthData getAuthData() {
return GithubAuthData.createTokenAuth(getUrl(), getToken());
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) return false;
if (!(o instanceof GithubRepository)) return false;
GithubRepository that = (GithubRepository)o;
if (!Comparing.equal(getRepoAuthor(), that.getRepoAuthor())) return false;
if (!Comparing.equal(getRepoName(), that.getRepoName())) return false;
if (!Comparing.equal(getToken(), that.getToken())) return false;
return true;
}
@Override
protected int getFeatures() {
return BASIC_HTTP_AUTHORIZATION;
}
}
|
plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepository.java
|
package org.jetbrains.plugins.github.tasks;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.PasswordUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tasks.Comment;
import com.intellij.tasks.Task;
import com.intellij.tasks.TaskRepository;
import com.intellij.tasks.TaskType;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.Transient;
import icons.TasksIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.github.api.GithubApiUtil;
import org.jetbrains.plugins.github.GithubAuthData;
import org.jetbrains.plugins.github.GithubUtil;
import org.jetbrains.plugins.github.api.GithubIssue;
import org.jetbrains.plugins.github.api.GithubIssueComment;
import javax.swing.*;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Dennis.Ushakov
*/
@Tag("GitHub")
public class GithubRepository extends BaseRepositoryImpl {
private static final Logger LOG = GithubUtil.LOG;
private Pattern myPattern = Pattern.compile("($^)");
private String myRepoAuthor = "";
private String myRepoName = "";
private String myUser = "";
private String myToken = "";
{
setUrl(GithubApiUtil.DEFAULT_GITHUB_HOST);
}
@SuppressWarnings({"UnusedDeclaration"})
public GithubRepository() {}
public GithubRepository(GithubRepository other) {
super(other);
setRepoName(other.myRepoName);
setRepoAuthor(other.myRepoAuthor);
setToken(other.myToken);
}
public GithubRepository(GithubRepositoryType type) {
super(type);
}
@Override
public void testConnection() throws Exception {
getIssues("", 10, 0);
}
@Override
public boolean isConfigured() {
return super.isConfigured() &&
StringUtil.isNotEmpty(getRepoName());
}
@Override
public String getPresentableName() {
final String name = super.getPresentableName();
return name +
(!StringUtil.isEmpty(getRepoAuthor()) ? "/" + getRepoAuthor() : "") +
(!StringUtil.isEmpty(getRepoName()) ? "/" + getRepoName() : "");
}
@Override
public Task[] getIssues(@Nullable String query, int max, long since) throws Exception {
return getIssues(query);
}
@NotNull
private Task[] getIssues(@Nullable String query) throws Exception {
List<GithubIssue> issues;
if (StringUtil.isEmptyOrSpaces(query)) {
if (StringUtil.isEmptyOrSpaces(myUser)) {
myUser = GithubApiUtil.getCurrentUser(getAuthData()).getLogin();
}
issues = GithubApiUtil.getIssuesAssigned(getAuthData(), getRepoAuthor(), getRepoName(), myUser);
}
else {
issues = GithubApiUtil.getIssuesQueried(getAuthData(), getRepoAuthor(), getRepoName(), query);
}
return ContainerUtil.map2Array(issues, Task.class, new Function<GithubIssue, Task>() {
@Override
public Task fun(GithubIssue issue) {
return createTask(issue);
}
});
}
@NotNull
private Task createTask(final GithubIssue issue) {
return new Task() {
@NotNull String myRepoName = getRepoName();
@Override
public boolean isIssue() {
return true;
}
@Override
public String getIssueUrl() {
return issue.getHtmlUrl();
}
@NotNull
@Override
public String getId() {
return myRepoName + "-" + issue.getNumber();
}
@NotNull
@Override
public String getSummary() {
return issue.getTitle();
}
public String getDescription() {
return issue.getBody();
}
@NotNull
@Override
public Comment[] getComments() {
try {
return fetchComments(issue.getNumber());
}
catch (Exception e) {
LOG.warn("Error fetching comments for " + issue.getNumber(), e);
return Comment.EMPTY_ARRAY;
}
}
@NotNull
@Override
public Icon getIcon() {
return TasksIcons.Github;
}
@NotNull
@Override
public TaskType getType() {
return TaskType.BUG;
}
@Override
public Date getUpdated() {
return issue.getUpdatedAt();
}
@Override
public Date getCreated() {
return issue.getCreatedAt();
}
@Override
public boolean isClosed() {
return !"open".equals(issue.getState());
}
@Override
public TaskRepository getRepository() {
return GithubRepository.this;
}
@Override
public String getPresentableName() {
return getId() + ": " + getSummary();
}
};
}
private Comment[] fetchComments(final long id) throws Exception {
List<GithubIssueComment> result = GithubApiUtil.getIssueComments(getAuthData(), getRepoAuthor(), getRepoName(), id);
return ContainerUtil.map2Array(result, Comment.class, new Function<GithubIssueComment, Comment>() {
@Override
public Comment fun(GithubIssueComment comment) {
return new GithubComment(comment.getCreatedAt(), comment.getUser().getLogin(), comment.getBodyHtml(), comment.getUser().getGravatarId(),
comment.getUser().getHtmlUrl());
}
});
}
@Nullable
public String extractId(String taskName) {
Matcher matcher = myPattern.matcher(taskName);
return matcher.find() ? matcher.group(1) : null;
}
@Nullable
@Override
public Task findTask(String id) throws Exception {
return createTask(GithubApiUtil.getIssue(getAuthData(), getRepoAuthor(), getRepoName(), id));
}
@Override
public BaseRepository clone() {
return new GithubRepository(this);
}
public String getRepoName() {
return myRepoName;
}
public void setRepoName(String repoName) {
myRepoName = repoName;
myPattern = Pattern.compile("(" + StringUtil.escapeToRegexp(repoName) + "\\-\\d+):\\s+");
}
public String getRepoAuthor() {
return !StringUtil.isEmpty(myRepoAuthor) ? myRepoAuthor : getUsername();
}
public void setRepoAuthor(String repoAuthor) {
myRepoAuthor = repoAuthor;
}
public String getUser() {
return myUser;
}
public void setUser(String user) {
myUser = user;
}
@Transient
public String getToken() {
return myToken;
}
public void setToken(@NotNull String token) {
myToken = token;
}
@Tag("token")
public String getEncodedToken() {
return PasswordUtil.encodePassword(getToken());
}
public void setEncodedToken(String password) {
try {
setToken(PasswordUtil.decodePassword(password));
}
catch (NumberFormatException e) {
LOG.warn("Can't decode token", e);
}
}
private GithubAuthData getAuthData() {
return GithubAuthData.createTokenAuth(getUrl(), getToken());
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) return false;
if (!(o instanceof GithubRepository)) return false;
GithubRepository that = (GithubRepository)o;
if (!Comparing.equal(getRepoAuthor(), that.getRepoAuthor())) return false;
if (!Comparing.equal(getRepoName(), that.getRepoName())) return false;
if (!Comparing.equal(getToken(), that.getToken())) return false;
return true;
}
@Override
protected int getFeatures() {
return BASIC_HTTP_AUTHORIZATION;
}
}
|
Github: add @NotNull
|
plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepository.java
|
Github: add @NotNull
|
|
Java
|
apache-2.0
|
cbec4ba29bddb027619e7e2c58ad53388b0569dc
| 0
|
vvv1559/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,signed/intellij-community,caot/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,da1z/intellij-community,da1z/intellij-community,caot/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,consulo/consulo,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,blademainer/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,izonder/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,consulo/consulo,asedunov/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,xfournet/intellij-community,mglukhikh/intellij-community,ernestp/consulo,ibinti/intellij-community,vvv1559/intellij-community,slisson/intellij-community,slisson/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,robovm/robovm-studio,adedayo/intellij-community,da1z/intellij-community,samthor/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,jexp/idea2,ahb0327/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,asedunov/intellij-community,consulo/consulo,salguarnieri/intellij-community,kool79/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,izonder/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,clumsy/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,clumsy/intellij-community,semonte/intellij-community,allotria/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,blademainer/intellij-community,signed/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,izonder/intellij-community,samthor/intellij-community,izonder/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,fitermay/intellij-community,ernestp/consulo,xfournet/intellij-community,gnuhub/intellij-community,allotria/intellij-community,fitermay/intellij-community,retomerz/intellij-community,izonder/intellij-community,wreckJ/intellij-community,jexp/idea2,blademainer/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,holmes/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,vladmm/intellij-community,slisson/intellij-community,holmes/intellij-community,clumsy/intellij-community,holmes/intellij-community,apixandru/intellij-community,supersven/intellij-community,ibinti/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,diorcety/intellij-community,dslomov/intellij-community,xfournet/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,adedayo/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,slisson/intellij-community,kool79/intellij-community,diorcety/intellij-community,ibinti/intellij-community,jagguli/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,dslomov/intellij-community,vladmm/intellij-community,jagguli/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,supersven/intellij-community,tmpgit/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,signed/intellij-community,diorcety/intellij-community,petteyg/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,holmes/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ryano144/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,fnouama/intellij-community,semonte/intellij-community,akosyakov/intellij-community,semonte/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,signed/intellij-community,FHannes/intellij-community,da1z/intellij-community,da1z/intellij-community,signed/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,kool79/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,semonte/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,allotria/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,diorcety/intellij-community,signed/intellij-community,allotria/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,adedayo/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,retomerz/intellij-community,holmes/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,SerCeMan/intellij-community,consulo/consulo,dslomov/intellij-community,consulo/consulo,ftomassetti/intellij-community,vvv1559/intellij-community,supersven/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,fitermay/intellij-community,jexp/idea2,adedayo/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ryano144/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,caot/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,ibinti/intellij-community,da1z/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,caot/intellij-community,suncycheng/intellij-community,slisson/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,caot/intellij-community,samthor/intellij-community,izonder/intellij-community,jexp/idea2,FHannes/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,petteyg/intellij-community,apixandru/intellij-community,xfournet/intellij-community,kool79/intellij-community,supersven/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,fitermay/intellij-community,samthor/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,kdwink/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,robovm/robovm-studio,vladmm/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,kdwink/intellij-community,signed/intellij-community,caot/intellij-community,clumsy/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,clumsy/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,clumsy/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,jexp/idea2,MER-GROUP/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,signed/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,gnuhub/intellij-community,ernestp/consulo,retomerz/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,suncycheng/intellij-community,semonte/intellij-community,izonder/intellij-community,akosyakov/intellij-community,caot/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,jexp/idea2,orekyuu/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,asedunov/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,caot/intellij-community,samthor/intellij-community,jagguli/intellij-community,izonder/intellij-community,hurricup/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,joewalnes/idea-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,supersven/intellij-community,petteyg/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,dslomov/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,asedunov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,supersven/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,allotria/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,diorcety/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,ernestp/consulo,da1z/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,caot/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,slisson/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,supersven/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,ibinti/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ibinti/intellij-community,samthor/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,retomerz/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,signed/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,slisson/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,slisson/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,vladmm/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,jexp/idea2,mglukhikh/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,kdwink/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,robovm/robovm-studio,semonte/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,consulo/consulo,SerCeMan/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,adedayo/intellij-community,diorcety/intellij-community,kdwink/intellij-community,fnouama/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,fitermay/intellij-community,signed/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,caot/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,retomerz/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,hurricup/intellij-community,caot/intellij-community,xfournet/intellij-community,allotria/intellij-community,ryano144/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,vladmm/intellij-community,jexp/idea2,xfournet/intellij-community
|
package org.jetbrains.idea.maven.core;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.embedder.*;
import org.apache.maven.extension.ExtensionManager;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.ComponentDescriptor;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.core.util.JDOMReader;
import org.jetbrains.idea.maven.project.MavenException;
import org.jetbrains.idea.maven.project.MavenToIdeaMapping;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MavenFactory {
private static final Logger LOG = Logger.getInstance("#" + MavenFactory.class.getName());
@NonNls private static final String PROP_MAVEN_HOME = "maven.home";
@NonNls private static final String PROP_USER_HOME = "user.home";
@NonNls private static final String ENV_M2_HOME = "M2_HOME";
@NonNls private static final String M2_DIR = "m2";
@NonNls private static final String BIN_DIR = "bin";
@NonNls private static final String DOT_M2_DIR = ".m2";
@NonNls private static final String CONF_DIR = "conf";
@NonNls private static final String SETTINGS_FILE = "settings.xml";
@NonNls private static final String M2_CONF_FILE = "m2.conf";
@NonNls private static final String REPOSITORY_DIR = "repository";
@NonNls private static final String LOCAL_REPOSITORY_TAG = "localRepository";
@NonNls private static final String[] standardPhases = {"clean", "compile", "test", "package", "install", "site"};
@NonNls private static final String[] standardGoals = {"clean", "validate", "generate-sources", "process-sources", "generate-resources",
"process-resources", "compile", "process-classes", "generate-test-sources", "process-test-sources", "generate-test-resources",
"process-test-resources", "test-compile", "test", "package", "pre-integration-test", "integration-test", "post-integration-test",
"verify", "install", "site", "deploy"};
@Nullable
public static File resolveMavenHomeDirectory(@Nullable final String override) {
if (!StringUtil.isEmptyOrSpaces(override)) {
return new File(override);
}
final String m2home = System.getenv(ENV_M2_HOME);
if (!StringUtil.isEmptyOrSpaces(m2home)) {
final File homeFromEnv = new File(m2home);
if (isValidMavenHome(homeFromEnv)) {
return homeFromEnv;
}
}
final String userHome = System.getProperty(PROP_USER_HOME);
if (!StringUtil.isEmptyOrSpaces(userHome)) {
final File underUserHome = new File(userHome, M2_DIR);
if (isValidMavenHome(underUserHome)) {
return underUserHome;
}
}
return null;
}
public static boolean isValidMavenHome(File home) {
return getMavenConfFile(home).exists();
}
public static File getMavenConfFile(File mavenHome) {
return new File(new File(mavenHome, BIN_DIR), M2_CONF_FILE);
}
@Nullable
public static File resolveGlobalSettingsFile(final String override) {
final File directory = resolveMavenHomeDirectory(override);
if (directory != null) {
final File file = new File(new File(directory, CONF_DIR), SETTINGS_FILE);
if (file.exists()) {
return file;
}
}
return null;
}
@Nullable
public static File resolveUserSettingsFile(final String override) {
if (!StringUtil.isEmptyOrSpaces(override)) {
return new File(override);
}
final String userHome = System.getProperty(PROP_USER_HOME);
if (!StringUtil.isEmptyOrSpaces(userHome)) {
final File file = new File(new File(userHome, DOT_M2_DIR), SETTINGS_FILE);
if (file.exists()) {
return file;
}
}
return null;
}
@Nullable
public static File resolveLocalRepository(final String mavenHome, final String userSettings, final String override) {
if (!StringUtil.isEmpty(override)) {
return new File(override);
}
final File userSettingsFile = resolveUserSettingsFile(userSettings);
if (userSettingsFile != null) {
final String fromUserSettings = MavenFactory.getRepositoryFromSettings(userSettingsFile);
if (!StringUtil.isEmpty(fromUserSettings)) {
return new File(fromUserSettings);
}
}
final File globalSettingsFile = resolveGlobalSettingsFile(mavenHome);
if (globalSettingsFile != null) {
final String fromGlobalSettings = MavenFactory.getRepositoryFromSettings(globalSettingsFile);
if (!StringUtil.isEmpty(fromGlobalSettings)) {
return new File(fromGlobalSettings);
}
}
final String userHome = System.getProperty(PROP_USER_HOME);
if (!StringUtil.isEmptyOrSpaces(userHome)) {
return new File(new File(userHome, DOT_M2_DIR), REPOSITORY_DIR);
}
return null;
}
public static String getRepositoryFromSettings(File file) {
JDOMReader reader = new JDOMReader();
try {
reader.init(new FileInputStream(file));
}
catch (IOException ignore) {
}
return reader.getChildText(reader.getRootElement(), LOCAL_REPOSITORY_TAG);
}
public static List<String> getStandardPhasesList() {
return Arrays.asList(standardPhases);
}
public static List<String> getStandardGoalsList() {
return Arrays.asList(standardGoals);
}
public static MavenEmbedder createEmbedderForExecute(MavenCoreSettings settings) throws MavenException {
return createEmbedder(settings, null);
}
public static MavenEmbedder createEmbedderForRead(MavenCoreSettings settings) throws MavenException {
return createEmbedder(settings, new EmbedderCustomizer(null));
}
public static MavenEmbedder createEmbedderForResolve(MavenCoreSettings settings, MavenToIdeaMapping mapping) throws MavenException {
return createEmbedder(settings, new EmbedderCustomizer(mapping));
}
private static MavenEmbedder createEmbedder(MavenCoreSettings settings, EmbedderCustomizer customizer) throws MavenException {
return createEmbedder(settings.getMavenHome(), settings.getEffectiveLocalRepository(), settings.getMavenSettingsFile(),
settings.getClass().getClassLoader(), customizer);
}
private static MavenEmbedder createEmbedder(String mavenHome,
File localRepo,
String userSettings,
ClassLoader classLoader,
EmbedderCustomizer customizer) throws MavenException {
Configuration configuration = new DefaultConfiguration();
configuration.setConfigurationCustomizer(customizer);
configuration.setClassLoader(classLoader);
configuration.setLocalRepository(localRepo);
MavenEmbedderConsoleLogger l = new MavenEmbedderConsoleLogger();
l.setThreshold(MavenEmbedderLogger.LEVEL_WARN);
configuration.setMavenEmbedderLogger(l);
File userSettingsFile = resolveUserSettingsFile(userSettings);
if (userSettingsFile != null) {
configuration.setUserSettingsFile(userSettingsFile);
}
File globalSettingsFile = resolveGlobalSettingsFile(mavenHome);
if (globalSettingsFile != null) {
configuration.setGlobalSettingsFile(globalSettingsFile);
}
validate(configuration);
System.setProperty(PROP_MAVEN_HOME, mavenHome);
try {
MavenEmbedder result = new MavenEmbedder(configuration);
if (customizer != null) {
customizer.postCustomize(result);
}
return result;
}
catch (MavenEmbedderException e) {
LOG.info(e);
throw new MavenException(e);
}
}
private static void validate(Configuration configuration) throws MavenException {
ConfigurationValidationResult result = MavenEmbedder.validateConfiguration(configuration);
if (!result.isValid()) {
List<Exception> ee = new ArrayList<Exception>();
Exception ex1 = result.getGlobalSettingsException();
Exception ex2 = result.getUserSettingsException();
if (ex1 != null) ee.add(ex1);
if (ex2 != null) ee.add(ex2);
throw new MavenException(ee);
}
}
public static void releaseEmbedder(MavenEmbedder mavenEmbedder) {
if (mavenEmbedder != null) {
try {
mavenEmbedder.stop();
}
catch (MavenEmbedderException ignore) {
}
}
}
public static CustomExtensionManager getExtensionManager(MavenEmbedder e) {
try {
return (CustomExtensionManager)e.getPlexusContainer().lookup(ExtensionManager.class.getName());
}
catch (ComponentLookupException ex) {
throw new RuntimeException(ex);
}
}
private static class EmbedderCustomizer implements ContainerCustomizer {
private MavenToIdeaMapping myMapping;
public EmbedderCustomizer(MavenToIdeaMapping mapping) {
myMapping = mapping;
}
public void customize(PlexusContainer c) {
ComponentDescriptor d = c.getComponentDescriptor(ArtifactResolver.ROLE);
d.setImplementation(CustomArtifactResolver.class.getName());
d = c.getComponentDescriptor(ExtensionManager.class.getName());
d.setImplementation(CustomExtensionManager.class.getName());
}
public void postCustomize(MavenEmbedder e) {
try {
CustomArtifactResolver r = (CustomArtifactResolver)e.getPlexusContainer().lookup(ArtifactResolver.ROLE);
r.setMapping(myMapping);
}
catch (ComponentLookupException ex) {
throw new RuntimeException(ex);
}
}
}
}
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/core/MavenFactory.java
|
package org.jetbrains.idea.maven.core;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.embedder.*;
import org.apache.maven.extension.ExtensionManager;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.ComponentDescriptor;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.core.util.JDOMReader;
import org.jetbrains.idea.maven.project.MavenException;
import org.jetbrains.idea.maven.project.MavenToIdeaMapping;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MavenFactory {
private static final Logger LOG = Logger.getInstance("#" + MavenFactory.class.getName());
@NonNls private static final String PROP_MAVEN_HOME = "maven.home";
@NonNls private static final String PROP_USER_HOME = "user.home";
@NonNls private static final String ENV_M2_HOME = "M2_HOME";
@NonNls private static final String M2_DIR = "m2";
@NonNls private static final String BIN_DIR = "bin";
@NonNls private static final String DOT_M2_DIR = ".m2";
@NonNls private static final String CONF_DIR = "conf";
@NonNls private static final String SETTINGS_FILE = "settings.xml";
@NonNls private static final String M2_CONF_FILE = "m2.conf";
@NonNls private static final String REPOSITORY_DIR = "repository";
@NonNls private static final String LOCAL_REPOSITORY_TAG = "localRepository";
@NonNls private static final String[] standardPhases = {"clean", "compile", "test", "package", "install", "site"};
@NonNls private static final String[] standardGoals = {"clean", "validate", "generate-sources", "process-sources", "generate-resources",
"process-resources", "compile", "process-classes", "generate-test-sources", "process-test-sources", "generate-test-resources",
"process-test-resources", "test-compile", "test", "package", "pre-integration-test", "integration-test", "post-integration-test",
"verify", "install", "site", "deploy"};
@Nullable
public static File resolveMavenHomeDirectory(@Nullable final String override) {
if (!StringUtil.isEmptyOrSpaces(override)) {
return new File(override);
}
final String m2home = System.getenv(ENV_M2_HOME);
if (!StringUtil.isEmptyOrSpaces(m2home)) {
final File homeFromEnv = new File(m2home);
if (isValidMavenHome(homeFromEnv)) {
return homeFromEnv;
}
}
final String userHome = System.getProperty(PROP_USER_HOME);
if (!StringUtil.isEmptyOrSpaces(userHome)) {
final File underUserHome = new File(userHome, M2_DIR);
if (isValidMavenHome(underUserHome)) {
return underUserHome;
}
}
return null;
}
public static boolean isValidMavenHome(File home) {
return getMavenConfFile(home).exists();
}
public static File getMavenConfFile(File mavenHome) {
return new File(new File(mavenHome, BIN_DIR), M2_CONF_FILE);
}
@Nullable
public static File resolveGlobalSettingsFile(final String override) {
final File directory = resolveMavenHomeDirectory(override);
if (directory != null) {
final File file = new File(new File(directory, CONF_DIR), SETTINGS_FILE);
if (file.exists()) {
return file;
}
}
return null;
}
@Nullable
public static File resolveUserSettingsFile(final String override) {
if (!StringUtil.isEmptyOrSpaces(override)) {
return new File(override);
}
final String userHome = System.getProperty(PROP_USER_HOME);
if (!StringUtil.isEmptyOrSpaces(userHome)) {
final File file = new File(new File(userHome, DOT_M2_DIR), SETTINGS_FILE);
if (file.exists()) {
return file;
}
}
return null;
}
@Nullable
public static File resolveLocalRepository(final String mavenHome, final String userSettings, final String override) {
if (!StringUtil.isEmpty(override)) {
return new File(override);
}
final File userSettingsFile = resolveUserSettingsFile(userSettings);
if (userSettingsFile != null) {
final String fromUserSettings = MavenFactory.getRepositoryFromSettings(userSettingsFile);
if (!StringUtil.isEmpty(fromUserSettings)) {
return new File(fromUserSettings);
}
}
final File globalSettingsFile = resolveGlobalSettingsFile(mavenHome);
if (globalSettingsFile != null) {
final String fromGlobalSettings = MavenFactory.getRepositoryFromSettings(globalSettingsFile);
if (!StringUtil.isEmpty(fromGlobalSettings)) {
return new File(fromGlobalSettings);
}
}
final String userHome = System.getProperty(PROP_USER_HOME);
if (!StringUtil.isEmptyOrSpaces(userHome)) {
return new File(new File(userHome, DOT_M2_DIR), REPOSITORY_DIR);
}
return null;
}
public static String getRepositoryFromSettings(File file) {
JDOMReader reader = new JDOMReader();
try {
reader.init(new FileInputStream(file));
}
catch (IOException ignore) {
}
return reader.getChildText(reader.getRootElement(), LOCAL_REPOSITORY_TAG);
}
public static List<String> getStandardPhasesList() {
return Arrays.asList(standardPhases);
}
public static List<String> getStandardGoalsList() {
return Arrays.asList(standardGoals);
}
public static MavenEmbedder createEmbedderForExecute(MavenCoreSettings settings) throws MavenException {
return createEmbedder(settings, null);
}
public static MavenEmbedder createEmbedderForRead(MavenCoreSettings settings) throws MavenException {
return createEmbedder(settings, new CustomizerForRead());
}
public static MavenEmbedder createEmbedderForResolve(MavenCoreSettings settings, MavenToIdeaMapping mapping) throws MavenException {
return createEmbedder(settings, new CustomizerForResolve(mapping));
}
private static MavenEmbedder createEmbedder(MavenCoreSettings settings, CustomizerForRead customizer) throws MavenException {
return createEmbedder(settings.getMavenHome(),
settings.getEffectiveLocalRepository(),
settings.getMavenSettingsFile(),
settings.getClass().getClassLoader(),
customizer);
}
private static MavenEmbedder createEmbedder(String mavenHome,
File localRepo,
String userSettings,
ClassLoader classLoader,
CustomizerForRead customizer) throws MavenException {
Configuration configuration = new DefaultConfiguration();
configuration.setConfigurationCustomizer(customizer);
configuration.setClassLoader(classLoader);
configuration.setLocalRepository(localRepo);
MavenEmbedderConsoleLogger l = new MavenEmbedderConsoleLogger();
l.setThreshold(MavenEmbedderLogger.LEVEL_WARN);
configuration.setMavenEmbedderLogger(l);
File userSettingsFile = resolveUserSettingsFile(userSettings);
if (userSettingsFile != null) {
configuration.setUserSettingsFile(userSettingsFile);
}
File globalSettingsFile = resolveGlobalSettingsFile(mavenHome);
if (globalSettingsFile != null) {
configuration.setGlobalSettingsFile(globalSettingsFile);
}
validate(configuration);
System.setProperty(PROP_MAVEN_HOME, mavenHome);
try {
MavenEmbedder result = new MavenEmbedder(configuration);
if (customizer != null) {
customizer.postCustomize(result);
}
return result;
}
catch (MavenEmbedderException e) {
LOG.info(e);
throw new MavenException(e);
}
}
private static void validate(Configuration configuration) throws MavenException {
ConfigurationValidationResult result = MavenEmbedder.validateConfiguration(configuration);
if (!result.isValid()) {
List<Exception> ee = new ArrayList<Exception>();
Exception ex1 = result.getGlobalSettingsException();
Exception ex2 = result.getUserSettingsException();
if (ex1 != null) ee.add(ex1);
if (ex2 != null) ee.add(ex2);
throw new MavenException(ee);
}
}
public static void releaseEmbedder(MavenEmbedder mavenEmbedder) {
if (mavenEmbedder != null) {
try {
mavenEmbedder.stop();
}
catch (MavenEmbedderException ignore) {
}
}
}
public static CustomExtensionManager getExtensionManager(MavenEmbedder e) {
try {
return (CustomExtensionManager)e.getPlexusContainer().lookup(ExtensionManager.class.getName());
}
catch (ComponentLookupException ex) {
throw new RuntimeException(ex);
}
}
public static class CustomizerForRead implements ContainerCustomizer {
public void customize(PlexusContainer c) {
ComponentDescriptor d = c.getComponentDescriptor(ExtensionManager.class.getName());
d.setImplementation(CustomExtensionManager.class.getName());
}
public void postCustomize(MavenEmbedder e) {
}
}
private static class CustomizerForResolve extends CustomizerForRead {
private MavenToIdeaMapping myMapping;
public CustomizerForResolve(MavenToIdeaMapping mapping) {
myMapping = mapping;
}
@Override
public void customize(PlexusContainer c) {
super.customize(c);
ComponentDescriptor d = c.getComponentDescriptor(ArtifactResolver.ROLE);
d.setImplementation(CustomArtifactResolver.class.getName());
}
@Override
public void postCustomize(MavenEmbedder e) {
try {
CustomArtifactResolver r = (CustomArtifactResolver)e.getPlexusContainer().lookup(ArtifactResolver.ROLE);
r.setMapping(myMapping);
}
catch (ComponentLookupException ex) {
throw new RuntimeException(ex);
}
}
}
}
|
Maven: artifact resolution optimization
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/core/MavenFactory.java
|
Maven: artifact resolution optimization
|
|
Java
|
apache-2.0
|
8e751349329ccfdef1584affaf851f4aa0915274
| 0
|
you21979/bitcoinj,schildbach/bitcoinj,HashEngineering/dashj,tjth/bitcoinj-lotterycoin,framewr/bitcoinj,HashEngineering/dashj,HashEngineering/digitalcoinj,peterdettman/bitcoinj,rnicoll/bitcoinj,greenaddress/bitcoinj,tjth/bitcoinj-lotterycoin,Enigmachine/btcjwork2,jife94/bitcoinj,janko33bd/bitcoinj,HashEngineering/digitalcoinj,natzei/bitcoinj,langerhans/dogecoinj-new,rootstock/bitcoinj,you21979/bitcoinj,therightwaystudio/fork_bitcoinj,kmels/bitcoinj,oscarguindzberg/bitcoinj,jdojff/bitcoinj,schildbach/bitcoinj,HashEngineering/darkcoinj,veritaseum/bitcoinj,dalbelap/bitcoinj,designsters/android-fork-bitcoinj,patricklodder/bitcoinj,HashEngineering/dashj,veritaseum/bitcoinj,MrDunne/bitcoinj,stonecoldpat/bitcoinj,HashEngineering/groestlcoinj,kurtwalker/bitcoinj,tangyves/bitcoinj,patricklodder/bitcoinj,akonring/bitcoinj_generous,GroestlCoin/groestlcoinj,stonecoldpat/bitcoinj,oscarguindzberg/bitcoinj,marctrem/bitcoinj,tangyves/bitcoinj,imzhuli/bitcoinj,dcw312/bitcoinj,bitsquare/bitcoinj,kurtwalker/bitcoinj,kurtwalker/bitcoinj,cpacia/bitcoinj,kmels/bitcoinj,janko33bd/bitcoinj,jdojff/bitcoinj,GroestlCoin/groestlcoinj,bitcoinj/bitcoinj,szdx/bitcoinj,langerhans/bitcoinj-alice-hd,veritaseum/bitcoinj,cpacia/bitcoinj,yenliangl/bitcoinj,dexX7/bitcoinj,cpacia/bitcoinj,you21979/bitcoinj,GroestlCoin/groestlcoinj,HashEngineering/darkcoinj,natzei/bitcoinj,haxwell/bitcoinj,blockchain/bitcoinj,HashEngineering/digitalcoinj,HashEngineering/groestlcoinj,jife94/bitcoinj,HashEngineering/dashj,jdojff/bitcoinj,peacekeeper/bitcoinj,tangyves/bitcoinj,tjth/bitcoinj-lotterycoin,patricklodder/bitcoinj,haxwell/bitcoinj,strawpay/bitcoinj,peterdettman/bitcoinj,VishalRao/bitcoinj,jife94/bitcoinj,nikileshsa/bitcoinj,bitcoinj/bitcoinj,HashEngineering/darkcoinj,HashEngineering/groestlcoinj,paulminer/bitcoinj,yenliangl/bitcoinj,stonecoldpat/bitcoinj,haxwell/bitcoinj
|
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.protocols.channels;
import org.bitcoinj.core.*;
import org.bitcoinj.store.WalletProtobufSerializer;
import org.bitcoinj.testing.TestWithWallet;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.WalletFiles;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.protobuf.ByteString;
import org.bitcoin.paymentchannel.Protos;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spongycastle.crypto.params.KeyParameter;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.bitcoinj.core.Coin.*;
import static org.bitcoinj.protocols.channels.PaymentChannelCloseException.CloseReason;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock;
import static org.bitcoin.paymentchannel.Protos.TwoWayChannelMessage.MessageType;
import static org.junit.Assert.*;
public class ChannelConnectionTest extends TestWithWallet {
private static final int CLIENT_MAJOR_VERSION = 1;
private Wallet serverWallet;
private AtomicBoolean fail;
private BlockingQueue<Transaction> broadcasts;
private TransactionBroadcaster mockBroadcaster;
private Semaphore broadcastTxPause;
private static final TransactionBroadcaster failBroadcaster = new TransactionBroadcaster() {
@Override
public TransactionBroadcast broadcastTransaction(Transaction tx) {
fail();
return null;
}
};
@Override
@Before
public void setUp() throws Exception {
super.setUp();
Utils.setMockClock(); // Use mock clock
sendMoneyToWallet(COIN, AbstractBlockChain.NewBlockType.BEST_CHAIN);
sendMoneyToWallet(COIN, AbstractBlockChain.NewBlockType.BEST_CHAIN);
wallet.addExtension(new StoredPaymentChannelClientStates(wallet, failBroadcaster));
serverWallet = new Wallet(params);
serverWallet.addExtension(new StoredPaymentChannelServerStates(serverWallet, failBroadcaster));
serverWallet.freshReceiveKey();
// Use an atomic boolean to indicate failure because fail()/assert*() dont work in network threads
fail = new AtomicBoolean(false);
// Set up a way to monitor broadcast transactions. When you expect a broadcast, you must release a permit
// to the broadcastTxPause semaphore so state can be queried in between.
broadcasts = new LinkedBlockingQueue<Transaction>();
broadcastTxPause = new Semaphore(0);
mockBroadcaster = new TransactionBroadcaster() {
@Override
public TransactionBroadcast broadcastTransaction(Transaction tx) {
broadcastTxPause.acquireUninterruptibly();
SettableFuture<Transaction> future = SettableFuture.create();
future.set(tx);
broadcasts.add(tx);
return TransactionBroadcast.createMockBroadcast(tx, future);
}
};
// Because there are no separate threads in the tests here (we call back into client/server in server/client
// handlers), we have lots of lock cycles. A normal user shouldn't have this issue as they are probably not both
// client+server running in the same thread.
Threading.warnOnLockCycles();
ECKey.FAKE_SIGNATURES = true;
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
ECKey.FAKE_SIGNATURES = false;
}
@After
public void checkFail() {
assertFalse(fail.get());
Threading.throwOnLockCycles();
}
@Test
public void testSimpleChannel() throws Exception {
exectuteSimpleChannelTest(null);
}
@Test
public void testEncryptedClientWallet() throws Exception {
// Encrypt the client wallet
String mySecretPw = "MySecret";
wallet.encrypt(mySecretPw);
KeyParameter userKeySetup = wallet.getKeyCrypter().deriveKey(mySecretPw);
exectuteSimpleChannelTest(userKeySetup);
}
public void exectuteSimpleChannelTest(KeyParameter userKeySetup) throws Exception {
// Test with network code and without any issues. We'll broadcast two txns: multisig contract and settle transaction.
final SettableFuture<ListenableFuture<PaymentChannelServerState>> serverCloseFuture = SettableFuture.create();
final SettableFuture<Sha256Hash> channelOpenFuture = SettableFuture.create();
final BlockingQueue<ChannelTestUtils.UpdatePair> q = new LinkedBlockingQueue<ChannelTestUtils.UpdatePair>();
final PaymentChannelServerListener server = new PaymentChannelServerListener(mockBroadcaster, serverWallet, 30, COIN,
new PaymentChannelServerListener.HandlerFactory() {
@Nullable
@Override
public ServerConnectionEventHandler onNewConnection(SocketAddress clientAddress) {
return new ServerConnectionEventHandler() {
@Override
public void channelOpen(Sha256Hash channelId) {
channelOpenFuture.set(channelId);
}
@Override
public ListenableFuture<ByteString> paymentIncrease(Coin by, Coin to, ByteString info) {
q.add(new ChannelTestUtils.UpdatePair(to, info));
return Futures.immediateFuture(info);
}
@Override
public void channelClosed(CloseReason reason) {
serverCloseFuture.set(null);
}
};
}
});
server.bindAndStart(4243);
PaymentChannelClientConnection client = new PaymentChannelClientConnection(
new InetSocketAddress("localhost", 4243), 30, wallet, myKey, COIN, "", PaymentChannelClient.DEFAULT_TIME_WINDOW, userKeySetup);
// Wait for the multi-sig tx to be transmitted.
broadcastTxPause.release();
Transaction broadcastMultiSig = broadcasts.take();
// Wait for the channel to finish opening.
client.getChannelOpenFuture().get();
assertEquals(broadcastMultiSig.getHash(), channelOpenFuture.get());
assertEquals(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE, client.state().getValueSpent());
// Set up an autosave listener to make sure the server is saving the wallet after each payment increase.
final CountDownLatch latch = new CountDownLatch(3); // Expect 3 calls.
File tempFile = File.createTempFile("channel_connection_test", ".wallet");
tempFile.deleteOnExit();
serverWallet.autosaveToFile(tempFile, 0, TimeUnit.SECONDS, new WalletFiles.Listener() {
@Override
public void onBeforeAutoSave(File tempFile) {
latch.countDown();
}
@Override
public void onAfterAutoSave(File newlySavedFile) {
}
});
Thread.sleep(1250); // No timeouts once the channel is open
Coin amount = client.state().getValueSpent();
q.take().assertPair(amount, null);
for (String info : new String[] {null, "one", "two"} ) {
final ByteString bytes = (info==null) ? null :ByteString.copyFromUtf8(info);
final PaymentIncrementAck ack = client.incrementPayment(CENT, bytes, userKeySetup).get();
if (info != null) {
final ByteString ackInfo = ack.getInfo();
assertNotNull("Ack info is null", ackInfo);
assertEquals("Ack info differs ", info, ackInfo.toStringUtf8());
}
amount = amount.add(CENT);
q.take().assertPair(amount, bytes);
}
latch.await();
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)serverWallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
StoredServerChannel storedServerChannel = channels.getChannel(broadcastMultiSig.getHash());
PaymentChannelServerState serverState = storedServerChannel.getOrCreateState(serverWallet, mockBroadcaster);
// Check that you can call settle multiple times with no exceptions.
client.settle();
client.settle();
broadcastTxPause.release();
Transaction settleTx = broadcasts.take();
assertEquals(PaymentChannelServerState.State.CLOSED, serverState.getState());
if (!serverState.getBestValueToMe().equals(amount) || !serverState.getFeePaid().equals(Coin.ZERO))
fail();
assertTrue(channels.mapChannels.isEmpty());
// Send the settle TX to the client wallet.
sendMoneyToWallet(settleTx, AbstractBlockChain.NewBlockType.BEST_CHAIN);
assertEquals(PaymentChannelClientState.State.CLOSED, client.state().getState());
server.close();
server.close();
// Now confirm the settle TX and see if the channel deletes itself from the wallet.
assertEquals(1, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
wallet.notifyNewBestBlock(createFakeBlock(blockStore).storedBlock);
assertEquals(1, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
wallet.notifyNewBestBlock(createFakeBlock(blockStore).storedBlock);
assertEquals(0, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
}
@Test
public void testServerErrorHandling() throws Exception {
// Gives the server crap and checks proper error responses are sent.
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
PaymentChannelServer server = pair.server;
server.connectionOpen();
client.connectionOpen();
// Make sure we get back a BAD_TRANSACTION if we send a bogus refund transaction.
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND);
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.PROVIDE_REFUND)
.setProvideRefund(
Protos.ProvideRefund.newBuilder(msg.getProvideRefund())
.setMultisigKey(ByteString.EMPTY)
.setTx(ByteString.EMPTY)
).build());
final Protos.TwoWayChannelMessage errorMsg = pair.serverRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(Protos.Error.ErrorCode.BAD_TRANSACTION, errorMsg.getError().getCode());
// Make sure the server closes the socket on CLOSE
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
server = pair.server;
server.connectionOpen();
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.settle();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLOSE));
assertEquals(CloseReason.CLIENT_REQUESTED_CLOSE, pair.serverRecorder.q.take());
// Make sure the server closes the socket on ERROR
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
server = pair.server;
server.connectionOpen();
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.ERROR)
.setError(Protos.Error.newBuilder().setCode(Protos.Error.ErrorCode.TIMEOUT))
.build());
assertEquals(CloseReason.REMOTE_SENT_ERROR, pair.serverRecorder.q.take());
}
@Test
public void testChannelResume() throws Exception {
// Tests various aspects of channel resuming.
Utils.setMockClock();
final Sha256Hash someServerId = Sha256Hash.create(new byte[]{});
// Open up a normal channel.
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
final Protos.TwoWayChannelMessage initiateMsg = pair.serverRecorder.checkNextMsg(MessageType.INITIATE);
Coin minPayment = Coin.valueOf(initiateMsg.getInitiate().getMinPayment());
client.receiveMessage(initiateMsg);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
assertEquals(minPayment, client.state().getValueSpent());
// Send a bitcent.
Coin amount = minPayment.add(CENT);
client.incrementPayment(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
assertEquals(amount, ((ChannelTestUtils.UpdatePair)pair.serverRecorder.q.take()).amount);
server.close();
server.connectionClosed();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CLOSE));
client.connectionClosed();
assertFalse(client.connectionOpen);
// There is now an inactive open channel worth COIN-CENT + minPayment with id Sha256.create(new byte[] {})
StoredPaymentChannelClientStates clientStoredChannels =
(StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
assertEquals(1, clientStoredChannels.mapChannels.size());
assertFalse(clientStoredChannels.mapChannels.values().iterator().next().active);
// Check that server-side won't attempt to reopen a nonexistent channel (it will tell the client to re-initiate
// instead).
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
pair.server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(Sha256Hash.create(new byte[]{0x03}).getBytes()))
.setMajor(CLIENT_MAJOR_VERSION).setMinor(42))
.build());
pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
pair.serverRecorder.checkNextMsg(MessageType.INITIATE);
// Now reopen/resume the channel after round-tripping the wallets.
wallet = roundTripClientWallet(wallet);
serverWallet = roundTripServerWallet(serverWallet);
clientStoredChannels =
(StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Check the contract hash is sent on the wire correctly.
final Protos.TwoWayChannelMessage clientVersionMsg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertTrue(clientVersionMsg.getClientVersion().hasPreviousChannelContractHash());
assertEquals(contractHash, new Sha256Hash(clientVersionMsg.getClientVersion().getPreviousChannelContractHash().toByteArray()));
server.receiveMessage(clientVersionMsg);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
assertEquals(contractHash, pair.serverRecorder.q.take());
pair.clientRecorder.checkOpened();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
// Send another bitcent and check 2 were received in total.
client.incrementPayment(CENT);
amount = amount.add(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.checkTotalPayment(amount);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
PaymentChannelClient openClient = client;
ChannelTestUtils.RecordingPair openPair = pair;
// Now open up a new client with the same id and make sure the server disconnects the previous client.
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Check that no prev contract hash is sent on the wire the client notices it's already in use by another
// client attached to the same wallet and refuses to resume.
{
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
}
// Make sure the server allows two simultaneous opens. It will close the first and allow resumption of the second.
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Swap out the clients version message for a custom one that tries to resume ...
pair.clientRecorder.getNextMsg();
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(contractHash.getBytes()))
.setMajor(CLIENT_MAJOR_VERSION).setMinor(42))
.build());
// We get the usual resume sequence.
pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN);
// Verify the previous one was closed.
openPair.serverRecorder.checkNextMsg(MessageType.CLOSE);
assertTrue(clientStoredChannels.getChannel(someServerId, contractHash).active);
// And finally close the first channel too.
openClient.connectionClosed();
assertFalse(clientStoredChannels.getChannel(someServerId, contractHash).active);
// Now roll the mock clock and recreate the client object so that it removes the channels and announces refunds.
assertEquals(86640, clientStoredChannels.getSecondsUntilExpiry(someServerId));
Utils.rollMockClock(60 * 60 * 24 + 60 * 5); // Client announces refund 5 minutes after expire time
StoredPaymentChannelClientStates newClientStates = new StoredPaymentChannelClientStates(wallet, mockBroadcaster);
newClientStates.deserializeWalletExtension(wallet, clientStoredChannels.serializeWalletExtension());
broadcastTxPause.release();
assertTrue(broadcasts.take().getOutput(0).getScriptPubKey().isSentToMultiSig());
broadcastTxPause.release();
assertEquals(TransactionConfidence.Source.SELF, broadcasts.take().getConfidence().getSource());
assertTrue(broadcasts.isEmpty());
assertTrue(newClientStates.mapChannels.isEmpty());
// Server also knows it's too late.
StoredPaymentChannelServerStates serverStoredChannels = new StoredPaymentChannelServerStates(serverWallet, mockBroadcaster);
Thread.sleep(2000); // TODO: Fix this stupid hack.
assertTrue(serverStoredChannels.mapChannels.isEmpty());
}
private static Wallet roundTripClientWallet(Wallet wallet) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, bos);
org.bitcoinj.wallet.Protos.Wallet proto = WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray()));
StoredPaymentChannelClientStates state = new StoredPaymentChannelClientStates(null, failBroadcaster);
return new WalletProtobufSerializer().readWallet(wallet.getParams(), new WalletExtension[] { state }, proto);
}
private static Wallet roundTripServerWallet(Wallet wallet) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, bos);
StoredPaymentChannelServerStates state = new StoredPaymentChannelServerStates(null, failBroadcaster);
org.bitcoinj.wallet.Protos.Wallet proto = WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray()));
return new WalletProtobufSerializer().readWallet(wallet.getParams(), new WalletExtension[] { state }, proto);
}
@Test
public void testBadResumeHash() throws InterruptedException {
// Check that server-side will reject incorrectly formatted hashes. If anything goes wrong with session resume,
// then the server will start the opening of a new channel automatically, so we expect to see INITIATE here.
ChannelTestUtils.RecordingPair srv =
ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
srv.server.connectionOpen();
srv.server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(new byte[]{0x00, 0x01}))
.setMajor(CLIENT_MAJOR_VERSION).setMinor(42))
.build());
srv.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
srv.serverRecorder.checkNextMsg(MessageType.INITIATE);
assertTrue(srv.serverRecorder.q.isEmpty());
}
@Test
public void testClientUnknownVersion() throws Exception {
// Tests client rejects unknown version
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setServerVersion(Protos.ServerVersion.newBuilder().setMajor(-1))
.setType(MessageType.SERVER_VERSION).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.NO_ACCEPTABLE_VERSION, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(Coin.SATOSHI);
fail();
} catch (IllegalStateException e) { }
}
@Test
public void testClientTimeWindowUnacceptable() throws Exception {
// Tests that clients reject too large time windows
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster, 100);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds() + 60 * 60 * 48)
.setMinAcceptedChannelSize(100)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.MIN_NONDUST_OUTPUT.value))
.setType(MessageType.INITIATE).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.TIME_WINDOW_UNACCEPTABLE, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(Coin.SATOSHI);
fail();
} catch (IllegalStateException e) { }
}
@Test
public void testValuesAreRespected() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(COIN.add(SATOSHI).value)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.MIN_NONDUST_OUTPUT.value))
.setType(MessageType.INITIATE).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.SERVER_REQUESTED_TOO_MUCH_VALUE, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(Coin.SATOSHI);
fail();
} catch (IllegalStateException e) { }
// Now check that if the server has a lower min size than what we are willing to spend, we do actually open
// a channel of that size.
sendMoneyToWallet(COIN.multiply(10), AbstractBlockChain.NewBlockType.BEST_CHAIN);
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
server = pair.server;
final Coin myValue = COIN.multiply(10);
client = new PaymentChannelClient(wallet, myKey, myValue, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(COIN.add(SATOSHI).value)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value))
.setType(MessageType.INITIATE).build());
final Protos.TwoWayChannelMessage provideRefund = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND);
Transaction refund = new Transaction(params, provideRefund.getProvideRefund().getTx().toByteArray());
assertEquals(myValue, refund.getOutput(0).getValue());
}
@Test
public void testEmptyWallet() throws Exception {
Wallet emptyWallet = new Wallet(params);
emptyWallet.freshReceiveKey();
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(emptyWallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
try {
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(CENT.value)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value))
.setType(MessageType.INITIATE).build());
fail();
} catch (InsufficientMoneyException expected) {
// This should be thrown.
}
}
@Test
public void testClientRefusesNonCanonicalKey() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
Protos.TwoWayChannelMessage.Builder initiateMsg = Protos.TwoWayChannelMessage.newBuilder(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
ByteString brokenKey = initiateMsg.getInitiate().getMultisigKey();
brokenKey = ByteString.copyFrom(Arrays.copyOf(brokenKey.toByteArray(), brokenKey.size() + 1));
initiateMsg.getInitiateBuilder().setMultisigKey(brokenKey);
client.receiveMessage(initiateMsg.build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testClientResumeNothing() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CHANNEL_OPEN).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testClientRandomMessage() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
// Send a CLIENT_VERSION back to the client - ?!?!!
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION).build());
Protos.TwoWayChannelMessage error = pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(Protos.Error.ErrorCode.SYNTAX_ERROR, error.getError().getCode());
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testDontResumeEmptyChannels() throws Exception {
// Check that if the client has an empty channel that's being kept around in case we need to broadcast the
// refund, we don't accidentally try to resume it).
// Open up a normal channel.
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
// Send the whole channel at once. The server will broadcast the final contract and settle the channel for us.
client.incrementPayment(client.state().getValueRefunded());
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
broadcasts.take();
// The channel is now empty.
assertEquals(Coin.ZERO, client.state().getValueRefunded());
pair.serverRecorder.q.take(); // Take the Coin.
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CLOSE));
assertEquals(CloseReason.SERVER_REQUESTED_CLOSE, pair.clientRecorder.q.take());
client.connectionClosed();
// Now try opening a new channel with the same server ID and verify the client asks for a new channel.
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
client.connectionOpen();
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
}
@Test
public void repeatedChannels() throws Exception {
// Ensures we're selecting channels correctly. Covers a bug in which we'd always try and fail to resume
// the first channel due to lack of proper closing behaviour.
// Open up a normal channel, but don't spend all of it, then settle it.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
for (int i = 0; i < 3; i++) {
ListenableFuture<PaymentIncrementAck> future = client.incrementPayment(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.q.take();
final Protos.TwoWayChannelMessage msg = pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK);
final Protos.PaymentAck paymentAck = msg.getPaymentAck();
assertTrue("No PaymentAck.Info", paymentAck.hasInfo());
assertEquals("Wrong PaymentAck info", ByteString.copyFromUtf8(CENT.toPlainString()), paymentAck.getInfo());
client.receiveMessage(msg);
assertTrue(future.isDone());
final PaymentIncrementAck paymentIncrementAck = future.get();
assertEquals("Wrong value returned from increasePayment", CENT, paymentIncrementAck.getValue());
assertEquals("Wrong info returned from increasePayment", ByteString.copyFromUtf8(CENT.toPlainString()), paymentIncrementAck.getInfo());
}
// Settle it and verify it's considered to be settled.
broadcastTxPause.release();
client.settle();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLOSE));
Transaction settlement1 = broadcasts.take();
// Server sends back the settle TX it just broadcast.
final Protos.TwoWayChannelMessage closeMsg = pair.serverRecorder.checkNextMsg(MessageType.CLOSE);
final Transaction settlement2 = new Transaction(params, closeMsg.getSettlement().getTx().toByteArray());
assertEquals(settlement1, settlement2);
client.receiveMessage(closeMsg);
assertNotNull(wallet.getTransaction(settlement2.getHash())); // Close TX entered the wallet.
sendMoneyToWallet(settlement1, AbstractBlockChain.NewBlockType.BEST_CHAIN);
client.connectionClosed();
server.connectionClosed();
}
// Now open a second channel and don't spend all of it/don't settle it.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
final Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
server.receiveMessage(msg);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
client.incrementPayment(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
client.connectionClosed();
server.connectionClosed();
}
// Now connect again and check we resume the second channel.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
}
assertEquals(2, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
}
}
|
core/src/test/java/org/bitcoinj/protocols/channels/ChannelConnectionTest.java
|
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bitcoinj.protocols.channels;
import org.bitcoinj.core.*;
import org.bitcoinj.store.WalletProtobufSerializer;
import org.bitcoinj.testing.TestWithWallet;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.WalletFiles;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.protobuf.ByteString;
import org.bitcoin.paymentchannel.Protos;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spongycastle.crypto.params.KeyParameter;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Arrays;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.bitcoinj.core.Coin.*;
import static org.bitcoinj.protocols.channels.PaymentChannelCloseException.CloseReason;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock;
import static org.bitcoin.paymentchannel.Protos.TwoWayChannelMessage.MessageType;
import static org.junit.Assert.*;
public class ChannelConnectionTest extends TestWithWallet {
private static final int CLIENT_MAJOR_VERSION = 1;
private Wallet serverWallet;
private BlockChain serverChain;
private AtomicBoolean fail;
private BlockingQueue<Transaction> broadcasts;
private TransactionBroadcaster mockBroadcaster;
private Semaphore broadcastTxPause;
private static final TransactionBroadcaster failBroadcaster = new TransactionBroadcaster() {
@Override
public TransactionBroadcast broadcastTransaction(Transaction tx) {
fail();
return null;
}
};
@Override
@Before
public void setUp() throws Exception {
super.setUp();
Utils.setMockClock(); // Use mock clock
sendMoneyToWallet(COIN, AbstractBlockChain.NewBlockType.BEST_CHAIN);
sendMoneyToWallet(COIN, AbstractBlockChain.NewBlockType.BEST_CHAIN);
wallet.addExtension(new StoredPaymentChannelClientStates(wallet, failBroadcaster));
serverWallet = new Wallet(params);
serverWallet.addExtension(new StoredPaymentChannelServerStates(serverWallet, failBroadcaster));
serverWallet.freshReceiveKey();
serverChain = new BlockChain(params, serverWallet, blockStore);
// Use an atomic boolean to indicate failure because fail()/assert*() dont work in network threads
fail = new AtomicBoolean(false);
// Set up a way to monitor broadcast transactions. When you expect a broadcast, you must release a permit
// to the broadcastTxPause semaphore so state can be queried in between.
broadcasts = new LinkedBlockingQueue<Transaction>();
broadcastTxPause = new Semaphore(0);
mockBroadcaster = new TransactionBroadcaster() {
@Override
public TransactionBroadcast broadcastTransaction(Transaction tx) {
broadcastTxPause.acquireUninterruptibly();
SettableFuture<Transaction> future = SettableFuture.create();
future.set(tx);
broadcasts.add(tx);
return TransactionBroadcast.createMockBroadcast(tx, future);
}
};
// Because there are no separate threads in the tests here (we call back into client/server in server/client
// handlers), we have lots of lock cycles. A normal user shouldn't have this issue as they are probably not both
// client+server running in the same thread.
Threading.warnOnLockCycles();
ECKey.FAKE_SIGNATURES = true;
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
ECKey.FAKE_SIGNATURES = false;
}
@After
public void checkFail() {
assertFalse(fail.get());
Threading.throwOnLockCycles();
}
@Test
public void testSimpleChannel() throws Exception {
exectuteSimpleChannelTest(null);
}
@Test
public void testEncryptedClientWallet() throws Exception {
// Encrypt the client wallet
String mySecretPw = "MySecret";
wallet.encrypt(mySecretPw);
KeyParameter userKeySetup = wallet.getKeyCrypter().deriveKey(mySecretPw);
exectuteSimpleChannelTest(userKeySetup);
}
public void exectuteSimpleChannelTest(KeyParameter userKeySetup) throws Exception {
// Test with network code and without any issues. We'll broadcast two txns: multisig contract and settle transaction.
final SettableFuture<ListenableFuture<PaymentChannelServerState>> serverCloseFuture = SettableFuture.create();
final SettableFuture<Sha256Hash> channelOpenFuture = SettableFuture.create();
final BlockingQueue<ChannelTestUtils.UpdatePair> q = new LinkedBlockingQueue<ChannelTestUtils.UpdatePair>();
final PaymentChannelServerListener server = new PaymentChannelServerListener(mockBroadcaster, serverWallet, 30, COIN,
new PaymentChannelServerListener.HandlerFactory() {
@Nullable
@Override
public ServerConnectionEventHandler onNewConnection(SocketAddress clientAddress) {
return new ServerConnectionEventHandler() {
@Override
public void channelOpen(Sha256Hash channelId) {
channelOpenFuture.set(channelId);
}
@Override
public ListenableFuture<ByteString> paymentIncrease(Coin by, Coin to, ByteString info) {
q.add(new ChannelTestUtils.UpdatePair(to, info));
return Futures.immediateFuture(info);
}
@Override
public void channelClosed(CloseReason reason) {
serverCloseFuture.set(null);
}
};
}
});
server.bindAndStart(4243);
PaymentChannelClientConnection client = new PaymentChannelClientConnection(
new InetSocketAddress("localhost", 4243), 30, wallet, myKey, COIN, "", PaymentChannelClient.DEFAULT_TIME_WINDOW, userKeySetup);
// Wait for the multi-sig tx to be transmitted.
broadcastTxPause.release();
Transaction broadcastMultiSig = broadcasts.take();
// Wait for the channel to finish opening.
client.getChannelOpenFuture().get();
assertEquals(broadcastMultiSig.getHash(), channelOpenFuture.get());
assertEquals(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE, client.state().getValueSpent());
// Set up an autosave listener to make sure the server is saving the wallet after each payment increase.
final CountDownLatch latch = new CountDownLatch(3); // Expect 3 calls.
File tempFile = File.createTempFile("channel_connection_test", ".wallet");
tempFile.deleteOnExit();
serverWallet.autosaveToFile(tempFile, 0, TimeUnit.SECONDS, new WalletFiles.Listener() {
@Override
public void onBeforeAutoSave(File tempFile) {
latch.countDown();
}
@Override
public void onAfterAutoSave(File newlySavedFile) {
}
});
Thread.sleep(1250); // No timeouts once the channel is open
Coin amount = client.state().getValueSpent();
q.take().assertPair(amount, null);
for (String info : new String[] {null, "one", "two"} ) {
final ByteString bytes = (info==null) ? null :ByteString.copyFromUtf8(info);
final PaymentIncrementAck ack = client.incrementPayment(CENT, bytes, userKeySetup).get();
if (info != null) {
final ByteString ackInfo = ack.getInfo();
assertNotNull("Ack info is null", ackInfo);
assertEquals("Ack info differs ", info, ackInfo.toStringUtf8());
}
amount = amount.add(CENT);
q.take().assertPair(amount, bytes);
}
latch.await();
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)serverWallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
StoredServerChannel storedServerChannel = channels.getChannel(broadcastMultiSig.getHash());
PaymentChannelServerState serverState = storedServerChannel.getOrCreateState(serverWallet, mockBroadcaster);
// Check that you can call settle multiple times with no exceptions.
client.settle();
client.settle();
broadcastTxPause.release();
Transaction settleTx = broadcasts.take();
assertEquals(PaymentChannelServerState.State.CLOSED, serverState.getState());
if (!serverState.getBestValueToMe().equals(amount) || !serverState.getFeePaid().equals(Coin.ZERO))
fail();
assertTrue(channels.mapChannels.isEmpty());
// Send the settle TX to the client wallet.
sendMoneyToWallet(settleTx, AbstractBlockChain.NewBlockType.BEST_CHAIN);
assertEquals(PaymentChannelClientState.State.CLOSED, client.state().getState());
server.close();
server.close();
// Now confirm the settle TX and see if the channel deletes itself from the wallet.
assertEquals(1, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
wallet.notifyNewBestBlock(createFakeBlock(blockStore).storedBlock);
assertEquals(1, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
wallet.notifyNewBestBlock(createFakeBlock(blockStore).storedBlock);
assertEquals(0, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
}
@Test
public void testServerErrorHandling() throws Exception {
// Gives the server crap and checks proper error responses are sent.
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
PaymentChannelServer server = pair.server;
server.connectionOpen();
client.connectionOpen();
// Make sure we get back a BAD_TRANSACTION if we send a bogus refund transaction.
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND);
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.PROVIDE_REFUND)
.setProvideRefund(
Protos.ProvideRefund.newBuilder(msg.getProvideRefund())
.setMultisigKey(ByteString.EMPTY)
.setTx(ByteString.EMPTY)
).build());
final Protos.TwoWayChannelMessage errorMsg = pair.serverRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(Protos.Error.ErrorCode.BAD_TRANSACTION, errorMsg.getError().getCode());
// Make sure the server closes the socket on CLOSE
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
server = pair.server;
server.connectionOpen();
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.settle();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLOSE));
assertEquals(CloseReason.CLIENT_REQUESTED_CLOSE, pair.serverRecorder.q.take());
// Make sure the server closes the socket on ERROR
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
server = pair.server;
server.connectionOpen();
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.ERROR)
.setError(Protos.Error.newBuilder().setCode(Protos.Error.ErrorCode.TIMEOUT))
.build());
assertEquals(CloseReason.REMOTE_SENT_ERROR, pair.serverRecorder.q.take());
}
@Test
public void testChannelResume() throws Exception {
// Tests various aspects of channel resuming.
Utils.setMockClock();
final Sha256Hash someServerId = Sha256Hash.create(new byte[]{});
// Open up a normal channel.
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
final Protos.TwoWayChannelMessage initiateMsg = pair.serverRecorder.checkNextMsg(MessageType.INITIATE);
Coin minPayment = Coin.valueOf(initiateMsg.getInitiate().getMinPayment());
client.receiveMessage(initiateMsg);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
assertEquals(minPayment, client.state().getValueSpent());
// Send a bitcent.
Coin amount = minPayment.add(CENT);
client.incrementPayment(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
assertEquals(amount, ((ChannelTestUtils.UpdatePair)pair.serverRecorder.q.take()).amount);
server.close();
server.connectionClosed();
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CLOSE));
client.connectionClosed();
assertFalse(client.connectionOpen);
// There is now an inactive open channel worth COIN-CENT + minPayment with id Sha256.create(new byte[] {})
StoredPaymentChannelClientStates clientStoredChannels =
(StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
assertEquals(1, clientStoredChannels.mapChannels.size());
assertFalse(clientStoredChannels.mapChannels.values().iterator().next().active);
// Check that server-side won't attempt to reopen a nonexistent channel (it will tell the client to re-initiate
// instead).
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
pair.server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(Sha256Hash.create(new byte[]{0x03}).getBytes()))
.setMajor(CLIENT_MAJOR_VERSION).setMinor(42))
.build());
pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
pair.serverRecorder.checkNextMsg(MessageType.INITIATE);
// Now reopen/resume the channel after round-tripping the wallets.
wallet = roundTripClientWallet(wallet);
serverWallet = roundTripServerWallet(serverWallet);
clientStoredChannels =
(StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Check the contract hash is sent on the wire correctly.
final Protos.TwoWayChannelMessage clientVersionMsg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertTrue(clientVersionMsg.getClientVersion().hasPreviousChannelContractHash());
assertEquals(contractHash, new Sha256Hash(clientVersionMsg.getClientVersion().getPreviousChannelContractHash().toByteArray()));
server.receiveMessage(clientVersionMsg);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
assertEquals(contractHash, pair.serverRecorder.q.take());
pair.clientRecorder.checkOpened();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
// Send another bitcent and check 2 were received in total.
client.incrementPayment(CENT);
amount = amount.add(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.checkTotalPayment(amount);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
PaymentChannelClient openClient = client;
ChannelTestUtils.RecordingPair openPair = pair;
// Now open up a new client with the same id and make sure the server disconnects the previous client.
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Check that no prev contract hash is sent on the wire the client notices it's already in use by another
// client attached to the same wallet and refuses to resume.
{
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
}
// Make sure the server allows two simultaneous opens. It will close the first and allow resumption of the second.
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
server = pair.server;
client.connectionOpen();
server.connectionOpen();
// Swap out the clients version message for a custom one that tries to resume ...
pair.clientRecorder.getNextMsg();
server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(contractHash.getBytes()))
.setMajor(CLIENT_MAJOR_VERSION).setMinor(42))
.build());
// We get the usual resume sequence.
pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN);
// Verify the previous one was closed.
openPair.serverRecorder.checkNextMsg(MessageType.CLOSE);
assertTrue(clientStoredChannels.getChannel(someServerId, contractHash).active);
// And finally close the first channel too.
openClient.connectionClosed();
assertFalse(clientStoredChannels.getChannel(someServerId, contractHash).active);
// Now roll the mock clock and recreate the client object so that it removes the channels and announces refunds.
assertEquals(86640, clientStoredChannels.getSecondsUntilExpiry(someServerId));
Utils.rollMockClock(60 * 60 * 24 + 60 * 5); // Client announces refund 5 minutes after expire time
StoredPaymentChannelClientStates newClientStates = new StoredPaymentChannelClientStates(wallet, mockBroadcaster);
newClientStates.deserializeWalletExtension(wallet, clientStoredChannels.serializeWalletExtension());
broadcastTxPause.release();
assertTrue(broadcasts.take().getOutput(0).getScriptPubKey().isSentToMultiSig());
broadcastTxPause.release();
assertEquals(TransactionConfidence.Source.SELF, broadcasts.take().getConfidence().getSource());
assertTrue(broadcasts.isEmpty());
assertTrue(newClientStates.mapChannels.isEmpty());
// Server also knows it's too late.
StoredPaymentChannelServerStates serverStoredChannels = new StoredPaymentChannelServerStates(serverWallet, mockBroadcaster);
Thread.sleep(2000); // TODO: Fix this stupid hack.
assertTrue(serverStoredChannels.mapChannels.isEmpty());
}
private static Wallet roundTripClientWallet(Wallet wallet) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, bos);
org.bitcoinj.wallet.Protos.Wallet proto = WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray()));
StoredPaymentChannelClientStates state = new StoredPaymentChannelClientStates(null, failBroadcaster);
return new WalletProtobufSerializer().readWallet(wallet.getParams(), new WalletExtension[] { state }, proto);
}
private static Wallet roundTripServerWallet(Wallet wallet) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, bos);
StoredPaymentChannelServerStates state = new StoredPaymentChannelServerStates(null, failBroadcaster);
org.bitcoinj.wallet.Protos.Wallet proto = WalletProtobufSerializer.parseToProto(new ByteArrayInputStream(bos.toByteArray()));
return new WalletProtobufSerializer().readWallet(wallet.getParams(), new WalletExtension[] { state }, proto);
}
@Test
public void testBadResumeHash() throws InterruptedException {
// Check that server-side will reject incorrectly formatted hashes. If anything goes wrong with session resume,
// then the server will start the opening of a new channel automatically, so we expect to see INITIATE here.
ChannelTestUtils.RecordingPair srv =
ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
srv.server.connectionOpen();
srv.server.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION)
.setClientVersion(Protos.ClientVersion.newBuilder()
.setPreviousChannelContractHash(ByteString.copyFrom(new byte[]{0x00, 0x01}))
.setMajor(CLIENT_MAJOR_VERSION).setMinor(42))
.build());
srv.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION);
srv.serverRecorder.checkNextMsg(MessageType.INITIATE);
assertTrue(srv.serverRecorder.q.isEmpty());
}
@Test
public void testClientUnknownVersion() throws Exception {
// Tests client rejects unknown version
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setServerVersion(Protos.ServerVersion.newBuilder().setMajor(-1))
.setType(MessageType.SERVER_VERSION).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.NO_ACCEPTABLE_VERSION, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(Coin.SATOSHI);
fail();
} catch (IllegalStateException e) { }
}
@Test
public void testClientTimeWindowUnacceptable() throws Exception {
// Tests that clients reject too large time windows
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster, 100);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds() + 60 * 60 * 48)
.setMinAcceptedChannelSize(100)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.MIN_NONDUST_OUTPUT.value))
.setType(MessageType.INITIATE).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.TIME_WINDOW_UNACCEPTABLE, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(Coin.SATOSHI);
fail();
} catch (IllegalStateException e) { }
}
@Test
public void testValuesAreRespected() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(COIN.add(SATOSHI).value)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.MIN_NONDUST_OUTPUT.value))
.setType(MessageType.INITIATE).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.SERVER_REQUESTED_TOO_MUCH_VALUE, pair.clientRecorder.q.take());
// Double-check that we cant do anything that requires an open channel
try {
client.incrementPayment(Coin.SATOSHI);
fail();
} catch (IllegalStateException e) { }
// Now check that if the server has a lower min size than what we are willing to spend, we do actually open
// a channel of that size.
sendMoneyToWallet(COIN.multiply(10), AbstractBlockChain.NewBlockType.BEST_CHAIN);
pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
server = pair.server;
final Coin myValue = COIN.multiply(10);
client = new PaymentChannelClient(wallet, myKey, myValue, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(COIN.add(SATOSHI).value)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value))
.setType(MessageType.INITIATE).build());
final Protos.TwoWayChannelMessage provideRefund = pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND);
Transaction refund = new Transaction(params, provideRefund.getProvideRefund().getTx().toByteArray());
assertEquals(myValue, refund.getOutput(0).getValue());
}
@Test
public void testEmptyWallet() throws Exception {
Wallet emptyWallet = new Wallet(params);
emptyWallet.freshReceiveKey();
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(emptyWallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
try {
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(Protos.Initiate.newBuilder().setExpireTimeSecs(Utils.currentTimeSeconds())
.setMinAcceptedChannelSize(CENT.value)
.setMultisigKey(ByteString.copyFrom(new ECKey().getPubKey()))
.setMinPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.value))
.setType(MessageType.INITIATE).build());
fail();
} catch (InsufficientMoneyException expected) {
// This should be thrown.
}
}
@Test
public void testClientRefusesNonCanonicalKey() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
Protos.TwoWayChannelMessage.Builder initiateMsg = Protos.TwoWayChannelMessage.newBuilder(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
ByteString brokenKey = initiateMsg.getInitiate().getMultisigKey();
brokenKey = ByteString.copyFrom(Arrays.copyOf(brokenKey.toByteArray(), brokenKey.size() + 1));
initiateMsg.getInitiateBuilder().setMultisigKey(brokenKey);
client.receiveMessage(initiateMsg.build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testClientResumeNothing() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelServer server = pair.server;
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
server.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CHANNEL_OPEN).build());
pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testClientRandomMessage() throws Exception {
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, Sha256Hash.ZERO_HASH, pair.clientRecorder);
client.connectionOpen();
pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
// Send a CLIENT_VERSION back to the client - ?!?!!
client.receiveMessage(Protos.TwoWayChannelMessage.newBuilder()
.setType(MessageType.CLIENT_VERSION).build());
Protos.TwoWayChannelMessage error = pair.clientRecorder.checkNextMsg(MessageType.ERROR);
assertEquals(Protos.Error.ErrorCode.SYNTAX_ERROR, error.getError().getCode());
assertEquals(CloseReason.REMOTE_SENT_INVALID_MESSAGE, pair.clientRecorder.q.take());
}
@Test
public void testDontResumeEmptyChannels() throws Exception {
// Check that if the client has an empty channel that's being kept around in case we need to broadcast the
// refund, we don't accidentally try to resume it).
// Open up a normal channel.
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
// Send the whole channel at once. The server will broadcast the final contract and settle the channel for us.
client.incrementPayment(client.state().getValueRefunded());
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
broadcasts.take();
// The channel is now empty.
assertEquals(Coin.ZERO, client.state().getValueRefunded());
pair.serverRecorder.q.take(); // Take the Coin.
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CLOSE));
assertEquals(CloseReason.SERVER_REQUESTED_CLOSE, pair.clientRecorder.q.take());
client.connectionClosed();
// Now try opening a new channel with the same server ID and verify the client asks for a new channel.
client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
client.connectionOpen();
Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
}
@Test
public void repeatedChannels() throws Exception {
// Ensures we're selecting channels correctly. Covers a bug in which we'd always try and fail to resume
// the first channel due to lack of proper closing behaviour.
// Open up a normal channel, but don't spend all of it, then settle it.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
for (int i = 0; i < 3; i++) {
ListenableFuture<PaymentIncrementAck> future = client.incrementPayment(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
pair.serverRecorder.q.take();
final Protos.TwoWayChannelMessage msg = pair.serverRecorder.checkNextMsg(MessageType.PAYMENT_ACK);
final Protos.PaymentAck paymentAck = msg.getPaymentAck();
assertTrue("No PaymentAck.Info", paymentAck.hasInfo());
assertEquals("Wrong PaymentAck info", ByteString.copyFromUtf8(CENT.toPlainString()), paymentAck.getInfo());
client.receiveMessage(msg);
assertTrue(future.isDone());
final PaymentIncrementAck paymentIncrementAck = future.get();
assertEquals("Wrong value returned from increasePayment", CENT, paymentIncrementAck.getValue());
assertEquals("Wrong info returned from increasePayment", ByteString.copyFromUtf8(CENT.toPlainString()), paymentIncrementAck.getInfo());
}
// Settle it and verify it's considered to be settled.
broadcastTxPause.release();
client.settle();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLOSE));
Transaction settlement1 = broadcasts.take();
// Server sends back the settle TX it just broadcast.
final Protos.TwoWayChannelMessage closeMsg = pair.serverRecorder.checkNextMsg(MessageType.CLOSE);
final Transaction settlement2 = new Transaction(params, closeMsg.getSettlement().getTx().toByteArray());
assertEquals(settlement1, settlement2);
client.receiveMessage(closeMsg);
assertNotNull(wallet.getTransaction(settlement2.getHash())); // Close TX entered the wallet.
sendMoneyToWallet(settlement1, AbstractBlockChain.NewBlockType.BEST_CHAIN);
client.connectionClosed();
server.connectionClosed();
}
// Now open a second channel and don't spend all of it/don't settle it.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
final Protos.TwoWayChannelMessage msg = pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION);
assertFalse(msg.getClientVersion().hasPreviousChannelContractHash());
server.receiveMessage(msg);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.INITIATE));
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_REFUND));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.RETURN_REFUND));
broadcastTxPause.release();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.PROVIDE_CONTRACT));
broadcasts.take();
pair.serverRecorder.checkTotalPayment(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
Sha256Hash contractHash = (Sha256Hash) pair.serverRecorder.q.take();
pair.clientRecorder.checkInitiated();
assertNull(pair.serverRecorder.q.poll());
assertNull(pair.clientRecorder.q.poll());
client.incrementPayment(CENT);
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.UPDATE_PAYMENT));
client.connectionClosed();
server.connectionClosed();
}
// Now connect again and check we resume the second channel.
{
Sha256Hash someServerId = Sha256Hash.ZERO_HASH;
ChannelTestUtils.RecordingPair pair = ChannelTestUtils.makeRecorders(serverWallet, mockBroadcaster);
pair.server.connectionOpen();
PaymentChannelClient client = new PaymentChannelClient(wallet, myKey, COIN, someServerId, pair.clientRecorder);
PaymentChannelServer server = pair.server;
client.connectionOpen();
server.receiveMessage(pair.clientRecorder.checkNextMsg(MessageType.CLIENT_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.SERVER_VERSION));
client.receiveMessage(pair.serverRecorder.checkNextMsg(MessageType.CHANNEL_OPEN));
}
assertEquals(2, StoredPaymentChannelClientStates.getFromWallet(wallet).mapChannels.size());
}
}
|
ChannelConnectionTest: Delete unused field.
|
core/src/test/java/org/bitcoinj/protocols/channels/ChannelConnectionTest.java
|
ChannelConnectionTest: Delete unused field.
|
|
Java
|
apache-2.0
|
6b6e2e19a7731e91d19ac3e82ef6f8bf5c41e2d1
| 0
|
MER-GROUP/intellij-community,kool79/intellij-community,signed/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,holmes/intellij-community,FHannes/intellij-community,semonte/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,jagguli/intellij-community,dslomov/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,ernestp/consulo,pwoodworth/intellij-community,semonte/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,consulo/consulo,nicolargo/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,hurricup/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,retomerz/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,caot/intellij-community,izonder/intellij-community,caot/intellij-community,fnouama/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,allotria/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,caot/intellij-community,ernestp/consulo,ibinti/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,izonder/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ryano144/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ahb0327/intellij-community,signed/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,allotria/intellij-community,slisson/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ernestp/consulo,ryano144/intellij-community,samthor/intellij-community,petteyg/intellij-community,signed/intellij-community,kool79/intellij-community,Distrotech/intellij-community,izonder/intellij-community,xfournet/intellij-community,izonder/intellij-community,retomerz/intellij-community,consulo/consulo,blademainer/intellij-community,holmes/intellij-community,allotria/intellij-community,signed/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,apixandru/intellij-community,kdwink/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,consulo/consulo,diorcety/intellij-community,slisson/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,signed/intellij-community,diorcety/intellij-community,izonder/intellij-community,ibinti/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,diorcety/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fnouama/intellij-community,diorcety/intellij-community,consulo/consulo,da1z/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,da1z/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,vladmm/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,signed/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,dslomov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,hurricup/intellij-community,robovm/robovm-studio,supersven/intellij-community,fitermay/intellij-community,asedunov/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,apixandru/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,samthor/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,vladmm/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,semonte/intellij-community,vladmm/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,blademainer/intellij-community,petteyg/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,kdwink/intellij-community,signed/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,pwoodworth/intellij-community,ernestp/consulo,SerCeMan/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,supersven/intellij-community,petteyg/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,holmes/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,da1z/intellij-community,hurricup/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,clumsy/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,caot/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,izonder/intellij-community,jagguli/intellij-community,robovm/robovm-studio,apixandru/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,holmes/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,apixandru/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,adedayo/intellij-community,FHannes/intellij-community,signed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,fitermay/intellij-community,consulo/consulo,allotria/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,fnouama/intellij-community,supersven/intellij-community,adedayo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,holmes/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,apixandru/intellij-community,fitermay/intellij-community,diorcety/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,holmes/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,gnuhub/intellij-community,kool79/intellij-community,signed/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,kdwink/intellij-community,supersven/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,slisson/intellij-community,youdonghai/intellij-community,da1z/intellij-community,kdwink/intellij-community,izonder/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ryano144/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,izonder/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,signed/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,semonte/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,kdwink/intellij-community,hurricup/intellij-community,retomerz/intellij-community,amith01994/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,da1z/intellij-community,retomerz/intellij-community,signed/intellij-community,clumsy/intellij-community,consulo/consulo,caot/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ibinti/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,da1z/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,kdwink/intellij-community,dslomov/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,fnouama/intellij-community,xfournet/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,caot/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,semonte/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,fnouama/intellij-community,mglukhikh/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,orekyuu/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,izonder/intellij-community,fitermay/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,holmes/intellij-community,fitermay/intellij-community,blademainer/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,xfournet/intellij-community,asedunov/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,retomerz/intellij-community,dslomov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vladmm/intellij-community,xfournet/intellij-community,supersven/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,jagguli/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,blademainer/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,kdwink/intellij-community,ernestp/consulo,suncycheng/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,semonte/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,dslomov/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ahb0327/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,kool79/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,samthor/intellij-community,kool79/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,retomerz/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.fileEditor.impl;
import com.intellij.lang.properties.charset.Native2AsciiCharset;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.BinaryFileDecompiler;
import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingRegistry;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
public final class LoadTextUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.LoadTextUtil");
private static final Key<String> DETECTED_LINE_SEPARATOR_KEY = Key.create("DETECTED_LINE_SEPARATOR_KEY");
private LoadTextUtil() {
}
@NotNull
private static Pair<CharSequence, String> convertLineSeparators(@NotNull CharBuffer buffer) {
int dst = 0;
char prev = ' ';
int crCount = 0;
int lfCount = 0;
int crlfCount = 0;
final int length = buffer.length();
final char[] bufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer);
for (int src = 0; src < length; src++) {
char c = bufferArray != null ? bufferArray[src]:buffer.charAt(src);
switch (c) {
case '\r':
if(bufferArray != null) bufferArray[dst++] = '\n';
else buffer.put(dst++, '\n');
crCount++;
break;
case '\n':
if (prev == '\r') {
crCount--;
crlfCount++;
}
else {
if(bufferArray != null) bufferArray[dst++] = '\n';
else buffer.put(dst++, '\n');
lfCount++;
}
break;
default:
if(bufferArray != null) bufferArray[dst++] = c;
else buffer.put(dst++, c);
break;
}
prev = c;
}
String detectedLineSeparator = null;
if (crlfCount > crCount && crlfCount > lfCount) {
detectedLineSeparator = "\r\n";
}
else if (crCount > lfCount) {
detectedLineSeparator = "\r";
}
else if (lfCount > 0) {
detectedLineSeparator = "\n";
}
CharSequence result = buffer.length() == dst ? buffer : buffer.subSequence(0, dst);
return Pair.create(result, detectedLineSeparator);
}
private static Charset detectCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
if (virtualFile.isCharsetSet()) return virtualFile.getCharset();
Charset charset = doDetectCharset(virtualFile, content);
charset = charset == null ? EncodingRegistry.getInstance().getDefaultCharset() : charset;
if (EncodingRegistry.getInstance().isNative2Ascii(virtualFile)) {
charset = Native2AsciiCharset.wrap(charset);
}
virtualFile.setCharset(charset);
return charset;
}
@NotNull
public static Charset detectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
return doDetectCharsetAndSetBOM(virtualFile, content).getFirst();
}
@NotNull
private static Pair<Charset, byte[]> doDetectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
Charset charset = detectCharset(virtualFile, content);
Pair<Charset,byte[]> bomAndCharset = getBOMAndCharset(content, charset);
final byte[] bom = bomAndCharset.second;
if (bom.length != 0) {
virtualFile.setBOM(bom);
}
return bomAndCharset;
}
private static Charset doDetectCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
Trinity<Charset,CharsetToolkit.GuessedEncoding, byte[]> guessed = guessFromContent(virtualFile, content, content.length);
if (guessed != null && guessed.first != null) return guessed.first;
FileType fileType = virtualFile.getFileType();
String charsetName = fileType.getCharset(virtualFile, content);
if (charsetName == null) {
Charset saved = EncodingRegistry.getInstance().getEncoding(virtualFile, true);
if (saved != null) return saved;
}
return CharsetToolkit.forName(charsetName);
}
@Nullable("null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
public static Trinity<Charset, CharsetToolkit.GuessedEncoding,byte[]> guessFromContent(VirtualFile virtualFile, byte[] content, int length) {
EncodingRegistry settings = EncodingRegistry.getInstance();
boolean shouldGuess = settings != null && settings.isUseUTFGuessing(virtualFile);
CharsetToolkit toolkit = shouldGuess ? new CharsetToolkit(content, EncodingRegistry.getInstance().getDefaultCharset()) : null;
setCharsetWasDetectedFromBytes(virtualFile, false);
if (shouldGuess) {
toolkit.setEnforce8Bit(true);
Charset charset = toolkit.guessFromBOM();
if (charset != null) {
setCharsetWasDetectedFromBytes(virtualFile, true);
byte[] bom = CharsetToolkit.getBom(charset);
if (bom == null) bom = CharsetToolkit.UTF8_BOM;
return Trinity.create(charset, null, bom);
}
CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length);
if (guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
setCharsetWasDetectedFromBytes(virtualFile, true);
return Trinity.create(CharsetToolkit.UTF8_CHARSET,null,null); //UTF detected, ignore all directives
}
return Trinity.create(null, guessed,null);
}
return null;
}
@NotNull
private static Pair<Charset,byte[]> getBOMAndCharset(@NotNull byte[] content, final Charset charset) {
if (charset != null && charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) {
return Pair.create(charset, CharsetToolkit.UTF8_BOM);
}
try {
if (CharsetToolkit.hasUTF16LEBom(content)) {
return Pair.create(CharsetToolkit.UTF_16LE_CHARSET, CharsetToolkit.UTF16LE_BOM);
}
if (CharsetToolkit.hasUTF16BEBom(content)) {
return Pair.create(CharsetToolkit.UTF_16BE_CHARSET, CharsetToolkit.UTF16BE_BOM);
}
}
catch (UnsupportedCharsetException ignore) {
}
return Pair.create(charset, ArrayUtil.EMPTY_BYTE_ARRAY);
}
/**
* Gets the <code>Writer</code> for this file and sets modification stamp and time stamp to the specified values
* after closing the Writer.<p>
* <p/>
* Normally you should not use this method.
*
* @param project
* @param virtualFile
* @param requestor any object to control who called this method. Note that
* it is considered to be an external change if <code>requestor</code> is <code>null</code>.
* See {@link com.intellij.openapi.vfs.VirtualFileEvent#getRequestor}
* @param text
* @param newModificationStamp new modification stamp or -1 if no special value should be set @return <code>Writer</code>
* @throws java.io.IOException if an I/O error occurs
* @see VirtualFile#getModificationStamp()
*/
@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
public static Writer getWriter(@Nullable Project project, @NotNull VirtualFile virtualFile, Object requestor, @NotNull String text, final long newModificationStamp)
throws IOException {
Charset existing = virtualFile.getCharset();
Charset specified = extractCharsetFromFileContent(project, virtualFile, text);
Charset charset = chooseMostlyHarmlessCharset(existing, specified, text);
if (charset != null) {
if (!charset.equals(existing)) {
virtualFile.setCharset(charset);
}
setDetectedFromBytesFlagBack(virtualFile, charset, text);
}
// in c ase of "UTF-16", OutputStreamWriter sometimes adds BOM on it's own.
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6800103
byte[] bom = virtualFile.getBOM();
Charset fromBom = bom == null ? null : CharsetToolkit.guessFromBOM(bom);
if (fromBom != null) charset = fromBom;
OutputStream outputStream = virtualFile.getOutputStream(requestor, newModificationStamp, -1);
OutputStreamWriter writer = charset == null ? new OutputStreamWriter(outputStream) : new OutputStreamWriter(outputStream, charset);
// no need to buffer ByteArrayOutputStream
return outputStream instanceof ByteArrayOutputStream ? writer : new BufferedWriter(writer);
}
private static void setDetectedFromBytesFlagBack(@NotNull VirtualFile virtualFile, @NotNull Charset charset, @NotNull String text) {
if (virtualFile.getBOM() != null) {
// prevent file to be reloaded in other encoding after save with BOM
setCharsetWasDetectedFromBytes(virtualFile, true);
return;
}
byte[] content = text.getBytes(charset);
CharsetToolkit.GuessedEncoding guessedEncoding = new CharsetToolkit(content).guessFromContent(content.length);
if (guessedEncoding == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
setCharsetWasDetectedFromBytes(virtualFile, true);
}
}
private static Charset chooseMostlyHarmlessCharset(Charset existing, Charset specified, String text) {
if (existing == null) return specified;
if (specified == null) return existing;
if (specified.equals(existing)) return specified;
if (isSupported(specified, text)) return specified; //if explicitly specified encoding is safe, return it
if (isSupported(existing, text)) return existing; //otherwise stick to the old encoding if it's ok
return specified; //if both are bad there is no difference
}
private static boolean isSupported(@NotNull Charset charset, @NotNull String str) {
if (!charset.canEncode()) return false;
ByteBuffer out = charset.encode(str);
CharBuffer buffer = charset.decode(out);
return str.equals(buffer.toString());
}
public static Charset extractCharsetFromFileContent(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text) {
Charset charset = charsetFromContentOrNull(project, virtualFile, text);
if (charset == null) charset = virtualFile.getCharset();
return charset;
}
@Nullable("returns null if cannot determine from content")
public static Charset charsetFromContentOrNull(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text) {
FileType fileType = virtualFile.getFileType();
if (fileType instanceof LanguageFileType) {
return ((LanguageFileType)fileType).extractCharsetFromFileContent(project, virtualFile, text);
}
return null;
}
public static CharSequence loadText(@NotNull VirtualFile file) {
if (file instanceof LightVirtualFile) {
CharSequence content = ((LightVirtualFile)file).getContent();
if (StringUtil.indexOf(content, '\r') == -1) return content;
CharBuffer buffer = CharBuffer.allocate(content.length());
buffer.append(content);
buffer.rewind();
return convertLineSeparators(buffer).first;
}
assert !file.isDirectory() : "'"+file.getPresentableUrl() + "' is directory";
final FileType fileType = file.getFileType();
if (fileType.isBinary()) {
final BinaryFileDecompiler decompiler = BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType);
if (decompiler != null) {
CharSequence text = decompiler.decompile(file);
StringUtil.assertValidSeparators(text);
return text;
}
throw new IllegalArgumentException("Attempt to load text for binary file, that doesn't have decompiler plugged in: "+file.getPresentableUrl());
}
try {
byte[] bytes = file.contentsToByteArray();
return getTextByBinaryPresentation(bytes, file);
}
catch (IOException e) {
return ArrayUtil.EMPTY_CHAR_SEQUENCE;
}
}
@NotNull
public static CharSequence getTextByBinaryPresentation(@NotNull final byte[] bytes, @NotNull VirtualFile virtualFile) {
return getTextByBinaryPresentation(bytes, virtualFile, true);
}
@NotNull
public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, @NotNull VirtualFile virtualFile, final boolean rememberDetectedSeparators) {
Pair<Charset, byte[]> pair = doDetectCharsetAndSetBOM(virtualFile, bytes);
final Charset charset = pair.getFirst();
byte[] bom = pair.getSecond();
int offset = bom == null ? 0 : bom.length;
final Pair<CharSequence, String> result = convertBytes(bytes, charset, offset);
if (rememberDetectedSeparators) {
virtualFile.putUserData(DETECTED_LINE_SEPARATOR_KEY, result.getSecond());
}
return result.getFirst();
}
/**
* Get detected line separator, if the file never been loaded, is loaded if checkFile parameter is specified.
*
* @param file the file to check
* @param checkFile if the line separator was not detected before, try to detect it
* @return the detected line separator or null
*/
@Nullable
public static String detectLineSeparator(@NotNull VirtualFile file, boolean checkFile) {
String lineSeparator = getDetectedLineSeparator(file);
if (lineSeparator == null && checkFile) {
try {
getTextByBinaryPresentation(file.contentsToByteArray(), file);
lineSeparator = getDetectedLineSeparator(file);
}
catch (IOException e) {
// null will be returned
}
}
return lineSeparator;
}
static String getDetectedLineSeparator(@NotNull VirtualFile file) {
return file.getUserData(DETECTED_LINE_SEPARATOR_KEY);
}
/**
* Change line separator for the file to the specified value (assumes that the documents were saved)
*
* @param project the project instance
* @param requestor the requestor for the operation
* @param file the file to convert
* @param newLineSeparator the new line separator for the file
* @throws IOException in the case of IO problem
*/
public static void changeLineSeparator(@Nullable Project project,
@Nullable Object requestor,
@NotNull VirtualFile file,
@NotNull String newLineSeparator) throws IOException {
String lineSeparator = getDetectedLineSeparator(file);
if (lineSeparator != null && lineSeparator.equals(newLineSeparator)) {
return;
}
CharSequence cs = getTextByBinaryPresentation(file.contentsToByteArray(), file);
lineSeparator = getDetectedLineSeparator(file);
if (lineSeparator == null || lineSeparator.equals(newLineSeparator)) {
return;
}
if (!newLineSeparator.equals("\n")) {
cs = StringUtil.convertLineSeparators(cs.toString(), newLineSeparator);
}
String text = cs.toString();
file.putUserData(DETECTED_LINE_SEPARATOR_KEY, newLineSeparator);
Writer w = getWriter(project, file, requestor, text, System.currentTimeMillis());
try {
w.write(text);
}
finally {
w.close();
}
}
@NotNull
public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, Charset charset) {
Pair<Charset, byte[]> pair = getBOMAndCharset(bytes, charset);
byte[] bom = pair.getSecond();
int offset = bom == null ? 0 : bom.length;
final Pair<CharSequence, String> result = convertBytes(bytes, charset, offset);
return result.getFirst();
}
// do not need to think about BOM here. it is processed outside
@NotNull
private static Pair<CharSequence, String> convertBytes(@NotNull byte[] bytes, Charset charset, final int startOffset) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, startOffset, bytes.length - startOffset);
if (charset == null) {
charset = CharsetToolkit.getDefaultSystemCharset();
}
if (charset == null) {
//noinspection HardCodedStringLiteral
charset = Charset.forName("ISO-8859-1");
}
CharBuffer charBuffer = charset.decode(byteBuffer);
return convertLineSeparators(charBuffer);
}
private static final Key<Boolean> CHARSET_WAS_DETECTED_FROM_BYTES = new Key<Boolean>("CHARSET_WAS_DETECTED_FROM_BYTES");
public static boolean wasCharsetDetectedFromBytes(@NotNull VirtualFile virtualFile) {
return virtualFile.getUserData(CHARSET_WAS_DETECTED_FROM_BYTES) != null;
}
public static void setCharsetWasDetectedFromBytes(@NotNull VirtualFile virtualFile, boolean flag) {
virtualFile.putUserData(CHARSET_WAS_DETECTED_FROM_BYTES, flag ? Boolean.TRUE : null);
}
}
|
platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.fileEditor.impl;
import com.intellij.lang.properties.charset.Native2AsciiCharset;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.BinaryFileDecompiler;
import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingRegistry;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
public final class LoadTextUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.LoadTextUtil");
private static final Key<String> DETECTED_LINE_SEPARATOR_KEY = Key.create("DETECTED_LINE_SEPARATOR_KEY");
private LoadTextUtil() {
}
@NotNull
private static Pair<CharSequence, String> convertLineSeparators(@NotNull CharBuffer buffer) {
int dst = 0;
char prev = ' ';
int crCount = 0;
int lfCount = 0;
int crlfCount = 0;
final int length = buffer.length();
final char[] bufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer);
for (int src = 0; src < length; src++) {
char c = bufferArray != null ? bufferArray[src]:buffer.charAt(src);
switch (c) {
case '\r':
buffer.put(dst++, '\n');
crCount++;
break;
case '\n':
if (prev == '\r') {
crCount--;
crlfCount++;
}
else {
buffer.put(dst++, '\n');
lfCount++;
}
break;
default:
buffer.put(dst++, c);
break;
}
prev = c;
}
String detectedLineSeparator = null;
if (crlfCount > crCount && crlfCount > lfCount) {
detectedLineSeparator = "\r\n";
}
else if (crCount > lfCount) {
detectedLineSeparator = "\r";
}
else if (lfCount > 0) {
detectedLineSeparator = "\n";
}
CharSequence result = buffer.length() == dst ? buffer : buffer.subSequence(0, dst);
return Pair.create(result, detectedLineSeparator);
}
private static Charset detectCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
if (virtualFile.isCharsetSet()) return virtualFile.getCharset();
Charset charset = doDetectCharset(virtualFile, content);
charset = charset == null ? EncodingRegistry.getInstance().getDefaultCharset() : charset;
if (EncodingRegistry.getInstance().isNative2Ascii(virtualFile)) {
charset = Native2AsciiCharset.wrap(charset);
}
virtualFile.setCharset(charset);
return charset;
}
@NotNull
public static Charset detectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
return doDetectCharsetAndSetBOM(virtualFile, content).getFirst();
}
@NotNull
private static Pair<Charset, byte[]> doDetectCharsetAndSetBOM(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
Charset charset = detectCharset(virtualFile, content);
Pair<Charset,byte[]> bomAndCharset = getBOMAndCharset(content, charset);
final byte[] bom = bomAndCharset.second;
if (bom.length != 0) {
virtualFile.setBOM(bom);
}
return bomAndCharset;
}
private static Charset doDetectCharset(@NotNull VirtualFile virtualFile, @NotNull byte[] content) {
Trinity<Charset,CharsetToolkit.GuessedEncoding, byte[]> guessed = guessFromContent(virtualFile, content, content.length);
if (guessed != null && guessed.first != null) return guessed.first;
FileType fileType = virtualFile.getFileType();
String charsetName = fileType.getCharset(virtualFile, content);
if (charsetName == null) {
Charset saved = EncodingRegistry.getInstance().getEncoding(virtualFile, true);
if (saved != null) return saved;
}
return CharsetToolkit.forName(charsetName);
}
@Nullable("null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
public static Trinity<Charset, CharsetToolkit.GuessedEncoding,byte[]> guessFromContent(VirtualFile virtualFile, byte[] content, int length) {
EncodingRegistry settings = EncodingRegistry.getInstance();
boolean shouldGuess = settings != null && settings.isUseUTFGuessing(virtualFile);
CharsetToolkit toolkit = shouldGuess ? new CharsetToolkit(content, EncodingRegistry.getInstance().getDefaultCharset()) : null;
setCharsetWasDetectedFromBytes(virtualFile, false);
if (shouldGuess) {
toolkit.setEnforce8Bit(true);
Charset charset = toolkit.guessFromBOM();
if (charset != null) {
setCharsetWasDetectedFromBytes(virtualFile, true);
byte[] bom = CharsetToolkit.getBom(charset);
if (bom == null) bom = CharsetToolkit.UTF8_BOM;
return Trinity.create(charset, null, bom);
}
CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length);
if (guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
setCharsetWasDetectedFromBytes(virtualFile, true);
return Trinity.create(CharsetToolkit.UTF8_CHARSET,null,null); //UTF detected, ignore all directives
}
return Trinity.create(null, guessed,null);
}
return null;
}
@NotNull
private static Pair<Charset,byte[]> getBOMAndCharset(@NotNull byte[] content, final Charset charset) {
if (charset != null && charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) {
return Pair.create(charset, CharsetToolkit.UTF8_BOM);
}
try {
if (CharsetToolkit.hasUTF16LEBom(content)) {
return Pair.create(CharsetToolkit.UTF_16LE_CHARSET, CharsetToolkit.UTF16LE_BOM);
}
if (CharsetToolkit.hasUTF16BEBom(content)) {
return Pair.create(CharsetToolkit.UTF_16BE_CHARSET, CharsetToolkit.UTF16BE_BOM);
}
}
catch (UnsupportedCharsetException ignore) {
}
return Pair.create(charset, ArrayUtil.EMPTY_BYTE_ARRAY);
}
/**
* Gets the <code>Writer</code> for this file and sets modification stamp and time stamp to the specified values
* after closing the Writer.<p>
* <p/>
* Normally you should not use this method.
*
* @param project
* @param virtualFile
* @param requestor any object to control who called this method. Note that
* it is considered to be an external change if <code>requestor</code> is <code>null</code>.
* See {@link com.intellij.openapi.vfs.VirtualFileEvent#getRequestor}
* @param text
* @param newModificationStamp new modification stamp or -1 if no special value should be set @return <code>Writer</code>
* @throws java.io.IOException if an I/O error occurs
* @see VirtualFile#getModificationStamp()
*/
@SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
public static Writer getWriter(@Nullable Project project, @NotNull VirtualFile virtualFile, Object requestor, @NotNull String text, final long newModificationStamp)
throws IOException {
Charset existing = virtualFile.getCharset();
Charset specified = extractCharsetFromFileContent(project, virtualFile, text);
Charset charset = chooseMostlyHarmlessCharset(existing, specified, text);
if (charset != null) {
if (!charset.equals(existing)) {
virtualFile.setCharset(charset);
}
setDetectedFromBytesFlagBack(virtualFile, charset, text);
}
// in c ase of "UTF-16", OutputStreamWriter sometimes adds BOM on it's own.
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6800103
byte[] bom = virtualFile.getBOM();
Charset fromBom = bom == null ? null : CharsetToolkit.guessFromBOM(bom);
if (fromBom != null) charset = fromBom;
OutputStream outputStream = virtualFile.getOutputStream(requestor, newModificationStamp, -1);
OutputStreamWriter writer = charset == null ? new OutputStreamWriter(outputStream) : new OutputStreamWriter(outputStream, charset);
// no need to buffer ByteArrayOutputStream
return outputStream instanceof ByteArrayOutputStream ? writer : new BufferedWriter(writer);
}
private static void setDetectedFromBytesFlagBack(@NotNull VirtualFile virtualFile, @NotNull Charset charset, @NotNull String text) {
if (virtualFile.getBOM() != null) {
// prevent file to be reloaded in other encoding after save with BOM
setCharsetWasDetectedFromBytes(virtualFile, true);
return;
}
byte[] content = text.getBytes(charset);
CharsetToolkit.GuessedEncoding guessedEncoding = new CharsetToolkit(content).guessFromContent(content.length);
if (guessedEncoding == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
setCharsetWasDetectedFromBytes(virtualFile, true);
}
}
private static Charset chooseMostlyHarmlessCharset(Charset existing, Charset specified, String text) {
if (existing == null) return specified;
if (specified == null) return existing;
if (specified.equals(existing)) return specified;
if (isSupported(specified, text)) return specified; //if explicitly specified encoding is safe, return it
if (isSupported(existing, text)) return existing; //otherwise stick to the old encoding if it's ok
return specified; //if both are bad there is no difference
}
private static boolean isSupported(@NotNull Charset charset, @NotNull String str) {
if (!charset.canEncode()) return false;
ByteBuffer out = charset.encode(str);
CharBuffer buffer = charset.decode(out);
return str.equals(buffer.toString());
}
public static Charset extractCharsetFromFileContent(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text) {
Charset charset = charsetFromContentOrNull(project, virtualFile, text);
if (charset == null) charset = virtualFile.getCharset();
return charset;
}
@Nullable("returns null if cannot determine from content")
public static Charset charsetFromContentOrNull(@Nullable Project project, @NotNull VirtualFile virtualFile, @NotNull String text) {
FileType fileType = virtualFile.getFileType();
if (fileType instanceof LanguageFileType) {
return ((LanguageFileType)fileType).extractCharsetFromFileContent(project, virtualFile, text);
}
return null;
}
public static CharSequence loadText(@NotNull VirtualFile file) {
if (file instanceof LightVirtualFile) {
CharSequence content = ((LightVirtualFile)file).getContent();
if (StringUtil.indexOf(content, '\r') == -1) return content;
CharBuffer buffer = CharBuffer.allocate(content.length());
buffer.append(content);
buffer.rewind();
return convertLineSeparators(buffer).first;
}
assert !file.isDirectory() : "'"+file.getPresentableUrl() + "' is directory";
final FileType fileType = file.getFileType();
if (fileType.isBinary()) {
final BinaryFileDecompiler decompiler = BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType);
if (decompiler != null) {
CharSequence text = decompiler.decompile(file);
StringUtil.assertValidSeparators(text);
return text;
}
throw new IllegalArgumentException("Attempt to load text for binary file, that doesn't have decompiler plugged in: "+file.getPresentableUrl());
}
try {
byte[] bytes = file.contentsToByteArray();
return getTextByBinaryPresentation(bytes, file);
}
catch (IOException e) {
return ArrayUtil.EMPTY_CHAR_SEQUENCE;
}
}
@NotNull
public static CharSequence getTextByBinaryPresentation(@NotNull final byte[] bytes, @NotNull VirtualFile virtualFile) {
return getTextByBinaryPresentation(bytes, virtualFile, true);
}
@NotNull
public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, @NotNull VirtualFile virtualFile, final boolean rememberDetectedSeparators) {
Pair<Charset, byte[]> pair = doDetectCharsetAndSetBOM(virtualFile, bytes);
final Charset charset = pair.getFirst();
byte[] bom = pair.getSecond();
int offset = bom == null ? 0 : bom.length;
final Pair<CharSequence, String> result = convertBytes(bytes, charset, offset);
if (rememberDetectedSeparators) {
virtualFile.putUserData(DETECTED_LINE_SEPARATOR_KEY, result.getSecond());
}
return result.getFirst();
}
/**
* Get detected line separator, if the file never been loaded, is loaded if checkFile parameter is specified.
*
* @param file the file to check
* @param checkFile if the line separator was not detected before, try to detect it
* @return the detected line separator or null
*/
@Nullable
public static String detectLineSeparator(@NotNull VirtualFile file, boolean checkFile) {
String lineSeparator = getDetectedLineSeparator(file);
if (lineSeparator == null && checkFile) {
try {
getTextByBinaryPresentation(file.contentsToByteArray(), file);
lineSeparator = getDetectedLineSeparator(file);
}
catch (IOException e) {
// null will be returned
}
}
return lineSeparator;
}
static String getDetectedLineSeparator(@NotNull VirtualFile file) {
return file.getUserData(DETECTED_LINE_SEPARATOR_KEY);
}
/**
* Change line separator for the file to the specified value (assumes that the documents were saved)
*
* @param project the project instance
* @param requestor the requestor for the operation
* @param file the file to convert
* @param newLineSeparator the new line separator for the file
* @throws IOException in the case of IO problem
*/
public static void changeLineSeparator(@Nullable Project project,
@Nullable Object requestor,
@NotNull VirtualFile file,
@NotNull String newLineSeparator) throws IOException {
String lineSeparator = getDetectedLineSeparator(file);
if (lineSeparator != null && lineSeparator.equals(newLineSeparator)) {
return;
}
CharSequence cs = getTextByBinaryPresentation(file.contentsToByteArray(), file);
lineSeparator = getDetectedLineSeparator(file);
if (lineSeparator == null || lineSeparator.equals(newLineSeparator)) {
return;
}
if (!newLineSeparator.equals("\n")) {
cs = StringUtil.convertLineSeparators(cs.toString(), newLineSeparator);
}
String text = cs.toString();
file.putUserData(DETECTED_LINE_SEPARATOR_KEY, newLineSeparator);
Writer w = getWriter(project, file, requestor, text, System.currentTimeMillis());
try {
w.write(text);
}
finally {
w.close();
}
}
@NotNull
public static CharSequence getTextByBinaryPresentation(@NotNull byte[] bytes, Charset charset) {
Pair<Charset, byte[]> pair = getBOMAndCharset(bytes, charset);
byte[] bom = pair.getSecond();
int offset = bom == null ? 0 : bom.length;
final Pair<CharSequence, String> result = convertBytes(bytes, charset, offset);
return result.getFirst();
}
// do not need to think about BOM here. it is processed outside
@NotNull
private static Pair<CharSequence, String> convertBytes(@NotNull byte[] bytes, Charset charset, final int startOffset) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, startOffset, bytes.length - startOffset);
if (charset == null) {
charset = CharsetToolkit.getDefaultSystemCharset();
}
if (charset == null) {
//noinspection HardCodedStringLiteral
charset = Charset.forName("ISO-8859-1");
}
CharBuffer charBuffer = charset.decode(byteBuffer);
return convertLineSeparators(charBuffer);
}
private static final Key<Boolean> CHARSET_WAS_DETECTED_FROM_BYTES = new Key<Boolean>("CHARSET_WAS_DETECTED_FROM_BYTES");
public static boolean wasCharsetDetectedFromBytes(@NotNull VirtualFile virtualFile) {
return virtualFile.getUserData(CHARSET_WAS_DETECTED_FROM_BYTES) != null;
}
public static void setCharsetWasDetectedFromBytes(@NotNull VirtualFile virtualFile, boolean flag) {
virtualFile.putUserData(CHARSET_WAS_DETECTED_FROM_BYTES, flag ? Boolean.TRUE : null);
}
}
|
write directly to char array if it is available (cherry picked from commit a664bc8)
|
platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java
|
write directly to char array if it is available (cherry picked from commit a664bc8)
|
|
Java
|
apache-2.0
|
5d34aa0afefad62e604fb1717be8860ff3579b2c
| 0
|
crosswalk-project/crosswalk-cordova-android,net19880504/cordova-android,manuelbrand/cordova-android,synaptek/cordova-android,matb33/cordova-android,egirshov/cordova-android,infil00p/cordova-android,dpogue/cordova-android,corimf/cordova-android,revolunet/cordova-android,ecit241/cordova-android,ogoguel/cordova-android,bso-intel/cordova-android,Icenium/cordova-android,archananaik/cordova-amazon-fireos-old,apache/cordova-android,mleoking/cordova-android,0359xiaodong/cordova-android,MetSystem/cordova-android,adobe-marketing-cloud-mobile/aemm-android,ecit241/cordova-android,matb33/cordova-android,ogoguel/cordova-android,cesine/cordova-android,awesome-niu/crosswalk-cordova-android,rakuco/crosswalk-cordova-android,csantanapr/cordova-android,CrandellWS/cordova-android,honger05/cordova-android,infil00p/cordova-android,corimf/cordova-android,synaptek/cordova-android,rohngonnarock/cordova-android,hgl888/crosswalk-cordova-android,xandroidx/cordova-android,polyvi/xface-android,MetSystem/cordova-android,macdonst/cordova-android,ttiurani/cordova-android,apache/cordova-android,filmaj/cordova-android,grigorkh/cordova-android,synaptek/cordova-android,awesome-niu/crosswalk-cordova-android,mmig/cordova-android,apache/cordova-android,infil00p/cordova-android,ttiurani/cordova-android,mmig/cordova-android,tony--/cordova-android,revolunet/cordova-android,alsorokin/cordova-android,manuelbrand/cordova-android,thedracle/cordova-android-chromeview,mleoking/cordova-android,mleoking/cordova-android,rakuco/crosswalk-cordova-android,rohngonnarock/cordova-android,askyheller/testgithub,ecit241/cordova-android,mokelab/cordova-android,jfrumar/cordova-android,lvrookie/cordova-android,tony--/cordova-android,leixinstar/cordova-android,lvrookie/cordova-android,0359xiaodong/cordova-android,hgl888/cordova-android-chromeview,sxagan/cordova-android,jasongin/cordova-android,corimf/cordova-android,sxagan/cordova-android,GroupAhead/cordova-android,macdonst/cordova-android,alsorokin/cordova-android,polyvi/xface-android,CloudCom/cordova-android,alsorokin/cordova-android,Icenium/cordova-android,chengxiaole/crosswalk-cordova-android,mokelab/cordova-android,filmaj/cordova-android,polyvi/xface-android,macdonst/cordova-android,hgl888/cordova-android,devgeeks/cordova-android,lvrookie/cordova-android,0359xiaodong/cordova-android,csantanapr/cordova-android,jasongin/cordova-android,grigorkh/cordova-android,chengxiaole/crosswalk-cordova-android,egirshov/cordova-android,jfrumar/cordova-android,leixinstar/cordova-android,crosswalk-project/crosswalk-cordova-android,forcedotcom/incubator-cordova-android,GroupAhead/cordova-android,filmaj/cordova-android,CrandellWS/cordova-android,grigorkh/cordova-android,alpache/cordova-android,vionescu/cordova-android,crosswalk-project/crosswalk-cordova-android,lybvinci/cordova-android,hgl888/cordova-android,rakuco/crosswalk-cordova-android,askyheller/testgithub,hgl888/crosswalk-cordova-android,lybvinci/cordova-android,CloudCom/cordova-android,xandroidx/cordova-android,MetSystem/cordova-android,hgl888/cordova-android-chromeview,chengxiaole/crosswalk-cordova-android,ttiurani/cordova-android,csantanapr/cordova-android,CrandellWS/cordova-android,grigorkh/cordova-android,ogoguel/cordova-android,sxagan/cordova-android,honger05/cordova-android,forcedotcom/incubator-cordova-android,devgeeks/cordova-android,cesine/cordova-android,hgl888/cordova-android-chromeview,mokelab/cordova-android,lybvinci/cordova-android,devgeeks/cordova-android,cesine/cordova-android,manuelbrand/cordova-android,adobe-marketing-cloud-mobile/aemm-android,dpogue/cordova-android,jasongin/cordova-android,net19880504/cordova-android,Icenium/cordova-android,thedracle/cordova-android-chromeview,hgl888/cordova-android,alpache/cordova-android,GroupAhead/cordova-android,forcedotcom/incubator-cordova-android,awesome-niu/crosswalk-cordova-android,alpache/cordova-android,leixinstar/cordova-android,CloudCom/cordova-android,mmig/cordova-android,egirshov/cordova-android,revolunet/cordova-android,bso-intel/cordova-android,tony--/cordova-android,vionescu/cordova-android,archananaik/cordova-amazon-fireos-old,thedracle/cordova-android-chromeview,dpogue/cordova-android,honger05/cordova-android,bso-intel/cordova-android,hgl888/cordova-android-chromeview,askyheller/testgithub,xandroidx/cordova-android,rohngonnarock/cordova-android,vionescu/cordova-android,hgl888/crosswalk-cordova-android,archananaik/cordova-amazon-fireos-old,jfrumar/cordova-android,matb33/cordova-android,net19880504/cordova-android,adobe-marketing-cloud-mobile/aemm-android
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
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.OutputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
/**
* This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed.
*/
public class CameraLauncher extends Plugin implements MediaScannerConnectionClient {
private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL
private static final int ALLMEDIA = 2; // allow selection from all media types
private static final int JPEG = 0; // Take a picture of type JPEG
private static final int PNG = 1; // Take a picture of type PNG
private static final String GET_PICTURE = "Get Picture";
private static final String GET_VIDEO = "Get Video";
private static final String GET_All = "Get All";
private static final String LOG_TAG = "CameraLauncher";
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
private int targetWidth; // desired width of the image
private int targetHeight; // desired height of the image
private Uri imageUri; // Uri of captured image
private int encodingType; // Type of encoding to use
private int mediaType; // What type of media to retrieve
private boolean saveToPhotoAlbum; // Should the picture be saved to the device's photo album
private boolean correctOrientation; // Should the pictures orientation be corrected
private boolean allowEdit; // Should we allow the user to crop the image
public String callbackId;
private int numPics;
private MediaScannerConnection conn; // Used to update gallery app with newly-written files
private Uri scanMe; // Uri of image to be added to content store
//This should never be null!
//private CordovaInterface cordova;
/**
* Constructor.
*/
public CameraLauncher() {
}
// public void setContext(CordovaInterface mCtx) {
// super.setContext(mCtx);
// if (CordovaInterface.class.isInstance(mCtx))
// cordova = (CordovaInterface) mCtx;
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
// }
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
this.callbackId = callbackId;
try {
if (action.equals("takePicture")) {
int srcType = CAMERA;
int destType = FILE_URI;
this.saveToPhotoAlbum = false;
this.targetHeight = 0;
this.targetWidth = 0;
this.encodingType = JPEG;
this.mediaType = PICTURE;
this.mQuality = 80;
this.mQuality = args.getInt(0);
destType = args.getInt(1);
srcType = args.getInt(2);
this.targetWidth = args.getInt(3);
this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5);
this.mediaType = args.getInt(6);
this.allowEdit = args.getBoolean(7);
this.correctOrientation = args.getBoolean(8);
this.saveToPhotoAlbum = args.getBoolean(9);
// If the user specifies a 0 or smaller width/height
// make it -1 so later comparisons succeed
if (this.targetWidth < 1) {
this.targetWidth = -1;
}
if (this.targetHeight < 1) {
this.targetHeight = -1;
}
if (srcType == CAMERA) {
this.takePicture(destType, encodingType);
}
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
this.getImage(srcType, destType);
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Take a picture with the camera.
* When an image is captured or the camera view is cancelled, the result is returned
* in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.
*
* The image can either be returned as a base64 string or a URI that points to the file.
* To display base64 string in an img tag, set the source to:
* img.src="data:image/jpeg;base64,"+result;
* or to display URI in an img tag
* img.src=result;
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param returnType Set the type of image to return.
*/
public void takePicture(int returnType, int encodingType) {
// Save the number of images currently on disk for later
this.numPics = queryImgDB(whichContentStore()).getCount();
// Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Specify file so that large image is captured and returned
File photo = createCaptureFile(encodingType);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
if (this.cordova != null) {
this.cordova.startActivityForResult((Plugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
}
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
}
/**
* Create a file in the applications temporary directory based upon the supplied encoding.
*
* @param encodingType of the image to be taken
* @return a File object pointing to the temporary picture
*/
private File createCaptureFile(int encodingType) {
File photo = null;
if (encodingType == JPEG) {
photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), ".Pic.jpg");
} else if (encodingType == PNG) {
photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), ".Pic.png");
} else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
}
return photo;
}
/**
* Get image from photo library.
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param srcType The album to get image from.
* @param returnType Set the type of image to return.
*/
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {
Intent intent = new Intent();
String title = GET_PICTURE;
if (this.mediaType == PICTURE) {
intent.setType("image/*");
}
else if (this.mediaType == VIDEO) {
intent.setType("video/*");
title = GET_VIDEO;
}
else if (this.mediaType == ALLMEDIA) {
// I wanted to make the type 'image/*, video/*' but this does not work on all versions
// of android so I had to go with the wildcard search.
intent.setType("*/*");
title = GET_All;
}
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (this.cordova != null) {
this.cordova.startActivityForResult((Plugin) this, Intent.createChooser(intent,
new String(title)), (srcType + 1) * 16 + returnType + 1);
}
}
/**
* Called when the camera view exits.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode / 16) - 1;
int destType = (requestCode % 16) - 1;
int rotate = 0;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/.Pic.jpg");
exif.readExifData();
rotate = exif.getOrientation();
}
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = null;
Uri uri = null;
// If sending base64 image back
if (destType == DATA_URL) {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
}
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI) {
if (!this.saveToPhotoAlbum) {
uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
} else {
uri = getUriFromMediaStore();
}
if (uri == null) {
this.failPicture("Error capturing image - no media storage found.");
}
// If all this is true we shouldn't compress the image.
if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && rotate == 0) {
writeUncompressedImage(uri);
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} else {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
String exifPath;
if (this.saveToPhotoAlbum) {
exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
} else {
exifPath = uri.getPath();
}
exif.createOutFile(exifPath);
exif.writeExifData();
}
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
bitmap = null;
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
else {
// This is a special case to just return the path as no scaling,
// rotating or compression needs to be done
if (this.targetHeight == -1 && this.targetWidth == -1 &&
this.mQuality == 100 && destType == FILE_URI && !this.correctOrientation) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} else {
// Get the path to the image. Makes loading so much easier.
String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
String mimeType = FileUtils.getMimeType(imagePath);
// Log.d(LOG_TAG, "Real path = " + imagePath);
// Log.d(LOG_TAG, "mime type = " + mimeType);
// If we don't have a valid image so quit.
if (imagePath == null || mimeType == null ||
!(mimeType.equalsIgnoreCase("image/jpeg") || mimeType.equalsIgnoreCase("image/png"))) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
this.failPicture("Unable to retrieve path to picture!");
return;
}
Bitmap bitmap = getScaledBitmap(imagePath);
if (bitmap == null) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
this.failPicture("Unable to create bitmap!");
return;
}
if (this.correctOrientation) {
String[] cols = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
cols, null, null, null);
if (cursor != null) {
cursor.moveToPosition(0);
rotate = cursor.getInt(0);
cursor.close();
}
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
}
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
}
// If sending filename back
else if (destType == FILE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
String resizePath = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(resizePath);
exif.readExifData();
rotate = exif.getOrientation();
}
} catch (IOException e) {
e.printStackTrace();
}
OutputStream os = new FileOutputStream(resizePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
exif.writeExifData();
}
// The resized image is cached by the app in order to get around this and not have to delete you
// application cache I'm adding the current system time to the end of the file url.
this.success(new PluginResult(PluginResult.Status.OK, ("file://" + resizePath + "?" + System.currentTimeMillis())), this.callbackId);
} catch (Exception e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
System.gc();
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
/**
* Figure out if the bitmap should be rotated. For instance if the picture was taken in
* portrait mode
*
* @param rotate
* @param bitmap
* @return rotated bitmap
*/
private Bitmap getRotatedBitmap(int rotate, Bitmap bitmap, ExifHelper exif) {
Matrix matrix = new Matrix();
if (rotate == 180) {
matrix.setRotate(rotate);
} else {
matrix.setRotate(rotate, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
}
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
exif.resetOrientation();
return bitmap;
}
/**
* In the special case where the default width, height and quality are unchanged
* we just write the file out to disk saving the expensive Bitmap.compress function.
*
* @param uri
* @throws FileNotFoundException
* @throws IOException
*/
private void writeUncompressedImage(Uri uri) throws FileNotFoundException,
IOException {
FileInputStream fis = new FileInputStream(FileUtils.stripFileProtocol(imageUri.toString()));
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
}
/**
* Create entry in media store for image
*
* @return uri
*/
private Uri getUriFromMediaStore() {
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri;
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
return null;
}
}
return uri;
}
/**
* Return a scaled bitmap based on the target width and height
*
* @param imagePath
* @return
*/
private Bitmap getScaledBitmap(String imagePath) {
// If no new width or height were specified return the original bitmap
if (this.targetWidth <= 0 && this.targetHeight <= 0) {
return BitmapFactory.decodeFile(imagePath);
}
// figure out the original width and height of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
// determine the correct aspect ratio
int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);
// Load in the smallest bitmap possible that is closest to the size we want
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options);
return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}
/**
* Maintain the aspect ratio so the resulting image does not look smooshed
*
* @param origWidth
* @param origHeight
* @return
*/
public int[] calculateAspectRatio(int origWidth, int origHeight) {
int newWidth = this.targetWidth;
int newHeight = this.targetHeight;
// If no new width or height were specified return the original bitmap
if (newWidth <= 0 && newHeight <= 0) {
newWidth = origWidth;
newHeight = origHeight;
}
// Only the width was specified
else if (newWidth > 0 && newHeight <= 0) {
newHeight = (newWidth * origHeight) / origWidth;
}
// only the height was specified
else if (newWidth <= 0 && newHeight > 0) {
newWidth = (newHeight * origWidth) / origHeight;
}
// If the user specified both a positive width and height
// (potentially different aspect ratio) then the width or height is
// scaled so that the image fits while maintaining aspect ratio.
// Alternatively, the specified width and height could have been
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double) newHeight;
double origRatio = origWidth / (double) origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
} else if (origRatio < newRatio) {
newWidth = (newHeight * origWidth) / origHeight;
}
}
int[] retval = new int[2];
retval[0] = newWidth;
retval[1] = newHeight;
return retval;
}
/**
* Figure out what ratio we can load our image into memory at while still being bigger than
* our desired width and height
*
* @param srcWidth
* @param srcHeight
* @param dstWidth
* @param dstHeight
* @return
*/
public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)dstWidth / (float)dstHeight;
if (srcAspect > dstAspect) {
return srcWidth / dstWidth;
} else {
return srcHeight / dstHeight;
}
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB(Uri contentStore) {
return this.cordova.getActivity().getContentResolver().query(
contentStore,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Cleans up after picture taking. Checking for duplicates and that kind of stuff.
* @param newImage
*/
private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) {
if (bitmap != null) {
bitmap.recycle();
}
// Clean up initial camera-written image file.
(new File(FileUtils.stripFileProtocol(oldImage.toString()))).delete();
checkForDuplicateImage(imageType);
// Scan for the gallery to update pic refs in gallery
if (this.saveToPhotoAlbum && newImage != null) {
this.scanForGallery(newImage);
}
System.gc();
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store. If we are using a FILE_URI and the number of images in the DB
* increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
*
* @param type FILE_URI or DATA_URL
*/
private void checkForDuplicateImage(int type) {
int diff = 1;
Uri contentStore = whichContentStore();
Cursor cursor = queryImgDB(contentStore);
int currentNumOfImages = cursor.getCount();
if (type == FILE_URI && this.saveToPhotoAlbum) {
diff = 2;
}
// delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
if ((currentNumOfImages - numPics) == diff) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
if (diff == 2) {
id--;
}
Uri uri = Uri.parse(contentStore + "/" + id);
this.cordova.getActivity().getContentResolver().delete(uri, null, null);
}
}
/**
* Determine if we are storing the images in internal or external storage
* @return Uri
*/
private Uri whichContentStore() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
}
/**
* Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
*
* @param bitmap
*/
public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code);
String js_out = new String(output);
this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId);
js_out = null;
output = null;
code = null;
}
} catch (Exception e) {
this.failPicture("Error compressing image.");
}
jpeg_data = null;
}
/**
* Send error message to JavaScript.
*
* @param err
*/
public void failPicture(String err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
private void scanForGallery(Uri newImage) {
this.scanMe = newImage;
if(this.conn != null) {
this.conn.disconnect();
}
this.conn = new MediaScannerConnection(this.ctx.getActivity().getApplicationContext(), this);
conn.connect();
}
public void onMediaScannerConnected() {
try{
this.conn.scanFile(this.scanMe.toString(), "image/*");
} catch (java.lang.IllegalStateException e){
LOG.e(LOG_TAG, "Can't scan file in MediaScanner after taking picture");
}
}
public void onScanCompleted(String path, Uri uri) {
this.conn.disconnect();
}
}
|
framework/src/org/apache/cordova/CameraLauncher.java
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
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.OutputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
/**
* This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed.
*/
public class CameraLauncher extends Plugin implements MediaScannerConnectionClient {
private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera
private static final int SAVEDPHOTOALBUM = 2; // Choose image from picture library (same as PHOTOLIBRARY for Android)
private static final int PICTURE = 0; // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
private static final int VIDEO = 1; // allow selection of video only, ONLY RETURNS URL
private static final int ALLMEDIA = 2; // allow selection from all media types
private static final int JPEG = 0; // Take a picture of type JPEG
private static final int PNG = 1; // Take a picture of type PNG
private static final String GET_PICTURE = "Get Picture";
private static final String GET_VIDEO = "Get Video";
private static final String GET_All = "Get All";
private static final String LOG_TAG = "CameraLauncher";
private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
private int targetWidth; // desired width of the image
private int targetHeight; // desired height of the image
private Uri imageUri; // Uri of captured image
private int encodingType; // Type of encoding to use
private int mediaType; // What type of media to retrieve
private boolean saveToPhotoAlbum; // Should the picture be saved to the device's photo album
private boolean correctOrientation; // Should the pictures orientation be corrected
private boolean allowEdit; // Should we allow the user to crop the image
public String callbackId;
private int numPics;
private MediaScannerConnection conn; // Used to update gallery app with newly-written files
private Uri scanMe; // Uri of image to be added to content store
//This should never be null!
//private CordovaInterface cordova;
/**
* Constructor.
*/
public CameraLauncher() {
}
// public void setContext(CordovaInterface mCtx) {
// super.setContext(mCtx);
// if (CordovaInterface.class.isInstance(mCtx))
// cordova = (CordovaInterface) mCtx;
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
// }
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
this.callbackId = callbackId;
try {
if (action.equals("takePicture")) {
int srcType = CAMERA;
int destType = FILE_URI;
this.saveToPhotoAlbum = false;
this.targetHeight = 0;
this.targetWidth = 0;
this.encodingType = JPEG;
this.mediaType = PICTURE;
this.mQuality = 80;
this.mQuality = args.getInt(0);
destType = args.getInt(1);
srcType = args.getInt(2);
this.targetWidth = args.getInt(3);
this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5);
this.mediaType = args.getInt(6);
this.allowEdit = args.getBoolean(7);
this.correctOrientation = args.getBoolean(8);
this.saveToPhotoAlbum = args.getBoolean(9);
// If the user specifies a 0 or smaller width/height
// make it -1 so later comparisons succeed
if (this.targetWidth < 1) {
this.targetWidth = -1;
}
if (this.targetHeight < 1) {
this.targetHeight = -1;
}
if (srcType == CAMERA) {
this.takePicture(destType, encodingType);
}
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
this.getImage(srcType, destType);
}
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
return new PluginResult(status, result);
} catch (JSONException e) {
e.printStackTrace();
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Take a picture with the camera.
* When an image is captured or the camera view is cancelled, the result is returned
* in CordovaActivity.onActivityResult, which forwards the result to this.onActivityResult.
*
* The image can either be returned as a base64 string or a URI that points to the file.
* To display base64 string in an img tag, set the source to:
* img.src="data:image/jpeg;base64,"+result;
* or to display URI in an img tag
* img.src=result;
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param returnType Set the type of image to return.
*/
public void takePicture(int returnType, int encodingType) {
// Save the number of images currently on disk for later
this.numPics = queryImgDB(whichContentStore()).getCount();
// Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// Specify file so that large image is captured and returned
File photo = createCaptureFile(encodingType);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
if (this.cordova != null) {
this.cordova.startActivityForResult((Plugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
}
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
}
/**
* Create a file in the applications temporary directory based upon the supplied encoding.
*
* @param encodingType of the image to be taken
* @return a File object pointing to the temporary picture
*/
private File createCaptureFile(int encodingType) {
File photo = null;
if (encodingType == JPEG) {
photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), ".Pic.jpg");
} else if (encodingType == PNG) {
photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), ".Pic.png");
} else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
}
return photo;
}
/**
* Get image from photo library.
*
* @param quality Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)
* @param srcType The album to get image from.
* @param returnType Set the type of image to return.
*/
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
public void getImage(int srcType, int returnType) {
Intent intent = new Intent();
String title = GET_PICTURE;
if (this.mediaType == PICTURE) {
intent.setType("image/*");
}
else if (this.mediaType == VIDEO) {
intent.setType("video/*");
title = GET_VIDEO;
}
else if (this.mediaType == ALLMEDIA) {
// I wanted to make the type 'image/*, video/*' but this does not work on all versions
// of android so I had to go with the wildcard search.
intent.setType("*/*");
title = GET_All;
}
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (this.cordova != null) {
this.cordova.startActivityForResult((Plugin) this, Intent.createChooser(intent,
new String(title)), (srcType + 1) * 16 + returnType + 1);
}
}
/**
* Called when the camera view exits.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode / 16) - 1;
int destType = (requestCode % 16) - 1;
int rotate = 0;
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/.Pic.jpg");
exif.readExifData();
rotate = exif.getOrientation();
}
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = null;
Uri uri = null;
// If sending base64 image back
if (destType == DATA_URL) {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
}
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI) {
if (!this.saveToPhotoAlbum) {
uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
} else {
uri = getUriFromMediaStore();
}
if (uri == null) {
this.failPicture("Error capturing image - no media storage found.");
}
// If all this is true we shouldn't compress the image.
if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && rotate == 0) {
writeUncompressedImage(uri);
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} else {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
}
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
String exifPath;
if (this.saveToPhotoAlbum) {
exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
} else {
exifPath = uri.getPath();
}
exif.createOutFile(exifPath);
exif.writeExifData();
}
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
bitmap = null;
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
}
}
// If cancelled
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Camera cancelled.");
}
// If something else
else {
this.failPicture("Did not complete!");
}
}
// If retrieving photo from library
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
if (this.mediaType != PICTURE) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
else {
// This is a special case to just return the path as no scaling,
// rotating or compression needs to be done
if (this.targetHeight == -1 && this.targetWidth == -1 &&
this.mQuality == 100 && destType == FILE_URI && !this.correctOrientation) {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} else {
// Get the path to the image. Makes loading so much easier.
String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
Log.d(LOG_TAG, "Real path = " + imagePath);
// If we don't have a valid image so quit.
if (imagePath == null) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
this.failPicture("Unable to retrieve path to picture!");
return;
}
Bitmap bitmap = getScaledBitmap(imagePath);
if (bitmap == null) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
this.failPicture("Unable to create bitmap!");
return;
}
if (this.correctOrientation) {
String[] cols = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
cols, null, null, null);
if (cursor != null) {
cursor.moveToPosition(0);
rotate = cursor.getInt(0);
cursor.close();
}
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
}
// If sending base64 image back
if (destType == DATA_URL) {
this.processPicture(bitmap);
}
// If sending filename back
else if (destType == FILE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
String resizePath = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(resizePath);
exif.readExifData();
rotate = exif.getOrientation();
}
} catch (IOException e) {
e.printStackTrace();
}
OutputStream os = new FileOutputStream(resizePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
exif.writeExifData();
}
// The resized image is cached by the app in order to get around this and not have to delete you
// application cache I'm adding the current system time to the end of the file url.
this.success(new PluginResult(PluginResult.Status.OK, ("file://" + resizePath + "?" + System.currentTimeMillis())), this.callbackId);
} catch (Exception e) {
e.printStackTrace();
this.failPicture("Error retrieving image.");
}
}
else {
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
}
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
System.gc();
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
this.failPicture("Selection cancelled.");
}
else {
this.failPicture("Selection did not complete!");
}
}
}
/**
* Figure out if the bitmap should be rotated. For instance if the picture was taken in
* portrait mode
*
* @param rotate
* @param bitmap
* @return rotated bitmap
*/
private Bitmap getRotatedBitmap(int rotate, Bitmap bitmap, ExifHelper exif) {
Matrix matrix = new Matrix();
if (rotate == 180) {
matrix.setRotate(rotate);
} else {
matrix.setRotate(rotate, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
}
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
exif.resetOrientation();
return bitmap;
}
/**
* In the special case where the default width, height and quality are unchanged
* we just write the file out to disk saving the expensive Bitmap.compress function.
*
* @param uri
* @throws FileNotFoundException
* @throws IOException
*/
private void writeUncompressedImage(Uri uri) throws FileNotFoundException,
IOException {
FileInputStream fis = new FileInputStream(FileUtils.stripFileProtocol(imageUri.toString()));
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
}
/**
* Create entry in media store for image
*
* @return uri
*/
private Uri getUriFromMediaStore() {
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri;
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
return null;
}
}
return uri;
}
/**
* Return a scaled bitmap based on the target width and height
*
* @param imagePath
* @return
*/
private Bitmap getScaledBitmap(String imagePath) {
// If no new width or height were specified return the original bitmap
if (this.targetWidth <= 0 && this.targetHeight <= 0) {
return BitmapFactory.decodeFile(imagePath);
}
// figure out the original width and height of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
// determine the correct aspect ratio
int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);
// Load in the smallest bitmap possible that is closest to the size we want
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options);
return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}
/**
* Maintain the aspect ratio so the resulting image does not look smooshed
*
* @param origWidth
* @param origHeight
* @return
*/
public int[] calculateAspectRatio(int origWidth, int origHeight) {
int newWidth = this.targetWidth;
int newHeight = this.targetHeight;
// If no new width or height were specified return the original bitmap
if (newWidth <= 0 && newHeight <= 0) {
newWidth = origWidth;
newHeight = origHeight;
}
// Only the width was specified
else if (newWidth > 0 && newHeight <= 0) {
newHeight = (newWidth * origHeight) / origWidth;
}
// only the height was specified
else if (newWidth <= 0 && newHeight > 0) {
newWidth = (newHeight * origWidth) / origHeight;
}
// If the user specified both a positive width and height
// (potentially different aspect ratio) then the width or height is
// scaled so that the image fits while maintaining aspect ratio.
// Alternatively, the specified width and height could have been
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double) newHeight;
double origRatio = origWidth / (double) origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
} else if (origRatio < newRatio) {
newWidth = (newHeight * origWidth) / origHeight;
}
}
int[] retval = new int[2];
retval[0] = newWidth;
retval[1] = newHeight;
return retval;
}
/**
* Figure out what ratio we can load our image into memory at while still being bigger than
* our desired width and height
*
* @param srcWidth
* @param srcHeight
* @param dstWidth
* @param dstHeight
* @return
*/
public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight) {
final float srcAspect = (float)srcWidth / (float)srcHeight;
final float dstAspect = (float)dstWidth / (float)dstHeight;
if (srcAspect > dstAspect) {
return srcWidth / dstWidth;
} else {
return srcHeight / dstHeight;
}
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB(Uri contentStore) {
return this.cordova.getActivity().getContentResolver().query(
contentStore,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Cleans up after picture taking. Checking for duplicates and that kind of stuff.
* @param newImage
*/
private void cleanup(int imageType, Uri oldImage, Uri newImage, Bitmap bitmap) {
if (bitmap != null) {
bitmap.recycle();
}
// Clean up initial camera-written image file.
(new File(FileUtils.stripFileProtocol(oldImage.toString()))).delete();
checkForDuplicateImage(imageType);
// Scan for the gallery to update pic refs in gallery
if (this.saveToPhotoAlbum && newImage != null) {
this.scanForGallery(newImage);
}
System.gc();
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store. If we are using a FILE_URI and the number of images in the DB
* increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
*
* @param type FILE_URI or DATA_URL
*/
private void checkForDuplicateImage(int type) {
int diff = 1;
Uri contentStore = whichContentStore();
Cursor cursor = queryImgDB(contentStore);
int currentNumOfImages = cursor.getCount();
if (type == FILE_URI && this.saveToPhotoAlbum) {
diff = 2;
}
// delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
if ((currentNumOfImages - numPics) == diff) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
if (diff == 2) {
id--;
}
Uri uri = Uri.parse(contentStore + "/" + id);
this.cordova.getActivity().getContentResolver().delete(uri, null, null);
}
}
/**
* Determine if we are storing the images in internal or external storage
* @return Uri
*/
private Uri whichContentStore() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
}
/**
* Compress bitmap using jpeg, convert to Base64 encoded string, and return to JavaScript.
*
* @param bitmap
*/
public void processPicture(Bitmap bitmap) {
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code);
String js_out = new String(output);
this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId);
js_out = null;
output = null;
code = null;
}
} catch (Exception e) {
this.failPicture("Error compressing image.");
}
jpeg_data = null;
}
/**
* Send error message to JavaScript.
*
* @param err
*/
public void failPicture(String err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
private void scanForGallery(Uri newImage) {
this.scanMe = newImage;
if(this.conn != null) {
this.conn.disconnect();
}
this.conn = new MediaScannerConnection(this.ctx.getActivity().getApplicationContext(), this);
conn.connect();
}
public void onMediaScannerConnected() {
try{
this.conn.scanFile(this.scanMe.toString(), "image/*");
} catch (java.lang.IllegalStateException e){
LOG.e(LOG_TAG, "Can't scan file in MediaScanner after taking picture");
}
}
public void onScanCompleted(String path, Uri uri) {
this.conn.disconnect();
}
}
|
Guard against null pointer exception in ES File Explorer being used to get a picture using DATA_URL
|
framework/src/org/apache/cordova/CameraLauncher.java
|
Guard against null pointer exception in ES File Explorer being used to get a picture using DATA_URL
|
|
Java
|
apache-2.0
|
909528215b3034f63c4ff883e88b3b2c6d542df3
| 0
|
amith01994/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,amith01994/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,semonte/intellij-community,caot/intellij-community,signed/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,slisson/intellij-community,caot/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,signed/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,allotria/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,fitermay/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,supersven/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fitermay/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,semonte/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,blademainer/intellij-community,da1z/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,adedayo/intellij-community,fitermay/intellij-community,supersven/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,kool79/intellij-community,semonte/intellij-community,petteyg/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,retomerz/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,retomerz/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,robovm/robovm-studio,signed/intellij-community,youdonghai/intellij-community,samthor/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,vladmm/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,caot/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,slisson/intellij-community,signed/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ryano144/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,signed/intellij-community,amith01994/intellij-community,diorcety/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,caot/intellij-community,samthor/intellij-community,allotria/intellij-community,diorcety/intellij-community,asedunov/intellij-community,petteyg/intellij-community,jagguli/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,vladmm/intellij-community,samthor/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,caot/intellij-community,clumsy/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,caot/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,slisson/intellij-community,nicolargo/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,apixandru/intellij-community,slisson/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,izonder/intellij-community,da1z/intellij-community,signed/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,vvv1559/intellij-community,da1z/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,supersven/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,semonte/intellij-community,retomerz/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,amith01994/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,supersven/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,da1z/intellij-community,FHannes/intellij-community,blademainer/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,izonder/intellij-community,vladmm/intellij-community,kool79/intellij-community,robovm/robovm-studio,FHannes/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,blademainer/intellij-community,holmes/intellij-community,hurricup/intellij-community,allotria/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,semonte/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,allotria/intellij-community,allotria/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,kool79/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,allotria/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,apixandru/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,kdwink/intellij-community,FHannes/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,caot/intellij-community,signed/intellij-community,blademainer/intellij-community,clumsy/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,xfournet/intellij-community,holmes/intellij-community,adedayo/intellij-community,signed/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,holmes/intellij-community,robovm/robovm-studio,petteyg/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,samthor/intellij-community,ryano144/intellij-community,retomerz/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,retomerz/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,caot/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,supersven/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,caot/intellij-community,lucafavatella/intellij-community,signed/intellij-community,ryano144/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,izonder/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,allotria/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,semonte/intellij-community,supersven/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,allotria/intellij-community,slisson/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,samthor/intellij-community,allotria/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,fnouama/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,fnouama/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,caot/intellij-community,samthor/intellij-community,clumsy/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,signed/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,hurricup/intellij-community,kdwink/intellij-community,ibinti/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,samthor/intellij-community,jagguli/intellij-community,adedayo/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,kool79/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,kool79/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,vladmm/intellij-community,clumsy/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,izonder/intellij-community,izonder/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,semonte/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,adedayo/intellij-community,izonder/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,vladmm/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,blademainer/intellij-community,samthor/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,FHannes/intellij-community,asedunov/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,retomerz/intellij-community,fnouama/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,semonte/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,kdwink/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.fileTypes.impl;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ide.highlighter.custom.SyntaxTable;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.TransferToPooledThreadQueue;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.fileTypes.ex.*;
import com.intellij.openapi.options.BaseSchemeProcessor;
import com.intellij.openapi.options.SchemesManager;
import com.intellij.openapi.options.SchemesManagerFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.ByteSequence;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.FileAttribute;
import com.intellij.openapi.vfs.newvfs.FileSystemInterface;
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
import com.intellij.psi.SingleRootFileViewProvider;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.*;
import com.intellij.util.containers.ConcurrentPackedBitsArray;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@State(
name = "FileTypeManager",
storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/filetypes.xml"),
additionalExportFile = FileTypeManagerImpl.FILE_SPEC
)
public class FileTypeManagerImpl extends FileTypeManagerEx implements PersistentStateComponent<Element>, ApplicationComponent, Disposable {
private static final Logger LOG = Logger.getInstance(FileTypeManagerImpl.class);
// You must update all existing default configurations accordingly
private static final int VERSION = 14;
private static final Key<FileType> FILE_TYPE_KEY = Key.create("FILE_TYPE_KEY");
// cached auto-detected file type. If the file was auto-detected as plain text or binary
// then the value is null and autoDetectedAsText, autoDetectedAsBinary and autoDetectWasRun sets are used instead.
private static final Key<FileType> DETECTED_FROM_CONTENT_FILE_TYPE_KEY = Key.create("DETECTED_FROM_CONTENT_FILE_TYPE_KEY");
private static final int DETECT_BUFFER_SIZE = 8192; // the number of bytes to read from the file to feed to the file type detector
@NonNls
private static final String DEFAULT_IGNORED =
"*.hprof;*.pyc;*.pyo;*.rbc;*~;.DS_Store;.bundle;.git;.hg;.svn;CVS;RCS;SCCS;__pycache__;.tox;_svn;rcs;vssver.scc;vssver2.scc;";
private static boolean RE_DETECT_ASYNC = !ApplicationManager.getApplication().isUnitTestMode();
private final Set<FileType> myDefaultTypes = new THashSet<FileType>();
private final List<FileTypeIdentifiableByVirtualFile> mySpecialFileTypes = new ArrayList<FileTypeIdentifiableByVirtualFile>();
private FileTypeAssocTable<FileType> myPatternsTable = new FileTypeAssocTable<FileType>();
private final IgnoredPatternSet myIgnoredPatterns = new IgnoredPatternSet();
private final IgnoredFileCache myIgnoredFileCache = new IgnoredFileCache(myIgnoredPatterns);
private final FileTypeAssocTable<FileType> myInitialAssociations = new FileTypeAssocTable<FileType>();
private final Map<FileNameMatcher, String> myUnresolvedMappings = new THashMap<FileNameMatcher, String>();
private final Map<FileNameMatcher, Trinity<String, String, Boolean>> myUnresolvedRemovedMappings = new THashMap<FileNameMatcher, Trinity<String, String, Boolean>>();
/** This will contain removed mappings with "approved" states */
private final Map<FileNameMatcher, Pair<FileType, Boolean>> myRemovedMappings = new THashMap<FileNameMatcher, Pair<FileType, Boolean>>();
@NonNls private static final String ELEMENT_FILETYPE = "filetype";
@NonNls private static final String ELEMENT_IGNORE_FILES = "ignoreFiles";
@NonNls private static final String ATTRIBUTE_LIST = "list";
@NonNls private static final String ATTRIBUTE_VERSION = "version";
@NonNls private static final String ATTRIBUTE_NAME = "name";
@NonNls private static final String ATTRIBUTE_DESCRIPTION = "description";
private static class StandardFileType {
@NotNull private final FileType fileType;
@NotNull private final List<FileNameMatcher> matchers;
private StandardFileType(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers) {
this.fileType = fileType;
this.matchers = matchers;
}
}
private final MessageBus myMessageBus;
private final Map<String, StandardFileType> myStandardFileTypes = new LinkedHashMap<String, StandardFileType>();
@NonNls
private static final String[] FILE_TYPES_WITH_PREDEFINED_EXTENSIONS = {"JSP", "JSPX", "DTD", "HTML", "Properties", "XHTML"};
private final SchemesManager<FileType, AbstractFileType> mySchemesManager;
@NonNls
static final String FILE_SPEC = StoragePathMacros.ROOT_CONFIG + "/filetypes";
// these flags are stored in 'packedFlags' as chunks of four bits
private static final int AUTO_DETECTED_AS_TEXT_MASK = 1;
private static final int AUTO_DETECTED_AS_BINARY_MASK = 2;
private static final int AUTO_DETECT_WAS_RUN_MASK = 4;
private static final int ATTRIBUTES_WERE_LOADED_MASK = 8;
private final ConcurrentPackedBitsArray packedFlags = new ConcurrentPackedBitsArray(4);
private final AtomicInteger counterAutoDetect = new AtomicInteger();
private final AtomicLong elapsedAutoDetect = new AtomicLong();
public FileTypeManagerImpl(MessageBus bus, SchemesManagerFactory schemesManagerFactory, PropertiesComponent propertiesComponent) {
int fileTypeChangedCounter = StringUtilRt.parseInt(propertiesComponent.getValue("fileTypeChangedCounter"), 0);
fileTypeChangedCount = new AtomicInteger(fileTypeChangedCounter);
autoDetectedAttribute = new FileAttribute("AUTO_DETECTION_CACHE_ATTRIBUTE", fileTypeChangedCounter, true);
myMessageBus = bus;
mySchemesManager = schemesManagerFactory.createSchemesManager(FILE_SPEC, new BaseSchemeProcessor<AbstractFileType>() {
@NotNull
@Override
public AbstractFileType readScheme(@NotNull Element element, boolean duringLoad) {
if (!duringLoad) {
fireBeforeFileTypesChanged();
}
AbstractFileType type = (AbstractFileType)loadFileType(element, false);
if (!duringLoad) {
fireFileTypesChanged();
}
return type;
}
@NotNull
@Override
public State getState(@NotNull AbstractFileType fileType) {
if (!shouldSave(fileType)) {
return State.NON_PERSISTENT;
}
if (!myDefaultTypes.contains(fileType)) {
return State.POSSIBLY_CHANGED;
}
return fileType.isModified() ? State.POSSIBLY_CHANGED : State.NON_PERSISTENT;
}
@Override
public Element writeScheme(@NotNull AbstractFileType fileType) {
Element root = new Element(ELEMENT_FILETYPE);
root.setAttribute("binary", String.valueOf(fileType.isBinary()));
if (!StringUtil.isEmpty(fileType.getDefaultExtension())) {
root.setAttribute("default_extension", fileType.getDefaultExtension());
}
root.setAttribute(ATTRIBUTE_DESCRIPTION, fileType.getDescription());
root.setAttribute(ATTRIBUTE_NAME, fileType.getName());
fileType.writeExternal(root);
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
writeExtensionsMap(map, fileType, false);
if (!map.getChildren().isEmpty()) {
root.addContent(map);
}
return root;
}
@Override
public void onSchemeDeleted(@NotNull AbstractFileType scheme) {
fireBeforeFileTypesChanged();
myPatternsTable.removeAllAssociations(scheme);
fireFileTypesChanged();
}
}, RoamingType.PER_USER);
bus.connect().subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener.Adapter() {
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
Collection<VirtualFile> files = ContainerUtil.map2Set(events, new Function<VFileEvent, VirtualFile>() {
@Override
public VirtualFile fun(VFileEvent event) {
VirtualFile file = event instanceof VFileCreateEvent ? null : event.getFile();
return file != null && wasAutoDetectedBefore(file) && isDetectable(file) ? file : null;
}
});
files.remove(null);
if (toLog()) {
log("F: VFS events: " + events);
}
if (!files.isEmpty() && RE_DETECT_ASYNC) {
if (toLog()) {
log("F: queued to redetect: " + files);
}
reDetectQueue.offerIfAbsent(files);
}
}
});
//noinspection SpellCheckingInspection
myIgnoredPatterns.setIgnoreMasks(DEFAULT_IGNORED);
// this should be done BEFORE reading state
initStandardFileTypes();
}
@VisibleForTesting
void initStandardFileTypes() {
FileTypeConsumer consumer = new FileTypeConsumer() {
@Override
public void consume(@NotNull FileType fileType) {
register(fileType, parse(fileType.getDefaultExtension()));
}
@Override
public void consume(@NotNull final FileType fileType, String extensions) {
register(fileType, parse(extensions));
}
@Override
public void consume(@NotNull final FileType fileType, @NotNull final FileNameMatcher... matchers) {
register(fileType, new ArrayList<FileNameMatcher>(Arrays.asList(matchers)));
}
@Override
public FileType getStandardFileTypeByName(@NotNull final String name) {
final StandardFileType type = myStandardFileTypes.get(name);
return type != null ? type.fileType : null;
}
private void register(@NotNull FileType fileType, @NotNull List<FileNameMatcher> fileNameMatchers) {
final StandardFileType type = myStandardFileTypes.get(fileType.getName());
if (type != null) {
type.matchers.addAll(fileNameMatchers);
}
else {
myStandardFileTypes.put(fileType.getName(), new StandardFileType(fileType, fileNameMatchers));
}
}
};
for (FileTypeFactory factory : FileTypeFactory.FILE_TYPE_FACTORY_EP.getExtensions()) {
try {
factory.createFileTypes(consumer);
}
catch (Throwable e) {
PluginManager.handleComponentError(e, factory.getClass().getName(), null);
}
}
for (StandardFileType pair : myStandardFileTypes.values()) {
registerFileTypeWithoutNotification(pair.fileType, pair.matchers, true);
}
if (PlatformUtils.isDatabaseIDE() || PlatformUtils.isCidr()) {
// build scripts are correct, but it is required to run from sources
return;
}
try {
URL defaultFileTypesUrl = FileTypeManagerImpl.class.getResource("/defaultFileTypes.xml");
if (defaultFileTypesUrl != null) {
Element defaultFileTypesElement = JDOMUtil.load(URLUtil.openStream(defaultFileTypesUrl));
for (Element e : defaultFileTypesElement.getChildren()) {
//noinspection SpellCheckingInspection
if ("filetypes".equals(e.getName())) {
for (Element element : e.getChildren(ELEMENT_FILETYPE)) {
loadFileType(element, true);
}
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(e.getName())) {
readGlobalMappings(e);
}
}
}
}
catch (Exception e) {
LOG.error(e);
}
}
private static boolean toLog() {
return RE_DETECT_ASYNC && ApplicationManager.getApplication().isUnitTestMode();
}
private static void log(@SuppressWarnings("UnusedParameters") String message) {
//System.out.println(message);
}
private final TransferToPooledThreadQueue<Collection<VirtualFile>> reDetectQueue = new TransferToPooledThreadQueue<Collection<VirtualFile>>("File type re-detect", Conditions.alwaysFalse(), -1, new Processor<Collection<VirtualFile>>() {
@Override
public boolean process(Collection<VirtualFile> files) {
reDetect(files);
return true;
}
});
@TestOnly
public void drainReDetectQueue() {
reDetectQueue.waitFor();
}
@TestOnly
@NotNull
Collection<VirtualFile> dumpReDetectQueue() {
return ContainerUtil.flatten(reDetectQueue.dump());
}
@TestOnly
static void reDetectAsync(boolean enable) {
RE_DETECT_ASYNC = enable;
}
private void reDetect(@NotNull Collection<VirtualFile> files) {
final List<VirtualFile> changed = new ArrayList<VirtualFile>();
for (VirtualFile file : files) {
boolean shouldRedetect = wasAutoDetectedBefore(file) && isDetectable(file);
if (toLog()) {
log("F: Redetect file: " + file.getName() + "; shouldRedetect: " + shouldRedetect);
}
if (shouldRedetect) {
int id = file instanceof VirtualFileWithId ? ((VirtualFileWithId)file).getId() : -1;
FileType before = getAutoDetectedType(file, id);
packedFlags.set(id, ATTRIBUTES_WERE_LOADED_MASK);
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
FileType after = getFileTypeByFile(file); // may be back to standard file type
if (toLog()) {
log("F: After redetect file: " + file.getName() + "; before: " + before.getName() + "; after: " + after.getName()+"; now getFileType()="+file.getFileType().getName());
}
if (before != after) {
changed.add(file);
LOG.debug(file+" type was re-detected. Was: "+before.getName()+"; now: "+after.getName());
}
}
}
if (!changed.isEmpty()) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
FileContentUtilCore.reparseFiles(changed);
}
}, ApplicationManager.getApplication().getDisposed());
}
}
private boolean wasAutoDetectedBefore(@NotNull VirtualFile file) {
if (file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) != null) return true;
if (file instanceof VirtualFileWithId) {
int id = Math.abs(((VirtualFileWithId)file).getId());
// do not re-detect binary files
return (packedFlags.get(id) & (AUTO_DETECT_WAS_RUN_MASK | AUTO_DETECTED_AS_BINARY_MASK)) == AUTO_DETECT_WAS_RUN_MASK;
}
return false;
}
@Override
@NotNull
public FileType getStdFileType(@NotNull @NonNls String name) {
StandardFileType stdFileType = myStandardFileTypes.get(name);
return stdFileType != null ? stdFileType.fileType : PlainTextFileType.INSTANCE;
}
@Override
public void disposeComponent() {
}
@Override
public void initComponent() {
if (!myUnresolvedMappings.isEmpty()) {
for (StandardFileType pair : myStandardFileTypes.values()) {
registerReDetectedMappings(pair);
}
}
// Resolve unresolved mappings initialized before certain plugin initialized.
for (StandardFileType pair : myStandardFileTypes.values()) {
bindUnresolvedMappings(pair.fileType);
}
boolean isAtLeastOneStandardFileTypeHasBeenRead = false;
for (AbstractFileType fileType : mySchemesManager.loadSchemes()) {
isAtLeastOneStandardFileTypeHasBeenRead |= myInitialAssociations.hasAssociationsFor(fileType);
}
if (isAtLeastOneStandardFileTypeHasBeenRead) {
restoreStandardFileExtensions();
}
}
@Override
@NotNull
public FileType getFileTypeByFileName(@NotNull String fileName) {
return getFileTypeByFileName((CharSequence)fileName);
}
@NotNull
private FileType getFileTypeByFileName(@NotNull CharSequence fileName) {
FileType type = myPatternsTable.findAssociatedFileType(fileName);
return type == null ? UnknownFileType.INSTANCE : type;
}
public static void cacheFileType(@NotNull VirtualFile file, @Nullable FileType fileType) {
file.putUserData(FILE_TYPE_KEY, fileType);
if (toLog()) {
log("F: Cached file type for "+file.getName()+" to "+(fileType == null ? null : fileType.getName()));
}
}
@Override
@NotNull
public FileType getFileTypeByFile(@NotNull VirtualFile file) {
FileType fileType = file.getUserData(FILE_TYPE_KEY);
if (fileType != null) return fileType;
if (file instanceof LightVirtualFile) {
fileType = ((LightVirtualFile)file).getAssignedFileType();
if (fileType != null) return fileType;
}
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < mySpecialFileTypes.size(); i++) {
FileTypeIdentifiableByVirtualFile type = mySpecialFileTypes.get(i);
if (type.isMyFileType(file)) {
if (toLog()) {
log("F: Special file type for "+file.getName()+"; type: "+type.getName());
}
return type;
}
}
fileType = getFileTypeByFileName(file.getNameSequence());
if (fileType != UnknownFileType.INSTANCE) {
if (toLog()) {
log("F: By name file type for "+file.getName()+"; type: "+fileType.getName());
}
return fileType;
}
if (!(file instanceof StubVirtualFile)) {
fileType = getOrDetectFromContent(file);
}
return fileType;
}
@NotNull
private FileType getOrDetectFromContent(@NotNull VirtualFile file) {
if (!isDetectable(file)) return UnknownFileType.INSTANCE;
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
if (id < 0) return UnknownFileType.INSTANCE;
//boolean autoDetectWasRun = this.autoDetectWasRun.get(id);
long flags = packedFlags.get(id);
boolean autoDetectWasRun = (flags & AUTO_DETECT_WAS_RUN_MASK) != 0;
if (autoDetectWasRun) {
FileType type = getAutoDetectedType(file, id);
if (toLog()) {
log("F: autodetected getFileType("+file.getName()+") = "+type.getName());
}
return type;
}
boolean wasDetectedAsText = false;
boolean wasDetectedAsBinary = false;
boolean wasAutoDetectRun = false;
if ((flags & ATTRIBUTES_WERE_LOADED_MASK) == 0) {
DataInputStream stream = autoDetectedAttribute.readAttribute(file);
try {
try {
byte status = stream != null ? stream.readByte() : 0;
wasAutoDetectRun = stream != null;
wasDetectedAsText = BitUtil.isSet(status, AUTO_DETECTED_AS_TEXT_MASK);
wasDetectedAsBinary = BitUtil.isSet(status, AUTO_DETECTED_AS_BINARY_MASK);
}
finally {
if (stream != null) {
stream.close();
}
}
}
catch (IOException ignored) {
}
flags = ATTRIBUTES_WERE_LOADED_MASK;
flags = BitUtil.set(flags, AUTO_DETECTED_AS_TEXT_MASK, wasDetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasDetectedAsBinary);
flags = BitUtil.set(flags, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun);
packedFlags.set(id, flags);
}
if (wasAutoDetectRun && (wasDetectedAsText || wasDetectedAsBinary)) {
return wasDetectedAsText ? FileTypes.PLAIN_TEXT : UnknownFileType.INSTANCE;
}
}
FileType fileType = file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY);
// run autodetection
if (fileType == null) {
fileType = detectFromContent(file);
}
if (toLog()) {
log("F: getFileType after detect run("+file.getName()+") = "+fileType.getName());
}
return fileType;
}
@NotNull
private FileType getAutoDetectedType(@NotNull VirtualFile file, int id) {
long flags = packedFlags.get(id);
return BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK) ? FileTypes.PLAIN_TEXT :
BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK) ? UnknownFileType.INSTANCE :
ObjectUtils.notNull(file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY), FileTypes.PLAIN_TEXT);
}
@NotNull
@Override
@Deprecated
public FileType detectFileTypeFromContent(@NotNull VirtualFile file) {
return file.getFileType();
}
private volatile FileAttribute autoDetectedAttribute;
private void cacheAutoDetectedFileType(@NotNull VirtualFile file, @NotNull FileType fileType) {
DataOutputStream stream = autoDetectedAttribute.writeAttribute(file);
boolean wasAutodetectedAsText = fileType == FileTypes.PLAIN_TEXT;
boolean wasAutodetectedAsBinary = fileType == FileTypes.UNKNOWN;
try {
try {
int flags = BitUtil.set(0, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
stream.writeByte(flags);
}
finally {
stream.close();
}
}
catch (IOException e) {
LOG.error(e);
}
if (file instanceof VirtualFileWithId) {
int id = Math.abs(((VirtualFileWithId)file).getId());
int flags = AUTO_DETECT_WAS_RUN_MASK | ATTRIBUTES_WERE_LOADED_MASK;
flags = BitUtil.set(flags, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
packedFlags.set(id, flags);
if (wasAutodetectedAsText || wasAutodetectedAsBinary) {
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
return;
}
}
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, fileType);
}
@Override
public FileType findFileTypeByName(String fileTypeName) {
FileType type = getStdFileType(fileTypeName);
// TODO: Abstract file types are not std one, so need to be restored specially,
// currently there are 6 of them and restoration does not happen very often so just iteration is enough
if (type == PlainTextFileType.INSTANCE && !fileTypeName.equals(type.getName())) {
for (FileType fileType: mySchemesManager.getAllSchemes()) {
if (fileTypeName.equals(fileType.getName())) {
return fileType;
}
}
}
return type;
}
private static boolean isDetectable(@NotNull final VirtualFile file) {
if (file.isDirectory() || !file.isValid() || file.is(VFileProperty.SPECIAL) || file.getLength() == 0) {
// for empty file there is still hope its type will change
return false;
}
return file.getFileSystem() instanceof FileSystemInterface && !SingleRootFileViewProvider.isTooLargeForContentLoading(file);
}
@NotNull
private FileType detectFromContent(@NotNull final VirtualFile file) {
long start = System.currentTimeMillis();
try {
final InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file);
final Ref<FileType> result = new Ref<FileType>(UnknownFileType.INSTANCE);
try {
FileUtil.processFirstBytes(inputStream, DETECT_BUFFER_SIZE, new Processor<ByteSequence>() {
@Override
public boolean process(ByteSequence byteSequence) {
boolean isText = guessIfText(file, byteSequence);
CharSequence text;
if (isText) {
byte[] bytes = Arrays.copyOf(byteSequence.getBytes(), byteSequence.getLength());
text = LoadTextUtil.getTextByBinaryPresentation(bytes, file, true, true, UnknownFileType.INSTANCE);
}
else {
text = null;
}
FileType detected = null;
for (FileTypeDetector detector : Extensions.getExtensions(FileTypeDetector.EP_NAME)) {
try {
detected = detector.detect(file, byteSequence, text);
}
catch (Exception e) {
LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e);
}
if (detected != null) break;
}
if (detected == null) {
detected = isText ? PlainTextFileType.INSTANCE : UnknownFileType.INSTANCE;
}
result.set(detected);
return true;
}
});
}
finally {
inputStream.close();
}
FileType fileType = result.get();
if (toLog()) {
log("F: Redetect run for file: " + file.getName() + "; result: "+fileType.getName());
}
if (LOG.isDebugEnabled()) {
LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect);
}
cacheAutoDetectedFileType(file, fileType);
counterAutoDetect.incrementAndGet();
long elapsed = System.currentTimeMillis() - start;
elapsedAutoDetect.addAndGet(elapsed);
return fileType;
}
catch (IOException ignored) {
return UnknownFileType.INSTANCE; // return unknown, do not cache
}
}
private static boolean guessIfText(@NotNull VirtualFile file, @NotNull ByteSequence byteSequence) {
byte[] bytes = byteSequence.getBytes();
Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessed = LoadTextUtil.guessFromContent(file, bytes, byteSequence.getLength());
if (guessed == null) return false;
file.setBOM(guessed.third);
if (guessed.first != null) {
// charset was detected unambiguously
return true;
}
// use wild guess
CharsetToolkit.GuessedEncoding guess = guessed.second;
return guess != null && (guess == CharsetToolkit.GuessedEncoding.VALID_UTF8 || guess == CharsetToolkit.GuessedEncoding.SEVEN_BIT);
}
@Override
public boolean isFileOfType(@NotNull VirtualFile file, @NotNull FileType type) {
if (type instanceof FileTypeIdentifiableByVirtualFile) {
return ((FileTypeIdentifiableByVirtualFile)type).isMyFileType(file);
}
return getFileTypeByFileName(file.getName()) == type;
}
@Override
@NotNull
public FileType getFileTypeByExtension(@NotNull String extension) {
return getFileTypeByFileName("IntelliJ_IDEA_RULES." + extension);
}
@Override
public void registerFileType(@NotNull FileType fileType) {
//noinspection deprecation
registerFileType(fileType, ArrayUtil.EMPTY_STRING_ARRAY);
}
@Override
public void registerFileType(@NotNull final FileType type, @NotNull final List<FileNameMatcher> defaultAssociations) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
fireBeforeFileTypesChanged();
registerFileTypeWithoutNotification(type, defaultAssociations, true);
fireFileTypesChanged();
}
});
}
@Override
public void unregisterFileType(@NotNull final FileType fileType) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
fireBeforeFileTypesChanged();
unregisterFileTypeWithoutNotification(fileType);
fireFileTypesChanged();
}
});
}
private void unregisterFileTypeWithoutNotification(FileType fileType) {
myPatternsTable.removeAllAssociations(fileType);
mySchemesManager.removeScheme(fileType);
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
final FileTypeIdentifiableByVirtualFile fakeFileType = (FileTypeIdentifiableByVirtualFile)fileType;
mySpecialFileTypes.remove(fakeFileType);
}
}
@Override
@NotNull
public FileType[] getRegisteredFileTypes() {
Collection<FileType> fileTypes = mySchemesManager.getAllSchemes();
return fileTypes.toArray(new FileType[fileTypes.size()]);
}
@Override
@NotNull
public String getExtension(@NotNull String fileName) {
int index = fileName.lastIndexOf('.');
if (index < 0) return "";
return fileName.substring(index + 1);
}
@Override
@NotNull
public String getIgnoredFilesList() {
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
return masks.isEmpty() ? "" : StringUtil.join(masks, ";") + ";";
}
@Override
public void setIgnoredFilesList(@NotNull String list) {
fireBeforeFileTypesChanged();
myIgnoredFileCache.clearCache();
myIgnoredPatterns.setIgnoreMasks(list);
fireFileTypesChanged();
}
@Override
public boolean isIgnoredFilesListEqualToCurrent(@NotNull String list) {
Set<String> tempSet = new THashSet<String>();
StringTokenizer tokenizer = new StringTokenizer(list, ";");
while (tokenizer.hasMoreTokens()) {
tempSet.add(tokenizer.nextToken());
}
return tempSet.equals(myIgnoredPatterns.getIgnoreMasks());
}
@Override
public boolean isFileIgnored(@NotNull String name) {
return myIgnoredPatterns.isIgnored(name);
}
@Override
public boolean isFileIgnored(@NonNls @NotNull VirtualFile file) {
return myIgnoredFileCache.isFileIgnored(file);
}
@Override
@SuppressWarnings({"deprecation"})
@NotNull
public String[] getAssociatedExtensions(@NotNull FileType type) {
return myPatternsTable.getAssociatedExtensions(type);
}
@Override
@NotNull
public List<FileNameMatcher> getAssociations(@NotNull FileType type) {
return myPatternsTable.getAssociations(type);
}
@Override
public void associate(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
associate(type, matcher, true);
}
@Override
public void removeAssociation(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
removeAssociation(type, matcher, true);
}
@Override
public void fireBeforeFileTypesChanged() {
FileTypeEvent event = new FileTypeEvent(this);
myMessageBus.syncPublisher(TOPIC).beforeFileTypesChanged(event);
}
private final AtomicInteger fileTypeChangedCount;
@Override
public void fireFileTypesChanged() {
clearCaches();
myMessageBus.syncPublisher(TOPIC).fileTypesChanged(new FileTypeEvent(this));
}
private void clearCaches() {
int count = fileTypeChangedCount.incrementAndGet();
autoDetectedAttribute = autoDetectedAttribute.newVersion(count);
PropertiesComponent.getInstance().setValue("fileTypeChangedCounter", Integer.toString(count));
packedFlags.clear();
}
private final Map<FileTypeListener, MessageBusConnection> myAdapters = new HashMap<FileTypeListener, MessageBusConnection>();
@Override
public void addFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myMessageBus.connect();
connection.subscribe(TOPIC, listener);
myAdapters.put(listener, connection);
}
@Override
public void removeFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myAdapters.remove(listener);
if (connection != null) {
connection.disconnect();
}
}
@Override
public void loadState(Element state) {
int savedVersion = StringUtilRt.parseInt(state.getAttributeValue(ATTRIBUTE_VERSION), 0);
for (Element element : state.getChildren()) {
if (element.getName().equals(ELEMENT_IGNORE_FILES)) {
myIgnoredPatterns.setIgnoreMasks(element.getAttributeValue(ATTRIBUTE_LIST));
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(element.getName())) {
readGlobalMappings(element);
}
}
if (savedVersion < 4) {
if (savedVersion == 0) {
addIgnore(".svn");
}
if (savedVersion < 2) {
restoreStandardFileExtensions();
}
addIgnore("*.pyc");
addIgnore("*.pyo");
addIgnore(".git");
}
if (savedVersion < 5) {
addIgnore("*.hprof");
}
if (savedVersion < 6) {
addIgnore("_svn");
}
if (savedVersion < 7) {
addIgnore(".hg");
}
if (savedVersion < 8) {
addIgnore("*~");
}
if (savedVersion < 9) {
addIgnore("__pycache__");
}
if (savedVersion < 10) {
addIgnore(".bundle");
}
if (savedVersion < 11) {
addIgnore("*.rbc");
}
if (savedVersion < 13) {
// we want *.lib back since it's an important user artifact for CLion, also for IDEA project itself, since we have some libs.
Set<String> masks = new LinkedHashSet<String>(myIgnoredPatterns.getIgnoreMasks());
masks.remove("*.lib");
myIgnoredPatterns.clearPatterns();
for (String each : masks) {
myIgnoredPatterns.addIgnoreMask(each);
}
}
if (savedVersion < 14) {
addIgnore(".tox");
}
myIgnoredFileCache.clearCache();
String counter = JDOMExternalizer.readString(state, "fileTypeChangedCounter");
if (counter != null) {
fileTypeChangedCount.set(StringUtilRt.parseInt(counter, 0));
autoDetectedAttribute = autoDetectedAttribute.newVersion(fileTypeChangedCount.get());
}
}
private void readGlobalMappings(@NotNull Element e) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(e)) {
FileType type = getFileTypeByName(association.getSecond());
FileNameMatcher matcher = association.getFirst();
if (type != null) {
if (PlainTextFileType.INSTANCE == type) {
FileType newFileType = myPatternsTable.findAssociatedFileType(matcher);
if (newFileType != null && newFileType != PlainTextFileType.INSTANCE && newFileType != UnknownFileType.INSTANCE) {
myRemovedMappings.put(matcher, Pair.create(newFileType, false));
}
}
associate(type, matcher, false);
}
else {
myUnresolvedMappings.put(matcher, association.getSecond());
}
}
List<Trinity<FileNameMatcher, String, Boolean>> removedAssociations = AbstractFileType.readRemovedAssociations(e);
for (Trinity<FileNameMatcher, String, Boolean> trinity : removedAssociations) {
FileType type = getFileTypeByName(trinity.getSecond());
FileNameMatcher matcher = trinity.getFirst();
if (type != null) {
removeAssociation(type, matcher, false);
}
else {
myUnresolvedRemovedMappings.put(matcher, Trinity.create(trinity.getSecond(), myUnresolvedMappings.get(matcher), trinity.getThird()));
}
}
}
private void addIgnore(@NonNls @NotNull String ignoreMask) {
myIgnoredPatterns.addIgnoreMask(ignoreMask);
}
private void restoreStandardFileExtensions() {
for (final String name : FILE_TYPES_WITH_PREDEFINED_EXTENSIONS) {
final StandardFileType stdFileType = myStandardFileTypes.get(name);
if (stdFileType != null) {
FileType fileType = stdFileType.fileType;
for (FileNameMatcher matcher : myPatternsTable.getAssociations(fileType)) {
FileType defaultFileType = myInitialAssociations.findAssociatedFileType(matcher);
if (defaultFileType != null && defaultFileType != fileType) {
removeAssociation(fileType, matcher, false);
associate(defaultFileType, matcher, false);
}
}
for (FileNameMatcher matcher : myInitialAssociations.getAssociations(fileType)) {
associate(fileType, matcher, false);
}
}
}
}
@Nullable
@Override
public Element getState() {
Element state = new Element("state");
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
String ignoreFiles;
if (masks.isEmpty()) {
ignoreFiles = "";
}
else {
String[] strings = ArrayUtil.toStringArray(masks);
Arrays.sort(strings);
ignoreFiles = StringUtil.join(strings, ";") + ";";
}
if (!ignoreFiles.equalsIgnoreCase(DEFAULT_IGNORED)) {
// empty means empty list - we need to distinguish null and empty to apply or not to apply default value
state.addContent(new Element(ELEMENT_IGNORE_FILES).setAttribute(ATTRIBUTE_LIST, ignoreFiles));
}
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
List<FileType> notExternalizableFileTypes = new ArrayList<FileType>();
for (FileType type : mySchemesManager.getAllSchemes()) {
if (!(type instanceof AbstractFileType)) {
notExternalizableFileTypes.add(type);
}
}
if (!notExternalizableFileTypes.isEmpty()) {
Collections.sort(notExternalizableFileTypes, new Comparator<FileType>() {
@Override
public int compare(@NotNull FileType o1, @NotNull FileType o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (FileType type : notExternalizableFileTypes) {
writeExtensionsMap(map, type, true);
}
}
if (!myUnresolvedMappings.isEmpty()) {
FileNameMatcher[] unresolvedMappingKeys = myUnresolvedMappings.keySet().toArray(new FileNameMatcher[myUnresolvedMappings.size()]);
Arrays.sort(unresolvedMappingKeys, new Comparator<FileNameMatcher>() {
@Override
public int compare(FileNameMatcher o1, FileNameMatcher o2) {
return o1.getPresentableString().compareTo(o2.getPresentableString());
}
});
for (FileNameMatcher fileNameMatcher : unresolvedMappingKeys) {
Element content = AbstractFileType.writeMapping(myUnresolvedMappings.get(fileNameMatcher), fileNameMatcher, true);
if (content != null) {
map.addContent(content);
}
}
}
if (!map.getChildren().isEmpty()) {
state.addContent(map);
}
if (!state.getChildren().isEmpty()) {
state.setAttribute(ATTRIBUTE_VERSION, String.valueOf(VERSION));
}
return state;
}
private void writeExtensionsMap(@NotNull Element map, @NotNull FileType type, boolean specifyTypeName) {
List<FileNameMatcher> associations = myPatternsTable.getAssociations(type);
Set<FileNameMatcher> defaultAssociations = new THashSet<FileNameMatcher>(myInitialAssociations.getAssociations(type));
for (FileNameMatcher matcher : associations) {
if (defaultAssociations.contains(matcher)) {
defaultAssociations.remove(matcher);
}
else if (shouldSave(type)) {
Element content = AbstractFileType.writeMapping(type.getName(), matcher, specifyTypeName);
if (content != null) {
map.addContent(content);
}
}
}
for (FileNameMatcher matcher : defaultAssociations) {
Element content = AbstractFileType.writeRemovedMapping(type, matcher, specifyTypeName, isApproved(matcher));
if (content != null) {
map.addContent(content);
}
}
}
private boolean isApproved(FileNameMatcher matcher) {
Pair<FileType, Boolean> pair = myRemovedMappings.get(matcher);
return pair != null && pair.getSecond();
}
// -------------------------------------------------------------------------
// Helper methods
// -------------------------------------------------------------------------
@Nullable
private FileType getFileTypeByName(@NotNull String name) {
return mySchemesManager.findSchemeByName(name);
}
@NotNull
private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited) {
if (semicolonDelimited == null) {
return Collections.emptyList();
}
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
ArrayList<FileNameMatcher> list = new ArrayList<FileNameMatcher>();
while (tokenizer.hasMoreTokens()) {
list.add(new ExtensionFileNameMatcher(tokenizer.nextToken().trim()));
}
return list;
}
/**
* Registers a standard file type. Doesn't notifyListeners any change events.
*/
private void registerFileTypeWithoutNotification(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers, boolean addScheme) {
if (addScheme) {
mySchemesManager.addNewScheme(fileType, true);
}
for (FileNameMatcher matcher : matchers) {
myPatternsTable.addAssociation(matcher, fileType);
myInitialAssociations.addAssociation(matcher, fileType);
}
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
mySpecialFileTypes.add((FileTypeIdentifiableByVirtualFile)fileType);
}
}
private void bindUnresolvedMappings(@NotNull FileType fileType) {
for (FileNameMatcher matcher : new THashSet<FileNameMatcher>(myUnresolvedMappings.keySet())) {
String name = myUnresolvedMappings.get(matcher);
if (Comparing.equal(name, fileType.getName())) {
myPatternsTable.addAssociation(matcher, fileType);
myUnresolvedMappings.remove(matcher);
}
}
for (FileNameMatcher matcher : new THashSet<FileNameMatcher>(myUnresolvedRemovedMappings.keySet())) {
Trinity<String, String, Boolean> trinity = myUnresolvedRemovedMappings.get(matcher);
if (Comparing.equal(trinity.getFirst(), fileType.getName())) {
removeAssociation(fileType, matcher, false);
myUnresolvedRemovedMappings.remove(matcher);
}
}
}
@NotNull
private FileType loadFileType(@NotNull Element typeElement, boolean isDefault) {
String fileTypeName = typeElement.getAttributeValue(ATTRIBUTE_NAME);
String fileTypeDescr = typeElement.getAttributeValue(ATTRIBUTE_DESCRIPTION);
String iconPath = typeElement.getAttributeValue("icon");
String extensionsStr = StringUtil.nullize(typeElement.getAttributeValue("extensions"));
if (isDefault && extensionsStr != null) {
// todo support wildcards
extensionsStr = filterAlreadyRegisteredExtensions(extensionsStr);
}
FileType type = isDefault ? getFileTypeByName(fileTypeName) : null;
if (type != null) {
return type;
}
Element element = typeElement.getChild(AbstractFileType.ELEMENT_HIGHLIGHTING);
if (element == null) {
for (CustomFileTypeFactory factory : CustomFileTypeFactory.EP_NAME.getExtensions()) {
type = factory.createFileType(typeElement);
if (type != null) {
break;
}
}
if (type == null) {
type = new UserBinaryFileType();
}
}
else {
SyntaxTable table = AbstractFileType.readSyntaxTable(element);
type = new AbstractFileType(table);
((AbstractFileType)type).initSupport();
}
setFileTypeAttributes((UserFileType)type, fileTypeName, fileTypeDescr, iconPath);
registerFileTypeWithoutNotification(type, parse(extensionsStr), isDefault);
if (isDefault) {
myDefaultTypes.add(type);
if (type instanceof ExternalizableFileType) {
((ExternalizableFileType)type).markDefaultSettings();
}
}
else {
Element extensions = typeElement.getChild(AbstractFileType.ELEMENT_EXTENSION_MAP);
if (extensions != null) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(extensions)) {
associate(type, association.getFirst(), false);
}
for (Trinity<FileNameMatcher, String, Boolean> removedAssociation : AbstractFileType.readRemovedAssociations(extensions)) {
removeAssociation(type, removedAssociation.getFirst(), false);
}
}
}
return type;
}
@Nullable
private String filterAlreadyRegisteredExtensions(@NotNull String semicolonDelimited) {
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
StringBuilder builder = null;
while (tokenizer.hasMoreTokens()) {
String extension = tokenizer.nextToken().trim();
if (getFileTypeByExtension(extension) == UnknownFileType.INSTANCE) {
if (builder == null) {
builder = new StringBuilder();
}
else if (builder.length() > 0) {
builder.append(FileTypeConsumer.EXTENSION_DELIMITER);
}
builder.append(extension);
}
}
return builder == null ? null : builder.toString();
}
private static void setFileTypeAttributes(@NotNull UserFileType fileType, @Nullable String name, @Nullable String description, @Nullable String iconPath) {
if (!StringUtil.isEmptyOrSpaces(iconPath)) {
fileType.setIcon(IconLoader.getIcon(iconPath));
}
if (description != null) {
fileType.setDescription(description);
}
if (name != null) {
fileType.setName(name);
}
}
private static boolean shouldSave(FileType fileType) {
return fileType != FileTypes.UNKNOWN && !fileType.isReadOnly();
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
@Override
@NotNull
public String getComponentName() {
return getFileTypeComponentName();
}
public static String getFileTypeComponentName() {
return PlatformUtils.isIdeaCommunity() ? "CommunityFileTypes" : "FileTypeManager";
}
@NotNull
FileTypeAssocTable getExtensionMap() {
return myPatternsTable;
}
void setPatternsTable(@NotNull Set<FileType> fileTypes, @NotNull FileTypeAssocTable<FileType> assocTable) {
fireBeforeFileTypesChanged();
for (FileType existing : getRegisteredFileTypes()) {
if (!fileTypes.contains(existing)) {
mySchemesManager.removeScheme(existing);
}
}
for (FileType fileType : fileTypes) {
mySchemesManager.addNewScheme(fileType, true);
if (fileType instanceof AbstractFileType) {
((AbstractFileType)fileType).initSupport();
}
}
myPatternsTable = assocTable.copy();
fireFileTypesChanged();
}
public void associate(FileType fileType, FileNameMatcher matcher, boolean fireChange) {
if (!myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.addAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
public void removeAssociation(FileType fileType, FileNameMatcher matcher, boolean fireChange) {
if (myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.removeAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
@Override
@Nullable
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file) {
FileType type = file.getFileType();
if (type != UnknownFileType.INSTANCE) return type;
return FileTypeChooser.getKnownFileTypeOrAssociate(file.getName());
}
@Override
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @NotNull Project project) {
return FileTypeChooser.getKnownFileTypeOrAssociate(file, project);
}
private void registerReDetectedMappings(StandardFileType pair) {
FileType fileType = pair.fileType;
if (fileType == PlainTextFileType.INSTANCE) return;
for (FileNameMatcher matcher : pair.matchers) {
registerReDetectedMapping(fileType, matcher);
if (matcher instanceof ExtensionFileNameMatcher) {
// also check exact file name matcher
ExtensionFileNameMatcher extMatcher = (ExtensionFileNameMatcher)matcher;
registerReDetectedMapping(fileType, new ExactFileNameMatcher("." + extMatcher.getExtension()));
}
}
}
private void registerReDetectedMapping(@NotNull FileType fileType, @NotNull FileNameMatcher matcher) {
String typeName = myUnresolvedMappings.get(matcher);
if (typeName != null && !typeName.equals(fileType.getName())) {
Trinity<String, String, Boolean> trinity = myUnresolvedRemovedMappings.get(matcher);
myRemovedMappings.put(matcher, Pair.create(fileType, trinity != null && trinity.third));
}
}
Map<FileNameMatcher, Pair<FileType, Boolean>> getRemovedMappings() {
return myRemovedMappings;
}
@TestOnly
void clearForTests() {
myStandardFileTypes.clear();
myUnresolvedMappings.clear();
mySchemesManager.clearAllSchemes();
}
@Override
public void dispose() {
LOG.info("FileTypeManager: "+ counterAutoDetect +" auto-detected files\nElapsed time on auto-detect: "+elapsedAutoDetect+" ms");
}
}
|
platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.fileTypes.impl;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.ide.highlighter.custom.SyntaxTable;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.TransferToPooledThreadQueue;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.fileTypes.ex.*;
import com.intellij.openapi.options.BaseSchemeProcessor;
import com.intellij.openapi.options.SchemesManager;
import com.intellij.openapi.options.SchemesManagerFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.ByteSequence;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.BulkFileListener;
import com.intellij.openapi.vfs.newvfs.FileAttribute;
import com.intellij.openapi.vfs.newvfs.FileSystemInterface;
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
import com.intellij.psi.SingleRootFileViewProvider;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.*;
import com.intellij.util.containers.ConcurrentPackedBitsArray;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@State(
name = "FileTypeManager",
storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/filetypes.xml"),
additionalExportFile = FileTypeManagerImpl.FILE_SPEC
)
public class FileTypeManagerImpl extends FileTypeManagerEx implements PersistentStateComponent<Element>, ApplicationComponent, Disposable {
private static final Logger LOG = Logger.getInstance(FileTypeManagerImpl.class);
// You must update all existing default configurations accordingly
private static final int VERSION = 13;
private static final Key<FileType> FILE_TYPE_KEY = Key.create("FILE_TYPE_KEY");
// cached auto-detected file type. If the file was auto-detected as plain text or binary
// then the value is null and autoDetectedAsText, autoDetectedAsBinary and autoDetectWasRun sets are used instead.
private static final Key<FileType> DETECTED_FROM_CONTENT_FILE_TYPE_KEY = Key.create("DETECTED_FROM_CONTENT_FILE_TYPE_KEY");
private static final int DETECT_BUFFER_SIZE = 8192; // the number of bytes to read from the file to feed to the file type detector
@NonNls
private static final String DEFAULT_IGNORED =
"*.hprof;*.pyc;*.pyo;*.rbc;*~;.DS_Store;.bundle;.git;.hg;.svn;CVS;RCS;SCCS;__pycache__;_svn;rcs;vssver.scc;vssver2.scc;";
private static boolean RE_DETECT_ASYNC = !ApplicationManager.getApplication().isUnitTestMode();
private final Set<FileType> myDefaultTypes = new THashSet<FileType>();
private final List<FileTypeIdentifiableByVirtualFile> mySpecialFileTypes = new ArrayList<FileTypeIdentifiableByVirtualFile>();
private FileTypeAssocTable<FileType> myPatternsTable = new FileTypeAssocTable<FileType>();
private final IgnoredPatternSet myIgnoredPatterns = new IgnoredPatternSet();
private final IgnoredFileCache myIgnoredFileCache = new IgnoredFileCache(myIgnoredPatterns);
private final FileTypeAssocTable<FileType> myInitialAssociations = new FileTypeAssocTable<FileType>();
private final Map<FileNameMatcher, String> myUnresolvedMappings = new THashMap<FileNameMatcher, String>();
private final Map<FileNameMatcher, Trinity<String, String, Boolean>> myUnresolvedRemovedMappings = new THashMap<FileNameMatcher, Trinity<String, String, Boolean>>();
/** This will contain removed mappings with "approved" states */
private final Map<FileNameMatcher, Pair<FileType, Boolean>> myRemovedMappings = new THashMap<FileNameMatcher, Pair<FileType, Boolean>>();
@NonNls private static final String ELEMENT_FILETYPE = "filetype";
@NonNls private static final String ELEMENT_IGNORE_FILES = "ignoreFiles";
@NonNls private static final String ATTRIBUTE_LIST = "list";
@NonNls private static final String ATTRIBUTE_VERSION = "version";
@NonNls private static final String ATTRIBUTE_NAME = "name";
@NonNls private static final String ATTRIBUTE_DESCRIPTION = "description";
private static class StandardFileType {
@NotNull private final FileType fileType;
@NotNull private final List<FileNameMatcher> matchers;
private StandardFileType(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers) {
this.fileType = fileType;
this.matchers = matchers;
}
}
private final MessageBus myMessageBus;
private final Map<String, StandardFileType> myStandardFileTypes = new LinkedHashMap<String, StandardFileType>();
@NonNls
private static final String[] FILE_TYPES_WITH_PREDEFINED_EXTENSIONS = {"JSP", "JSPX", "DTD", "HTML", "Properties", "XHTML"};
private final SchemesManager<FileType, AbstractFileType> mySchemesManager;
@NonNls
static final String FILE_SPEC = StoragePathMacros.ROOT_CONFIG + "/filetypes";
// these flags are stored in 'packedFlags' as chunks of four bits
private static final int AUTO_DETECTED_AS_TEXT_MASK = 1;
private static final int AUTO_DETECTED_AS_BINARY_MASK = 2;
private static final int AUTO_DETECT_WAS_RUN_MASK = 4;
private static final int ATTRIBUTES_WERE_LOADED_MASK = 8;
private final ConcurrentPackedBitsArray packedFlags = new ConcurrentPackedBitsArray(4);
private final AtomicInteger counterAutoDetect = new AtomicInteger();
private final AtomicLong elapsedAutoDetect = new AtomicLong();
public FileTypeManagerImpl(MessageBus bus, SchemesManagerFactory schemesManagerFactory, PropertiesComponent propertiesComponent) {
int fileTypeChangedCounter = StringUtilRt.parseInt(propertiesComponent.getValue("fileTypeChangedCounter"), 0);
fileTypeChangedCount = new AtomicInteger(fileTypeChangedCounter);
autoDetectedAttribute = new FileAttribute("AUTO_DETECTION_CACHE_ATTRIBUTE", fileTypeChangedCounter, true);
myMessageBus = bus;
mySchemesManager = schemesManagerFactory.createSchemesManager(FILE_SPEC, new BaseSchemeProcessor<AbstractFileType>() {
@NotNull
@Override
public AbstractFileType readScheme(@NotNull Element element, boolean duringLoad) {
if (!duringLoad) {
fireBeforeFileTypesChanged();
}
AbstractFileType type = (AbstractFileType)loadFileType(element, false);
if (!duringLoad) {
fireFileTypesChanged();
}
return type;
}
@NotNull
@Override
public State getState(@NotNull AbstractFileType fileType) {
if (!shouldSave(fileType)) {
return State.NON_PERSISTENT;
}
if (!myDefaultTypes.contains(fileType)) {
return State.POSSIBLY_CHANGED;
}
return fileType.isModified() ? State.POSSIBLY_CHANGED : State.NON_PERSISTENT;
}
@Override
public Element writeScheme(@NotNull AbstractFileType fileType) {
Element root = new Element(ELEMENT_FILETYPE);
root.setAttribute("binary", String.valueOf(fileType.isBinary()));
if (!StringUtil.isEmpty(fileType.getDefaultExtension())) {
root.setAttribute("default_extension", fileType.getDefaultExtension());
}
root.setAttribute(ATTRIBUTE_DESCRIPTION, fileType.getDescription());
root.setAttribute(ATTRIBUTE_NAME, fileType.getName());
fileType.writeExternal(root);
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
writeExtensionsMap(map, fileType, false);
if (!map.getChildren().isEmpty()) {
root.addContent(map);
}
return root;
}
@Override
public void onSchemeDeleted(@NotNull AbstractFileType scheme) {
fireBeforeFileTypesChanged();
myPatternsTable.removeAllAssociations(scheme);
fireFileTypesChanged();
}
}, RoamingType.PER_USER);
bus.connect().subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener.Adapter() {
@Override
public void after(@NotNull List<? extends VFileEvent> events) {
Collection<VirtualFile> files = ContainerUtil.map2Set(events, new Function<VFileEvent, VirtualFile>() {
@Override
public VirtualFile fun(VFileEvent event) {
VirtualFile file = event instanceof VFileCreateEvent ? null : event.getFile();
return file != null && wasAutoDetectedBefore(file) && isDetectable(file) ? file : null;
}
});
files.remove(null);
if (toLog()) {
log("F: VFS events: " + events);
}
if (!files.isEmpty() && RE_DETECT_ASYNC) {
if (toLog()) {
log("F: queued to redetect: " + files);
}
reDetectQueue.offerIfAbsent(files);
}
}
});
//noinspection SpellCheckingInspection
myIgnoredPatterns.setIgnoreMasks(DEFAULT_IGNORED);
// this should be done BEFORE reading state
initStandardFileTypes();
}
@VisibleForTesting
void initStandardFileTypes() {
FileTypeConsumer consumer = new FileTypeConsumer() {
@Override
public void consume(@NotNull FileType fileType) {
register(fileType, parse(fileType.getDefaultExtension()));
}
@Override
public void consume(@NotNull final FileType fileType, String extensions) {
register(fileType, parse(extensions));
}
@Override
public void consume(@NotNull final FileType fileType, @NotNull final FileNameMatcher... matchers) {
register(fileType, new ArrayList<FileNameMatcher>(Arrays.asList(matchers)));
}
@Override
public FileType getStandardFileTypeByName(@NotNull final String name) {
final StandardFileType type = myStandardFileTypes.get(name);
return type != null ? type.fileType : null;
}
private void register(@NotNull FileType fileType, @NotNull List<FileNameMatcher> fileNameMatchers) {
final StandardFileType type = myStandardFileTypes.get(fileType.getName());
if (type != null) {
type.matchers.addAll(fileNameMatchers);
}
else {
myStandardFileTypes.put(fileType.getName(), new StandardFileType(fileType, fileNameMatchers));
}
}
};
for (FileTypeFactory factory : FileTypeFactory.FILE_TYPE_FACTORY_EP.getExtensions()) {
try {
factory.createFileTypes(consumer);
}
catch (Throwable e) {
PluginManager.handleComponentError(e, factory.getClass().getName(), null);
}
}
for (StandardFileType pair : myStandardFileTypes.values()) {
registerFileTypeWithoutNotification(pair.fileType, pair.matchers, true);
}
if (PlatformUtils.isDatabaseIDE() || PlatformUtils.isCidr()) {
// build scripts are correct, but it is required to run from sources
return;
}
try {
URL defaultFileTypesUrl = FileTypeManagerImpl.class.getResource("/defaultFileTypes.xml");
if (defaultFileTypesUrl != null) {
Element defaultFileTypesElement = JDOMUtil.load(URLUtil.openStream(defaultFileTypesUrl));
for (Element e : defaultFileTypesElement.getChildren()) {
//noinspection SpellCheckingInspection
if ("filetypes".equals(e.getName())) {
for (Element element : e.getChildren(ELEMENT_FILETYPE)) {
loadFileType(element, true);
}
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(e.getName())) {
readGlobalMappings(e);
}
}
}
}
catch (Exception e) {
LOG.error(e);
}
}
private static boolean toLog() {
return RE_DETECT_ASYNC && ApplicationManager.getApplication().isUnitTestMode();
}
private static void log(@SuppressWarnings("UnusedParameters") String message) {
//System.out.println(message);
}
private final TransferToPooledThreadQueue<Collection<VirtualFile>> reDetectQueue = new TransferToPooledThreadQueue<Collection<VirtualFile>>("File type re-detect", Conditions.alwaysFalse(), -1, new Processor<Collection<VirtualFile>>() {
@Override
public boolean process(Collection<VirtualFile> files) {
reDetect(files);
return true;
}
});
@TestOnly
public void drainReDetectQueue() {
reDetectQueue.waitFor();
}
@TestOnly
@NotNull
Collection<VirtualFile> dumpReDetectQueue() {
return ContainerUtil.flatten(reDetectQueue.dump());
}
@TestOnly
static void reDetectAsync(boolean enable) {
RE_DETECT_ASYNC = enable;
}
private void reDetect(@NotNull Collection<VirtualFile> files) {
final List<VirtualFile> changed = new ArrayList<VirtualFile>();
for (VirtualFile file : files) {
boolean shouldRedetect = wasAutoDetectedBefore(file) && isDetectable(file);
if (toLog()) {
log("F: Redetect file: " + file.getName() + "; shouldRedetect: " + shouldRedetect);
}
if (shouldRedetect) {
int id = file instanceof VirtualFileWithId ? ((VirtualFileWithId)file).getId() : -1;
FileType before = getAutoDetectedType(file, id);
packedFlags.set(id, ATTRIBUTES_WERE_LOADED_MASK);
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
FileType after = getFileTypeByFile(file); // may be back to standard file type
if (toLog()) {
log("F: After redetect file: " + file.getName() + "; before: " + before.getName() + "; after: " + after.getName()+"; now getFileType()="+file.getFileType().getName());
}
if (before != after) {
changed.add(file);
LOG.debug(file+" type was re-detected. Was: "+before.getName()+"; now: "+after.getName());
}
}
}
if (!changed.isEmpty()) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
FileContentUtilCore.reparseFiles(changed);
}
}, ApplicationManager.getApplication().getDisposed());
}
}
private boolean wasAutoDetectedBefore(@NotNull VirtualFile file) {
if (file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY) != null) return true;
if (file instanceof VirtualFileWithId) {
int id = Math.abs(((VirtualFileWithId)file).getId());
// do not re-detect binary files
return (packedFlags.get(id) & (AUTO_DETECT_WAS_RUN_MASK | AUTO_DETECTED_AS_BINARY_MASK)) == AUTO_DETECT_WAS_RUN_MASK;
}
return false;
}
@Override
@NotNull
public FileType getStdFileType(@NotNull @NonNls String name) {
StandardFileType stdFileType = myStandardFileTypes.get(name);
return stdFileType != null ? stdFileType.fileType : PlainTextFileType.INSTANCE;
}
@Override
public void disposeComponent() {
}
@Override
public void initComponent() {
if (!myUnresolvedMappings.isEmpty()) {
for (StandardFileType pair : myStandardFileTypes.values()) {
registerReDetectedMappings(pair);
}
}
// Resolve unresolved mappings initialized before certain plugin initialized.
for (StandardFileType pair : myStandardFileTypes.values()) {
bindUnresolvedMappings(pair.fileType);
}
boolean isAtLeastOneStandardFileTypeHasBeenRead = false;
for (AbstractFileType fileType : mySchemesManager.loadSchemes()) {
isAtLeastOneStandardFileTypeHasBeenRead |= myInitialAssociations.hasAssociationsFor(fileType);
}
if (isAtLeastOneStandardFileTypeHasBeenRead) {
restoreStandardFileExtensions();
}
}
@Override
@NotNull
public FileType getFileTypeByFileName(@NotNull String fileName) {
return getFileTypeByFileName((CharSequence)fileName);
}
@NotNull
private FileType getFileTypeByFileName(@NotNull CharSequence fileName) {
FileType type = myPatternsTable.findAssociatedFileType(fileName);
return type == null ? UnknownFileType.INSTANCE : type;
}
public static void cacheFileType(@NotNull VirtualFile file, @Nullable FileType fileType) {
file.putUserData(FILE_TYPE_KEY, fileType);
if (toLog()) {
log("F: Cached file type for "+file.getName()+" to "+(fileType == null ? null : fileType.getName()));
}
}
@Override
@NotNull
public FileType getFileTypeByFile(@NotNull VirtualFile file) {
FileType fileType = file.getUserData(FILE_TYPE_KEY);
if (fileType != null) return fileType;
if (file instanceof LightVirtualFile) {
fileType = ((LightVirtualFile)file).getAssignedFileType();
if (fileType != null) return fileType;
}
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < mySpecialFileTypes.size(); i++) {
FileTypeIdentifiableByVirtualFile type = mySpecialFileTypes.get(i);
if (type.isMyFileType(file)) {
if (toLog()) {
log("F: Special file type for "+file.getName()+"; type: "+type.getName());
}
return type;
}
}
fileType = getFileTypeByFileName(file.getNameSequence());
if (fileType != UnknownFileType.INSTANCE) {
if (toLog()) {
log("F: By name file type for "+file.getName()+"; type: "+fileType.getName());
}
return fileType;
}
if (!(file instanceof StubVirtualFile)) {
fileType = getOrDetectFromContent(file);
}
return fileType;
}
@NotNull
private FileType getOrDetectFromContent(@NotNull VirtualFile file) {
if (!isDetectable(file)) return UnknownFileType.INSTANCE;
if (file instanceof VirtualFileWithId) {
int id = ((VirtualFileWithId)file).getId();
if (id < 0) return UnknownFileType.INSTANCE;
//boolean autoDetectWasRun = this.autoDetectWasRun.get(id);
long flags = packedFlags.get(id);
boolean autoDetectWasRun = (flags & AUTO_DETECT_WAS_RUN_MASK) != 0;
if (autoDetectWasRun) {
FileType type = getAutoDetectedType(file, id);
if (toLog()) {
log("F: autodetected getFileType("+file.getName()+") = "+type.getName());
}
return type;
}
boolean wasDetectedAsText = false;
boolean wasDetectedAsBinary = false;
boolean wasAutoDetectRun = false;
if ((flags & ATTRIBUTES_WERE_LOADED_MASK) == 0) {
DataInputStream stream = autoDetectedAttribute.readAttribute(file);
try {
try {
byte status = stream != null ? stream.readByte() : 0;
wasAutoDetectRun = stream != null;
wasDetectedAsText = BitUtil.isSet(status, AUTO_DETECTED_AS_TEXT_MASK);
wasDetectedAsBinary = BitUtil.isSet(status, AUTO_DETECTED_AS_BINARY_MASK);
}
finally {
if (stream != null) {
stream.close();
}
}
}
catch (IOException ignored) {
}
flags = ATTRIBUTES_WERE_LOADED_MASK;
flags = BitUtil.set(flags, AUTO_DETECTED_AS_TEXT_MASK, wasDetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasDetectedAsBinary);
flags = BitUtil.set(flags, AUTO_DETECT_WAS_RUN_MASK, wasAutoDetectRun);
packedFlags.set(id, flags);
}
if (wasAutoDetectRun && (wasDetectedAsText || wasDetectedAsBinary)) {
return wasDetectedAsText ? FileTypes.PLAIN_TEXT : UnknownFileType.INSTANCE;
}
}
FileType fileType = file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY);
// run autodetection
if (fileType == null) {
fileType = detectFromContent(file);
}
if (toLog()) {
log("F: getFileType after detect run("+file.getName()+") = "+fileType.getName());
}
return fileType;
}
@NotNull
private FileType getAutoDetectedType(@NotNull VirtualFile file, int id) {
long flags = packedFlags.get(id);
return BitUtil.isSet(flags, AUTO_DETECTED_AS_TEXT_MASK) ? FileTypes.PLAIN_TEXT :
BitUtil.isSet(flags, AUTO_DETECTED_AS_BINARY_MASK) ? UnknownFileType.INSTANCE :
ObjectUtils.notNull(file.getUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY), FileTypes.PLAIN_TEXT);
}
@NotNull
@Override
@Deprecated
public FileType detectFileTypeFromContent(@NotNull VirtualFile file) {
return file.getFileType();
}
private volatile FileAttribute autoDetectedAttribute;
private void cacheAutoDetectedFileType(@NotNull VirtualFile file, @NotNull FileType fileType) {
DataOutputStream stream = autoDetectedAttribute.writeAttribute(file);
boolean wasAutodetectedAsText = fileType == FileTypes.PLAIN_TEXT;
boolean wasAutodetectedAsBinary = fileType == FileTypes.UNKNOWN;
try {
try {
int flags = BitUtil.set(0, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
stream.writeByte(flags);
}
finally {
stream.close();
}
}
catch (IOException e) {
LOG.error(e);
}
if (file instanceof VirtualFileWithId) {
int id = Math.abs(((VirtualFileWithId)file).getId());
int flags = AUTO_DETECT_WAS_RUN_MASK | ATTRIBUTES_WERE_LOADED_MASK;
flags = BitUtil.set(flags, AUTO_DETECTED_AS_TEXT_MASK, wasAutodetectedAsText);
flags = BitUtil.set(flags, AUTO_DETECTED_AS_BINARY_MASK, wasAutodetectedAsBinary);
packedFlags.set(id, flags);
if (wasAutodetectedAsText || wasAutodetectedAsBinary) {
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, null);
return;
}
}
file.putUserData(DETECTED_FROM_CONTENT_FILE_TYPE_KEY, fileType);
}
@Override
public FileType findFileTypeByName(String fileTypeName) {
FileType type = getStdFileType(fileTypeName);
// TODO: Abstract file types are not std one, so need to be restored specially,
// currently there are 6 of them and restoration does not happen very often so just iteration is enough
if (type == PlainTextFileType.INSTANCE && !fileTypeName.equals(type.getName())) {
for (FileType fileType: mySchemesManager.getAllSchemes()) {
if (fileTypeName.equals(fileType.getName())) {
return fileType;
}
}
}
return type;
}
private static boolean isDetectable(@NotNull final VirtualFile file) {
if (file.isDirectory() || !file.isValid() || file.is(VFileProperty.SPECIAL) || file.getLength() == 0) {
// for empty file there is still hope its type will change
return false;
}
return file.getFileSystem() instanceof FileSystemInterface && !SingleRootFileViewProvider.isTooLargeForContentLoading(file);
}
@NotNull
private FileType detectFromContent(@NotNull final VirtualFile file) {
long start = System.currentTimeMillis();
try {
final InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file);
final Ref<FileType> result = new Ref<FileType>(UnknownFileType.INSTANCE);
try {
FileUtil.processFirstBytes(inputStream, DETECT_BUFFER_SIZE, new Processor<ByteSequence>() {
@Override
public boolean process(ByteSequence byteSequence) {
boolean isText = guessIfText(file, byteSequence);
CharSequence text;
if (isText) {
byte[] bytes = Arrays.copyOf(byteSequence.getBytes(), byteSequence.getLength());
text = LoadTextUtil.getTextByBinaryPresentation(bytes, file, true, true, UnknownFileType.INSTANCE);
}
else {
text = null;
}
FileType detected = null;
for (FileTypeDetector detector : Extensions.getExtensions(FileTypeDetector.EP_NAME)) {
try {
detected = detector.detect(file, byteSequence, text);
}
catch (Exception e) {
LOG.error("Detector " + detector + " (" + detector.getClass() + ") exception occurred:", e);
}
if (detected != null) break;
}
if (detected == null) {
detected = isText ? PlainTextFileType.INSTANCE : UnknownFileType.INSTANCE;
}
result.set(detected);
return true;
}
});
}
finally {
inputStream.close();
}
FileType fileType = result.get();
if (toLog()) {
log("F: Redetect run for file: " + file.getName() + "; result: "+fileType.getName());
}
if (LOG.isDebugEnabled()) {
LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect);
}
cacheAutoDetectedFileType(file, fileType);
counterAutoDetect.incrementAndGet();
long elapsed = System.currentTimeMillis() - start;
elapsedAutoDetect.addAndGet(elapsed);
return fileType;
}
catch (IOException ignored) {
return UnknownFileType.INSTANCE; // return unknown, do not cache
}
}
private static boolean guessIfText(@NotNull VirtualFile file, @NotNull ByteSequence byteSequence) {
byte[] bytes = byteSequence.getBytes();
Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessed = LoadTextUtil.guessFromContent(file, bytes, byteSequence.getLength());
if (guessed == null) return false;
file.setBOM(guessed.third);
if (guessed.first != null) {
// charset was detected unambiguously
return true;
}
// use wild guess
CharsetToolkit.GuessedEncoding guess = guessed.second;
return guess != null && (guess == CharsetToolkit.GuessedEncoding.VALID_UTF8 || guess == CharsetToolkit.GuessedEncoding.SEVEN_BIT);
}
@Override
public boolean isFileOfType(@NotNull VirtualFile file, @NotNull FileType type) {
if (type instanceof FileTypeIdentifiableByVirtualFile) {
return ((FileTypeIdentifiableByVirtualFile)type).isMyFileType(file);
}
return getFileTypeByFileName(file.getName()) == type;
}
@Override
@NotNull
public FileType getFileTypeByExtension(@NotNull String extension) {
return getFileTypeByFileName("IntelliJ_IDEA_RULES." + extension);
}
@Override
public void registerFileType(@NotNull FileType fileType) {
//noinspection deprecation
registerFileType(fileType, ArrayUtil.EMPTY_STRING_ARRAY);
}
@Override
public void registerFileType(@NotNull final FileType type, @NotNull final List<FileNameMatcher> defaultAssociations) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
fireBeforeFileTypesChanged();
registerFileTypeWithoutNotification(type, defaultAssociations, true);
fireFileTypesChanged();
}
});
}
@Override
public void unregisterFileType(@NotNull final FileType fileType) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
fireBeforeFileTypesChanged();
unregisterFileTypeWithoutNotification(fileType);
fireFileTypesChanged();
}
});
}
private void unregisterFileTypeWithoutNotification(FileType fileType) {
myPatternsTable.removeAllAssociations(fileType);
mySchemesManager.removeScheme(fileType);
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
final FileTypeIdentifiableByVirtualFile fakeFileType = (FileTypeIdentifiableByVirtualFile)fileType;
mySpecialFileTypes.remove(fakeFileType);
}
}
@Override
@NotNull
public FileType[] getRegisteredFileTypes() {
Collection<FileType> fileTypes = mySchemesManager.getAllSchemes();
return fileTypes.toArray(new FileType[fileTypes.size()]);
}
@Override
@NotNull
public String getExtension(@NotNull String fileName) {
int index = fileName.lastIndexOf('.');
if (index < 0) return "";
return fileName.substring(index + 1);
}
@Override
@NotNull
public String getIgnoredFilesList() {
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
return masks.isEmpty() ? "" : StringUtil.join(masks, ";") + ";";
}
@Override
public void setIgnoredFilesList(@NotNull String list) {
fireBeforeFileTypesChanged();
myIgnoredFileCache.clearCache();
myIgnoredPatterns.setIgnoreMasks(list);
fireFileTypesChanged();
}
@Override
public boolean isIgnoredFilesListEqualToCurrent(@NotNull String list) {
Set<String> tempSet = new THashSet<String>();
StringTokenizer tokenizer = new StringTokenizer(list, ";");
while (tokenizer.hasMoreTokens()) {
tempSet.add(tokenizer.nextToken());
}
return tempSet.equals(myIgnoredPatterns.getIgnoreMasks());
}
@Override
public boolean isFileIgnored(@NotNull String name) {
return myIgnoredPatterns.isIgnored(name);
}
@Override
public boolean isFileIgnored(@NonNls @NotNull VirtualFile file) {
return myIgnoredFileCache.isFileIgnored(file);
}
@Override
@SuppressWarnings({"deprecation"})
@NotNull
public String[] getAssociatedExtensions(@NotNull FileType type) {
return myPatternsTable.getAssociatedExtensions(type);
}
@Override
@NotNull
public List<FileNameMatcher> getAssociations(@NotNull FileType type) {
return myPatternsTable.getAssociations(type);
}
@Override
public void associate(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
associate(type, matcher, true);
}
@Override
public void removeAssociation(@NotNull FileType type, @NotNull FileNameMatcher matcher) {
removeAssociation(type, matcher, true);
}
@Override
public void fireBeforeFileTypesChanged() {
FileTypeEvent event = new FileTypeEvent(this);
myMessageBus.syncPublisher(TOPIC).beforeFileTypesChanged(event);
}
private final AtomicInteger fileTypeChangedCount;
@Override
public void fireFileTypesChanged() {
clearCaches();
myMessageBus.syncPublisher(TOPIC).fileTypesChanged(new FileTypeEvent(this));
}
private void clearCaches() {
int count = fileTypeChangedCount.incrementAndGet();
autoDetectedAttribute = autoDetectedAttribute.newVersion(count);
PropertiesComponent.getInstance().setValue("fileTypeChangedCounter", Integer.toString(count));
packedFlags.clear();
}
private final Map<FileTypeListener, MessageBusConnection> myAdapters = new HashMap<FileTypeListener, MessageBusConnection>();
@Override
public void addFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myMessageBus.connect();
connection.subscribe(TOPIC, listener);
myAdapters.put(listener, connection);
}
@Override
public void removeFileTypeListener(@NotNull FileTypeListener listener) {
final MessageBusConnection connection = myAdapters.remove(listener);
if (connection != null) {
connection.disconnect();
}
}
@Override
public void loadState(Element state) {
int savedVersion = StringUtilRt.parseInt(state.getAttributeValue(ATTRIBUTE_VERSION), 0);
for (Element element : state.getChildren()) {
if (element.getName().equals(ELEMENT_IGNORE_FILES)) {
myIgnoredPatterns.setIgnoreMasks(element.getAttributeValue(ATTRIBUTE_LIST));
}
else if (AbstractFileType.ELEMENT_EXTENSION_MAP.equals(element.getName())) {
readGlobalMappings(element);
}
}
if (savedVersion < 4) {
if (savedVersion == 0) {
addIgnore(".svn");
}
if (savedVersion < 2) {
restoreStandardFileExtensions();
}
addIgnore("*.pyc");
addIgnore("*.pyo");
addIgnore(".git");
}
if (savedVersion < 5) {
addIgnore("*.hprof");
}
if (savedVersion < 6) {
addIgnore("_svn");
}
if (savedVersion < 7) {
addIgnore(".hg");
}
if (savedVersion < 8) {
addIgnore("*~");
}
if (savedVersion < 9) {
addIgnore("__pycache__");
}
if (savedVersion < 10) {
addIgnore(".bundle");
}
if (savedVersion < 11) {
addIgnore("*.rbc");
}
if (savedVersion < 13) {
// we want *.lib back since it's an important user artifact for CLion, also for IDEA project itself, since we have some libs.
Set<String> masks = new LinkedHashSet<String>(myIgnoredPatterns.getIgnoreMasks());
masks.remove("*.lib");
myIgnoredPatterns.clearPatterns();
for (String each : masks) {
myIgnoredPatterns.addIgnoreMask(each);
}
}
myIgnoredFileCache.clearCache();
String counter = JDOMExternalizer.readString(state, "fileTypeChangedCounter");
if (counter != null) {
fileTypeChangedCount.set(StringUtilRt.parseInt(counter, 0));
autoDetectedAttribute = autoDetectedAttribute.newVersion(fileTypeChangedCount.get());
}
}
private void readGlobalMappings(@NotNull Element e) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(e)) {
FileType type = getFileTypeByName(association.getSecond());
FileNameMatcher matcher = association.getFirst();
if (type != null) {
if (PlainTextFileType.INSTANCE == type) {
FileType newFileType = myPatternsTable.findAssociatedFileType(matcher);
if (newFileType != null && newFileType != PlainTextFileType.INSTANCE && newFileType != UnknownFileType.INSTANCE) {
myRemovedMappings.put(matcher, Pair.create(newFileType, false));
}
}
associate(type, matcher, false);
}
else {
myUnresolvedMappings.put(matcher, association.getSecond());
}
}
List<Trinity<FileNameMatcher, String, Boolean>> removedAssociations = AbstractFileType.readRemovedAssociations(e);
for (Trinity<FileNameMatcher, String, Boolean> trinity : removedAssociations) {
FileType type = getFileTypeByName(trinity.getSecond());
FileNameMatcher matcher = trinity.getFirst();
if (type != null) {
removeAssociation(type, matcher, false);
}
else {
myUnresolvedRemovedMappings.put(matcher, Trinity.create(trinity.getSecond(), myUnresolvedMappings.get(matcher), trinity.getThird()));
}
}
}
private void addIgnore(@NonNls @NotNull String ignoreMask) {
myIgnoredPatterns.addIgnoreMask(ignoreMask);
}
private void restoreStandardFileExtensions() {
for (final String name : FILE_TYPES_WITH_PREDEFINED_EXTENSIONS) {
final StandardFileType stdFileType = myStandardFileTypes.get(name);
if (stdFileType != null) {
FileType fileType = stdFileType.fileType;
for (FileNameMatcher matcher : myPatternsTable.getAssociations(fileType)) {
FileType defaultFileType = myInitialAssociations.findAssociatedFileType(matcher);
if (defaultFileType != null && defaultFileType != fileType) {
removeAssociation(fileType, matcher, false);
associate(defaultFileType, matcher, false);
}
}
for (FileNameMatcher matcher : myInitialAssociations.getAssociations(fileType)) {
associate(fileType, matcher, false);
}
}
}
}
@Nullable
@Override
public Element getState() {
Element state = new Element("state");
Set<String> masks = myIgnoredPatterns.getIgnoreMasks();
String ignoreFiles;
if (masks.isEmpty()) {
ignoreFiles = "";
}
else {
String[] strings = ArrayUtil.toStringArray(masks);
Arrays.sort(strings);
ignoreFiles = StringUtil.join(strings, ";") + ";";
}
if (!ignoreFiles.equalsIgnoreCase(DEFAULT_IGNORED)) {
// empty means empty list - we need to distinguish null and empty to apply or not to apply default value
state.addContent(new Element(ELEMENT_IGNORE_FILES).setAttribute(ATTRIBUTE_LIST, ignoreFiles));
}
Element map = new Element(AbstractFileType.ELEMENT_EXTENSION_MAP);
List<FileType> notExternalizableFileTypes = new ArrayList<FileType>();
for (FileType type : mySchemesManager.getAllSchemes()) {
if (!(type instanceof AbstractFileType)) {
notExternalizableFileTypes.add(type);
}
}
if (!notExternalizableFileTypes.isEmpty()) {
Collections.sort(notExternalizableFileTypes, new Comparator<FileType>() {
@Override
public int compare(@NotNull FileType o1, @NotNull FileType o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (FileType type : notExternalizableFileTypes) {
writeExtensionsMap(map, type, true);
}
}
if (!myUnresolvedMappings.isEmpty()) {
FileNameMatcher[] unresolvedMappingKeys = myUnresolvedMappings.keySet().toArray(new FileNameMatcher[myUnresolvedMappings.size()]);
Arrays.sort(unresolvedMappingKeys, new Comparator<FileNameMatcher>() {
@Override
public int compare(FileNameMatcher o1, FileNameMatcher o2) {
return o1.getPresentableString().compareTo(o2.getPresentableString());
}
});
for (FileNameMatcher fileNameMatcher : unresolvedMappingKeys) {
Element content = AbstractFileType.writeMapping(myUnresolvedMappings.get(fileNameMatcher), fileNameMatcher, true);
if (content != null) {
map.addContent(content);
}
}
}
if (!map.getChildren().isEmpty()) {
state.addContent(map);
}
if (!state.getChildren().isEmpty()) {
state.setAttribute(ATTRIBUTE_VERSION, String.valueOf(VERSION));
}
return state;
}
private void writeExtensionsMap(@NotNull Element map, @NotNull FileType type, boolean specifyTypeName) {
List<FileNameMatcher> associations = myPatternsTable.getAssociations(type);
Set<FileNameMatcher> defaultAssociations = new THashSet<FileNameMatcher>(myInitialAssociations.getAssociations(type));
for (FileNameMatcher matcher : associations) {
if (defaultAssociations.contains(matcher)) {
defaultAssociations.remove(matcher);
}
else if (shouldSave(type)) {
Element content = AbstractFileType.writeMapping(type.getName(), matcher, specifyTypeName);
if (content != null) {
map.addContent(content);
}
}
}
for (FileNameMatcher matcher : defaultAssociations) {
Element content = AbstractFileType.writeRemovedMapping(type, matcher, specifyTypeName, isApproved(matcher));
if (content != null) {
map.addContent(content);
}
}
}
private boolean isApproved(FileNameMatcher matcher) {
Pair<FileType, Boolean> pair = myRemovedMappings.get(matcher);
return pair != null && pair.getSecond();
}
// -------------------------------------------------------------------------
// Helper methods
// -------------------------------------------------------------------------
@Nullable
private FileType getFileTypeByName(@NotNull String name) {
return mySchemesManager.findSchemeByName(name);
}
@NotNull
private static List<FileNameMatcher> parse(@Nullable String semicolonDelimited) {
if (semicolonDelimited == null) {
return Collections.emptyList();
}
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
ArrayList<FileNameMatcher> list = new ArrayList<FileNameMatcher>();
while (tokenizer.hasMoreTokens()) {
list.add(new ExtensionFileNameMatcher(tokenizer.nextToken().trim()));
}
return list;
}
/**
* Registers a standard file type. Doesn't notifyListeners any change events.
*/
private void registerFileTypeWithoutNotification(@NotNull FileType fileType, @NotNull List<FileNameMatcher> matchers, boolean addScheme) {
if (addScheme) {
mySchemesManager.addNewScheme(fileType, true);
}
for (FileNameMatcher matcher : matchers) {
myPatternsTable.addAssociation(matcher, fileType);
myInitialAssociations.addAssociation(matcher, fileType);
}
if (fileType instanceof FileTypeIdentifiableByVirtualFile) {
mySpecialFileTypes.add((FileTypeIdentifiableByVirtualFile)fileType);
}
}
private void bindUnresolvedMappings(@NotNull FileType fileType) {
for (FileNameMatcher matcher : new THashSet<FileNameMatcher>(myUnresolvedMappings.keySet())) {
String name = myUnresolvedMappings.get(matcher);
if (Comparing.equal(name, fileType.getName())) {
myPatternsTable.addAssociation(matcher, fileType);
myUnresolvedMappings.remove(matcher);
}
}
for (FileNameMatcher matcher : new THashSet<FileNameMatcher>(myUnresolvedRemovedMappings.keySet())) {
Trinity<String, String, Boolean> trinity = myUnresolvedRemovedMappings.get(matcher);
if (Comparing.equal(trinity.getFirst(), fileType.getName())) {
removeAssociation(fileType, matcher, false);
myUnresolvedRemovedMappings.remove(matcher);
}
}
}
@NotNull
private FileType loadFileType(@NotNull Element typeElement, boolean isDefault) {
String fileTypeName = typeElement.getAttributeValue(ATTRIBUTE_NAME);
String fileTypeDescr = typeElement.getAttributeValue(ATTRIBUTE_DESCRIPTION);
String iconPath = typeElement.getAttributeValue("icon");
String extensionsStr = StringUtil.nullize(typeElement.getAttributeValue("extensions"));
if (isDefault && extensionsStr != null) {
// todo support wildcards
extensionsStr = filterAlreadyRegisteredExtensions(extensionsStr);
}
FileType type = isDefault ? getFileTypeByName(fileTypeName) : null;
if (type != null) {
return type;
}
Element element = typeElement.getChild(AbstractFileType.ELEMENT_HIGHLIGHTING);
if (element == null) {
for (CustomFileTypeFactory factory : CustomFileTypeFactory.EP_NAME.getExtensions()) {
type = factory.createFileType(typeElement);
if (type != null) {
break;
}
}
if (type == null) {
type = new UserBinaryFileType();
}
}
else {
SyntaxTable table = AbstractFileType.readSyntaxTable(element);
type = new AbstractFileType(table);
((AbstractFileType)type).initSupport();
}
setFileTypeAttributes((UserFileType)type, fileTypeName, fileTypeDescr, iconPath);
registerFileTypeWithoutNotification(type, parse(extensionsStr), isDefault);
if (isDefault) {
myDefaultTypes.add(type);
if (type instanceof ExternalizableFileType) {
((ExternalizableFileType)type).markDefaultSettings();
}
}
else {
Element extensions = typeElement.getChild(AbstractFileType.ELEMENT_EXTENSION_MAP);
if (extensions != null) {
for (Pair<FileNameMatcher, String> association : AbstractFileType.readAssociations(extensions)) {
associate(type, association.getFirst(), false);
}
for (Trinity<FileNameMatcher, String, Boolean> removedAssociation : AbstractFileType.readRemovedAssociations(extensions)) {
removeAssociation(type, removedAssociation.getFirst(), false);
}
}
}
return type;
}
@Nullable
private String filterAlreadyRegisteredExtensions(@NotNull String semicolonDelimited) {
StringTokenizer tokenizer = new StringTokenizer(semicolonDelimited, FileTypeConsumer.EXTENSION_DELIMITER, false);
StringBuilder builder = null;
while (tokenizer.hasMoreTokens()) {
String extension = tokenizer.nextToken().trim();
if (getFileTypeByExtension(extension) == UnknownFileType.INSTANCE) {
if (builder == null) {
builder = new StringBuilder();
}
else if (builder.length() > 0) {
builder.append(FileTypeConsumer.EXTENSION_DELIMITER);
}
builder.append(extension);
}
}
return builder == null ? null : builder.toString();
}
private static void setFileTypeAttributes(@NotNull UserFileType fileType, @Nullable String name, @Nullable String description, @Nullable String iconPath) {
if (!StringUtil.isEmptyOrSpaces(iconPath)) {
fileType.setIcon(IconLoader.getIcon(iconPath));
}
if (description != null) {
fileType.setDescription(description);
}
if (name != null) {
fileType.setName(name);
}
}
private static boolean shouldSave(FileType fileType) {
return fileType != FileTypes.UNKNOWN && !fileType.isReadOnly();
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
@Override
@NotNull
public String getComponentName() {
return getFileTypeComponentName();
}
public static String getFileTypeComponentName() {
return PlatformUtils.isIdeaCommunity() ? "CommunityFileTypes" : "FileTypeManager";
}
@NotNull
FileTypeAssocTable getExtensionMap() {
return myPatternsTable;
}
void setPatternsTable(@NotNull Set<FileType> fileTypes, @NotNull FileTypeAssocTable<FileType> assocTable) {
fireBeforeFileTypesChanged();
for (FileType existing : getRegisteredFileTypes()) {
if (!fileTypes.contains(existing)) {
mySchemesManager.removeScheme(existing);
}
}
for (FileType fileType : fileTypes) {
mySchemesManager.addNewScheme(fileType, true);
if (fileType instanceof AbstractFileType) {
((AbstractFileType)fileType).initSupport();
}
}
myPatternsTable = assocTable.copy();
fireFileTypesChanged();
}
public void associate(FileType fileType, FileNameMatcher matcher, boolean fireChange) {
if (!myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.addAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
public void removeAssociation(FileType fileType, FileNameMatcher matcher, boolean fireChange) {
if (myPatternsTable.isAssociatedWith(fileType, matcher)) {
if (fireChange) {
fireBeforeFileTypesChanged();
}
myPatternsTable.removeAssociation(matcher, fileType);
if (fireChange) {
fireFileTypesChanged();
}
}
}
@Override
@Nullable
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file) {
FileType type = file.getFileType();
if (type != UnknownFileType.INSTANCE) return type;
return FileTypeChooser.getKnownFileTypeOrAssociate(file.getName());
}
@Override
public FileType getKnownFileTypeOrAssociate(@NotNull VirtualFile file, @NotNull Project project) {
return FileTypeChooser.getKnownFileTypeOrAssociate(file, project);
}
private void registerReDetectedMappings(StandardFileType pair) {
FileType fileType = pair.fileType;
if (fileType == PlainTextFileType.INSTANCE) return;
for (FileNameMatcher matcher : pair.matchers) {
registerReDetectedMapping(fileType, matcher);
if (matcher instanceof ExtensionFileNameMatcher) {
// also check exact file name matcher
ExtensionFileNameMatcher extMatcher = (ExtensionFileNameMatcher)matcher;
registerReDetectedMapping(fileType, new ExactFileNameMatcher("." + extMatcher.getExtension()));
}
}
}
private void registerReDetectedMapping(@NotNull FileType fileType, @NotNull FileNameMatcher matcher) {
String typeName = myUnresolvedMappings.get(matcher);
if (typeName != null && !typeName.equals(fileType.getName())) {
Trinity<String, String, Boolean> trinity = myUnresolvedRemovedMappings.get(matcher);
myRemovedMappings.put(matcher, Pair.create(fileType, trinity != null && trinity.third));
}
}
Map<FileNameMatcher, Pair<FileType, Boolean>> getRemovedMappings() {
return myRemovedMappings;
}
@TestOnly
void clearForTests() {
myStandardFileTypes.clear();
myUnresolvedMappings.clear();
mySchemesManager.clearAllSchemes();
}
@Override
public void dispose() {
LOG.info("FileTypeManager: "+ counterAutoDetect +" auto-detected files\nElapsed time on auto-detect: "+elapsedAutoDetect+" ms");
}
}
|
Exclude .tox folders from indexing.
|
platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java
|
Exclude .tox folders from indexing.
|
|
Java
|
apache-2.0
|
e20a975e6e6b64a717ee1a524c37438099dbecfa
| 0
|
vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,da1z/intellij-community,ibinti/intellij-community,signed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,signed/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,da1z/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,allotria/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,da1z/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,semonte/intellij-community,semonte/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,semonte/intellij-community,allotria/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,ibinti/intellij-community,signed/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,signed/intellij-community,signed/intellij-community,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,allotria/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,FHannes/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,asedunov/intellij-community,signed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,allotria/intellij-community,semonte/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.dom;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.xml.XmlElement;
import com.intellij.util.xml.DomElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.model.MavenDomConfiguration;
import org.jetbrains.idea.maven.dom.model.MavenDomPlugin;
import org.jetbrains.idea.maven.dom.plugin.MavenDomPluginModel;
import org.jetbrains.idea.maven.model.MavenId;
import org.jetbrains.idea.maven.model.MavenPlugin;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenArtifactUtil;
import java.io.File;
public class MavenPluginDomUtil {
@Nullable
public static MavenProject findMavenProject(@NotNull DomElement domElement) {
XmlElement xmlElement = domElement.getXmlElement();
if (xmlElement == null) return null;
PsiFile psiFile = xmlElement.getContainingFile();
if (psiFile == null) return null;
VirtualFile file = psiFile.getVirtualFile();
if (file == null) return null;
return MavenProjectsManager.getInstance(psiFile.getProject()).findProject(file);
}
@Nullable
public static MavenDomPluginModel getMavenPluginModel(DomElement element) {
Project project = element.getManager().getProject();
MavenDomPlugin pluginElement = element.getParentOfType(MavenDomPlugin.class, false);
if (pluginElement == null) return null;
String groupId = pluginElement.getGroupId().getStringValue();
String artifactId = pluginElement.getArtifactId().getStringValue();
String version = pluginElement.getVersion().getStringValue();
if (version == null) {
MavenProject mavenProject = findMavenProject(element);
if (mavenProject != null) {
for (MavenPlugin plugin : mavenProject.getPlugins()) {
if (MavenArtifactUtil.isPluginIdEquals(groupId, artifactId, plugin.getGroupId(), plugin.getArtifactId())) {
MavenId pluginMavenId = plugin.getMavenId();
version = pluginMavenId.getVersion();
break;
}
}
}
}
return getMavenPluginModel(project, groupId, artifactId, version);
}
@Nullable
public static MavenDomPluginModel getMavenPluginModel(Project project, String groupId, String artifactId, String version) {
VirtualFile pluginXmlFile = getPluginXmlFile(project, groupId, artifactId, version);
if (pluginXmlFile == null) return null;
return MavenDomUtil.getMavenDomModel(project, pluginXmlFile, MavenDomPluginModel.class);
}
public static boolean isPlugin(@NotNull MavenDomConfiguration configuration, @Nullable String groupId, @NotNull String artifactId) {
MavenDomPlugin domPlugin = configuration.getParentOfType(MavenDomPlugin.class, true);
if (domPlugin == null) return false;
return isPlugin(domPlugin, groupId, artifactId);
}
public static boolean isPlugin(@NotNull MavenDomPlugin plugin, @Nullable String groupId, @NotNull String artifactId) {
if (!artifactId.equals(plugin.getArtifactId().getStringValue())) return false;
String pluginGroupId = plugin.getGroupId().getStringValue();
if (groupId == null) {
return pluginGroupId == null || (pluginGroupId.equals("org.apache.maven.plugins") || pluginGroupId.equals("org.codehaus.mojo"));
}
if (pluginGroupId == null && (groupId.equals("org.apache.maven.plugins") || groupId.equals("org.codehaus.mojo"))) {
return true;
}
return groupId.equals(pluginGroupId);
}
@Nullable
private static VirtualFile getPluginXmlFile(Project project, String groupId, String artifactId, String version) {
File file = MavenArtifactUtil.getArtifactFile(MavenProjectsManager.getInstance(project).getLocalRepository(),
groupId, artifactId, version, "jar");
VirtualFile pluginFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (pluginFile == null) return null;
VirtualFile pluginJarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(pluginFile);
if (pluginJarRoot == null) return null;
return pluginJarRoot.findFileByRelativePath(MavenArtifactUtil.MAVEN_PLUGIN_DESCRIPTOR);
}
}
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginDomUtil.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.dom;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.xml.DomElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.dom.model.MavenDomConfiguration;
import org.jetbrains.idea.maven.dom.model.MavenDomPlugin;
import org.jetbrains.idea.maven.dom.plugin.MavenDomPluginModel;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenArtifactUtil;
import java.io.File;
public class MavenPluginDomUtil {
@Nullable
public static MavenDomPluginModel getMavenPluginModel(DomElement element) {
Project project = element.getManager().getProject();
MavenDomPlugin pluginElement = element.getParentOfType(MavenDomPlugin.class, false);
if (pluginElement == null) return null;
String groupId = pluginElement.getGroupId().getStringValue();
String artifactId = pluginElement.getArtifactId().getStringValue();
String version = pluginElement.getVersion().getStringValue();
return getMavenPluginModel(project, groupId, artifactId, version);
}
@Nullable
public static MavenDomPluginModel getMavenPluginModel(Project project, String groupId, String artifactId, String version) {
VirtualFile pluginXmlFile = getPluginXmlFile(project, groupId, artifactId, version);
if (pluginXmlFile == null) return null;
return MavenDomUtil.getMavenDomModel(project, pluginXmlFile, MavenDomPluginModel.class);
}
public static boolean isPlugin(@NotNull MavenDomConfiguration configuration, @Nullable String groupId, @NotNull String artifactId) {
MavenDomPlugin domPlugin = configuration.getParentOfType(MavenDomPlugin.class, true);
if (domPlugin == null) return false;
return isPlugin(domPlugin, groupId, artifactId);
}
public static boolean isPlugin(@NotNull MavenDomPlugin plugin, @Nullable String groupId, @NotNull String artifactId) {
if (!artifactId.equals(plugin.getArtifactId().getStringValue())) return false;
String pluginGroupId = plugin.getGroupId().getStringValue();
if (groupId == null) {
return pluginGroupId == null || (pluginGroupId.equals("org.apache.maven.plugins") || pluginGroupId.equals("org.codehaus.mojo"));
}
if (pluginGroupId == null && (groupId.equals("org.apache.maven.plugins") || groupId.equals("org.codehaus.mojo"))) {
return true;
}
return groupId.equals(pluginGroupId);
}
@Nullable
private static VirtualFile getPluginXmlFile(Project project, String groupId, String artifactId, String version) {
File file = MavenArtifactUtil.getArtifactFile(MavenProjectsManager.getInstance(project).getLocalRepository(),
groupId, artifactId, version, "jar");
VirtualFile pluginFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (pluginFile == null) return null;
VirtualFile pluginJarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(pluginFile);
if (pluginJarRoot == null) return null;
return pluginJarRoot.findFileByRelativePath(MavenArtifactUtil.MAVEN_PLUGIN_DESCRIPTOR);
}
}
|
Maven: resolve plugin version using imported plugins (IDEA-154133)
|
plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/MavenPluginDomUtil.java
|
Maven: resolve plugin version using imported plugins (IDEA-154133)
|
|
Java
|
apache-2.0
|
21a782841800e56b6d80ede8907e35b04bac79de
| 0
|
ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,allotria/intellij-community,FHannes/intellij-community,da1z/intellij-community,semonte/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,allotria/intellij-community,FHannes/intellij-community,ibinti/intellij-community,allotria/intellij-community,semonte/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,da1z/intellij-community,signed/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,signed/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,ibinti/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,signed/intellij-community,allotria/intellij-community,semonte/intellij-community,apixandru/intellij-community,apixandru/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,da1z/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,asedunov/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,ibinti/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.util.DelegatingProgressIndicator;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.actions.MoveChangesToAnotherListAction;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import static com.intellij.openapi.application.ApplicationManager.getApplication;
import static com.intellij.openapi.progress.ProgressManager.progress;
import static com.intellij.openapi.ui.Messages.getQuestionIcon;
import static com.intellij.openapi.util.text.StringUtil.isEmpty;
import static com.intellij.openapi.util.text.StringUtil.*;
import static com.intellij.openapi.vcs.VcsBundle.message;
import static com.intellij.openapi.vcs.changes.ChangesUtil.processChangesByVcs;
import static com.intellij.util.ArrayUtil.toObjectArray;
import static com.intellij.util.WaitForProgressToShow.runOrInvokeLaterAboveProgress;
import static com.intellij.util.containers.ContainerUtil.isEmpty;
import static com.intellij.util.containers.ContainerUtil.*;
import static com.intellij.util.ui.ConfirmationDialog.requestForConfirmation;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
public class CommitHelper {
public static final Key<Object> DOCUMENT_BEING_COMMITTED_KEY = new Key<>("DOCUMENT_BEING_COMMITTED");
private final static Logger LOG = Logger.getInstance(CommitHelper.class);
@NotNull private final Project myProject;
@NotNull private final ChangeList myChangeList;
@NotNull private final List<Change> myIncludedChanges;
@NotNull private final String myActionName;
@NotNull private final String myCommitMessage;
@NotNull private final List<CheckinHandler> myHandlers;
private final boolean myAllOfDefaultChangeListChangesIncluded;
private final boolean myForceSyncCommit;
@NotNull private final NullableFunction<Object, Object> myAdditionalData;
@Nullable private final CommitResultHandler myCustomResultHandler;
@NotNull private final List<Document> myCommittingDocuments = newArrayList();
@NotNull private final VcsConfiguration myConfiguration;
@NotNull private final HashSet<String> myFeedback = newHashSet();
public CommitHelper(@NotNull Project project,
@NotNull ChangeList changeList,
@NotNull List<Change> includedChanges,
@NotNull String actionName,
@NotNull String commitMessage,
@NotNull List<CheckinHandler> handlers,
boolean allOfDefaultChangeListChangesIncluded,
boolean synchronously,
@NotNull NullableFunction<Object, Object> additionalDataHolder,
@Nullable CommitResultHandler customResultHandler) {
myProject = project;
myChangeList = changeList;
myIncludedChanges = includedChanges;
myActionName = actionName;
myCommitMessage = commitMessage;
myHandlers = handlers;
myAllOfDefaultChangeListChangesIncluded = allOfDefaultChangeListChangesIncluded;
myForceSyncCommit = synchronously;
myAdditionalData = additionalDataHolder;
myCustomResultHandler = customResultHandler;
myConfiguration = VcsConfiguration.getInstance(myProject);
}
public boolean doCommit() {
return doCommit((AbstractVcs)null);
}
public boolean doCommit(@Nullable AbstractVcs vcs) {
return doCommit(new CommitProcessor(vcs));
}
public void doAlienCommit(@NotNull AbstractVcs vcs) {
doCommit(new AlienCommitProcessor(vcs));
}
private boolean doCommit(@NotNull GeneralCommitProcessor processor) {
Task.Backgroundable task = new Task.Backgroundable(myProject, myActionName, true, myConfiguration.getCommitOption()) {
public void run(@NotNull ProgressIndicator indicator) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
vcsManager.startBackgroundVcsOperation();
try {
delegateCommitToVcsThread(processor);
}
finally {
vcsManager.stopBackgroundVcsOperation();
}
}
@Override
public boolean shouldStartInBackground() {
return !myForceSyncCommit && super.shouldStartInBackground();
}
@Override
public boolean isConditionalModal() {
return myForceSyncCommit;
}
};
ProgressManager.getInstance().run(task);
return hasOnlyWarnings(processor.getVcsExceptions());
}
private void delegateCommitToVcsThread(@NotNull GeneralCommitProcessor processor) {
ProgressIndicator indicator = new DelegatingProgressIndicator();
Semaphore endSemaphore = new Semaphore();
endSemaphore.down();
ChangeListManagerImpl.getInstanceImpl(myProject).executeOnUpdaterThread(() -> {
indicator.setText("Performing VCS commit...");
try {
ProgressManager.getInstance().runProcess(() -> {
indicator.checkCanceled();
generalCommit(processor);
}, indicator);
}
finally {
endSemaphore.up();
}
});
indicator.setText("Waiting for VCS background tasks to finish...");
while (!endSemaphore.waitFor(20)) {
indicator.checkCanceled();
}
}
private void reportResult(@NotNull GeneralCommitProcessor processor) {
List<VcsException> errors = collectErrors(processor.getVcsExceptions());
int errorsSize = errors.size();
int warningsSize = processor.getVcsExceptions().size() - errorsSize;
VcsNotifier notifier = VcsNotifier.getInstance(myProject);
String message = getCommitSummary(processor);
if (errorsSize > 0) {
String title = pluralize(message("message.text.commit.failed.with.error"), errorsSize);
notifier.notifyError(title, message);
}
else if (warningsSize > 0) {
String title = pluralize(message("message.text.commit.finished.with.warning"), warningsSize);
notifier.notifyImportantWarning(title, message);
}
else {
notifier.notifySuccess(message);
}
}
@NotNull
private String getCommitSummary(@NotNull GeneralCommitProcessor processor) {
StringBuilder content = new StringBuilder(getFileSummaryReport(processor.getChangesFailedToCommit()));
if (!isEmpty(myCommitMessage)) {
content.append(": ").append(escape(myCommitMessage));
}
if (!myFeedback.isEmpty()) {
content.append("<br/>");
content.append(join(myFeedback, "<br/>"));
}
List<VcsException> exceptions = processor.getVcsExceptions();
if (!hasOnlyWarnings(exceptions)) {
content.append("<br/>");
content.append(join(exceptions, Throwable::getMessage, "<br/>"));
}
return content.toString();
}
@NotNull
private String getFileSummaryReport(@NotNull List<Change> changesFailedToCommit) {
int failed = changesFailedToCommit.size();
int committed = myIncludedChanges.size() - failed;
String fileSummary = committed + " " + pluralize("file", committed) + " committed";
if (failed > 0) {
fileSummary += ", " + failed + " " + pluralize("file", failed) + " failed to commit";
}
return fileSummary;
}
/*
Commit message is passed to NotificationManagerImpl#doNotify and displayed as HTML.
Thus HTML tag braces (< and >) should be escaped,
but only they since the text is passed directly to HTML <BODY> tag and is not a part of an attribute or else.
*/
private static String escape(String s) {
String[] FROM = {"<", ">"};
String[] TO = {"<", ">"};
return replace(s, FROM, TO);
}
private static boolean hasOnlyWarnings(@NotNull List<VcsException> exceptions) {
return exceptions.stream().allMatch(VcsException::isWarning);
}
private void generalCommit(@NotNull GeneralCommitProcessor processor) throws RuntimeException {
try {
ReadAction.run(() -> markCommittingDocuments());
try {
processor.callSelf();
}
finally {
ReadAction.run(() -> unmarkCommittingDocuments());
}
processor.doBeforeRefresh();
}
catch (ProcessCanceledException pce) {
throw pce;
}
catch (Throwable e) {
LOG.error(e);
processor.myVcsExceptions.add(new VcsException(e));
ExceptionUtil.rethrow(e);
}
finally {
commitCompleted(processor.getVcsExceptions(), processor);
processor.customRefresh();
runOrInvokeLaterAboveProgress(() -> processor.doPostRefresh(), null, myProject);
}
}
private class AlienCommitProcessor extends GeneralCommitProcessor {
@NotNull private final AbstractVcs myVcs;
private AlienCommitProcessor(@NotNull AbstractVcs vcs) {
myVcs = vcs;
}
@Override
public void callSelf() {
ChangesUtil.processItemsByVcs(myIncludedChanges, change -> myVcs, this::process);
}
private void process(@NotNull AbstractVcs vcs, @NotNull List<Change> items) {
if (myVcs.getName().equals(vcs.getName())) {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null) {
myPathsToRefresh.addAll(ChangesUtil.getPaths(items));
List<VcsException> exceptions = environment.commit(items, myCommitMessage, myAdditionalData, myFeedback);
if (!isEmpty(exceptions)) {
myVcsExceptions.addAll(exceptions);
myChangesFailedToCommit.addAll(items);
}
}
}
}
@Override
public void afterSuccessfulCheckIn() {
}
@Override
public void afterFailedCheckIn() {
}
@Override
public void doBeforeRefresh() {
}
@Override
public void customRefresh() {
}
@Override
public void doPostRefresh() {
}
}
private abstract static class GeneralCommitProcessor {
@NotNull protected final List<FilePath> myPathsToRefresh = newArrayList();
@NotNull protected final List<VcsException> myVcsExceptions = newArrayList();
@NotNull protected final List<Change> myChangesFailedToCommit = newArrayList();
public abstract void callSelf();
public abstract void afterSuccessfulCheckIn();
public abstract void afterFailedCheckIn();
public abstract void doBeforeRefresh();
public abstract void customRefresh();
public abstract void doPostRefresh();
@NotNull
public List<FilePath> getPathsToRefresh() {
return myPathsToRefresh;
}
@NotNull
public List<VcsException> getVcsExceptions() {
return myVcsExceptions;
}
@NotNull
public List<Change> getChangesFailedToCommit() {
return myChangesFailedToCommit;
}
}
private enum ChangeListsModificationAfterCommit {
DELETE_LIST,
MOVE_OTHERS,
NOTHING
}
private class CommitProcessor extends GeneralCommitProcessor {
private boolean myKeepChangeListAfterCommit;
@NotNull private LocalHistoryAction myAction = LocalHistoryAction.NULL;
private ChangeListsModificationAfterCommit myAfterVcsRefreshModification;
private boolean myCommitSuccess;
@Nullable private final AbstractVcs myVcs;
private CommitProcessor(@Nullable AbstractVcs vcs) {
myVcs = vcs;
myAfterVcsRefreshModification = ChangeListsModificationAfterCommit.NOTHING;
if (myChangeList instanceof LocalChangeList) {
LocalChangeList localList = (LocalChangeList)myChangeList;
boolean containsAll = newHashSet(myIncludedChanges).containsAll(myChangeList.getChanges());
if (containsAll && !localList.isDefault() && !localList.isReadOnly()) {
myAfterVcsRefreshModification = ChangeListsModificationAfterCommit.DELETE_LIST;
}
else if (myConfiguration.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT &&
!containsAll &&
localList.isDefault() &&
myAllOfDefaultChangeListChangesIncluded) {
myAfterVcsRefreshModification = ChangeListsModificationAfterCommit.MOVE_OTHERS;
}
}
}
@Override
public void callSelf() {
if (myVcs != null && myIncludedChanges.isEmpty()) {
process(myVcs, myIncludedChanges);
}
processChangesByVcs(myProject, myIncludedChanges, this::process);
}
private void process(@NotNull AbstractVcs vcs, @NotNull List<Change> changes) {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null) {
myPathsToRefresh.addAll(ChangesUtil.getPaths(changes));
if (environment.keepChangeListAfterCommit(myChangeList)) {
myKeepChangeListAfterCommit = true;
}
List<VcsException> exceptions = environment.commit(changes, myCommitMessage, myAdditionalData, myFeedback);
if (!isEmpty(exceptions)) {
myVcsExceptions.addAll(exceptions);
myChangesFailedToCommit.addAll(changes);
}
}
}
@Override
public void afterSuccessfulCheckIn() {
myCommitSuccess = true;
}
@Override
public void afterFailedCheckIn() {
getApplication().invokeLater(
() -> moveToFailedList(myChangeList, myCommitMessage, getChangesFailedToCommit(),
message("commit.dialog.failed.commit.template", myChangeList.getName()), myProject),
ModalityState.defaultModalityState(), myProject.getDisposed());
}
@Override
public void doBeforeRefresh() {
ChangeListManagerImpl.getInstanceImpl(myProject).showLocalChangesInvalidated();
myAction = ReadAction.compute(() -> LocalHistory.getInstance().startAction(myActionName));
}
@Override
public void customRefresh() {
List<Change> toRefresh = newArrayList();
processChangesByVcs(myProject, myIncludedChanges, (vcs, changes) -> {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null && environment.isRefreshAfterCommitNeeded()) {
toRefresh.addAll(changes);
}
});
if (!toRefresh.isEmpty()) {
progress(message("commit.dialog.refresh.files"));
RefreshVFsSynchronously.updateChanges(toRefresh);
}
}
@Override
public void doPostRefresh() {
myAction.finish();
if (!myProject.isDisposed()) {
// after vcs refresh is completed, outdated notifiers should be removed if some exists...
ChangeListManager clManager = ChangeListManager.getInstance(myProject);
clManager.invokeAfterUpdate(
() -> {
if (myCommitSuccess) {
// do delete/ move of change list if needed
if (ChangeListsModificationAfterCommit.DELETE_LIST.equals(myAfterVcsRefreshModification)) {
if (!myKeepChangeListAfterCommit) {
clManager.removeChangeList(myChangeList.getName());
}
}
else if (ChangeListsModificationAfterCommit.MOVE_OTHERS.equals(myAfterVcsRefreshModification)) {
ChangelistMoveOfferDialog dialog = new ChangelistMoveOfferDialog(myConfiguration);
if (dialog.showAndGet()) {
Collection<Change> changes = clManager.getDefaultChangeList().getChanges();
MoveChangesToAnotherListAction.askAndMove(myProject, changes, emptyList());
}
}
}
CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
// in background since commit must have authorized
cache.refreshAllCachesAsync(false, true);
cache.refreshIncomingChangesAsync();
}, InvokeAfterUpdateMode.SILENT, null, vcsDirtyScopeManager -> vcsDirtyScopeManager.filePathsDirty(getPathsToRefresh(), null),
null);
LocalHistory.getInstance().putSystemLabel(myProject, myActionName + ": " + myCommitMessage);
}
}
}
private void markCommittingDocuments() {
myCommittingDocuments.addAll(markCommittingDocuments(myProject, myIncludedChanges));
}
private void unmarkCommittingDocuments() {
unmarkCommittingDocuments(myCommittingDocuments);
myCommittingDocuments.clear();
}
/**
* Marks {@link Document documents} related to the given changes as "being committed".
* @return documents which were marked that way.
* @see #unmarkCommittingDocuments(Collection)
* @see VetoSavingCommittingDocumentsAdapter
*/
@NotNull
private static Collection<Document> markCommittingDocuments(@NotNull Project project, @NotNull List<Change> changes) {
Collection<Document> result = newArrayList();
for (Change change : changes) {
VirtualFile virtualFile = ChangesUtil.getFilePath(change).getVirtualFile();
if (virtualFile != null && !virtualFile.getFileType().isBinary()) {
Document doc = FileDocumentManager.getInstance().getDocument(virtualFile);
if (doc != null) {
doc.putUserData(DOCUMENT_BEING_COMMITTED_KEY, project);
result.add(doc);
}
}
}
return result;
}
/**
* Removes the "being committed marker" from the given {@link Document documents}.
* @see #markCommittingDocuments(Project, List)
* @see VetoSavingCommittingDocumentsAdapter
*/
private static void unmarkCommittingDocuments(@NotNull Collection<Document> committingDocs) {
committingDocs.forEach(document -> document.putUserData(DOCUMENT_BEING_COMMITTED_KEY, null));
}
private void commitCompleted(@NotNull List<VcsException> allExceptions, @NotNull GeneralCommitProcessor processor) {
List<VcsException> errors = collectErrors(allExceptions);
boolean noErrors = errors.isEmpty();
boolean noWarnings = allExceptions.isEmpty();
if (noErrors) {
myHandlers.forEach(CheckinHandler::checkinSuccessful);
processor.afterSuccessfulCheckIn();
if (myCustomResultHandler != null) {
myCustomResultHandler.onSuccess(myCommitMessage);
}
else {
reportResult(processor);
}
if (noWarnings) {
progress(message("commit.dialog.completed.successfully"));
}
}
else {
myHandlers.forEach(handler -> handler.checkinFailed(errors));
processor.afterFailedCheckIn();
if (myCustomResultHandler != null) {
myCustomResultHandler.onFailure();
}
else {
reportResult(processor);
}
}
}
@CalledInAwt
public static void moveToFailedList(@NotNull ChangeList changeList,
@NotNull String commitMessage,
@NotNull List<Change> failedChanges,
@NotNull String newChangelistName,
@NotNull Project project) {
// No need to move since we'll get exactly the same changelist.
if (failedChanges.containsAll(changeList.getChanges())) return;
VcsConfiguration configuration = VcsConfiguration.getInstance(project);
if (configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST != VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) {
VcsShowConfirmationOption option = new VcsShowConfirmationOption() {
@Override
public Value getValue() {
return configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST;
}
@Override
public void setValue(Value value) {
configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST = value;
}
@Override
public boolean isPersistent() {
return true;
}
};
boolean result =
requestForConfirmation(option, project, message("commit.failed.confirm.prompt"), message("commit.failed.confirm.title"),
getQuestionIcon());
if (!result) return;
}
ChangeListManager changeListManager = ChangeListManager.getInstance(project);
int index = 1;
String failedListName = newChangelistName;
while (changeListManager.findChangeList(failedListName) != null) {
index++;
failedListName = newChangelistName + " (" + index + ")";
}
LocalChangeList failedList = changeListManager.addChangeList(failedListName, commitMessage);
changeListManager.moveChangesTo(failedList, toObjectArray(failedChanges, Change.class));
}
@NotNull
private static List<VcsException> collectErrors(@NotNull List<VcsException> exceptions) {
return exceptions.stream().filter(e -> !e.isWarning()).collect(toList());
}
}
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitHelper.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.util.DelegatingProgressIndicator;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.actions.MoveChangesToAnotherListAction;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.NullableFunction;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import static com.intellij.openapi.application.ApplicationManager.getApplication;
import static com.intellij.openapi.ui.Messages.getQuestionIcon;
import static com.intellij.openapi.util.text.StringUtil.*;
import static com.intellij.openapi.vcs.VcsBundle.message;
import static com.intellij.openapi.vcs.changes.ChangesUtil.processChangesByVcs;
import static com.intellij.util.WaitForProgressToShow.runOrInvokeLaterAboveProgress;
import static com.intellij.util.containers.ContainerUtil.newArrayList;
import static com.intellij.util.containers.ContainerUtil.newHashSet;
import static com.intellij.util.ui.ConfirmationDialog.requestForConfirmation;
import static java.util.Collections.emptyList;
public class CommitHelper {
public static final Key<Object> DOCUMENT_BEING_COMMITTED_KEY = new Key<>("DOCUMENT_BEING_COMMITTED");
private final static Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ui.CommitHelper");
@NotNull private final Project myProject;
@NotNull private final ChangeList myChangeList;
@NotNull private final List<Change> myIncludedChanges;
@NotNull private final String myActionName;
@NotNull private final String myCommitMessage;
@NotNull private final List<CheckinHandler> myHandlers;
private final boolean myAllOfDefaultChangeListChangesIncluded;
private final boolean myForceSyncCommit;
@NotNull private final NullableFunction<Object, Object> myAdditionalData;
@Nullable private final CommitResultHandler myCustomResultHandler;
@NotNull private final List<Document> myCommittingDocuments = newArrayList();
@NotNull private final VcsConfiguration myConfiguration;
@NotNull private final HashSet<String> myFeedback = newHashSet();
public CommitHelper(@NotNull Project project,
@NotNull ChangeList changeList,
@NotNull List<Change> includedChanges,
@NotNull String actionName,
@NotNull String commitMessage,
@NotNull List<CheckinHandler> handlers,
boolean allOfDefaultChangeListChangesIncluded,
boolean synchronously,
@NotNull NullableFunction<Object, Object> additionalDataHolder,
@Nullable CommitResultHandler customResultHandler) {
myProject = project;
myChangeList = changeList;
myIncludedChanges = includedChanges;
myActionName = actionName;
myCommitMessage = commitMessage;
myHandlers = handlers;
myAllOfDefaultChangeListChangesIncluded = allOfDefaultChangeListChangesIncluded;
myForceSyncCommit = synchronously;
myAdditionalData = additionalDataHolder;
myCustomResultHandler = customResultHandler;
myConfiguration = VcsConfiguration.getInstance(myProject);
}
public boolean doCommit() {
return doCommit((AbstractVcs)null);
}
public boolean doCommit(@Nullable AbstractVcs vcs) {
return doCommit(new CommitProcessor(vcs));
}
public boolean doAlienCommit(@NotNull AbstractVcs vcs) {
return doCommit(new AlienCommitProcessor(vcs));
}
private boolean doCommit(GeneralCommitProcessor processor) {
Task.Backgroundable task = new Task.Backgroundable(myProject, myActionName, true, myConfiguration.getCommitOption()) {
public void run(@NotNull ProgressIndicator indicator) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
vcsManager.startBackgroundVcsOperation();
try {
delegateCommitToVcsThread(processor);
}
finally {
vcsManager.stopBackgroundVcsOperation();
}
}
@Override
public boolean shouldStartInBackground() {
return !myForceSyncCommit && super.shouldStartInBackground();
}
@Override
public boolean isConditionalModal() {
return myForceSyncCommit;
}
};
ProgressManager.getInstance().run(task);
return doesntContainErrors(processor.getVcsExceptions());
}
private void delegateCommitToVcsThread(GeneralCommitProcessor processor) {
ProgressIndicator indicator = new DelegatingProgressIndicator();
Semaphore endSemaphore = new Semaphore();
endSemaphore.down();
ChangeListManagerImpl.getInstanceImpl(myProject).executeOnUpdaterThread(() -> {
indicator.setText("Performing VCS commit...");
try {
ProgressManager.getInstance().runProcess(() -> {
indicator.checkCanceled();
generalCommit(processor);
}, indicator);
}
finally {
endSemaphore.up();
}
});
indicator.setText("Waiting for VCS background tasks to finish...");
while (!endSemaphore.waitFor(20)) {
indicator.checkCanceled();
}
}
private void reportResult(@NotNull GeneralCommitProcessor processor) {
List<VcsException> errors = collectErrors(processor.getVcsExceptions());
int errorsSize = errors.size();
int warningsSize = processor.getVcsExceptions().size() - errorsSize;
VcsNotifier notifier = VcsNotifier.getInstance(myProject);
String message = getCommitSummary(processor);
if (errorsSize > 0) {
String title = pluralize(message("message.text.commit.failed.with.error"), errorsSize);
notifier.notifyError(title, message);
}
else if (warningsSize > 0) {
String title = pluralize(message("message.text.commit.finished.with.warning"), warningsSize);
notifier.notifyImportantWarning(title, message);
}
else {
notifier.notifySuccess(message);
}
}
@NotNull
private String getCommitSummary(@NotNull GeneralCommitProcessor processor) {
StringBuilder content = new StringBuilder(getFileSummaryReport(processor.getChangesFailedToCommit()));
if (!isEmpty(myCommitMessage)) {
content.append(": ").append(escape(myCommitMessage));
}
if (!myFeedback.isEmpty()) {
content.append("<br/>");
content.append(join(myFeedback, "<br/>"));
}
List<VcsException> exceptions = processor.getVcsExceptions();
if (!doesntContainErrors(exceptions)) {
content.append("<br/>");
content.append(join(exceptions, Throwable::getMessage, "<br/>"));
}
return content.toString();
}
@NotNull
private String getFileSummaryReport(@NotNull List<Change> changesFailedToCommit) {
int failed = changesFailedToCommit.size();
int committed = myIncludedChanges.size() - failed;
String fileSummary = committed + " " + pluralize("file", committed) + " committed";
if (failed > 0) {
fileSummary += ", " + failed + " " + pluralize("file", failed) + " failed to commit";
}
return fileSummary;
}
/*
Commit message is passed to NotificationManagerImpl#doNotify and displayed as HTML.
Thus HTML tag braces (< and >) should be escaped,
but only they since the text is passed directly to HTML <BODY> tag and is not a part of an attribute or else.
*/
private static String escape(String s) {
String[] FROM = {"<", ">"};
String[] TO = {"<", ">"};
return replace(s, FROM, TO);
}
private static boolean doesntContainErrors(List<VcsException> vcsExceptions) {
for (VcsException vcsException : vcsExceptions) {
if (!vcsException.isWarning()) return false;
}
return true;
}
private void generalCommit(GeneralCommitProcessor processor) {
try {
ReadAction.run(() -> markCommittingDocuments());
try {
processor.callSelf();
}
finally {
ReadAction.run(() -> unmarkCommittingDocuments());
}
processor.doBeforeRefresh();
}
catch (ProcessCanceledException pce) {
throw pce;
}
catch (RuntimeException e) {
LOG.error(e);
processor.myVcsExceptions.add(new VcsException(e));
throw e;
}
catch (Throwable e) {
LOG.error(e);
processor.myVcsExceptions.add(new VcsException(e));
throw new RuntimeException(e);
}
finally {
commitCompleted(processor.getVcsExceptions(), processor);
processor.customRefresh();
runOrInvokeLaterAboveProgress(() -> processor.doPostRefresh(), null, myProject);
}
}
private class AlienCommitProcessor extends GeneralCommitProcessor {
@NotNull private final AbstractVcs myVcs;
private AlienCommitProcessor(@NotNull AbstractVcs vcs) {
myVcs = vcs;
}
@Override
public void callSelf() {
ChangesUtil.processItemsByVcs(myIncludedChanges, change -> myVcs, this::process);
}
private void process(@NotNull AbstractVcs vcs, @NotNull List<Change> items) {
if (myVcs.getName().equals(vcs.getName())) {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null) {
Collection<FilePath> paths = ChangesUtil.getPaths(items);
myPathsToRefresh.addAll(paths);
List<VcsException> exceptions = environment.commit(items, myCommitMessage, myAdditionalData, myFeedback);
if (exceptions != null && exceptions.size() > 0) {
myVcsExceptions.addAll(exceptions);
myChangesFailedToCommit.addAll(items);
}
}
}
}
@Override
public void afterSuccessfulCheckIn() {
}
@Override
public void afterFailedCheckIn() {
}
@Override
public void doBeforeRefresh() {
}
@Override
public void customRefresh() {
}
@Override
public void doPostRefresh() {
}
}
private abstract static class GeneralCommitProcessor {
protected final List<FilePath> myPathsToRefresh = newArrayList();
protected final List<VcsException> myVcsExceptions = newArrayList();
protected final List<Change> myChangesFailedToCommit = newArrayList();
public abstract void callSelf();
public abstract void afterSuccessfulCheckIn();
public abstract void afterFailedCheckIn();
public abstract void doBeforeRefresh();
public abstract void customRefresh();
public abstract void doPostRefresh();
public List<FilePath> getPathsToRefresh() {
return myPathsToRefresh;
}
public List<VcsException> getVcsExceptions() {
return myVcsExceptions;
}
public List<Change> getChangesFailedToCommit() {
return myChangesFailedToCommit;
}
}
private enum ChangeListsModificationAfterCommit {
DELETE_LIST,
MOVE_OTHERS,
NOTHING
}
private class CommitProcessor extends GeneralCommitProcessor {
private boolean myKeepChangeListAfterCommit;
private LocalHistoryAction myAction;
private ChangeListsModificationAfterCommit myAfterVcsRefreshModification;
private boolean myCommitSuccess;
@Nullable private final AbstractVcs myVcs;
private CommitProcessor(@Nullable AbstractVcs vcs) {
myVcs = vcs;
myAfterVcsRefreshModification = ChangeListsModificationAfterCommit.NOTHING;
if (myChangeList instanceof LocalChangeList) {
LocalChangeList localList = (LocalChangeList)myChangeList;
boolean containsAll = newHashSet(myIncludedChanges).containsAll(newHashSet(myChangeList.getChanges()));
if (containsAll && !localList.isDefault() && !localList.isReadOnly()) {
myAfterVcsRefreshModification = ChangeListsModificationAfterCommit.DELETE_LIST;
}
else if (myConfiguration.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT &&
!containsAll &&
localList.isDefault() &&
myAllOfDefaultChangeListChangesIncluded) {
myAfterVcsRefreshModification = ChangeListsModificationAfterCommit.MOVE_OTHERS;
}
}
}
@Override
public void callSelf() {
if (myVcs != null && myIncludedChanges.isEmpty()) {
process(myVcs, myIncludedChanges);
}
processChangesByVcs(myProject, myIncludedChanges, this::process);
}
private void process(@NotNull AbstractVcs vcs, @NotNull List<Change> items) {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null) {
Collection<FilePath> paths = ChangesUtil.getPaths(items);
myPathsToRefresh.addAll(paths);
if (environment.keepChangeListAfterCommit(myChangeList)) {
myKeepChangeListAfterCommit = true;
}
List<VcsException> exceptions = environment.commit(items, myCommitMessage, myAdditionalData, myFeedback);
if (exceptions != null && exceptions.size() > 0) {
myVcsExceptions.addAll(exceptions);
myChangesFailedToCommit.addAll(items);
}
}
}
@Override
public void afterSuccessfulCheckIn() {
myCommitSuccess = true;
}
@Override
public void afterFailedCheckIn() {
getApplication().invokeLater(
() -> moveToFailedList(myChangeList, myCommitMessage, getChangesFailedToCommit(),
message("commit.dialog.failed.commit.template", myChangeList.getName()), myProject),
ModalityState.defaultModalityState(), myProject.getDisposed());
}
@Override
public void doBeforeRefresh() {
ChangeListManagerImpl clManager = (ChangeListManagerImpl)ChangeListManager.getInstance(myProject);
clManager.showLocalChangesInvalidated();
myAction = ReadAction.compute(() -> LocalHistory.getInstance().startAction(myActionName));
}
@Override
public void customRefresh() {
List<Change> toRefresh = newArrayList();
processChangesByVcs(myProject, myIncludedChanges, (vcs, items) -> {
CheckinEnvironment ce = vcs.getCheckinEnvironment();
if (ce != null && ce.isRefreshAfterCommitNeeded()) {
toRefresh.addAll(items);
}
});
if (toRefresh.isEmpty()) {
return;
}
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(message("commit.dialog.refresh.files"));
}
RefreshVFsSynchronously.updateChanges(toRefresh);
}
@Override
public void doPostRefresh() {
// to be completely sure
if (myAction != null) {
myAction.finish();
}
if (!myProject.isDisposed()) {
// after vcs refresh is completed, outdated notifiers should be removed if some exists...
ChangeListManager clManager = ChangeListManager.getInstance(myProject);
clManager.invokeAfterUpdate(() -> {
if (myCommitSuccess) {
// do delete/ move of change list if needed
if (ChangeListsModificationAfterCommit.DELETE_LIST.equals(myAfterVcsRefreshModification)) {
if (!myKeepChangeListAfterCommit) {
clManager.removeChangeList(myChangeList.getName());
}
}
else if (ChangeListsModificationAfterCommit.MOVE_OTHERS.equals(myAfterVcsRefreshModification)) {
ChangelistMoveOfferDialog dialog = new ChangelistMoveOfferDialog(myConfiguration);
if (dialog.showAndGet()) {
Collection<Change> changes = clManager.getDefaultChangeList().getChanges();
MoveChangesToAnotherListAction.askAndMove(myProject, changes, emptyList());
}
}
}
CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
// in background since commit must have authorized
cache.refreshAllCachesAsync(false, true);
cache.refreshIncomingChangesAsync();
}, InvokeAfterUpdateMode.SILENT, null, vcsDirtyScopeManager -> {
for (FilePath path : getPathsToRefresh()) {
vcsDirtyScopeManager.fileDirty(path);
}
}, null);
LocalHistory.getInstance().putSystemLabel(myProject, myActionName + ": " + myCommitMessage);
}
}
}
private void markCommittingDocuments() {
myCommittingDocuments.addAll(markCommittingDocuments(myProject, myIncludedChanges));
}
private void unmarkCommittingDocuments() {
unmarkCommittingDocuments(myCommittingDocuments);
myCommittingDocuments.clear();
}
/**
* Marks {@link Document documents} related to the given changes as "being committed".
* @return documents which were marked that way.
* @see #unmarkCommittingDocuments(Collection)
* @see VetoSavingCommittingDocumentsAdapter
*/
@NotNull
private static Collection<Document> markCommittingDocuments(@NotNull Project project, @NotNull List<Change> changes) {
Collection<Document> committingDocs = newArrayList();
for (Change change : changes) {
VirtualFile virtualFile = ChangesUtil.getFilePath(change).getVirtualFile();
if (virtualFile != null && !virtualFile.getFileType().isBinary()) {
Document doc = FileDocumentManager.getInstance().getDocument(virtualFile);
if (doc != null) {
doc.putUserData(DOCUMENT_BEING_COMMITTED_KEY, project);
committingDocs.add(doc);
}
}
}
return committingDocs;
}
/**
* Removes the "being committed marker" from the given {@link Document documents}.
* @see #markCommittingDocuments(Project, List)
* @see VetoSavingCommittingDocumentsAdapter
*/
private static void unmarkCommittingDocuments(@NotNull Collection<Document> committingDocs) {
for (Document doc : committingDocs) {
doc.putUserData(DOCUMENT_BEING_COMMITTED_KEY, null);
}
}
private void commitCompleted(List<VcsException> allExceptions, GeneralCommitProcessor processor) {
List<VcsException> errors = collectErrors(allExceptions);
boolean noErrors = errors.isEmpty();
boolean noWarnings = allExceptions.isEmpty();
if (noErrors) {
for (CheckinHandler handler : myHandlers) {
handler.checkinSuccessful();
}
processor.afterSuccessfulCheckIn();
if (myCustomResultHandler != null) {
myCustomResultHandler.onSuccess(myCommitMessage);
}
else {
reportResult(processor);
}
if (noWarnings) {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(message("commit.dialog.completed.successfully"));
}
}
}
else {
for (CheckinHandler handler : myHandlers) {
handler.checkinFailed(errors);
}
processor.afterFailedCheckIn();
if (myCustomResultHandler != null) {
myCustomResultHandler.onFailure();
}
else {
reportResult(processor);
}
}
}
@CalledInAwt
public static void moveToFailedList(ChangeList changeList,
String commitMessage,
List<Change> failedChanges,
String newChangelistName,
Project project) {
// No need to move since we'll get exactly the same changelist.
if (failedChanges.containsAll(changeList.getChanges())) return;
VcsConfiguration configuration = VcsConfiguration.getInstance(project);
if (configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST != VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) {
VcsShowConfirmationOption option = new VcsShowConfirmationOption() {
@Override
public Value getValue() {
return configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST;
}
@Override
public void setValue(Value value) {
configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST = value;
}
@Override
public boolean isPersistent() {
return true;
}
};
boolean result =
requestForConfirmation(option, project, message("commit.failed.confirm.prompt"), message("commit.failed.confirm.title"),
getQuestionIcon());
if (!result) return;
}
ChangeListManager changeListManager = ChangeListManager.getInstance(project);
int index = 1;
String failedListName = newChangelistName;
while (changeListManager.findChangeList(failedListName) != null) {
index++;
failedListName = newChangelistName + " (" + index + ")";
}
LocalChangeList failedList = changeListManager.addChangeList(failedListName, commitMessage);
changeListManager.moveChangesTo(failedList, failedChanges.toArray(new Change[failedChanges.size()]));
}
private static List<VcsException> collectErrors(List<VcsException> vcsExceptions) {
List<VcsException> result = newArrayList();
for (VcsException vcsException : vcsExceptions) {
if (!vcsException.isWarning()) {
result.add(vcsException);
}
}
return result;
}
}
|
Refactor "CommitHelper" - simplify, @NotNull
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitHelper.java
|
Refactor "CommitHelper" - simplify, @NotNull
|
|
Java
|
apache-2.0
|
ce0aea7f7349a75330b6011c08ea08e48fbd063f
| 0
|
suncycheng/intellij-community,hurricup/intellij-community,FHannes/intellij-community,retomerz/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,amith01994/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,signed/intellij-community,xfournet/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,hurricup/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,robovm/robovm-studio,holmes/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,asedunov/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,caot/intellij-community,adedayo/intellij-community,apixandru/intellij-community,vladmm/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,kool79/intellij-community,kdwink/intellij-community,robovm/robovm-studio,clumsy/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,da1z/intellij-community,fitermay/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,signed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,xfournet/intellij-community,da1z/intellij-community,vvv1559/intellij-community,allotria/intellij-community,FHannes/intellij-community,amith01994/intellij-community,izonder/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,supersven/intellij-community,asedunov/intellij-community,blademainer/intellij-community,allotria/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,vvv1559/intellij-community,izonder/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,izonder/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,caot/intellij-community,clumsy/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,allotria/intellij-community,Lekanich/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,allotria/intellij-community,kdwink/intellij-community,fitermay/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,slisson/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,jagguli/intellij-community,izonder/intellij-community,ryano144/intellij-community,holmes/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,fitermay/intellij-community,semonte/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,fitermay/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,holmes/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,hurricup/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,signed/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fnouama/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,apixandru/intellij-community,samthor/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,blademainer/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,samthor/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,youdonghai/intellij-community,caot/intellij-community,slisson/intellij-community,kool79/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,retomerz/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,clumsy/intellij-community,slisson/intellij-community,FHannes/intellij-community,supersven/intellij-community,clumsy/intellij-community,hurricup/intellij-community,blademainer/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,signed/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ibinti/intellij-community,fitermay/intellij-community,retomerz/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,izonder/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,semonte/intellij-community,allotria/intellij-community,wreckJ/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,adedayo/intellij-community,allotria/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,slisson/intellij-community,robovm/robovm-studio,samthor/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,adedayo/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,semonte/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,caot/intellij-community,signed/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,semonte/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,clumsy/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,samthor/intellij-community,da1z/intellij-community,holmes/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,supersven/intellij-community,dslomov/intellij-community,izonder/intellij-community,Distrotech/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,da1z/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,slisson/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,semonte/intellij-community,da1z/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,kool79/intellij-community,samthor/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,da1z/intellij-community,amith01994/intellij-community,robovm/robovm-studio,vladmm/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,kool79/intellij-community,holmes/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,gnuhub/intellij-community,signed/intellij-community,semonte/intellij-community,semonte/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,caot/intellij-community,signed/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,diorcety/intellij-community,adedayo/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,holmes/intellij-community,holmes/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,samthor/intellij-community,gnuhub/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,fitermay/intellij-community,apixandru/intellij-community,diorcety/intellij-community,retomerz/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,supersven/intellij-community,slisson/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,FHannes/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,caot/intellij-community,fnouama/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,samthor/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,blademainer/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,slisson/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,holmes/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ryano144/intellij-community,kdwink/intellij-community,ryano144/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,da1z/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,allotria/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,caot/intellij-community,apixandru/intellij-community,dslomov/intellij-community,semonte/intellij-community,supersven/intellij-community,nicolargo/intellij-community,kool79/intellij-community,da1z/intellij-community,fnouama/intellij-community,allotria/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,supersven/intellij-community,petteyg/intellij-community,robovm/robovm-studio,izonder/intellij-community,supersven/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,signed/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kdwink/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,blademainer/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,caot/intellij-community,adedayo/intellij-community,ibinti/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,signed/intellij-community,samthor/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.updateSettings.impl;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Collection;
import java.util.List;
/**
* @author pti
*/
class UpdateInfoDialog extends AbstractUpdateDialog {
private final UpdateChannel myUpdatedChannel;
private final Collection<PluginDownloader> myUpdatedPlugins;
private final BuildInfo myLatestBuild;
private final PatchInfo myPatch;
private final boolean myWriteProtected;
protected UpdateInfoDialog(@NotNull UpdateChannel channel,
boolean enableLink,
Collection<PluginDownloader> updatedPlugins,
Collection<IdeaPluginDescriptor> incompatiblePlugins) {
super(enableLink);
myUpdatedChannel = channel;
myUpdatedPlugins = updatedPlugins;
myLatestBuild = channel.getLatestBuild();
myPatch = myLatestBuild != null ? myLatestBuild.findPatchForCurrentBuild() : null;
myWriteProtected = myPatch != null && !new File(PathManager.getHomePath()).canWrite();
getCancelAction().putValue(DEFAULT_ACTION, Boolean.TRUE);
if (myLatestBuild != null) {
initLicensingInfo(myUpdatedChannel, myLatestBuild);
}
init();
if (incompatiblePlugins != null && !incompatiblePlugins.isEmpty()) {
final boolean onePluginFound = incompatiblePlugins.size() == 1;
String incompatibilityError = "Incompatible with new version plugin";
incompatibilityError += (onePluginFound ? " is" : "s are") + " detected: ";
incompatibilityError += onePluginFound ? "" : "<br>";
incompatibilityError += StringUtil.join(incompatiblePlugins, new Function<IdeaPluginDescriptor, String>() {
@Override
public String fun(IdeaPluginDescriptor downloader) {
return downloader.getName();
}
}, "<br/>");
setErrorText(incompatibilityError);
}
}
@Override
protected JComponent createCenterPanel() {
return new UpdateInfoPanel().myPanel;
}
@NotNull
@Override
protected Action[] createActions() {
List<Action> actions = ContainerUtil.newArrayList();
if (myPatch != null) {
final boolean canRestart = ApplicationManager.getApplication().isRestartCapable();
String button = IdeBundle.message(canRestart ? "updates.download.and.restart.button" : "updates.download.and.install.button");
actions.add(new AbstractAction(button) {
{
setEnabled(!myWriteProtected);
}
@Override
public void actionPerformed(ActionEvent e) {
downloadPatch(canRestart);
}
});
}
List<ButtonInfo> buttons = myLatestBuild.getButtons();
if (buttons.isEmpty()) {
actions.add(new AbstractAction(IdeBundle.message("updates.more.info.button")) {
@Override
public void actionPerformed(ActionEvent e) {
openDownloadPage();
}
});
}
else {
for (ButtonInfo info : buttons) {
if (!info.isDownload() || myPatch == null) {
actions.add(new ButtonAction(info));
}
}
}
actions.add(new AbstractAction(IdeBundle.message("updates.ignore.update.button")) {
@Override
public void actionPerformed(ActionEvent e) {
String build = myLatestBuild.getNumber().asStringWithoutProductCode();
UpdateSettings.getInstance().getIgnoredBuildNumbers().add(build);
doCancelAction();
}
});
actions.add(getCancelAction());
return actions.toArray(new Action[actions.size()]);
}
@Override
protected String getCancelButtonText() {
return IdeBundle.message("updates.remind.later.button");
}
private void downloadPatch(final boolean canRestart) {
final UpdateChecker.DownloadPatchResult result = UpdateChecker.downloadAndInstallPatch(myLatestBuild);
if (result == UpdateChecker.DownloadPatchResult.SUCCESS) {
if (myUpdatedPlugins != null && !myUpdatedPlugins.isEmpty()) {
new PluginUpdateInfoDialog(getContentPanel(), myUpdatedPlugins, true){
@Override
protected boolean downloadModal() {
return true;
}
@Override
protected String getOkButtonText() {
return IdeBundle.message(canRestart ? "update.restart.plugins.update.action" : "update.shutdown.plugins.update.action");
}
}.show();
}
restart();
}
else if (result == UpdateChecker.DownloadPatchResult.FAILED) {
openDownloadPage();
}
}
private void openDownloadPage() {
BrowserUtil.browse(myUpdatedChannel.getHomePageUrl());
}
private static class ButtonAction extends AbstractAction {
private final String myUrl;
private ButtonAction(ButtonInfo info) {
super(info.getName());
myUrl = info.getUrl();
}
@Override
public void actionPerformed(ActionEvent e) {
BrowserUtil.browse(myUrl);
}
}
private class UpdateInfoPanel {
private JPanel myPanel;
private JEditorPane myUpdateMessage;
private JBLabel myCurrentVersion;
private JBLabel myNewVersion;
private JBLabel myPatchLabel;
private JBLabel myPatchInfo;
private JEditorPane myMessageArea;
private JEditorPane myLicenseArea;
public UpdateInfoPanel() {
ApplicationInfo appInfo = ApplicationInfo.getInstance();
ApplicationNamesInfo appNames = ApplicationNamesInfo.getInstance();
String message = myLatestBuild.getMessage();
final String fullProductName = appNames.getFullProductName();
if (message == null) {
message = IdeBundle.message("updates.new.version.available", fullProductName);
}
final String homePageUrl = myUpdatedChannel.getHomePageUrl();
if (!StringUtil.isEmptyOrSpaces(homePageUrl)) {
final int idx = message.indexOf(fullProductName);
if (idx >= 0) {
message = message.substring(0, idx) +
"<a href=\'" + homePageUrl + "\'>" + fullProductName + "</a>" + message.substring(idx + fullProductName.length());
}
}
configureMessageArea(myUpdateMessage, message, null, BrowserHyperlinkListener.INSTANCE);
myCurrentVersion.setText(
formatVersion(
appInfo.getFullVersion() + (appInfo instanceof ApplicationInfoEx && ((ApplicationInfoEx)appInfo).isEAP() ? " EAP": ""),
appInfo.getBuild().asStringWithoutProductCode()
)
);
myNewVersion.setText(formatVersion(myLatestBuild.getVersion(), myLatestBuild.getNumber().asStringWithoutProductCode()));
if (myPatch != null) {
myPatchInfo.setText(myPatch.getSize() + " MB");
}
else {
myPatchLabel.setVisible(false);
myPatchInfo.setVisible(false);
}
if (myWriteProtected) {
message = IdeBundle.message("updates.write.protected", appNames.getProductName(), PathManager.getHomePath());
configureMessageArea(myMessageArea, message, JBColor.RED, null);
}
else {
configureMessageArea(myMessageArea);
}
if (mySubscribtionLicense && myLicenseInfo != null) {
configureMessageArea(myLicenseArea, myLicenseInfo, myPaidUpgrade ? JBColor.RED : null, null);
}
}
private String formatVersion(String version, String build) {
String[] parts = version.split("\\.", 3);
String major = parts.length > 0 ? parts[0] : "0";
String minor = parts.length > 1 ? parts[1] : "0";
String patch = parts.length > 2 ? parts[2] : "0";
version = major + '.' + minor + '.' + patch;
return IdeBundle.message("updates.version.info", version, build);
}
}
}
|
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.updateSettings.impl;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.BrowserHyperlinkListener;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Collection;
import java.util.List;
/**
* @author pti
*/
class UpdateInfoDialog extends AbstractUpdateDialog {
private final UpdateChannel myUpdatedChannel;
private final Collection<PluginDownloader> myUpdatedPlugins;
private final BuildInfo myLatestBuild;
private final PatchInfo myPatch;
private final boolean myWriteProtected;
protected UpdateInfoDialog(@NotNull UpdateChannel channel,
boolean enableLink,
Collection<PluginDownloader> updatedPlugins,
Collection<IdeaPluginDescriptor> incompatiblePlugins) {
super(enableLink);
myUpdatedChannel = channel;
myUpdatedPlugins = updatedPlugins;
myLatestBuild = channel.getLatestBuild();
myPatch = myLatestBuild != null ? myLatestBuild.findPatchForCurrentBuild() : null;
myWriteProtected = myPatch != null && !new File(PathManager.getHomePath()).canWrite();
getCancelAction().putValue(DEFAULT_ACTION, Boolean.TRUE);
if (myLatestBuild != null) {
initLicensingInfo(myUpdatedChannel, myLatestBuild);
}
init();
if (incompatiblePlugins != null && !incompatiblePlugins.isEmpty()) {
final boolean onePluginFound = incompatiblePlugins.size() == 1;
String incompatibilityError = "Incompatible with new version plugin";
incompatibilityError += (onePluginFound ? " is" : "s are") + " detected: ";
incompatibilityError += onePluginFound ? "" : "<br>";
incompatibilityError += StringUtil.join(incompatiblePlugins, new Function<IdeaPluginDescriptor, String>() {
@Override
public String fun(IdeaPluginDescriptor downloader) {
return downloader.getName();
}
}, "<br/>");
setErrorText(incompatibilityError);
}
}
@Override
protected JComponent createCenterPanel() {
return new UpdateInfoPanel().myPanel;
}
@NotNull
@Override
protected Action[] createActions() {
List<Action> actions = ContainerUtil.newArrayList();
if (myPatch != null) {
final boolean canRestart = ApplicationManager.getApplication().isRestartCapable();
String button = IdeBundle.message(canRestart ? "updates.download.and.restart.button" : "updates.download.and.install.button");
actions.add(new AbstractAction(button) {
{
setEnabled(!myWriteProtected);
}
@Override
public void actionPerformed(ActionEvent e) {
downloadPatch(canRestart);
}
});
}
List<ButtonInfo> buttons = myLatestBuild.getButtons();
if (buttons.isEmpty()) {
actions.add(new AbstractAction(IdeBundle.message("updates.more.info.button")) {
@Override
public void actionPerformed(ActionEvent e) {
openDownloadPage();
}
});
}
else {
for (ButtonInfo info : buttons) {
if (!info.isDownload() || myPatch == null) {
actions.add(new ButtonAction(info));
}
}
}
actions.add(new AbstractAction(IdeBundle.message("updates.ignore.update.button")) {
@Override
public void actionPerformed(ActionEvent e) {
String build = myLatestBuild.getNumber().asStringWithoutProductCode();
UpdateSettings.getInstance().getIgnoredBuildNumbers().add(build);
doCancelAction();
}
});
actions.add(getCancelAction());
return actions.toArray(new Action[actions.size()]);
}
@Override
protected String getCancelButtonText() {
return IdeBundle.message("updates.remind.later.button");
}
private void downloadPatch(final boolean canRestart) {
final UpdateChecker.DownloadPatchResult result = UpdateChecker.downloadAndInstallPatch(myLatestBuild);
if (result == UpdateChecker.DownloadPatchResult.SUCCESS) {
if (myUpdatedPlugins != null && !myUpdatedPlugins.isEmpty()) {
new PluginUpdateInfoDialog(getContentPanel(), myUpdatedPlugins, true){
@Override
protected boolean downloadModal() {
return true;
}
@Override
protected String getOkButtonText() {
return IdeBundle.message(canRestart ? "update.restart.plugins.update.action" : "update.shutdown.plugins.update.action");
}
}.show();
}
restart();
}
else if (result == UpdateChecker.DownloadPatchResult.FAILED) {
openDownloadPage();
}
}
private void openDownloadPage() {
BrowserUtil.browse(myUpdatedChannel.getHomePageUrl());
}
private static class ButtonAction extends AbstractAction {
private final String myUrl;
private ButtonAction(ButtonInfo info) {
super(info.getName());
myUrl = info.getUrl();
}
@Override
public void actionPerformed(ActionEvent e) {
BrowserUtil.browse(myUrl);
}
}
private class UpdateInfoPanel {
private JPanel myPanel;
private JEditorPane myUpdateMessage;
private JBLabel myCurrentVersion;
private JBLabel myNewVersion;
private JBLabel myPatchLabel;
private JBLabel myPatchInfo;
private JEditorPane myMessageArea;
private JEditorPane myLicenseArea;
public UpdateInfoPanel() {
ApplicationInfo appInfo = ApplicationInfo.getInstance();
ApplicationNamesInfo appNames = ApplicationNamesInfo.getInstance();
String message = myLatestBuild.getMessage();
final String fullProductName = appNames.getFullProductName();
if (message == null) {
message = IdeBundle.message("updates.new.version.available", fullProductName);
}
final String homePageUrl = myUpdatedChannel.getHomePageUrl();
if (!StringUtil.isEmptyOrSpaces(homePageUrl)) {
final int idx = message.indexOf(fullProductName);
if (idx >= 0) {
message = message.substring(0, idx) +
"<a href=\'" + homePageUrl + "\'>" + fullProductName + "</a>" + message.substring(idx + fullProductName.length());
}
}
configureMessageArea(myUpdateMessage, message, null, BrowserHyperlinkListener.INSTANCE);
myCurrentVersion.setText(formatVersion(appInfo.getFullVersion(), appInfo.getBuild().asStringWithoutProductCode()));
myNewVersion.setText(formatVersion(myLatestBuild.getVersion(), myLatestBuild.getNumber().asStringWithoutProductCode()));
if (myPatch != null) {
myPatchInfo.setText(myPatch.getSize() + " MB");
}
else {
myPatchLabel.setVisible(false);
myPatchInfo.setVisible(false);
}
if (myWriteProtected) {
message = IdeBundle.message("updates.write.protected", appNames.getProductName(), PathManager.getHomePath());
configureMessageArea(myMessageArea, message, JBColor.RED, null);
}
else {
configureMessageArea(myMessageArea);
}
if (mySubscribtionLicense && myLicenseInfo != null) {
configureMessageArea(myLicenseArea, myLicenseInfo, myPaidUpgrade ? JBColor.RED : null, null);
}
}
private String formatVersion(String version, String build) {
String[] parts = version.split("\\.", 3);
String major = parts.length > 0 ? parts[0] : "0";
String minor = parts.length > 1 ? parts[1] : "0";
String patch = parts.length > 2 ? parts[2] : "0";
version = major + '.' + minor + '.' + patch;
return IdeBundle.message("updates.version.info", version, build);
}
}
}
|
(if needed) add EAP suffix for updated version (IDEA-133731)
|
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java
|
(if needed) add EAP suffix for updated version (IDEA-133731)
|
|
Java
|
apache-2.0
|
3348086c008fc5e7df7dbeabb8d99563a299413c
| 0
|
adilakhter/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,wmaintw/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,adilakhter/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,hansjoachim/DependencyCheck,adilakhter/DependencyCheck,dwvisser/DependencyCheck,hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,dwvisser/DependencyCheck,adilakhter/DependencyCheck,recena/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,hansjoachim/DependencyCheck,recena/DependencyCheck,recena/DependencyCheck,wmaintw/DependencyCheck,awhitford/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,wmaintw/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,dwvisser/DependencyCheck,colezlaw/DependencyCheck,wmaintw/DependencyCheck,dwvisser/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,wmaintw/DependencyCheck,hansjoachim/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,dwvisser/DependencyCheck,stevespringett/DependencyCheck,recena/DependencyCheck,jeremylong/DependencyCheck,recena/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,dwvisser/DependencyCheck,wmaintw/DependencyCheck,recena/DependencyCheck
|
/*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.exception;
import java.io.IOException;
/**
* An exception used when the data needed does not exist to perform analysis.
*
* @author Jeremy Long
*/
public class NoDataException extends IOException {
/**
* The serial version uid.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new NoDataException.
*/
public NoDataException() {
super();
}
/**
* Creates a new NoDataException.
*
* @param msg a message for the exception.
*/
public NoDataException(String msg) {
super(msg);
}
/**
* Creates a new NoDataException.
*
* @param ex the cause of the exception.
*/
public NoDataException(Throwable ex) {
super(ex);
}
/**
* Creates a new NoDataException.
*
* @param msg a message for the exception.
* @param ex the cause of the exception.
*/
public NoDataException(String msg, Throwable ex) {
super(msg, ex);
}
}
|
dependency-check-core/src/main/java/org/owasp/dependencycheck/exception/NoDataException.java
|
/*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.exception;
import java.io.IOException;
/**
* An exception used when the data needed does not exist to perform analysis.
*
* @author Jeremy Long <jeremy.long@owasp.org>
*/
public class NoDataException extends IOException {
/**
* The serial version uid.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new NoDataException.
*/
public NoDataException() {
super();
}
/**
* Creates a new NoDataException.
*
* @param msg a message for the exception.
*/
public NoDataException(String msg) {
super(msg);
}
/**
* Creates a new NoDataException.
*
* @param ex the cause of the exception.
*/
public NoDataException(Throwable ex) {
super(ex);
}
/**
* Creates a new NoDataException.
*
* @param msg a message for the exception.
* @param ex the cause of the exception.
*/
public NoDataException(String msg, Throwable ex) {
super(msg, ex);
}
}
|
updated javadoc author
Former-commit-id: f68b96df72699fd541ac14af9a98e198729017d6
|
dependency-check-core/src/main/java/org/owasp/dependencycheck/exception/NoDataException.java
|
updated javadoc author
|
|
Java
|
apache-2.0
|
790e703d3b9cad6e49655ea5cb2d918804706514
| 0
|
oussemaAr/cw-omnibus,knighthunter09/cw-omnibus,tianyong2/cw-omnibus,knighthunter09/cw-omnibus,itasanb/cw-omnibus,AkechiNEET/cw-omnibus,oussemaAr/cw-omnibus,itasanb/cw-omnibus,jvvlives2005/cw-omnibus,onloner/cw-omnibus,maduhu/cw-omnibus,MingxuanChen/cw-omnibus,xyzy/cw-omnibus,aschworer/cw-omnibus,suclike/cw-omnibus,a-ankitpatel/cw-omnibus,yuriysych/cw-omnibus,commonsguy/cw-omnibus,prashant31191/cw-omnibus,esavard/cw-omnibus,alexsh/cw-omnibus,hamidsn/cw-omnibus,juanmendez/cw-omnibus,iconodo/cw-omnibus,esavard/cw-omnibus,alexsh/cw-omnibus,yuriysych/cw-omnibus,IUHHUI/cw-omnibus,alexsh/cw-omnibus,gkavyakurpad/cw-omnibus,rjhonsl/cw-omnibus,PavelKniha/cw-omnibus,ryandh/cw-omnibus,rickywo/cw-omnibus,suclike/cw-omnibus,commonsguy/cw-omnibus,andy199609/cw-omnibus,weikipeng/cw-omnibus,raghunandankavi2010/cw-omnibus,HaiderAliG/cw-omnibus,rjhonsl/cw-omnibus,knighthunter09/cw-omnibus,DaveKavanagh/cw-omnibus,Jumshaid/empublite,yuriysych/cw-omnibus,ryandh/cw-omnibus,mangel99/cw-omnibus,jojobando/cw-omnibus,superboonie/cw-omnibus,aschworer/cw-omnibus,maharsh007/cw-omnibus,beyondbycyx/cw-omnibus,treejames/cw-omnibus,tianyong2/cw-omnibus,atishagrawal/cw-omnibus,raghunandankavi2010/cw-omnibus,itasanb/cw-omnibus,atishagrawal/cw-omnibus,EvidenceKiller/cw-omnibus,andrea9a/cw-omnibus,commonsguy/cw-omnibus,tianyong2/cw-omnibus,ajju4455/cw-omnibus,andrea9a/cw-omnibus,ryandh/cw-omnibus,alexsh/cw-omnibus,xyzy/cw-omnibus,AkechiNEET/cw-omnibus,commonsguy/cw-omnibus,EvidenceKiller/cw-omnibus,Jumshaid/empublite,iconodo/cw-omnibus,immuvijay/cw-omnibus,andrea9a/cw-omnibus,aeron1sh/cw-omnibus,iconodo/cw-omnibus,maduhu/cw-omnibus,HasanAliKaraca/cw-omnibus,ajju4455/cw-omnibus,raghunandankavi2010/cw-omnibus,ryandh/cw-omnibus,prashant31191/cw-omnibus,MingxuanChen/cw-omnibus,maduhu/cw-omnibus,hamidsn/cw-omnibus,VinayakDeshpande11/cw-omnibus,andrea9a/cw-omnibus,juanmendez/cw-omnibus,speedyGonzales/cw-omnibus,hamidsn/cw-omnibus,jasonzhong/cw-omnibus,ajju4455/cw-omnibus,rjhonsl/cw-omnibus,itasanb/cw-omnibus,andy199609/cw-omnibus,weikipeng/cw-omnibus,superboonie/cw-omnibus,jasonzhong/cw-omnibus,suclike/cw-omnibus,rickywo/cw-omnibus,superboonie/cw-omnibus,itasanb/cw-omnibus,weikipeng/cw-omnibus,ranjith068/cw-omnibus,kinghy2302/cw-omnibus,HaiderAliG/cw-omnibus,speedyGonzales/cw-omnibus,mangel99/cw-omnibus,HaiderAliG/cw-omnibus,ajju4455/cw-omnibus,immuvijay/cw-omnibus,kinghy2302/cw-omnibus,ajju4455/cw-omnibus,xyzy/cw-omnibus,PavelKniha/cw-omnibus,tianyong2/cw-omnibus,beyondbycyx/cw-omnibus,a-ankitpatel/cw-omnibus,onloner/cw-omnibus,treejames/cw-omnibus,HaiderAliG/cw-omnibus,prashant31191/cw-omnibus,knighthunter09/cw-omnibus,knighthunter09/cw-omnibus,juanmendez/cw-omnibus,hamidsn/cw-omnibus,lexiaoyao20/cw-omnibus,Jumshaid/empublite,PavelKniha/cw-omnibus,kinghy2302/cw-omnibus,aschworer/cw-omnibus,JGeovani/cw-omnibus,hkngoc/cw-omnibus,speedyGonzales/cw-omnibus,aschworer/cw-omnibus,Jumshaid/empublite,maduhu/cw-omnibus,poojawins/cw-omnibus,VinayakDeshpande11/cw-omnibus,immuvijay/cw-omnibus,superboonie/cw-omnibus,mangel99/cw-omnibus,jasonzhong/cw-omnibus,prashant31191/cw-omnibus,weikipeng/cw-omnibus,jorgereina1986/cw-omnibus,c00240488/cw-omnibus,speedyGonzales/cw-omnibus,janzoner/cw-omnibus,c00240488/cw-omnibus,HasanAliKaraca/cw-omnibus,jorgereina1986/cw-omnibus,c00240488/cw-omnibus,esavard/cw-omnibus,rjhonsl/cw-omnibus,jojobando/cw-omnibus,mangel99/cw-omnibus,andy199609/cw-omnibus,HasanAliKaraca/cw-omnibus,maharsh007/cw-omnibus,aeron1sh/cw-omnibus,LG67/cw-omnibus,iconodo/cw-omnibus,kinghy2302/cw-omnibus,maharsh007/cw-omnibus,EvidenceKiller/cw-omnibus,xyzy/cw-omnibus,alexsh/cw-omnibus,IUHHUI/cw-omnibus,jasonzhong/cw-omnibus,esavard/cw-omnibus,commonsguy/cw-omnibus,c00240488/cw-omnibus,JGeovani/cw-omnibus,ranjith068/cw-omnibus,JGeovani/cw-omnibus,lexiaoyao20/cw-omnibus,janzoner/cw-omnibus,jasonzhong/cw-omnibus,andrea9a/cw-omnibus,ryandh/cw-omnibus,PavelKniha/cw-omnibus,raghunandankavi2010/cw-omnibus,maharsh007/cw-omnibus,raghunandankavi2010/cw-omnibus,janzoner/cw-omnibus,HasanAliKaraca/cw-omnibus,weikipeng/cw-omnibus,poojawins/cw-omnibus,kinghy2302/cw-omnibus,lexiaoyao20/cw-omnibus,beyondbycyx/cw-omnibus,knighthunter09/cw-omnibus,itasanb/cw-omnibus,LG67/cw-omnibus,a-ankitpatel/cw-omnibus,JGeovani/cw-omnibus,lexiaoyao20/cw-omnibus,atishagrawal/cw-omnibus,speedyGonzales/cw-omnibus,HaiderAliG/cw-omnibus,beyondbycyx/cw-omnibus,juanmendez/cw-omnibus,MingxuanChen/cw-omnibus,jorgereina1986/cw-omnibus,VinayakDeshpande11/cw-omnibus,MingxuanChen/cw-omnibus,hkngoc/cw-omnibus,maduhu/cw-omnibus,gkavyakurpad/cw-omnibus,LG67/cw-omnibus,ryandh/cw-omnibus,jvvlives2005/cw-omnibus,jvvlives2005/cw-omnibus,onloner/cw-omnibus,DaveKavanagh/cw-omnibus,jojobando/cw-omnibus,oussemaAr/cw-omnibus,LG67/cw-omnibus,gkavyakurpad/cw-omnibus,VinayakDeshpande11/cw-omnibus,aeron1sh/cw-omnibus,yuriysych/cw-omnibus,gkavyakurpad/cw-omnibus,onloner/cw-omnibus,superboonie/cw-omnibus,MingxuanChen/cw-omnibus,aschworer/cw-omnibus,DaveKavanagh/cw-omnibus,AkechiNEET/cw-omnibus,onloner/cw-omnibus,IUHHUI/cw-omnibus,rickywo/cw-omnibus,commonsguy/cw-omnibus,HaiderAliG/cw-omnibus,onloner/cw-omnibus,juanmendez/cw-omnibus,kinghy2302/cw-omnibus,treejames/cw-omnibus,tianyong2/cw-omnibus,ranjith068/cw-omnibus,raghunandankavi2010/cw-omnibus,jorgereina1986/cw-omnibus,maharsh007/cw-omnibus,maduhu/cw-omnibus,andrea9a/cw-omnibus,hkngoc/cw-omnibus,atishagrawal/cw-omnibus,mangel99/cw-omnibus,LG67/cw-omnibus,jojobando/cw-omnibus,treejames/cw-omnibus,PavelKniha/cw-omnibus,poojawins/cw-omnibus,esavard/cw-omnibus,janzoner/cw-omnibus,prashant31191/cw-omnibus,VinayakDeshpande11/cw-omnibus,weikipeng/cw-omnibus,hamidsn/cw-omnibus,jvvlives2005/cw-omnibus,hkngoc/cw-omnibus,beyondbycyx/cw-omnibus,LG67/cw-omnibus,janzoner/cw-omnibus,speedyGonzales/cw-omnibus,andy199609/cw-omnibus,AkechiNEET/cw-omnibus,jorgereina1986/cw-omnibus,suclike/cw-omnibus,AkechiNEET/cw-omnibus,maharsh007/cw-omnibus,aeron1sh/cw-omnibus,andy199609/cw-omnibus,IUHHUI/cw-omnibus,juanmendez/cw-omnibus,jasonzhong/cw-omnibus,janzoner/cw-omnibus,hamidsn/cw-omnibus,rickywo/cw-omnibus,hkngoc/cw-omnibus,atishagrawal/cw-omnibus,poojawins/cw-omnibus,atishagrawal/cw-omnibus,suclike/cw-omnibus,suclike/cw-omnibus,yuriysych/cw-omnibus,Jumshaid/empublite,JGeovani/cw-omnibus,c00240488/cw-omnibus,HasanAliKaraca/cw-omnibus,DaveKavanagh/cw-omnibus,jorgereina1986/cw-omnibus,MingxuanChen/cw-omnibus,IUHHUI/cw-omnibus,jojobando/cw-omnibus,aschworer/cw-omnibus,DaveKavanagh/cw-omnibus,rickywo/cw-omnibus,jojobando/cw-omnibus,aeron1sh/cw-omnibus,IUHHUI/cw-omnibus,ranjith068/cw-omnibus,a-ankitpatel/cw-omnibus,poojawins/cw-omnibus,Jumshaid/empublite,alexsh/cw-omnibus,jvvlives2005/cw-omnibus,andy199609/cw-omnibus,rjhonsl/cw-omnibus,DaveKavanagh/cw-omnibus,beyondbycyx/cw-omnibus,esavard/cw-omnibus,gkavyakurpad/cw-omnibus,jvvlives2005/cw-omnibus,alexsh/cw-omnibus,lexiaoyao20/cw-omnibus,lexiaoyao20/cw-omnibus,oussemaAr/cw-omnibus,xyzy/cw-omnibus,immuvijay/cw-omnibus,treejames/cw-omnibus,yuriysych/cw-omnibus,immuvijay/cw-omnibus,HasanAliKaraca/cw-omnibus,xyzy/cw-omnibus,treejames/cw-omnibus,prashant31191/cw-omnibus,ajju4455/cw-omnibus,rickywo/cw-omnibus,iconodo/cw-omnibus,oussemaAr/cw-omnibus,rjhonsl/cw-omnibus,PavelKniha/cw-omnibus,superboonie/cw-omnibus,tianyong2/cw-omnibus,ranjith068/cw-omnibus,c00240488/cw-omnibus,ranjith068/cw-omnibus,iconodo/cw-omnibus,mangel99/cw-omnibus,EvidenceKiller/cw-omnibus,JGeovani/cw-omnibus,commonsguy/cw-omnibus,EvidenceKiller/cw-omnibus,poojawins/cw-omnibus,gkavyakurpad/cw-omnibus,VinayakDeshpande11/cw-omnibus,EvidenceKiller/cw-omnibus,hkngoc/cw-omnibus,a-ankitpatel/cw-omnibus,AkechiNEET/cw-omnibus,a-ankitpatel/cw-omnibus,oussemaAr/cw-omnibus
|
/***
Copyright (c) 2013 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.preso.slides;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import com.commonsware.cwac.preso.PresentationHelper;
import com.viewpagerindicator.TabPageIndicator;
public class MainActivity extends Activity implements
PresentationHelper.Listener, OnPageChangeListener {
private ViewPager pager=null;
private SlidePresentationFragment preso=null;
private SlidesAdapter adapter=null;
private PresentationHelper helper=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabPageIndicator tabs=(TabPageIndicator)findViewById(R.id.titles);
pager=(ViewPager)findViewById(R.id.pager);
adapter=new SlidesAdapter(this);
pager.setAdapter(adapter);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(this);
helper=new PresentationHelper(this, this);
}
@Override
public void onResume() {
super.onResume();
helper.onResume();
}
@Override
public void onPause() {
helper.onPause();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.present:
boolean original=item.isChecked();
item.setChecked(!original);
if (original) {
helper.disable();
}
else {
helper.enable();
}
break;
case R.id.first:
pager.setCurrentItem(0);
break;
case R.id.last:
pager.setCurrentItem(adapter.getCount() - 1);
break;
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onPageScrollStateChanged(int arg0) {
// ignored
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// ignored
}
@Override
public void onPageSelected(int position) {
if (preso != null) {
preso.setSlideContent(adapter.getPageResource(position));
}
}
@Override
public void clearPreso(boolean showInline) {
if (preso != null) {
preso.dismiss();
preso=null;
}
}
@Override
public void showPreso(Display display) {
int drawable=adapter.getPageResource(pager.getCurrentItem());
preso=
SlidePresentationFragment.newInstance(this, display, drawable);
preso.show(getFragmentManager(), "preso");
}
}
|
Presentation/Slides/src/com/commonsware/android/preso/slides/MainActivity.java
|
/***
Copyright (c) 2013 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.preso.slides;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import com.commonsware.cwac.preso.PresentationHelper;
import com.viewpagerindicator.TabPageIndicator;
public class MainActivity extends Activity implements
PresentationHelper.Listener, OnPageChangeListener {
private ViewPager pager=null;
private SlidePresentationFragment preso=null;
private SlidesAdapter adapter=null;
private PresentationHelper helper=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabPageIndicator tabs=(TabPageIndicator)findViewById(R.id.titles);
pager=(ViewPager)findViewById(R.id.pager);
adapter=new SlidesAdapter(this);
pager.setAdapter(adapter);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(this);
helper=new PresentationHelper(this, this);
}
@Override
public void onResume() {
super.onResume();
helper.onResume();
}
@Override
public void onPause() {
helper.onPause();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.present:
boolean original=item.isChecked();
item.setChecked(!original);
if (original) {
helper.disable();
}
else {
helper.enable();
}
break;
case R.id.first:
pager.setCurrentItem(0);
break;
case R.id.last:
pager.setCurrentItem(adapter.getCount() - 1);
break;
}
return(super.onOptionsItemSelected(item));
}
@Override
public void onPageScrollStateChanged(int arg0) {
// ignored
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// ignored
}
@Override
public void onPageSelected(int position) {
if (preso != null) {
preso.setSlideContent(adapter.getPageResource(position));
}
}
@Override
public void clearPreso(boolean showInline) {
if (preso != null) {
preso.dismiss();
preso=null;
}
}
@Override
public void showPreso(Display display) {
preso=
SlidePresentationFragment.newInstance(this,
display,
adapter.getPageResource(pager.getCurrentItem()));
preso.show(getFragmentManager(), "preso");
}
}
|
reformatting for print
|
Presentation/Slides/src/com/commonsware/android/preso/slides/MainActivity.java
|
reformatting for print
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/com/google/inject/GuiceTest.java' did not match any file(s) known to git
|
e53273db533b61529798af855ca74cbfcea252ca
| 1
|
mikosik/deguicifier
|
package com.google.inject;
import static org.hamcrest.Matchers.instanceOf;
import static org.testory.Testory.given;
import static org.testory.Testory.thenReturned;
import static org.testory.Testory.thenThrown;
import static org.testory.Testory.when;
import org.junit.Test;
public class GuiceTest {
Guice guice = new Guice();
Injector injector;
@Test
public void guice_injector_provides_binding_for_class_with_default_constructor() throws Exception {
given(injector = guice.createInjector());
when(injector.getInstance(Object.class));
thenReturned(instanceOf(Object.class));
}
@Test
public void interface_cannot_be_annotated_as_singleton() throws Exception {
when(guice).createInjector(new ModuleBindingAnnotatedInterface());
thenThrown(CreationException.class);
}
public static class ModuleBindingAnnotatedInterface extends AbstractModule {
@Override
protected void configure() {
bind(AnnotatedInterface.class);
}
}
@Test
public void binding_wrapper_also_binds_primitive() throws Exception {
given(injector = guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Integer.class).toInstance(Integer.valueOf(3));
}
}));
when(injector.getInstance(int.class));
thenReturned(3);
}
@Singleton
public interface AnnotatedInterface {}
private static class Guice {
public Injector createInjector(Module... modules) {
return com.google.inject.Guice.createInjector(modules);
}
}
}
|
src/test/com/google/inject/GuiceTest.java
|
added GuiceTest
|
src/test/com/google/inject/GuiceTest.java
|
added GuiceTest
|
|
Java
|
apache-2.0
|
error: pathspec 'src/com/facebook/buck/rules/args/FormatArg.java' did not match any file(s) known to git
|
ced27a8b5dea77ef11d1ff041d3814d05be51e11
| 1
|
kageiit/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,nguyentruongtho/buck,kageiit/buck,Addepar/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,Addepar/buck,Addepar/buck,nguyentruongtho/buck,kageiit/buck,JoelMarcey/buck,JoelMarcey/buck,facebook/buck,nguyentruongtho/buck,kageiit/buck,kageiit/buck,nguyentruongtho/buck,JoelMarcey/buck,JoelMarcey/buck,JoelMarcey/buck,Addepar/buck,JoelMarcey/buck,facebook/buck,Addepar/buck,JoelMarcey/buck,facebook/buck,kageiit/buck,facebook/buck,facebook/buck,JoelMarcey/buck,JoelMarcey/buck,facebook/buck,Addepar/buck,JoelMarcey/buck,kageiit/buck,JoelMarcey/buck,nguyentruongtho/buck,facebook/buck,Addepar/buck,Addepar/buck,Addepar/buck
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.rules.args;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import java.util.function.Consumer;
/**
* Arg that stringifies another {@link Arg}, and passes that string representation into {@link
* java.lang.String#format(java.lang.String, java.lang.Object...)}
*/
@BuckStyleValue
public abstract class FormatArg implements Arg {
@AddToRuleKey
public abstract Arg getArg();
/**
* @return the format string
* <p>The format string should be either a string with one or more %s. Each %s will be
* replaced with the string value of {@link #getArg()}
*/
@AddToRuleKey
public abstract String getFormatString();
@Override
public void appendToCommandLine(
Consumer<String> consumer, SourcePathResolverAdapter pathResolver) {
StringBuilder builder = new StringBuilder();
getArg().appendToCommandLine(builder::append, pathResolver);
String stringified = builder.toString();
String formatString = getFormatString();
if (formatString.isEmpty() || formatString.equals("%s")) {
consumer.accept(stringified);
} else {
consumer.accept(getFormatString().replace("%s", stringified));
}
}
}
|
src/com/facebook/buck/rules/args/FormatArg.java
|
Add FormatArg to allow format strings
Summary:
Add a wrapper arg that lets us apply the final stringified value to a format string that has a single %s.
This will be used for an additional post-stringification formatting step. An example is the '/out' parameter to csc. It takes `/out:<some path>`. These cannot be passed as two arguments. However, we don't know the real path until we finally execute the action. Until then it's a SourcePath, or an Artifact, or any number of other things. But in the end, we'd want `/out:buck-out/gen/foo/bar/baz.exe` to be used. In this case the format string would be `/out:%s`. This allows that semi-arbitrary formatting.
Reviewed By: bobyangyf
shipit-source-id: 0693706be63a8ec761e6da1ff1dd9f7aeaf0573e
|
src/com/facebook/buck/rules/args/FormatArg.java
|
Add FormatArg to allow format strings
|
|
Java
|
apache-2.0
|
error: pathspec 'src/fr/softwaresemantics/howmanydroid/Locale.java' did not match any file(s) known to git
|
14f58ca94e84607344a1969794f343894bfb7c1d
| 1
|
cyrilmhansen/how-many-droid
|
package fr.softwaresemantics.howmanydroid;
import com.j256.ormlite.field.DatabaseField;
import java.io.Serializable;
/**
* Created by christophe goessen on 19/01/14.
*/
public class Locale implements Serializable {
@DatabaseField(id = true, generatedId = true, canBeNull = false, index = true)
private int localeId;
@DatabaseField(canBeNull = false)
String name;
@DatabaseField(canBeNull = false)
String description;
public Locale() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
src/fr/softwaresemantics/howmanydroid/Locale.java
|
fix missing Locale
|
src/fr/softwaresemantics/howmanydroid/Locale.java
|
fix missing Locale
|
|
Java
|
apache-2.0
|
error: pathspec 'src/com/itmill/toolkit/tests/tickets/Ticket1934.java' did not match any file(s) known to git
|
116e3761c096440929d94024e55e423a03b32de5
| 1
|
mstahv/framework,mittop/vaadin,travisfw/vaadin,sitexa/vaadin,Scarlethue/vaadin,udayinfy/vaadin,Darsstar/framework,travisfw/vaadin,magi42/vaadin,mstahv/framework,Flamenco/vaadin,mittop/vaadin,Darsstar/framework,kironapublic/vaadin,cbmeeks/vaadin,Scarlethue/vaadin,Legioth/vaadin,travisfw/vaadin,oalles/vaadin,synes/vaadin,Flamenco/vaadin,bmitc/vaadin,synes/vaadin,shahrzadmn/vaadin,Peppe/vaadin,shahrzadmn/vaadin,peterl1084/framework,udayinfy/vaadin,oalles/vaadin,jdahlstrom/vaadin.react,asashour/framework,Peppe/vaadin,udayinfy/vaadin,jdahlstrom/vaadin.react,udayinfy/vaadin,oalles/vaadin,Scarlethue/vaadin,asashour/framework,Legioth/vaadin,peterl1084/framework,magi42/vaadin,synes/vaadin,Darsstar/framework,shahrzadmn/vaadin,Scarlethue/vaadin,mstahv/framework,mstahv/framework,Peppe/vaadin,kironapublic/vaadin,mstahv/framework,Darsstar/framework,shahrzadmn/vaadin,bmitc/vaadin,peterl1084/framework,carrchang/vaadin,bmitc/vaadin,Legioth/vaadin,sitexa/vaadin,cbmeeks/vaadin,travisfw/vaadin,udayinfy/vaadin,asashour/framework,synes/vaadin,Darsstar/framework,mittop/vaadin,synes/vaadin,Peppe/vaadin,mittop/vaadin,peterl1084/framework,kironapublic/vaadin,cbmeeks/vaadin,sitexa/vaadin,Legioth/vaadin,magi42/vaadin,magi42/vaadin,oalles/vaadin,magi42/vaadin,cbmeeks/vaadin,Flamenco/vaadin,fireflyc/vaadin,jdahlstrom/vaadin.react,oalles/vaadin,fireflyc/vaadin,kironapublic/vaadin,fireflyc/vaadin,bmitc/vaadin,peterl1084/framework,carrchang/vaadin,carrchang/vaadin,kironapublic/vaadin,Legioth/vaadin,fireflyc/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,Flamenco/vaadin,jdahlstrom/vaadin.react,sitexa/vaadin,sitexa/vaadin,carrchang/vaadin,asashour/framework,Scarlethue/vaadin,asashour/framework,jdahlstrom/vaadin.react,travisfw/vaadin,Peppe/vaadin
|
package com.itmill.toolkit.tests.tickets;
import com.itmill.toolkit.Application;
import com.itmill.toolkit.ui.Button;
import com.itmill.toolkit.ui.ExpandLayout;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.Window;
public class Ticket1934 extends Application {
public void init() {
Window w = new Window(
"#1934 : Horizontal ExpandLayout completely broken");
setMainWindow(w);
w.addComponent(new Label(
"Horizontal 500x200 ExpandLayout with two components:"));
ExpandLayout testedLayout = new ExpandLayout(
ExpandLayout.ORIENTATION_HORIZONTAL);
testedLayout.setWidth(500);
testedLayout.setHeight(200);
Button b1 = new Button("b1");
testedLayout.addComponent(b1);
testedLayout.expand(b1);
testedLayout.addComponent(new Button("b2"));
w.addComponent(testedLayout);
}
}
|
src/com/itmill/toolkit/tests/tickets/Ticket1934.java
|
Test for #1934 : Horizontal ExpandLayout completely broken
svn changeset:5085/svn branch:trunk
|
src/com/itmill/toolkit/tests/tickets/Ticket1934.java
|
Test for #1934 : Horizontal ExpandLayout completely broken
|
|
Java
|
apache-2.0
|
error: pathspec 'src/com/github/booknara/nioexample/SelectorExample.java' did not match any file(s) known to git
|
df0838c2bccf277e6d2c505feafa706ebb202930
| 1
|
booknara/nio_playground
|
package com.github.booknara.nioexample;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* Created by Daehee Han(@daniel_booknara) on 2/12/16.
* This example is an incomplete code.
*/
public class SelectorExample {
public static void main(String[] args) {
Selector selector;
// Define socket channel
// SocketChannel channel = new SocketChannel();
//
// try {
// selector = Selector.open();
// channel.configureBlocking(false);
//
// SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_READ);
//
//
// while(true) {
//
// // Return how many channels are ready to read
// int readyChannels = selector.select();
//
// if(readyChannels == 0)
// continue;
//
//
// Set<SelectionKey> selectedKeys = selector.selectedKeys();
//
// Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
//
// while(keyIterator.hasNext()) {
//
// SelectionKey key = keyIterator.next();
//
// if(key.isAcceptable()) {
// // a connection was accepted by a ServerSocketChannel.
// // ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
// // SocketChannel socketChannel = (SocketChannel) key.channel();
//
// } else if (key.isConnectable()) {
// // a connection was established with a remote server.
//
// } else if (key.isReadable()) {
// // a channel is ready for reading
//
// } else if (key.isWritable()) {
// // a channel is ready for writing
// }
//
// keyIterator.remove();
// }
// }
//
// } catch (IOException e) {
// System.out.println(e.getStackTrace());
// }
}
}
|
src/com/github/booknara/nioexample/SelectorExample.java
|
Add Selector example
|
src/com/github/booknara/nioexample/SelectorExample.java
|
Add Selector example
|
|
Java
|
apache-2.0
|
error: pathspec 'core/src/main/java/dagger/internal/MembersInjectors.java' did not match any file(s) known to git
|
f98a2b1300d1816d56454d06836bb80643e8ac6a
| 1
|
tieusangaka/dagger,adriancole/dagger,gk5885/dagger,ronshapiro/dagger,chundongwang/dagger,google/dagger,talkxin/dagger,e10dokup/dagger,yongjhih/dagger2-sample,hanks-zyh/dagger,ravn/dagger,talkxin/dagger,ze-pequeno/dagger,adriancole/dagger,hansonchar/dagger,IgorGanapolsky/dagger,gk5885/dagger,DavidMihola/dagger,ze-pequeno/dagger,ravn/dagger,goinstant/dagger,vogellacompany/dagger,18611480882/dagger,cgruber/dagger,NorbertSandor/dagger,18611480882/dagger,tasomaniac/dagger,vogellacompany/dagger,AttwellBrian/dagger,google/dagger,NorbertSandor/dagger,cgpllx/dagger,dushmis/dagger,dushmis/dagger,cgruber/dagger,google/dagger,ronshapiro/dagger,tasomaniac/dagger,DavidMihola/dagger,hansonchar/dagger,hanks-zyh/dagger,Godchin1990/dagger,bboyfeiyu/dagger,tasomaniac/dagger,yawkat/dagger,Godchin1990/dagger,yawkat/dagger,AttwellBrian/dagger,18611480882/dagger,IgorGanapolsky/dagger,adriancole/dagger,google/dagger,andyao/dagger,yongjhih/dagger2-sample,tieusangaka/dagger,goinstant/dagger,yongjhih/dagger2-sample,cgpllx/dagger,gk5885/dagger,bboyfeiyu/dagger,andyao/dagger,yawkat/dagger,chundongwang/dagger,e10dokup/dagger,ze-pequeno/dagger,cgruber/dagger,ronshapiro/dagger,ze-pequeno/dagger,hansonchar/dagger,ravn/dagger
|
/*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.internal;
import dagger.MembersInjector;
import javax.inject.Inject;
/**
* Basic {@link MembersInjector} implementations used by the framework.
*
* @author Gregory Kick
* @since 2.0
*/
public final class MembersInjectors {
/**
* Returns a {@link MembersInjector} implementation that injects no members
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> noOp() {
return (MembersInjector<T>) NoOpMembersInjector.INSTANCE;
}
private static enum NoOpMembersInjector implements MembersInjector<Object> {
INSTANCE;
@Override public void injectMembers(Object instance) {
if (instance == null) {
throw new NullPointerException();
}
}
}
/**
* Returns a {@link MembersInjector} that delegates to the {@link MembersInjector} of its
* supertype. This is useful for cases where a type is known not to have its own {@link Inject}
* members, but must still inject members on its supertype(s).
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> delegatingTo(MembersInjector<? super T> delegate) {
return (MembersInjector<T>) delegate;
}
private MembersInjectors() {}
}
|
core/src/main/java/dagger/internal/MembersInjectors.java
|
Add the MembersInjectors class, which provides a few standard MembersInjector implementations that are to be used from within generated components.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=71274942
|
core/src/main/java/dagger/internal/MembersInjectors.java
|
Add the MembersInjectors class, which provides a few standard MembersInjector implementations that are to be used from within generated components. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=71274942
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/mybatis/guice/datasource/helper/JdbcHelper.java' did not match any file(s) known to git
|
cb6ae3c58e49d91ea905aa568caeda6c22905d5a
| 1
|
WilliamRen/guice,mybatis/guice,johnzeringue/guice,hazendaz/guice
|
/*
* Copyright 2010 The myBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.guice.datasource.helper;
/**
*
*
* @version $Id$
*/
public enum JdbcHelper {
Cache("jdbc:Cache://${JDBC.host}:${JDBC.port|1972}/${JDBC.schema}", "com.intersys.jdbc.CacheDriver"),
Daffodil_DB("jdbc:daffodilDB://${JDBC.host}:${JDBC.port|3456}/${JDBC.schema}", "in.co.daffodil.db.rmi.RmiDaffodilDBDriver"),
DB2("jdbc:db2://${JDBC.host}:${JDBC.port|50000}/${JDBC.schema}", "com.ibm.db2.jcc.DB2Driver"),
DB2_DataDirect("jdbc:datadirect:db2://${JDBC.host}:${JDBC.port|50000}/DatabaseName=${JDBC.schema}", "com.ddtek.jdbc.db2.DB2Driver"),
DB2_AS400_JTOpen("jdbc:as400://${JDBC.host}naming=sql;errors=full", "com.ibm.as400.access.AS400JDBCDriver"),
Firebird("jdbc:firebirdsql:${JDBC.host}/${JDBC.port|3050}:${JDBC.schema}", "org.firebirdsql.jdbc.FBDriver"),
FrontBase("jdbc:FrontBase://${JDBC.host}/${JDBC.schema}", "jdbc.FrontBase.FBJDriver"),
HP_Neoview("jdbc:hpt4jdbc://${system}:${JDBC.port}/:", "com.hp.t4jdbc.HPT4Driver"),
HSQLDB_Server("jdbc:hsqldb:hsql://${JDBC.host}:${JDBC.port|9001}/${JDBC.schema}", "org.hsqldb.jdbcDriver"),
HSQLDB_Embedded("jdbc:hsqldb:${JDBC.schema}", "org.hsqldb.jdbcDriver"),
Informix("jdbc:informix-sqli://${JDBC.host}:${JDBC.port|1533}/${JDBC.schema}:informixserver=${dbservername}", "com.informix.jdbc.IfxDriver"),
Informix_DataDirect("jdbc:datadirect:informix://${JDBC.host}:${JDBC.port|1533};InformixServer=${informixserver};DatabaseServer=${JDBC.schema}", "com.ddtek.jdbc.informix.InformixDriver"),
Derby_Server("jdbc:derby://${JDBC.host}:${JDBC.port|1527}/${JDBC.schema}", "org.apache.derby.jdbc.ClientDriver"),
Derby_Embedded("jdbc:derby:${JDBC.schema}", "org.apache.derby.jdbc.EmbeddedDriver"),
JDataStore("jdbc:borland:dslocal:${JDBC.schema}", "com.borland.datastore.jdbc.DataStoreDriver"),
JDBC_ODBC_Bridge("jdbc:odbc:${ODBC.datasource}", "sun.jdbc.odbc.JdbcOdbcDriver"),
MaxDB("jdbc:sapdb://${JDBC.host}:${JDBC.port|7210}/${JDBC.schema}", "com.sap.dbtech.jdbc.DriverSapDB"),
McKoi("jdbc:mckoi://${JDBC.host}:${JDBC.port|9157}/${JDBC.schema}", "com.mckoi.JDBCDriver"),
Mimer("jdbc:mimer:${protocol}://${JDBC.host}:${JDBC.port|1360}/${JDBC.schema}", "com.mimer.jdbc.Driver"),
MySQL("jdbc:mysql://${JDBC.host}:${JDBC.port|3306}/${JDBC.schema}", "com.mysql.jdbc.Driver"),
Netezza("jdbc:netezza://${JDBC.host}:${JDBC.port|5480}/${JDBC.schema}", "org.netezza.Driver"),
Oracle_Thin("jdbc:oracle:thin:@${JDBC.host}:${JDBC.port|1521}:${JDBC.schema}", "oracle.jdbc.OracleDriver"),
Oracle_OCI("jdbc:oracle:oci:@${JDBC.host}:${JDBC.port|1521}:${JDBC.schema}", "oracle.jdbc.OracleDriver"),
Oracle_DataDirect("jdbc:datadirect:oracle://${JDBC.host}:${JDBC.port|1521};ServiceName=${servicename}", "com.ddtek.jdbc.oracle.OracleDriver"),
Pervasive("jdbc:pervasive://${JDBC.host}:${JDBC.port}/${JDBC.schema}", "pervasive.jdbc.PervasiveDriver"),
Pointbase_Embedded("jdbc:pointbase:embedded:${:database}", "com.pointbase.jdbc.jdbcUniversalDriver"),
Pointbase_Server("jdbc:pointbase:server://${JDBC.host}:${JDBC.port|9092}/${JDBC.schema}", "com.pointbase.jdbc.jdbcUniversalDriver"),
PostgreSQL("jdbc:postgresql://${JDBC.host}:${JDBC.port|5432}/${JDBC.schema}", "org.postgresql.Driver"),
Progress("jdbc:jdbcProgress:T:${JDBC.host}:${JDBC.port|2055}:${JDBC.schema}", "com.progress.sql.jdbc.JdbcProgressDriver"),
SQL_Server_DataDirect("jdbc:datadirect:sqlserver://${JDBC.host}:${JDBC.port|1433};DatabaseName=${JDBC.schema}", "com.ddtek.jdbc.sqlserver.SQLServerDriver"),
SQL_Server_jTDS("jdbc:jtds:sqlserver://${JDBC.host}:${JDBC.port|1433};DatabaseName=${JDBC.schema}", "net.sourceforge.jtds.jdbc.Driver"),
SQL_Server_MS_Driver("jdbc:microsoft:sqlserver://${JDBC.host}:${JDBC.port|1433};DatabaseName=${JDBC.schema}", "com.microsoft.jdbc.sqlserver.SQLServerDriver"),
SQL_Server_2005_MS_Driver("jdbc:sqlserver://${JDBC.host}:${JDBC.port|1433};DatabaseName=${JDBC.schema}", "com.microsoft.sqlserver.jdbc.SQLServerDriver"),
Sybase_ASE_jTDS("jdbc:jtds:sybase://${JDBC.host}:${JDBC.port|5000};DatabaseName=${JDBC.schema}", "net.sourceforge.jtds.jdbc.Driver"),
Sybase_ASE_JConnect("jdbc:sybase:Tds:${JDBC.host}:${JDBC.port|5000}/${JDBC.schema}", "com.sybase.jdbc3.jdbc.SybDriver"),
Sybase_SQL_Anywhere_JConnect("jdbc:sybase:Tds:${JDBC.host}:${JDBC.port|2638}/${JDBC.schema}", "com.sybase.jdbc3.jdbc.SybDriver"),
Sybase_DataDirect("jdbc:datadirect:sybase://${JDBC.host}:${JDBC.port|2048};ServiceName=${servicename}", "com.ddtek.jdbc.sybase.SybaseDriver");
private final String urlTemplate;
private final String driverClass;
JdbcHelper(String urlTemplate, String driverClass) {
this.urlTemplate = urlTemplate;
this.driverClass = driverClass;
}
public String getUrlTemplate() {
return this.urlTemplate;
}
public String getDriverClass() {
return this.driverClass;
}
}
|
src/main/java/org/mybatis/guice/datasource/helper/JdbcHelper.java
|
first checkin of helper to make easier jdbc url and driver binding
|
src/main/java/org/mybatis/guice/datasource/helper/JdbcHelper.java
|
first checkin of helper to make easier jdbc url and driver binding
|
|
Java
|
apache-2.0
|
error: pathspec 'maven-latex-plugin/src/main/java/org/m2latex/core/LatexPreProcessor.java' did not match any file(s) known to git
|
b51b3fc5104be524929d38087360ccaf3b7e1033
| 1
|
Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin,Reissner/maven-latex-plugin
|
/*
* The akquinet maven-latex-plugin project
*
* Copyright (c) 2011 by akquinet tech@spree GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.m2latex.core;
import org.m2latex.mojo.CfgLatexMojo;
import org.m2latex.mojo.GraphicsMojo;
import org.m2latex.mojo.ClearMojo;
import java.io.File;
import java.io.FileFilter;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
// idea: use latex2rtf and unoconv
// idea: targets for latex2html, latex2man, latex2png and many more.
/**
* The latex processor creates various output from latex sources
* including also preprocessing of graphic files in several formats.
* This is the core class of this piece of software.
* The main method is {@link #create()} which is executed by the ant task
* and by the maven plugin.
* It does preprocessing of the graphic files
* and main processing of the latex file according to the target(s)
* given by the parameters.
*/
public class LatexProcessor {
/**
* Maps the suffix to the according handler.
* If the handler is <code>null</code>, there is no handler.
*/
private final static Map<String, SuffixHandler> SUFFIX2HANDLER =
new HashMap<String, SuffixHandler>();
static {
for (SuffixHandler handler : SuffixHandler.values()) {
SUFFIX2HANDLER.put(handler.getSuffix(), handler);
}
} // static
private final Collection<File> latexMainFiles = new ArrayList<File>();
// For pattern matching, it is vital to avoid false positive matches.
// e.g. Overfull \box with text '! ' is not an error
// and Overfull \box with text 'Warning' is no warning.
static final String PATTERN_NEED_BIBTEX_RUN = "^\\\\bibdata";
// Note that two \\ represent a single \ in the string.
// Thus \\\\ represents '\\' in the pattern,
// which in turn represents a single \.
static final String PATTERN_OUFULL_HVBOX =
"^(Ov|Und)erfull \\\\[hv]box \\(";
// LaTeX
final static String SUFFIX_TOC = ".toc";
final static String SUFFIX_LOF = ".lof";
final static String SUFFIX_LOT = ".lot";
final static String SUFFIX_AUX = ".aux";
// LaTeX and mpost with option -recorder
final static String SUFFIX_FLS = ".fls";
// for LaTeX but also for mpost
final static String SUFFIX_LOG = ".log";
// used in preprocessing only
private final static String SUFFIX_TEX = ".tex";
// home-brewed ending to represent tex including postscript
private final static String SUFFIX_PTX = ".ptx";// For preprocessing only
// the next two for preprocessing and in LatexDev only
final static String SUFFIX_PSTEX = ".pstex";
final static String SUFFIX_PDFTEX = ".pdf_tex";
// suffix for xfig
private final static String SUFFIX_FIG = ".fig";// in SuffixHandler only
// suffix for svg
private final static String SUFFIX_SVG = ".svg";// in SuffixHandler only
// suffix for gnuplot
private final static String SUFFIX_PLT = ".plt";// in SuffixHandler only
// suffix for metapost
private final static String SUFFIX_MP = ".mp";// in SuffixHandler only
// from xxx.mp creates xxx1.mps, xxx.log and xxx.mpx
private final static String SUFFIX_MPS = ".mps";// For preprocessing only
private final static String SUFFIX_MPX = ".mpx";// For preprocessing only
final static String SUFFIX_PDF = ".pdf";
// odt2doc
private final static String SUFFIX_ODT = ".odt";
// makeindex for index
// unsorted and not unified index created by latex
final static String SUFFIX_IDX = ".idx";
// log file created by makeindex
final static String SUFFIX_ILG = ".ilg";
// makeindex for glossary
// unsorted and not unified glossary created by latex
final static String SUFFIX_GLO = ".glo";
// index style, better glossary style created by latex for makeindex.
final static String SUFFIX_IST = ".ist";
// index style, better glossary style created by latex for xindy.
final static String SUFFIX_XDY = ".xdy";
// sorted and unified glossary created by makeindex
final static String SUFFIX_GLS = ".gls";
// logging file for makeindex used with glossaries
final static String SUFFIX_GLG = ".glg";
// bibtex
final static String SUFFIX_BLG = ".blg";
// needed by makeglossaries
final static String SUFFIX_VOID = "";
private final Settings settings;
private final CommandExecutor executor;
private final LogWrapper log;
private final TexFileUtils fileUtils;
private final ParameterAdapter paramAdapt;
// also for tests
LatexProcessor(Settings settings,
CommandExecutor executor,
LogWrapper log,
TexFileUtils fileUtils,
ParameterAdapter paramAdapt) {
this.settings = settings;
this.log = log;
this.executor = executor;
this.fileUtils = fileUtils;
this.paramAdapt = paramAdapt;
}
/**
* Creates a LatexProcessor with parameters given by <code>settings</code>
* which logs onto <code>log</code> and used by <code>paramAdapt</code>.
*
* @param settings
* the settings controlling latex processing
* @param log
* the logger to write on events while processing
* @param paramAdapt
* the parameter adapter, refers to maven-plugin or ant-task.
*/
public LatexProcessor(Settings settings,
LogWrapper log,
ParameterAdapter paramAdapt) {
this(settings, new CommandExecutorImpl(log), log,
new TexFileUtilsImpl(log), paramAdapt);
}
/**
* Defines creational ant-task and the maven plugin
* in {@link CfgLatexMojo} and subclasses.
* This consists in reading the parameters
* via {@link ParameterAdapter#initialize()}
* processing graphic-files
* via {@link #processGraphicsSelectMain(Collection)}
* and processing the tex main files
* via {@link Target#processSource(LatexProcessor, File)}.
* The resulting files are identified by its suffixes
* via {@link Target#getOutputFileSuffixes()}
* and copied to the target folder.
* Finally, by default a cleanup is performed
* invoking {@link TexFileUtils#cleanUp(Collection, File)}.
* <p>
* Logging:
* <ul>
* <li>
* If the tex directory does not exist.
* <li>
* FIXME: logging of invoked methods.
* </ul>
*
* FIXME: exceptions not really clear.
* @throws BuildExecutionException
* <ul>
* <li>
* if copying the latex-directory to the temporary directory
* or copying the results from the temporary directory
* into the target directory fails.
* <li>
* if processing xfig-files or gnuplot files or latex-files fail.
* <li>
* if latex main documents could not be identified.
* <li>
* if processing xfig-files or gnuplot files fail.
* </ul>
*/
public void create() throws BuildExecutionException, BuildFailureException {
this.paramAdapt.initialize();
this.log.debug("Settings: " + this.settings.toString() );
File texDirectory = this.settings.getTexSrcDirectoryFile();
if (!texDirectory.exists()) {
this.log.info("No tex directory - skipping LaTeX processing. ");
return;
}
// may throw BuildExecutionException
// should fail without finally cleanup
Collection<File> orgFiles = this.fileUtils.getFilesRec(texDirectory);
try {
// process graphics and determine latexMainFiles
// may throw BuildExecutionException
Collection<File> latexMainFiles =
processGraphicsSelectMain(orgFiles);
for (File texFile : latexMainFiles) {
// may throw BuildExecutionException, BuildFailureException
File targetDir = this.fileUtils.getTargetDirectory
(texFile,
texDirectory,
this.settings.getOutputDirectoryFile());
for (Target target : this.paramAdapt.getTargetSet()) {
// may throw BuildExecutionException
target.processSource(this, texFile);
FileFilter fileFilter = this.fileUtils
.getFileFilter(texFile,
target.getOutputFileSuffixes());
// may throw BuildExecutionException, BuildFailureException
this.fileUtils.copyOutputToTargetFolder(texFile,
fileFilter,
targetDir);
} // target
} // texFile
} finally {
if (this.settings.isCleanUp()) {
// may throw BuildExecutionException
this.fileUtils.cleanUp(orgFiles, texDirectory);
}
}
}
/**
* Used by {@link GraphicsMojo}.
*/
public void processGraphics() throws BuildExecutionException {
File texDirectory = this.settings.getTexSrcDirectoryFile();
if (!texDirectory.exists()) {
this.log.info("No tex directory - " +
"skipping graphics processing. ");
return;
}
// may throw BuildExecutionException
Collection<File> orgFiles = this.fileUtils.getFilesRec(texDirectory);
processGraphicsSelectMain(orgFiles);
}
/**
*
*/
enum SuffixHandler {
fig {
// converts a fig-file into pdf
// invoking {@link #runFig2Dev(File, LatexDev)}
void transformSrc(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.runFig2Dev(file, LatexDev.pdf);
}
void clearTarget(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.clearTargetFig(file);
}
String getSuffix() {
return LatexProcessor.SUFFIX_FIG;
}
},
plt {
// converts a gnuplot-file into pdf
// invoking {@link #runGnuplot2Dev(File, LatexDev)}
void transformSrc(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.runGnuplot2Dev(file, LatexDev.pdf);
}
void clearTarget(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.clearTargetPlt(file);
}
String getSuffix() {
return LatexProcessor.SUFFIX_PLT;
}
},
mp {
// converts a metapost-file into mps-format
// invoking {@link #runMetapost2mps(File)}
void transformSrc(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.runMetapost2mps(file);
}
void clearTarget(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.clearTargetMp(file);
}
String getSuffix() {
return LatexProcessor.SUFFIX_MP;
}
},
svg {
void transformSrc(File file, LatexProcessor proc)
throws BuildExecutionException {
// proc.log.info("Processing svg-file " + file +
// " done implicitly. ");
}
void clearTarget(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.clearTargetSvg(file);
}
String getSuffix() {
return LatexProcessor.SUFFIX_SVG;
}
},
tex {
void transformSrc(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.addMainFile(file);
}
void clearTarget(File file, LatexProcessor proc)
throws BuildExecutionException {
proc.clearTargetTex(file);
}
String getSuffix() {
return LatexProcessor.SUFFIX_TEX;
}
};
abstract void transformSrc(File file, LatexProcessor proc)
throws BuildExecutionException;
abstract void clearTarget(File file, LatexProcessor proc)
throws BuildExecutionException;
abstract String getSuffix();
} // enum SuffixHandler
/**
* Runs fig2dev on fig-files to generate pdf and pdf_t files.
* This is a quite restricted usage of fig2dev.
*
* @param figFile
* the fig file to be processed.
* @throws BuildExecutionException
* if running the fig2dev command
* returned by {@link Settings#getFig2devCommand()} failed.
* This is invoked twice: once for creating the pdf-file
* and once for creating the pdf_t-file.
* @see #create()
*/
// used in processGraphics(File) only
private void runFig2Dev(File figFile, LatexDev dev)
throws BuildExecutionException {
this.log.info("Processing fig-file " + figFile + ". ");
String command = this.settings.getFig2devCommand();
File workingDir = figFile.getParentFile();
String[] args;
//File pdfFile = this.fileUtils.replaceSuffix(figFile, SUFFIX_PDF);
// create pdf-file (graphics without text)
// embedded in some tex-file
//if (update(figFile, pdfFile)) {
args = buildArgumentsFig2Pdf(dev,
this.settings.getFig2devGenOptions(),
this.settings.getFig2devPdfOptions(),
figFile);
log.debug("Running " + command +
" -Lpdftex ... on " + figFile.getName() + ". ");
// may throw BuildExecutionException
this.executor.execute(workingDir,
this.settings.getTexPath(), //****
command,
args);
//}
// create tex-file (text without grapics)
// enclosing the pdf-file above
//if (update(figFile, pdf_tFile)) {
args = buildArgumentsFig2Ptx(dev,
this.settings.getFig2devGenOptions(),
this.settings.getFig2devPtxOptions(),
figFile);
log.debug("Running " + command +
" -Lpdftex_t... on " + figFile.getName() + ". ");
// may throw BuildExecutionException
this.executor.execute(workingDir,
this.settings.getTexPath(), //****
command,
args);
//}
// no check: just warning that no output has been created.
}
private String[] buildArgumentsFig2Pdf(LatexDev dev,
String optionsGen,
String optionsPdf,
File figFile) {
String[] optionsGenArr = optionsGen.isEmpty()
? new String[0] : optionsGen.split(" ");
String[] optionsPdfArr = optionsPdf.isEmpty()
? new String[0] : optionsPdf.split(" ");
int lenSum = optionsGenArr.length +optionsPdfArr.length;
String[] args = new String[lenSum + 4];
// language
args[0] = "-L";
args[1] = dev.getXFigInTexLanguage();
// general options
System.arraycopy(optionsGenArr, 0, args, 2, optionsGenArr.length);
// language specific options
System.arraycopy(optionsPdfArr, 0,
args, 2+optionsGenArr.length, optionsPdfArr.length);
// input: fig-file
args[2+lenSum] = figFile.getName();
// output: pdf-file
args[3+lenSum] = dev.getXFigInTexFile(this.fileUtils, figFile);
return args;
}
private String[] buildArgumentsFig2Ptx(LatexDev dev,
String optionsGen,
String optionsPtx,
File figFile) {
String[] optionsGenArr = optionsGen.isEmpty()
? new String[0] : optionsGen.split(" ");
String[] optionsPtxArr = optionsPtx.isEmpty()
? new String[0] : optionsPtx.split(" ");
int lenSum = optionsGenArr.length +optionsPtxArr.length;
String[] args = new String[lenSum + 6];
// language
args[0] = "-L";
args[1] = dev.getXFigTexLanguage();
// general options
System.arraycopy(optionsGenArr, 0,
args, 2, optionsGenArr.length);
// language specific options
System.arraycopy(optionsPtxArr, 0,
args, 2+optionsGenArr.length, optionsPtxArr.length);
// -p pdf-file in ptx-file
args[2+lenSum] = "-p";
args[3+lenSum] = dev.getXFigInTexFile(this.fileUtils, figFile);
// input: fig-file
args[4+lenSum] = figFile.getName();
// output: ptx-file
args[5+lenSum] = this.fileUtils.replaceSuffix(figFile, SUFFIX_PTX)
.getName();
return args;
}
/**
* Converts a gnuplot file into a tex-file with ending ptx
* including a pdf-file.
*
* @param pltFile
* the plt-file (gnuplot format) to be converted to pdf.
* @throws BuildExecutionException
* if running the ptx/pdf-conversion built in in gnuplot fails.
* @see #create()
*/
// used in processGraphics(Collection) only
private void runGnuplot2Dev(File pltFile, LatexDev dev)
throws BuildExecutionException {
this.log.info("Processing gnuplot-file " + pltFile + ". ");
String command = this.settings.getGnuplotCommand();
File pdfFile = this.fileUtils.replaceSuffix(pltFile, SUFFIX_PDF);
File ptxFile = this.fileUtils.replaceSuffix(pltFile, SUFFIX_PTX);
String[] args = new String[] {
"-e", // run a command string "..." with commands sparated by ';'
//
"set terminal cairolatex " + dev.getGnuplotInTexLanguage() +
" " + this.settings.getGnuplotOptions() +
";set output \"" + ptxFile.getName() +
"\";load \"" + pltFile.getName() + "\""
};
// FIXME: include options.
// set terminal cairolatex
// {eps | pdf} done before.
// {standalone | input}
// {blacktext | colortext | colourtext}
// {header <header> | noheader}
// {mono|color}
// {{no}transparent} {{no}crop} {background <rgbcolor>}
// {font <font>} {fontscale <scale>}
// {linewidth <lw>} {rounded|butt|square} {dashlength <dl>}
// {size <XX>{unit},<YY>{unit}}
// if (update(pltFile, ptxFile)) {
log.debug("Running " + command +
" -e... on " + pltFile.getName() + ". ");
// may throw BuildExecutionException
this.executor.execute(pltFile.getParentFile(), //workingDir
this.settings.getTexPath(), //****
command,
args);
// }
// no check: just warning that no output has been created.
}
/**
* Runs mpost on mp-files to generate mps-files.
*
* @param mpFile
* the metapost file to be processed.
* @throws BuildExecutionException
* if running the mpost command failed.
* @see #processGraphics(File)
*/
// used in processGraphics(Collection) only
private void runMetapost2mps(File mpFile) throws BuildExecutionException {
this.log.info("Processing metapost-file " + mpFile + ". ");
String command = this.settings.getMetapostCommand();
File workingDir = mpFile.getParentFile();
// for more information just type mpost --help
String[] args = buildArguments(this.settings.getMetapostOptions(),
mpFile);
log.debug("Running " + command + " on " + mpFile.getName() + ". ");
// may throw BuildExecutionException
this.executor.execute(workingDir,
this.settings.getTexPath(), //****
command,
args);
// from xxx.mp creates xxx1.mps, xxx.log and xxx.mpx
// FIXME: what is xxx.mpx for?
File logFile = this.fileUtils.replaceSuffix(mpFile, SUFFIX_LOG);
logErrs(logFile, command, this.settings.getPatternErrMPost());
// FIXME: what about warnings?
}
private void addMainFile(File texFile) throws BuildExecutionException {
// may throw BuildExecutionException
if (this.fileUtils
.matchInFile(texFile,
this.settings.getPatternLatexMainFile())) {
this.log.info("Detected latex-main-file " + texFile + ". ");
this.latexMainFiles.add(texFile);
}
}
/**
* Converts files in various graphic formats incompatible with LaTeX
* into formats which can be inputted or included directly
* into a latex file and returns the latex main files.
*
* @throws BuildExecutionException
*/
private Collection<File> processGraphicsSelectMain(Collection<File> files)
throws BuildExecutionException {
this.latexMainFiles.clear();
SuffixHandler handler;
for (File file : files) {
handler = SUFFIX2HANDLER.get(this.fileUtils.getSuffix(file));
if (handler != null) {
// may throw BuildExecutionException
handler.transformSrc(file, this);
}
}
return this.latexMainFiles;
}
private void clearTargetFig(File figFile)
throws BuildExecutionException {
this.log.info("Deleting targets of fig-file " + figFile + ". ");
// may throw BuildExecutionException
this.fileUtils.replaceSuffix(figFile, SUFFIX_PTX).delete();
this.fileUtils.replaceSuffix(figFile, SUFFIX_PDF).delete();
}
private void clearTargetPlt(File pltFile)
throws BuildExecutionException {
this.log.info("Deleting targets of gnuplot-file " + pltFile + ". ");
// may throw BuildExecutionException
this.fileUtils.replaceSuffix(pltFile, SUFFIX_PTX).delete();
this.fileUtils.replaceSuffix(pltFile, SUFFIX_PDF).delete();
}
private void clearTargetMp(File mpFile)
throws BuildExecutionException {
this.log.info("Deleting targets of metapost-file " + mpFile + ". ");
// may throw BuildExecutionException
this.fileUtils.replaceSuffix(mpFile, SUFFIX_LOG).delete();
this.fileUtils.replaceSuffix(mpFile, SUFFIX_FLS).delete();
this.fileUtils.replaceSuffix(mpFile, SUFFIX_MPX).delete();
// delete files xxxNumber.mps
String name1 = mpFile.getName();
final String root = name1.substring(0, name1.lastIndexOf("."));
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory()
&& file.getName().matches(root + "\\d+" + SUFFIX_MPS);
}
};
// may throw BuildExecutionException
this.fileUtils.delete(mpFile, filter);
}
private void clearTargetSvg(File svgFile)
throws BuildExecutionException {
this.log.info("Deleting targets of svg-file " + svgFile + ". ");
// may throw BuildExecutionException
this.fileUtils.replaceSuffix(svgFile, SUFFIX_PDFTEX).delete();
// this.fileUtils.replaceSuffix(svgFile, SUFFIX_PSTEX ).delete();
this.fileUtils.replaceSuffix(svgFile, SUFFIX_PDF ).delete();
}
private void clearTargetTex(final File texFile)
throws BuildExecutionException {
// may throw BuildExecutionException
if (!this.fileUtils
.matchInFile(texFile,
this.settings.getPatternLatexMainFile())) {
return;
}
// filter to delete
String name1 = texFile.getName();
final String root = name1.substring(0, name1.lastIndexOf("."));
FileFilter filter = new FileFilter() {
public boolean accept(File file) {
return !file.isDirectory()
&& file.getName().startsWith(root)
&& !file.equals(texFile);
}
};
this.log.info("Deleting files " + root + "... . ");
// may throw BuildExecutionException
this.fileUtils.delete(texFile, filter);
this.log.info("Deleting file zz" + root + ".eps. ");
// FIXME: eliminate literal ".eps"
new File(texFile.getParent(), "zz" + root + ".eps").delete();
}
/**
* Defines clearing ant-task and the maven plugin
* in {@link ClearMojo}.
* Consists in clearing created graphic files
* and created files derived from latex main file.
*
* @throws BuildExecutionException
*/
public void clearAll() throws BuildExecutionException {
this.paramAdapt.initialize();
this.log.debug("Settings: " + this.settings.toString());
File texDirectory = this.settings.getTexSrcDirectoryFile();
// may throw BuildExecutionException
Collection<File> files = this.fileUtils.getFilesRec(texDirectory);
SuffixHandler handler;
for (File file : files) {
handler = SUFFIX2HANDLER.get(this.fileUtils.getSuffix(file));
if (handler != null) {
handler.clearTarget(file, this);
}
}
}
// FIXME: use the -recorder option to resolve dependencies.
// With that option, a file xxx.fls is generated with form
// PWD /home/ernst/OpenSource/maven-latex-plugin/maven-latex-plugin.git/trunk/maven-latex-plugin/src/site/tex
// INPUT /usr/local/texlive/2014/texmf.cnf
// INPUT /usr/local/texlive/2014/texmf-dist/web2c/texmf.cnf
// INPUT /usr/local/texlive/2014/texmf-var/web2c/pdftex/pdflatex.fmt
// INPUT manualLatexMavenPlugin.tex
// OUTPUT manualLatexMavenPlugin.log
// INPUT /usr/local/texlive/2014/texmf-dist/tex/latex/base/article.cls
// INPUT /usr/local/texlive/2014/texmf-dist/tex/latex/base/article.cls
// INPUT /usr/local/texlive/2014/texmf-dist/tex/latex/base/size12.clo
//
// The first line starts has the form 'PWD <working directory>'
// The other lines have the form '(INPUT|OUTPUT) <file>'
// We distinguishe those in the installation,
// here '/usr/local/texlive/2014/...' which do not change ever
// and others.
// In this example, the others are (unified and sorted):
// INPUT manualLatexMavenPlugin.tex
// OUTPUT manualLatexMavenPlugin.log
// INPUT manualLatexMavenPlugin.aux
// OUTPUT manualLatexMavenPlugin.aux
// INPUT manualLatexMavenPlugin.out
// OUTPUT manualLatexMavenPlugin.out
// INPUT manualLatexMavenPlugin.toc
// OUTPUT manualLatexMavenPlugin.toc
// INPUT manualLatexMavenPlugin.lof
// OUTPUT manualLatexMavenPlugin.lof
// INPUT manualLatexMavenPlugin.lot
// OUTPUT manualLatexMavenPlugin.lot
// OUTPUT manualLatexMavenPlugin.idx
// INPUT manualLatexMavenPlugin.ind
// OUTPUT manualLatexMavenPlugin.pdf
// INPUT 1fig2dev.ptx
// INPUT 1fig2dev.pdf
// INPUT 2plt2pdf.ptx
// INPUT 2plt2pdf.pdf
// INPUT 4tex2pdf.ptx
// INPUT 5aux2bbl.ptx
// INPUT 5aux2bbl.pdf
// INPUT 6idx2ind.ptx
// INPUT 6idx2ind.pdf
// INPUT 7tex2xml.ptx
// INPUT 7tex2xml.pdf
// what is missing is all to do with bibliography, i.e. the bib-file.
// FIXME: determine whether to use latexmk makes sense
/**
* Runs LaTeX on <code>texFile</code> at once,
* runs BibTeX, MakeIndex and MakeGlossaries by need
* and returns whether a second LaTeX run is required.
* The latter also holds, if a table of contents, a list of figures
* or a list of tables is specified.
* <p>
* A warning is logged if the LaTeX, a BibTeX run a MakeIndex
* or a MakeGlossaries run fails
* or if a BibTeX run or a MakeIndex or a MakeGlossary run issues a warning
* in the according methods {@link #runLatex2pdf(File, File)},
* {@link #runBibtexByNeed(File)}, {@link #runMakeIndexByNeed(File)} and
* {@link #runMakeGlossaryByNeed(File)}.
*
* @param texFile
* the latex-file to be processed.
* @param logFile
* the log-file after processing <code>texFile</code>.
* @return
* the number of LaTeX runs required
* because bibtex, makeindex or makeglossaries had been run
* or to update a table of contents or a list figures or tables.
* <ul>
* <li>
* If neither of these are present, no rerun is required.
* <li>
* If a bibliography, an index and a glossary is included
* and a table of contents,
* we assume that these are in the table of contents.
* Thus two reruns are required:
* one to include the bibliography or that like
* and the second one to make it appear in the table of contents.
* <li>
* In all other cases, a single rerun suffices
* </ul>
* @see #processLatex2pdfCore(File, File)
* @see #processLatex2html(File)
* @see #processLatex2odt(File)
* @see #processLatex2docx(File)
*/
private int preProcessLatex2pdf(final File texFile, File logFile)
throws BuildExecutionException {
// initial latex run
runLatex2pdf(texFile, logFile);
// create bibliography, index and glossary by need
boolean hasBib = runBibtexByNeed (texFile);
boolean hasIdxGls = runMakeIndexByNeed (texFile)
| runMakeGlossaryByNeed(texFile);
// rerun LaTeX at least once if bibtex or makeindex had been run
// or if a toc, a lof or a lot exists.
if (hasBib) {
// on run to include the bibliography from xxx.bbl into the pdf
// and the lables into the aux file
// and another run to put the lables from the aux file
// to the locations of the \cite commands.
// This suffices also to include a bib in a toc
return 2;
}
boolean hasToc =
this.fileUtils.replaceSuffix(texFile, SUFFIX_TOC) .exists();
if (hasIdxGls) {
// Here, an index or a glossary exists
// This requires at least one LaTeX run.
// if one of these has to be included in a toc,
// a second run is needed.
return hasToc ? 2 : 1;
}
// Here, no bib, index or glossary exists.
// The result is either 0 or 1,
// depending on whether a toc, lof or lot exists
boolean needLatexReRun = hasToc
|| this.fileUtils.replaceSuffix(texFile, SUFFIX_LOF).exists()
|| this.fileUtils.replaceSuffix(texFile, SUFFIX_LOT).exists();
return needLatexReRun ? 1 : 0;
}
/**
* Runs LaTeX on <code>texFile</code> at once,
* runs BibTeX, MakeIndex and MakeGlossaries by need
* according to {@link #preProcessLatex2pdf(File, File)}
* and reruns latex as long as needed to get all links
* or as threshold {@link Settings#maxNumReRunsLatex} specifies.
* <p>
* The result of the LaTeX run is typically some pdf-file,
* but it is also possible to specify the dvi-format
* (no longer recommended but still working).
* <p>
* Note that no warnings are issued by the latex run.
*
* @param texFile
* the latex-file to be processed.
* @param logFile
* the log-file after processing <code>texFile</code>.
* @see #processLatex2pdf(File)
* @see #processLatex2txt(File)
*/
public void processLatex2pdfCore(final File texFile, File logFile)
throws BuildExecutionException {
int numLatexReRuns = preProcessLatex2pdf(texFile, logFile);
assert numLatexReRuns == 0
|| numLatexReRuns == 1
|| numLatexReRuns == 2;
if (numLatexReRuns > 0) {
// rerun LaTeX without makeindex and makeglossaries
log.debug("Rerun LaTeX to update table of contents, ... " +
"bibliography, index, or that like. ");
runLatex2pdf(texFile, logFile);
numLatexReRuns--;
}
assert numLatexReRuns == 0 || numLatexReRuns == 1;
// rerun latex by need patternRerunMakeIndex
boolean needMakeIndexReRun;
boolean needLatexReRun = (numLatexReRuns == 1)
|| needAnotherLatexRun(logFile);
int maxNumReruns = this.settings.getMaxNumReRunsLatex();
for (int num = 0; maxNumReruns == -1 || num < maxNumReruns; num++) {
needMakeIndexReRun = needAnotherMakeIndexRun(logFile);
// FIXME: superfluous since pattern rerunfileckeck
// triggering makeindex also fits rerun of LaTeX
needLatexReRun |= needMakeIndexReRun;
if (!needLatexReRun) {
return;
}
log.debug("Latex must be rerun. ");
if (needMakeIndexReRun) {
// FIXME: not by need
runMakeIndexByNeed(texFile);
}
runLatex2pdf(texFile, logFile);
needLatexReRun = needAnotherLatexRun(logFile);
}
log.warn("Max rerun reached although LaTeX demands another run. ");
}
/**
* Runs LaTeX on <code>texFile</code>
* BibTeX, MakeIndex and MakeGlossaries
* and again LaTeX creating a pdf-file
* as specified by {@link #preProcessLatex2pdf(File, File)}
* and issues a warning if
* <ul>
* <li>
* another LaTeX rerun is required
* beyond {@link Settings#maxNumReRunsLatex},
* <li>
* bad boxes or warnings occurred.
* For details see {@link #logWarns(File, String)}.
* </ul>
*
* @param texFile
* the tex file to be processed.
* @see #needAnotherLatexRun(File)
*/
public void processLatex2pdf(File texFile) throws BuildExecutionException {
log.info("Converting into pdf: LaTeX file " + texFile + ". ");
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
processLatex2pdfCore(texFile, logFile);
// emit warnings (errors are emitted by runLatex2pdf and that like.)
logWarns(logFile, this.settings.getLatex2pdfCommand());
}
/**
* Logs errors detected in the according log file:
* The log file is by replacing the ending of <code>texFile</code>
* by <code>log</code>.
* If the log file exists, a <em>warning</em> is logged
* if the error pattern given by {@link Settings#getPatternErrLatex()}
* occurs in the log file.
* If the log file does not exist, an <em>error</em> is logged.
* In both cases, the message logged refers to the <code>command</code>
* which failed.
*/
private void logErrs(File logFile, String command)
throws BuildExecutionException {
logErrs(logFile, command, this.settings.getPatternErrLatex());
}
/**
* Logs if an error occurred running <code>command</code>
* by detecting that the log file <code>logFile</code> has not been created
* or by detecting the error pattern <code>pattern</code>
* in <code>logFile</code>.
*
* @throws BuildExecutionException
* if <code>logFile</code> does not exist or is not readable.
* @see #logWarns(File, String, String)
*/
private void logErrs(File logFile, String command, String pattern)
throws BuildExecutionException {
if (logFile.exists()) {
// matchInFile may throw BuildExecutionException
if (this.fileUtils.matchInFile(logFile, pattern)) {
log.warn("Running " + command + " failed. For details see " +
logFile.getName() + ". ");
}
} else {
this.log.error("Running " + command + " failed: no log file " +
logFile.getName() + " found. ");
}
}
/**
* Logs warnings detected in the according log-file <code>logFile</code>:
* Before logging warnings,
* errors are logged via {@link #logErrs(File, String)}.
* So, if the log-file does not exist,
* an error was already shown and so nothing is to be done here.
* If the log-file exists, a <em>warning</em> is logged if
* <ul>
* <li>
* another LaTeX rerun is required beyond {@link Settings#maxNumReruns},
* <li>
* bad boxes occurred and shall be logged
* according to {@link Settings#getDebugBadBoxes()}.
* <li>
* warnings occurred and shall be logged
* according to {@link Settings#getDebugWarnings()}.
* </ul>
* Both criteria are based on pattern recognized in the log file:
* {@link #PATTERN_OUFULL_HVBOX} for bad boxes is fixed,
* whereas {@link Settings#getPatternWarnLatex()} is configurable.
* The message logged refers to the <code>command</code> which failed.
*
* @param logFile
* the log-file to detect warnings in.
* @param command
* the command which created <code>logFile</code>
* and which maybe created warnings.
*/
private void logWarns(File logFile, String command)
throws BuildExecutionException {
if (!logFile.exists()) {
return;
}
if (this.settings.getDebugBadBoxes() &&
this.fileUtils.matchInFile(logFile, PATTERN_OUFULL_HVBOX)) {
log.warn("Running " + command + " created bad boxes. ");
}
if (this.settings.getDebugWarnings() &&
this.fileUtils.matchInFile(logFile,
this.settings.getPatternWarnLatex())) {
log.warn("Running " + command + " emited warnings. ");
}
}
/**
* Logs if a warning occurred running <code>command</code>
* by detecting the warning pattern <code>pattern</code>
* in <code>logFile</code>.
* If <code>logFile</code> then an error occurred
* making detection of warnings obsolete.
*
* @see #logErrs(File, String, String)
*/
private void logWarns(File logFile, String command, String pattern)
throws BuildExecutionException {
if (logFile.exists() && this.fileUtils.matchInFile(logFile, pattern)) {
log.warn("Running " + command +
" emitted warnings. For details see " +
logFile.getName() + ". ");
}
}
/**
* Runs conversion of <code>texFile</code> to html or xhtml
* after processing latex to set up the references,
* bibliography, index and that like.
*
* @param texFile
* the tex file to be processed.
* @see #preProcessLatex2pdf(File, File)
* @see #runLatex2html(File)
*/
public void processLatex2html(File texFile)
throws BuildExecutionException {
log.info("Converting into html: LaTeX file " + texFile + ". ");
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
preProcessLatex2pdf(texFile, logFile);
runLatex2html (texFile);
}
/**
* Runs conversion of <code>texFile</code>
* to odt or other open office formats
* after processing latex to set up the references,
* bibliography, index and that like.
*
* @param texFile
* the tex file to be processed.
* @see #preProcessLatex2pdf(File, File)
* @see #runLatex2odt(File)
*/
public void processLatex2odt(File texFile) throws BuildExecutionException {
log.info("Converting into odt: LaTeX file " + texFile + ". ");
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
preProcessLatex2pdf(texFile, logFile);
runLatex2odt (texFile);
}
/**
* Runs conversion of <code>texFile</code>
* to docx or other MS word formats
* after processing latex to set up the references,
* bibliography, index and that like.
*
* @param texFile
* the tex file to be processed.
* @see #preProcessLatex2pdf(File, File)
* @see #runLatex2odt(File)
* @see #runOdt2doc(File)
*/
public void processLatex2docx(File texFile) throws BuildExecutionException {
log.info("Converting into doc(x): LaTeX file " + texFile + ". ");
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
preProcessLatex2pdf(texFile, logFile);
runLatex2odt (texFile);
runOdt2doc (texFile);
}
/**
* Runs direct conversion of <code>texFile</code> to rtf format.
* <p>
* FIXME: Maybe prior invocation of LaTeX MakeIndex and BibTeX
* after set up the references, bibliography, index and that like
* would be better.
*
* @param texFile
* the tex file to be processed.
* @see #runLatex2rtf(File)
*/
public void processLatex2rtf(File texFile) throws BuildExecutionException {
log.info("Converting into rtf: LaTeX file " + texFile + ". ");
runLatex2rtf(texFile);
}
/**
* Runs conversion of <code>texFile</code> to txt format via pdf.
*
* @param texFile
* the tex file to be processed.
* @see #processLatex2pdfCore(File, File)
* @see #runPdf2txt(File)
*/
public void processLatex2txt(File texFile) throws BuildExecutionException {
log.info("Converting into txt: LaTeX file " + texFile + ". ");
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
processLatex2pdfCore(texFile, logFile);
// warnings emitted by LaTex are ignored
// (errors are emitted by runLatex2pdf and that like.)
runPdf2txt (texFile);
}
private boolean update(File source, File target) {
if (!target.exists()) {
return true;
}
assert source.exists();
return source.lastModified() > target.lastModified();
}
// suffix for tex files containing text and including pdf
/**
* Runs the latex2rtf command
* given by {@link Settings#getLatex2rtfCommand()}
* on <code>texFile</code>
* in the directory containing <code>texFile</code>
* with arguments given by {@link #buildLatex2rtfArguments(String, File)}.
*
* @param texFile
* the latex file to be processed.
* @throws BuildExecutionException
* if running the latex2rtf command
* returned by {@link Settings#getLatex2rtfCommand()} failed.
*/
private void runLatex2rtf(File texFile)
throws BuildExecutionException {
String command = this.settings.getLatex2rtfCommand();
log.debug("Running " + command + " on " + texFile.getName() + ". ");
String[] args = buildArguments(this.settings.getLatex2rtfOptions(),
texFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(), // workingDir
this.settings.getTexPath(),
command,
args);
// FIXME: no check: just warning that no output has been created.
// Warnings and error messages are output to stderr
// and by default listed in the console window.
// aThey can be redirected to a file “latex2rtf.log” by
// appending 2>latex2rtf.log to the command line.
}
/**
* Runs the tex4ht command given by {@link Settings#getTex4htCommand()}
* on <code>texFile</code>
* in the directory containing <code>texFile</code>
* with arguments given by {@link #buildHtlatexArguments(String, File)}.
* FIXME: document about errors and warnings.
*
* @param texFile
* the latex-file to be processed.
* @throws BuildExecutionException
* if running the tex4ht command
* returned by {@link Settings#getTex4htCommand()} failed.
*/
private void runLatex2html(File texFile)
throws BuildExecutionException {
String command = this.settings.getTex4htCommand();
log.debug("Running " + command + " on " + texFile.getName() + ". ");
String[] args = buildHtlatexArguments(texFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(), // workingDir
this.settings.getTexPath(),
command,
args);
// logging errors and warnings
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
logErrs (logFile, command);
logWarns(logFile, command);
}
private String[] buildHtlatexArguments(File texFile)
throws BuildExecutionException {
return new String[] {
texFile.getName(),
this.settings.getTex4htStyOptions(),
this.settings.getTex4htOptions(),
this.settings.getT4htOptions(),
this.settings.getLatex2pdfOptions()
};
}
/**
* Runs conversion from latex to odt
* executing {@link Settings#getTex4htCommand()}
* on <code>texFile</code>
* in the directory containing <code>texFile</code>
* with arguments given by {@link #buildLatexArguments(String, File)}.
* <p>
* Logs a warning or an error if the latex run failed
* invoking {@link #logErrs(File, String)}
* but not if bad boxes ocurred or if warnings occurred.
* This is done in {@link #processLatex2pdf(File)}
* after the last LaTeX run only.
*
* @param texFile
* the latex file to be processed.
* @throws BuildExecutionException
* if running the tex4ht command
* returned by {@link Settings#getTex4htCommand()} failed.
*/
private void runLatex2odt(File texFile)
throws BuildExecutionException {
String command = this.settings.getTex4htCommand();
log.debug("Running " + command + " on" + texFile.getName() + ". ");
String[] args = new String[] {
texFile.getName(),
"xhtml,ooffice", // there is no choice here
"ooffice/! -cmozhtf",// ooffice/! represents a font direcory
"-coo -cvalidate"// -coo is mandatory, -cvalidate is not
};
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(),
this.settings.getTexPath(),
command,
args);
// FIXME: logging refers to latex only, not to tex4ht or t4ht script
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_LOG);
logErrs (logFile, command);
logWarns(logFile, command);
}
// FIXME: missing options.
// above all (input) doctype: -ddoc, -ddocx
// and (output) doctype: -fdoc, -fdocx,
// available: odt2doc --show.
// among those also: latex and rtf !!!!!!
// This is important to define the copy filter accordingly
/**
* Runs conversion from odt to doc or docx-file
* executing {@link Settings#getOdt2docCommand()}
* on an odt-file created from <code>texFile</code>
* in the directory containing <code>texFile</code>
* with arguments given by {@link #buildLatexArguments(String, File)}.
*
* @param texFile
* the latex file to be processed.
* @throws BuildExecutionException
* if running the odt2doc command
* returned by {@link Settings#getOdt2docCommand()} failed.
*/
private void runOdt2doc(File texFile)
throws BuildExecutionException {
File odtFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_ODT);
String command = this.settings.getOdt2docCommand();
log.debug("Running " + command + " on " + odtFile.getName() + ". ");
String[] args = buildArguments(this.settings.getOdt2docOptions(),
odtFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(),
this.settings.getTexPath(),
command,
args);
}
/**
* Runs conversion from pdf to txt-file
* executing {@link Settings#getPdf2txtCommand()}
* on a pdf-file created from <code>texFile</code>
* in the directory containing <code>texFile</code>
* with arguments given by {@link #buildLatexArguments(String, File)}.
*
* @param texFile
* the latex file to be processed.
* @throws BuildExecutionException
* if running the pdf2txt command
* returned by {@link Settings#getPdf2txtCommand()} failed.
*/
private void runPdf2txt(File texFile) throws BuildExecutionException {
File pdfFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_PDF);
String command = this.settings.getPdf2txtCommand();
log.debug("Running " + command + " on " + pdfFile.getName() + ". ");
String[] args = buildArguments(this.settings.getPdf2txtOptions(),
pdfFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(),
this.settings.getTexPath(),
command,
args);
// FIXME: what about error logging?
// Seems not to create a log-file.
}
/**
* Returns an array of strings,
* each entry with a single option given by <code>options</code>
* except the last one which is the name of <code>file</code>.
*
* @param options
* the options string. The individual options
* are expected to be separated by a single blank.
* @param file
*
* @return
* An array of strings:
* The 0th entry is the file name,
* The others, if <code>options</code> is not empty,
* are the options in <code>options</code>.
*/
static String[] buildArguments(String options, File file) {
if (options.isEmpty()) {
return new String[] {file.getName()};
}
String[] optionsArr = options.split(" ");
String[] args = Arrays.copyOf(optionsArr, optionsArr.length + 1);
args[optionsArr.length] = file.getName();
return args;
}
/**
* Returns whether another LaTeX run is necessary
* based on a pattern matching in the log file.
*
* @see Settings#getPatternReRunMakeIndex()
*/
// FIXME: unification with needAnotherLatexRun?
private boolean needAnotherMakeIndexRun(File logFile)
throws BuildExecutionException {
String reRunPattern = this.settings.getPatternReRunMakeIndex();
// may throw a BuildExecutionException
boolean needRun = this.fileUtils.matchInFile(logFile, reRunPattern);
log.debug("Another MakeIndex run? " + needRun);
return needRun;
}
/**
* Returns whether another LaTeX run is necessary
* based on a pattern matching in the log file.
*
* @see Settings#getPatternReRunLatex()
*/
private boolean needAnotherLatexRun(File logFile)
throws BuildExecutionException {
String reRunPattern = this.settings.getPatternReRunLatex();
// may throw a BuildExecutionException
boolean needRun = this.fileUtils.matchInFile(logFile, reRunPattern);
log.debug("Another LaTeX run? " + needRun);
return needRun;
}
/**
* Runs the MakeIndex command
* given by {@link Settings#getMakeIndexCommand()}
* on the idx-file corresponding with <code>texFile</code>
* in the directory containing <code>texFile</code>
* provided that the existence of an idx-file indicates
* that an index shall be created.
*
* @param texFile
* the latex-file MakeIndex is to be processed for.
* @return
* whether MakeIndex had been run.
* Equivalently, whether LaTeX has to be rerun because of MakeIndex.
*/
// FIXME: bad name since now there are reruns.
// Suggestion: runMakeIndexInitByNeed
// Other methods accordingly.
// maybe better: eliminate altogether
private boolean runMakeIndexByNeed(File texFile)
throws BuildExecutionException {
// raw index file written by pdflatex
File idxFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_IDX);
boolean needRun = idxFile.exists();
log.debug("MakeIndex run required? " + needRun);
if (needRun) {
// may throw BuildExecutionException
runMakeIndex(idxFile);
}
return needRun;
}
/**
* Runs the MakeIndex command
* given by {@link Settings#getMakeIndexCommand()}.
*
* @param idxFile
* the idx-file MakeIndex is to be run on.
*/
// FIXME: strange: runMakeIndexByNeed based on tex-file
// and this one based on idx-file.
// no longer appropriate to create idx-file
// because makeIndex is rerun.
private void runMakeIndex(File idxFile) throws BuildExecutionException {
String command = this.settings.getMakeIndexCommand();
log.debug("Running " + command + " on " + idxFile.getName() + ". ");
String[] args = buildArguments(this.settings.getMakeIndexOptions(),
idxFile);
// may throw BuildExecutionException
this.executor.execute(idxFile.getParentFile(), //workingDir
this.settings.getTexPath(),
command,
args);
// detect errors and warnings makeindex wrote into xxx.ilg
File logFile = this.fileUtils.replaceSuffix(idxFile, SUFFIX_ILG);
logErrs (logFile, command, this.settings.getPatternErrMakeIndex());
logWarns(logFile, command, this.settings.getPatternWarnMakeIndex());
}
/**
* Runs the MakeGlossaries command
* given by {@link Settings#getMakeGlossariesCommand()}
* on the aux-file corresponding with <code>texFile</code>
* in the directory containing <code>texFile</code>
* provided that the existence of an glo-file indicates
* that a glossary shall be created.
* The MakeGlossaries command is just a wrapper
* arround the programs <code>makeindex</code> and <code>xindy</code>.
*
* @param texFile
* the latex-file MakeGlossaries is to be processed for.
* @return
* whether MakeGlossaries had been run.
* Equivalently,
* whether LaTeX has to be rerun because of MakeGlossaries.
*/
private boolean runMakeGlossaryByNeed(File texFile)
throws BuildExecutionException {
// file name without ending: parameter for makeglossaries
File xxxFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_VOID);
// raw glossaries file created by pdflatex
File gloFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_GLO);
// style file for glossaries created by pdflatex for makeindex
File istFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_IST);
// style file for glossaries created by pdflatex for xindy
File xdyFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_XDY);
// Note that LaTeX creates the ist-file if makeindex is specified
// and the xdy-file if xindy is specified as sorting application.
boolean needRun = gloFile.exists();
assert ( gloFile.exists() && ( istFile.exists() ^ xdyFile.exists()))
|| (!gloFile.exists() && (!istFile.exists() && !xdyFile.exists()));
log.debug("MakeGlossaries run required? " + needRun);
if (!needRun) {
return false;
}
String command = this.settings.getMakeGlossariesCommand();
log.debug("Running " + command + " on " + xxxFile.getName()+ ". ");
String[] args = buildArguments(this.settings.getMakeGlossariesOptions(),
xxxFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(), //workingDir
this.settings.getTexPath(),
command,
args);
// detect errors and warnings makeglossaries wrote into xxx.glg
File glgFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_GLG);
logErrs (glgFile, command, this.settings.getPatternErrMakeGlossaries());
logWarns(glgFile, command, this.settings.getPatternWarnMakeIndex()
+ "|" + this.settings.getPatternWarnXindy());
return true;
}
/**
* Runs the BibTeX command given by {@link Settings#getBibtexCommand()}
* on the aux-file corresponding with <code>texFile</code>
* in the directory containing <code>texFile</code>
* provided an according pattern in the aux-file indicates
* that a bibliography shall be created.
*
* @param texFile
* the latex-file BibTeX is to be processed for.
* @return
* whether BibTeX has been run.
* Equivalently, whether LaTeX has to be rerun because of BibTeX.
*/
private boolean runBibtexByNeed(File texFile)
throws BuildExecutionException {
File auxFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_AUX);
boolean needRun = this.fileUtils.matchInFile(auxFile,
PATTERN_NEED_BIBTEX_RUN);
log.debug("BibTeX run required? " + needRun);
if (!needRun) {
return false;
}
String command = this.settings.getBibtexCommand();
log.debug("Running " + command + " on " + auxFile.getName() + ". ");
String[] args = buildArguments(this.settings.getBibtexOptions(),
auxFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(), // workingDir
this.settings.getTexPath(),
command,
args);
File logFile = this.fileUtils.replaceSuffix(texFile, SUFFIX_BLG);
logErrs (logFile, command, this.settings.getPatternErrBibtex());
logWarns(logFile, command, this.settings.getPatternWarnBibtex());
return true;
}
/**
* Runs the LaTeX command given by {@link Settings#getLatexCommand()}
* on <code>texFile</code>
* in the directory containing <code>texFile</code>
* with arguments given by {@link #buildLatexArguments(File)}.
* <p>
* Logs a warning or an error if the latex run failed
* invoking {@link #logErrs(File, String)}
* but not if bad boxes occurred or if warnings occurred.
* This is done in {@link #processLatex2pdf(File)}
* after the last LaTeX run only.
*
* @param texFile
* the latex-file to be processed.
* @param logFile
* the log-file after processing <code>texFile</code>.
* @throws BuildExecutionException
* if running the latex command
* returned by {@link Settings#getLatexCommand()} failed.
*/
private void runLatex2pdf(File texFile, File logFile)
throws BuildExecutionException {
String command = this.settings.getLatex2pdfCommand();
log.debug("Running " + command + " on " + texFile.getName() + ". ");
String[] args = buildArguments(this.settings.getLatex2pdfOptions(),
texFile);
// may throw BuildExecutionException
this.executor.execute(texFile.getParentFile(), // workingDir
this.settings.getTexPath(),
command,
args);
// logging errors (warnings are done in processLatex2pdf)
logErrs(logFile, command);
}
}
|
maven-latex-plugin/src/main/java/org/m2latex/core/LatexPreProcessor.java
|
@new
extracting preprocessing
- copying source outer.
|
maven-latex-plugin/src/main/java/org/m2latex/core/LatexPreProcessor.java
|
@new extracting preprocessing - copying source outer.
|
|
Java
|
apache-2.0
|
error: pathspec 'core/optimization/src/test/java/it/unibz/inf/ontop/iq/NormalizationTest.java' did not match any file(s) known to git
|
267cdfaef1ee702cf0eae40ad8c334f020eb52bd
| 1
|
ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop
|
package it.unibz.inf.ontop.iq;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.iq.node.ConstructionNode;
import it.unibz.inf.ontop.iq.node.DistinctNode;
import it.unibz.inf.ontop.iq.node.ExtensionalDataNode;
import it.unibz.inf.ontop.model.atom.DistinctVariableOnlyDataAtom;
import it.unibz.inf.ontop.model.atom.RelationPredicate;
import it.unibz.inf.ontop.model.term.*;
import org.junit.Test;
import static it.unibz.inf.ontop.NoDependencyTestDBMetadata.*;
import static it.unibz.inf.ontop.OptimizationTestingTools.*;
import static it.unibz.inf.ontop.model.term.functionsymbol.ExpressionOperation.CONCAT;
import static junit.framework.TestCase.assertEquals;
public class NormalizationTest {
private static GroundFunctionalTerm GROUND_FUNCTIONAL_TERM =
(GroundFunctionalTerm) TERM_FACTORY.getImmutableFunctionalTerm(CONCAT,
TERM_FACTORY.getConstantLiteral("this-"),
TERM_FACTORY.getConstantLiteral("that"));
@Test
public void testDistinct1() {
ExtensionalDataNode extensionalDataNode = createExtensionalDataNode(TABLE1_AR2, A, B);
DistinctNode distinctNode = IQ_FACTORY.createDistinctNode();
UnaryIQTree iqTree = IQ_FACTORY.createUnaryIQTree(distinctNode, extensionalDataNode);
DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR2_PREDICATE, A, B);
IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, iqTree);
normalizeAndCompare(initialIQ, initialIQ);
}
@Test
public void testDistinctInjective1() {
testDistinctInjective(createInjectiveFunctionalTerm(A));
}
@Test
public void testDistinctInjective2() {
testDistinctInjective(ONE);
}
@Test
public void testDistinctInjective3() {
testDistinctInjective(GROUND_FUNCTIONAL_TERM);
}
private static void testDistinctInjective(ImmutableTerm injectiveTerm) {
ExtensionalDataNode extensionalDataNode = createExtensionalDataNode(TABLE1_AR2, A, B);
DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR1_PREDICATE, X);
ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(X),
SUBSTITUTION_FACTORY.getSubstitution(X, injectiveTerm));
DistinctNode distinctNode = IQ_FACTORY.createDistinctNode();
UnaryIQTree tree = IQ_FACTORY.createUnaryIQTree(distinctNode,
IQ_FACTORY.createUnaryIQTree(constructionNode, extensionalDataNode));
IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, tree);
UnaryIQTree expectedTree = IQ_FACTORY.createUnaryIQTree(constructionNode,
IQ_FACTORY.createUnaryIQTree(distinctNode, extensionalDataNode));
normalizeAndCompare(initialIQ, IQ_FACTORY.createIQ(projectionAtom, expectedTree));
}
@Test
public void testDistinct2() {
ExtensionalDataNode extensionalDataNode = createExtensionalDataNode(TABLE1_AR2, A, B);
DistinctVariableOnlyDataAtom projectionAtom = ATOM_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_AR1_PREDICATE, X);
ConstructionNode constructionNode = IQ_FACTORY.createConstructionNode(ImmutableSet.of(X),
SUBSTITUTION_FACTORY.getSubstitution(X, createNonInjectiveFunctionalTerm(A, B)));
DistinctNode distinctNode = IQ_FACTORY.createDistinctNode();
UnaryIQTree iqTree = IQ_FACTORY.createUnaryIQTree(distinctNode,
IQ_FACTORY.createUnaryIQTree(constructionNode, extensionalDataNode));
IQ initialIQ = IQ_FACTORY.createIQ(projectionAtom, iqTree);
normalizeAndCompare(initialIQ, initialIQ);
}
private static void normalizeAndCompare(IQ initialIQ, IQ expectedIQ) {
System.out.println("Initial IQ: " + initialIQ);
System.out.println("Expected IQ: " + expectedIQ);
IQ normalizedIQ = initialIQ.normalizeForOptimization();
System.out.println("Normalized IQ: " + normalizedIQ);
assertEquals(expectedIQ, normalizedIQ);
}
private static ExtensionalDataNode createExtensionalDataNode(RelationPredicate predicate,
VariableOrGroundTerm... terms) {
return IQ_FACTORY.createExtensionalDataNode(
ATOM_FACTORY.getDataAtom(predicate, terms));
}
private ImmutableFunctionalTerm createNonInjectiveFunctionalTerm(Variable stringV1, Variable stringV2) {
return TERM_FACTORY.getImmutableExpression(CONCAT, stringV1, stringV2);
}
private ImmutableFunctionalTerm createInjectiveFunctionalTerm(Variable stringVariable) {
return TERM_FACTORY.getImmutableExpression(CONCAT, TERM_FACTORY.getConstantLiteral(""),
stringVariable);
}
}
|
core/optimization/src/test/java/it/unibz/inf/ontop/iq/NormalizationTest.java
|
Few tests added DISTINCT normalization.
|
core/optimization/src/test/java/it/unibz/inf/ontop/iq/NormalizationTest.java
|
Few tests added DISTINCT normalization.
|
|
Java
|
apache-2.0
|
error: pathspec 'src/test/java/com/github/pedrovgs/problem41/GoThroughMatrixInSpiralTest.java' did not match any file(s) known to git
|
cc53e46ef235e3017d5af179ca018f7d5b94db1f
| 1
|
zhdh2008/Algorithms,VeskoI/Algorithms,jibaro/Algorithms,Arkar-Aung/Algorithms,007slm/Algorithms,mrgenco/Algorithms-1,sridhar-newsdistill/Algorithms,ArlenLiu/Algorithms,chengjinqian/Algorithms,inexistence/Algorithms,Ariloum/Algorithms,JeffreyWei/Algorithms,zmywly8866/Algorithms,ajinkyakolhe112/Algorithms,pedrovgs/Algorithms,AppScientist/Algorithms
|
/*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pedrovgs.problem41;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* @author Pedro Vicente Gómez Sánchez.
*/
public class GoThroughMatrixInSpiralTest {
private GoThroughMatrixInSpiral goThroughMatrixInSpiral;
@Before public void setUp() {
goThroughMatrixInSpiral = new GoThroughMatrixInSpiral();
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNullInstancesAsInput() {
goThroughMatrixInSpiral.go(null);
}
@Test public void shouldReturnEmptyArrayIfMatrixIsEmpty() {
int[][] matrix = { };
int[] result = goThroughMatrixInSpiral.go(matrix);
assertEquals(0, result.length);
}
@Test public void shouldGoThroughTheMatrixInSpiral() {
int[][] matrix = {
{ 1, 2, 3, 4, 5, 6 }, { 20, 21, 22, 23, 24, 7 }, { 19, 32, 33, 34, 25, 8 },
{ 18, 31, 36, 35, 26, 9 }, { 17, 30, 29, 28, 27, 10 }, { 16, 15, 14, 13, 12, 11 }
};
int[] result = goThroughMatrixInSpiral.go(matrix);
int[] expected = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36
};
assertArrayEquals(expected, result);
}
}
|
src/test/java/com/github/pedrovgs/problem41/GoThroughMatrixInSpiralTest.java
|
Add some tests to problem 41
|
src/test/java/com/github/pedrovgs/problem41/GoThroughMatrixInSpiralTest.java
|
Add some tests to problem 41
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/uk/ac/ebi/subs/api/resourceAssembly/RootEndpointLinkProcessor.java' did not match any file(s) known to git
|
7e1408058f7f18d6a70927ef893f586aa5a57ff8
| 1
|
EMBL-EBI-SUBS/subs-api,EMBL-EBI-SUBS/subs-api
|
package uk.ac.ebi.subs.api.resourceAssembly;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.rest.webmvc.RepositoryLinksResource;
import org.springframework.hateoas.ResourceProcessor;
import org.springframework.stereotype.Component;
import uk.ac.ebi.subs.api.StatusDescriptionController;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
@Component
public class RootEndpointLinkProcessor implements ResourceProcessor<RepositoryLinksResource> {
private Pageable defaultPageRequest() {
return new PageRequest(0, 1);
}
public RootEndpointLinkProcessor() {
}
@Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
Pageable pageable = defaultPageRequest();
resource.add(
linkTo(
methodOn(StatusDescriptionController.class)
.allProcessingStatus(pageable))
.withRel("processingStatusDescriptions")
);
resource.add(
linkTo(
methodOn(StatusDescriptionController.class)
.allReleaseStatus(pageable))
.withRel("releaseStatusDescriptions")
);
resource.add(
linkTo(
methodOn(StatusDescriptionController.class)
.allSubmissionStatus(pageable))
.withRel("submissionStatusDescriptions")
);
return resource;
}
}
|
src/main/java/uk/ac/ebi/subs/api/resourceAssembly/RootEndpointLinkProcessor.java
|
customise root resource with links to status descriptions
|
src/main/java/uk/ac/ebi/subs/api/resourceAssembly/RootEndpointLinkProcessor.java
|
customise root resource with links to status descriptions
|
|
Java
|
apache-2.0
|
error: pathspec 'Bletia/src/main/java/info/izumin/android/bletia/BluetoothGattCallbackHandler.java' did not match any file(s) known to git
|
be64b39f4db42a0f3be91b13b29595a7c75cf4a2
| 1
|
izumin5210/Bletia
|
package info.izumin.android.bletia;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import info.izumin.android.bletia.wrapper.BluetoothGattCallbackWrapper;
import info.izumin.android.bletia.wrapper.BluetoothGattWrapper;
/**
* Created by izumin on 9/7/15.
*/
public class BluetoothGattCallbackHandler extends BluetoothGattCallbackWrapper {
public BluetoothGattCallbackHandler() {
}
@Override
public void onConnectionStateChange(BluetoothGattWrapper gatt, int status, int newState) {
// TODO: Not yet implemented.
}
@Override
public void onServicesDiscovered(BluetoothGattWrapper gatt, int status) {
// TODO: Not yet implemented.
}
@Override
public void onCharacteristicRead(BluetoothGattWrapper gatt, BluetoothGattCharacteristic characteristic, int status) {
// TODO: Not yet implemented.
}
@Override
public void onCharacteristicWrite(BluetoothGattWrapper gatt, BluetoothGattCharacteristic characteristic, int status) {
// TODO: Not yet implemented.
}
@Override
public void onCharacteristicChanged(BluetoothGattWrapper gatt, BluetoothGattCharacteristic characteristic) {
// TODO: Not yet implemented.
}
@Override
public void onDescriptorRead(BluetoothGattWrapper gatt, BluetoothGattDescriptor descriptor, int status) {
// TODO: Not yet implemented.
}
@Override
public void onDescriptorWrite(BluetoothGattWrapper gatt, BluetoothGattDescriptor descriptor, int status) {
// TODO: Not yet implemented.
}
@Override
public void onReliableWriteCompleted(BluetoothGattWrapper gatt, int status) {
// TODO: Not yet implemented.
}
@Override
public void onReadRemoteRssi(BluetoothGattWrapper gatt, int rssi, int status) {
// TODO: Not yet implemented.
}
@Override
public void onMtuChanged(BluetoothGattWrapper gatt, int mtu, int status) {
// TODO: Not yet implemented.
}
}
|
Bletia/src/main/java/info/izumin/android/bletia/BluetoothGattCallbackHandler.java
|
Add BluetoothGattCallbackHandler class
|
Bletia/src/main/java/info/izumin/android/bletia/BluetoothGattCallbackHandler.java
|
Add BluetoothGattCallbackHandler class
|
|
Java
|
apache-2.0
|
error: pathspec 'common/src/test/java/com/alibaba/fescar/common/thread/NamedThreadFactoryTest.java' did not match any file(s) known to git
|
d64f5bf426fcadd7d2b8dbf695adb320a67c5379
| 1
|
seata/seata,seata/seata,seata/seata,seata/seata,seata/seata
|
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fescar.common.thread;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
/**
* @author Otis.z
* @date 2019/2/26
*/
public class NamedThreadFactoryTest {
@Test
public void testNewThread() {
NamedThreadFactory namedThreadFactory = new NamedThreadFactory("testNameThread", 5);
Thread testNameThread = namedThreadFactory
.newThread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
assertThat(testNameThread.getName()).startsWith("testNameThread");
assertThat(testNameThread.isDaemon()).isTrue();
}
}
|
common/src/test/java/com/alibaba/fescar/common/thread/NamedThreadFactoryTest.java
|
[Test-1] add test for NamedThreadFactory (#524)
|
common/src/test/java/com/alibaba/fescar/common/thread/NamedThreadFactoryTest.java
|
[Test-1] add test for NamedThreadFactory (#524)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.