answer
stringlengths 17
10.2M
|
|---|
package view;
import java.util.ArrayList;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
public class ColorPane {
private ObservableList<String> myColorList;
private ListView<String> myColorListView;
public ColorPane(Group root, ArrayList<String> colorList) {
initializeSuggestedView(root, colorList);
}
private void initializeSuggestedView(Group root, ArrayList<String> colorList) {
myColorList = FXCollections.observableArrayList(colorList);
VBox colorBox = new VBox();
myColorListView.setItems(myColorList);
colorBox.getChildren().add(myColorListView);
root.getChildren().add(colorBox);
}
public void changeList(ArrayList<String> colorList) {
myColorList = FXCollections.observableArrayList(colorList);
myColorListView.setItems(myColorList);
}
}
|
package org.jnosql.diana.couchbase.document;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.Select;
import com.couchbase.client.java.query.Statement;
import com.couchbase.client.java.query.dsl.Expression;
import com.couchbase.client.java.query.dsl.path.GroupByPath;
import org.jnosql.diana.api.TypeReference;
import org.jnosql.diana.api.document.Document;
import org.jnosql.diana.api.document.DocumentDeleteQuery;
import org.jnosql.diana.api.document.DocumentEntity;
import org.jnosql.diana.api.document.DocumentQuery;
import org.jnosql.diana.api.document.Documents;
import org.jnosql.diana.api.document.query.DocumentQueryBuilder;
import org.jnosql.diana.api.key.BucketManager;
import org.jnosql.diana.api.key.BucketManagerFactory;
import org.jnosql.diana.couchbase.CouchbaseUtil;
import org.jnosql.diana.couchbase.key.CouchbaseKeyValueConfiguration;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.couchbase.client.java.query.dsl.Expression.x;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CouchbaseDocumentCollectionManagerTest {
public static final String COLLECTION_NAME = "person";
private CouchbaseDocumentCollectionManager entityManager;
{
CouchbaseDocumentConfiguration configuration = new CouchbaseDocumentConfiguration();
CouhbaseDocumentCollectionManagerFactory managerFactory = configuration.get();
entityManager = managerFactory.get(CouchbaseUtil.BUCKET_NAME);
}
@AfterAll
public static void afterClass() {
CouchbaseKeyValueConfiguration configuration = new CouchbaseKeyValueConfiguration();
BucketManagerFactory keyValueEntityManagerFactory = configuration.get();
BucketManager keyValueEntityManager = keyValueEntityManagerFactory.getBucketManager(CouchbaseUtil.BUCKET_NAME);
keyValueEntityManager.remove("person:id");
}
@Test
public void shouldInsert() {
DocumentEntity entity = getEntity();
DocumentEntity documentEntity = entityManager.insert(entity);
assertEquals(entity, documentEntity);
}
@Test
public void shouldInsertWithKey() {
DocumentEntity entity = getEntity();
entity.add("_key", "anyvalue");
DocumentEntity documentEntity = entityManager.insert(entity);
assertEquals(entity, documentEntity);
}
@Test
public void shouldUpdate() {
DocumentEntity entity = getEntity();
DocumentEntity documentEntity = entityManager.insert(entity);
Document newField = Documents.of("newField", "10");
entity.add(newField);
DocumentEntity updated = entityManager.update(entity);
assertEquals(newField, updated.find("newField").get());
}
@Test
public void shouldRemoveEntityByName() {
DocumentEntity documentEntity = entityManager.insert(getEntity());
Document name = documentEntity.find("name").get();
DocumentQuery query = select().from(COLLECTION_NAME).where(name.getName()).eq(name.get()).build();
DocumentDeleteQuery deleteQuery = DocumentQueryBuilder.delete().from(COLLECTION_NAME)
.where(name.getName()).eq(name.get()).build();
entityManager.delete(deleteQuery);
assertTrue(entityManager.select(query).isEmpty());
}
@Test
public void shouldSaveSubDocument() throws InterruptedException {
DocumentEntity entity = getEntity();
entity.add(Document.of("phones", Document.of("mobile", "1231231")));
DocumentEntity entitySaved = entityManager.insert(entity);
Thread.sleep(5_00L);
Document id = entitySaved.find("_id").get();
DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build();
DocumentEntity entityFound = entityManager.select(query).get(0);
Document subDocument = entityFound.find("phones").get();
List<Document> documents = subDocument.get(new TypeReference<List<Document>>() {
});
assertThat(documents, contains(Document.of("mobile", "1231231")));
}
@Test
public void shouldSaveSubDocument2() throws InterruptedException {
DocumentEntity entity = getEntity();
entity.add(Document.of("phones", asList(Document.of("mobile", "1231231"), Document.of("mobile2", "1231231"))));
DocumentEntity entitySaved = entityManager.insert(entity);
Thread.sleep(1_00L);
Document id = entitySaved.find("_id").get();
DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build();
DocumentEntity entityFound = entityManager.select(query).get(0);
Document subDocument = entityFound.find("phones").get();
List<Document> documents = subDocument.get(new TypeReference<List<Document>>() {
});
assertThat(documents, contains(Document.of("mobile", "1231231"), Document.of("mobile2", "1231231")));
}
@Test
public void shouldSaveSetDocument() throws InterruptedException {
Set<String> set = new HashSet<>();
set.add("Acarajé");
set.add("Munguzá");
DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME);
entity.add(Document.of("_id", "id"));
entity.add(Document.of("foods", set));
entityManager.insert(entity);
Document id = entity.find("_id").get();
Thread.sleep(1_000L);
DocumentQuery query = select().from(COLLECTION_NAME).where(id.getName()).eq(id.get()).build();
DocumentEntity entityFound = entityManager.singleResult(query).get();
Optional<Document> foods = entityFound.find("foods");
Set<String> setFoods = foods.get().get(new TypeReference<Set<String>>() {
});
assertEquals(set, setFoods);
}
@Test
public void shouldConvertFromListSubdocumentList() {
DocumentEntity entity = createSubdocumentList();
entityManager.insert(entity);
}
@Test
public void shouldRetrieveListSubdocumentList() {
DocumentEntity entity = entityManager.insert(createSubdocumentList());
Document key = entity.find("_id").get();
DocumentQuery query = select().from("AppointmentBook").where(key.getName()).eq(key.get()).build();
DocumentEntity documentEntity = entityManager.singleResult(query).get();
assertNotNull(documentEntity);
List<List<Document>> contacts = (List<List<Document>>) documentEntity.find("contacts").get().get();
assertEquals(3, contacts.size());
assertTrue(contacts.stream().allMatch(d -> d.size() == 3));
}
private DocumentEntity createSubdocumentList() {
DocumentEntity entity = DocumentEntity.of("AppointmentBook");
entity.add(Document.of("_id", "ids"));
List<List<Document>> documents = new ArrayList<>();
documents.add(asList(Document.of("name", "Ada"), Document.of("type", ContactType.EMAIL),
Document.of("information", "ada@lovelace.com")));
documents.add(asList(Document.of("name", "Ada"), Document.of("type", ContactType.MOBILE),
Document.of("information", "11 1231231 123")));
documents.add(asList(Document.of("name", "Ada"), Document.of("type", ContactType.PHONE),
Document.of("information", "phone")));
entity.add(Document.of("contacts", documents));
return entity;
}
@Test
public void shouldRunN1Ql() {
DocumentEntity entity = getEntity();
entityManager.insert(entity);
List<DocumentEntity> entities = entityManager.n1qlQuery("select * from jnosql");
assertFalse(entities.isEmpty());
}
@Test
public void shouldRunN1QlParameters() {
DocumentEntity entity = getEntity();
entityManager.insert(entity);
JsonObject params = JsonObject.create().put("name", "Poliana");
List<DocumentEntity> entities = entityManager.n1qlQuery("select * from jnosql where name = $name", params);
assertFalse(entities.isEmpty());
assertEquals(1, entities.size());
}
@Test
public void shouldRunN1QlStatement() {
DocumentEntity entity = getEntity();
entityManager.insert(entity);
Statement statement = Select.select("*").from("jnosql").where(x("name").eq("\"Poliana\""));
List<DocumentEntity> entities = entityManager.n1qlQuery(statement);
assertFalse(entities.isEmpty());
assertEquals(1, entities.size());
}
@Test
public void shouldRunN1QlStatementParams() {
DocumentEntity entity = getEntity();
entityManager.insert(entity);
Statement statement = Select.select("*").from("jnosql").where(x("name").eq("$name"));
JsonObject params = JsonObject.create().put("name", "Poliana");
List<DocumentEntity> entities = entityManager.n1qlQuery(statement, params);
assertFalse(entities.isEmpty());
assertEquals(1, entities.size());
}
private DocumentEntity getEntity() {
DocumentEntity entity = DocumentEntity.of(COLLECTION_NAME);
Map<String, Object> map = new HashMap<>();
map.put("name", "Poliana");
map.put("city", "Salvador");
map.put("_id", "id");
List<Document> documents = Documents.of(map);
documents.forEach(entity::add);
return entity;
}
}
|
package view;
import java.util.*;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.CacheHint;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import model.BoxReference;
import model.Proof;
import model.ProofListener;
public class ProofView extends Symbolic implements ProofListener, View {
/*
* These are magic constants that decide the lineNo padding.
* Margin can't be changed as a property, so the solution is to take into account how much the border
* and the padding increases the distance between rows and add the padding to the line numbers accordingly.
*/
static final int carryAddOpen = 3;
static final int carryAddClose = 5;
// TextFields of the premises and conclusion for quick access
private TextField premises;
private TextField conclusion;
private Stack<VBox> curBoxDepth = new Stack<>();
// This is a list of RowPanes, which are the "lines" of the proof.
private List<RowPane> rList = new ArrayList<>();
private int counter = 1;
//private int carry = 0;
private VBox lineNo;
private VBox rows;
//The tab object of this view
private ViewTab tab;
//The proof displayed in this view
private Proof proof;
//The patth where this proof was loaded/should be saved
private String path;
//Name of the proof/file of this view
private String name;
private TextField lastTf;
//hashmap for all the rules and number of arguments for all rules
private HashMap<String, Integer> ruleMap = new HashMap<String, Integer>();
/**
* This ia listener that is applied to the last textField. It creates a new row, each time the value of the textField is changed.
*/
private ChangeListener<? extends String> lastTfListener = (ov, oldValue, newValue) -> {
newRow();
};
private AnchorPane createProofPane() {
lineNo = new VBox();
rows = new VBox();
lineNo.setFillWidth(true);
rows.setFillWidth(true);
HBox hb = new HBox();
hb.setHgrow(rows, Priority.ALWAYS);
hb.getChildren().addAll(lineNo, rows);
hb.setPadding(new Insets(5, 5, 5, 5));
ScrollPane sp = new ScrollPane(hb);
sp.getStyleClass().add("fit");
hb.heightProperty().addListener((ov, oldValue, newValue) -> {
if (newValue.doubleValue() > oldValue.doubleValue()) { // Change this to only trigger on new row!!
sp.setVvalue(1.0); // Otherwise it will scroll down when you insert a row in the middle
}
});
AnchorPane proofPane = new AnchorPane(sp);
proofPane.setTopAnchor(sp, 0.0);
proofPane.setRightAnchor(sp, 0.0);
proofPane.setLeftAnchor(sp, 0.0);
proofPane.setBottomAnchor(sp, 0.0);
return proofPane;
}
public ProofView(TabPane tabPane, Proof proof, HBox premisesAndConclusion) {
this.proof = proof;
this.proof.registerProofListener(this);
this.premises = (TextField) premisesAndConclusion.getChildren().get(0);
this.premises.setId("expression");
this.conclusion = (TextField) premisesAndConclusion.getChildren().get(2);
this.conclusion.setId("expression");
this.conclusion.textProperty().addListener((ov, oldValue, newValue) -> {
proof.updateConclusion(newValue);
});
proof.updateConclusion(this.conclusion.getText());
this.premises.focusedProperty().addListener((observable, oldValue, newValue) -> {
lastFocusedTf = this.premises;
caretPosition = this.premises.getCaretPosition();
});
this.conclusion.focusedProperty().addListener((observable, oldValue, newValue) -> {
lastFocusedTf = this.conclusion;
caretPosition = this.conclusion.getCaretPosition();
});
AnchorPane cp=createProofPane();
SplitPane sp = new SplitPane(premisesAndConclusion, cp);
sp.setOrientation(Orientation.VERTICAL);
sp.setDividerPosition(0, 0.1);
AnchorPane anchorPane = new AnchorPane(sp);
anchorPane.setTopAnchor(sp, 0.0);
anchorPane.setRightAnchor(sp, 0.0);
anchorPane.setLeftAnchor(sp, 0.0);
anchorPane.setBottomAnchor(sp, 0.0);
this.tab = new ViewTab("Proof", this);
this.tab.setContent(anchorPane);
tabPane.getTabs().add(this.tab);
tabPane.getSelectionModel().select(this.tab); // Byt till den nya tabben
newRow();
//Code for placing the splitpane containing an AssumptionPane containing buttons for open/close box
AssumptionPane assumptionPane=new AssumptionPane();
assumptionPane.setMinHeight(60);
anchorPane.setBottomAnchor(assumptionPane,0.00);
SplitPane splitPaneAssumptions = new SplitPane(assumptionPane);
sp.getItems().add(splitPaneAssumptions);
anchorPane.setBottomAnchor(splitPaneAssumptions,0.0);
splitPaneAssumptions.setMinHeight(57);
splitPaneAssumptions.setMaxHeight(57);
splitPaneAssumptions.setFocusTraversable(false);
splitPaneAssumptions.setOrientation(Orientation.VERTICAL);
//controller for buttons in AssumptionPane
anchorPane.getChildren().add(splitPaneAssumptions);
assumptionPane.getOpenButton().setOnAction(event -> {
proof.openBox();
});
assumptionPane.getCloseButton().setOnAction(event -> {
proof.closeBox();
});;
initializeRuleMap();
}
/**
* a method to initialize the ruleMap
* TODO: keep track of when it is a interval
*/
private void initializeRuleMap() {
ruleMap.put("∧I", 2);
ruleMap.put("∧E1", 1);
ruleMap.put("∧E2", 1);
ruleMap.put("∨I1", 1);
ruleMap.put("∨I2", 1);
ruleMap.put("∨E", 3);
ruleMap.put("→I", 1);
ruleMap.put("→E", 2);
ruleMap.put("⊥E", 1);
ruleMap.put("¬I", 1);
ruleMap.put("¬E", 1);
ruleMap.put("¬¬E", 1);
ruleMap.put("Premise", 0);
ruleMap.put("∀I", 1);
ruleMap.put("∀E", 1);
ruleMap.put("∃I", 1);
ruleMap.put("∃E", 1);
ruleMap.put("=E", 2);
ruleMap.put("=I", 0);
}
public ProofView(TabPane tabPane, Proof proof) {
this(tabPane, proof, new premisesAndConclusion());
}
public ProofView(TabPane tabPane, Proof proof, String sPremises, String sConclusion) {
this(tabPane, proof, new premisesAndConclusion(sPremises, sConclusion));
}
/* Controller begin */
public void openBox() {
proof.openBox();
}
public void closeBox() {
proof.closeBox();
}
public void newRow() {
proof.addRow();
}
public void rowDeleteRow(){
//needs rowNr
}
public void insertNewRow(int rowNo, BoxReference br){
proof.insertNewRow(rowNo, br);
}
/* End of controller */
private void checkAndAdd(Region item) {
if (curBoxDepth.isEmpty()) {
rows.getChildren().add(item);
} else {
VBox temp = curBoxDepth.peek();
temp.getChildren().add(item);
}
}
/**
* Creates a new row with a textfield for the expression and a textfield
* for the rules and adds listeners to both of them.
* @return bp, the BorderPane containing two textfields.
*/
private RowPane createRow(boolean isFirstRowInBox, int nrOfClosingBoxes) {
//borderpane which contains the textfield for the expression and the rule
RowPane bp = new RowPane(isFirstRowInBox,nrOfClosingBoxes);
//setting up a context menu for right-clicking a textfield
ContextMenu contextMenu = new ContextMenu();
MenuItem delete = new MenuItem("Delete");
MenuItem insertAbove = new MenuItem("Insert Above");
MenuItem insertBelow = new MenuItem("Insert Below");
contextMenu.getItems().add(delete);
contextMenu.getItems().add(insertAbove);
contextMenu.getItems().add(insertBelow);
bp.getRule().setContextMenu(contextMenu);
bp.getRulePrompt1().setContextMenu(contextMenu);
bp.getRulePrompt2().setContextMenu(contextMenu);
bp.getRulePrompt3().setContextMenu(contextMenu);
((TextField)bp.getCenter()).setContextMenu(contextMenu);
bp.getRule().setContextMenu(contextMenu);
delete.setOnAction(event -> {
int rowOfPressedButton=rList.indexOf(bp) + 1;
proof.deleteRow(rowOfPressedButton);
});;
insertAbove.setOnAction(event -> {
int rowOfPressedButton=rList.indexOf(bp) + 1;
proof.insertNewRow(rowOfPressedButton,BoxReference.BEFORE);
});;
insertBelow.setOnAction(event -> {
int rowOfPressedButton=rList.indexOf(bp) + 1;
proof.insertNewRow(rowOfPressedButton,BoxReference.AFTER);
});;
//Action Events for delete and insert buttons in RowButtonsPane
bp.getEditRowPane().getDeleteButton().setOnAction(event -> {
int rowOfPressedButton=rList.indexOf(bp) + 1;;
proof.deleteRow(rowOfPressedButton);
});
bp.getEditRowPane().getInsertBeforeButton().setOnAction(event -> {
int rowOfPressedButton=rList.indexOf(bp) + 1;;
proof.insertNewRow(rowOfPressedButton,BoxReference.BEFORE);
});
bp.getEditRowPane().getInsertAfterButton().setOnAction(event -> {
int rowOfPressedButton=rList.indexOf(bp) + 1;;
proof.insertNewRow(rowOfPressedButton,BoxReference.AFTER);
});
//adding listeners to the expression- and rule textfield
TextField tfExpression = bp.getExpression();
tfExpression.focusedProperty().addListener((observable, oldValue, newValue) -> {
lastFocusedTf = tfExpression;
caretPosition = tfExpression.getCaretPosition();
});
TextField tfRule = bp.getRule();
tfRule.focusedProperty().addListener((observable, oldValue, newValue) -> {
lastFocusedTf = tfRule;
caretPosition = tfRule.getCaretPosition();
});
return bp;
}
//should only be called AFTER a new row has been added to rList since it uses rList.size()
Label createLabel() {
Label lbl = new Label(""+rList.size());
lbl.getStyleClass().add("lineNo");
lbl.setPadding(new Insets(8,2,2,2));
//lbl.setCache(true);
//lbl.setCacheShape(true);
lbl.setCacheHint(CacheHint.SPEED);
return lbl;
}
//Adds a new row at the end of the proof
public void rowAdded(){
RowPane rp;
if(curBoxDepth.isEmpty()){
rp = createRow(false, 0);
rList.add(rp);
rows.getChildren().add(rp);
}
else{
VBox box = curBoxDepth.peek();
List<Node> children = box.getChildren();
boolean isFirstRowInBox = (children.isEmpty()) ? true : false;
rp = createRow(isFirstRowInBox, 0);
rList.add(rp);
children.add(rp);
}
lineNo.getChildren().add(createLabel());
updateLabelPaddings(rList.size());
addListeners(rp);
newRowListener(rp.getExpression());
}
public void newRowListener(TextField tf) {
if (lastTf != null) {
lastTf.textProperty().removeListener((ChangeListener<? super String>) lastTfListener);
}
lastTf = tf;
lastTf.textProperty().addListener((ChangeListener<? super String>) lastTfListener);
}
//rowNo is which row the reference row is at, BoxReference tells you if you want to add the new row before or after
public void rowInserted(int rowNo, BoxReference br) {
RowPane referenceRow;//row we'll use to get a refence to the box where we add the new row
boolean isFirstRowInBox;
int nrOfClosingBoxes; //the nr of boxes that closes at line rowNo
int indexToInsertInParent;
VBox parentBox; // which vbox to display the new row in
int rListInsertionIndex = (br == BoxReference.BEFORE) ? rowNo-1 : rowNo;
if(br == BoxReference.BEFORE){
referenceRow = rList.get(rowNo-1);
isFirstRowInBox = referenceRow.getIsFirstRowInBox();
nrOfClosingBoxes = 0;
referenceRow.setIsFirstRowInBox(false);
parentBox = (VBox)referenceRow.getParent();
indexToInsertInParent = parentBox.getChildren().indexOf(referenceRow);
}
else{ //br == BoxReference.AFTER
referenceRow = rList.get(rowNo-1);
nrOfClosingBoxes = referenceRow.getNrOfClosingBoxes();
isFirstRowInBox = false;
referenceRow.setNrOfClosingBoxes(0);
parentBox = (VBox)referenceRow.getParent();
indexToInsertInParent = parentBox.getChildren().indexOf(referenceRow) + 1;
}
RowPane rp = createRow(isFirstRowInBox, nrOfClosingBoxes);
((TextField)rp.getExpression()).setText("*");
parentBox.getChildren().add(indexToInsertInParent,rp);
rList.add(rListInsertionIndex, rp);
lineNo.getChildren().add(createLabel());
updateLabelPaddings(rowNo);
addListeners(rp);
/*
if (lastTf != null) {
lastTf.textProperty().removeListener((ChangeListener<? super String>) lastTfListener);
}
TextField tempTf = (TextField) bp.getCenter();
//...tempTf.setText(formula);
lastTf = tempTf;
lastTf.textProperty().addListener((ChangeListener<? super String>) lastTfListener);
*/
}
// public void focus() { // Save the last focused textfield here for quick resuming?
// Platform.runLater(() -> lastTf.requestFocus());
public void boxOpened(){
VBox vb = new VBox();
vb.getStyleClass().add("openBox");
checkAndAdd(vb);
curBoxDepth.push(vb);
newRow();
}
public void boxClosed(){
if (!curBoxDepth.isEmpty()) {
VBox vb = curBoxDepth.pop();
//Update last row and its padding
rList.get(rList.size()-1).incrementNrOfClosingBoxes();
updateLabelPaddings(rList.size()-1);
vb.getStyleClass().clear();
vb.getStyleClass().add("closedBox");
}
}
private void applyStyleIf(TextField expression, boolean bool, String style) {
expression.getStyleClass().removeIf((s) -> s.equals(style));
if (bool) {
expression.getStyleClass().add(style);
}
}
public void rowUpdated(boolean wellFormed, int lineNo) {
TextField expression = (TextField) rList.get(lineNo-1).getExpression();
if (expression.getText().equals(""))
wellFormed = true;
applyStyleIf(expression, !wellFormed, "bad");
}
public void conclusionReached(boolean correct, int lineNo){
TextField expression = (TextField) rList.get(lineNo-1).getExpression();
applyStyleIf(expression, correct, "conclusionReached");
}
//update view to reflect that row with nr rowNr has been deleted
public void rowDeleted(int rowNr){
RowPane rp = rList.get(rowNr-1);
if (rowNr-1 == rList.size()-1 && (rowNr-2 >= 0)) { // Just check if this is the last row
newRowListener(rList.get(rowNr-2).getExpression());
}
VBox box = (VBox)rp.getParent();
List<Node> parentComponentList = box.getChildren();
if(parentComponentList.remove(rp) == false){
System.out.println("ProofView.rowDeleted: something went wrong!");
return;
}
rList.remove(rp);
boolean wasOnlyRowInBox = parentComponentList.isEmpty();
boolean updatePreviousRowLabel = false;
//deleted row was last row in this box, remove the box
if(wasOnlyRowInBox){
removeRecursivelyIfEmpty(box);
}
else{
if(rp.getIsFirstRowInBox()){ // next row is now first in this box
RowPane nextRow = rList.get(rowNr-1);
nextRow.setIsFirstRowInBox(rp.getIsFirstRowInBox());
}
if(rp.getNrOfClosingBoxes() > 0){ // previous row now closes the boxes
rList.get(rowNr-2).setNrOfClosingBoxes(rp.getNrOfClosingBoxes());
updatePreviousRowLabel = true;
}
}
//remove a Label and update paddings in relevant labels
List<Node> labelList = lineNo.getChildren();
labelList.remove(labelList.size()-1);
updateLabelPaddings( updatePreviousRowLabel ? rowNr-1 : rowNr );
}
public ViewTab getTab(){ return tab;}
public Proof getProof(){ return proof;}
public String getPath(){ return path;}
public void setPath(String path){ this.path = path; }
public String getName(){ return name;}
public void setName(String name){ this.name = name; }
//updates the padding for the labels starting from lineNr all the way down
//TODO: get rid of magic numbers
private void updateLabelPaddings(int lineNr){
List<Node> labelList = this.lineNo.getChildren();
assert(rList.size() == labelList.size());
//update the padding for each label by checking the corresponding rowPane
for(int i = lineNr-1; i < labelList.size() ; i++){
RowPane rp = rList.get(i);
int topPadding = rp.getIsFirstRowInBox() ? 11 : 8;
int bottomPadding = 2 + 5 * rp.getNrOfClosingBoxes();
Label label = (Label) labelList.get(i);
label.setPadding(new Insets(topPadding,2,bottomPadding,2));
}
}
//add listeners for the formula and rule textfields in the RowPane at the given rowNr
private void addListeners(RowPane rp){
// Updates the Proof object if the textField is updated
TextField formulaField = (TextField) rp.getExpression();
TextField ruleField = (TextField) rp.getRule();
formulaField.textProperty().addListener((ov, oldValue, newValue) -> {
int rpIndex = rList.indexOf(rp);
proof.updateFormulaRow(newValue, rpIndex+1);
});
// Updates the Proof object if the textField is updated
ruleField.textProperty().addListener((ov, oldValue, newValue) -> {
int rpIndex = rList.indexOf(rp);
proof.updateRuleRow(newValue, rpIndex+1);
rp.setPrompts(ruleMap.getOrDefault(newValue,-1));
});
}
private void removeRecursivelyIfEmpty(VBox box){
Node parentNode = box.getParent();
assert( box.getChildren().isEmpty() );
if(parentNode instanceof VBox ){
VBox parentBox = (VBox) parentNode;
parentBox.getChildren().remove(box);
if(box.getStyleClass().toString().equals("openBox")){
VBox box2 = curBoxDepth.pop();
assert(box == box2);
}
if( parentBox.getChildren().isEmpty() ){
removeRecursivelyIfEmpty(parentBox);
}
}
}
/**
* Adds the rule symbol that has been pressed to the text field for the rule.
* @param event
*/
public void addRule(javafx.event.ActionEvent event){
if(lastFocusedTf != null && lastFocusedTf.getId() == "rightTextfield"){
int tmpCaretPosition = caretPosition;
String[] parts = event.toString().split("'");
lastFocusedTf.setText(parts[1]);
lastFocusedTf.requestFocus();
lastFocusedTf.positionCaret(tmpCaretPosition+1);
}
}
}
|
package view;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import control.ControladorGeral;
import control.ControladorLogin;
public class TelaLogin extends JDialog {
private JFrame parent;
private final JPanel contentPanel = new JPanel();
private JTextField tFUsuario;
private JPasswordField pFSenha;
/**
* Create the dialog.
*/
public TelaLogin(JFrame parent) {
this.parent = parent;
initialize();
}
private void initialize() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setVisible(true);
setResizable(false);
setTitle("Pode Ser? - Login");
setBounds(100, 100, 265, 150);
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JLabel lblUsuario = new JLabel("Usu\u00E1rio");
lblUsuario.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblSenha = new JLabel("Senha");
lblSenha.setFont(new Font("Tahoma", Font.PLAIN, 13));
tFUsuario = new JTextField();
tFUsuario.setColumns(15);
pFSenha = new JPasswordField();
pFSenha.setColumns(15);
GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
gl_contentPanel.setHorizontalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addComponent(lblUsuario)
.addComponent(lblSenha))
.addGap(18)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addComponent(tFUsuario, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(pFSenha, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(11, Short.MAX_VALUE))
);
gl_contentPanel.setVerticalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblUsuario)
.addComponent(tFUsuario, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblSenha)
.addComponent(pFSenha, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(16, Short.MAX_VALUE))
);
contentPanel.setLayout(gl_contentPanel);
JPanel panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(contentPanel, GroupLayout.PREFERRED_SIZE, 259, Short.MAX_VALUE)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(contentPanel, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 48, GroupLayout.PREFERRED_SIZE))
);
JButton btnEntrar = new JButton("Entrar");
btnEntrar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (ControladorLogin.getInstance().logar(tFUsuario.getText(), pFSenha.getPassword().toString())) {
setVisible(false);
parent.setVisible(true);
} else {
JOptionPane.showMessageDialog(getDialog(), "Usuário e/ou senha não encontrados!", "Erro", JOptionPane.ERROR_MESSAGE);
}
}
});
panel.add(btnEntrar);
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ControladorGeral.getInstance().serializarBancoDeDados();
System.exit(0);
}
});
panel.add(btnCancelar);
getContentPane().setLayout(groupLayout);
}
public JDialog getDialog() {
return this;
}
}
|
package org.deeplearning4j.datasets.iterator.parallel;
import lombok.extern.slf4j.Slf4j;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.DataSetPreProcessor;
import org.nd4j.linalg.dataset.api.iterator.ParallelDataSetIterator;
import org.nd4j.linalg.dataset.api.iterator.enums.InequalityHandling;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author raver119@gmail.com
*/
@Slf4j
public abstract class BaseParallelDataSetIterator implements ParallelDataSetIterator {
protected AtomicLong counter = new AtomicLong(0);
protected InequalityHandling inequalityHandling;
protected int numProducers;
protected AtomicBoolean allDepleted = new AtomicBoolean(false);
protected MultiBoolean states;
protected MultiBoolean resetTracker;
protected ThreadLocal<Integer> producerAffinity = new ThreadLocal<>();
protected BaseParallelDataSetIterator(int numProducers) {
states = new MultiBoolean(numProducers, true);
resetTracker = new MultiBoolean(numProducers, false, true);
this.numProducers = numProducers;
}
public boolean hasNext() {
// if all producers are depleted - there's nothing to do here then
if (states.allFalse() || allDepleted.get())
return false;
int curIdx = getCurrentProducerIndex();
log.info("Going for hasNext({})", curIdx);
boolean hasNext = hasNextFor(curIdx);
if (hasNext)
return true;
else
states.set(hasNext, curIdx);
if (states.allFalse())
return false;
switch (inequalityHandling) {
// FIXME: RESET should be applicable ONLY to producers which return TRUE for resetSupported();
case RESET: {
resetTracker.set(true, curIdx);
// we don't want to have endless loop here, so we only do reset until all producers depleted at least once
if (resetTracker.allTrue()) {
allDepleted.set(true);
return false;
}
reset(curIdx);
// triggering possible adsi underneath
hasNextFor(curIdx);
return true;
}
case RELOCATE: {
// TODO: transparent switch to next producer should happen here
while (!hasNext) {
stepForward();
hasNext = hasNextFor(getCurrentProducerIndex());
states.set(hasNext, getCurrentProducerIndex());
if (states.allFalse())
return false;
}
return true;
}
case PASS_NULL: {
// we just return true here, no matter what's up
return true;
}
case STOP_EVERYONE: {
if (!states.allTrue())
return false;
return true;
}
default:
throw new ND4JIllegalStateException("Unknown InequalityHanding option was passed in: " + inequalityHandling);
}
}
public DataSet next() {
DataSet ds = nextFor(getCurrentProducerIndex());
stepForward();
return ds;
}
protected int getCurrentProducerIndex() {
return (int)(counter.get() % numProducers);
}
protected void stepForward() {
counter.getAndIncrement();
}
@Override
public void reset() {
for(int i = 0; i < numProducers; i++)
reset(i);
}
@Override
public void attachThread(int producer) {
producerAffinity.set(producer);
}
@Override
public boolean hasNextFor() {
if (producerAffinity.get() == null)
throw new ND4JIllegalStateException("attachThread(int) should be called prior to this call");
return hasNextFor(producerAffinity.get());
}
@Override
public DataSet nextFor() {
if (producerAffinity.get() == null)
throw new ND4JIllegalStateException("attachThread(int) should be called prior to this call");
return nextFor(producerAffinity.get());
}
public abstract boolean hasNextFor(int consumer);
public abstract DataSet nextFor(int consumer);
protected abstract void reset(int consumer);
@Override
public int totalExamples() {
return 0;
}
@Override
public int totalOutcomes() {
return 0;
}
@Override
public boolean resetSupported() {
return true;
}
@Override
public boolean asyncSupported() {
return false;
}
@Override
public int batch() {
return 0;
}
@Override
public int cursor() {
return 0;
}
@Override
public int numExamples() {
return 0;
}
@Override
public DataSet next(int num) {
throw new UnsupportedOperationException();
}
@Override
public int inputColumns() {
return 0;
}
@Override
public void setPreProcessor(DataSetPreProcessor preProcessor) {
throw new UnsupportedOperationException();
}
@Override
public DataSetPreProcessor getPreProcessor() {
throw new UnsupportedOperationException();
}
@Override
public List<String> getLabels() {
return null;
}
@Override
public void remove() {
// no-op
}
}
|
package com.codahale.dropwizard.views.freemarker;
import com.codahale.dropwizard.views.View;
import com.codahale.dropwizard.views.ViewRenderer;
import com.google.common.base.Charsets;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.sun.jersey.api.container.MappableContainerException;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import javax.ws.rs.WebApplicationException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Locale;
/**
* A {@link ViewRenderer} which renders Freemarker ({@code .ftl}) templates.
*/
public class FreemarkerViewRenderer implements ViewRenderer {
private static class TemplateLoader extends CacheLoader<Class<?>, Configuration> {
@Override
public Configuration load(Class<?> key) throws Exception {
final Configuration configuration = new Configuration();
configuration.setObjectWrapper(new DefaultObjectWrapper());
configuration.loadBuiltInEncodingMap();
configuration.setDefaultEncoding(Charsets.UTF_8.name());
configuration.setClassForTemplateLoading(key, "/");
return configuration;
}
}
private final LoadingCache<Class<?>, Configuration> configurationCache;
public FreemarkerViewRenderer() {
this.configurationCache = CacheBuilder.newBuilder()
.concurrencyLevel(128)
.build(new TemplateLoader());
}
@Override
public boolean isRenderable(View view) {
return view.getTemplateName().endsWith(".ftl");
}
@Override
public void render(View view,
Locale locale,
OutputStream output) throws IOException, WebApplicationException {
try {
final Configuration configuration = configurationCache.getUnchecked(view.getClass());
final Charset charset = view.getCharset().or(Charset.forName(configuration.getEncoding(locale)));
final Template template = configuration.getTemplate(view.getTemplateName(), locale, charset.name());
template.process(view, new OutputStreamWriter(output, template.getEncoding()));
} catch (TemplateException e) {
throw new MappableContainerException(e);
}
}
}
|
package org.monarchinitiative.exomiser.core.analysis.util;
import com.google.common.collect.ImmutableList;
import de.charite.compbio.jannovar.mendel.ModeOfInheritance;
import de.charite.compbio.jannovar.pedigree.*;
import htsjdk.variant.variantcontext.*;
import htsjdk.variant.variantcontext.Genotype;
import org.junit.Ignore;
import org.junit.Test;
import org.monarchinitiative.exomiser.core.filters.FilterResult;
import org.monarchinitiative.exomiser.core.filters.FilterType;
import org.monarchinitiative.exomiser.core.model.Gene;
import org.monarchinitiative.exomiser.core.model.VariantEvaluation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
/**
*
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class InheritanceModeAnalyserTest {
private VariantEvaluation filteredVariant(int chr, int pos, String ref, String alt, FilterResult filterResult) {
VariantEvaluation variant = new VariantEvaluation.Builder(chr, pos, ref, alt).build();
variant.addFilterResult(filterResult);
return variant;
}
private VariantEvaluation filteredVariant(int chr, int pos, String ref, String alt, FilterResult filterResult, VariantContext variantContext) {
List<Allele> altAlleles = variantContext.getAlternateAlleles();
int altAlleleId = 0;
for (int i = 0; i < altAlleles.size(); i++) {
if (alt.equalsIgnoreCase(altAlleles.get(i).getBaseString())) {
altAlleleId = i;
}
}
VariantEvaluation variant = new VariantEvaluation.Builder(chr, pos, ref, alt)
.altAlleleId(altAlleleId)
.variantContext(variantContext)
.build();
variant.addFilterResult(filterResult);
return variant;
}
private List<Allele> buildAlleles(String ref, String... alts) {
Allele refAllele = Allele.create(ref, true);
List<Allele> altAlleles = Arrays.asList(alts).stream().map(Allele::create).collect(toList());
List<Allele> alleles = new ArrayList<>();
alleles.add(refAllele);
alleles.addAll(altAlleles);
return alleles;
}
private Genotype buildSampleGenotype(String sampleName, Allele ref, Allele alt) {
GenotypeBuilder gtBuilder = new GenotypeBuilder(sampleName).noAttributes().alleles(Arrays.asList(ref, alt)).phased(true);
return gtBuilder.make();
}
private VariantContext buildVariantContext(int chr, int pos, List<Allele> alleles, Genotype... genotypes) {
Allele refAllele = alleles.get(0);
VariantContextBuilder vcBuilder = new VariantContextBuilder();
vcBuilder.loc(Integer.toString(chr), pos, (pos - 1) + refAllele.length());
vcBuilder.alleles(alleles);
vcBuilder.genotypes(genotypes);
//yeah I know, it's a zero
vcBuilder.log10PError(-0.1 * 0);
return vcBuilder.make();
}
private Pedigree buildPedigree(PedPerson... people) {
ImmutableList.Builder<PedPerson> individualBuilder = new ImmutableList.Builder<PedPerson>();
individualBuilder.addAll(Arrays.asList(people));
PedFileContents pedFileContents = new PedFileContents(new ImmutableList.Builder<String>().build(), individualBuilder.build());
return buildPedigreeFromPedFile(pedFileContents);
}
private Pedigree buildPedigreeFromPedFile(PedFileContents pedFileContents) {
final String name = pedFileContents.getIndividuals().get(0).getPedigree();
try {
return new Pedigree(name, new PedigreeExtractor(name, pedFileContents).run());
} catch (PedParseException e) {
throw new RuntimeException(e);
}
}
@Test
public void testAnalyseInheritanceModes_SingleSample_NoVariants() {
Gene gene = newGene();
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Adam");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.ANY);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
}
@Test
public void testAnalyseInheritanceModes_SingleSample_NoPassedVariants() {
Gene gene = newGene();
gene.addVariant(filteredVariant(1, 1 , "A", "T", FilterResult.fail(FilterType.FREQUENCY_FILTER)));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Adam");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.ANY);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
}
@Test
public void testAnalyseInheritanceModes_SingleSample_OnePassedVariant_HET() {
List<Allele> alleles = buildAlleles("A", "T");
// build Genotype
Genotype genotype = buildSampleGenotype("Adam", alleles.get(0), alleles.get(1));
assertThat(genotype.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, genotype);
System.out.println("Built variant context " + variantContext);
Gene gene = newGene();
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Adam");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(true));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
}
@Test
public void testAnalyseInheritanceModes_SingleSample_OnePassedVariant_HOM_REF_ShouldBeIncompatibleWith_RECESIVE() {
List<Allele> alleles = buildAlleles("A", "T");
//HomRef 0/0 or 0|0 variants really shouldn't be causing rare diseases so we need to ensure these are removed
Genotype genotype = buildSampleGenotype("Adam", alleles.get(0), alleles.get(0));
assertThat(genotype.getType(), equalTo(GenotypeType.HOM_REF));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, genotype);
System.out.println("Built variant context " + variantContext);
Gene gene = newGene();
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Adam");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
}
@Test
public void testAnalyseInheritanceModes_SingleSample_OnePassedVariant_HOM_REF_ShouldBeIncompatibleWith_DOMINANT() {
List<Allele> alleles = buildAlleles("A", "T");
//HomRef 0/0 or 0|0 variants really shouldn't be causing rare diseases so we need to ensure these are removed
Genotype genotype = buildSampleGenotype("Adam", alleles.get(0), alleles.get(0));
assertThat(genotype.getType(), equalTo(GenotypeType.HOM_REF));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, genotype);
System.out.println("Built variant context " + variantContext);
Gene gene = newGene();
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Adam");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> assertThat(variant.getInheritanceModes().isEmpty(), is(true)));
}
@Test
public void testAnalyseInheritanceModes_SingleSample_OnePassedVariant_HOM_VAR() {
List<Allele> alleles = buildAlleles("A", "T");
//HOM_ALT
Genotype genotype = buildSampleGenotype("Adam", alleles.get(1), alleles.get(1));
assertThat(genotype.getType(), equalTo(GenotypeType.HOM_VAR));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, genotype);
System.out.println("Built variant context " + variantContext);
Gene gene = newGene();
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Adam");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> assertThat(variant.getInheritanceModes().isEmpty(), is(true)));
}
@Test
public void testAnalyseInheritanceModes_MultiSample_OnePassedVariant_HOM_VAR_shouldBeCompatibelWith_RECESSIVE() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T");
// build Genotype
//HomVar 1/1 or 1|1 variants are a really likely candidate for recessive rare diseases
Genotype proband = buildSampleGenotype("Cain", alleles.get(1), alleles.get(1));
assertThat(proband.getType(), equalTo(GenotypeType.HOM_VAR));
Genotype mother = buildSampleGenotype("Eve", alleles.get(0), alleles.get(1));
assertThat(mother.getType(), equalTo(GenotypeType.HET));
Genotype father = buildSampleGenotype("Adam", alleles.get(1), alleles.get(0));
assertThat(father.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband, mother, father);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
PedPerson probandPerson = new PedPerson("Family", "Cain", "Adam", "Eve", Sex.MALE, Disease.AFFECTED, new ArrayList<String>());
PedPerson motherPerson = new PedPerson("Family", "Eve", "0", "0", Sex.FEMALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson fatherPerson = new PedPerson("Family", "Adam", "0", "0", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
Pedigree pedigree = buildPedigree(probandPerson, motherPerson, fatherPerson);
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(true));
gene.getPassedVariantEvaluations()
.forEach(variant -> assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_RECESSIVE)));
}
@Test
public void testAnalyseInheritanceModes_MultiSample_OnePassedVariant_HOM_REF_shouldNotBeCompatibleWith_AR() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T");
// build Genotype
//HomVar 1/1 or 1|1 variants are a really likely candidate for recessive rare diseases
Genotype proband = buildSampleGenotype("Cain", alleles.get(0), alleles.get(0));
assertThat(proband.getType(), equalTo(GenotypeType.HOM_REF));
Genotype mother = buildSampleGenotype("Eve", alleles.get(0), alleles.get(1));
assertThat(mother.getType(), equalTo(GenotypeType.HET));
Genotype father = buildSampleGenotype("Adam", alleles.get(1), alleles.get(0));
assertThat(father.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband, mother, father);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
PedPerson probandPerson = new PedPerson("Family", "Cain", "Adam", "Eve", Sex.MALE, Disease.AFFECTED, new ArrayList<String>());
PedPerson motherPerson = new PedPerson("Family", "Eve", "0", "0", Sex.FEMALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson fatherPerson = new PedPerson("Family", "Adam", "0", "0", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
Pedigree pedigree = buildPedigree(probandPerson, motherPerson, fatherPerson);
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> assertThat(variant.getInheritanceModes().isEmpty(), is(true)));
}
@Test
public void testAnalyseInheritanceModes_MultiSample_OnePassedVariant_HET_shouldBeCompatibleWith_AD() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T");
// build Genotype
//HomVar 1/1 or 1|1 variants are a really likely candidate for recessive rare diseases
Genotype proband = buildSampleGenotype("Cain", alleles.get(0), alleles.get(1));
assertThat(proband.getType(), equalTo(GenotypeType.HET));
Genotype mother = buildSampleGenotype("Eve", alleles.get(0), alleles.get(0));
assertThat(mother.getType(), equalTo(GenotypeType.HOM_REF));
Genotype father = buildSampleGenotype("Adam", alleles.get(0), alleles.get(0));
assertThat(father.getType(), equalTo(GenotypeType.HOM_REF));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband, mother, father);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
PedPerson probandPerson = new PedPerson("Family", "Cain", "Adam", "Eve", Sex.MALE, Disease.AFFECTED, new ArrayList<String>());
PedPerson motherPerson = new PedPerson("Family", "Eve", "0", "0", Sex.FEMALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson fatherPerson = new PedPerson("Family", "Adam", "0", "0", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
Pedigree pedigree = buildPedigree(probandPerson, motherPerson, fatherPerson);
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(true));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_DOMINANT)));
}
@Test
public void testAnalyseInheritanceModes_MultiSample_MultiAllelic_TwoPassedVariant_HOM_VAR_shouldBeCompatibleWith_AR() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
// build Genotype
//HomVar 1/1 or 1|1 variants are a really likely candidate for recessive rare diseases
Genotype proband = buildSampleGenotype("Cain", alleles.get(2), alleles.get(2));
assertThat(proband.getType(), equalTo(GenotypeType.HOM_VAR));
Genotype mother = buildSampleGenotype("Eve", alleles.get(0), alleles.get(1));
assertThat(mother.getType(), equalTo(GenotypeType.HET));
Genotype father = buildSampleGenotype("Adam", alleles.get(1), alleles.get(0));
assertThat(father.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband, mother, father);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
PedPerson probandPerson = new PedPerson("Family", "Cain", "Adam", "Eve", Sex.MALE, Disease.AFFECTED, new ArrayList<String>());
PedPerson motherPerson = new PedPerson("Family", "Eve", "0", "0", Sex.FEMALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson fatherPerson = new PedPerson("Family", "Adam", "0", "0", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
Pedigree pedigree = buildPedigree(probandPerson, motherPerson, fatherPerson);
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(true));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_RECESSIVE));
});
}
private String variantString(VariantEvaluation variant) {
return String.format("%s\t%s\t%s\t%s\t%s\tcompatibleWith=%s",variant.getChromosome(), variant.getRef(), variant.getAlt(), variant.getAltAlleleId(), variant.getGenotypeString(), variant.getInheritanceModes());
}
/**
* Currently ignored as Jannovar multi-allelic inheritance compatibility is broken for multi-sample VCF.
*/
@Ignore
@Test
public void testAnalyseInheritanceModes_MultiSample_MultiAllelic_OnePassedVariant_HOM_VAR_altAllele2_shouldBeCompatibleWith_AR() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
// build Genotype
//HomVar 1/1 or 1|1 variants are a really likely candidate for recessive rare diseases
Genotype proband = buildSampleGenotype("Cain", alleles.get(2), alleles.get(2));
assertThat(proband.getType(), equalTo(GenotypeType.HOM_VAR));
Genotype mother = buildSampleGenotype("Eve", alleles.get(1), alleles.get(1));
assertThat(mother.getType(), equalTo(GenotypeType.HOM_VAR));
Genotype father = buildSampleGenotype("Adam", alleles.get(1), alleles.get(0));
assertThat(father.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband, mother, father);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.fail(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
PedPerson probandPerson = new PedPerson("Family", "Cain", "Adam", "Eve", Sex.MALE, Disease.AFFECTED, new ArrayList<String>());
PedPerson motherPerson = new PedPerson("Family", "Eve", "0", "0", Sex.FEMALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson fatherPerson = new PedPerson("Family", "Adam", "0", "0", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
Pedigree pedigree = buildPedigree(probandPerson, motherPerson, fatherPerson);
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(true));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_RECESSIVE));
});
}
/**
* Currently ignored as Jannovar multi-allelic inheritance compatibility is broken for multi-sample VCF.
*/
@Ignore
@Test
public void testAnalyseInheritanceModes_MultiSample_MultiAllelic_OnePassedVariant_HET_shouldBeCompatibleWith_AD() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
Genotype proband = buildSampleGenotype("Cain", alleles.get(1), alleles.get(2));
assertThat(proband.getType(), equalTo(GenotypeType.HET));
Genotype brother = buildSampleGenotype("Abel", alleles.get(1), alleles.get(1));
assertThat(brother.getType(), equalTo(GenotypeType.HOM_VAR));
Genotype mother = buildSampleGenotype("Eve", alleles.get(0), alleles.get(1));
assertThat(mother.getType(), equalTo(GenotypeType.HET));
Genotype father = buildSampleGenotype("Adam", alleles.get(1), alleles.get(0));
assertThat(father.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband, brother, mother, father);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.fail(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
PedPerson probandPerson = new PedPerson("Family", "Cain", "Adam", "Eve", Sex.MALE, Disease.AFFECTED, new ArrayList<String>());
PedPerson brotherPerson = new PedPerson("Family", "Abel", "Adam", "Eve", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson motherPerson = new PedPerson("Family", "Eve", "0", "0", Sex.FEMALE, Disease.UNAFFECTED, new ArrayList<String>());
PedPerson fatherPerson = new PedPerson("Family", "Adam", "0", "0", Sex.MALE, Disease.UNAFFECTED, new ArrayList<String>());
Pedigree pedigree = buildPedigree(probandPerson, brotherPerson, motherPerson, fatherPerson);
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(true));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_DOMINANT));
});
}
private Gene newGene() {
return new Gene("ABC", 123);
}
@Test
public void testAnalyseInheritanceModes_SingleSample_MultiAllelic_OnePassedVariant_HET_shouldBeCompatibleWith_AD() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
Genotype proband = buildSampleGenotype("Cain", alleles.get(1), alleles.get(2));
assertThat(proband.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.fail(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Cain");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(true));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_DOMINANT));
});
}
@Test
public void testAnalyseInheritanceModes_SingleSample_MultiAllelic_TwoPassedVariant_HET_shouldBeCompatibleWith_AD() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
Genotype proband = buildSampleGenotype("Cain", alleles.get(1), alleles.get(2));
assertThat(proband.getType(), equalTo(GenotypeType.HET));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Cain");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_DOMINANT);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(true));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(false));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_DOMINANT));
});
}
@Test
public void testAnalyseInheritanceModes_SingleSample_MultiAllelic_TwoPassedVariant_HOM_VAR_Allele2_shouldBeCompatibleWith_AR() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
Genotype proband = buildSampleGenotype("Cain", alleles.get(2), alleles.get(2));
assertThat(proband.getType(), equalTo(GenotypeType.HOM_VAR));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Cain");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(true));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_RECESSIVE));
});
}
@Test
public void testAnalyseInheritanceModes_SingleSample_MultiAllelic_TwoPassedVariant_HOM_VAR_Allele1_shouldBeCompatibleWith_AR() {
Gene gene = newGene();
List<Allele> alleles = buildAlleles("A", "T", "C");
Genotype proband = buildSampleGenotype("Cain", alleles.get(1), alleles.get(1));
assertThat(proband.getType(), equalTo(GenotypeType.HOM_VAR));
VariantContext variantContext = buildVariantContext(1, 12345, alleles, proband);
System.out.println("Built variant context " + variantContext);
gene.addVariant(filteredVariant(1, 12345, "A", "T", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
gene.addVariant(filteredVariant(1, 12345, "A", "C", FilterResult.pass(FilterType.FREQUENCY_FILTER), variantContext));
Pedigree pedigree = Pedigree.constructSingleSamplePedigree("Cain");
InheritanceModeAnalyser instance = new InheritanceModeAnalyser(pedigree, ModeOfInheritance.AUTOSOMAL_RECESSIVE);
instance.analyseInheritanceModes(gene);
assertThat(gene.isCompatibleWith(ModeOfInheritance.ANY), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_DOMINANT), is(false));
assertThat(gene.isCompatibleWith(ModeOfInheritance.AUTOSOMAL_RECESSIVE), is(true));
gene.getPassedVariantEvaluations()
.forEach(variant -> {
System.out.println(variantString(variant));
assertThat(variant.getInheritanceModes(), hasItem(ModeOfInheritance.AUTOSOMAL_RECESSIVE));
});
}
}
|
package org.opennms.features.gwt.ksc.add.client.presenter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.opennms.features.gwt.ksc.add.client.GraphInfo;
import org.opennms.features.gwt.ksc.add.client.KscReport;
import org.opennms.features.gwt.ksc.add.client.rest.DefaultKscReportService;
import org.opennms.features.gwt.ksc.add.client.rest.KscReportService;
import org.opennms.features.gwt.ksc.add.client.view.KscAddGraphView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodeEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
public class KscAddGraphPresenter implements Presenter, KscAddGraphView.Presenter<KscReport> {
private static final List<KscReport> EMPTY_KSCREPORT_LIST = Collections.unmodifiableList(new ArrayList<KscReport>());
private KscAddGraphView<KscReport> m_view;
private List<KscReport> m_KscReports;
private PopupPanel m_mainPopup;
private final Image m_addImage;
private GraphInfo m_graphInfo;
private final KscReportService m_reportService = new DefaultKscReportService();
public KscAddGraphPresenter(final PopupPanel mainPopup, final KscAddGraphView<KscReport> addGraphView, final List<KscReport> kscReports, final GraphInfo graphInfo) {
m_mainPopup = mainPopup;
m_view = addGraphView;
m_view.setPresenter(this);
m_KscReports = kscReports;
m_graphInfo = graphInfo;
m_addImage = new Image("images/plus.gif");
m_addImage.setAltText("Add this graph to a KSC report.");
m_addImage.setTitle("Add this graph to a KSC report.");
}
private List<KscReport> filterResultsByName(final String searchText) {
final List<KscReport> list = new ArrayList<KscReport>();
for (final KscReport detail : m_KscReports) {
if (detail.getLabel().toLowerCase().contains(searchText.toLowerCase())) {
list.add(detail);
}
}
return list;
}
@Override
public void onKeyCodeEvent(final KeyCodeEvent<?> event, final String searchText) {
final int keyCode = event.getNativeEvent().getKeyCode();
final boolean isKeyUp = event instanceof KeyUpEvent;
final boolean isKeyDown = event instanceof KeyDownEvent;
if (isKeyUp && keyCode == KeyCodes.KEY_ESCAPE) {
GWT.log("escape, hiding results");
m_view.hidePopup();
} else if (isKeyUp && keyCode == KeyCodes.KEY_BACKSPACE && searchText.length() == 0) {
m_view.hidePopup();
m_view.setDataList(EMPTY_KSCREPORT_LIST);
m_view.clearSelection();
} else if (isKeyDown && keyCode == KeyCodes.KEY_ENTER && m_view.getSelectedReport() != null && m_view.getTitle() != null && !m_view.isPopupShowing()) {
onAddButtonClicked();
} else if (isKeyUp) {
if (searchText.length() == 0) {
GWT.log("search text is empty");
m_view.setDataList(EMPTY_KSCREPORT_LIST);
} else {
GWT.log("search text is not empty");
final List<KscReport> results = filterResultsByName(searchText);
if (keyCode == KeyCodes.KEY_ENTER && results.size() == 1) {
m_view.hidePopup();
m_view.select(results.get(0));
} else {
m_view.setDataList(results);
m_view.showPopup();
m_view.clearSelection();
}
}
}
}
@Override
public void onKscReportSelected() {
GWT.log("selected report " + m_view.getSelectedReport().getId());
m_view.hidePopup();
}
@Override
public void onAddButtonClicked() {
final String graphTitle = m_view.getTitle();
final int kscReportId = m_view.getSelectedReport().getId();
final String kscReportName = m_view.getSelectedReport().getLabel();
final String resourceId = m_graphInfo.getResourceId();
final String graphName = m_graphInfo.getReportName();
final String timeSpan = m_graphInfo.getTimespan();
final RequestCallback callback = new RequestCallback() {
@Override
public void onResponseReceived(final Request request, final Response response) {
GWT.log("got response: " + response.getText() + " (" + response.getStatusCode() + ")");
}
@Override
public void onError(final Request request, final Throwable t) {
GWT.log("got error: " + t.getLocalizedMessage());
}
};
GWT.log("adding resource '" + resourceId + "' from graph report '" + graphName + "' to KSC report '" + kscReportName + "' (" + kscReportId + ") with title '" + graphTitle + "' and timespan '" + timeSpan + "'");
m_reportService.addGraphToReport(callback, kscReportId, graphTitle, graphName, resourceId, timeSpan);
m_mainPopup.hide();
}
@Override
public void go(final HasWidgets container) {
m_addImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
GWT.log("clicked (showing = " + m_mainPopup.isShowing() + ", visible = " + m_mainPopup.isVisible() + ")");
if (m_mainPopup.isShowing()) {
m_mainPopup.hide();
m_mainPopup.getElement().getStyle().setDisplay(Display.NONE);
} else {
m_mainPopup.getElement().getStyle().setDisplay(Display.BLOCK);
m_mainPopup.showRelativeTo(m_addImage);
}
}
});
m_mainPopup.setVisible(false);
m_mainPopup.getElement().getStyle().setDisplay(Display.NONE);
m_mainPopup.addAutoHidePartner(m_addImage.getElement());
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(final ResizeEvent event) {
final int[] positions = calculateMainPopupPosition();
m_mainPopup.setPopupPosition(positions[0], positions[1]);
}
});
container.clear();
container.add(m_addImage);
container.add(m_mainPopup.asWidget());
}
public native final String getBaseHref() /*-{
try{
return $wnd.getBaseHref();
}catch(err){
return "";
}
}-*/;
private int[] calculateMainPopupPosition() {
final int[] positions = {0, 0};
final int windowWidth = Window.getClientWidth();
final int imageRightEdge = m_addImage.getAbsoluteLeft() + m_addImage.getWidth();
if (imageRightEdge + 300 > windowWidth) {
positions[0] = windowWidth - 320;
} else {
positions[0] = imageRightEdge - 3;
}
if (positions[0] < 0) positions[0] = 0;
positions[1] = m_addImage.getAbsoluteTop() + m_addImage.getHeight() - 1;
return positions;
}
}
|
package org.opennms.features.vaadin.nodemaps.ui;
import java.util.List;
import org.opennms.core.criteria.CriteriaBuilder;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.features.geocoder.Coordinates;
import org.opennms.features.geocoder.GeocoderException;
import org.opennms.features.geocoder.GeocoderService;
import org.opennms.features.vaadin.nodemaps.gwt.client.VOpenlayersWidget;
import org.opennms.netmgt.dao.AlarmDao;
import org.opennms.netmgt.dao.AssetRecordDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.model.OnmsAssetRecord;
import org.opennms.netmgt.model.OnmsGeolocation;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSeverity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.ui.ClientWidget;
import com.vaadin.ui.VerticalLayout;
@ClientWidget(value = VOpenlayersWidget.class)
public class OpenlayersWidgetComponent extends VerticalLayout {
private static final long serialVersionUID = 1L;
private NodeDao m_nodeDao;
private AssetRecordDao m_assetDao;
private AlarmDao m_alarmDao;
private GeocoderService m_geocoderService;
private boolean m_enableGeocoding = false;
private Logger m_log = LoggerFactory.getLogger(getClass());
public OpenlayersWidgetComponent() {
}
public OpenlayersWidgetComponent(final NodeDao nodeDao, final AssetRecordDao assetDao, final AlarmDao alarmDao, final GeocoderService geocoder) {
m_nodeDao = nodeDao;
m_assetDao = assetDao;
m_alarmDao = alarmDao;
m_geocoderService = geocoder;
}
@Override
public void paintContent(final PaintTarget target) throws PaintException {
super.paintContent(target);
if (m_nodeDao == null) return;
final CriteriaBuilder cb = new CriteriaBuilder(OnmsNode.class);
cb.alias("assetRecord", "asset");
cb.orderBy("id");
target.startTag("nodes");
for (final OnmsNode node : m_nodeDao.findMatching(cb.toCriteria())) {
paintNode(target, node);
}
target.endTag("nodes");
}
void paintNode(final PaintTarget target, final OnmsNode node) throws PaintException {
final OnmsAssetRecord assets = node.getAssetRecord();
if (assets != null && assets.getGeolocation() != null) {
final OnmsGeolocation geolocation = assets.getGeolocation();
final String addressString = geolocation.asAddressString();
final String coordinateString = geolocation.getCoordinates();
if (m_enableGeocoding && (coordinateString == null || coordinateString == "" || !coordinateString.contains(",")) && addressString != "") {
m_log.debug("No coordinates for node {}, getting geolocation for street address: {}", new Object[] { node.getId(), addressString });
Coordinates coordinates = null;
try {
coordinates = m_geocoderService.getCoordinates(addressString);
if (coordinates == null) {
geolocation.setCoordinates("-1,-1");
m_log.debug("Failed to look up coordinates for street address: {}", addressString);
} else {
geolocation.setCoordinates(coordinates.getLatitude() + "," + coordinates.getLongitude());
}
updateDatabase(assets);
} catch (final GeocoderException e) {
m_log.debug("Failed to retrieve coordinates", e);
}
} else {
m_log.debug("Found coordinates for node {}, geolocation for street address: {} = {}", new Object[] { node.getId(), addressString, coordinateString });
}
if (coordinateString != null && coordinateString != "") {
final String[] coordinates = coordinateString.split(",");
if (coordinates[0] != "-1" && coordinates[1] != "-1") {
target.startTag(node.getId().toString());
CriteriaBuilder builder = new CriteriaBuilder(OnmsAlarm.class);
builder.alias("node", "node");
builder.eq("node.id", node.getId());
builder.ge("severity", OnmsSeverity.WARNING);
builder.orderBy("severity").desc();
builder.limit(1);
// first, get the highest severity alarm
final List<OnmsAlarm> alarms = m_alarmDao.findMatching(builder.toCriteria());
if (alarms.size() == 1) {
final OnmsAlarm alarm = alarms.get(0);
final OnmsSeverity severity = alarm.getSeverity();
target.addAttribute("severityLabel", severity.getLabel());
target.addAttribute("severity", severity.getId());
} else {
// assumes everything is OK
target.addAttribute("severityLabel", OnmsSeverity.NORMAL.getLabel());
target.addAttribute("severity", OnmsSeverity.NORMAL.getId());
}
builder = new CriteriaBuilder(OnmsAlarm.class);
builder.alias("node", "node");
builder.eq("node.id", node.getId());
builder.ge("severity", OnmsSeverity.WARNING);
builder.isNull("alarmAckTime");
final int unackedCount = m_alarmDao.countMatching(builder.toCriteria());
target.addAttribute("nodeId", node.getId());
target.addAttribute("nodeLabel", node.getLabel());
target.addAttribute("foreignSource", node.getForeignSource());
target.addAttribute("foreignId", node.getForeignId());
target.addAttribute("ipAddress", InetAddressUtils.str(node.getPrimaryInterface().getIpAddress()));
target.addAttribute("unackedCount", unackedCount);
target.addAttribute("latitude", coordinates[0]);
target.addAttribute("longitude", coordinates[1]);
target.endTag(node.getId().toString());
}
}
}
}
@Transactional
void updateDatabase(final OnmsAssetRecord assets) {
m_assetDao.saveOrUpdate(assets);
}
public void setNodeDao(final NodeDao nodeDao) {
m_nodeDao = nodeDao;
}
public void setAssetRecordDao(final AssetRecordDao assetDao) {
m_assetDao = assetDao;
}
public void setAlarmDao(final AlarmDao alarmDao) {
m_alarmDao = alarmDao;
}
public void setGeocoderService(final GeocoderService geocoderService) {
m_geocoderService = geocoderService;
}
}
|
package org.testeditor.fitnesse.resultreader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.testeditor.core.model.testresult.ActionResultTable;
import org.testeditor.core.model.testresult.InstructionExpectation;
import org.testeditor.core.model.testresult.InstructionsResult;
import org.testeditor.core.model.testresult.TestResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Reads from result file of an test case end returns a {@link TestResult}
* object.
*
*
*/
public class FitNesseTestHistoryResultReader implements FitNesseResultReader {
private static final Logger LOGGER = Logger.getLogger(FitNesseTestHistoryResultReader.class);
@Override
public TestResult readTestResult(InputStream resultStream) {
TestResult testResult = new TestResult();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new InputStreamReader(resultStream, "UTF-8")));
doc.getDocumentElement().normalize();
// create testresult for summary of suite
Element finalCounts = (Element) doc.getElementsByTagName("counts").item(0);
String right = finalCounts.getElementsByTagName("right").item(0).getTextContent();
String wrong = finalCounts.getElementsByTagName("wrong").item(0).getTextContent();
String ignores = finalCounts.getElementsByTagName("ignores").item(0).getTextContent();
String exceptions = finalCounts.getElementsByTagName("exceptions").item(0).getTextContent();
String runTimeInMillis = doc.getElementsByTagName("runTimeInMillis").item(0).getTextContent();
if(right.isEmpty() && wrong.isEmpty() && ignores.isEmpty()) {
// this case will be exists if test were canceled.
return testResult;
}
testResult.setRight(Integer.parseInt(right));
testResult.setWrong(Integer.parseInt(wrong));
testResult.setIgnored(Integer.parseInt(ignores));
testResult.setException(Integer.parseInt(exceptions));
testResult.setRunTimeMillis(Integer.parseInt(runTimeInMillis));
testResult.setActionResultTables(createActionResultTable(doc.getElementsByTagName("tables").item(0)));
testResult.setInstructionResultTables(createInstructionsResult(doc.getElementsByTagName("instructions")
.item(0)));
} catch (ParserConfigurationException | SAXException | IOException e) {
LOGGER.error(e.getMessage());
}
return testResult;
}
/**
* Reads the DOM Tree from the Node "tables".
*
* @param item
* Node named tables
* @return Object model of the XML as List with the ActionResultTable's.
*/
protected List<InstructionsResult> createInstructionsResult(Node item) {
List<InstructionsResult> result = new ArrayList<InstructionsResult>();
if (item != null) {
NodeList tableList = item.getChildNodes();
for (int i = 0; i < tableList.getLength(); i++) {
InstructionsResult resultTable = createInstructionsResultFrom(tableList.item(i));
result.add(resultTable);
}
}
return result;
}
/**
* Creates an InstructionsResultTable based on the given node.
*
* @param item
* used to create an InstructionsResultTable.
* @return new InstructionsResultTable.
*/
protected InstructionsResult createInstructionsResultFrom(Node item) {
InstructionsResult result = new InstructionsResult();
if (item != null && item.getNodeName().equals("instructionResult")) {
NodeList childNodes = item.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
switch (node.getNodeName()) {
case "instruction":
result.setInstruction(node.getTextContent());
break;
case "slimResult":
result.setResult(node.getTextContent());
break;
case "expectation":
result.addExpectation(createExpectationFrom(node));
default:
break;
}
}
} else {
result.setInstruction("Invalid Instruction");
}
return result;
}
/**
*
* @param node
* expectation part of the testresult xml document.
* @return InstructionExpectation with the data of the xml node.
*/
protected InstructionExpectation createExpectationFrom(Node node) {
InstructionExpectation exp = new InstructionExpectation();
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node item = nodeList.item(i);
switch (item.getNodeName()) {
case "status":
exp.setStatus(item.getTextContent());
break;
case "row":
exp.setActionPartPosition(Integer.parseInt(item.getTextContent()));
break;
default:
break;
}
}
return exp;
}
/**
* Reads the DOM Tree from the Node "tables".
*
* @param item
* Node named tables
* @return Object model of the XML as List with the ActionResultTable's.
*/
protected List<ActionResultTable> createActionResultTable(Node item) {
ArrayList<ActionResultTable> result = new ArrayList<ActionResultTable>();
if (item != null) {
NodeList tableList = item.getChildNodes();
for (int i = 0; i < tableList.getLength(); i++) {
if (tableList.item(i).getNodeName().equals("table")) {
ActionResultTable resultTable = createActionResultTableFrom(tableList.item(i));
result.add(resultTable);
}
}
}
return result;
}
/**
* Creates an ActionResultTable based on the given node.
*
* @param item
* used to create an ActionResultTable.
* @return new ActionResultTable.
*/
protected ActionResultTable createActionResultTableFrom(Node item) {
ActionResultTable resultTable = new ActionResultTable();
if (item != null) {
NodeList childNodes = item.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
switch (node.getNodeName()) {
case "name":
resultTable.setName(node.getTextContent());
break;
case "row":
List<String> newRow = resultTable.createNewRow();
NodeList colNodes = node.getChildNodes();
for (int j = 0; j < colNodes.getLength(); j++) {
if (colNodes.item(j).getNodeName().equals("col")) {
newRow.add(colNodes.item(j).getTextContent());
}
}
break;
default:
break;
}
}
} else {
resultTable.setName("Invalid ResultTable");
}
return resultTable;
}
}
|
package uk.ac.ebi.spot.goci.curation.controller;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import uk.ac.ebi.spot.goci.curation.component.EnsemblMappingPipeline;
import uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException;
import uk.ac.ebi.spot.goci.curation.model.AssociationFormErrorView;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView;
import uk.ac.ebi.spot.goci.curation.model.SnpFormColumn;
import uk.ac.ebi.spot.goci.curation.model.SnpFormRow;
import uk.ac.ebi.spot.goci.curation.service.AssociationBatchLoaderService;
import uk.ac.ebi.spot.goci.curation.service.AssociationDownloadService;
import uk.ac.ebi.spot.goci.curation.service.AssociationFormErrorViewService;
import uk.ac.ebi.spot.goci.curation.service.AssociationReportService;
import uk.ac.ebi.spot.goci.curation.service.AssociationViewService;
import uk.ac.ebi.spot.goci.curation.service.LociAttributesService;
import uk.ac.ebi.spot.goci.curation.service.SingleSnpMultiSnpAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpGenomicContextMappingService;
import uk.ac.ebi.spot.goci.curation.service.SnpInteractionAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpLocationMappingService;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Gene;
import uk.ac.ebi.spot.goci.model.GenomicContext;
import uk.ac.ebi.spot.goci.model.Location;
import uk.ac.ebi.spot.goci.model.Locus;
import uk.ac.ebi.spot.goci.model.RiskAllele;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.LocusRepository;
import uk.ac.ebi.spot.goci.repository.SingleNucleotidePolymorphismRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Controller
public class AssociationController {
// Repositories
private AssociationRepository associationRepository;
private StudyRepository studyRepository;
private EfoTraitRepository efoTraitRepository;
private LocusRepository locusRepository;
private SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository;
// Services
private AssociationBatchLoaderService associationBatchLoaderService;
private AssociationDownloadService associationDownloadService;
private AssociationViewService associationViewService;
private SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService;
private SnpInteractionAssociationService snpInteractionAssociationService;
private LociAttributesService lociAttributesService;
private AssociationFormErrorViewService associationFormErrorViewService;
private SnpLocationMappingService snpLocationMappingService;
private SnpGenomicContextMappingService snpGenomicContextMappingService;
private AssociationReportService associationReportService;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public AssociationController(AssociationRepository associationRepository,
StudyRepository studyRepository,
EfoTraitRepository efoTraitRepository,
LocusRepository locusRepository,
SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository,
AssociationBatchLoaderService associationBatchLoaderService,
AssociationDownloadService associationDownloadService,
AssociationViewService associationViewService,
SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService,
SnpInteractionAssociationService snpInteractionAssociationService,
LociAttributesService lociAttributesService,
AssociationFormErrorViewService associationFormErrorViewService,
SnpLocationMappingService snpLocationMappingService,
SnpGenomicContextMappingService snpGenomicContextMappingService,
AssociationReportService associationReportService) {
this.associationRepository = associationRepository;
this.studyRepository = studyRepository;
this.efoTraitRepository = efoTraitRepository;
this.locusRepository = locusRepository;
this.singleNucleotidePolymorphismRepository = singleNucleotidePolymorphismRepository;
this.associationBatchLoaderService = associationBatchLoaderService;
this.associationDownloadService = associationDownloadService;
this.associationViewService = associationViewService;
this.singleSnpMultiSnpAssociationService = singleSnpMultiSnpAssociationService;
this.snpInteractionAssociationService = snpInteractionAssociationService;
this.lociAttributesService = lociAttributesService;
this.associationFormErrorViewService = associationFormErrorViewService;
this.snpLocationMappingService = snpLocationMappingService;
this.snpGenomicContextMappingService = snpGenomicContextMappingService;
this.associationReportService = associationReportService;
}
/* Study SNP/Associations */
// Generate list of SNP associations linked to a study
@RequestMapping(value = "/studies/{studyId}/associations",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String viewStudySnps(Model model, @PathVariable Long studyId) {
// Get all associations for a study
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView =
associationViewService.createSnpAssociationTableView(association);
snpAssociationTableViews.add(snpAssociationTableView);
}
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
@RequestMapping(value = "/studies/{studyId}/associations/sortpvalue",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String sortStudySnpsByPvalue(Model model,
@PathVariable Long studyId,
@RequestParam(required = true) String direction) {
// Get all associations for a study and perform relevant sorting
Collection<Association> associations = new ArrayList<>();
switch (direction) {
case "asc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByPvalueExponentAndMantissaAsc()));
break;
case "desc":
associations.addAll(associationRepository.findByStudyId(studyId,
sortByPvalueExponentAndMantissaDesc()));
break;
default:
associations.addAll(associationRepository.findByStudyId(studyId));
break;
}
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView = associationViewService.createSnpAssociationTableView(
association);
snpAssociationTableViews.add(snpAssociationTableView);
}
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
@RequestMapping(value = "/studies/{studyId}/associations/sortrsid",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String sortStudySnpsByRsid(Model model,
@PathVariable Long studyId,
@RequestParam(required = true) String direction) {
// Get all associations for a study and perform relevant sorting
Collection<Association> associations = new ArrayList<>();
// Sorting will not work for multi-snp haplotype or snp interactions so need to check for that
Boolean sortValues = true;
switch (direction) {
case "asc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByRsidAsc()));
break;
case "desc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByRsidDesc()));
break;
default:
associations.addAll(associationRepository.findByStudyId(studyId));
break;
}
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView = associationViewService.createSnpAssociationTableView(
association);
// Cannot sort multi field values
if (snpAssociationTableView.getMultiSnpHaplotype() != null) {
if (snpAssociationTableView.getMultiSnpHaplotype().equalsIgnoreCase("Yes")) {
sortValues = false;
}
}
if (snpAssociationTableView.getSnpInteraction() != null) {
if (snpAssociationTableView.getSnpInteraction().equalsIgnoreCase("Yes")) {
sortValues = false;
}
}
snpAssociationTableViews.add(snpAssociationTableView);
}
// Only return sorted results if its not a multi-snp haplotype or snp interaction
if (sortValues) {
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
else {
return "redirect:/studies/" + studyId + "/associations";
}
}
// Upload a spreadsheet of snp association information
@RequestMapping(value = "/studies/{studyId}/associations/upload",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String uploadStudySnps(@RequestParam("file") MultipartFile file, @PathVariable Long studyId, Model model) {
// Establish our study object
Study study = studyRepository.findOne(studyId);
if (!file.isEmpty()) {
// Save the uploaded file received in a multipart request as a file in the upload directory
// The default temporary-file directory is specified by the system property java.io.tmpdir.
String uploadDir =
System.getProperty("java.io.tmpdir") + File.separator + "gwas_batch_upload" + File.separator;
// Create file
File uploadedFile = new File(uploadDir + file.getOriginalFilename());
uploadedFile.getParentFile().mkdirs();
// Copy contents of multipart request to newly created file
try {
file.transferTo(uploadedFile);
}
catch (IOException e) {
throw new RuntimeException(
"Unable to to upload file ", e);
}
String uploadedFilePath = uploadedFile.getAbsolutePath();
uploadedFile.setExecutable(true, false);
uploadedFile.setReadable(true, false);
uploadedFile.setWritable(true, false);
// Send file, including path, to SNP batch loader process
Collection<Association> newAssociations = new ArrayList<>();
try {
newAssociations = associationBatchLoaderService.processData(uploadedFilePath);
}
catch (InvalidOperationException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (InvalidFormatException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (IOException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (RuntimeException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "data_upload_problem";
}
// Create our associations
if (!newAssociations.isEmpty()) {
for (Association newAssociation : newAssociations) {
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
}
}
return "redirect:/studies/" + studyId + "/associations";
}
else {
// File is empty so let user know
model.addAttribute("study", studyRepository.findOne(studyId));
return "empty_snpfile_upload_warning";
}
}
// Generate a empty form page to add standard snp
@RequestMapping(value = "/studies/{studyId}/associations/add_standard",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addStandardSnps(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationForm emptyForm = new SnpAssociationForm();
// Add one row by default and set description
emptyForm.getSnpFormRows().add(new SnpFormRow());
emptyForm.setMultiSnpHaplotypeDescr("Single variant");
model.addAttribute("snpAssociationForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_standard_snp_association";
}
// Generate a empty form page to add multi-snp haplotype
@RequestMapping(value = "/studies/{studyId}/associations/add_multi",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addMultiSnps(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationForm emptyForm = new SnpAssociationForm();
emptyForm.setMultiSnpHaplotype(true);
model.addAttribute("snpAssociationForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Generate a empty form page to add a interaction association
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addSnpInteraction(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationInteractionForm emptyForm = new SnpAssociationInteractionForm();
model.addAttribute("snpAssociationInteractionForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add multiple rows to table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"addRows"})
public String addRows(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long studyId) {
Integer numberOfRows = snpAssociationForm.getMultiSnpHaplotypeNum();
// Add number of rows curator selected
while (numberOfRows != 0) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
numberOfRows
}
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Add multiple rows to table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"addCols"})
public String addRows(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model,
@PathVariable Long studyId) {
Integer numberOfCols = snpAssociationInteractionForm.getNumOfInteractions();
// Add number of cols curator selected
while (numberOfCols != 0) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
numberOfCols
}
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add single row to table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"addRow"})
public String addRow(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long studyId) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Add single column to table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"addCol"})
public String addCol(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model,
@PathVariable Long studyId) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Remove row from table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"removeRow"})
public String removeRow(SnpAssociationForm snpAssociationForm,
HttpServletRequest req,
Model model,
@PathVariable Long studyId) {
//Index of value to remove
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
// Remove row
snpAssociationForm.getSnpFormRows().remove(rowId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Remove column from table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"removeCol"})
public String removeCol(SnpAssociationInteractionForm snpAssociationInteractionForm,
HttpServletRequest req,
Model model,
@PathVariable Long studyId) {
//Index of value to remove
final Integer colId = Integer.valueOf(req.getParameter("removeCol"));
// Remove col
snpAssociationInteractionForm.getSnpFormColumns().remove(colId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add new standard association/snp information to a study
@RequestMapping(value = "/studies/{studyId}/associations/add_standard",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addStandardSnps(@ModelAttribute SnpAssociationForm snpAssociationForm, @PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
@RequestMapping(value = "/studies/{studyId}/associations/add_multi",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addMultiSnps(@ModelAttribute SnpAssociationForm snpAssociationForm, @PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addSnpInteraction(@ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm,
@PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationInteractionForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationInteractionForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationInteractionForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
/* Existing association information */
// View association information
@RequestMapping(value = "/associations/{associationId}",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String viewAssociation(Model model, @PathVariable Long associationId) {
// Return association with that ID
Association associationToView = associationRepository.findOne(associationId);
// Return any association errors
AssociationFormErrorView associationFormErrorView = associationFormErrorViewService.checkAssociationForErrors(
associationToView);
model.addAttribute("errors", associationFormErrorView);
// Establish study
Long studyId = associationToView.getStudy().getId();
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
if (associationToView.getSnpInteraction() != null && associationToView.getSnpInteraction()) {
SnpAssociationInteractionForm snpAssociationInteractionForm =
snpInteractionAssociationService.createSnpAssociationInteractionForm(associationToView);
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
return "edit_snp_interaction_association";
}
else if (associationToView.getMultiSnpHaplotype() != null && associationToView.getMultiSnpHaplotype()) {
// Create form and return to user
SnpAssociationForm snpAssociationForm = singleSnpMultiSnpAssociationService.createSnpAssociationForm(
associationToView);
model.addAttribute("snpAssociationForm", snpAssociationForm);
return "edit_multi_snp_association";
}
// If attributes haven't been set determine based on locus count and risk allele count
else {
Integer locusCount = associationToView.getLoci().size();
List<RiskAllele> riskAlleles = new ArrayList<>();
for (Locus locus : associationToView.getLoci()) {
for (RiskAllele riskAllele : locus.getStrongestRiskAlleles()) {
riskAlleles.add(riskAllele);
}
}
// Case where we have SNP interaction
if (locusCount > 1) {
SnpAssociationInteractionForm snpAssociationInteractionForm =
snpInteractionAssociationService.createSnpAssociationInteractionForm(associationToView);
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
return "edit_snp_interaction_association";
}
else {
// Create form and return to user
SnpAssociationForm snpAssociationForm = singleSnpMultiSnpAssociationService.createSnpAssociationForm(
associationToView);
model.addAttribute("snpAssociationForm", snpAssociationForm);
// If editing multi-snp haplotype
if (riskAlleles.size() > 1) {
return "edit_multi_snp_association";
}
else {
return "edit_standard_snp_association";
}
}
}
}
//Edit existing association
@RequestMapping(value = "/associations/{associationId}",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String editAssociation(@ModelAttribute SnpAssociationForm snpAssociationForm,
@ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm,
@PathVariable Long associationId,
@RequestParam(value = "associationtype", required = true) String associationType) {
//Create association
Association editedAssociation = null;
// Request parameter determines how to process form and also which form to process
if (associationType.equalsIgnoreCase("interaction")) {
editedAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
}
else if (associationType.equalsIgnoreCase("standardormulti")) {
editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
}
// default to standard view
else {
editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
}
// Set ID of new association to the ID of the association we're currently editing
editedAssociation.setId(associationId);
// Set study to one currently linked to association
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
editedAssociation.setStudy(associationStudy);
// Save our association information
associationRepository.save(editedAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm != null) {
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
}
if (snpAssociationInteractionForm != null) {
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationInteractionForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationInteractionForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationInteractionForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
}
}
return "redirect:/associations/" + associationId;
}
// Add multiple rows to table
@RequestMapping(value = "/associations/{associationId}", params = {"addRows"})
public String addRowsEditMode(SnpAssociationForm snpAssociationForm,
Model model,
@PathVariable Long associationId) {
Integer numberOfRows = snpAssociationForm.getMultiSnpHaplotypeNum();
// Add number of rows curator selected
while (numberOfRows != 0) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
numberOfRows
}
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Add single row to table
@RequestMapping(value = "/associations/{associationId}", params = {"addRow"})
public String addRowEditMode(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long associationId) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Add single column to table
@RequestMapping(value = "/associations/{associationId}", params = {"addCol"})
public String addColEditMode(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model, @PathVariable Long associationId) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_snp_interaction_association";
}
// Remove row from table
@RequestMapping(value = "/associations/{associationId}", params = {"removeRow"})
public String removeRowEditMode(SnpAssociationForm snpAssociationForm,
HttpServletRequest req,
Model model,
@PathVariable Long associationId) {
//Index of value to remove
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
// Remove row
snpAssociationForm.getSnpFormRows().remove(rowId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Remove column from table
@RequestMapping(value = "/associations/{associationId}", params = {"removeCol"})
public String removeColEditMode(SnpAssociationInteractionForm snpAssociationInteractionForm,
HttpServletRequest req,
Model model,
@PathVariable Long associationId) {
//Index of value to remove
final Integer colId = Integer.valueOf(req.getParameter("removeCol"));
// Remove col
snpAssociationInteractionForm.getSnpFormColumns().remove(colId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_snp_interaction_association";
}
// Delete all associations linked to a study
@RequestMapping(value = "/studies/{studyId}/associations/delete_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String deleteAllAssociations(Model model, @PathVariable Long studyId) {
// Get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// For each association get the loci
Collection<Locus> loci = new ArrayList<Locus>();
for (Association association : studyAssociations) {
loci.addAll(association.getLoci());
}
// Delete each locus and risk allele, which in turn deletes link to genes via author_reported_gene table,
// Snps are not deleted as they may be used in other associations
for (Locus locus : loci) {
Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles();
locus.setStrongestRiskAlleles(new ArrayList<>());
for (RiskAllele riskAllele : locusRiskAlleles) {
lociAttributesService.deleteRiskAllele(riskAllele);
}
locusRepository.delete(locus);
}
// Delete associations
for (Association association : studyAssociations) {
associationRepository.delete(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
// Delete checked SNP associations
@RequestMapping(value = "/studies/{studyId}/associations/delete_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> deleteChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
Collection<Locus> loci = new ArrayList<Locus>();
Collection<Association> studyAssociations = new ArrayList<Association>();
// For each association get the loci attached
for (String associationId : associationsIds) {
Association association = associationRepository.findOne(Long.valueOf(associationId));
loci.addAll(association.getLoci());
studyAssociations.add(association);
count++;
}
// Delete each locus and risk allele, which in turn deletes link to genes via author_reported_gene table,
// Snps are not deleted as they may be used in other associations
for (Locus locus : loci) {
Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles();
locus.setStrongestRiskAlleles(new ArrayList<>());
for (RiskAllele riskAllele : locusRiskAlleles) {
lociAttributesService.deleteRiskAllele(riskAllele);
}
locusRepository.delete(locus);
}
// Delete associations
for (Association association : studyAssociations) {
associationRepository.delete(association);
}
message = "Successfully deleted " + count + " associations";
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
/* Approve snp associations */
// Approve a SNP association
@RequestMapping(value = "associations/{associationId}/approve",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String approveSnpAssociation(Model model, @PathVariable Long associationId) {
Association association = associationRepository.findOne(associationId);
// Set snpChecked attribute to true
association.setSnpChecked(true);
associationRepository.save(association);
return "redirect:/studies/" + association.getStudy().getId() + "/associations";
}
// Approve checked SNPs
@RequestMapping(value = "/studies/{studyId}/associations/approve_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> approveChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
// For each one set snpChecked attribute to true
for (String associationId : associationsIds) {
Association association = associationRepository.findOne(Long.valueOf(associationId));
association.setSnpChecked(true);
associationRepository.save(association);
count++;
}
message = "Successfully updated " + count + " associations";
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
// Approve all SNPs
@RequestMapping(value = "/studies/{studyId}/associations/approve_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String approveAll(Model model, @PathVariable Long studyId) {
// Get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// For each one set snpChecked attribute to true
for (Association association : studyAssociations) {
association.setSnpChecked(true);
associationRepository.save(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
// Validate all SNPs
@RequestMapping(value = "/studies/{studyId}/associations/validate_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String validateAll(Model model, @PathVariable Long studyId) {
// For the study get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// Maps to store returned location data, this is used as
// snpLocationMappingService process all locations linked
// to a single snp in one go
Map<String, Set<Location>> snpToLocationsMap = new HashMap<>();
// Collection to store all genomic contexts
Collection<GenomicContext> allGenomicContexts = new ArrayList<>();
// For each association get the loci
for (Association studyAssociation : studyAssociations) {
// Collection to store all errors for one association
Collection<String> associationPipelineErrors = new ArrayList<>();
Collection<Locus> studyAssociationLoci = studyAssociation.getLoci();
// For each loci get the get the SNP and author reported genes
for (Locus associationLocus : studyAssociationLoci) {
Long locusId = associationLocus.getId();
Collection<SingleNucleotidePolymorphism> snpsLinkedToLocus =
singleNucleotidePolymorphismRepository.findByRiskAllelesLociId(locusId);
Collection<Gene> authorReportedGenesLinkedToSnp = associationLocus.getAuthorReportedGenes();
// Get gene names
Collection<String> authorReportedGeneNamesLinkedToSnp = new ArrayList<>();
for (Gene authorReportedGeneLinkedToSnp : authorReportedGenesLinkedToSnp) {
authorReportedGeneNamesLinkedToSnp.add(authorReportedGeneLinkedToSnp.getGeneName());
}
// Pass rs_id and author reported genes to mapping component
for (SingleNucleotidePolymorphism snpLinkedToLocus : snpsLinkedToLocus) {
String snpRsId = snpLinkedToLocus.getRsId();
EnsemblMappingPipeline ensemblMappingPipeline =
new EnsemblMappingPipeline(snpRsId, authorReportedGeneNamesLinkedToSnp);
ensemblMappingPipeline.run_pipeline();
Collection<Location> locations = ensemblMappingPipeline.getLocations();
Collection<GenomicContext> snpGenomicContexts = ensemblMappingPipeline.getGenomicContexts();
ArrayList<String> pipelineErrors = ensemblMappingPipeline.getPipelineErrors();
// Store location information for SNP
if (!locations.isEmpty()) {
for (Location location : locations) {
// Next time we see SNP, add location to set
// This would only occur is SNP has multiple locations
if (snpToLocationsMap.containsKey(snpRsId)) {
snpToLocationsMap.get(snpRsId).add(location);
}
// First time we see a SNP store the location
else {
Set<Location> snpLocation = new HashSet<>();
snpLocation.add(location);
snpToLocationsMap.put(snpRsId, snpLocation);
}
}
}
// Store genomic context data for snp
if (!snpGenomicContexts.isEmpty()) {
allGenomicContexts.addAll(snpGenomicContexts);
}
if (!pipelineErrors.isEmpty()) {
associationPipelineErrors.addAll(pipelineErrors);
}
}
}
// Store error information
if (!associationPipelineErrors.isEmpty()) {
associationReportService.processAssociationErrors(studyAssociation, associationPipelineErrors);
}
}
// Save data
if (!snpToLocationsMap.isEmpty()) {
snpLocationMappingService.storeSnpLocation(snpToLocationsMap);
}
if (!allGenomicContexts.isEmpty()) {
snpGenomicContextMappingService.processGenomicContext(allGenomicContexts);
}
return "redirect:/studies/" + studyId + "/associations";
}
@RequestMapping(value = "/studies/{studyId}/associations/download",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String downloadStudySnps(HttpServletResponse response, Model model, @PathVariable Long studyId)
throws IOException {
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
Study study = studyRepository.findOne((studyId));
if (associations.size() == 0) {
model.addAttribute("study", study);
return "no_association_download_warning";
}
else {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String now = dateFormat.format(date);
String fileName =
study.getAuthor().concat("-").concat(study.getPubmedId()).concat("-").concat(now).concat(".tsv");
response.setContentType("text/tsv");
response.setHeader("Content-Disposition", "attachement; filename=" + fileName);
associationDownloadService.createDownloadFile(response.getOutputStream(), associations);
return "redirect:/studies/" + studyId + "/associations";
}
}
@RequestMapping(value = "/studies/{studyId}/associations/applyefotraits",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String applyStudyEFOtraitToSnps(Model model, @PathVariable Long studyId,
@RequestParam(value = "e",
required = false,
defaultValue = "false") boolean existing,
@RequestParam(value = "o",
required = false,
defaultValue = "true") boolean overwrite)
throws IOException {
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
Study study = studyRepository.findOne((studyId));
Collection<EfoTrait> efoTraits = study.getEfoTraits();
if (associations.size() == 0 || efoTraits.size() == 0) {
model.addAttribute("study", study);
return "no_association_efo_trait_warning";
}
else {
if (!existing) {
for (Association association : associations) {
if (association.getEfoTraits().size() != 0) {
model.addAttribute("study", study);
return "existing_efo_traits_warning";
}
}
}
Collection<EfoTrait> associationTraits = new ArrayList<EfoTrait>();
for (EfoTrait efoTrait : efoTraits) {
associationTraits.add(efoTrait);
}
for (Association association : associations) {
if (association.getEfoTraits().size() != 0 && !overwrite) {
for (EfoTrait trait : associationTraits) {
if (!association.getEfoTraits().contains(trait)) {
association.addEfoTrait(trait);
}
}
}
else {
association.setEfoTraits(associationTraits);
}
associationRepository.save(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
}
/* Exception handling */
@ExceptionHandler(DataIntegrityException.class)
public String handleDataIntegrityException(DataIntegrityException dataIntegrityException, Model model) {
return dataIntegrityException.getMessage();
}
// @ExceptionHandler(InvalidFormatException.class)
// public String handleInvalidFormatException(InvalidFormatException invalidFormatException, Model model, Study study){
// getLog().error("Invalid format exception", invalidFormatException);
// model.addAttribute("study", study);
// return "wrong_file_format_warning";
// @ExceptionHandler(InvalidOperationException.class)
// public String handleInvalidOperationException(InvalidOperationException invalidOperationException){
// getLog().error("Invalid operation exception", invalidOperationException);
//// model.addAttribute("study", study);
// System.out.println("Caught the exception but couldn't quite handle it");
// return "wrong_file_format_warning";
/* Model Attributes :
* Used for dropdowns in HTML forms
*/
// EFO traits
@ModelAttribute("efoTraits")
public List<EfoTrait> populateEfoTraits() {
return efoTraitRepository.findAll(sortByTraitAsc());
}
// Sort options
private Sort sortByTraitAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase());
}
private Sort sortByPvalueExponentAndMantissaAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "pvalueExponent"),
new Sort.Order(Sort.Direction.ASC, "pvalueMantissa"));
}
private Sort sortByPvalueExponentAndMantissaDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC, "pvalueExponent"),
new Sort.Order(Sort.Direction.DESC, "pvalueMantissa"));
}
private Sort sortByRsidAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "loci.strongestRiskAlleles.snp.rsId"));
}
private Sort sortByRsidDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC, "loci.strongestRiskAlleles.snp.rsId"));
}
}
|
package sexy.code;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.Executor;
public class HttPizza {
private final HttpConfig httpConfig;
private final ConverterProvider converterProvider;
private ConnectionListener connectionListener;
HttPizza(HttpConfig config, ConverterProvider converterProvider) {
this.httpConfig = config;
this.converterProvider = converterProvider;
}
public HttPizza() {
this(new HttpConfig(), DEFAULT_CONVERTER);
}
public void setConnectionListener(final ConnectionListener listener) {
connectionListener = listener;
}
public <T> Call<T> newCall(final Request request, ConverterProvider.ResponseConverter<T> converter) {
return new Call<>(new HttpEngine(httpConfig, connectionListener), converter, request);
}
public <T> Call<T> newCall(final Request request, Type type) {
return newCall(request, converterProvider.<T>responseConverter(type));
}
public Call<String> newCall(final Request request) {
return newCall(request, DEFAULT_CONVERTER.<String>responseConverter(String.class));
}
public Request.Builder newRequest() {
return new Request.Builder(converterProvider);
}
public static class Builder {
private final HttpConfig httpConfig = new HttpConfig();
private ConverterProvider converterProvider = DEFAULT_CONVERTER;
/**
* Set the connect timeout in milliseconds. The default is set to 10 seconds.
*
* @see java.net.URLConnection#setConnectTimeout(int)
*/
public Builder connectTimeout(int timeoutMillis) {
httpConfig.connectTimeout = timeoutMillis;
return this;
}
/**
* Set the read timeout in milliseconds. The default is set to 10 seconds.
*
* @see java.net.URLConnection#setReadTimeout(int)
*/
public Builder readTimeout(int timeoutMillis) {
httpConfig.readTimeout = timeoutMillis;
return this;
}
public Builder httpExecutor(Executor executor) {
httpConfig.httpExecutor = executor;
return this;
}
public Builder callbackExecutor(Executor executor) {
httpConfig.callbackExecutor = executor;
return this;
}
public Builder converterProvider(ConverterProvider provider) {
converterProvider = provider;
return this;
}
public HttPizza build() {
return new HttPizza(httpConfig, converterProvider);
}
}
private static final ConverterProvider DEFAULT_CONVERTER =
new ConverterProvider() {
@Override
protected <T> RequestConverter<T> requestConverter(Type type) {
return new RequestConverter<T>() {
@Override
public RequestBody convert(final T origin) throws IOException {
return new RequestBody() {
@Override
public String contentType() {
return "text/plain; charset=utf-8";
}
@Override
public void writeTo(BufferedOutputStream os) throws IOException {
if (origin == null) {
return;
}
os.write(origin.toString().getBytes(Util.UTF_8));
}
@Override
public long contentLength() throws IOException {
if (origin == null) {
return 0;
} else {
return origin.toString().length();
}
}
};
}
};
}
@Override
protected <T> ResponseConverter<T> responseConverter(Type type) {
return new ResponseConverter<T>() {
@Override
public T convert(ResponseBody body) throws IOException {
try {
return (T) body.string();
} catch (ClassCastException e) {
throw new IOException(e);
}
}
};
}
};
}
|
package org.jboss.test.selenium.listener;
import static org.jboss.test.selenium.utils.testng.TestInfo.STATUSES;
import static org.jboss.test.selenium.utils.testng.TestInfo.getMethodName;
import java.util.Date;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
/**
* This class is used as ITestListener in testNG tests to put test's status to the console output
*
* @author <a href="mailto:lfryc@redhat.com">Lukas Fryc</a>, <a href="mailto:pjha@redhat.com">Prabhat Jha</a>, <a
* href="mailto:ppitonak@redhat.com">Pavol Pitonak</a>
* @version $Revision$
*
*/
public class ConsoleStatusTestListener extends TestListenerAdapter {
@Override
public void onTestStart(ITestResult result) {
logStatus(result, true);
}
@Override
public void onTestFailure(ITestResult result) {
logStatus(result, false);
}
@Override
public void onTestSkipped(ITestResult result) {
logStatus(result, false);
}
@Override
public void onTestSuccess(ITestResult result) {
logStatus(result, false);
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
logStatus(result, false);
}
/**
* This method will output method name and status on the standard output
*
* @param result
* from the fine-grained listener's method such as onTestFailure(ITestResult)
* @param ctx
* test context
*/
private void logStatus(ITestResult result, boolean isTestStart) {
final String methodName = getMethodName(result);
final String status = STATUSES.get(result.getStatus());
// parameters
StringBuilder parameters = new StringBuilder("(");
if (result.getParameters() != null && result.getParameters().length != 0) {
for (int i = 0; i < result.getParameters().length; i++) {
parameters.append("\"");
parameters.append(result.getParameters()[i]);
parameters.append(i == result.getParameters().length - 1 ? "\"" : "\", ");
}
}
parameters.append(")");
// invocation count
String invocationCount = "";
if (result.getMethod().getInvocationCount() > 1) {
int count = result.getMethod().getCurrentInvocationCount();
count += isTestStart ? 1 : 0;
invocationCount = String.format(" [%d]", count);
}
// result
String message = String.format("[%tT] %s: %s%s%s", new Date(), status.toUpperCase(), methodName, parameters
.toString(), invocationCount);
System.out.println(message);
}
}
|
package one.kii.kiimate.model.core.ctl;
import one.kii.kiimate.model.core.api.DeclareExtensionApi;
import one.kii.summer.io.context.ErestHeaders;
import one.kii.summer.io.context.WriteContext;
import one.kii.summer.io.exception.BadRequest;
import one.kii.summer.io.exception.Conflict;
import one.kii.summer.io.exception.NotFound;
import one.kii.summer.io.receiver.ErestResponse;
import one.kii.summer.io.receiver.WriteController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import static one.kii.kiimate.model.core.ctl.DeclareExtensionCtl.OWNER_ID;
@RestController
@RequestMapping("/api/v1/{" + OWNER_ID + "}/extensions")
@CrossOrigin(value = "*")
public class DeclareExtensionCtl extends WriteController {
public static final String OWNER_ID = "ownerId";
@Autowired
private DeclareExtensionApi api;
@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public ResponseEntity<DeclareExtensionApi.CommitReceipt> commitForm(
@RequestHeader(ErestHeaders.REQUEST_ID) String requestId,
@RequestHeader(ErestHeaders.OPERATOR_ID) String operatorId,
@PathVariable(OWNER_ID) String ownerId,
@ModelAttribute DeclareExtensionApi.CommitForm form) {
return commit(requestId, operatorId, ownerId, form);
}
@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<DeclareExtensionApi.CommitReceipt> commitJson(
@RequestHeader(ErestHeaders.REQUEST_ID) String requestId,
@RequestHeader(ErestHeaders.OPERATOR_ID) String operatorId,
@PathVariable(OWNER_ID) String ownerId,
@RequestBody DeclareExtensionApi.CommitForm form) {
return commit(requestId, operatorId, ownerId, form);
}
private ResponseEntity<DeclareExtensionApi.CommitReceipt> commit(
String requestId,
String operatorId,
String ownerId,
DeclareExtensionApi.CommitForm form) {
try {
WriteContext context = buildContext(requestId, operatorId, ownerId);
return ErestResponse.created(requestId, api.commit(context, form));
} catch (BadRequest badRequest) {
return ErestResponse.badRequest(requestId, badRequest.getFields());
} catch (Conflict conflict) {
return ErestResponse.conflict(requestId, conflict.getKeys());
}
}
@RequestMapping(method = RequestMethod.PATCH, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<DeclareExtensionApi.CancelReceipt> cancel(
@RequestHeader(ErestHeaders.REQUEST_ID) String requestId,
@RequestHeader(ErestHeaders.OPERATOR_ID) String operatorId,
@PathVariable(OWNER_ID) String ownerId,
@ModelAttribute DeclareExtensionApi.CancelForm form) {
try {
WriteContext context = buildContext(requestId, operatorId, ownerId);
return ErestResponse.created(requestId, api.cancel(context, form));
} catch (NotFound notFound) {
return ErestResponse.notFound(requestId, notFound.getKey());
} catch (BadRequest badRequest) {
return ErestResponse.badRequest(requestId, badRequest.getFields());
}
}
}
|
package org.verapdf.model.visitor.cos.pb;
import org.apache.pdfbox.cos.*;
import org.verapdf.model.impl.pb.cos.*;
import java.io.IOException;
/**
* Implementation of {@link ICOSVisitor} which realize Visitor pattern. Implements singleton pattern.
* Current implementation create objects of abstract model implementation for corresponding objects
* of pdf box. Methods call from {@code <? extends COSBase>} objects using accept() method.
*
* @author Evgeniy Muravitskiy
*/
public final class PBCosVisitor implements ICOSVisitor {
private static final PBCosVisitor visitor = new PBCosVisitor();
private PBCosVisitor() {
// Disable default constructor
}
public static PBCosVisitor getInstance() {
return visitor;
}
/** {@inheritDoc} Create a PBCosArray for corresponding COSArray.
* @return PBCosArray object
* @see PBCosArray
*/
@Override
public Object visitFromArray(COSArray obj) throws IOException {
return new PBCosArray(obj);
}
/** {@inheritDoc} Create a PBCosBool for corresponding COSBoolean.
* @return PBCosBool object
* @see PBCosBool
*/
@Override
public Object visitFromBoolean(COSBoolean obj) throws IOException {
return PBCosBool.valueOf(obj);
}
/** {@inheritDoc} Create a PBCosFileSpecification COSDictionary if
* value of type key of {@code obj} is file specification. Otherwise
* create PBCosDict
* @return PBCosFileSpecification or PBCosDict
* @see PBCosDict
* @see PBCosFileSpecification
*/
@Override
public Object visitFromDictionary(COSDictionary obj) throws IOException {
COSName type = obj.getCOSName(COSName.TYPE);
boolean isFileSpec = type != null && COSName.FILESPEC.equals(type);
return isFileSpec ? new PBCosFileSpecification(obj) : new PBCosDict(obj);
}
/** {@inheritDoc} Create a PBCosDocument for corresponding COSDocument.
* @return PBCosDocument object
* @see PBCosDocument
*/
@Override
public Object visitFromDocument(COSDocument obj) throws IOException {
return new PBCosDocument(obj);
}
/** {@inheritDoc} Create a PBCosReal for corresponding COSFloat.
* @return PBCosReal object
* @see PBCosReal
*/
@Override
public Object visitFromFloat(COSFloat obj) throws IOException {
return new PBCosReal(obj);
}
/** {@inheritDoc} Create a PBCosInteger for corresponding COSInteger.
* @return PBCosInteger object
* @see PBCosInteger
*/
@Override
public Object visitFromInt(COSInteger obj) throws IOException {
return new PBCosInteger(obj);
}
/** {@inheritDoc} Create a PBCosName for corresponding COSName.
* @return PBCosName object
* @see PBCosName
*/
@Override
public Object visitFromName(COSName obj) throws IOException {
return new PBCosName(obj);
}
/** {@inheritDoc} Create a PBCosNull for corresponding COSNull.
* @return PBCosNull object
* @see PBCosNull
*/
@Override
public Object visitFromNull(COSNull obj) throws IOException {
return PBCosNull.getInstance();
}
/** {@inheritDoc} Create a PBCosStream for corresponding COSStream.
* @return PBCosStream object
* @see PBCosStream
*/
@Override
public Object visitFromStream(COSStream obj) throws IOException {
return new PBCosStream(obj);
}
/** {@inheritDoc} Create a PBCosString for corresponding COSString.
* @return PBCosString object
* @see PBCosString
*/
@Override
public Object visitFromString(COSString obj) throws IOException {
return new PBCosString(obj);
}
/** Notification of visiting in indirect object. Create a PBCosIndirect for corresponding
* COSObject. {@code COSObject#accept(ICOSVisitor)} not accept indirect objects - its get
* direct content and accepting it.
* @return {@link PBCosIndirect} object
* @see PBCosIndirect
* @see COSObject#accept(ICOSVisitor)
*/
public static Object visitFromObject(COSObject obj) {
return new PBCosIndirect(obj);
}
}
|
package name.abuchen.portfolio.ui.views.columns;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import name.abuchen.portfolio.model.Adaptor;
import name.abuchen.portfolio.model.Annotated;
import name.abuchen.portfolio.model.Named;
import name.abuchen.portfolio.ui.Images;
import name.abuchen.portfolio.ui.Messages;
import name.abuchen.portfolio.ui.util.viewers.Column;
import name.abuchen.portfolio.ui.util.viewers.ColumnViewerSorter;
import name.abuchen.portfolio.ui.util.viewers.StringEditingSupport;
import name.abuchen.portfolio.util.TextUtil;
public class NoteColumn extends Column
{
public NoteColumn()
{
this("note"); //$NON-NLS-1$
}
public NoteColumn(String id)
{
super(id, Messages.ColumnNote, SWT.LEFT, 22);
setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object e)
{
Annotated n = Adaptor.adapt(Annotated.class, e);
if (n != null)
return n.getNote();
Named n2 = Adaptor.adapt(Named.class, e);
return n2 != null ? n2.getNote() : null;
}
@Override
public Image getImage(Object e)
{
String note = getText(e);
return note != null && note.length() > 0 ? Images.NOTE.image() : null;
}
@Override
public String getToolTipText(Object e)
{
String note = getText(e);
return note == null || note.isEmpty() ? null : TextUtil.wordwrap(note);
}
});
setSorter(ColumnViewerSorter.create(Annotated.class, "note")); //$NON-NLS-1$
new StringEditingSupport(Annotated.class, "note").attachTo(this); //$NON-NLS-1$
}
}
|
package org.innovateuk.ifs.shibboleth.api.component;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.innovateuk.ifs.shibboleth.api.models.NewIdentity;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
@RunWith(SpringRunner.class)
public class PasswordValidationTest {
private ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
@Test
public void testValidPassword() {
assertPasswordViolations("aCtU4lGoodP4$$worD", ImmutableSet.of());
}
@Ignore
@Test
public void testNoNumberPassword() {
assertPasswordViolations("pAssWordThEFg", ImmutableSet.of(
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_NUMBER"
));
}
@Ignore
@Test
public void testLongPassword() {
assertPasswordViolations("paSSsword123456789!!kljdfsjkdfsjkldfsdfjklsdfsjkldfsjkl", ImmutableSet.of(
"PASSWORD_CANNOT_BE_SO_LONG"
));
}
@Ignore
@Test
public void testNoUppercasePassword() {
assertPasswordViolations("password123456789", ImmutableSet.of(
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_UPPER_CASE_LETTER"
));
}
@Test
@Ignore
public void testNoLowercasePassword() {
assertPasswordViolations("PASSWORD123456789", ImmutableSet.of(
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_LOWER_CASE_LETTER"
));
}
@Ignore
@Test
public void testBlankPassword() {
assertPasswordViolations("", ImmutableSet.of(
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_UPPER_CASE_LETTER",
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_NUMBER",
"PASSWORD_CANNOT_BE_SO_SHORT",
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_LOWER_CASE_LETTER",
"PASSWORD_MUST_NOT_BE_BLANK"
));
}
@Ignore
@Test
public void testShortPassword() {
assertPasswordViolations("short", ImmutableSet.of(
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_UPPER_CASE_LETTER",
"PASSWORD_MUST_CONTAIN_AT_LEAST_ONE_NUMBER",
"PASSWORD_CANNOT_BE_SO_SHORT"
));
}
private void assertPasswordViolations(String password, Set<String> expected) {
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<NewIdentity>> violations = validator.validate(new NewIdentity("test@test.com", password));
assertThat(violations.size(), equalTo(expected.size()));
assertThat(
Sets.symmetricDifference(
violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.toSet()),
expected).size(), equalTo(0));
}
}
|
package org.mycompany;
import java.util.List;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
import org.mycompany.wizard.panels.HelloWorldPanel;
import org.mycompany.installer.utils.applications.NetBeansRCPUtils;
import org.netbeans.installer.product.components.ProductConfigurationLogic;
import org.netbeans.installer.product.components.Product;
import org.netbeans.installer.utils.FileUtils;
import org.netbeans.installer.utils.helper.RemovalMode;
import org.netbeans.installer.utils.exceptions.InitializationException;
import org.netbeans.installer.utils.exceptions.InstallationException;
import org.netbeans.installer.utils.exceptions.UninstallationException;
import org.netbeans.installer.utils.progress.Progress;
import org.netbeans.installer.utils.system.shortcut.FileShortcut;
import org.netbeans.installer.utils.system.shortcut.LocationType;
import org.netbeans.installer.utils.system.shortcut.Shortcut;
import org.netbeans.installer.utils.SystemUtils;
import org.netbeans.installer.utils.LogManager;
import org.netbeans.installer.utils.ResourceUtils;
import org.netbeans.installer.utils.StreamUtils;
import org.netbeans.installer.utils.StringUtils;
import org.netbeans.installer.utils.exceptions.NativeException;
import org.netbeans.installer.wizard.Wizard;
import org.netbeans.installer.wizard.components.WizardComponent;
//normen - JDK launchers
import org.netbeans.installer.utils.system.launchers.LauncherResource;
public class ConfigurationLogic extends ProductConfigurationLogic {
private List<WizardComponent> wizardComponents;
// constructor //////////////////////////////////////////////////////////////////
public ConfigurationLogic() throws InitializationException {
wizardComponents = Wizard.loadWizardComponents(
WIZARD_COMPONENTS_URI,
getClass().getClassLoader());
}
public List<WizardComponent> getWizardComponents() {
return wizardComponents;
}
@Override
public boolean allowModifyMode() {
return false;
}
@Override
public void install(Progress progress) throws InstallationException {
final Product product = getProduct();
final File installLocation = product.getInstallationLocation();
//final FilesList filesList = product.getInstalledFiles();
String appName=ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name");
if (SystemUtils.isMacOS()) {
//normen: use parent folder of install dir for icon
File f = new File(installLocation.getParentFile(), ICON_MACOSX);
if(!f.exists()) {
try {
FileUtils.writeFile(f,
ResourceUtils.getResource(ICON_MACOSX_RESOURCE,
getClass().getClassLoader()));
getProduct().getInstalledFiles().add(f);
} catch (IOException e) {
LogManager.log(
"... cannot handle icns icon " + f, e); // NOI18N
}
}
//normen: rename executable
File shortcut=new File(installLocation.getParentFile().getParent()+"/MacOS/executable");
if(shortcut.exists()){
try {
shortcut.renameTo(new File(installLocation.getParentFile().getParent()+"/MacOS/"+appName));
getProduct().getInstalledFiles().add(shortcut.getAbsoluteFile());
} catch (IOException e) {
LogManager.log(
"... cannot rename executable " + f, e); // NOI18N
}
}
//normen: replace icon + app in Info.plist
try {
File plist=new File(installLocation.getParentFile().getParentFile(),"Info.plist");
FileUtils.modifyFile(plist, "icon.icns", appName+".icns");
FileUtils.modifyFile(plist, "executable", appName);
} catch (Exception e) {
e.printStackTrace();
}
}
if (Boolean.parseBoolean(getProperty(HelloWorldPanel.CREATE_DESKTOP_SHORTCUT_PROPERTY))) {
LogManager.logIndent(
"creating the desktop shortcut for the application"); // NOI18N
if (!SystemUtils.isMacOS()) {
try {
progress.setDetail(getString("CL.install.desktop")); // NOI18N
if (SystemUtils.isCurrentUserAdmin()) {
LogManager.log(
"... current user is an administrator " + // NOI18N
"-- creating the shortcut for all users"); // NOI18N
SystemUtils.createShortcut(
getDesktopShortcut(installLocation),
LocationType.ALL_USERS_DESKTOP);
product.setProperty(
DESKTOP_SHORTCUT_LOCATION_PROPERTY,
ALL_USERS_PROPERTY_VALUE);
} else {
LogManager.log(
"... current user is an ordinary user " + // NOI18N
"-- creating the shortcut for the current " + // NOI18N
"user only"); // NOI18N
SystemUtils.createShortcut(
getDesktopShortcut(installLocation),
LocationType.CURRENT_USER_DESKTOP);
getProduct().setProperty(
DESKTOP_SHORTCUT_LOCATION_PROPERTY,
CURRENT_USER_PROPERTY_VALUE);
}
} catch (NativeException e) {
LogManager.unindent();
LogManager.log(
getString("CL.install.error.desktop"), // NOI18N
e);
}
} else {
LogManager.log(
"... skipping this step as we're on Mac OS"); // NOI18N
}
}
LogManager.logUnindent(
"... done"); // NOI18N
// create start menu shortcut
if (Boolean.parseBoolean(getProperty(HelloWorldPanel.CREATE_START_MENU_SHORTCUT_PROPERTY))) {
LogManager.logIndent(
"creating the start menu shortcut for the application"); // NOI18N
try {
progress.setDetail(getString("CL.install.start.menu")); // NOI18N
if (SystemUtils.isCurrentUserAdmin()) {
LogManager.log(
"... current user is an administrator " + // NOI18N
"-- creating the shortcut for all users"); // NOI18N
SystemUtils.createShortcut(
getStartMenuShortcut(installLocation),
LocationType.ALL_USERS_START_MENU);
getProduct().setProperty(
START_MENU_SHORTCUT_LOCATION_PROPERTY,
ALL_USERS_PROPERTY_VALUE);
} else {
LogManager.log(
"... current user is an ordinary user " + // NOI18N
"-- creating the shortcut for the current " + // NOI18N
"user only"); // NOI18N
SystemUtils.createShortcut(
getStartMenuShortcut(installLocation),
LocationType.CURRENT_USER_START_MENU);
getProduct().setProperty(
START_MENU_SHORTCUT_LOCATION_PROPERTY,
CURRENT_USER_PROPERTY_VALUE);
}
} catch (NativeException e) {
LogManager.log(
getString("CL.install.error.start.menu"), // NOI18N
e);
}
LogManager.logUnindent(
"... done"); // NOI18N
}
//normen - JDK install - uses package on OSX
if (!SystemUtils.isMacOS()) {
File javaHome = new File(System.getProperty("java.home")).getParentFile();
File target = new File(installLocation, "jdk");
try {
FileUtils.copyFile(javaHome, target, true); //FileUtils is one of the NBI core classes, already imported in ConfigurationLogic.java
} catch (IOException e) {
throw new InstallationException("Cannot copy JDK",e);
}
LogManager.log("Setting JDK files as executable");
setExecutableContents(target, "bin");
setExecutableContents(target, "jre/bin");
setExecutableFile(target, "lib/jexec");
setExecutableFile(target, "lib/amd64/libjawt.so");
setExecutableFile(target, "lib/amd64/jli/libjli.so");
setExecutableFile(target, "lib/visualvm/platform/lib/nbexec");
// to add uninstaller logic:
SystemUtils.getNativeUtils().addUninstallerJVM(new LauncherResource(false, target));
}
}
private static void setExecutableContents(File parent, String path) {
File binDir = new File(parent, path);
File[] fileList = binDir.listFiles();
for (File file : fileList) {
try {
file.setExecutable(true, false);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private static void setExecutableFile(File parent, String path) {
File binFile = new File(parent, path);
try {
binFile.setExecutable(true, false);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void uninstall(Progress progress) throws UninstallationException {
final Product product = getProduct();
final File installLocation = product.getInstallationLocation();
//NetBeansUtils.warnNetbeansRunning(installLocation);
if (Boolean.parseBoolean(getProperty(HelloWorldPanel.CREATE_START_MENU_SHORTCUT_PROPERTY))) {
try {
progress.setDetail(getString("CL.uninstall.start.menu")); // NOI18N
final String shortcutLocation =
getProduct().getProperty(START_MENU_SHORTCUT_LOCATION_PROPERTY);
if ((shortcutLocation == null)
|| shortcutLocation.equals(CURRENT_USER_PROPERTY_VALUE)) {
SystemUtils.removeShortcut(
getStartMenuShortcut(installLocation),
LocationType.CURRENT_USER_START_MENU,
true);
} else {
SystemUtils.removeShortcut(
getStartMenuShortcut(installLocation),
LocationType.ALL_USERS_START_MENU,
true);
}
} catch (NativeException e) {
LogManager.log(
getString("CL.uninstall.error.start.menu"), // NOI18N
e);
}
}
if (Boolean.parseBoolean(getProperty(HelloWorldPanel.CREATE_DESKTOP_SHORTCUT_PROPERTY))) {
if (!SystemUtils.isMacOS()) {
try {
progress.setDetail(getString("CL.uninstall.desktop")); // NOI18N
final String shortcutLocation = getProduct().getProperty(
DESKTOP_SHORTCUT_LOCATION_PROPERTY);
if ((shortcutLocation == null)
|| shortcutLocation.equals(CURRENT_USER_PROPERTY_VALUE)) {
SystemUtils.removeShortcut(
getDesktopShortcut(installLocation),
LocationType.CURRENT_USER_DESKTOP,
false);
} else {
SystemUtils.removeShortcut(
getDesktopShortcut(installLocation),
LocationType.ALL_USERS_DESKTOP,
false);
}
} catch (NativeException e) {
LogManager.log(
getString("CL.uninstall.error.desktop"), // NOI18N
e);
}
}
}
if (Boolean.getBoolean("remove.app.userdir")) {
try {
progress.setDetail(getString("CL.uninstall.remove.userdir")); // NOI18N
LogManager.logIndent("Removing application`s userdir... ");
File userDir = NetBeansRCPUtils.getApplicationUserDirFile(installLocation);
LogManager.log("... application userdir location : " + userDir);
if (FileUtils.exists(userDir) && FileUtils.canWrite(userDir)) {
FileUtils.deleteFile(userDir, true);
FileUtils.deleteEmptyParents(userDir);
}
LogManager.log("... application userdir totally removed");
} catch (IOException e) {
LogManager.log("Can`t remove application userdir", e);
} finally {
LogManager.unindent();
}
}
//normen - JDK uninstall
if (!SystemUtils.isMacOS()) {
File jre = new File(installLocation, "jdk");
if (jre.exists()) {
try {
for (File file : FileUtils.listFiles(jre).toList()) {
FileUtils.deleteOnExit(file);
}
FileUtils.deleteOnExit(installLocation);
} catch (IOException e) {
//ignore
}
}
} else{
String appName=ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name");
File exeLink = new File(installLocation.getParentFile().getParent()+"/MacOS/"+appName);
try {
FileUtils.deleteWithEmptyParents(exeLink);
} catch (IOException ex) {
LogManager.log("Error removing app Link: " + ex);
}
}
//remove cluster/update files
/*
try {
progress.setDetail(getString("CL.uninstall.update.files")); // NOI18N
for(String cluster : CLUSTERS) {
File updateDir = new File(installLocation, cluster + File.separator + "update");
if ( updateDir.exists()) {
FileUtils.deleteFile(updateDir, true);
}
}
} catch (IOException e) {
LogManager.log(
getString("CL.uninstall.error.update.files"), // NOI18N
e);
}
*/
progress.setPercentage(Progress.COMPLETE);
}
@Override
public String getExecutable() {
if (SystemUtils.isWindows()) {
return EXECUTABLE_WINDOWS;
} else {
return EXECUTABLE_UNIX;
}
}
@Override
public String getIcon() {
if (SystemUtils.isWindows()) {
return ICON_WINDOWS;
} else if (SystemUtils.isMacOS()) {
return ICON_MACOSX;
} else {
return ICON_UNIX;
}
}
public RemovalMode getRemovalMode() {
return RemovalMode.LIST;
}
@Override
public boolean registerInSystem() {
return true;
}
@Override
public boolean requireLegalArtifactSaving() {
return false;
}
@Override
public boolean requireDotAppForMacOs() {
return true;
}
@Override
public boolean wrapForMacOs() {
return true;
}
private Shortcut getDesktopShortcut(final File directory) {
return getShortcut(
getStrings("CL.desktop.shortcut.name"), // NOI18N
getStrings("CL.desktop.shortcut.description"), // NOI18N
getString("CL.desktop.shortcut.path"), // NOI18N
directory);
}
private Shortcut getStartMenuShortcut(final File directory) {
if (SystemUtils.isMacOS()) {
return getShortcut(
getStrings("CL.start.menu.shortcut.name.macosx"), // NOI18N
getStrings("CL.start.menu.shortcut.description"), // NOI18N
getString("CL.start.menu.shortcut.path"), // NOI18N
directory);
} else {
return getShortcut(
getStrings("CL.start.menu.shortcut.name"), // NOI18N
getStrings("CL.start.menu.shortcut.description"), // NOI18N
getString("CL.start.menu.shortcut.path"), // NOI18N
directory);
}
}
private Shortcut getShortcut(
final Map<Locale, String> names,
final Map<Locale, String> descriptions,
final String relativePath,
final File location) {
final File icon;
final File executable;
if (SystemUtils.isWindows()) {
icon = new File(location, ICON_WINDOWS);
} else if (SystemUtils.isMacOS()) {
icon = new File(location, ICON_MACOSX);
} else {
icon = new File(location, ICON_UNIX);
LogManager.log("... icon file: " + icon);
if(!FileUtils.exists(icon)) {
LogManager.log("... icon file does not exist: " + icon);
InputStream is = null;
is = ResourceUtils.getResource(ICON_UNIX_RESOURCE, this.getClass().getClassLoader());
if(is!=null) {
FileOutputStream fos =null;
try {
fos = new FileOutputStream(icon);
StreamUtils.transferData(is, fos);
is.close();
fos.close();
getProduct().getInstalledFiles().add(icon);
} catch (IOException e) {
LogManager.log(e);
} finally {
if(fos!=null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
}
if (SystemUtils.isWindows()) {
executable = new File(location, EXECUTABLE_WINDOWS);
} else {
executable = new File(location, EXECUTABLE_UNIX);
}
final String name = names.get(new Locale(StringUtils.EMPTY_STRING));
final FileShortcut shortcut = new FileShortcut(name, executable);
shortcut.setNames(names);
shortcut.setDescriptions(descriptions);
shortcut.setCategories(SHORTCUT_CATEGORIES);
shortcut.setFileName(SHORTCUT_FILENAME);
shortcut.setIcon(icon);
shortcut.setRelativePath(relativePath);
shortcut.setWorkingDirectory(location);
shortcut.setModifyPath(true);
return shortcut;
}
public static final String SHORTCUT_FILENAME =
ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name") + ".desktop"; // NOI18N
public static final String[] SHORTCUT_CATEGORIES =
ResourceUtils.getString(ConfigurationLogic.class, "CL.app.categories").split(","); // NOI18N
public static final String BIN_SUBDIR =
"bin/";
public static final String EXECUTABLE_WINDOWS =
BIN_SUBDIR
+ ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name") + (SystemUtils.isCurrentJava64Bit() ? "64" : "") + ".exe"; // NOI18N
public static final String EXECUTABLE_UNIX =
BIN_SUBDIR
+ ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name"); // NOI18N
public static final String ICON_WINDOWS =
EXECUTABLE_WINDOWS;
public static final String ICON_UNIX =
ResourceUtils.getString(ConfigurationLogic.class,
"CL.unix.icon.name"); // NOI18N
public static final String ICON_UNIX_RESOURCE =
ResourceUtils.getString(ConfigurationLogic.class,
"CL.unix.icon.resource"); // NOI18N
public static final String ICON_MACOSX =
ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name") + ".icns"; // NOI18N
public static final String ICON_MACOSX_RESOURCE =
"org/mycompany/" + ResourceUtils.getString(ConfigurationLogic.class, "CL.app.name") + ".icns"; // NOI18N
public static final String WIZARD_COMPONENTS_URI =
"resource:" + // NOI18N
"org/mycompany/wizard.xml"; // NOI18N
private static final String DESKTOP_SHORTCUT_LOCATION_PROPERTY =
"desktop.shortcut.location"; // NOI18N
private static final String START_MENU_SHORTCUT_LOCATION_PROPERTY =
"start.menu.shortcut.location"; // NOI18N
private static final String ALL_USERS_PROPERTY_VALUE =
"all.users"; // NOI18N
private static final String CURRENT_USER_PROPERTY_VALUE =
"current.user"; // NOI18N
}
|
package ch.difty.scipamato.core.entity;
import static ch.difty.scipamato.core.entity.CodeClass.CodeClassFields.DESCRIPTION;
import static ch.difty.scipamato.core.entity.CodeClass.CodeClassFields.NAME;
import static org.assertj.core.api.Assertions.assertThat;
import javax.validation.ConstraintViolation;
import org.junit.Test;
import ch.difty.scipamato.common.entity.FieldEnumType;
public class CodeClassTest extends Jsr303ValidatedEntityTest<CodeClass> {
private static final String JAVAX_VALIDATION_CONSTRAINTS_NOT_NULL_MESSAGE = "{javax.validation.constraints.NotNull.message}";
private static final String DESC = "this is cc1";
@Override
protected void localSetUp() {
}
private void validateAndAssertFailure(final CodeClass cc, final FieldEnumType fieldType, final Object invalidValue,
final String msg) {
validate(cc);
assertThat(getViolations())
.isNotEmpty()
.hasSize(1);
ConstraintViolation<CodeClass> violation = getViolations()
.iterator()
.next();
assertThat(violation.getMessageTemplate()).isEqualTo(msg);
assertThat(violation.getInvalidValue()).isEqualTo(invalidValue);
assertThat(violation
.getPropertyPath()
.toString()).isEqualTo(fieldType.getName());
}
@Test
public void validatingCodeClass_beingValid_succeeds() {
verifySuccessfulValidation(new CodeClass(1, "foo", "bar"));
}
@Test
public void validatingCodeClass_withNullName_fails() {
CodeClass cc = new CodeClass(1, null, "bar");
validateAndAssertFailure(cc, NAME, null, JAVAX_VALIDATION_CONSTRAINTS_NOT_NULL_MESSAGE);
}
@Test
public void validatingCodeClass_withNullDescription_fails() {
CodeClass cc = new CodeClass(1, "foo", null);
validateAndAssertFailure(cc, DESCRIPTION, null, JAVAX_VALIDATION_CONSTRAINTS_NOT_NULL_MESSAGE);
}
@Test
public void testingToString() {
CodeClass cc = new CodeClass(1, "foo", "bar");
assertThat(cc.toString()).isEqualTo("CodeClass[id=1]");
}
@Test
public void cloning_copiesValues() {
CodeClass orig = new CodeClass(1, "cc1", DESC);
CodeClass copy = new CodeClass(orig);
assertThat(copy).isEqualToComparingFieldByField(orig);
}
@Test
public void sameValues_makeEquality() {
CodeClass cc1 = new CodeClass(1, "cc1", DESC);
CodeClass cc2 = new CodeClass(cc1);
assertEquality(cc1, cc2);
}
private void assertEquality(CodeClass cc1, CodeClass cc2) {
assertThat(cc1.equals(cc2)).isTrue();
assertThat(cc2.equals(cc1)).isTrue();
assertThat(cc1.hashCode()).isEqualTo(cc2.hashCode());
}
@Test
public void differingValues_makeInequality() {
CodeClass cc1 = new CodeClass(1, "cc1", DESC);
CodeClass cc2 = new CodeClass(2, "cc1", DESC);
CodeClass cc3 = new CodeClass(1, "cc2", DESC);
CodeClass cc4 = new CodeClass(1, "cc1", "this is cc2");
assertThat(cc1.equals(cc2)).isFalse();
assertThat(cc1.equals(cc3)).isFalse();
assertThat(cc1.equals(cc4)).isFalse();
assertThat(cc2.equals(cc3)).isFalse();
assertThat(cc2.equals(cc4)).isFalse();
assertThat(cc3.equals(cc4)).isFalse();
assertThat(cc1.hashCode()).isNotEqualTo(cc2.hashCode());
assertThat(cc1.hashCode()).isNotEqualTo(cc3.hashCode());
assertThat(cc1.hashCode()).isNotEqualTo(cc4.hashCode());
assertThat(cc2.hashCode()).isNotEqualTo(cc3.hashCode());
assertThat(cc2.hashCode()).isNotEqualTo(cc4.hashCode());
assertThat(cc3.hashCode()).isNotEqualTo(cc4.hashCode());
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void equalingToSpecialCases() {
CodeClass cc1 = new CodeClass(1, "cc1", DESC);
assertThat(cc1.equals(cc1)).isTrue();
assertThat(cc1.equals(null)).isFalse();
assertThat(cc1.equals("")).isFalse();
}
@Test
public void displayValue() {
CodeClass cc1 = new CodeClass(1, "cc1", DESC);
assertThat(cc1.getDisplayValue()).isEqualTo("cc1");
}
@Test
public void differingValues_withIdNullOnOne() {
CodeClass cc1 = new CodeClass(1, "cc1", DESC);
CodeClass cc2 = new CodeClass(null, "cc1", DESC);
assertInequality(cc1, cc2);
}
private void assertInequality(CodeClass cc1, CodeClass cc2) {
assertThat(cc1.equals(cc2)).isFalse();
assertThat(cc2.equals(cc1)).isFalse();
assertThat(cc1.hashCode()).isNotEqualTo(cc2.hashCode());
}
@Test
public void differingValues_withIdNullOnBoth() {
CodeClass cc1 = new CodeClass(null, "cc1", DESC);
CodeClass cc2 = new CodeClass(null, "cc1", DESC);
assertEquality(cc1, cc2);
}
@Test
public void differingValues_withNameNullOnOne() {
CodeClass cc1 = new CodeClass(1, null, DESC);
CodeClass cc2 = new CodeClass(1, "cc1", DESC);
assertInequality(cc1, cc2);
}
@Test
public void differingValues_withNameNullOnBoth() {
CodeClass cc1 = new CodeClass(1, null, DESC);
CodeClass cc2 = new CodeClass(1, null, DESC);
assertEquality(cc1, cc2);
}
@Test
public void differingValues_withDescriptionNullOnOne() {
CodeClass cc1 = new CodeClass(1, "cc1", DESC);
CodeClass cc2 = new CodeClass(1, "cc1", null);
assertInequality(cc1, cc2);
}
@Test
public void differingValues_withDescriptionNullOnBoth() {
CodeClass cc1 = new CodeClass(1, "cc1", null);
CodeClass cc2 = new CodeClass(1, "cc1", null);
assertEquality(cc1, cc2);
}
}
|
package org.nuxeo.ecm.platform.login;
import java.io.IOException;
import java.security.Principal;
import java.security.acl.Group;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.security.SecurityConstants;
import org.nuxeo.ecm.platform.api.login.UserIdentificationInfo;
import org.nuxeo.ecm.platform.api.login.UserIdentificationInfoCallback;
import org.nuxeo.ecm.platform.usermanager.NuxeoPrincipalImpl;
import org.nuxeo.ecm.platform.usermanager.UserManager;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.api.login.LoginComponent;
import sun.security.acl.GroupImpl;
import sun.security.acl.PrincipalImpl;
public class NuxeoLoginModule extends NuxeoAbstractServerLoginModule {
private static final Log log = LogFactory.getLog(NuxeoLoginModule.class);
private UserManager manager;
private Random random;
private NuxeoPrincipal identity;
private LoginPluginRegistry loginPluginManager;
private boolean useUserIdentificationInfoCB = false;
@Override
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options) {
// explicit cast to match the direct superclass method declaration
// (JBoss implementation)
// rather than the newer (jdk1.5) LoginModule (... Map<String,?>...)
// This is needed to avoid compilation errors when the linker wants to
// bind
// with the (interface) LoginModule method (which is abstract of course
// and cannot be called)
String useUIICB = (String) options.get("useUserIdentificationInfoCB");
if (useUIICB != null && useUIICB.equalsIgnoreCase("true")) {
useUserIdentificationInfoCB = true;
}
super.initialize(subject, callbackHandler, (Map<?, ?>) sharedState,
(Map<?, ?>) options);
random = new Random(System.currentTimeMillis());
try {
manager = Framework.getService(UserManager.class);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("UserManager implementation not found", e);
}
if (manager != null) {
log.debug("NXLoginModule initialized");
} else {
log.error("UserManager implementation not found");
}
try {
loginPluginManager = (LoginPluginRegistry) Framework.getRuntime()
.getComponent(LoginPluginRegistry.NAME);
} catch (Throwable t) {
log.error("Unable to load Plugin Registry : " + t.getMessage());
}
}
/**
* Gets the roles the user belongs to.
*/
@Override
protected Group[] getRoleSets() throws LoginException {
log.debug("getRoleSets");
if (manager == null) {
throw new LoginException("UserManager implementation not found");
}
String username = identity.getName();
List<String> roles = identity.getRoles();
Group roleSet = new GroupImpl("Roles");
log.debug("Getting roles for user=" + username);
for (String roleName : roles) {
PrincipalImpl role = new PrincipalImpl(roleName);
log.debug("Found role=" + roleName);
roleSet.addMember(role);
}
Group callerPrincipal = new GroupImpl("CallerPrincipal");
callerPrincipal.addMember(identity);
return new Group[] { roleSet, callerPrincipal };
}
private NuxeoPrincipal getPrincipal() throws LoginException {
UserIdentificationInfo userIdent = null;
// Std login/password callbacks
NameCallback nc = new NameCallback("Username: ", SecurityConstants.ANONYMOUS);
PasswordCallback pc = new PasswordCallback("Password: ", false);
// Nuxeo specific cb : handle LoginPlugin initialization
UserIdentificationInfoCallback uic = new UserIdentificationInfoCallback();
// JBoss specific cb : handle web=>ejb propagation
//SecurityAssociationCallback ac = new SecurityAssociationCallback();
//ObjectCallback oc = new ObjectCallback("UserInfo:");
// We can't check the callback handler class to know what will be supported
// because the cbh is wrapped by JAAS
// => just try and swalow exceptions
// => will be externalised to plugins via EP to avoid JBoss dependency
boolean cb_handled = false;
try {
// only try this cbh when called from the web layer
if (useUserIdentificationInfoCB) {
callbackHandler.handle(new Callback[] { uic });
// First check UserInfo CB return
userIdent = uic.getUserInfo();
cb_handled = true;
}
} catch (UnsupportedCallbackException e) {
log.debug("UserIdentificationInfoCallback is not supported");
} catch (IOException e) {
log.warn("Error calling callback handler with UserIdentificationInfoCallback : "
+ e.getMessage());
}
Principal principal = null;
Object credential = null;
if (!cb_handled) {
CallbackResult result = loginPluginManager.handleSpecifcCallbacks(callbackHandler);
if (result!=null && result.cb_handled)
{
if (result.userIdent!=null && result.userIdent.containsValidIdentity())
{
userIdent = result.userIdent;
cb_handled=true;
}
else
{
principal=result.principal;
credential = result.credential;
if (principal!=null)
cb_handled=true;
}
}
}
if (!cb_handled) {
try {
// Std CBH : will only works for L/P
callbackHandler.handle(new Callback[] { nc, pc });
cb_handled = true;
} catch (UnsupportedCallbackException e) {
LoginException le = new LoginException(
"Authentications Failure - " + e.getMessage());
le.initCause(e);
} catch (IOException e) {
LoginException le = new LoginException(
"Authentications Failure - " + e.getMessage());
le.initCause(e);
}
}
try {
// Login via the Web Interface : may be using a plugin
if (userIdent != null && userIdent.containsValidIdentity()) {
NuxeoPrincipal nxp = validateUserIdentity(userIdent);
if (nxp != null) {
sharedState.put("javax.security.auth.login.name",
nxp.getName());
sharedState.put("javax.security.auth.login.password",
userIdent);
}
return nxp;
}
if (LoginComponent.isSystemLogin(principal)) {
return new SystemPrincipal(principal.getName());
}
// if (principal instanceof NuxeoPrincipal) { // a nuxeo principal
// return validatePrincipal((NuxeoPrincipal) principal);
// } else
if (principal != null) { // a non null principal
String password = null;
if (credential instanceof char[]) {
password = new String((char[]) credential);
} else if (credential != null) {
password = credential.toString();
}
return validateUsernamePassword(principal.getName(), password);
} else { // we don't have a principal - try the username &
// password
String username = nc.getName();
if (username == null) {
return null;
}
char[] password = pc.getPassword();
return validateUsernamePassword(username,
password != null ? new String(password) : null);
}
} catch (LoginException e) {
throw e;
} catch (Exception e) {
// jboss catches LoginException, so show it at least in the logs
log.error(e);
LoginException le = new LoginException("Authentication Failure - "
+ e.getMessage());
le.initCause(e);
throw le;
}
}
public boolean login() throws LoginException {
if (manager == null) {
throw new LoginException("UserManager implementation not found");
}
super.loginOk = false;
identity = getPrincipal();
if (identity == null) { // auth failed
throw new LoginException("Authentication Failed");
}
super.loginOk = true;
log.trace("User '" + identity + "' authenticated");
/*if( getUseFirstPass() == true )
{ // Add the username and password to the shared state map
// not sure it's needed
sharedState.put("javax.security.auth.login.name", identity.getName());
sharedState.put("javax.security.auth.login.password", identity.getPassword());
}*/
return true;
}
@Override
public Principal getIdentity() {
return identity;
}
public Principal createIdentity(String name) throws LoginException {
log.debug("createIdentity: " + name);
try {
NuxeoPrincipal principal = null;
if (manager == null) {
principal = new NuxeoPrincipalImpl(name);
} else {
principal = manager.getPrincipal(name);
if (principal == null) {
throw new LoginException(String.format(
"principal %s does not exist", name));
}
}
String principalId = String.valueOf(random.nextLong());
principal.setPrincipalId(principalId);
return principal;
} catch (Exception e) {
log.error("createIdentity failed", e);
LoginException le = new LoginException("createIdentity failed for user " + name);
le.initCause(e);
throw le;
}
}
private NuxeoPrincipal validateUserIdentity(UserIdentificationInfo userIdent)
throws Exception {
String loginPluginName = userIdent.getLoginPluginName();
if (loginPluginName == null) {
// we don't use a specific plugin
if (manager.checkUsernamePassword(userIdent.getUserName(),
userIdent.getPassword())) {
return (NuxeoPrincipal) createIdentity(userIdent.getUserName());
} else {
return null;
}
} else {
LoginPlugin lp = loginPluginManager.getPlugin(loginPluginName);
if (lp == null) {
log.error("Can't authenticate against a null loginModul plugin");
return null;
}
// set the parameters and reinit if needed
LoginPluginDescriptor lpd = loginPluginManager.getPluginDescriptor(loginPluginName);
if (!lpd.getInitialized()) {
Map<String, String> existingParams = lp.getParameters();
if (existingParams == null) {
existingParams = new HashMap<String, String>();
}
Map<String, String> loginParams = userIdent.getLoginParameters();
if (loginParams != null) {
existingParams.putAll(loginParams);
}
boolean init = lp.initLoginModule();
if (init) {
lpd.setInitialized(true);
} else {
log.error("Unable to initialize LoginModulePlugin "
+ lp.getName());
return null;
}
}
String username = lp.validatedUserIdentity(userIdent);
if (username == null) {
return null;
} else {
return (NuxeoPrincipal) createIdentity(username);
}
}
}
private NuxeoPrincipal validateUsernamePassword(String username, String password)
throws Exception {
if (!manager.checkUsernamePassword(username, password)) {
return null;
}
return (NuxeoPrincipal) createIdentity(username);
}
private NuxeoPrincipal validatePrincipal(NuxeoPrincipal principal) throws Exception {
if (!manager.checkUsernamePassword(principal.getName(), principal.getPassword())) {
return null;
}
return principal;
}
}
|
package cx2x.translator.transformation.claw.parallelize;
import cx2x.translator.language.ClawLanguage;
import cx2x.translator.language.helper.TransformationHelper;
import cx2x.xcodeml.exception.IllegalTransformationException;
import cx2x.xcodeml.helper.XnodeUtil;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Transformer;
import cx2x.xcodeml.xnode.*;
import xcodeml.util.XmOption;
import java.util.List;
/**
* The parallelize forward transformation applies the changes in the subroutine
* signatures to function call and function in which the call is nested if
* needed.
*
* During the tranformation, a new "CLAW" XcodeML module file is generated
* if the transformation has to be applied accross several file unit. This
* file will be located in the same directory as the original XcodeML module
* file and has the following naming structure: module_name.claw.xmod
*
* @author clementval
*/
public class ParallelizeForward extends Transformation {
private final ClawLanguage _claw;
private Xnode _fctCall;
private XfunctionType _fctType;
private Xmod _mod = null;
private boolean _localFct = false;
private boolean _flatten = false;
private Xnode _innerDoStatement;
private Xnode _outerDoStatement;
private String _calledFctName; // For topological sorting
private String _callingFctName; // For topological sorting
/**
* Constructs a new Parallelize transformation triggered from a specific
* pragma.
* @param directive The directive that triggered the define transformation.
*/
public ParallelizeForward(ClawLanguage directive) {
super(directive);
_claw = directive; // Keep information about the claw directive here
}
@Override
public boolean analyze(XcodeProgram xcodeml, Transformer transformer) {
Xnode next = XnodeUtil.getNextSibling(_claw.getPragma());
if(next == null){
xcodeml.addError("Directive is not followed by a valid statement.",
_claw.getPragma().getLineNo());
return false;
}
if(next.Opcode() == Xcode.EXPRSTATEMENT
|| next.Opcode() == Xcode.FASSIGNSTATEMENT)
{
_fctCall = next.find(Xcode.FUNCTIONCALL);
if(_fctCall != null){
return analyzeForward(xcodeml);
}
} else if (next.Opcode() == Xcode.FDOSTATEMENT) {
_outerDoStatement = next;
return analyzeForwardWithDo(xcodeml, next);
}
xcodeml.addError("Directive is not followed by a valid statement.",
_claw.getPragma().getLineNo());
return false;
}
/**
* Analyze the directive when it is used just before a do statement.
* @param xcodeml Current XcodeML file unit.
* @param doStmt The do statement following the pragma.
* @return True if the analysis succeed. False otherwise.
*/
private boolean analyzeForwardWithDo(XcodeProgram xcodeml, Xnode doStmt){
_flatten = true;
if(doStmt == null){
xcodeml.addError("Directive is not followed by do statement.",
_claw.getPragma().getLineNo());
return false;
}
// Try to locate the fct call inside of the do statements. Can be nested.
return analyzeNestedDoStmts(xcodeml, doStmt);
}
/**
* Recursively analyze nested do statements in order to find the call
* statements.
* @param xcodeml Current XcodeML file unit.
* @param doStmt First do statement to start the analyzis.
* @return True if the analysis succed. False otehrwise.
*/
private boolean analyzeNestedDoStmts(XcodeProgram xcodeml, Xnode doStmt){
_innerDoStatement = doStmt;
Xnode body = doStmt.find(Xcode.BODY);
if(body == null){
xcodeml.addError("Cannot locate function call.",
_claw.getPragma().getLineNo());
return false;
}
for(Xnode n : body.getChildren()){
if(n.Opcode() == Xcode.FDOSTATEMENT){
return analyzeNestedDoStmts(xcodeml, n);
} else if(n.Opcode() != Xcode.FPRAGMASTATEMENT
&& n.Opcode() != Xcode.EXPRSTATEMENT)
{
xcodeml.addError("Only pragmas, comments and function calls allowed " +
"in the do statements.",
_claw.getPragma().getLineNo());
return false;
} else if (n.Opcode() == Xcode.EXPRSTATEMENT
|| n.Opcode() == Xcode.FASSIGNSTATEMENT)
{
_fctCall = n.find(Xcode.FUNCTIONCALL);
if(_fctCall != null){
return analyzeForward(xcodeml);
}
}
}
xcodeml.addError("Function call not found.", _claw.getPragma().getLineNo());
return false;
}
/**
* Analyze the directive when it is used just before a function call.
* @param xcodeml Current XcodeML file unit.
* @return True if the analysis succeed. False otherwise.
*/
private boolean analyzeForward(XcodeProgram xcodeml){
if(_fctCall == null){
xcodeml.addError("Directive is not followed by a fct call.",
_claw.getPragma().getLineNo());
return false;
}
_calledFctName = _fctCall.find(Xcode.NAME).getValue();
XfunctionDefinition fctDef = XnodeUtil.findFunctionDefinition(
xcodeml.getGlobalDeclarationsTable(), _calledFctName);
XfunctionDefinition parentFctDef =
XnodeUtil.findParentFunction(_claw.getPragma());
if(parentFctDef == null){
xcodeml.addError("Parellilize directive is not nested in a " +
"function/subroutine.", _claw.getPragma().getLineNo());
return false;
}
XmoduleDefinition parentModule = XnodeUtil.findParentModule(parentFctDef);
if(parentModule == null){
xcodeml.addError("Called function is not nested in a module. Abort",
_claw.getPragma().getLineNo());
return false;
}
String fctType = _fctCall.find(Xcode.NAME).getAttribute(Xattr.TYPE);
Xtype rawType = xcodeml.getTypeTable().get(fctType);
if(rawType instanceof XfunctionType){
_fctType = (XfunctionType)rawType;
} else if (rawType instanceof XbasicType
&& fctType.startsWith(XbasicType.PREFIX_PROCEDURE))
{
/* If type is a FbasicType element for a type-bound procedure, we have to
* find the correct function in the typeTable.
* TODO if there is a rename. */
Xid id = parentModule.getSymbolTable().get(_calledFctName);
_fctType = (XfunctionType)xcodeml.getTypeTable().get(id.getType());
} else {
xcodeml.addError("Unsupported type of XcodeML/F element for the function "
+ _calledFctName, _claw.getPragma().getLineNo());
return false;
}
/* Workaround for a bug in OMNI Compiler. Look at test case
* claw/abstraction10. In this test case, the XcodeML/F intermediate
* representation for the function call points to a FfunctionType element
* with no parameters. Thus, we have to find the correct FfunctionType
* for the same function/subroutine with the same name in the module
* symbol table. */
if(_fctType.getParameterNb() == 0){
// If not, try to find the correct FfunctionType in the module definitions
Xid id = parentModule.getSymbolTable().get(_calledFctName);
_fctType = (XfunctionType)xcodeml.getTypeTable().get(id.getType());
if(_fctType == null){
xcodeml.addError("Called function cannot be found in the same module ",
_claw.getPragma().getLineNo());
return false;
}
}
// end of workaround
_callingFctName = parentFctDef.getName().getValue();
if(_fctType != null && fctDef != null){
_localFct = true;
} else {
List<Xdecl> localScopeUsesStmt = XnodeUtil.getAllUse(parentFctDef);
List<Xdecl> moduleScoptUsesStmt =
XnodeUtil.getAllUse(parentModule);
if(findInModule(localScopeUsesStmt) || findInModule(moduleScoptUsesStmt)){
return true;
}
xcodeml.addError("Function signature not found in the current module.",
_claw.getPragma().getLineNo());
return false;
}
return true;
}
/**
* Find a function in modules.
* @param useDecls List of all USE statement declarations available for
* search.
* @return True if the function was found. False otherwise.
*/
private boolean findInModule(List<Xdecl> useDecls){
for(Xdecl d : useDecls){
// Check whether a CLAW file is available.
_mod = TransformationHelper.
locateClawModuleFile(d.getAttribute(Xattr.NAME));
if(_mod != null){
// debug information
if(XmOption.isDebugOutput()){
System.out.println("Reading CLAW module file: " + _mod.getFullPath());
}
if(_mod.getIdentifiers().contains(_calledFctName)){
String type = _mod.getIdentifiers().get(_calledFctName).
getAttribute(Xattr.TYPE);
_fctType = (XfunctionType) _mod.getTypeTable().get(type);
if(_fctType != null){
_calledFctName = null;
return true;
}
}
}
}
return false;
}
@Override
public void transform(XcodeProgram xcodeml, Transformer transformer,
Transformation other) throws Exception
{
if(_flatten){
transformFlatten(xcodeml, transformer);
} else {
transformStd(xcodeml, transformer);
}
// Delete pragma
_claw.getPragma().delete();
}
/**
* Do the flatten transformation for the forward directive. This
* transformation adapt the function call nested in the do statements and
* removes those do statements. The containing subroutine is not adapted.
* @param xcodeml Current XcodeML file unit.
* @param transformer Current transformer.
* @throws Exception If something goes wrong.
*/
private void transformFlatten(XcodeProgram xcodeml, Transformer transformer)
throws Exception
{
XnodeUtil.extractBody(_innerDoStatement, _outerDoStatement);
_outerDoStatement.delete();
transformStd(xcodeml, transformer);
}
/**
* Do the standard transformation for the forward directive. This
* transformation adapt the function call and replicates any necessary changes
* to the containing subroutine.
* @param xcodeml Current XcodeML file unit.
* @param transformer Current transformer.
* @throws Exception If something goes wrong.
*/
private void transformStd(XcodeProgram xcodeml, Transformer transformer)
throws Exception
{
XfunctionDefinition fDef = XnodeUtil.findParentFunction(_claw.getPragma());
if(fDef == null){
throw new IllegalTransformationException("Parallelize directive is not " +
"nested in a function/subroutine.", _claw.getPragma().getLineNo());
}
XfunctionType parentFctType = (XfunctionType)xcodeml.getTypeTable().
get(fDef.getName().getAttribute(Xattr.TYPE));
List<Xnode> params = _fctType.getParams().getAll();
List<Xnode> args = _fctCall.find(Xcode.ARGUMENTS).getChildren();
// 1. Adapt function call with potential new arguments
for(int i = args.size(); i < params.size(); i++){
Xnode p = params.get(i);
String var = p.getValue();
String type;
if(!fDef.getSymbolTable().contains(var)){
if(_flatten){
throw new IllegalTransformationException("Variable " + var + " must" +
" be locally defined where the last call to parallelize if made.",
_claw.getPragma().getLineNo());
}
// Size variable have to be declared
XbasicType intTypeIntentIn = XnodeUtil.createBasicType(xcodeml,
xcodeml.getTypeTable().generateIntegerTypeHash(),
Xname.TYPE_F_INT, Xintent.IN);
xcodeml.getTypeTable().add(intTypeIntentIn);
XnodeUtil.createIdAndDecl(var,
intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, fDef, xcodeml);
type = intTypeIntentIn.getType();
XnodeUtil.createAndAddParam(xcodeml, var, type, parentFctType);
} else {
// Var exists already. Add to the parameters if not here.
type = fDef.getSymbolTable().get(var).getType();
/* If flatten mode, we do not add extra parameters to the function
* definition */
if(!_flatten) {
XnodeUtil.
createAndAddParamIfNotExists(xcodeml, var, type, parentFctType);
}
}
// Add variable in the function call
Xnode arg = XnodeUtil.createNamedValue(var, xcodeml);
Xnode namedValVar = XnodeUtil.createVar(type, var, Xscope.LOCAL, xcodeml);
arg.appendToChildren(namedValVar, false);
_fctCall.find(Xcode.ARGUMENTS).appendToChildren(arg, false);
}
// In flatten mode, arguments are demoted if needed.
if(_flatten){
Xnode arguments = _fctCall.find(Xcode.ARGUMENTS);
for(Xnode arg : arguments.getChildren()){
if(arg.Opcode() == Xcode.FARRAYREF
&& arg.find(Xcode.INDEXRANGE) != null)
{
Xnode var = arg.find(Xcode.VARREF, Xcode.VAR);
if(var != null){
XnodeUtil.insertAfter(arg, var.cloneObject());
arg.delete();
}
}
}
} else {
// 2. Adapt function/subroutine in which the function call is nested
for(Xnode pBase : _fctType.getParams().getAll()){
for(Xnode pUpdate : parentFctType.getParams().getAll()){
if(pBase.getValue().equals(pUpdate.getValue())){
XbasicType typeBase = (_localFct) ? (XbasicType)
xcodeml.getTypeTable().get(pBase.getAttribute(Xattr.TYPE)) :
(XbasicType) _mod.getTypeTable().
get(pBase.getAttribute(Xattr.TYPE));
XbasicType typeToUpdate = (XbasicType)xcodeml.getTypeTable().
get(pUpdate.getAttribute(Xattr.TYPE));
// Types have different dimensions
if(typeBase.getDimensions() > typeToUpdate.getDimensions()){
String type = XnodeUtil.duplicateWithDimension(typeBase,
typeToUpdate, xcodeml);
pUpdate.setAttribute(Xattr.TYPE, type);
Xid id = fDef.getSymbolTable().get(pBase.getValue());
if(id != null){
id.setAttribute(Xattr.TYPE, type);
}
Xdecl varDecl = fDef.getDeclarationTable().get(pBase.getValue());
if(varDecl != null){
varDecl.find(Xcode.NAME).setAttribute(Xattr.TYPE, type);
}
}
}
}
}
if(!parentFctType.getBooleanAttribute(Xattr.IS_PRIVATE)){
// 3. Replicate the change in a potential module file
XmoduleDefinition modDef = XnodeUtil.findParentModule(fDef);
XnodeUtil.updateModuleSignature(xcodeml, fDef, parentFctType, modDef,
_claw, transformer);
}
}
}
@Override
public boolean canBeTransformedWith(Transformation other) {
return false; // independent transformation
}
/**
* Get the called fct name.
* @return Fct name.
*/
public String getCalledFctName(){
return _calledFctName;
}
/**
* Get the parent fct name.
* @return Fct name.
*/
public String getCallingFctName(){
return _callingFctName;
}
}
|
package com.jenjinstudios.world.client.message;
import com.jenjinstudios.client.net.ClientUser;
import com.jenjinstudios.client.net.LoginTracker;
import com.jenjinstudios.core.io.Message;
import com.jenjinstudios.core.io.MessageRegistry;
import com.jenjinstudios.world.World;
import com.jenjinstudios.world.client.WorldClient;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
/**
* @author Caleb Brinkman
*/
public class ExecutableWorldLoginResponseTest
{
@Test
public void testMessageExecution() {
MessageRegistry messageRegistry = MessageRegistry.getInstance();
Message message = messageRegistry.createMessage("WorldLoginResponse");
message.setArgument("id", 0);
message.setArgument("success", true);
message.setArgument("loginTime", 0l);
message.setArgument("xCoordinate", 0.0);
message.setArgument("yCoordinate", 0.0);
message.setArgument("zoneNumber", 0);
WorldClient worldClient = mock(WorldClient.class);
World world = mock(World.class);
LoginTracker loginTracker = mock(LoginTracker.class);
when(loginTracker.isLoggedIn()).thenReturn(true);
when(worldClient.getWorld()).thenReturn(world);
when(worldClient.getUser()).thenReturn(new ClientUser("Foo", "Bar"));
when(worldClient.getLoginTracker()).thenReturn(loginTracker);
ExecutableWorldLoginResponse response = new ExecutableWorldLoginResponse(worldClient, message);
response.runImmediate();
response.runDelayed();
verify(loginTracker).setLoggedIn(true);
verify(loginTracker).setLoggedInTime(0l);
verify(worldClient).setPlayer(any());
verify(world).addObject(any(), eq(0));
}
}
|
package net.nemerosa.ontrack.service;
import net.nemerosa.ontrack.extension.api.DecorationExtension;
import net.nemerosa.ontrack.extension.api.ExtensionManager;
import net.nemerosa.ontrack.model.security.SecurityService;
import net.nemerosa.ontrack.model.structure.Decoration;
import net.nemerosa.ontrack.model.structure.DecorationService;
import net.nemerosa.ontrack.model.structure.Decorator;
import net.nemerosa.ontrack.model.structure.ProjectEntity;
import net.nemerosa.ontrack.service.support.ErrorDecorator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class DecorationServiceImpl implements DecorationService {
private final ExtensionManager extensionManager;
private final List<Decorator> builtinDecorators;
private final SecurityService securityService;
private final ErrorDecorator errorDecorator = new ErrorDecorator();
@Autowired
public DecorationServiceImpl(ExtensionManager extensionManager, List<Decorator> builtinDecorators, SecurityService securityService) {
this.extensionManager = extensionManager;
this.builtinDecorators = builtinDecorators.stream()
.filter(decorator -> !(decorator instanceof DecorationExtension))
.collect(Collectors.toList());
this.securityService = securityService;
}
@Override
public List<Decoration> getDecorations(ProjectEntity entity) {
// Downloading a decoration with the current security context
Function<Decorator, Decoration> securedDecoratorFunction = securityService.runner(
decorator -> getDecoration(entity, decorator)
);
List<Decoration> decorations = new ArrayList<>();
// Built-in decorations
decorations.addAll(
builtinDecorators.parallelStream()
// ... and gets the decoration
.map(securedDecoratorFunction)
// ... and excludes the null ones
.filter(decoration -> decoration != null)
.collect(Collectors.toList())
);
// Extended decorations
decorations.addAll(
extensionManager.getExtensions(DecorationExtension.class)
.parallelStream()
// ... and filters per entity
.filter(decorator -> decorator.getScope().contains(entity.getProjectEntityType()))
// ... and gets the decoration
.map(securedDecoratorFunction)
// ... and excludes the null ones
.filter(decoration -> decoration != null)
.collect(Collectors.toList())
);
return decorations;
}
/**
* Gets the decoration for an entity, and returns an "error" decoration in case of problem.
*/
protected Decoration getDecoration(ProjectEntity entity, Decorator decorator) {
try {
return decorator.getDecoration(entity);
} catch (Exception ex) {
return errorDecorator.getDecoration(ex);
}
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
package org.opennms.netmgt.capsd.plugins;
import java.net.InetAddress;
import java.util.Map;
import net.sourceforge.jradiusclient.RadiusAttribute;
import net.sourceforge.jradiusclient.RadiusAttributeValues;
import net.sourceforge.jradiusclient.RadiusClient;
import net.sourceforge.jradiusclient.RadiusPacket;
import net.sourceforge.jradiusclient.exception.InvalidParameterException;
import net.sourceforge.jradiusclient.exception.RadiusException;
import net.sourceforge.jradiusclient.util.ChapUtil;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.capsd.AbstractPlugin;
import org.opennms.netmgt.utils.ParameterMap;
public final class RadiusAuthPlugin extends AbstractPlugin {
/**
* </P>
* The protocol name that is tested by this plugin.
* </P>
*/
private final static String PROTOCOL_NAME = "RadiusAuth";
/**
* Number of milliseconds to wait before timing out a radius AUTH request
*/
public static final int DEFAULT_TIMEOUT = 5000;
/**
* Default number of times to retry a test
*/
public static final int DEFAULT_RETRY = 0;
/**
* Default radius authentication port
*/
public static final int DEFAULT_AUTH_PORT = 1812;
/**
* Default radius accounting port
*/
public static final int DEFAULT_ACCT_PORT = 1813;
/**
* Default radius authentication type
*/
public static final String DEFAULT_AUTH_TYPE = "pap";
/**
* Default user
*/
public static final String DEFAULT_USER = "OpenNMS";
/**
* Default password
*/
public static final String DEFAULT_PASSWORD = "OpenNMS";
/**
* Default secret
*/
public static final String DEFAULT_SECRET = "secret";
/**
*
* Default NAS_ID
*/
public static final String DEFAULT_NAS_ID = "opennms";
/**
*
* @param host
* The address for the radius server test.
* @param authport
* Radius authentication port
* @param acctport
* Radius accounting port - required by jradius
* but not explicitly checked
* @param authType
* authentication type - pap or chap
* @param user
* user for Radius authentication
* @param password
* password for Radius authentication
* @param secret
* Radius shared secret
* @param timeout
* Timeout in milliseconds
* @param retry
* Number of times to retry
*
* @param nasid
* NAS Identifier to use
*
* @return True if server, false if not.
*/
private boolean isRadius(InetAddress host, int authport, int acctport, String authType,
String user, String password, String secret, String nasid,
int retry, int timeout) {
boolean isRadiusServer = false;
Category log = ThreadCategory.getInstance(getClass());
RadiusClient rc = null;
try {
rc = new RadiusClient(host.getCanonicalHostName(), authport ,acctport, secret, timeout);
} catch(RadiusException rex) {
log.info(getClass().getName() + ": Radius Exception: " + rex.getMessage());
return isRadiusServer;
} catch(InvalidParameterException ivpex) {
log.error(getClass().getName() + ": Radius parameter exception: " + ivpex.getMessage());
return isRadiusServer;
}
for (int attempts = 0; attempts <= retry; attempts++) {
try {
ChapUtil chapUtil = new ChapUtil();
RadiusPacket accessRequest = new RadiusPacket(RadiusPacket.ACCESS_REQUEST);
RadiusAttribute userNameAttribute;
RadiusAttribute nasIdAttribute;
nasIdAttribute = new RadiusAttribute(RadiusAttributeValues.NAS_IDENTIFIER,nasid.getBytes());
userNameAttribute = new RadiusAttribute(RadiusAttributeValues.USER_NAME,user.getBytes());
accessRequest.setAttribute(userNameAttribute);
accessRequest.setAttribute(nasIdAttribute);
if(authType.equalsIgnoreCase("chap")){
byte[] chapChallenge = chapUtil.getNextChapChallenge(16);
accessRequest.setAttribute(new RadiusAttribute(RadiusAttributeValues.CHAP_PASSWORD, chapEncrypt(password, chapChallenge, chapUtil)));
accessRequest.setAttribute(new RadiusAttribute(RadiusAttributeValues.CHAP_CHALLENGE, chapChallenge));
}else{
accessRequest.setAttribute(new RadiusAttribute(RadiusAttributeValues.USER_PASSWORD,password.getBytes()));
}
RadiusPacket accessResponse = rc.authenticate(accessRequest);
if ( ( accessResponse.getPacketType() == RadiusPacket.ACCESS_ACCEPT ) |
( accessResponse.getPacketType() == RadiusPacket.ACCESS_CHALLENGE ) |
( accessResponse.getPacketType() == RadiusPacket.ACCESS_REJECT ) ){
isRadiusServer = true;
if (log.isDebugEnabled()) {
log.debug(getClass().getName() + ": Discovered Radius service on: " + host.getCanonicalHostName());
}
break;
}
} catch (InvalidParameterException ivpex){
log.error(getClass().getName() + ": Invalid Radius Parameter: " + ivpex);
} catch (RadiusException radex){
log.info(getClass().getName() + ": Radius Exception : " + radex);
}
}
return isRadiusServer;
}
/**
* Returns the name of the protocol that this plugin checks on the target
* system for support.
*
* @return The protocol name for this plugin.
*/
public String getProtocolName() {
return PROTOCOL_NAME;
}
/**
* Returns true if the protocol defined by this plugin is supported. If the
* protocol is not supported then a false value is returned to the caller.
*
* @param address
* The address to check for support.
*
* @return True if the protocol is supported by the address.
*/
public boolean isProtocolSupported(InetAddress address) {
return isRadius(address, DEFAULT_AUTH_PORT, DEFAULT_ACCT_PORT, DEFAULT_AUTH_TYPE,
DEFAULT_USER, DEFAULT_PASSWORD, DEFAULT_SECRET, DEFAULT_NAS_ID,
DEFAULT_RETRY, DEFAULT_TIMEOUT);
}
/**
* <p>
* Returns true if the protocol defined by this plugin is supported. If the
* protocol is not supported then a false value is returned to the caller.
* The qualifier map passed to the method is used by the plugin to return
* additional information by key-name. These key-value pairs can be added to
* service events if needed.
* </p>
*
* <p>
* In addition, the input qualifiers map also provides information about how
* the plugin should contact the remote server. The plugin may check the
* qualifier map for specific elements and then adjust its behavior as
* necessary
* </p>
*
* @param address
* The address to check for support.
* @param qualifiers
* The map where qualification are set by the plugin.
*
* @return True if the protocol is supported by the address.
*/
public boolean isProtocolSupported(InetAddress address, Map<String, Object> qualifiers) {
int authport = DEFAULT_AUTH_PORT;
int acctport = DEFAULT_ACCT_PORT;
String authType = DEFAULT_AUTH_TYPE;
int timeout = DEFAULT_TIMEOUT;
int retry = DEFAULT_RETRY;
String user = DEFAULT_USER;
String password = DEFAULT_PASSWORD;
String secret = DEFAULT_SECRET;
String nasid = DEFAULT_NAS_ID;
if (qualifiers != null) {
authport = ParameterMap.getKeyedInteger(qualifiers, "authport", DEFAULT_AUTH_PORT);
acctport = ParameterMap.getKeyedInteger(qualifiers, "acctport", DEFAULT_ACCT_PORT);
authType = ParameterMap.getKeyedString(qualifiers, "authtype", DEFAULT_AUTH_TYPE);
timeout = ParameterMap.getKeyedInteger(qualifiers, "timeout", DEFAULT_TIMEOUT);
retry = ParameterMap.getKeyedInteger(qualifiers, "retry", DEFAULT_RETRY);
user = ParameterMap.getKeyedString(qualifiers, "user", DEFAULT_USER);
password = ParameterMap.getKeyedString(qualifiers, "password", DEFAULT_PASSWORD);
secret = ParameterMap.getKeyedString(qualifiers, "secret", DEFAULT_SECRET);
nasid = ParameterMap.getKeyedString(qualifiers, "nasid", DEFAULT_NAS_ID);
}
return isRadius(address, authport, acctport, authType,
user, password, secret, nasid,
retry, timeout);
}
/**
* Encrypt password using chap challenge
*
* @param plainText
* plain text password
* @param chapChallenge
* chap challenge
* @param chapUtil
* ref ChapUtil
*
* @return encrypted chap password
*/
private static byte[] chapEncrypt(final String plainText,
final byte[] chapChallenge,
final ChapUtil chapUtil){
byte chapIdentifier = chapUtil.getNextChapIdentifier();
byte[] chapPassword = new byte[17];
chapPassword[0] = chapIdentifier;
System.arraycopy(ChapUtil.chapEncrypt(chapIdentifier, plainText.getBytes(),chapChallenge),
0, chapPassword, 1, 16);
return chapPassword;
}
}
|
package nak.nakloidGUI.gui;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Shell;
import nak.nakloidGUI.NakloidGUI;
import nak.nakloidGUI.actions.displays.DisplayHorizontalZoomInAction;
import nak.nakloidGUI.actions.displays.DisplayHorizontalZoomOutAction;
import nak.nakloidGUI.actions.displays.DisplayLogAction;
import nak.nakloidGUI.actions.displays.DisplayNotesAction;
import nak.nakloidGUI.actions.displays.DisplayNotesWindowAction;
import nak.nakloidGUI.actions.displays.DisplayPitchesAction;
import nak.nakloidGUI.actions.displays.DisplayVerticalZoomInAction;
import nak.nakloidGUI.actions.displays.DisplayVerticalZoomOutAction;
import nak.nakloidGUI.actions.displays.DisplayZoomInAction;
import nak.nakloidGUI.actions.displays.DisplayZoomOutAction;
import nak.nakloidGUI.actions.editors.AddNoteAction;
import nak.nakloidGUI.actions.editors.EditLyricsAction;
import nak.nakloidGUI.actions.executors.BuildAction;
import nak.nakloidGUI.actions.executors.BuildAndPlayAction;
import nak.nakloidGUI.actions.executors.ExportWavAction;
import nak.nakloidGUI.actions.executors.InitializePitchesAction;
import nak.nakloidGUI.actions.executors.PlayAction;
import nak.nakloidGUI.actions.files.ExitAction;
import nak.nakloidGUI.actions.files.ExportVocalAction;
import nak.nakloidGUI.actions.files.ImportScoreAction;
import nak.nakloidGUI.actions.files.ImportVocalAction;
import nak.nakloidGUI.actions.files.OpenAction;
import nak.nakloidGUI.actions.files.SaveAction;
import nak.nakloidGUI.actions.files.SaveAsAction;
import nak.nakloidGUI.actions.files.SpeechSynthesisAction;
import nak.nakloidGUI.actions.options.AboutNakloidAction;
import nak.nakloidGUI.actions.options.NakloidOptionAction;
import nak.nakloidGUI.actions.options.VocalOptionAction;
import nak.nakloidGUI.coredata.CoreData;
import nak.nakloidGUI.coredata.CoreData.CoreDataSubscriber;
import nak.nakloidGUI.gui.mainWindowViews.KeyboardView;
import nak.nakloidGUI.gui.mainWindowViews.MainView;
import nak.nakloidGUI.gui.mainWindowViews.MainView.MainViewListener;
import nak.nakloidGUI.gui.mainWindowViews.OverView;
import nak.nakloidGUI.gui.mainWindowViews.OverView.OverViewListener;
import nak.nakloidGUI.gui.mainWindowViews.VocalInfoView;
import nak.nakloidGUI.models.Waveform;
import nak.nakloidGUI.models.Waveform.WaveformStatus;
public class MainWindow extends ApplicationWindow implements CoreDataSubscriber, MainViewListener, OverViewListener {
private CoreData coreData;
private MainWindowDisplayMode displayMode;
private OverView overView;
private VocalInfoView vocalInfoView;
private KeyboardView keyboardView;
private MainView mainView;
private LoggerWindow loggerWindow;
private NotesWindow notesWindow;
private boolean displayLog = NakloidGUI.preferenceStore.getBoolean("gui.mainWindow.displayLogWindow");
private boolean displayNotesWindow = NakloidGUI.preferenceStore.getBoolean("gui.mainWindow.displayNotesWindow");
private double msByPixel = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.baseMsByPixel");
private double noteHeight = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.baseNoteHeight");
final public Action saveAction, saveAsAction, openAction, importNarAction, importVocalAction, exportVocalAction, speechSynthesisAction,exitAction,
addNoteAction, editLyricsAction, displayNotesAction, displayPitchesAction, displayLogAction, displayNotesWindowAction,
displayZoomInAction, displayZoomOutAction, displayHorizontalZoomInAction, displayHorizontalZoomOutAction, displayVerticalZoomInAction, displayVerticalZoomOutAction,
playAction, buildAction, buildAndPlayAction, exportWavAction, initializePitchesAction,
nakloidOptionAction, vocalOptionAction, aboutNakloidAction;
static public enum MusicalScales {
C(0),C_MAJOR(1),D(2),D_MAJOR(3),E(4),F(5),F_MAJOR(6),G(7),G_MAJOR(8),A(9),A_MAJOR(10),B(11);
private static final String[] MusicalScaleStrings = {"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"};
private static final MusicalScales[] MusicalScaleInstances = {C,C_MAJOR,D,D_MAJOR,E,F,F_MAJOR,G,G_MAJOR,A,A_MAJOR,B};
private final int id;
private MusicalScales(int id) {
this.id = id;
}
public String getString() {
return MusicalScaleStrings[id];
}
public boolean isMajor() {
return MusicalScaleStrings[id].endsWith("
}
public boolean equals(int numMidiNote) {
return id == numMidiNote%12;
}
public static String getStringFromNumMidiNote(int numMidiNote, boolean withOctave) {
return MusicalScaleStrings[numMidiNote%12]+((withOctave)?Integer.toString(numMidiNote/12-1):"");
}
public static MusicalScales getMusicalScalesFromNumMidiNote(int numMidiNote) {
return MusicalScaleInstances[numMidiNote%12];
}
}
public enum MainWindowDisplayMode {NOTES, PITCHES}
public MainWindow() {
super(null);
Shell shellSplash = new Shell(SWT.ON_TOP);
shellSplash.setLayout(new FillLayout());
Image imgLoad = loadImage("icon256.png");
Splash splash = new Splash(shellSplash, imgLoad);
splash.setText("...");
shellSplash.open();
StringBuilder sb = new StringBuilder();
CoreData.Builder cdb = new CoreData.Builder();
splash.setText("...");
try {
cdb.loadOtoIni();
} catch (IOException e) {
sb.append("\n");
}
if (!NakloidGUI.preferenceStore.getString("workspace.path_nar").isEmpty()) {
splash.setText("nar...");
try {
cdb.loadNar(Paths.get(NakloidGUI.preferenceStore.getString("workspace.path_nar")));
} catch (IOException e) {
sb.append("nar\n");
}
splash.setText("...");
try {
cdb.loadScore();
} catch (IOException e) {
sb.append("\n");
}
splash.setText("...");
try {
cdb.loadPitches();
} catch (IOException e) {
sb.append("\n");
}
}
splash.setText("...");
coreData = cdb.build();
coreData.addSubscribers(this);
displayMode = MainWindowDisplayMode.NOTES;
saveAction = new SaveAction(this, coreData);
saveAsAction = new SaveAsAction(this, coreData);
openAction = new OpenAction(this, coreData);
importNarAction = new ImportScoreAction(this, coreData);
importVocalAction = new ImportVocalAction(this, coreData);
exportVocalAction = new ExportVocalAction(this, coreData);
speechSynthesisAction = new SpeechSynthesisAction(this, coreData);
exitAction = new ExitAction(this, coreData);
addNoteAction = new AddNoteAction(this, coreData);
editLyricsAction = new EditLyricsAction(this, coreData);
displayNotesAction = new DisplayNotesAction(this, coreData);
displayPitchesAction = new DisplayPitchesAction(this, coreData);
displayLogAction = new DisplayLogAction(this, coreData);
displayNotesWindowAction = new DisplayNotesWindowAction(this, coreData);
displayZoomInAction = new DisplayZoomInAction(this, coreData);
displayZoomOutAction = new DisplayZoomOutAction(this, coreData);
displayHorizontalZoomInAction = new DisplayHorizontalZoomInAction(this, coreData);
displayHorizontalZoomOutAction = new DisplayHorizontalZoomOutAction(this, coreData);
displayVerticalZoomInAction = new DisplayVerticalZoomInAction(this, coreData);
displayVerticalZoomOutAction = new DisplayVerticalZoomOutAction(this, coreData);
playAction = new PlayAction(this, coreData);
buildAction = new BuildAction(this, coreData);
buildAndPlayAction = new BuildAndPlayAction(this, coreData);
exportWavAction = new ExportWavAction(this, coreData);
initializePitchesAction = new InitializePitchesAction(this, coreData);
nakloidOptionAction = new NakloidOptionAction(this, coreData);
vocalOptionAction = new VocalOptionAction(this, coreData);
aboutNakloidAction = new AboutNakloidAction(this, coreData);
addMenuBar();
if (sb.length() > 0) {
MessageDialog.openWarning(shellSplash, "NakloidGUI", sb.toString());
}
shellSplash.close();
imgLoad.dispose();
splash.dispose();
shellSplash.dispose();
}
@Override
protected final void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(getWindowName());
Image[] images = new Image[5];
images[0] = loadImage("icon16.png");
images[1] = loadImage("icon32.png");
images[2] = loadImage("icon64.png");
images[3] = loadImage("icon128.png");
images[4] = loadImage("icon256.png");
shell.setImages(images);
shell.setSize(900, 600);
shell.setMaximized(true);
}
@Override
protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NONE);
{
GridLayout layContainer = new GridLayout(1, false);
layContainer.marginHeight = layContainer.horizontalSpacing = layContainer.marginWidth = layContainer.verticalSpacing = 0;
container.setLayout(layContainer);
container.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {}
public void controlResized(ControlEvent e) {
overView.redraw();
keyboardView.redraw();
mainView.redraw();
}
});
}
{
Composite cntPlayer = new Composite(container, SWT.NONE);
GridLayout layCntPlayer = new GridLayout(3, false);
layCntPlayer.marginHeight = layCntPlayer.marginWidth = layCntPlayer.verticalSpacing = 0;
layCntPlayer.marginLeft = 3;
layCntPlayer.marginBottom = 3;
layCntPlayer.horizontalSpacing = 3;
cntPlayer.setLayout(layCntPlayer);
GridData gdCntPlayer = new GridData(GridData.FILL_HORIZONTAL);
int headerHeight = NakloidGUI.preferenceStore.getInt("gui.mainWindow.headerHeight");
gdCntPlayer.heightHint = headerHeight;
cntPlayer.setLayoutData(gdCntPlayer);
{
vocalInfoView = new VocalInfoView(cntPlayer, coreData.getVocalInfo());
GridData gdlblLoadImage = new GridData(GridData.FILL_VERTICAL);
gdlblLoadImage.heightHint = headerHeight;
gdlblLoadImage.widthHint = headerHeight;
vocalInfoView.setLayoutData(gdlblLoadImage);
}
{
overView = new OverView(cntPlayer, coreData.getSongWaveform());
overView.addOverViewListener(this);
}
{
Scale sclPlayer = new Scale(cntPlayer, SWT.VERTICAL);
sclPlayer.setMinimum(0);
sclPlayer.setMaximum(100);
sclPlayer.setIncrement(20);
sclPlayer.setSelection(0);
GridData gdSclPlayer = new GridData(GridData.FILL_VERTICAL);
sclPlayer.setLayoutData(gdSclPlayer);
sclPlayer.addListener(SWT.MouseWheel, new Listener(){
@Override
public void handleEvent(Event e) {
e.doit = false;
}
});
sclPlayer.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e){
if (coreData.getSongWaveform()!=null && coreData.getSongWaveform().isLoaded()) {
coreData.getSongWaveform().setVolume(100-sclPlayer.getSelection());
}
}
});
}
}
{
Composite cntMainView = new Composite(container, SWT.NONE);
GridLayout layCntMainView = new GridLayout(2, false);
layCntMainView.marginHeight = layCntMainView.horizontalSpacing = layCntMainView.marginWidth = layCntMainView.verticalSpacing = 0;
cntMainView.setLayout(layCntMainView);
GridData gdCntMainView = new GridData(GridData.FILL_BOTH);
cntMainView.setLayoutData(gdCntMainView);
keyboardView = new KeyboardView(cntMainView);
mainView = new MainView(cntMainView, coreData);
mainView.addMainViewListener(this);
mainView.setFocus();
}
if (displayLog) {
displayLogAction.run();
}
if (displayNotesWindow) {
displayNotesWindowAction.run();
}
if (coreData.getScoreLength()>0 && coreData.getVoicesSize()>0) {
try {
coreData.synthesize();
} catch (IOException | InterruptedException e) {}
}
return container;
}
@Override
protected MenuManager createMenuManager() {
MenuManager menuBar = new MenuManager("");
{
MenuManager exitMenu = new MenuManager("(&F)");
menuBar.add(exitMenu);
exitMenu.add(saveAction);
exitMenu.add(saveAsAction);
exitMenu.add(openAction);
exitMenu.add(new org.eclipse.jface.action.Separator());
exitMenu.add(importNarAction);
exitMenu.add(importVocalAction);
exitMenu.add(exportVocalAction);
exitMenu.add(new org.eclipse.jface.action.Separator());
exitMenu.add(speechSynthesisAction);
exitMenu.add(new org.eclipse.jface.action.Separator());
exitMenu.add(exitAction);
}
{
MenuManager displayMenu = new MenuManager("(&E)");
menuBar.add(displayMenu);
displayMenu.add(addNoteAction);
displayMenu.add(editLyricsAction);
}
{
MenuManager displayMenu = new MenuManager("(&D)");
menuBar.add(displayMenu);
displayMenu.add(displayNotesAction);
displayMenu.add(displayPitchesAction);
displayMenu.add(displayLogAction);
displayMenu.add(displayNotesWindowAction);
displayMenu.add(new org.eclipse.jface.action.Separator());
displayMenu.add(displayZoomInAction);
displayMenu.add(displayZoomOutAction);
displayMenu.add(displayHorizontalZoomInAction);
displayMenu.add(displayHorizontalZoomOutAction);
displayMenu.add(displayVerticalZoomInAction);
displayMenu.add(displayVerticalZoomOutAction);
}
{
MenuManager editMenu = new MenuManager("(&R)");
menuBar.add(editMenu);
editMenu.add(playAction);
editMenu.add(buildAction);
editMenu.add(buildAndPlayAction);
editMenu.add(exportWavAction);
editMenu.add(new org.eclipse.jface.action.Separator());
editMenu.add(initializePitchesAction);
}
{
MenuManager optionMenu = new MenuManager("(&O)");
menuBar.add(optionMenu);
optionMenu.add(nakloidOptionAction);
optionMenu.add(vocalOptionAction);
optionMenu.add(aboutNakloidAction);
}
return menuBar;
}
@Override
protected boolean canHandleShellCloseEvent() {
return showSaveConfirmDialog();
}
public boolean showSaveConfirmDialog() {
if (!coreData.isSaved()) {
int result = new MessageDialog(getShell(), "NakloidGUI", null,
"", MessageDialog.QUESTION,
new String[] { "", "", "" }, 0).open();
if (result == 0) {
saveAction.run();
return showSaveConfirmDialog();
} else if (result == 1) {
return true;
} else {
return false;
}
}
return true;
}
@Override
public void updateScore() {
mainView.redraw();
}
@Override
public void updatePitches() {
mainView.redraw();
}
@Override
public void updateVocal() {
overView.redraw((Waveform)coreData.getSongWaveform());
vocalInfoView.redraw(coreData.getVocalInfo());
}
@Override
public void updateSongWaveform() {
if (coreData.getSongWaveform() == null) {
showWaveformStatus("");
return;
}
showWaveformStatus("...");
Display.getCurrent().syncExec(new Runnable() {
@Override
public void run() {
if (coreData.getSongWaveform() != null) {
if (coreData.getSongWaveform().getStatus()==WaveformStatus.LOADING) {
Display.getCurrent().timerExec(100, this);
return;
}
if (coreData.getSongWaveform().isLoaded()) {
overView.redraw(coreData.getSongWaveform(), mainView.getClientArea().width, mainView.getOffset().x, msByPixel);
mainView.redraw();
return;
}
}
showWaveformStatus("");
}
});
}
@Override
public void updateSaveState() {
if (getShell() != null) {
getShell().setText(getWindowName());
}
}
@Override
public void mainViewHorizontalBarUpdated(SelectionEvent e) {
overView.redraw(mainView.getClientArea().width, mainView.getOffset().x, msByPixel);
}
@Override
public void mainViewVerticalBarUpdated(SelectionEvent e) {
keyboardView.redraw(mainView.getOffset().y, (int)noteHeight);
}
@Override
public void pitchesDrawn() {
mainView.redraw();
mainView.update();
}
@Override
public void waveformSeeked() {
if (getShell()!=null && !getShell().isDisposed()) {
overView.redraw();
mainView.redraw();
}
}
public void preferenceReloaded() {
try {
coreData.reloadPreference();
mainView.redraw();
keyboardView.redraw();
} catch (IOException e) {
ErrorDialog.openError(getShell(), "NakloidGUI",
"NakloidGUInakloidGUI.properties",
new MultiStatus(".", IStatus.ERROR,
Stream.of(e.getStackTrace())
.map(s->new Status(IStatus.ERROR, ".", "at "+s.getClassName()+": "+s.getMethodName()))
.collect(Collectors.toList()).toArray(new Status[]{}),
e.getLocalizedMessage(), e));
}
}
public MainWindowDisplayMode getDisplayMode() {
return displayMode;
}
public void displayNotes() {
displayMode = MainWindowDisplayMode.NOTES;
mainView.redraw(MainWindowDisplayMode.NOTES);
}
public void displayPitches() {
displayMode = MainWindowDisplayMode.PITCHES;
mainView.redraw(MainWindowDisplayMode.PITCHES);
}
public boolean displayingLog() {
return displayLog;
}
public void displayLog(boolean displayLog) {
this.displayLog = displayLog;
if (displayLog) {
loggerWindow = new LoggerWindow(getShell());
loggerWindow.open();
mainView.forceFocus();
} else {
loggerWindow.close();
loggerWindow = null;
}
}
public boolean displayingNotesWindow() {
return displayNotesWindow;
}
public void displayNotesWindow(boolean displayNotesWindow) {
this.displayNotesWindow = displayNotesWindow;
if (displayNotesWindow) {
notesWindow = new NotesWindow(getShell(), coreData);
notesWindow.open();
mainView.forceFocus();
} else {
notesWindow.close();
notesWindow = null;
}
}
public int getMainViewWidth() {
return mainView.getClientArea().width;
}
public int getMainViewHorizontalOffset() {
return mainView.getOffset().x;
}
public int getMainViewVerticalOffset() {
return mainView.getOffset().y;
}
public void setHorizontalScale(double scale) {
double upperLimit = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.msByPixelUpperLimit");
double lowerLimit = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.msByPixelLowerLimit");
msByPixel *= scale;
if (msByPixel > upperLimit) {
msByPixel = upperLimit;
} else if (msByPixel < lowerLimit) {
msByPixel = lowerLimit;
}
mainView.redraw(msByPixel, (int)noteHeight);
overView.redraw(mainView.getClientArea().width, mainView.getOffset().x, msByPixel);
}
public void setVerticalScale(double scale) {
double upperLimit = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.noteHeightUpperLimit");
double lowerLimit = NakloidGUI.preferenceStore.getDouble("gui.mainWindow.noteHeightLowerLimit");
noteHeight *= scale;
if (noteHeight > upperLimit) {
noteHeight = upperLimit;
} else if (noteHeight < lowerLimit) {
noteHeight = lowerLimit;
}
mainView.redraw(msByPixel, (int)noteHeight);
keyboardView.redraw(mainView.getOffset().y, (int)noteHeight);
}
public void flushLoggerWindow() {
if (loggerWindow != null) {
loggerWindow.flush();
}
}
public void showWaveformStatus(String message) {
overView.redraw(message);
}
private Image loadImage(String filename) {
return ImageDescriptor.createFromURL(getClass().getResource(filename)).createImage();
}
private String getWindowName() {
String windowName = " - NakloidGUI";
Path pathNar = coreData.getNarPath();
if (pathNar!=null && pathNar.toFile().exists()) {
windowName = pathNar.toFile().getName() + (coreData.isSaved()?"":"*") + windowName;
} else {
windowName = "" + (coreData.getScoreLength()>0?"*":"") + windowName;
}
return windowName;
}
}
|
package com.github.dubu.lockscreenusingservice.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.github.dubu.lockscreenusingservice.Lockscreen;
import com.github.dubu.lockscreenusingservice.LockscreenUtil;
import com.github.dubu.lockscreenusingservice.R;
import com.github.dubu.lockscreenusingservice.SharedPreferencesUtil;
import com.romainpiel.shimmer.Shimmer;
import com.romainpiel.shimmer.ShimmerTextView;
public class LockscreenViewService extends Service {
private final int LOCK_OPEN_OFFSET_VALUE = 50;
private Context mContext = null;
private LayoutInflater mInflater = null;
private View mLockscreenView = null;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mParams;
private RelativeLayout mBackgroundLayout = null;
private RelativeLayout mBackgroundInLayout = null;
private ImageView mBackgroundLockImageView = null;
private RelativeLayout mForgroundLayout = null;
private RelativeLayout mStatusBackgruondDummyView = null;
private RelativeLayout mStatusForgruondDummyView = null;
private ShimmerTextView mShimmerTextView = null;
private boolean mIsLockEnable = false;
private boolean mIsSoftkeyEnable = false;
private int mDeviceWidth = 0;
private int mDevideDeviceWidth = 0;
private float mLastLayoutX = 0;
private int mServiceStartId = 0;
private SendMassgeHandler mMainHandler = null;
// private boolean sIsSoftKeyEnable = false;
private class SendMassgeHandler extends android.os.Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
changeBackGroundLockView(mLastLayoutX);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mContext = this;
SharedPreferencesUtil.init(mContext);
// sIsSoftKeyEnable = SharedPreferencesUtil.get(Lockscreen.ISSOFTKEY);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mMainHandler = new SendMassgeHandler();
if (isLockScreenAble()) {
if (null != mWindowManager) {
if (null != mLockscreenView) {
mWindowManager.removeView(mLockscreenView);
}
mWindowManager = null;
mParams = null;
mInflater = null;
mLockscreenView = null;
}
initState();
initView();
attachLockScreenView();
}
return LockscreenViewService.START_NOT_STICKY;
}
@Override
public void onDestroy() {
dettachLockScreenView();
}
private void initState() {
mIsLockEnable = LockscreenUtil.getInstance(mContext).isStandardKeyguardState();
if (mIsLockEnable) {
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
} else {
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,
PixelFormat.TRANSLUCENT);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mIsLockEnable && mIsSoftkeyEnable) {
mParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
} else {
mParams.flags = WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
}
} else {
mParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
}
if (null == mWindowManager) {
mWindowManager = ((WindowManager) mContext.getSystemService(WINDOW_SERVICE));
}
}
private void initView() {
if (null == mInflater) {
mInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (null == mLockscreenView) {
mLockscreenView = mInflater.inflate(R.layout.view_locokscreen, null);
}
}
private boolean isLockScreenAble() {
boolean isLock = SharedPreferencesUtil.get(Lockscreen.ISLOCK);
////// delete at github
// if (isLock) {
// isLock = true;
// } else {
// isLock = false;
return isLock;
}
private void attachLockScreenView() {
if (null != mWindowManager && null != mLockscreenView && null != mParams) {
mLockscreenView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
mWindowManager.addView(mLockscreenView, mParams);
settingLockView();
}
}
private boolean dettachLockScreenView() {
if (null != mWindowManager && null != mLockscreenView) {
mWindowManager.removeView(mLockscreenView);
mLockscreenView = null;
mWindowManager = null;
stopSelf(mServiceStartId);
return true;
} else {
return false;
}
}
private void settingLockView() {
mBackgroundLayout = (RelativeLayout) mLockscreenView.findViewById(R.id.lockscreen_background_layout);
mBackgroundInLayout = (RelativeLayout) mLockscreenView.findViewById(R.id.lockscreen_background_in_layout);
mBackgroundLockImageView = (ImageView) mLockscreenView.findViewById(R.id.lockscreen_background_image);
mForgroundLayout = (RelativeLayout) mLockscreenView.findViewById(R.id.lockscreen_forground_layout);
mShimmerTextView = (ShimmerTextView) mLockscreenView.findViewById(R.id.shimmer_tv);
(new Shimmer()).start(mShimmerTextView);
mForgroundLayout.setOnTouchListener(mViewTouchListener);
mStatusBackgruondDummyView = (RelativeLayout) mLockscreenView.findViewById(R.id.lockscreen_background_status_dummy);
mStatusForgruondDummyView = (RelativeLayout) mLockscreenView.findViewById(R.id.lockscreen_forground_status_dummy);
setBackGroundLockView();
DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
mDeviceWidth = displayMetrics.widthPixels;
mDevideDeviceWidth = (mDeviceWidth / 2);
mBackgroundLockImageView.setX((int) (((mDevideDeviceWidth) * -1)));
//kitkat
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
int val = LockscreenUtil.getInstance(mContext).getStatusBarHeight();
RelativeLayout.LayoutParams forgroundParam = (RelativeLayout.LayoutParams) mStatusForgruondDummyView.getLayoutParams();
forgroundParam.height = val;
mStatusForgruondDummyView.setLayoutParams(forgroundParam);
AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); // Make animation instant
alpha.setFillAfter(true); // Tell it to persist after the animation ends
mStatusForgruondDummyView.startAnimation(alpha);
RelativeLayout.LayoutParams backgroundParam = (RelativeLayout.LayoutParams) mStatusBackgruondDummyView.getLayoutParams();
backgroundParam.height = val;
mStatusBackgruondDummyView.setLayoutParams(backgroundParam);
}
}
private void setBackGroundLockView() {
if (mIsLockEnable) {
mBackgroundInLayout.setBackgroundColor(getResources().getColor(R.color.lock_background_color));
mBackgroundLockImageView.setVisibility(View.VISIBLE);
} else {
mBackgroundInLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));
mBackgroundLockImageView.setVisibility(View.GONE);
}
}
private void changeBackGroundLockView(float forgroundX) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (forgroundX < mDeviceWidth) {
mBackgroundLockImageView.setBackground(getResources().getDrawable(R.drawable.lock));
} else {
mBackgroundLockImageView.setBackground(getResources().getDrawable(R.drawable.unlock));
}
} else {
if (forgroundX < mDeviceWidth) {
mBackgroundLockImageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.lock));
} else {
mBackgroundLockImageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.unlock));
}
}
}
private View.OnTouchListener mViewTouchListener = new View.OnTouchListener() {
private float firstTouchX = 0;
private float layoutPrevX = 0;
private float lastLayoutX = 0;
private float layoutInPrevX = 0;
private boolean isLockOpen = false;
private int touchMoveX = 0;
private int touchInMoveX = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
firstTouchX = event.getX();
layoutPrevX = mForgroundLayout.getX();
layoutInPrevX = mBackgroundLockImageView.getX();
if (firstTouchX <= LOCK_OPEN_OFFSET_VALUE) {
isLockOpen = true;
}
}
break;
case MotionEvent.ACTION_MOVE: {
if (isLockOpen) {
touchMoveX = (int) (event.getRawX() - firstTouchX);
if (mForgroundLayout.getX() >= 0) {
mForgroundLayout.setX((int) (layoutPrevX + touchMoveX));
mBackgroundLockImageView.setX((int) (layoutInPrevX + (touchMoveX / 1.8)));
mLastLayoutX = lastLayoutX;
mMainHandler.sendEmptyMessage(0);
if (mForgroundLayout.getX() < 0) {
mForgroundLayout.setX(0);
}
lastLayoutX = mForgroundLayout.getX();
}
} else {
return false;
}
}
break;
case MotionEvent.ACTION_UP: {
if (isLockOpen) {
mForgroundLayout.setX(lastLayoutX);
mForgroundLayout.setY(0);
optimizeForground(lastLayoutX);
}
isLockOpen = false;
firstTouchX = 0;
layoutPrevX = 0;
layoutInPrevX = 0;
touchMoveX = 0;
lastLayoutX = 0;
}
break;
default:
break;
}
return true;
}
};
private void optimizeForground(float forgroundX) {
// final int devideDeviceWidth = (mDeviceWidth / 2);
if (forgroundX < mDevideDeviceWidth) {
int startPostion = 0;
for (startPostion = mDevideDeviceWidth; startPostion >= 0; startPostion
mForgroundLayout.setX(startPostion);
}
} else {
TranslateAnimation animation = new TranslateAnimation(0, mDevideDeviceWidth, 0, 0);
animation.setDuration(300);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mForgroundLayout.setX(mDevideDeviceWidth);
mForgroundLayout.setY(0);
dettachLockScreenView();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mForgroundLayout.startAnimation(animation);
}
}
}
|
package com.sonymobile.lifelog;
import android.app.Activity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.sonymobile.lifelog.auth.GetAuthTokenTask;
import com.sonymobile.lifelog.utils.Debug;
public class LoginActivity extends Activity {
private static final String TAG = LoginActivity.class.getSimpleName();
private static final Uri AUTH_BASE_URL = Uri.parse("https://platform.lifelog.sonymobile.com/oauth/2/authorize");
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_login);
mWebView = (WebView) findViewById(R.id.webview);
if (Build.VERSION.SDK_INT >= 19) {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(LifeLog.getCallback_url())) {
final String authenticationCode = Uri.parse(url).getQueryParameter("code");
if (!TextUtils.isEmpty(authenticationCode)) {
mWebView.setVisibility(View.GONE);
GetAuthTokenTask gat = new GetAuthTokenTask(getApplicationContext());
gat.getAuth(authenticationCode, new GetAuthTokenTask.OnAuthenticatedListener() {
@Override
public void onAuthenticated(String authToken) {
LifeLog.auth_token = authToken;
setResult(RESULT_OK);
finish();
}
@Override
public void onError(Exception e) {
if (Debug.isDebuggable(LoginActivity.this)) {
Log.w(TAG, "onError", e);
}
setResult(RESULT_CANCELED);
finish();
}
});
}
}
return super.shouldOverrideUrlLoading(view, url);
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
setProgress(newProgress * 100);
}
});
if (TextUtils.isEmpty(LifeLog.getScope())) {
throw new RuntimeException("Scope parameter is empty!");
}
Uri uri = AUTH_BASE_URL.buildUpon()
.appendQueryParameter("client_id", LifeLog.getClient_id())
.appendQueryParameter("scope", LifeLog.getScope()).build();
mWebView.loadUrl(uri.toString());
}
@Override
protected void onResume() {
super.onResume();
mWebView.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
mWebView.restoreState(savedInstanceState);
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onPause() {
mWebView.onPause();
super.onPause();
}
@Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
setResult(RESULT_CANCELED);
finish();
}
}
@Override
protected void onDestroy() {
mWebView.destroy();
super.onDestroy();
}
}
|
package org.caleydo.core.view.opengl.layout2.basic;
import gleem.linalg.Vec2f;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GL2ES1;
import org.caleydo.core.data.collection.EDimension;
import org.caleydo.core.view.opengl.canvas.IGLCanvas;
import org.caleydo.core.view.opengl.layout2.AGLElementDecorator;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.GLGraphics;
import org.caleydo.core.view.opengl.layout2.IGLElementContext;
import org.caleydo.core.view.opengl.layout2.IGLElementParent;
import org.caleydo.core.view.opengl.layout2.basic.IScrollBar.IScrollBarCallback;
import org.caleydo.core.view.opengl.layout2.geom.Rect;
import org.caleydo.core.view.opengl.layout2.layout.IGLLayoutElement;
import org.caleydo.core.view.opengl.picking.IPickingListener;
import org.caleydo.core.view.opengl.picking.Pick;
import org.caleydo.core.view.opengl.picking.PickingMode;
/**
* wrapper element that enables the use of scrollbars.
*
* by convention the min size is part of the layout data
*
* @author Samuel Gratzl
*
*/
public class ScrollingDecorator extends AGLElementDecorator implements IScrollBarCallback {
private final ScrollBarImpl vertical;
private final ScrollBarImpl horizontal;
/**
* in which direction a mouse wheel changes a scrollbar
*/
private final EDimension mouseWheelScrolls;
private int mouseWheelsScrollsPickingId = -1;
private final float scrollBarWidth;
/**
* whether scrolling should be enabled
*/
private boolean enabled = true;
/**
* whether the viewport should be automatically reseted, if scrolling isn't needed anymore
*/
private boolean autoResetViewport = true;
/**
* a custom min size provider otherwise the content will be used
*/
private IHasMinSize minSizeProvider = null;
public ScrollingDecorator(GLElement content, IScrollBar horizontal, IScrollBar vertical, float scrollBarWidth) {
this(content, horizontal, vertical, scrollBarWidth, null);
}
public ScrollingDecorator(GLElement content, IScrollBar horizontal, IScrollBar vertical, float scrollBarWidth,
EDimension mouseWheelsScrolls) {
super(content);
this.scrollBarWidth = scrollBarWidth;
mouseWheelScrolls = mouseWheelsScrolls;
this.horizontal = horizontal != null ? new ScrollBarImpl(horizontal) : null;
if (horizontal != null) {
horizontal.setCallback(this);
horizontal.setWidth(scrollBarWidth);
}
this.vertical = vertical != null ? new ScrollBarImpl(vertical) : null;
if (vertical != null) {
vertical.setCallback(this);
vertical.setWidth(scrollBarWidth);
}
}
/**
* factory method for creating a {@link ScrollingDecorator}
*
* @param content
* what
* @param scrollBarWidth
* size of the scrollbar
* @param mouseWheelsScrolls
* in which direction should the mouse wheel scroll, null is allowed
* @return
*/
public static ScrollingDecorator wrap(GLElement content, float scrollBarWidth, EDimension mouseWheelsScrolls) {
return new ScrollingDecorator(content, new ScrollBar(true), new ScrollBar(false), scrollBarWidth,
mouseWheelsScrolls);
}
public static ScrollingDecorator wrap(GLElement content, float scrollBarWidth) {
return wrap(content, scrollBarWidth, null);
}
@Override
protected void init(IGLElementContext context) {
super.init(context);
if (horizontal != null)
horizontal.pickingId = context.registerPickingListener(horizontal.scrollBar);
if (vertical != null)
vertical.pickingId = context.registerPickingListener(vertical.scrollBar);
if (mouseWheelScrolls != null && mouseWheelScrolls.select(horizontal, vertical) != null)
mouseWheelsScrollsPickingId = context.registerPickingListener(new IPickingListener() {
@Override
public void pick(Pick pick) {
if (pick.getPickingMode() == PickingMode.MOUSE_WHEEL)
mouseWheelScrolls.select(horizontal, vertical).scrollBar.pick(pick);
}
});
}
@Override
protected void takeDown() {
if (horizontal != null)
context.unregisterPickingListener(horizontal.pickingId);
if (vertical != null)
context.unregisterPickingListener(vertical.pickingId);
if (mouseWheelsScrollsPickingId != -1) {
context.unregisterPickingListener(mouseWheelsScrollsPickingId);
mouseWheelsScrollsPickingId = -1;
}
super.takeDown();
}
/**
* @param minSizeProvider
* setter, see {@link minSizeProvider}
*/
@Override
public void setMinSizeProvider(IHasMinSize minSizeProvider) {
super.setMinSizeProvider(minSizeProvider);
this.minSizeProvider = minSizeProvider;
relayout();
}
/**
* @param autoResetViewport
* setter, see {@link autoResetViewport}
*/
public void setAutoResetViewport(boolean autoResetViewport) {
this.autoResetViewport = autoResetViewport;
if (this.autoResetViewport)
relayout();
}
/**
* @param enabled
* setter, see {@link enabled}
*/
public void setEnabled(boolean enabled) {
if (this.enabled == enabled)
return;
this.enabled = enabled;
relayout();
}
/**
* @return the enabled, see {@link #enabled}
*/
public boolean isEnabled() {
return enabled;
}
@Override
protected void layoutContent(IGLLayoutElement layout, float w, float h, int deltaTimeMs) {
if (!enabled) {
layout.setBounds(0, 0, w, h);
return;
}
Vec2f minSize = getMinSize(layout);
Vec2f size = getSize();
Vec2f contentSize = new Vec2f();
Vec2f offset = content.getLocation();
offset.setX(-offset.x());
offset.setY(-offset.y());
if (!autoResetViewport && offset.x() != 0) {
minSize.setX(Math.max(size.x() + offset.x(), minSize.x()));
}
if (!autoResetViewport && offset.y() != 0) {
minSize.setY(Math.max(size.y() + offset.y(), minSize.y()));
}
boolean needHor = horizontal != null && size.x() < minSize.x();
if (needHor)
size.setY(size.y() - scrollBarWidth);
boolean needVer = vertical != null && size.y() < minSize.y();
if (needVer) {
size.setX(size.x() - scrollBarWidth);
if (!needHor) {
needHor = horizontal != null && size.x() < minSize.x();
if (needHor) {
size.setY(size.y() - scrollBarWidth);
}
}
}
if (needHor) {
contentSize.setX(minSize.x());
horizontal.needIt = true;
offset.setX(horizontal.scrollBar.setBounds(offset.x(), size.x(), minSize.x()));
} else {
if (horizontal != null)
horizontal.needIt = false;
contentSize.setX(size.x());
offset.setX(0);
}
if (needVer) {
contentSize.setY(minSize.y());
vertical.needIt = true;
offset.setY(vertical.scrollBar.setBounds(offset.y(), size.y(), minSize.y()));
} else {
if (vertical != null)
vertical.needIt = false;
contentSize.setY(size.y());
offset.setY(0);
}
layout.setLocation(-offset.x(), -offset.y());
layout.setSize(contentSize.x(), contentSize.y());
}
/**
* @param layout
* @return
*/
private Vec2f getMinSize(IGLLayoutElement layout) {
if (minSizeProvider != null)
return minSizeProvider.getMinSize();
IHasMinSize minSize = layout.getLayoutDataAs(IHasMinSize.class, null);
if (minSize != null)
return minSize.getMinSize();
return layout.getLayoutDataAs(Vec2f.class, new Vec2f(0, 0));
}
@Override
public float getHeight(IScrollBar scrollBar) {
if (horizontal != null && horizontal.scrollBar == scrollBar)
return getSize().x();
else
return getSize().y();
}
/**
* externally set the clipping location
*
* @param x
* @param y
*/
public void setClippingLocation(float x, float y) {
x = fix(horizontal, x);
y = fix(vertical, y);
content.setLocation(x, y);
repaint();
}
private static float fix(ScrollBarImpl s, float v) {
if (s == null) // no scrolling in this dimension
return 0;
v = Math.max(0, Math.min(v, s.scrollBar.getSize() - s.scrollBar.getWindow()));
return v;
}
@Override
public void onScrollBarMoved(IScrollBar scrollBar, float value) {
Vec2f loc = content.getLocation();
if (horizontal != null && horizontal.scrollBar == scrollBar) {
content.setLocation(-value, loc.y());
} else {
content.setLocation(loc.x(), -value);
}
repaint();
}
@Override
protected void renderImpl(GLGraphics g, float w, float h) {
doRender(g, w, h, false);
super.renderImpl(g, w, h);
}
@Override
protected void renderPickImpl(GLGraphics g, float w, float h) {
doRender(g, w, h, true);
super.renderPickImpl(g, w, h);
}
protected void doRender(GLGraphics g, float w, float h, boolean pick) {
if (!enabled) {
if (pick)
renderPickContent(g, w, h);
else
content.render(g);
return;
}
final boolean doHor = needHor();
final boolean doVer = needVer();
final GL2 gl = g.gl;
if (doVer || doHor) {
gl.glPushAttrib(GL2.GL_ENABLE_BIT);
}
if (doHor) {
g.move(0, h - scrollBarWidth);
g.pushName(horizontal.pickingId);
if (pick)
horizontal.scrollBar.renderPick(g, doVer ? w - scrollBarWidth : w, scrollBarWidth, this);
else
horizontal.scrollBar.render(g, doVer ? w - scrollBarWidth : w, scrollBarWidth, this);
g.popName();
g.move(0, -h + scrollBarWidth);
}
if (doVer) {
g.move(w - scrollBarWidth, 0);
g.pushName(vertical.pickingId);
if (pick)
vertical.scrollBar.renderPick(g, scrollBarWidth, doHor ? h - scrollBarWidth : h, this);
else
vertical.scrollBar.render(g, scrollBarWidth, doHor ? h - scrollBarWidth : h, this);
g.popName();
g.move(-w + scrollBarWidth, 0);
}
if (doHor) {
double[] clipPlane1 = new double[] { 1.0, 0.0, 0.0, 0 };
double[] clipPlane3 = new double[] { -1.0, 0.0, 0.0, doVer ? w - scrollBarWidth : w };
gl.glClipPlane(GL2ES1.GL_CLIP_PLANE0, clipPlane1, 0);
gl.glClipPlane(GL2ES1.GL_CLIP_PLANE1, clipPlane3, 0);
gl.glEnable(GL2ES1.GL_CLIP_PLANE0);
gl.glEnable(GL2ES1.GL_CLIP_PLANE1);
}
if (doVer) {
double[] clipPlane2 = new double[] { 0.0, 1.0, 0.0, 0 };
double[] clipPlane4 = new double[] { 0.0, -1.0, 0.0, doHor ? h - scrollBarWidth : h };
gl.glClipPlane(GL2ES1.GL_CLIP_PLANE2, clipPlane2, 0);
gl.glClipPlane(GL2ES1.GL_CLIP_PLANE3, clipPlane4, 0);
gl.glEnable(GL2ES1.GL_CLIP_PLANE2);
gl.glEnable(GL2ES1.GL_CLIP_PLANE3);
}
gl.glEnable(GL.GL_SCISSOR_TEST);
IGLCanvas canvas = findCanvas();
int height = canvas.toRawPixel(canvas.getDIPHeight()); // gl.glScissor(0, 0, 100, 100);
final Vec2f abs = getAbsoluteLocation();
int locx = canvas.toRawPixel(abs.x());
int locy = canvas.toRawPixel(abs.y());
if (horizontal == null)
locx = 0;
if (vertical == null)
locy = 0;
int pixelW = canvas.toRawPixel(w);
int pixelH = canvas.toRawPixel(h);
gl.glScissor(locx, height - locy - pixelH + (doHor ? canvas.toRawPixel(scrollBarWidth) : 0), pixelW
- (doVer ? canvas.toRawPixel(scrollBarWidth) : 0), pixelH
- (doHor ? canvas.toRawPixel(scrollBarWidth) : 0));
if (pick)
renderPickContent(g, w, h);
else
content.render(g);
gl.glDisable(GL.GL_SCISSOR_TEST);
if (doVer || doHor) {
gl.glPopAttrib();
}
}
private IGLCanvas findCanvas() {
IGLElementParent p = getParent();
for (;;) {
IGLElementParent p2 = p.getParent();
if (p2 == null) { // we have to reach the root
return p.getLayoutDataAs(IGLCanvas.class, null);
}
p = p2;
}
}
private void renderPickContent(GLGraphics g, float w, float h) {
if (mouseWheelsScrollsPickingId >= 0)
g.pushName(mouseWheelsScrollsPickingId).fillRect(0, 0, w, h);
content.renderPick(g);
if (mouseWheelsScrollsPickingId >= 0)
g.popName();
}
/**
* @return the applied clipping area
*/
public Rect getClipingArea() {
Vec2f loc = content.getLocation();
Vec2f size = getSize();
if (!enabled)
return new Rect(0, 0, size.x(), size.y());
Rect r = new Rect();
r.x(-loc.x());
r.y(-loc.y());
r.width(needVer() ? size.x() - scrollBarWidth : size.x());
r.height(needHor() ? size.y() - scrollBarWidth : size.y());
return r;
}
public void setClippingLocation(Vec2f location) {
setClippingLocation(location.x(), location.y());
}
public void moveContentTo(Vec2f pos) {
if (horizontal != null)
horizontal.scrollBar.moveTo(pos.x());
if (vertical != null)
vertical.scrollBar.moveTo(pos.y());
}
public void moveContent(Vec2f delta) {
if (horizontal != null)
horizontal.scrollBar.move(delta.x());
if (vertical != null)
vertical.scrollBar.move(delta.y());
}
protected boolean needHor() {
return horizontal != null && horizontal.needIt;
}
protected boolean needVer() {
return vertical != null && vertical.needIt;
}
@Override
public boolean moved(GLElement child) {
return false;
}
private class ScrollBarImpl {
final IScrollBar scrollBar;
int pickingId;
boolean needIt;
public ScrollBarImpl(IScrollBar scrollBar) {
this.scrollBar = scrollBar;
}
}
/**
* contract for delivering a min size, alternative provide a Vec2f in the layout data
*
* @author Samuel Gratzl
*
*/
public static interface IHasMinSize {
Vec2f getMinSize();
}
}
|
package com.github.mjdev.libaums.fs;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.github.mjdev.libaums.util.Pair;
import org.apache.commons.io.IOUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.xenei.junit.contract.Contract;
import org.xenei.junit.contract.ContractTest;
import org.xenei.junit.contract.IProducer;
import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
import static org.junit.Assert.*;
@Contract(UsbFile.class)
public class UsbFileTest {
private IProducer<Pair<FileSystem, JsonObject>> producer;
private FileSystem fs;
private UsbFile root;
private JsonObject expectedValues;
@Contract.Inject
public void setFileSystem(IProducer<Pair<FileSystem, JsonObject>> producer) {
this.producer = producer;
}
@Before
public void setUp() {
newInstance();
}
@After
public void cleanup() {
producer.cleanUp();
}
private void newInstance() {
Pair<FileSystem, JsonObject> pair = producer.newInstance();
fs = pair.getLeft();
root = fs.getRootDirectory();
expectedValues = pair.getRight();
}
@ContractTest
public void testSingleFileReferenceSearch() throws IOException {
for (JsonValue value : expectedValues.get("search").asArray()) {
String path = value.asString();
assertSame(root.search(path), root.search(path));
}
}
@ContractTest
public void testSingleFileReferenceCreate() throws IOException {
assertSame(root.createDirectory("ref_test"), root.search("ref_test"));
assertSame(root.createFile("ref_test.txt"), root.search("ref_test.txt"));
UsbFile file = root.createDirectory("test_single_ref").createDirectory("sub").createFile("file.txt");
assertSame(file, root.search("test_single_ref/sub/file.txt"));
assertSame(file.getParent(), root.search("/test_single_ref/sub/"));
assertSame(file.getParent().getParent(), root.search("test_single_ref/"));
newInstance();
assertNotSame(file, root.search("test_single_ref/sub/file.txt"));
assertNotSame(file.getParent(), root.search("/test_single_ref/sub/"));
assertNotSame(file.getParent().getParent(), root.search("test_single_ref/"));
}
@ContractTest
public void search() throws Exception {
for (JsonValue value : expectedValues.get("search").asArray()) {
String path = value.asString();
Assert.assertNotNull(path, root.search(path));
}
String garbagePath = "garbage path!)(&`";
assertNull(garbagePath, root.search(garbagePath));
try {
root.search(expectedValues.get("fileToCreateDirectoryOrFileOn").asString())
.search("should not happen");
fail("UsbFile did not throw UnsupportedOperationException on search");
} catch (UnsupportedOperationException e) {
}
}
@ContractTest
public void isDirectory() throws Exception {
for (JsonObject.Member member: expectedValues.get("isDirectory").asObject()) {
String path = member.getName();
assertEquals(path, member.getValue().asBoolean(), root.search(path).isDirectory());
}
}
@ContractTest
public void getName() throws Exception {
assertEquals("Root getName", "/", root.getName());
for (JsonValue value : expectedValues.get("getName").asArray()) {
String filePath = value.asString();
assertEquals("Get Name", filePath, root.search(filePath).getName());
}
}
@ContractTest
public void setName() throws Exception {
JsonArray oldNames = expectedValues.get("getName").asArray();
JsonArray newNames = expectedValues.get("setName").asArray();
int i = 0;
for (JsonValue value : newNames) {
String newName = value.asString();
String oldName = oldNames.get(i).asString();
i++;
UsbFile file = root.search(oldName);
file.setName(newName);
assertEquals(newName, file.getName());
}
// force reread
newInstance();
for (JsonValue value : newNames) {
String filePath = value.asString();
assertEquals(filePath, root.search(filePath).getName());
}
}
@ContractTest
public void createdAt() throws Exception {
FileSystemFactory.setTimeZone(TimeZone.getTimeZone(expectedValues.get("timezone").asString()));
JsonObject foldersToMove = expectedValues.get("createdAt").asObject();
for (JsonObject.Member member : foldersToMove) {
UsbFile file = root.search(member.getName());
assertEquals(member.getName(), member.getValue().asLong(), file.createdAt() / 1000);
}
}
@ContractTest
public void lastModified() throws Exception {
FileSystemFactory.setTimeZone(TimeZone.getTimeZone(expectedValues.get("timezone").asString()));
JsonObject foldersToMove = expectedValues.get("lastModified").asObject();
for (JsonObject.Member member : foldersToMove) {
UsbFile file = root.search(member.getName());
assertEquals(member.getName(), member.getValue().asLong(), file.lastModified() / 1000);
}
}
@ContractTest
public void lastAccessed() throws Exception {
FileSystemFactory.setTimeZone(TimeZone.getTimeZone(expectedValues.get("timezone").asString()));
JsonObject foldersToMove = expectedValues.get("lastAccessed").asObject();
for (JsonObject.Member member : foldersToMove) {
UsbFile file = root.search(member.getName());
assertEquals(member.getName(), member.getValue().asLong(), file.lastAccessed() / 1000);
}
}
@ContractTest
public void getParent() throws Exception {
UsbFile root = fs.getRootDirectory();
assertNull(root.getParent());
for (UsbFile file : root.listFiles()) {
assertSame(root, file.getParent());
if (file.isDirectory()) {
for (UsbFile file2 : file.listFiles()) {
assertSame(file, file2.getParent());
}
}
}
}
@ContractTest
public void list() throws Exception {
JsonObject listedFolders = expectedValues.get("list").asObject();
for (JsonObject.Member member : listedFolders) {
String toList = member.getName();
JsonArray listed = member.getValue().asArray();
String[] actualList = root.search(toList).list();
int count = 0;
for (String fileName : actualList) {
if (!fileName.startsWith(".")) {
count++;
}
}
assertEquals(listed.size(), count);
for (JsonValue fileName : listed) {
assertTrue(Arrays.asList(actualList).contains(fileName.asString()));
}
}
}
@ContractTest
public void listFiles() throws Exception {
JsonObject listedFolders = expectedValues.get("list").asObject();
for (JsonObject.Member member : listedFolders) {
String toList = member.getName();
JsonArray listed = member.getValue().asArray();
UsbFile[] actualList = root.search(toList).listFiles();
List<String> names = new ArrayList<>();
int count = 0;
for (UsbFile file : actualList) {
names.add(file.getName());
if (!file.getName().startsWith(".")) {
count++;
}
}
assertEquals(listed.size(), count);
for (JsonValue fileName : listed) {
assertTrue(names.contains(fileName.asString()));
}
}
}
@ContractTest
public void getLengthFolder() throws Exception {
JsonArray folders = expectedValues.get("getLengthFolders").asArray();
for (JsonValue value : folders) {
String folder = value.asString();
try {
root.search(folder).getLength();
fail("Folder did not throw UnsupportedOperationException on getLength(): " + folder);
} catch(UnsupportedOperationException e) {
}
}
}
@ContractTest
public void getLengthFile() throws Exception {
for (JsonObject.Member member: expectedValues.get("getLengthFiles").asObject()) {
String path = member.getName();
assertEquals(path, member.getValue().asInt(), root.search(path).getLength());
}
}
@ContractTest
public void setLength() throws Exception {
UsbFile file = root.createFile("testlength");
file.setLength(1337);
assertEquals(1337, file.getLength());
newInstance();
assertEquals(1337, file.getLength());
file = root.search("testlength");
file.setLength(1134571);
assertEquals(1134571, file.getLength());
newInstance();
assertEquals(1134571, file.getLength());
UsbFile dir = root.createDirectory("my dir");
try {
dir.setLength(1337);
fail("Directory did not throw UnsupportedOperationException on setLength");
} catch (UnsupportedOperationException e) {
}
}
@ContractTest
public void read() throws Exception {
int numberOfFiles = root.listFiles().length;
String[] files = root.list();
ByteBuffer buffer = ByteBuffer.allocate(19);
UsbFile file = root.search(expectedValues.get("fileToRead").asString());
file.read(0, buffer);
assertEquals(buffer.capacity(), buffer.limit());
assertEquals("this is just a test", new String(buffer.array()));
JsonObject bigFileToRead = expectedValues.get("bigFileToRead").asObject();
for(JsonObject.Member member : bigFileToRead) {
String path = member.getName();
file = root.search(path);
URL url = new URL(member.getValue().asString());
assertTrue(IOUtils.contentEquals(url.openStream(), new UsbFileInputStream(file)));
}
// do that again to check LRU cache of FAT
file = root.search(expectedValues.get("fileToRead").asString());
file.read(0, buffer);
file.flush();
assertEquals(buffer.capacity(), buffer.limit());
for(JsonObject.Member member : bigFileToRead) {
String path = member.getName();
file = root.search(path);
URL url = new URL(member.getValue().asString());
assertTrue(IOUtils.contentEquals(url.openStream(), new UsbFileInputStream(file)));
}
file.flush();
assertArrayEquals(files, root.list());
assertEquals(numberOfFiles, root.listFiles().length);
newInstance();
assertArrayEquals(files, root.list());
assertEquals(numberOfFiles, root.listFiles().length);
UsbFile dir = root.createDirectory("my dir");
try {
dir.read(0, buffer);
fail("Directory did not throw UnsupportedOperationException on read");
} catch (UnsupportedOperationException e) {
}
}
/**
* shamelessly stolen from IOUtils of apache commons to increase buffer size
* Copy bytes from a large (over 2GB) <code>InputStream</code> to an
* <code>OutputStream</code>.
* <p>
* This method uses the provided buffer, so there is no need to use a
* <code>BufferedInputStream</code>.
* <p>
*
* @param input the <code>InputStream</code> to read from
* @param output the <code>OutputStream</code> to write to
* @param buffer the buffer to use for the copy
* @return the number of bytes copied
* @throws NullPointerException if the input or output is null
* @throws IOException if an I/O error occurs
* @since 2.2
*/
static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
throws IOException {
long count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
output.close();
return count;
}
@ContractTest
public void write() throws Exception {
int numberOfFiles = root.listFiles().length;
// TODO test exception when disk is full
URL bigFileUrl = new URL(expectedValues.get("bigFileToWrite").asString());
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.put("this is just a test!".getBytes());
buffer.flip();
UsbFile file = root.createFile("writetest");
file.write(0, buffer);
buffer.flip();
file.read(0, buffer);
buffer.flip();
byte[] dst = new byte[20];
buffer.get(dst);
assertEquals("this is just a test!", new String(dst));
UsbFile bigFile = root.createFile("bigwritetest");
IOUtils.copy(bigFileUrl.openStream(), new UsbFileOutputStream(bigFile));
assertTrue(IOUtils.contentEquals(bigFileUrl.openStream(), new UsbFileInputStream(bigFile)));
UsbFile bigFileLargeBuffer = root.createFile("bigwritetestlargebuffer");
copyLarge(new UsbFileInputStream(bigFile),
new UsbFileOutputStream(bigFileLargeBuffer), new byte[7 * 32768]);
assertTrue(IOUtils.contentEquals(bigFileUrl.openStream(), new UsbFileInputStream(bigFileLargeBuffer)));
assertEquals(numberOfFiles + 3, root.listFiles().length);
newInstance();
file = root.search("writetest");
buffer.flip();
file.read(0, buffer);
buffer.flip();
buffer.get(dst);
assertEquals("this is just a test!", new String(dst));
bigFile = root.search("bigwritetest");
assertTrue(IOUtils.contentEquals(bigFileUrl.openStream(), new UsbFileInputStream(bigFile)));
bigFile = root.search("bigwritetestlargebuffer");
assertEquals(bigFileLargeBuffer.getLength(), bigFile.getLength());
assertTrue(IOUtils.contentEquals(bigFileUrl.openStream(), new UsbFileInputStream(bigFile)));
assertEquals(numberOfFiles + 3, root.listFiles().length);
}
@ContractTest
public void flush() throws Exception {
// TODO
}
@ContractTest
public void close() throws Exception {
// TODO
}
@ContractTest
public void createDirectory() throws Exception {
UsbFile directory = root.createDirectory("new dir");
UsbFile subDir = directory.createDirectory("new subdir");
assertTrue(root.search(directory.getName()).isDirectory());
assertTrue(root.search(directory.getName() + UsbFile.separator + subDir.getName()).isDirectory());
newInstance();
assertTrue(root.search(directory.getName()).isDirectory());
assertTrue(root.search(directory.getName() + UsbFile.separator + subDir.getName()).isDirectory());
try {
root.search(expectedValues.get("fileToCreateDirectoryOrFileOn").asString())
.createDirectory("should not happen");
fail("UsbFile did not throw UnsupportedOperationException on createDirectory");
} catch (UnsupportedOperationException e) {
}
try {
root.createDirectory(directory.getName());
fail("UsbFile did not throw IOException when creating same name dir");
} catch (IOException e) {
}
}
@ContractTest
public void createFile() throws Exception {
UsbFile file = root.createFile("new file");
UsbFile subFile = root.search(expectedValues.get("createFileInDir").asString()).
createFile("new file");
UsbFile specialCharFile = root.createFile("as~!@
UsbFile specialCharFile2 = root.createFile("as~!@
assertFalse(root.search(file.getName()).isDirectory());
assertFalse(root.search(specialCharFile.getName()).isDirectory());
assertFalse(root.search(specialCharFile2.getName()).isDirectory());
assertFalse(root.search(expectedValues.get("createFileInDir").asString() + UsbFile.separator + subFile.getName()).isDirectory());
newInstance();
assertFalse(root.search(file.getName()).isDirectory());
assertFalse(root.search("as~!@
assertFalse(root.search("as~!@
assertFalse(root.search(expectedValues.get("createFileInDir").asString() + UsbFile.separator + subFile.getName()).isDirectory());
try {
root.search(expectedValues.get("fileToCreateDirectoryOrFileOn").asString())
.createFile("should not happen");
fail("UsbFile did not throw UnsupportedOperationException on createFile");
} catch (UnsupportedOperationException e) {
}
try {
root.createFile(file.getName());
fail("UsbFile did not throw IOException when creating same name file");
} catch (IOException e) {
}
}
@ContractTest
public void moveFile() throws Exception {
JsonObject filesToMove = expectedValues.get("filesToMove").asObject();
for (JsonObject.Member member : filesToMove) {
UsbFile file = root.search(member.getName());
UsbFile dest = root.search(member.getValue().asString());
file.moveTo(dest);
// try to move dir into file
try {
dest.moveTo(file);
fail("Moving into file did not throw IllegalStateException");
} catch (IllegalStateException e) {
}
// try to move file into file
try {
file.moveTo(file);
fail("Moving into file did not throw IllegalStateException");
} catch (IllegalStateException e) {
}
}
for (JsonObject.Member member : filesToMove) {
UsbFile file = root.search(member.getName());
UsbFile dest = root.search(member.getValue().asString());
assertNull(file);
String path = member.getName();
int lastSep = path.lastIndexOf(UsbFile.separator);
if (lastSep == -1) lastSep = 0;
assertFalse(dest.search(path.substring(lastSep))
.isDirectory());
}
newInstance();
for (JsonObject.Member member : filesToMove) {
UsbFile file = root.search(member.getName());
UsbFile dest = root.search(member.getValue().asString());
assertNull(file);
String path = member.getName();
int lastSep = path.lastIndexOf(UsbFile.separator);
if (lastSep == -1) lastSep = 0;
file = dest.search(path.substring(lastSep));
assertFalse(file.isDirectory());
}
}
@ContractTest
public void moveDirectory() throws Exception {
JsonObject foldersToMove = expectedValues.get("foldersToMove").asObject();
for (JsonObject.Member member : foldersToMove) {
UsbFile file = root.search(member.getName());
UsbFile dest = root.search(member.getValue().asString());
file.moveTo(dest);
}
for (JsonObject.Member member : foldersToMove) {
UsbFile file = root.search(member.getName());
UsbFile dest = root.search(member.getValue().asString());
assertNull(file);
String path = member.getName();
int lastSep = path.lastIndexOf(UsbFile.separator);
if (lastSep == -1) lastSep = 0;
assertTrue(dest.search(path.substring(lastSep))
.isDirectory());
}
newInstance();
UsbFile lastDest = null;
for (JsonObject.Member member : foldersToMove) {
UsbFile file = root.search(member.getName());
UsbFile dest = root.search(member.getValue().asString());
assertNull(file);
String path = member.getName();
int lastSep = path.lastIndexOf(UsbFile.separator);
if (lastSep == -1) lastSep = 0;
assertTrue(dest.search(path.substring(lastSep))
.isDirectory());
lastDest = dest;
}
// try to move root dir
try {
root.moveTo(lastDest);
fail("Moving root dir did not throw IllegalStateException");
} catch (IllegalStateException e) {
}
cleanup();
newInstance();
}
@ContractTest
public void delete() throws Exception {
UsbFile fileToDelete = root.search(expectedValues.get("fileToDelete").asString());
UsbFile folderToDelete = root.search(expectedValues.get("folderToDelete").asString());
fileToDelete.delete();
folderToDelete.delete();
assertNull(root.search(expectedValues.get("fileToDelete").asString()));
assertNull(root.search(expectedValues.get("folderToDelete").asString()));
newInstance();
assertNull(root.search(expectedValues.get("fileToDelete").asString()));
assertNull(root.search(expectedValues.get("folderToDelete").asString()));
}
@ContractTest
public void deleteAll() throws Exception {
String path = expectedValues.get("subDeleteAll").asString();
UsbFile subDeleteAllFolder = root.search(path);
int parentCount = subDeleteAllFolder.getParent().list().length;
for (UsbFile file : subDeleteAllFolder.listFiles()) {
file.delete();
}
assertEquals(parentCount, subDeleteAllFolder.getParent().list().length);
assertEquals(0, subDeleteAllFolder.list().length);
newInstance();
subDeleteAllFolder = root.search(path);
assertEquals(parentCount, subDeleteAllFolder.getParent().list().length);
assertEquals(0, subDeleteAllFolder.list().length);
newInstance();
for (UsbFile file : root.listFiles()) {
file.delete();
}
assertEquals(0, root.list().length);
newInstance();
assertEquals(0, root.list().length);
}
@ContractTest
public void isRoot() throws Exception {
assertTrue(root.isRoot());
for (UsbFile file : root.listFiles()) {
assertFalse(file.isRoot());
}
}
private void checkAbsolutePathRecursive(String currentDir, UsbFile dir) throws IOException {
for (UsbFile file : dir.listFiles()) {
String test = currentDir + UsbFile.separator + file.getName();
if (currentDir.equals(UsbFile.separator)) {
test = UsbFile.separator + file.getName();
}
assertEquals(test, file.getAbsolutePath());
if (file.isDirectory()) {
String nextDir = currentDir + UsbFile.separator + file.getName();
if (currentDir.equals(UsbFile.separator)) {
nextDir = UsbFile.separator + file.getName();
}
checkAbsolutePathRecursive(nextDir, file);
}
}
}
@ContractTest
public void absolutePath() throws Exception {
assertEquals("/", root.getAbsolutePath());
checkAbsolutePathRecursive(UsbFile.separator, root);
}
private void checkEqualsRecursive(UsbFile dir) throws IOException {
for (UsbFile file : dir.listFiles()) {
if (file.isDirectory()) {
checkEqualsRecursive(file);
}
assertEquals(file, file);
}
}
@ContractTest
public void equals() throws Exception {
checkEqualsRecursive(root);
}
@ContractTest
public void createLotsOfFiles() throws IOException {
UsbFile dir = root.createDirectory("test_lots_of_files");
List<String> nameList = new ArrayList<>();
for(int i = 0; i < 4500; i++) {
String name = String.format("IMG_09082016_%06d", i);
nameList.add(name);
dir.createFile(name);
}
assertEquals(nameList.size(), dir.list().length);
assertEquals(nameList, dir.list());
newInstance();
dir = root.search("test_lots_of_files");
assertEquals(nameList.size(), dir.list().length);
assertEquals(nameList, dir.list());
}
@ContractTest
public void testIssue187() throws IOException {
UsbFile file = root.createFile("testissue187");
OutputStream outputStream = UsbFileStreamFactory.createBufferedOutputStream(file, fs);
outputStream.write("START\n".getBytes());
int i;
for (i = 6; i < 40000; i += 5) {
outputStream.write("TEST\n".getBytes());
}
outputStream.write("END\n".getBytes());
outputStream.close();
UsbFile srcPtr = root.search("testissue187");
long srcLen = srcPtr.getLength();
UsbFile dstPtr = root.createFile("testissue187_copy");
InputStream inputStream = UsbFileStreamFactory.createBufferedInputStream(srcPtr, fs);
OutputStream outStream = UsbFileStreamFactory.createBufferedOutputStream(dstPtr, fs);
byte[] bytes = new byte[fs.getChunkSize()];
dstPtr.setLength(srcLen);
int count;
while ((count=inputStream.read(bytes))>0) {
outStream.write(bytes,0,count);
}
inputStream.close();
outStream.close();
InputStream inputStream1 = UsbFileStreamFactory.createBufferedInputStream(srcPtr, fs);
InputStream inputStream2 = UsbFileStreamFactory.createBufferedInputStream(dstPtr, fs);
assertTrue(IOUtils.contentEquals(inputStream1, inputStream2));
}
@ContractTest
public void testIssue215() throws IOException {
UsbFile file1b1 = getFile(root, "Folder1a/Folder1b/File1b1.txt");
UsbFile file1b2 = getFile(root, "Folder1a/Folder1b/File1b2.txt");
UsbFile file1b3 = getFile(root, "Folder1a/Folder1b/File1b3.txt");
UsbFile file2a = getFile(root, "Folder2a/File2a.txt");
UsbFile file1 = getFile(root, "File1.txt");
OutputStream outputStream = new UsbFileOutputStream(file1b1);
outputStream.write(file1b1.getName().getBytes());
outputStream.close();
outputStream = new UsbFileOutputStream(file1b2);
outputStream.write(file1b2.getName().getBytes());
outputStream.close();
outputStream = new UsbFileOutputStream(file1b3);
outputStream.write(file1b3.getName().getBytes());
outputStream.close();
outputStream = new UsbFileOutputStream(file2a);
outputStream.write(file2a.getName().getBytes());
outputStream.close();
outputStream = new UsbFileOutputStream(file1);
outputStream.write(file1.getName().getBytes());
outputStream.close();
assertSame(file1b1.getParent(), file1b2.getParent());
assertSame(file1b1.getParent(), file1b2.getParent());
assertNotNull(root.search("Folder1a/Folder1b/File1b1.txt"));
assertNotNull(root.search("Folder1a/Folder1b/File1b2.txt"));
assertNotNull(root.search("Folder1a/Folder1b/File1b3.txt"));
assertTrue(IOUtils.contentEquals(new UsbFileInputStream(root.search("Folder1a/Folder1b/File1b3.txt")),
new ByteArrayInputStream("File1b3.txt".getBytes(StandardCharsets.UTF_8))));
assertTrue(IOUtils.contentEquals(new UsbFileInputStream(root.search("Folder1a/Folder1b/File1b1.txt")),
new ByteArrayInputStream("File1b1.txt".getBytes(StandardCharsets.UTF_8))));
assertTrue(IOUtils.contentEquals(new UsbFileInputStream(root.search("Folder1a/Folder1b/File1b2.txt")),
new ByteArrayInputStream("File1b2.txt".getBytes(StandardCharsets.UTF_8))));
newInstance();
assertNotNull(root.search("Folder1a/Folder1b/File1b1.txt"));
assertNotNull(root.search("Folder1a/Folder1b/File1b2.txt"));
assertNotNull(root.search("Folder1a/Folder1b/File1b3.txt"));
assertTrue(IOUtils.contentEquals(new UsbFileInputStream(root.search("Folder1a/Folder1b/File1b1.txt")),
new ByteArrayInputStream("File1b1.txt".getBytes(StandardCharsets.UTF_8))));
assertTrue(IOUtils.contentEquals(new UsbFileInputStream(root.search("Folder1a/Folder1b/File1b2.txt")),
new ByteArrayInputStream("File1b2.txt".getBytes(StandardCharsets.UTF_8))));
assertTrue(IOUtils.contentEquals(new UsbFileInputStream(root.search("Folder1a/Folder1b/File1b3.txt")),
new ByteArrayInputStream("File1b3.txt".getBytes(StandardCharsets.UTF_8))));
}
private static UsbFile getFile(UsbFile root, String path) throws IOException {
String[] items = path.split("/");
UsbFile child = root;
for (int i=0; i<items.length; ++i) {
UsbFile next = child.search(items[i]);
if (next == null) {
for (; i < items.length - 1; ++i)
child = child.createDirectory(items[i]);
child = child.createFile(items[i++]);
} else {
child = next;
}
}
return child;
}
}
|
package org.csstudio.display.builder.model;
import static org.csstudio.display.builder.model.ModelPlugin.logger;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propActions;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propHeight;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propName;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propRules;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propScripts;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propType;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propWidgetClass;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propWidth;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propX;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propY;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.csstudio.display.builder.model.macros.MacroOrPropertyProvider;
import org.csstudio.display.builder.model.macros.MacroValueProvider;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.display.builder.model.properties.ActionInfo;
import org.csstudio.display.builder.model.properties.RuleInfo;
import org.csstudio.display.builder.model.properties.ScriptInfo;
import org.csstudio.display.builder.model.widgets.EmbeddedDisplayWidget;
import org.osgi.framework.Version;
/** Base class for all widgets.
*
* <p>A Widget has properties, supporting read access, subscription
* and for most properties also write access.
*
* <p>Properties can be accessed in a most generic way based on the
* property name:
* <pre>
* getPropertyValue("text")
* setPropertyValue("text", "Hello")
* getPropertyValue("x")
* setPropertyValue("x", 60)
* </pre>
*
* <p>While this is ideal for access from scripts,
* Java code that deals with a specific widget can access
* properties in the type-safe way:
* <pre>
* LabelWidget label;
* label.positionX().getValue();
* label.positionX().setValue(60);
* </pre>
*
* <p>Widgets are part of a hierarchy.
* Their parent is either the {@link DisplayModel} or another
* widget with a {@link ChildrenProperty}
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class Widget
{
// These user data keys are reserved for internal use
// of the framework.
// On the API level, the Model (DisplayModel, Widgets)
// is independent from the Representation (ToolkitRepresentation)
// and Runtime (WidgetRuntime).
// The representation and runtime implementations, however,
// need to associate certain pieces of data with model elements,
// which is done via the following reserved user data keys.
// They all start with an underscore to indicate that they
// are meant to be private, not to be used as API.
/** Reserved widget user data key for storing the representation.
*
* <p>The WidgetRepresentation for each {@link Widget}
* is stored under this key.
*/
public static final String USER_DATA_REPRESENTATION = "_representation";
/** Reserved user data key for Widget that has 'children', i.e. is a parent,
* to store the toolkit parent item
*/
public static final String USER_DATA_TOOLKIT_PARENT = "_toolkit_parent";
/** Reserved widget user data key for storing the runtime.
*
* <p>The WidgetRuntime for each {@link Widget}
* is stored under this key.
*/
public static final String USER_DATA_RUNTIME = "_runtime";
/** Reserved widget user data key for storing script support.
*
* <p>ScriptSupport is attached to the top-level root
* of the widget tree, i.e. the {@link DisplayModel}
* that is obtained by traversing up via {@link EmbeddedDisplayWidget}s
* to the top-level model.
*/
public static final String USER_DATA_SCRIPT_SUPPORT = "_script_support";
/** Parent widget */
private volatile Widget parent = null;
/** All properties, ordered by category, then sequence of definition */
protected final Set<WidgetProperty<?>> properties;
// Design decision:
// Widget holds a map of properties: "name" -> CommonWidgetProperties.widgetName
// Could also depend on each widget defining getters/setters getName()/setName()
// and then use beam-type introspection, but this would not allow determining
// if a property has a default value, is a runtime-only property etc.
// A property accessor nameProperty() as used for JavaFX bindable properties
// would work as long as it preserves the order of properties.
// The implementation might later change from a property_map to
// introspection-based lookup of xxxProperty() accessors.
// The API for widget users would remain the same:
// getProperties(), getProperty(), getPropertyValue(), setPropertyValue()
/** Map of property names to properties */
// Map is final, all properties are collected in widget constructor.
// Values of properties can change, but the list of properties itself
// is thread safe
protected final Map<String, WidgetProperty<?>> property_map;
// Actual properties
private WidgetProperty<String> type;
private WidgetProperty<String> name;
private WidgetProperty<String> widget_class;
private WidgetProperty<Integer> x;
private WidgetProperty<Integer> y;
private WidgetProperty<Integer> width;
private WidgetProperty<Integer> height;
private WidgetProperty<List<ActionInfo>> actions;
private WidgetProperty<List<RuleInfo>> rules;
private WidgetProperty<List<ScriptInfo>> scripts;
/** Map of user data */
protected final Map<String, Object> user_data = new ConcurrentHashMap<>(4); // Reserve room for "representation", "runtime"
/** Widget constructor.
* @param type Widget type
*/
public Widget(final String type)
{
this(type, 100, 20);
}
/** Widget constructor.
* @param type Widget type
* @param default_width Default width
* @param default_height .. and height
*/
public Widget(final String type, final int default_width, final int default_height)
{
// Collect properties
final List<WidgetProperty<?>> prelim_properties = new ArrayList<>();
// -- Mandatory properties --
prelim_properties.add(this.type = propType.createProperty(this, type));
prelim_properties.add(name = propName.createProperty(this, ""));
prelim_properties.add(widget_class = propWidgetClass.createProperty(this, WidgetClassSupport.DEFAULT));
prelim_properties.add(x = propX.createProperty(this, 0));
prelim_properties.add(y = propY.createProperty(this, 0));
prelim_properties.add(width = propWidth.createProperty(this, default_width));
prelim_properties.add(height = propHeight.createProperty(this, default_height));
prelim_properties.add(actions = propActions.createProperty(this, Collections.emptyList()));
prelim_properties.add(rules = propRules.createProperty(this, Collections.emptyList()));
prelim_properties.add(scripts = propScripts.createProperty(this, Collections.emptyList()));
// -- Widget-specific properties --
defineProperties(prelim_properties);
if (prelim_properties.contains(null))
throw new IllegalStateException("Null properties");
// Sort by category, then order of definition.
// Prelim_properties has the original order of definition,
// which we want to preserve as a secondary sorting criteria
// after property category.
final List<WidgetProperty<?>> sorted = new ArrayList<>(prelim_properties.size());
sorted.addAll(prelim_properties);
final Comparator<WidgetProperty<?>> byCategory =
Comparator.comparing(WidgetProperty::getCategory);
final Comparator<WidgetProperty<?>> byOrder =
Comparator.comparingInt(p -> prelim_properties.indexOf(p));
Collections.sort(sorted, byCategory.thenComparing(byOrder));
// Capture as constant sorted set
properties = Collections.unmodifiableSet(new LinkedHashSet<>(sorted));
// Map for faster lookup by property name
property_map = properties.stream().collect(
Collectors.toMap(WidgetProperty::getName, Function.identity()));
}
/** Unique runtime identifier of a widget
*
* <p>At runtime, this ID can be used to construct
* PVs that are unique and specific to this instance
* of a widget.
* Even if the same display is opened multiple times
* within the same JVM, the widget is very likely
* to receive a new, unique identifier.
*
* @return Unique Runtime Identifier for widget
*/
public final String getID()
{ // Base on ID hash code
final int id = System.identityHashCode(this);
return "WD" + Integer.toHexString(id);
}
/** @return Widget version number */
public Version getVersion()
{
// Legacy used 1.0.0 for most widgets,
// so 2.0.0 indicates an update.
// Selected legacy widgets had incremented to a higher version,
// which needs to be handled for each such widget.
return new Version(2, 0, 0);
}
/** @return Widget Type */
public final String getType()
{
return type.getValue();
}
/** @return Widget Name */
public final String getName()
{
return name.getValue();
}
/** @return Widget class to use for updating properties that use the class */
public final String getWidgetClass()
{
return widget_class.getValue();
}
/** @return Parent widget in Widget tree */
public final Optional<Widget> getParent()
{
return Optional.ofNullable(parent);
}
/** Invoked by the parent widget
* @param parent Parent widget
*/
protected void setParent(final Widget parent)
{
if (parent == this)
throw new IllegalArgumentException();
this.parent = parent;
}
/** Locate display model, i.e. root of widget tree
*
* <p>Note that for embedded displays, this would
* return the embedded model, not the top-level
* model of the window.
* Compare <code>getTopDisplayModel()</code>
*
* @return {@link DisplayModel} for widget
* @throws Exception if widget is not part of a model
*/
public final DisplayModel getDisplayModel() throws Exception
{
final DisplayModel model = checkDisplayModel();
if (model == null)
throw new Exception("Missing DisplayModel for " + this);
return model;
}
/** Locate display model, i.e. root of widget tree
*
* @return {@link DisplayModel} for widget or <code>null</code>
* @see #getDisplayModel() version that throws exception
*/
public final DisplayModel checkDisplayModel()
{
Widget candidate = this;
while (candidate.getParent().isPresent())
candidate = candidate.getParent().get();
if (candidate instanceof DisplayModel)
return (DisplayModel) candidate;
return null;
}
/** Locate top display model.
*
* <p>For embedded displays, <code>getDisplayModel</code>
* only provides the embedded model.
* This method traverses up via the {@link EmbeddedDisplayWidget}
* to the top-level display model.
*
* @return Top-level {@link DisplayModel} for widget
* @throws Exception if widget is not part of a model
*/
public final DisplayModel getTopDisplayModel() throws Exception
{
DisplayModel model = getDisplayModel();
while (true)
{
final EmbeddedDisplayWidget embedder = model.getUserData(DisplayModel.USER_DATA_EMBEDDING_WIDGET);
if (embedder == null)
return model;
model = embedder.getTopDisplayModel();
}
}
/** Called on construction to define widget's properties.
*
* <p>Mandatory properties have already been defined.
* Derived class overrides to add its own properties.
*
* @param properties List to which properties must be added
*/
protected void defineProperties(final List<WidgetProperty<?>> properties)
{
// Derived class should invoke
// super.defineProperties(properties)
// and may then add its own properties.
}
// Accessors to properties are not strictly needed
// because of generic getProperty(..),
// but are useful in IDE when dealing with
// known widget type
/** @return 'name' property */
public final WidgetProperty<String> propName()
{
return name;
}
/** @return 'class' property */
public final WidgetProperty<String> propClass()
{
return widget_class;
}
/** @return 'x' property */
public final WidgetProperty<Integer> propX()
{
return x;
}
/** @return 'y' property */
public final WidgetProperty<Integer> propY()
{
return y;
}
/** @return 'width' property */
public final WidgetProperty<Integer> propWidth()
{
return width;
}
/** @return 'height' property */
public final WidgetProperty<Integer> propHeight()
{
return height;
}
/** @return 'actions' property */
public final WidgetProperty<List<ActionInfo>> propActions()
{
return actions;
}
/** @return 'rules' property */
public final WidgetProperty<List<RuleInfo>> propRules()
{
return rules;
}
/** @return 'scripts' property */
public final WidgetProperty<List<ScriptInfo>> propScripts()
{
return scripts;
}
/** Obtain configurator.
*
* <p>While typically using the default {@link WidgetConfigurator},
* widget may provide a different configurator for reading older
* persisted date.
* @param persisted_version Version of the persisted data.
* @return Widget configurator for that version
* @throws Exception if persisted version cannot be handled
*/
public WidgetConfigurator getConfigurator(final Version persisted_version)
throws Exception
{
// if (persisted_version.getMajor() < 1)
// throw new Exception("Can only handle version 1.0.0 and higher");
return new WidgetConfigurator(persisted_version);
}
/** Get all properties of the widget.
*
* <p>Properties are ordered by category and sequence of definition.
* @return Unmodifiable set
*/
public final Set<WidgetProperty<?>> getProperties()
{
return properties;
}
/** Helper for obtaining the complete property name 'paths'
*
* <p>For a scalar property, this method simply returns that property name.
*
* <p>For arrays or structures, it returns names for each array resp. structure element.
*
* @param property
* @return List of property names
*/
public static final List<String> expandPropertyNames(final WidgetProperty<?> property)
{
final List<String> names = new ArrayList<>();
doAddPropertyNames(names, property.getName(), property);
return names;
}
private static final void doAddPropertyNames(final List<String> names, String path, final WidgetProperty<?> property)
{
if (property instanceof ArrayWidgetProperty)
{
final ArrayWidgetProperty<?> array = (ArrayWidgetProperty<?>) property;
for (int i=0; i<array.size(); ++i)
doAddPropertyNames(names, path + "[" + i + "]", array.getElement(i));
}
else if (property instanceof StructuredWidgetProperty)
{
final StructuredWidgetProperty struct = (StructuredWidgetProperty) property;
for (int i=0; i<struct.size(); ++i)
{
final WidgetProperty<?> item = struct.getElement(i);
doAddPropertyNames(names, path + "." + item.getName(), item);
}
}
else
names.add(path);
}
/** Check if widget has a given property.
*
* <p>This is called by code that needs to
* test if a widget has a certain property.
*
* <p>Only checks for direct properties of
* the widget, neither mapping legacy property names
* nor allowing for complex property paths.
*
* @param name Property name
* @return Optional {@link WidgetProperty}
* @see #getProperty(String)
*/
public final <PT> Optional<WidgetProperty<PT>> checkProperty(final String name)
{
@SuppressWarnings("unchecked")
final WidgetProperty<PT> property = (WidgetProperty<PT>) property_map.get(name);
return Optional.ofNullable(property);
}
/** Check if widget has a given property.
* @param property Property descriptor
* @return Optional {@link WidgetProperty}
* @see #checkProperty(WidgetPropertyDescriptor)
*/
public final <PT> Optional<WidgetProperty<PT>> checkProperty(final WidgetPropertyDescriptor<PT> property_description)
{
return checkProperty(property_description.getName());
}
@SuppressWarnings("unchecked")
public final <PT> WidgetProperty<PT> getProperty(final WidgetPropertyDescriptor<PT> property_description)
{
final WidgetProperty<?> property = getProperty(property_description.getName());
return (WidgetProperty<PT>)property;
}
public WidgetProperty<?> getProperty(final String name) throws IllegalArgumentException, IndexOutOfBoundsException
{ // Is name a path "struct_prop.array_prop[2].element" ?
if (name.indexOf('.') >=0 || name.indexOf('[') >= 0)
return getPropertyByPath(name, false);
// Plain property name
final WidgetProperty<?> property = property_map.get(name);
if (property == null)
throw new IllegalArgumentException(toString() + " has no '" + name + "' property");
return property;
}
@SuppressWarnings("rawtypes")
public WidgetProperty<?> getPropertyByPath(final String path_name, final boolean create_elements) throws IllegalArgumentException, IndexOutOfBoundsException
{
final String[] path = path_name.split("\\.");
WidgetProperty<?> property = null;
for (String item : path)
{ // Does item refer to array element?
final String name;
final int index;
final int braces = item.indexOf('[');
if (braces >= 0)
{
if (! item.endsWith("]"))
throw new IllegalArgumentException("Missing ']' for end of array element");
name = item.substring(0, braces);
index = Integer.parseInt(item.substring(braces+1, item.length() - 1));
}
else
{
name = item;
index = -1;
}
// Get property for the 'name'.
// For first item, from widget. Later descent into structure.
if (property == null)
{
property = property_map.get(name);
if (property == null)
throw new IllegalArgumentException("Cannot locate '" + name + "' for '" + path_name + "'");
}
else if (property instanceof StructuredWidgetProperty)
property = ((StructuredWidgetProperty)property).getElement(name);
else
throw new IllegalArgumentException("Cannot locate '" + name + "' for '" + path_name + "'");
// Fetch individual array element?
if (index >= 0)
if (property instanceof ArrayWidgetProperty)
{
final ArrayWidgetProperty array = (ArrayWidgetProperty)property;
// Add array elements?
if (create_elements)
{
while (array.size() <= index)
array.addElement();
}
else
if (array.size() < index)
throw new IndexOutOfBoundsException("'" + name + "' of '" + path_name +
"' has only " + array.size() + " elements");
property = array.getElement(index);
}
else
throw new IllegalArgumentException("'" + name + "' of '" + path_name + "' it not an array");
}
return property;
}
public final <PT> PT getPropertyValue(final WidgetPropertyDescriptor<PT> property_description)
{
return getProperty(property_description).getValue();
}
@SuppressWarnings("unchecked")
public final <TYPE> TYPE getPropertyValue(final String name)
{
return (TYPE) getProperty(name).getValue();
}
public final <PT> void setPropertyValue(final WidgetPropertyDescriptor<PT> property_description,
final PT value)
{
getProperty(property_description).setValue(value);
}
public final void setPropertyValue(final String name,
final Object value) throws Exception
{
getProperty(name).setValueFromObject(value);
}
public Macros getEffectiveMacros()
{
final Optional<Widget> the_parent = getParent();
if (! the_parent.isPresent())
return null;
return the_parent.get().getEffectiveMacros();
}
/** @return Macro provider for effective macros, falling back to properties */
public MacroValueProvider getMacrosOrProperties()
{
return new MacroOrPropertyProvider(this);
}
/** Set user data
*
* <p>User code can attach arbitrary data to a widget.
* This data is _not_ persisted with the model,
* and there is no change notification.
*
* <p>User code should avoid using reserved keys
* which start with an underscore "_...".
*
* @param key Key
* @param data Data
*/
public final void setUserData(final String key, final Object data)
{
user_data.put(key, data);
}
/** @param key Key
* @param <TYPE> Data is cast to the receiver's type
* @return User data associated with key, or <code>null</code>
* @see #setUserData(String, Object)
*/
@SuppressWarnings("unchecked")
public final <TYPE> TYPE getUserData(final String key)
{
if (key == null)
{ // Debug gimmick:
// null is not supported as valid key,
// but triggers dump of all user properties
logger.info(this + " user data: " + user_data.entrySet());
return null;
}
final Object data = user_data.get(key);
return (TYPE)data;
}
/** Remove a user data entry
* @param key Key for which to remove user data
* @return User data associated with key that has been removed, or <code>null</code>
*/
@SuppressWarnings("unchecked")
public final <TYPE> TYPE clearUserData(final String key)
{
return (TYPE)user_data.remove(key);
}
@Override
public String toString()
{
// Show name's specification, not value, because otherwise
// a plain debug printout can trigger macro resolution for the name
return "Widget '" + ((MacroizedWidgetProperty<?>)name).getSpecification() + "' (" + getType() + ")";
}
}
|
package wombat.gui.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import javax.swing.event.CaretListener;
import javax.swing.event.CaretEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.StyleConstants;
import javax.swing.text.Utilities;
import wombat.gui.frames.MainFrame;
import wombat.util.errors.ErrorManager;
/**
* Used to highlight matching brackets (both square and rounded, but not angle
* or curly, although those could be added easily enough.
*/
public class BracketMatcher implements CaretListener {
// The text area that
SchemeTextArea textArea;
// If we can't match brackets enough times, disable them.
static boolean disabled = false;
// Any active brackets are moved before each new highlight.
List<Object> activeTags = new ArrayList<Object>();
/**
* Create a bracket matcher for a given text area.
*
* @param text
*/
public BracketMatcher(SchemeTextArea text) {
textArea = text;
}
/**
* When the caret moves, update the matched brackets.
*
* Also used to show the current line and column. TODO: Move this code to
* its own object.
*
* @param event
* Event parameters (ignored).
*/
public void caretUpdate(CaretEvent event) {
// Update the current row and column of the caret.
try {
// Find the current row of the caret.
int caretPos = textArea.code.getCaretPosition();
int rowNum = (caretPos == 0) ? 1 : 0;
for (int offset = caretPos; offset > 0;) {
offset = Utilities.getRowStart(textArea.code, offset) - 1;
rowNum++;
}
// Use that to find the current column.
int offset = Utilities.getRowStart(textArea.code, caretPos);
int colNum = caretPos - offset + 1;
MainFrame.Singleton().RowColumn.setText(rowNum + ":" + colNum);
}
// Can't find the caret correctly, reset the row:column indicator.
catch (BadLocationException ex) {
MainFrame.Singleton().RowColumn.setText("row:column");
}
// If the bracket matcher has broken, don't keep trying.
if (disabled)
return;
try {
// Get the highlighter and remove all active tags.
Highlighter h = textArea.code.getHighlighter();
for (Object tag : activeTags)
h.removeHighlight(tag);
activeTags.clear();
// Get the caret position.
int pos = event.getDot() - 1;
// If the caret is in the document and adjacent to a bracket.
if (pos >= 0
&& pos < textArea.getText().length()
&& "()[]".contains(textArea.code.getDocument().getText(pos, 1))) {
// Get a direct link to the full text of the document to speed up future access.
String text = textArea.code.getDocument().getText(0, textArea.code.getDocument().getLength());
// Skip character literals
if (pos >= 2 && "#\\".equals(text.substring(pos - 2, pos)))
return;
// Skip if we're in a comment
if ((text.lastIndexOf("#|", pos) > text.lastIndexOf("|#", pos))
|| (text.lastIndexOf(';', pos) > text.lastIndexOf('\n', pos)))
return;
// Which way are we going?
char orig, c;
orig = c = text.charAt(pos);
int matchPos, d = ((orig == '(' || orig == '[') ? 1 : -1);
// Keep a stack of brackets so we find the correct level.
Stack<Character> brackets = new Stack<Character>();
// Loop either forward or back depending on opening or closing initial bracket.
int index;
boolean foundMatch = false;
for (matchPos = pos; matchPos >= 0 && matchPos < text.length(); matchPos += d) {
// When moving towards the front:
if (d < 0) {
// Ignore line comments.
index = text.lastIndexOf(';', matchPos);
if (index >= 0 && index > text.lastIndexOf("\n", matchPos)) {
matchPos = index;
continue;
}
// Ignore block comments.
index = text.lastIndexOf("#|", matchPos);
if (index >= 0 && index < matchPos && matchPos < text.indexOf("|
matchPos = index;
continue;
}
}
// When moving towards the end:
else {
// Ignore line comments.
index = text.lastIndexOf(';', matchPos);
if (index >= 0 && text.lastIndexOf('\n', matchPos) < index) {
matchPos = text.indexOf('\n', matchPos);
if (matchPos < 0) break;
continue;
}
// Ignore block comments.
index = text.indexOf("|#", matchPos);
if (index >= 0 && text.lastIndexOf("#|", matchPos) < matchPos && matchPos < index) {
matchPos = index;
continue;
}
}
// Get the current character.
c = text.charAt(matchPos);
// Ignore character literals
if (matchPos >= 2 && "#\\".equals(text.substring(matchPos - 2, matchPos)))
continue;
// We're only done when we're at the correct level and find the correct bracket.
if (!brackets.isEmpty() && brackets.peek() == c) {
brackets.pop();
if (brackets.isEmpty()) {
foundMatch = true;
break;
}
}
// If we still have brackets to deal with, make sure it's the correct kind.
// If it's the incorrect kind, highligh with an error (default = red).
else if (!brackets.isEmpty()
&& ((brackets.peek() == '(' && c == '[')
|| (brackets.peek() == '[' && c == '(')
|| (brackets.peek() == ')' && c == ']')
|| (brackets.peek() == ']' && c == ')'))) {
foundMatch = false;
break;
}
// Remember bracket level.
else if (c == '(')
brackets.push(')');
else if (c == ')')
brackets.push('(');
else if (c == '[')
brackets.push(']');
else if (c == ']')
brackets.push('[');
}
// Highlight it.
Highlighter.HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(
StyleConstants.getForeground(SchemeDocument.attributes.get(foundMatch ? "bracket" : "invalid-bracket")));
// Remember the bracket so we can remove it on the next cycle.
try {
activeTags.add(h.addHighlight(pos, pos + 1, hp));
activeTags.add(h.addHighlight(matchPos, matchPos + 1, hp));
} catch (BadLocationException ble) {
}
}
}
// Ignore bad locations. This is usually empty documents.
catch (BadLocationException ex) {
}
// If we get this, we broke the bracket matcher. Remember the error and disable it for the future.
// This shouldn't happen unless things go badly wrong.
catch (Exception ex) {
ErrorManager.logError("Unable to match paranthesis: " + ex.getMessage());
ex.printStackTrace();
disabled = true;
}
}
}
|
package org.navalplanner.business.test.resources.services;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.resources.daos.IResourceDao;
import org.navalplanner.business.resources.entities.ResourceGroup;
import org.navalplanner.business.resources.entities.Worker;
import org.navalplanner.business.resources.services.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.navalplanner.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE;
import static org.navalplanner.business.test.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_TEST_FILE;
/**
* A class for testing <code>ResourceService</code>. The service and the
* resource DAOs are autowired.
* @author Fernando Bellas Permuy <fbellas@udc.es>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
@Transactional
public class ResourceServiceTest {
@Autowired
private ResourceService resourceService;
@Autowired
private IResourceDao resourceDao;
@Test
public void testAddResourceToResourceGroup()
throws InstanceNotFoundException {
/* Two workers. One of them belongs to a resource group. */
Worker worker1 = new Worker("worker-1", "worker-1-surname",
"11111111A", 8);
Worker worker2 = new Worker("worker-2", "worker-2-surname",
"22222222B", 7);
ResourceGroup resourceGroup1 = new ResourceGroup();
resourceGroup1.addResource(worker1);
resourceService.saveResource(resourceGroup1); // worker1 is also saved.
resourceService.saveResource(worker2);
/* A resource group. */
ResourceGroup resourceGroup2 = new ResourceGroup();
resourceService.saveResource(resourceGroup2);
/* Add workers to resource group. */
resourceService.addResourceToResourceGroup(worker1.getId(),
resourceGroup2.getId());
resourceService.addResourceToResourceGroup(worker2.getId(),
resourceGroup2.getId());
/* Check resource group. */
ResourceGroup resourceGroup = (ResourceGroup) resourceService
.findResource(resourceGroup2.getId());
assertEquals(2, resourceGroup.getResources().size());
assertTrue(resourceGroup.getResources().contains(worker1));
assertTrue(resourceGroup.getResources().contains(worker2));
/* Check worker1 is no longer in group 1. */
assertFalse(resourceGroup1.getResources().contains(worker1));
}
@Test
public void testGetResourceDailyCapacity() throws InstanceNotFoundException {
/* Three workers. */
Worker worker1 = new Worker("worker-1", "worker-1-surname",
"11111111A", 8);
Worker worker2 = new Worker("worker-2", "worker-2-surname",
"22222222B", 7);
Worker worker3 = new Worker("worker-3", "worker-3-surname",
"33333333C", 6);
/* A group of two workers. */
ResourceGroup resourceGroup1 = new ResourceGroup();
Worker worker4 = new Worker("worker-4", "worker-4-surname",
"44444444D", 5);
Worker worker5 = new Worker("worker-5", "worker-5-surname",
"55555555E", 4);
resourceGroup1.addResource(worker4);
resourceGroup1.addResource(worker5);
/*
* A complex group containing the first three workers and a group with
* the last two workers.
*/
ResourceGroup resourceGroup2 = new ResourceGroup();
resourceGroup2.addResource(worker1);
resourceGroup2.addResource(worker2);
resourceGroup2.addResource(worker3);
resourceGroup2.addResource(resourceGroup1);
/* Calculate total daily capacity. */
int totalDailyCapacity = worker1.getDailyCapacity()
+ worker2.getDailyCapacity() + worker3.getDailyCapacity()
+ worker4.getDailyCapacity() + worker5.getDailyCapacity();
/* Save the second group (and in consequence all resources). */
resourceService.saveResource(resourceGroup2);
/* Test ResourceService's getResourceDailyCapacity. */
int resourceGroupDailyCapacity = resourceService
.getResourceDailyCapacity(resourceGroup2.getId());
assertEquals(totalDailyCapacity, resourceGroupDailyCapacity);
}
@Test
public void testRemoveResource() throws InstanceNotFoundException {
/* A group of three workers. */
ResourceGroup resourceGroup = new ResourceGroup();
Worker worker1 = new Worker("worker-1", "worker-2-surname",
"11111111A", 8);
Worker worker2 = new Worker("worker-2", "worker-3-surname",
"22222222B", 6);
Worker worker3 = new Worker("worker-3", "worker-3-surname",
"33333333C", 4);
resourceGroup.addResource(worker1);
resourceGroup.addResource(worker2);
resourceGroup.addResource(worker3);
resourceService.saveResource(resourceGroup);
/* Remove worker 3. */
resourceService.removeResource(worker3.getId());
/* Check worker 3 does not exist. */
assertFalse(resourceDao.exists(worker3.getId()));
/*
* Check worker 3 is not in resource group and the other workers are
* still in the group.
*/
assertFalse(resourceGroup.getResources().contains(worker3));
assertTrue(resourceGroup.getResources().contains(worker1));
assertTrue(resourceGroup.getResources().contains(worker2));
/* Remove the group. */
resourceService.removeResource(resourceGroup.getId());
/* Check the resource group does not exist. */
assertFalse(resourceDao.exists(resourceGroup.getId()));
/* Check workers still exist. */
assertTrue(resourceDao.exists(worker1.getId()));
assertTrue(resourceDao.exists(worker2.getId()));
/* Check workers do not belong to any resource group. */
assertNull(worker1.getResourceGroup());
assertNull(worker2.getResourceGroup());
/* Remove workers. */
resourceService.removeResource(worker1.getId());
resourceService.removeResource(worker2.getId());
/* Check workers do not exist. */
assertFalse(resourceDao.exists(worker1.getId()));
assertFalse(resourceDao.exists(worker2.getId()));
}
@Test
public void testListWorkers() throws Exception {
final int previousWorkers = resourceService.getWorkers().size();
ResourceGroup resourceGroup = new ResourceGroup();
Worker worker1 = new Worker("worker-1", "worker-2-surname",
"11111111A", 8);
Worker worker2 = new Worker("worker-2", "worker-3-surname",
"22222222B", 6);
Worker worker3 = new Worker("worker-3", "worker-3-surname",
"33333333C", 4);
resourceGroup.addResource(worker1);
resourceGroup.addResource(worker2);
resourceService.saveResource(resourceGroup);
assertEquals(
"Two workers has been created when saving the resource group",
previousWorkers + 2, resourceService.getWorkers().size());
resourceService.saveResource(worker3);
assertEquals("Three workers has been created", previousWorkers + 3,
resourceService.getWorkers().size());
}
}
|
package com.github.clans.fab;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
public class FloatingActionMenu extends ViewGroup {
private static final int ANIMATION_DURATION = 300;
private static final float CLOSED_PLUS_ROTATION = 0f;
private static final float OPENED_PLUS_ROTATION_LEFT = -90f - 45f;
private static final float OPENED_PLUS_ROTATION_RIGHT = 90f + 45f;
private static final int OPEN_UP = 0;
private static final int OPEN_DOWN = 1;
private static final int LABELS_POSITION_LEFT = 0;
private static final int LABELS_POSITION_RIGHT = 1;
private AnimatorSet mOpenAnimatorSet = new AnimatorSet();
private AnimatorSet mCloseAnimatorSet = new AnimatorSet();
private AnimatorSet mIconToggleSet;
private int mButtonSpacing = Util.dpToPx(getContext(), 0f);
private int mInitialButtonsOffset = Util.dpToPx(getContext(), 0f);
private FloatingActionButton mMenuButton;
private String mMenuButtonLabelText;
private int mMaxButtonWidth;
private int mLabelsMargin = Util.dpToPx(getContext(), 0f);
private int mLabelsVerticalOffset = Util.dpToPx(getContext(), 0f);
private int mButtonsCount;
private boolean mMenuOpened;
private Handler mUiHandler = new Handler();
private int mLabelsShowAnimation;
private int mLabelsHideAnimation;
private int mLabelsPaddingTop = Util.dpToPx(getContext(), 4f);
private int mLabelsPaddingRight = Util.dpToPx(getContext(), 8f);
private int mLabelsPaddingBottom = Util.dpToPx(getContext(), 4f);
private int mLabelsPaddingLeft = Util.dpToPx(getContext(), 8f);
private int mLabelsTextColor;
private float mLabelsTextSize;
private int mLabelsCornerRadius = Util.dpToPx(getContext(), 3f);
private boolean mLabelsShowShadow;
private int mLabelsColorNormal;
private int mLabelsColorPressed;
private int mLabelsColorRipple;
private boolean mMenuShowShadow;
private int mMenuShadowColor;
private float mMenuShadowRadius = 4f;
private float mMenuShadowXOffset = 1f;
private float mMenuShadowYOffset = 3f;
private int mMenuColorNormal;
private int mMenuColorPressed;
private int mMenuColorRipple;
private Drawable mIcon;
private int mAnimationDelayPerItem;
private Interpolator mOpenInterpolator;
private Interpolator mCloseInterpolator;
private boolean mIsAnimated = true;
private boolean mLabelsSingleLine;
private int mLabelsEllipsize;
private int mLabelsMaxLines;
private int mMenuFabSize;
private int mLabelsStyle;
private boolean mIconAnimated = true;
private ImageView mImageToggle;
private Animation mMenuButtonShowAnimation;
private Animation mMenuButtonHideAnimation;
private boolean mIsMenuButtonAnimationRunning;
private boolean mIsSetClosedOnTouchOutside;
private int mOpenDirection;
private OnMenuToggleListener mToggleListener;
private ValueAnimator mShowBackgroundAnimator;
private ValueAnimator mHideBackgroundAnimator;
private int mBackgroundColor;
private int mLabelsPosition;
private OnClickListener mOnOpenMenuButtonClickListener;
private boolean mAnimateOnCloseIfActiveMenuButtonClickListener = true;
public interface OnMenuToggleListener {
void onMenuToggle(boolean opened);
}
public FloatingActionMenu(Context context) {
this(context, null);
}
public FloatingActionMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FloatingActionMenu(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.FloatingActionMenu, 0, 0);
mButtonSpacing = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_buttonSpacing, mButtonSpacing);
mInitialButtonsOffset = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_initalButtonsOffset, mInitialButtonsOffset);
mLabelsMargin = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_margin, mLabelsMargin);
mLabelsPosition = attr.getInt(R.styleable.FloatingActionMenu_menu_labels_position, LABELS_POSITION_LEFT);
mLabelsShowAnimation = attr.getResourceId(R.styleable.FloatingActionMenu_menu_labels_showAnimation,
mLabelsPosition == LABELS_POSITION_LEFT ? R.anim.fab_slide_in_from_right : R.anim.fab_slide_in_from_left);
mLabelsHideAnimation = attr.getResourceId(R.styleable.FloatingActionMenu_menu_labels_hideAnimation,
mLabelsPosition == LABELS_POSITION_LEFT ? R.anim.fab_slide_out_to_right : R.anim.fab_slide_out_to_left);
mLabelsPaddingTop = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_paddingTop, mLabelsPaddingTop);
mLabelsPaddingRight = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_paddingRight, mLabelsPaddingRight);
mLabelsPaddingBottom = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_paddingBottom, mLabelsPaddingBottom);
mLabelsPaddingLeft = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_paddingLeft, mLabelsPaddingLeft);
mLabelsTextColor = attr.getColor(R.styleable.FloatingActionMenu_menu_labels_textColor, Color.WHITE);
mLabelsTextSize = attr.getDimension(R.styleable.FloatingActionMenu_menu_labels_textSize, getResources().getDimension(R.dimen.labels_text_size));
mLabelsCornerRadius = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_cornerRadius, mLabelsCornerRadius);
mLabelsShowShadow = attr.getBoolean(R.styleable.FloatingActionMenu_menu_labels_showShadow, true);
mLabelsColorNormal = attr.getColor(R.styleable.FloatingActionMenu_menu_labels_colorNormal, 0xFF333333);
mLabelsColorPressed = attr.getColor(R.styleable.FloatingActionMenu_menu_labels_colorPressed, 0xFF444444);
mLabelsColorRipple = attr.getColor(R.styleable.FloatingActionMenu_menu_labels_colorRipple, 0x66FFFFFF);
mMenuShowShadow = attr.getBoolean(R.styleable.FloatingActionMenu_menu_showShadow, true);
mMenuShadowColor = attr.getColor(R.styleable.FloatingActionMenu_menu_shadowColor, 0x66000000);
mMenuShadowRadius = attr.getDimension(R.styleable.FloatingActionMenu_menu_shadowRadius, mMenuShadowRadius);
mMenuShadowXOffset = attr.getDimension(R.styleable.FloatingActionMenu_menu_shadowXOffset, mMenuShadowXOffset);
mMenuShadowYOffset = attr.getDimension(R.styleable.FloatingActionMenu_menu_shadowYOffset, mMenuShadowYOffset);
mMenuColorNormal = attr.getColor(R.styleable.FloatingActionMenu_menu_colorNormal, 0xFFDA4336);
mMenuColorPressed = attr.getColor(R.styleable.FloatingActionMenu_menu_colorPressed, 0xFFE75043);
mMenuColorRipple = attr.getColor(R.styleable.FloatingActionMenu_menu_colorRipple, 0x99FFFFFF);
mAnimationDelayPerItem = attr.getInt(R.styleable.FloatingActionMenu_menu_animationDelayPerItem, 50);
mIcon = attr.getDrawable(R.styleable.FloatingActionMenu_menu_icon);
if (mIcon == null) {
mIcon = getResources().getDrawable(R.drawable.fab_add);
}
mIconAnimated = attr.getBoolean(R.styleable.FloatingActionMenu_menu_menuButton_animate, true);
mMenuButtonLabelText = attr.getString(R.styleable.FloatingActionMenu_menu_button_label);
mLabelsSingleLine = attr.getBoolean(R.styleable.FloatingActionMenu_menu_labels_singleLine, false);
mLabelsEllipsize = attr.getInt(R.styleable.FloatingActionMenu_menu_labels_ellipsize, 0);
mLabelsMaxLines = attr.getInt(R.styleable.FloatingActionMenu_menu_labels_maxLines, -1);
mMenuFabSize = attr.getInt(R.styleable.FloatingActionMenu_menu_fab_size, FloatingActionButton.SIZE_NORMAL);
mLabelsStyle = attr.getResourceId(R.styleable.FloatingActionMenu_menu_labels_style, 0);
mOpenDirection = attr.getInt(R.styleable.FloatingActionMenu_menu_openDirection, OPEN_UP);
mBackgroundColor = attr.getColor(R.styleable.FloatingActionMenu_menu_backgroundColor, Color.TRANSPARENT);
if (attr.hasValue(R.styleable.FloatingActionMenu_menu_labels_padding)) {
int padding = attr.getDimensionPixelSize(R.styleable.FloatingActionMenu_menu_labels_padding, 0);
initPadding(padding);
}
attr.recycle();
mOpenInterpolator = new OvershootInterpolator();
mCloseInterpolator = new AnticipateInterpolator();
initMenuButtonAnimations();
initBackgroundDimAnimation();
createMenuButton();
}
private void initMenuButtonAnimations() {
mMenuButtonShowAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.fab_scale_up);
mMenuButtonHideAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.fab_scale_down);
}
private void initBackgroundDimAnimation() {
final int maxAlpha = Color.alpha(mBackgroundColor);
final int red = Color.red(mBackgroundColor);
final int green = Color.green(mBackgroundColor);
final int blue = Color.blue(mBackgroundColor);
mShowBackgroundAnimator = ValueAnimator.ofInt(0, maxAlpha);
mShowBackgroundAnimator.setDuration(ANIMATION_DURATION);
mShowBackgroundAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer alpha = (Integer) animation.getAnimatedValue();
setBackgroundColor(Color.argb(alpha, red, green, blue));
}
});
mHideBackgroundAnimator = ValueAnimator.ofInt(maxAlpha, 0);
mHideBackgroundAnimator.setDuration(ANIMATION_DURATION);
mHideBackgroundAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer alpha = (Integer) animation.getAnimatedValue();
setBackgroundColor(Color.argb(alpha, red, green, blue));
}
});
}
private boolean isBackgroundEnabled() {
return mBackgroundColor != Color.TRANSPARENT;
}
private void initPadding(int padding) {
mLabelsPaddingTop = padding;
mLabelsPaddingRight = padding;
mLabelsPaddingBottom = padding;
mLabelsPaddingLeft = padding;
}
private void createMenuButton() {
mMenuButton = new FloatingActionButton(getContext());
mMenuButton.mShowShadow = mMenuShowShadow;
if (mMenuShowShadow) {
mMenuButton.mShadowRadius = Util.dpToPx(getContext(), mMenuShadowRadius);
mMenuButton.mShadowXOffset = Util.dpToPx(getContext(), mMenuShadowXOffset);
mMenuButton.mShadowYOffset = Util.dpToPx(getContext(), mMenuShadowYOffset);
}
mMenuButton.setColors(mMenuColorNormal, mMenuColorPressed, mMenuColorRipple);
mMenuButton.mShadowColor = mMenuShadowColor;
mMenuButton.mFabSize = mMenuFabSize;
mMenuButton.setLabelText(mMenuButtonLabelText);
mMenuButton.updateBackground();
mMenuButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnOpenMenuButtonClickListener != null && isOpened()) {
toggle(mAnimateOnCloseIfActiveMenuButtonClickListener);
mOnOpenMenuButtonClickListener.onClick(v);
} else {
toggle(mIsAnimated);
}
}
});
mImageToggle = new ImageView(getContext());
mImageToggle.setImageDrawable(mIcon);
addView(mMenuButton, super.generateDefaultLayoutParams());
addView(mImageToggle);
createDefaultIconAnimation();
}
private void createDefaultIconAnimation() {
ObjectAnimator collapseAnimator = ObjectAnimator.ofFloat(
mImageToggle,
"rotation",
mLabelsPosition == LABELS_POSITION_LEFT ? OPENED_PLUS_ROTATION_LEFT : OPENED_PLUS_ROTATION_RIGHT,
CLOSED_PLUS_ROTATION
);
ObjectAnimator expandAnimator = ObjectAnimator.ofFloat(
mImageToggle,
"rotation",
CLOSED_PLUS_ROTATION,
mLabelsPosition == LABELS_POSITION_LEFT ? OPENED_PLUS_ROTATION_LEFT : OPENED_PLUS_ROTATION_RIGHT);
mOpenAnimatorSet.play(expandAnimator);
mCloseAnimatorSet.play(collapseAnimator);
mOpenAnimatorSet.setInterpolator(mOpenInterpolator);
mCloseAnimatorSet.setInterpolator(mCloseInterpolator);
mOpenAnimatorSet.setDuration(ANIMATION_DURATION);
mCloseAnimatorSet.setDuration(ANIMATION_DURATION);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = 0;
int maxLabelWidth = 0;
measureChildWithMargins(mMenuButton, widthMeasureSpec, 0, heightMeasureSpec, 0);
mMaxButtonWidth = Math.max(0, mMenuButton.getMeasuredWidth());
measureChildWithMargins(mImageToggle, widthMeasureSpec, 0, heightMeasureSpec, 0);
for (int i = 0; i < mButtonsCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() == GONE || child == mImageToggle) continue;
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
mMaxButtonWidth = Math.max(mMaxButtonWidth, child.getMeasuredWidth());
}
for (int i = 0; i < mButtonsCount; i++) {
int usedWidth = 0;
View child = getChildAt(i);
if (child.getVisibility() == GONE || child == mImageToggle) continue;
usedWidth += child.getMeasuredWidth();
height += child.getMeasuredHeight();
Label label = (Label) child.getTag(R.id.fab_label);
if (label != null) {
int labelOffset = (mMaxButtonWidth - child.getMeasuredWidth()) / 2;
int labelUsedWidth = child.getMeasuredWidth() + label.calculateShadowWidth() + mLabelsMargin + labelOffset;
measureChildWithMargins(label, widthMeasureSpec, labelUsedWidth, heightMeasureSpec, 0);
usedWidth += label.getMeasuredWidth();
maxLabelWidth = Math.max(maxLabelWidth, usedWidth + labelOffset);
}
}
width = Math.max(mMaxButtonWidth, maxLabelWidth + mLabelsMargin) + getPaddingLeft() + getPaddingRight();
height += mInitialButtonsOffset + mButtonSpacing * (getChildCount() - 1) + getPaddingTop() + getPaddingBottom();
height = adjustForOvershoot(height);
if (getLayoutParams().width == LayoutParams.MATCH_PARENT) {
width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
}
if (getLayoutParams().height == LayoutParams.MATCH_PARENT) {
height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
}
setMeasuredDimension(width, height);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int buttonsHorizontalCenter = mLabelsPosition == LABELS_POSITION_LEFT
? r - l - mMaxButtonWidth / 2 - getPaddingRight()
: mMaxButtonWidth / 2 + getPaddingLeft();
boolean openUp = mOpenDirection == OPEN_UP;
int menuButtonTop = openUp
? b - t - mMenuButton.getMeasuredHeight() - getPaddingBottom()
: getPaddingTop();
int menuButtonLeft = buttonsHorizontalCenter - mMenuButton.getMeasuredWidth() / 2;
mMenuButton.layout(menuButtonLeft, menuButtonTop, menuButtonLeft + mMenuButton.getMeasuredWidth(),
menuButtonTop + mMenuButton.getMeasuredHeight());
int imageLeft = buttonsHorizontalCenter - mImageToggle.getMeasuredWidth() / 2;
int imageTop = menuButtonTop + mMenuButton.getMeasuredHeight() / 2 - mImageToggle.getMeasuredHeight() / 2;
mImageToggle.layout(imageLeft, imageTop, imageLeft + mImageToggle.getMeasuredWidth(),
imageTop + mImageToggle.getMeasuredHeight());
int nextY = openUp
? menuButtonTop - mButtonSpacing - mInitialButtonsOffset
: menuButtonTop + mMenuButton.getMeasuredHeight() + mButtonSpacing + mInitialButtonsOffset;
// measure label for menu-button
View label = (View) mMenuButton.getTag(R.id.fab_label);
if (label != null) {
int labelsOffset = mMenuButton.getMeasuredWidth() / 2 + mLabelsMargin;
int labelXNearButton = mLabelsPosition == LABELS_POSITION_LEFT
? buttonsHorizontalCenter - labelsOffset
: buttonsHorizontalCenter + labelsOffset;
int labelXAwayFromButton = mLabelsPosition == LABELS_POSITION_LEFT
? labelXNearButton - label.getMeasuredWidth()
: labelXNearButton + label.getMeasuredWidth();
int labelLeft = mLabelsPosition == LABELS_POSITION_LEFT
? labelXAwayFromButton
: labelXNearButton;
int labelRight = mLabelsPosition == LABELS_POSITION_LEFT
? labelXNearButton
: labelXAwayFromButton;
int childY = menuButtonTop;
int labelTop = childY - mLabelsVerticalOffset + (mMenuButton.getMeasuredHeight()
- label.getMeasuredHeight()) / 2;
label.layout(labelLeft, labelTop, labelRight, labelTop + label.getMeasuredHeight());
if (!mMenuOpened) {
label.setVisibility(INVISIBLE);
}
}
for (int i = mButtonsCount - 1; i >= 0; i
View child = getChildAt(i);
if (child == mImageToggle) continue;
FloatingActionButton fab = (FloatingActionButton) child;
if (fab == mMenuButton || fab.getVisibility() == GONE) continue;
int childX = buttonsHorizontalCenter - fab.getMeasuredWidth() / 2;
int childY = openUp ? nextY - fab.getMeasuredHeight() : nextY;
fab.layout(childX, childY, childX + fab.getMeasuredWidth(),
childY + fab.getMeasuredHeight());
if (!mMenuOpened) {
fab.hide(false);
}
label = (View) fab.getTag(R.id.fab_label);
if (label != null) {
int labelsOffset = fab.getMeasuredWidth() / 2 + mLabelsMargin;
int labelXNearButton = mLabelsPosition == LABELS_POSITION_LEFT
? buttonsHorizontalCenter - labelsOffset
: buttonsHorizontalCenter + labelsOffset;
int labelXAwayFromButton = mLabelsPosition == LABELS_POSITION_LEFT
? labelXNearButton - label.getMeasuredWidth()
: labelXNearButton + label.getMeasuredWidth();
int labelLeft = mLabelsPosition == LABELS_POSITION_LEFT
? labelXAwayFromButton
: labelXNearButton;
int labelRight = mLabelsPosition == LABELS_POSITION_LEFT
? labelXNearButton
: labelXAwayFromButton;
int labelTop = childY - mLabelsVerticalOffset + (fab.getMeasuredHeight()
- label.getMeasuredHeight()) / 2;
label.layout(labelLeft, labelTop, labelRight, labelTop + label.getMeasuredHeight());
if (!mMenuOpened) {
label.setVisibility(INVISIBLE);
}
}
nextY = openUp
? childY - mButtonSpacing
: childY + child.getMeasuredHeight() + mButtonSpacing;
}
}
private int adjustForOvershoot(int dimension) {
return dimension * 12 / 10;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
bringChildToFront(mMenuButton);
bringChildToFront(mImageToggle);
mButtonsCount = getChildCount();
createLabels();
}
private void createLabels() {
Context context = new ContextThemeWrapper(getContext(), mLabelsStyle);
for (int i = 0; i < mButtonsCount; i++) {
if (getChildAt(i) == mImageToggle) continue;
final FloatingActionButton fab = (FloatingActionButton) getChildAt(i);
String text = fab.getLabelText();
if (TextUtils.isEmpty(text) || fab.getTag(R.id.fab_label) != null) {
continue;
}
final Label label = new Label(context);
label.setFab(fab);
label.setShowAnimation(AnimationUtils.loadAnimation(getContext(), mLabelsShowAnimation));
label.setHideAnimation(AnimationUtils.loadAnimation(getContext(), mLabelsHideAnimation));
if (mLabelsStyle > 0) {
label.setTextAppearance(getContext(), mLabelsStyle);
label.setShowShadow(false);
label.setUsingStyle(true);
} else {
label.setColors(mLabelsColorNormal, mLabelsColorPressed, mLabelsColorRipple);
label.setShowShadow(mLabelsShowShadow);
label.setCornerRadius(mLabelsCornerRadius);
if (mLabelsEllipsize > 0) {
setLabelEllipsize(label);
}
label.setMaxLines(mLabelsMaxLines);
label.updateBackground();
label.setTextSize(TypedValue.COMPLEX_UNIT_PX, mLabelsTextSize);
label.setTextColor(mLabelsTextColor);
int left = mLabelsPaddingLeft;
int top = mLabelsPaddingTop;
if (mLabelsShowShadow) {
left += fab.getShadowRadius() + Math.abs(fab.getShadowXOffset());
top += fab.getShadowRadius() + Math.abs(fab.getShadowYOffset());
}
label.setPadding(
left,
top,
mLabelsPaddingLeft,
mLabelsPaddingTop
);
if (mLabelsMaxLines < 0 || mLabelsSingleLine) {
label.setSingleLine(mLabelsSingleLine);
}
}
label.setText(text);
addView(label);
fab.setTag(R.id.fab_label, label);
}
}
private void setLabelEllipsize(Label label) {
switch (mLabelsEllipsize) {
case 1:
label.setEllipsize(TextUtils.TruncateAt.START);
break;
case 2:
label.setEllipsize(TextUtils.TruncateAt.MIDDLE);
break;
case 3:
label.setEllipsize(TextUtils.TruncateAt.END);
break;
case 4:
label.setEllipsize(TextUtils.TruncateAt.MARQUEE);
break;
}
}
@Override
public MarginLayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(), attrs);
}
@Override
protected MarginLayoutParams generateLayoutParams(LayoutParams p) {
return new MarginLayoutParams(p);
}
@Override
protected MarginLayoutParams generateDefaultLayoutParams() {
return new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT,
MarginLayoutParams.WRAP_CONTENT);
}
@Override
protected boolean checkLayoutParams(LayoutParams p) {
return p instanceof MarginLayoutParams;
}
private void hideMenuButtonWithImage(boolean animate) {
if (!isMenuButtonHidden()) {
mMenuButton.hide(animate);
if (animate) {
mImageToggle.startAnimation(mMenuButtonHideAnimation);
}
mImageToggle.setVisibility(INVISIBLE);
mIsMenuButtonAnimationRunning = false;
}
}
private void showMenuButtonWithImage(boolean animate) {
if (isMenuButtonHidden()) {
mMenuButton.show(animate);
if (animate) {
mImageToggle.startAnimation(mMenuButtonShowAnimation);
}
mImageToggle.setVisibility(VISIBLE);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mIsSetClosedOnTouchOutside) {
return mGestureDetector.onTouchEvent(event);
} else {
return super.onTouchEvent(event);
}
}
GestureDetector mGestureDetector = new GestureDetector(getContext(),
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return mIsSetClosedOnTouchOutside && isOpened();
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
close(mIsAnimated);
return true;
}
});
public boolean isOpened() {
return mMenuOpened;
}
public void toggle(boolean animate) {
if (isOpened()) {
close(animate);
} else {
open(animate);
}
}
public void open(final boolean animate) {
if (!isOpened()) {
if (isBackgroundEnabled()) {
mShowBackgroundAnimator.start();
}
if (mIconAnimated) {
if (mIconToggleSet != null) {
mIconToggleSet.start();
} else {
mCloseAnimatorSet.cancel();
mOpenAnimatorSet.start();
}
}
mMenuOpened = true;
int delay = 0;
for (int i = getChildCount() - 1; i >= 0; i
View child = getChildAt(i);
if (child instanceof FloatingActionButton
&& child.getVisibility() != GONE) {
final FloatingActionButton fab = (FloatingActionButton) child;
mUiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (fab != mMenuButton) {
fab.show(animate);
}
Label label = (Label) fab.getTag(R.id.fab_label);
if (label != null) {
label.show(animate);
}
}
}, delay);
delay += mAnimationDelayPerItem;
}
}
if (mToggleListener != null) {
mToggleListener.onMenuToggle(true);
}
}
}
public void close(final boolean animate) {
if (isOpened()) {
if (isBackgroundEnabled()) {
mHideBackgroundAnimator.start();
}
if (mIconAnimated) {
if (mIconToggleSet != null) {
mIconToggleSet.start();
} else {
mCloseAnimatorSet.start();
mOpenAnimatorSet.cancel();
}
}
mMenuOpened = false;
int delay = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child instanceof FloatingActionButton
&& child.getVisibility() != GONE) {
final FloatingActionButton fab = (FloatingActionButton) child;
mUiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (fab != mMenuButton) {
fab.hide(animate);
}
Label label = (Label) fab.getTag(R.id.fab_label);
if (label != null) {
label.hide(animate);
}
}
}, delay);
delay += animate ? mAnimationDelayPerItem : 0;
}
}
if (mToggleListener != null) {
mToggleListener.onMenuToggle(false);
}
}
}
/**
* Sets the {@link android.view.animation.Interpolator} for <b>FloatingActionButton's</b> icon animation.
*
* @param interpolator the Interpolator to be used in animation
*/
public void setIconAnimationInterpolator(Interpolator interpolator) {
mOpenAnimatorSet.setInterpolator(interpolator);
mCloseAnimatorSet.setInterpolator(interpolator);
}
public void setIconAnimationOpenInterpolator(Interpolator openInterpolator) {
mOpenAnimatorSet.setInterpolator(openInterpolator);
}
public void setIconAnimationCloseInterpolator(Interpolator closeInterpolator) {
mCloseAnimatorSet.setInterpolator(closeInterpolator);
}
/**
* Sets whether open and close actions should be animated
*
* @param animated if <b>false</b> - menu items will appear/disappear instantly without any animation
*/
public void setAnimated(boolean animated) {
mIsAnimated = animated;
mOpenAnimatorSet.setDuration(animated ? ANIMATION_DURATION : 0);
mCloseAnimatorSet.setDuration(animated ? ANIMATION_DURATION : 0);
}
public boolean isAnimated() {
return mIsAnimated;
}
public void setAnimationDelayPerItem(int animationDelayPerItem) {
mAnimationDelayPerItem = animationDelayPerItem;
}
public int getAnimationDelayPerItem() {
return mAnimationDelayPerItem;
}
public void setOnMenuToggleListener(OnMenuToggleListener listener) {
mToggleListener = listener;
}
public void setIconAnimated(boolean animated) {
mIconAnimated = animated;
}
public boolean isIconAnimated() {
return mIconAnimated;
}
public ImageView getMenuIconView() {
return mImageToggle;
}
public void setIconToggleAnimatorSet(AnimatorSet toggleAnimatorSet) {
mIconToggleSet = toggleAnimatorSet;
}
public AnimatorSet getIconToggleAnimatorSet() {
return mIconToggleSet;
}
public void setMenuButtonShowAnimation(Animation showAnimation) {
mMenuButtonShowAnimation = showAnimation;
mMenuButton.setShowAnimation(showAnimation);
}
public void setMenuButtonHideAnimation(Animation hideAnimation) {
mMenuButtonHideAnimation = hideAnimation;
mMenuButton.setHideAnimation(hideAnimation);
}
public boolean isMenuButtonHidden() {
return mMenuButton.isHidden();
}
public void showMenuButton(boolean animate) {
if (isMenuButtonHidden()) {
showMenuButtonWithImage(animate);
}
}
public void hideMenuButton(final boolean animate) {
if (!isMenuButtonHidden() && !mIsMenuButtonAnimationRunning) {
mIsMenuButtonAnimationRunning = true;
if (isOpened()) {
close(animate);
mUiHandler.postDelayed(new Runnable() {
@Override
public void run() {
hideMenuButtonWithImage(animate);
}
}, mAnimationDelayPerItem * mButtonsCount);
} else {
hideMenuButtonWithImage(animate);
}
}
}
public void toggleMenuButton(boolean animate) {
if (isMenuButtonHidden()) {
showMenuButton(animate);
} else {
hideMenuButton(animate);
}
}
public void setClosedOnTouchOutside(boolean close) {
mIsSetClosedOnTouchOutside = close;
}
public void setMenuButtonColorNormal(int color) {
mMenuColorNormal = color;
mMenuButton.setColorNormal(color);
}
public void setMenuButtonColorNormalResId(int colorResId) {
mMenuColorNormal = getResources().getColor(colorResId);
mMenuButton.setColorNormalResId(colorResId);
}
public int getMenuButtonColorNormal() {
return mMenuColorNormal;
}
public void setMenuButtonColorPressed(int color) {
mMenuColorPressed = color;
mMenuButton.setColorPressed(color);
}
public void setMenuButtonColorPressedResId(int colorResId) {
mMenuColorPressed = getResources().getColor(colorResId);
mMenuButton.setColorPressedResId(colorResId);
}
public int getMenuButtonColorPressed() {
return mMenuColorPressed;
}
public void setMenuButtonColorRipple(int color) {
mMenuColorRipple = color;
mMenuButton.setColorRipple(color);
}
public void setMenuButtonColorRippleResId(int colorResId) {
mMenuColorRipple = getResources().getColor(colorResId);
mMenuButton.setColorRippleResId(colorResId);
}
public int getMenuButtonColorRipple() {
return mMenuColorRipple;
}
public void setMenuButtonLabelText(String labelText)
{
mMenuButtonLabelText = labelText;
mMenuButton.setLabelText(labelText);
createLabels();
}
public void addMenuButton(FloatingActionButton fab) {
addView(fab, mButtonsCount - 1);
mButtonsCount++;
createLabels();
}
public void removeMenuButton(FloatingActionButton fab) {
removeView(fab.getLabelView());
removeView(fab);
mButtonsCount
}
public void setOnOpenMenuButtonClickListener(OnClickListener listener, boolean animateOnClose) {
mOnOpenMenuButtonClickListener = listener;
mAnimateOnCloseIfActiveMenuButtonClickListener = animateOnClose;
if (mOnOpenMenuButtonClickListener == null) {
mAnimateOnCloseIfActiveMenuButtonClickListener = true;
}
}
}
|
package org.eclipse.xtext.formatting2.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.formatting2.AbstractFormatter2;
import org.eclipse.xtext.formatting2.FormatterPreferenceKeys;
import org.eclipse.xtext.formatting2.FormattingNotApplicableException;
import org.eclipse.xtext.formatting2.IFormattableDocument;
import org.eclipse.xtext.formatting2.IFormattableSubDocument;
import org.eclipse.xtext.formatting2.IHiddenRegionFormatter;
import org.eclipse.xtext.formatting2.IHiddenRegionFormatting;
import org.eclipse.xtext.formatting2.ISubFormatter;
import org.eclipse.xtext.formatting2.ITextReplacer;
import org.eclipse.xtext.formatting2.ITextReplacerContext;
import org.eclipse.xtext.formatting2.debug.HiddenRegionFormattingToString;
import org.eclipse.xtext.formatting2.debug.TextRegionsToString;
import org.eclipse.xtext.formatting2.regionaccess.IEObjectRegion;
import org.eclipse.xtext.formatting2.regionaccess.IHiddenRegion;
import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegion;
import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess;
import org.eclipse.xtext.formatting2.regionaccess.ITextReplacement;
import org.eclipse.xtext.formatting2.regionaccess.ITextSegment;
import org.eclipse.xtext.preferences.ITypedPreferenceValues;
import org.eclipse.xtext.util.IAcceptor;
import org.eclipse.xtext.util.Tuples;
import org.eclipse.xtext.xbase.lib.Pair;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
public abstract class FormattableDocument implements IFormattableDocument {
private TextSegmentSet<ITextReplacer> replacers = null;
protected FormattableDocument() {
super();
}
protected TextSegmentSet<ITextReplacer> getReplacers() {
if (replacers == null)
replacers = createTextReplacerSet();
return replacers;
}
@Override
public void addReplacer(ITextReplacer replacer) {
if (!this.getRegion().contains(replacer.getRegion())) {
String frameTitle = getClass().getSimpleName();
ITextSegment frameRegion = getRegion();
String replacerTitle = replacer.getClass().getSimpleName();
ITextSegment replacerRegion = replacer.getRegion();
RegionsOutsideFrameException exception = new RegionsOutsideFrameException(frameTitle, frameRegion,
Tuples.create(replacerTitle, replacerRegion));
getRequest().getExceptionHandler().accept(exception);
return;
}
try {
getReplacers().add(replacer, getFormatter().createTextReplacerMerger());
} catch (ConflictingRegionsException e) {
getRequest().getExceptionHandler().accept(e);
}
}
@Override
public ISemanticRegion append(ISemanticRegion token, Procedure1<? super IHiddenRegionFormatter> after) {
if (token != null) {
IHiddenRegion gap = token.getNextHiddenRegion();
set(gap, after);
}
return token;
}
@Override
public <T extends EObject> T append(T owner, Procedure1<? super IHiddenRegionFormatter> after) {
if (owner != null) {
IEObjectRegion region = getTextRegionAccess().regionForEObject(owner);
if (region != null) {
IHiddenRegion gap = region.getNextHiddenRegion();
set(gap, after);
}
}
return owner;
}
// TODO: use org.eclipse.xtext.formatting2.TextReplacements
protected String applyTextReplacements(Iterable<ITextReplacement> replacements) {
ITextSegment region = getRegion();
String input = region.getText();
ArrayList<ITextReplacement> list = Lists.newArrayList(replacements);
Collections.sort(list);
int startOffset = region.getOffset();
int lastOffset = 0;
StringBuilder result = new StringBuilder();
for (ITextReplacement r : list) {
int offset = r.getOffset() - startOffset;
result.append(input.subSequence(lastOffset, offset));
result.append(r.getReplacementText());
lastOffset = offset + r.getLength();
}
result.append(input.subSequence(lastOffset, input.length()));
return result.toString();
}
protected ITextReplacerContext createReplacements(ITextReplacerContext previous) {
Integer maxLineWidth = getRequest().getPreferences().getPreference(FormatterPreferenceKeys.maxLineWidth);
ITextReplacerContext context = previous.withDocument(this);
ITextReplacerContext wrappable = null;
Set<ITextReplacer> wrapped = Sets.newHashSet();
LinkedList<ITextReplacer> queue = new LinkedList<ITextReplacer>();
TextSegmentSet<ITextReplacer> replacers = getReplacers();
for (ITextReplacer replacer : replacers) {
queue.add(replacer);
}
while (!queue.isEmpty()) {
ITextReplacer replacer = queue.poll();
context = context.withReplacer(replacer);
if (wrappable != null && context.isWrapSincePrevious()) {
wrappable = null;
}
if (wrappable != null && needsAutowrap(wrappable, context, maxLineWidth)) {
// TODO: raise report if replacer claims it can do autowrap but
// then doesn't
while (context != wrappable) {
ITextReplacer r = context.getReplacer();
if (r != null) {
ITextReplacer r2 = replacers.get(r);
if (r2 instanceof ICompositeTextReplacer) {
if (r == r2) {
queue.addFirst(r2);
}
} else if (r2 != null) {
queue.addFirst(r2);
}
}
context = context.getPreviousContext();
}
replacer = context.getReplacer();
context.setAutowrap(true);
wrappable = null;
}
ITextReplacerContext nextContext = replacer.createReplacements(context);
if (wrappable != null && context.isWrapInRegion()) {
wrappable = null;
} else {
Integer canAutowrap = context.canAutowrap();
if (canAutowrap != null && canAutowrap >= 0 && !context.isAutowrap() && !wrapped.contains(replacer)) {
boolean can = true;
if (wrappable != null) {
int lastEndOffset = wrappable.canAutowrap()
+ wrappable.getReplacer().getRegion().getEndOffset();
int thisEndOffset = canAutowrap + context.getReplacer().getRegion().getEndOffset();
can = lastEndOffset < thisEndOffset;
}
if (can) {
wrappable = context;
wrapped.add(replacer);
}
}
}
context = nextContext;
}
return context.withDocument(previous.getDocument());
}
protected TextSegmentSet<ITextReplacer> createTextReplacerSet() {
return new ArrayListTextSegmentSet<ITextReplacer>(ITextReplacer.GET_REGION,
new Function<ITextReplacer, String>() {
@Override
public String apply(ITextReplacer input) {
if (input instanceof HiddenRegionReplacer)
return new HiddenRegionFormattingToString()
.apply(((HiddenRegionReplacer) input).getFormatting());
return input.getClass().getSimpleName();
}
}, getRequest().isEnableDebugTracing());
}
@Override
public <T> T format(T obj) {
AbstractFormatter2 formatter = getFormatter();
if (formatter.shouldFormat(obj, this)) {
try {
formatter.format(obj, this);
} catch (RegionTraceMissingException e) {
throw e;
} catch (Exception e) {
IAcceptor<Exception> handler = getRequest().getExceptionHandler();
handler.accept(e);
}
}
return obj;
}
@Override
public void formatConditionally(EObject owner, ISubFormatter... formatters) {
IEObjectRegion region = getTextRegionAccess().regionForEObject(owner);
if (region != null)
formatConditionally(region.getOffset(), region.getLength(), formatters);
}
@Override
public void formatConditionally(int offset, int length, ISubFormatter... formatters)
throws FormattingNotApplicableException {
ConditionalReplacer replacer = new ConditionalReplacer(this, offset, length, ImmutableList.copyOf(formatters));
addReplacer(replacer);
}
public ITypedPreferenceValues getPreferences() {
return getFormatter().getPreferences();
}
public ITextRegionAccess getTextRegionAccess() {
return getRequest().getTextRegionAccess();
}
@Override
public <T1 extends ISemanticRegion, T2 extends ISemanticRegion>
Pair<T1, T2> interior(Pair<T1, T2> pair, Procedure1<? super IHiddenRegionFormatter> init) {
return interior(pair.getKey(), pair.getValue(), init);
}
@Override
public <T extends EObject> T interior(T object, Procedure1<? super IHiddenRegionFormatter> init) {
if (object != null) {
IEObjectRegion objRegion = getTextRegionAccess().regionForEObject(object);
if (objRegion != null) {
IHiddenRegion previous = objRegion.getPreviousHiddenRegion();
IHiddenRegion next = objRegion.getNextHiddenRegion();
if (previous != null && next != null && previous != next) {
interior(previous.getNextSemanticRegion(), next.getPreviousSemanticRegion(), init);
}
}
}
return object;
}
@Override
public <T1 extends ISemanticRegion, T2 extends ISemanticRegion>
Pair<T1, T2> interior(T1 first, T2 second, Procedure1<? super IHiddenRegionFormatter> init) {
if (first != null && second != null) {
set(first.getNextHiddenRegion(), second.getPreviousHiddenRegion(), init);
}
return Pair.of(first, second);
}
protected boolean needsAutowrap(ITextReplacerContext wrappable, ITextReplacerContext context, int maxLineWidth) {
if (context.getLeadingCharsInLineCount() > maxLineWidth)
return true;
int offset = wrappable.getReplacer().getRegion().getOffset();
int length = context.getReplacer().getRegion().getEndOffset() - offset;
if (length > wrappable.canAutowrap())
return false;
// for (ITextReplacement rep : context.getReplacementsUntil(wrappable))
// if (rep.getReplacementText().contains("\n"))
// return true;
// TextSegment region = new TextSegment(getTextRegionAccess(), offset, length);
// String text = TextReplacements.apply(region, );
// if (text.contains("\n"))
// return true;
return false;
}
@Override
public ISemanticRegion prepend(ISemanticRegion token, Procedure1<? super IHiddenRegionFormatter> before) {
if (token != null) {
IHiddenRegion gap = token.getPreviousHiddenRegion();
set(gap, before);
}
return token;
}
@Override
public <T extends EObject> T prepend(T owner, Procedure1<? super IHiddenRegionFormatter> before) {
if (owner != null) {
IEObjectRegion region = getTextRegionAccess().regionForEObject(owner);
if (region != null) {
IHiddenRegion gap = region.getPreviousHiddenRegion();
set(gap, before);
}
}
return owner;
}
@Override
public List<ITextReplacement> renderToTextReplacements() {
ITextReplacerContext first = getFormatter().createTextReplacerContext(this);
ITextReplacerContext last = createReplacements(first);
List<ITextReplacement> replacements = last.getReplacementsUntil(first);
return replacements;
}
@Override
public Pair<IHiddenRegion, IHiddenRegion> set(IHiddenRegion first, IHiddenRegion second,
Procedure1<? super IHiddenRegionFormatter> init) {
if (first != null && second != null) {
AbstractFormatter2 formatter = getFormatter();
IHiddenRegionFormatting f1 = formatter.createHiddenRegionFormatting();
IHiddenRegionFormatting f2 = formatter.createHiddenRegionFormatting();
init.apply(formatter.createHiddenRegionFormatter(f1, f2));
ITextReplacer replacer1 = formatter.createHiddenRegionReplacer(first, f1);
ITextReplacer replacer2 = formatter.createHiddenRegionReplacer(second, f2);
addReplacer(replacer1);
addReplacer(replacer2);
}
return Pair.of(first, second);
}
@Override
public IHiddenRegion set(IHiddenRegion hiddenRegion, Procedure1<? super IHiddenRegionFormatter> init) {
if (hiddenRegion != null) {
AbstractFormatter2 formatter = getFormatter();
IHiddenRegionFormatting formatting = formatter.createHiddenRegionFormatting();
init.apply(formatter.createHiddenRegionFormatter(formatting));
ITextReplacer replacer = formatter.createHiddenRegionReplacer(hiddenRegion, formatting);
addReplacer(replacer);
}
return hiddenRegion;
}
@Override
public ISemanticRegion surround(ISemanticRegion token, Procedure1<? super IHiddenRegionFormatter> beforeAndAfter) {
if (token != null) {
IHiddenRegion previous = token.getPreviousHiddenRegion();
IHiddenRegion next = token.getNextHiddenRegion();
set(previous, next, beforeAndAfter);
}
return token;
}
@Override
public <T extends EObject> T surround(T owner, Procedure1<? super IHiddenRegionFormatter> beforeAndAfter) {
if (owner != null && !owner.eIsProxy()) {
IEObjectRegion region = getTextRegionAccess().regionForEObject(owner);
if (region == null)
return owner;
IHiddenRegion previous = region.getPreviousHiddenRegion();
IHiddenRegion next = region.getNextHiddenRegion();
set(previous, next, beforeAndAfter);
}
return owner;
}
@Override
public String toString() {
TextRegionsToString toString = new TextRegionsToString();
toString.setFrame(this.getRegion());
toString.setTitle(getClass().getSimpleName() + " with ITextReplacers");
for (ITextReplacer repl : getReplacers())
toString.add(repl.getRegion(), repl.getClass().getSimpleName() + ": " + repl.toString());
return toString.toString();
}
@Override
public IFormattableSubDocument withReplacerFilter(Predicate<? super ITextReplacer> filter) {
return new FilteredSubDocument(getRegion(), this, filter);
}
}
|
package org.nuxeo.ecm.platform.jbpm.web;
import java.io.Serializable;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;
import org.jbpm.graph.exe.ProcessInstance;
import org.jbpm.taskmgmt.exe.TaskInstance;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.security.ACP;
import org.nuxeo.ecm.core.api.security.SecurityConstants;
import org.nuxeo.ecm.platform.forms.layout.api.BuiltinModes;
import org.nuxeo.ecm.platform.jbpm.AbstractJbpmHandlerHelper;
import org.nuxeo.ecm.platform.jbpm.JbpmEventNames;
import org.nuxeo.ecm.platform.jbpm.JbpmSecurityPolicy;
import org.nuxeo.ecm.platform.jbpm.JbpmService;
import org.nuxeo.ecm.platform.jbpm.TaskListFilter;
import org.nuxeo.ecm.platform.jbpm.TaskStartDateComparator;
import org.nuxeo.ecm.platform.jbpm.VirtualTaskInstance;
import org.nuxeo.ecm.platform.ui.web.api.NavigationContext;
import org.nuxeo.ecm.platform.ui.web.util.ComponentUtils;
import org.nuxeo.ecm.webapp.helpers.ResourcesAccessor;
/**
* @author Anahide Tchertchian
*
*/
@Name("jbpmActions")
@Scope(ScopeType.CONVERSATION)
public class JbpmActionsBean implements JbpmActions {
private static final long serialVersionUID = 1L;
@In(create = true, required = false)
protected transient CoreSession documentManager;
@In(create = true)
protected transient NavigationContext navigationContext;
@In(create = true)
protected transient JbpmService jbpmService;
@In(create = true)
protected transient JbpmHelper jbpmHelper;
@In(create = true, required = false)
protected FacesMessages facesMessages;
@In(create = true)
protected ResourcesAccessor resourcesAccessor;
@In(create = true)
protected transient Principal currentUser;
protected Boolean canManageCurrentProcess;
protected ProcessInstance currentProcess;
protected String currentProcessInitiator;
protected List<TaskInstance> currentTasks;
protected ArrayList<VirtualTaskInstance> currentVirtualTasks;
protected VirtualTaskInstance newVirtualTask;
protected Boolean showAddVirtualTaskForm;
// TODO: use it for notifications
protected String userComment;
public boolean getCanCreateProcess() throws ClientException {
ProcessInstance currentProcess = getCurrentProcess();
if (currentProcess == null) {
DocumentModel currentDoc = navigationContext.getCurrentDocument();
if (currentDoc != null) {
DocumentRef docRef = currentDoc.getRef();
return documentManager.hasPermission(docRef,
SecurityConstants.WRITE);
}
}
return false;
}
public boolean getCanManageProcess() throws ClientException {
if (canManageCurrentProcess == null) {
canManageCurrentProcess = false;
ProcessInstance currentProcess = getCurrentProcess();
if (currentProcess != null) {
Boolean canWrite = jbpmService.getPermission(currentProcess,
JbpmSecurityPolicy.Action.write,
navigationContext.getCurrentDocument(),
(NuxeoPrincipal) currentUser);
if (canWrite != null) {
canManageCurrentProcess = canWrite;
}
}
}
return canManageCurrentProcess;
}
public boolean getCanEndTask(TaskInstance taskInstance)
throws ClientException {
if (taskInstance != null
&& (!taskInstance.isCancelled() && !taskInstance.hasEnded())) {
JbpmHelper helper = new JbpmHelper();
NuxeoPrincipal pal = (NuxeoPrincipal) currentUser;
return pal.isAdministrator()
|| pal.getName().equals(getCurrentProcessInitiator())
|| helper.isTaskAssignedToUser(taskInstance, pal);
}
return false;
}
public String createProcessInstance(NuxeoPrincipal principal, String pd,
DocumentModel dm, String endLifeCycle) throws ClientException {
if (getCanCreateProcess()) {
Map<String, Serializable> map = null;
if (endLifeCycle != null && !endLifeCycle.equals("")
&& !"null".equals(endLifeCycle)) {
map = new HashMap<String, Serializable>();
map.put(JbpmService.VariableName.endLifecycleTransition.name(),
endLifeCycle);
}
jbpmService.createProcessInstance(principal, pd, dm, map, null);
// TODO: add feedback?
Events.instance().raiseEvent(JbpmEventNames.WORKFLOW_NEW_STARTED);
resetCurrentData();
}
return null;
}
public ProcessInstance getCurrentProcess() throws ClientException {
if (currentProcess == null) {
List<ProcessInstance> processes = jbpmService.getProcessInstances(
navigationContext.getCurrentDocument(),
(NuxeoPrincipal) currentUser, null);
if (processes != null && !processes.isEmpty()) {
currentProcess = processes.get(0);
}
}
return currentProcess;
}
public String getCurrentProcessInitiator() throws ClientException {
if (currentProcessInitiator == null) {
currentProcessInitiator = "";
ProcessInstance currentProcess = getCurrentProcess();
if (currentProcess != null) {
Object initiator = currentProcess.getContextInstance().getVariable(
JbpmService.VariableName.initiator.name());
if (initiator instanceof String) {
currentProcessInitiator = (String) initiator;
if (currentProcessInitiator.startsWith(NuxeoPrincipal.PREFIX)) {
currentProcessInitiator = currentProcessInitiator.substring(NuxeoPrincipal.PREFIX.length());
}
}
}
}
return currentProcessInitiator;
}
public List<TaskInstance> getCurrentTasks(String... taskNames)
throws ClientException {
if (currentTasks == null) {
currentTasks = new ArrayList<TaskInstance>();
ProcessInstance currentProcess = getCurrentProcess();
if (currentProcess != null) {
currentTasks.addAll(jbpmService.getTaskInstances(
currentProcess.getId(), null, new TaskListFilter(
taskNames)));
Collections.sort(currentTasks, new TaskStartDateComparator());
}
}
return currentTasks;
}
public String getVirtualTasksLayoutMode() throws ClientException {
if (getCanManageProcess()) {
return BuiltinModes.EDIT;
}
return BuiltinModes.VIEW;
}
@SuppressWarnings("unchecked")
public ArrayList<VirtualTaskInstance> getCurrentVirtualTasks()
throws ClientException {
if (currentVirtualTasks == null) {
currentVirtualTasks = new ArrayList<VirtualTaskInstance>();
ProcessInstance currentProcess = getCurrentProcess();
if (currentProcess != null) {
Object participants = currentProcess.getContextInstance().getVariable(
JbpmService.VariableName.participants.name());
if (participants != null && participants instanceof List) {
currentVirtualTasks.addAll((List<VirtualTaskInstance>) participants);
}
}
}
return currentVirtualTasks;
}
public boolean getShowAddVirtualTaskForm() throws ClientException {
if (showAddVirtualTaskForm == null) {
showAddVirtualTaskForm = false;
if (getCurrentVirtualTasks().isEmpty()
&& (currentTasks == null || currentTasks.isEmpty())) {
showAddVirtualTaskForm = true;
}
}
return showAddVirtualTaskForm;
}
public void toggleShowAddVirtualTaskForm(ActionEvent event)
throws ClientException {
showAddVirtualTaskForm = !getShowAddVirtualTaskForm();
}
public VirtualTaskInstance getNewVirtualTask() throws ClientException {
if (newVirtualTask == null) {
newVirtualTask = new VirtualTaskInstance();
}
return newVirtualTask;
}
public String addNewVirtualTask() throws ClientException {
ProcessInstance pi = getCurrentProcess();
if (pi != null && newVirtualTask != null && getCanManageProcess()) {
List<VirtualTaskInstance> virtualTasks = getCurrentVirtualTasks();
if (virtualTasks == null) {
virtualTasks = new ArrayList<VirtualTaskInstance>();
}
virtualTasks.add(newVirtualTask);
pi.getContextInstance().setVariable(
JbpmService.VariableName.participants.name(), virtualTasks);
jbpmService.persistProcessInstance(pi);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.added.reviewer"));
// reset so that's reloaded
newVirtualTask = null;
currentVirtualTasks = null;
showAddVirtualTaskForm = null;
// TODO: refresh process instance?
}
return null;
}
public String moveDownVirtualTask(int index) throws ClientException {
ProcessInstance pi = getCurrentProcess();
if (pi != null && getCanManageProcess()) {
List<VirtualTaskInstance> virtualTasks = getCurrentVirtualTasks();
if (virtualTasks != null && index + 1 < virtualTasks.size()) {
VirtualTaskInstance task = virtualTasks.remove(index);
virtualTasks.add(index + 1, task);
}
pi.getContextInstance().setVariable(
JbpmService.VariableName.participants.name(), virtualTasks);
jbpmService.persistProcessInstance(pi);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.movedUp.reviewer"));
// reset so that's reloaded
currentVirtualTasks = null;
// TODO: refresh process instance?
}
return null;
}
public String moveUpVirtualTask(int index) throws ClientException {
ProcessInstance pi = getCurrentProcess();
if (pi != null && getCanManageProcess()) {
List<VirtualTaskInstance> virtualTasks = getCurrentVirtualTasks();
if (virtualTasks != null && index - 1 < virtualTasks.size()) {
VirtualTaskInstance task = virtualTasks.remove(index);
virtualTasks.add(index - 1, task);
}
pi.getContextInstance().setVariable(
JbpmService.VariableName.participants.name(), virtualTasks);
jbpmService.persistProcessInstance(pi);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.movedDown.reviewer"));
// reset so that's reloaded
currentVirtualTasks = null;
// TODO: refresh process instance?
}
return null;
}
public String removeVirtualTask(int index) throws ClientException {
ProcessInstance pi = getCurrentProcess();
if (pi != null && getCanManageProcess()) {
List<VirtualTaskInstance> virtualTasks = getCurrentVirtualTasks();
if (virtualTasks != null && index < virtualTasks.size()) {
virtualTasks.remove(index);
}
pi.getContextInstance().setVariable(
JbpmService.VariableName.participants.name(), virtualTasks);
jbpmService.persistProcessInstance(pi);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.removed.reviewer"));
// reset so that's reloaded
currentVirtualTasks = null;
showAddVirtualTaskForm = null;
// TODO: refresh process instance?
}
return null;
}
public void validateTaskDueDate(FacesContext context,
UIComponent component, Object value) {
final String DATE_FORMAT = "dd/MM/yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String messageString = null;
if (value != null) {
Date today = null;
Date dueDate = null;
try {
dueDate = dateFormat.parse(dateFormat.format((Date) value));
today = dateFormat.parse(dateFormat.format(new Date()));
} catch (ParseException e) {
messageString = "label.workflow.error.date_parsing";
}
if (dueDate.before(today)) {
messageString = "label.workflow.error.outdated_duedate";
}
}
if (messageString != null) {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_ERROR, ComponentUtils.translate(
context, "label.workflow.error.outdated_duedate"),
null);
((EditableValueHolder) component).setValid(false);
context.addMessage(component.getClientId(context), message);
// also add global message?
// context.addMessage(null, message);
}
}
protected TaskInstance getStartTask(String taskName) throws ClientException {
TaskInstance startTask = null;
if (taskName != null) {
// get task with that name on current process
ProcessInstance pi = getCurrentProcess();
if (pi != null) {
List<TaskInstance> tasks = jbpmService.getTaskInstances(
currentProcess.getId(), null, new TaskListFilter(
taskName));
if (tasks != null && !tasks.isEmpty()) {
// take first one found
startTask = tasks.get(0);
}
}
}
if (startTask == null) {
throw new ClientException(
"No start task found on current process with name "
+ taskName);
}
return null;
}
public boolean isProcessStarted(String startTaskName)
throws ClientException {
TaskInstance startTask = getStartTask(startTaskName);
return startTask.hasEnded();
}
public String startProcess(String startTaskName) throws ClientException {
if (getCanManageProcess()) {
TaskInstance startTask = getStartTask(startTaskName);
if (startTask.hasEnded()) {
throw new ClientException("Process is already started");
}
// optim: pass participants as transient variables to avoid
// lookup in the process instance
Map<String, Serializable> transientVariables = new HashMap<String, Serializable>();
transientVariables.put(
JbpmService.VariableName.participants.name(),
getCurrentVirtualTasks());
jbpmService.endTask(startTask.getId(), null, null, null,
transientVariables);
resetCurrentData();
}
return null;
}
public String validateTask(TaskInstance taskInstance, String transition)
throws ClientException {
if (taskInstance != null) {
// add marker that task was validated
Map<String, Serializable> taskVariables = new HashMap<String, Serializable>();
taskVariables.put(JbpmService.TaskVariableName.validated.name(),
true);
jbpmService.endTask(taskInstance.getId(), transition,
taskVariables, null, null);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.task.ended"));
Events.instance().raiseEvent(JbpmEventNames.WORKFLOW_TASK_COMPLETED);
resetCurrentData();
}
return null;
}
public String rejectTask(TaskInstance taskInstance, String transition)
throws ClientException {
if (taskInstance != null) {
// add marker that task was rejected
Map<String, Serializable> taskVariables = new HashMap<String, Serializable>();
taskVariables.put(JbpmService.TaskVariableName.validated.name(),
false);
jbpmService.endTask(taskInstance.getId(), transition,
taskVariables, null, null);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.task.ended"));
Events.instance().raiseEvent(JbpmEventNames.WORKFLOW_TASK_REJECTED);
resetCurrentData();
}
return null;
}
public String abandonCurrentProcess() throws ClientException {
ProcessInstance currentProcess = getCurrentProcess();
if (currentProcess != null && getCanManageProcess()) {
// remove wf acls
Long pid = currentProcess.getId();
DocumentModel currentDoc = navigationContext.getCurrentDocument();
if (currentDoc != null) {
ACP acp = currentDoc.getACP();
acp.removeACL(AbstractJbpmHandlerHelper.getProcessACLName(pid));
documentManager.setACP(currentDoc.getRef(), acp, true);
documentManager.save();
}
// end process and tasks
jbpmService.abandonProcessInstance((NuxeoPrincipal) currentUser,
pid);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.review.task.ended"));
Events.instance().raiseEvent(JbpmEventNames.WORKFLOW_ABANDONED);
resetCurrentData();
}
return null;
}
public String getUserComment() throws ClientException {
return userComment;
}
public void setUserComment(String comment) throws ClientException {
this.userComment = comment;
}
public void resetCurrentData() throws ClientException {
canManageCurrentProcess = null;
currentProcess = null;
currentProcessInitiator = null;
currentTasks = null;
currentVirtualTasks = null;
newVirtualTask = null;
showAddVirtualTaskForm = null;
userComment = null;
}
}
|
package com.rejasupotaro.android.kvs;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashSet;
import java.util.Set;
public abstract class PrefSchema extends Schema {
private SharedPreferences prefs;
protected void init(Context context, String tableName) {
this.prefs = context.getSharedPreferences(tableName, Context.MODE_PRIVATE);
}
protected void init(SharedPreferences prefs) {
this.prefs = prefs;
}
@Override
protected void putBoolean(String key, boolean value) {
prefs.edit().putBoolean(key, value).apply();
}
@Override
protected void putString(String key, String value) {
prefs.edit().putString(key, value).apply();
}
@Override
protected void putFloat(String key, float value) {
prefs.edit().putFloat(key, value).apply();
}
@Override
protected void putInt(String key, int value) {
prefs.edit().putInt(key, value).apply();
}
@Override
protected void putLong(String key, long value) {
prefs.edit().putLong(key, value).apply();
}
@Override
protected void putStringSet(String key, Set<String> value) {
prefs.edit().putStringSet(key, value).apply();
}
@Override
protected boolean getBoolean(String key, boolean defValue) {
return prefs.getBoolean(key, defValue);
}
@Override
protected String getString(String key, String defValue) {
return prefs.getString(key, defValue);
}
@Override
protected float getFloat(String key, float defValue) {
return prefs.getFloat(key, defValue);
}
@Override
protected int getInt(String key, int defValue) {
return prefs.getInt(key, defValue);
}
@Override
protected long getLong(String key, long defValue) {
return prefs.getLong(key, defValue);
}
@Override
protected Set<String> getStringSet(String key, Set<String> defValue) {
return prefs.getStringSet(key, new HashSet<String>());
}
@Override
protected boolean has(String key) {
return prefs.contains(key);
}
@Override
protected void remove(String key) {
prefs.edit().remove(key).apply();
}
@Override
public void clear() {
prefs.edit().clear().apply();
}
}
|
package org.mwc.cmap.TimeController.views;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.Vector;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.mwc.cmap.TimeController.TimeControllerPlugin;
import org.mwc.cmap.TimeController.controls.DTGBiSlider;
import org.mwc.cmap.TimeController.controls.DTGBiSlider.DoFineControl;
import org.mwc.cmap.TimeController.properties.FineTuneStepperProps;
import org.mwc.cmap.TimeController.recorders.CoordinateRecorder;
import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.DataTypes.Temporal.ControllablePeriod;
import org.mwc.cmap.core.DataTypes.Temporal.ControllableTime;
import org.mwc.cmap.core.DataTypes.Temporal.SteppableTime;
import org.mwc.cmap.core.DataTypes.Temporal.TimeControlPreferences;
import org.mwc.cmap.core.DataTypes.Temporal.TimeControlProperties;
import org.mwc.cmap.core.DataTypes.Temporal.TimeProvider;
import org.mwc.cmap.core.interfaces.TimeControllerOperation;
import org.mwc.cmap.core.interfaces.TimeControllerOperation.TimeControllerOperationStore;
import org.mwc.cmap.core.property_support.EditableWrapper;
import org.mwc.cmap.core.ui_support.PartMonitor;
import org.mwc.cmap.plotViewer.editors.CorePlotEditor;
import org.mwc.debrief.core.editors.PlotEditor;
import org.mwc.debrief.core.editors.painters.LayerPainterManager;
import org.mwc.debrief.core.editors.painters.TemporalLayerPainter;
import org.mwc.debrief.core.editors.painters.highlighters.SWTPlotHighlighter;
import MWC.Algorithms.PlainProjection;
import MWC.Algorithms.PlainProjection.RelativeProjectionParent;
import MWC.GUI.Layers;
import MWC.GUI.Properties.DateFormatPropertyEditor;
import MWC.GenericData.Duration;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldLocation;
import MWC.TacticalData.TrackDataProvider;
import MWC.Utilities.TextFormatting.GMTDateFormat;
import MWC.Utilities.Timer.TimerListener;
import junit.framework.TestCase;
/**
* View performing time management: show current time, allow control of time, allow selection of
* time periods
*/
public class TimeController extends ViewPart implements ISelectionProvider,
TimerListener, RelativeProjectionParent
{
private class FilterToPeriodAction extends Action
{
FilterToPeriodAction()
{
super("Filter to period", IAction.AS_CHECK_BOX);
}
@Override
public void run()
{
super.run();
if (isChecked())
{
final HiResDate tNow = _myTemporalDataset.getTime();
if (tNow != null)
{
final TimePeriod period = _controllablePeriod.getPeriod();
if (period != null)
{
if (!period.contains(tNow))
{
if (tNow.greaterThan(period.getEndDTG()))
{
fireNewTime(period.getEndDTG());
}
else
{
fireNewTime(period.getStartDTG());
}
}
stopPlayingTimer();
}
}
}
}
}
protected final class NewTimeListener implements PropertyChangeListener
{
@Override
public void propertyChange(final PropertyChangeEvent event)
{
// see if it's the time or the period which
// has changed
if (event.getPropertyName().equals(
TimeProvider.TIME_CHANGED_PROPERTY_NAME))
{
// ok, use the new time
final HiResDate newDTG = (HiResDate) event.getNewValue();
timeUpdated(newDTG);
}
else if (event.getPropertyName().equals(
TimeProvider.PERIOD_CHANGED_PROPERTY_NAME))
{
final TimePeriod newPeriod = (TimePeriod) event.getNewValue();
if (newPeriod == null)
{
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
// hey, we haven't got a time period- disable
_wholePanel.setEnabled(false);
// hey - remember the updated time range (largely so
// that we can
// restore from file later on)
_myStepperProperties.setSliderStartTime(null);
_myStepperProperties.setSliderEndTime(null);
}
});
}
else
{
// extend the slider
_slideManager.resetRange(newPeriod.getStartDTG(), newPeriod
.getEndDTG());
// now the slider selector bar thingy
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
// ok, double-check we're enabled
_wholePanel.setEnabled(true);
// and our range selector - first the outer
// ranges
_dtgRangeSlider.updateOuterRanges(newPeriod);
// ok - we no longer reset the range limits on a data change,
// since it's proving inconvenient to have to reset the sliders
// after some data is dropped in.
// hey - we're setting them again now, since they go screwy with
// high throughput DIS data
// ok, now the user ranges...
_dtgRangeSlider.updateSelectedRanges(newPeriod.getStartDTG(),
newPeriod.getEndDTG());
}
});
}
}
// also double-check if it's time to enable our interface
checkTimeEnabled();
}
}
private class PlayButtonListener extends SelectionAdapter
{
@Override
public void widgetSelected(final SelectionEvent se)
{
final boolean playing = _playButton.getSelection();
_playing = true;
if (playing)
{
// and start playing
startPlaying();
// ok, disable the buttons
setVCREnabled(false);
_playButton.setToolTipText(PAUSE_TEXT);
_playButton.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_PAUSE));
}
else
{
stopPlaying();
// ok, disable the buttons
setVCREnabled(true);
// ok, set the tooltip & image
_playButton.setToolTipText(PLAY_TEXT);
_playButton.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_PLAY));
}
}
}
/**
* SplitButton
*/
private class RecordButtonListener extends SelectionAdapter
{
@Override
public void widgetSelected(final SelectionEvent e)
{
final boolean isRecording = _recordButton.getSelection();
_playing = false;
if (isRecording)
{
startPlaying();
startRecording();
}
else
{
stopPlaying();
stopRecording(getTimeProvider().getTime());
}
}
}
private class RepeatingTimeButtonListener implements Listener
{
private static final long DELAY = 300;
protected final boolean _fwd;
protected final STEP_SIZE _step;
private final boolean _doRepeat;
private java.util.Timer _timer;
/**
*
* @param fwd
* whether this button moves forward or backwards
* @param large
* whether this button moves in large or small steps
* @param doRepeat
* whether this button repeats if held down
*/
public RepeatingTimeButtonListener(final boolean fwd, final STEP_SIZE step,
final boolean doRepeat)
{
_fwd = fwd;
_step = step;
_doRepeat = doRepeat;
}
@Override
public void handleEvent(final Event event)
{
final int type = event.type;
if (type == SWT.MouseDown)
{
// clear any previous timers
purge();
// fire a single step
process();
// do we need a repeating behaviour?
if (_doRepeat)
{
// initiate a timer to give repeating behaviour
_timer = new java.util.Timer();
final TimerTask task = new TimerTask()
{
@Override
public void run()
{
// fire a single step
process();
}
};
_timer.scheduleAtFixedRate(task, DELAY, DELAY);
}
}
if (type == SWT.MouseUp)
{
purge();
}
}
public void process()
{
try
{
processClick(_step, _fwd);
}
catch (final RuntimeException e1)
{
CorePlugin.logError(IStatus.ERROR, "Failed when trying to time step",
e1);
purge();
}
}
/**
* clear any active timer
*
*/
public void purge()
{
if (_timer != null)
{
_timer.cancel();
_timer.purge();
_timer = null;
}
}
}
/**
* declare a range of sizes for different types of time step
*
* @author ian
*
*/
protected enum STEP_SIZE
{
END, SMALL, NORMAL, LARGE
}
public static class TestTimeController extends TestCase
{
private int _min;
private int _max;
private int _smallTick;
private int _largeTick;
private int _dragSize;
private boolean _enabled;
public void testSliderScales()
{
final SliderRangeManagement range = new SliderRangeManagement()
{
@Override
public void setEnabled(final boolean val)
{
_enabled = val;
}
@Override
public void setMaxVal(final int max)
{
_max = max;
}
@Override
public void setMinVal(final int min)
{
_min = min;
}
@Override
public void setTickSize(final int small, final int large,
final int drag)
{
_smallTick = small;
_largeTick = large;
_dragSize = drag;
}
};
// initialise our testing values
_min = _max = _smallTick = _largeTick = -1;
_enabled = false;
HiResDate starter = new HiResDate(0, 100);
HiResDate ender = new HiResDate(0, 200);
range.resetRange(starter, ender);
assertEquals("min val set", 0, _min);
assertEquals("max val set", 100, _max);
assertEquals("sml tick set", 1, _smallTick);
assertEquals("drag size set", 0, _dragSize);
assertEquals("large tick set", 1000, _largeTick);
assertTrue("slider should be enabled", _enabled);
// ok, see how the transfer goes
HiResDate newToSlider = new HiResDate(0, 130);
final int res = range.toSliderUnits(newToSlider);
assertEquals("correct to slider units", 30, res);
// and backwards
newToSlider = range.fromSliderUnits(res, 1000);
assertEquals("correct from slider units", 130, newToSlider.getMicros());
// right, now back to millis
final Calendar cal = new GregorianCalendar();
cal.set(2005, 3, 3, 12, 1, 1);
final Date starterD = cal.getTime();
cal.set(2005, 3, 12, 12, 1, 1);
final Date enderD = cal.getTime();
starter = new HiResDate(starterD.getTime());
ender = new HiResDate(enderD.getTime());
range.resetRange(starter, ender);
final long diff = (enderD.getTime() - starterD.getTime()) / 1000;
assertEquals("correct range in secs", diff, _max);
assertEquals("sml tick set", 1, _smallTick);
assertEquals("large tick set", 60000, _largeTick);
}
}
protected class WheelMovedEvent implements Listener
{
@Override
public void handleEvent(final Event event)
{
// find out what keys are pressed
final int keys = event.stateMask;
// is is the control button?
if ((keys & SWT.CTRL) != 0)
{
final double zoomFactor;
// decide if we're going in or out
if (event.count > 0)
zoomFactor = 0.9;
else
zoomFactor = 1.1;
// and request the zoom
doZoom(zoomFactor);
}
else
{
// right, we're not zooming, we must be time-stepping
final int count = event.count;
boolean fwd;
STEP_SIZE size = STEP_SIZE.NORMAL;
if ((keys & SWT.SHIFT) != 0)
size = STEP_SIZE.LARGE;
else if ((keys & SWT.ALT) != 0)
size = STEP_SIZE.SMALL;
if (count < 0)
fwd = true;
else
fwd = false;
processClick(size, fwd);
}
}
}
private static final String PLAY_BUTTON_KEY = "play";
private static final String RECORD_BUTTON_KEY = "record";
private static final String ICON_BKMRK_NAV = "icons/bkmrk_nav.gif";
private static final String ICON_FILTER_TO_PERIOD = "icons/16/filter.png";
private static final String ICON_LOCK_VIEW2 = "icons/lock_view2.png";
private static final String ICON_LOCK_VIEW1 = "icons/lock_view1.png";
private static final String ICON_LOCK_VIEW = "icons/lock_view.png";
private static final String ICON_PROPERTIES = "icons/16/properties.png";
private static final String ICON_TIME_BARS = "icons/16/gantt_bars.png";
private static final String ICON_MEDIA_END = "icons/24/media_end.png";
private static final String ICON_MEDIA_FAST_FORWARD =
"icons/24/media_fast_forward.png";
private static final String ICON_MEDIA_FORWARD = "icons/24/media_forward.png";
private static final String ICON_MEDIA_BACK = "icons/24/media_back.png";
private static final String ICON_MEDIA_REWIND = "icons/24/media_rewind.png";
private static final String ICON_MEDIA_BEGINNING =
"icons/24/media_beginning.png";
private static final String ICON_MEDIA_PAUSE = "icons/24/media_pause.png";
private static final String ICON_MEDIA_PLAY = "icons/24/media_play.png";
private static final String ICON_MEDIA_RECORD = "icons/24/media_record.png";
private static final String ICON_MEDIA_STOP_RECORD =
"icons/24/media_stop.png";
private static final String ICON_PULSATING_GIF = "icons/16/pulse.gif";
private static final String DUFF_TIME_TEXT = "
private static final String PAUSE_TEXT = "Pause automatically moving forward";
private static final String PLAY_TEXT = "Start automatically moving forward";
private static final String STOP_TEXT =
"Stop recording, start export process";
private static final String RECORD_TEXT =
"Start recording screen positions, for export";
private static final String OP_LIST_MARKER_ID = "OPERATION_LIST_MARKER";
// private static final Color bColor = new Color(Display.getDefault(), 0, 0,
private static final Color bColor = Display.getCurrent().getSystemColor(
SWT.COLOR_BLACK);
private static final Color fColor = new Color(Display.getDefault(), 33, 255,
22);
private static final Font arialFont = new Font(Display.getDefault(), "Arial",
16, SWT.NONE);
private static SimpleDateFormat _myFormat = null;
private static String _myFormatString = null;
private static void addTimeButtonListener(final Button button,
final RepeatingTimeButtonListener listener)
{
button.addListener(SWT.MouseDown, listener);
button.addListener(SWT.MouseUp, listener);
button.addDisposeListener(new DisposeListener()
{
@Override
public void widgetDisposed(final DisposeEvent e)
{
listener.purge();
button.removeListener(SWT.MouseDown, listener);
button.removeListener(SWT.MouseUp, listener);
}
});
}
public synchronized static String toStringHiRes(final HiResDate time,
final String pattern) throws IllegalArgumentException
{
// so, have a look at the data
final long micros = time.getMicros();
// long wholeSeconds = micros / 1000000;
final StringBuffer res = new StringBuffer();
final Date theTime = new Date(micros / 1000);
// do we already know about a date format?
if (_myFormatString != null && !_myFormatString.equals(pattern))
{
// nope, it's not what we're after. ditch gash
_myFormatString = null;
_myFormat = null;
}
// so, we either don't have a format yet, or we did have, and now we
// want to
// forget it...
if (_myFormat == null)
{
_myFormatString = pattern;
_myFormat = new GMTDateFormat(pattern);
}
res.append(_myFormat.format(theTime));
final DecimalFormat microsFormat = new DecimalFormat("000000");
// DecimalFormat millisFormat = new DecimalFormat("000");
// do we have micros?
if (micros % 1000 > 0)
{
// yes
res.append(".");
res.append(microsFormat.format(micros % 1000000));
}
else
{
// do we have millis?
// if (micros % 1000000 > 0)
// // yes, convert the value to millis
// long millis = micros = (micros % 1000000) / 1000;
// res.append(".");
// res.append(millisFormat.format(millis));
// else
// // just use the normal output
}
return res.toString();
}
private PartMonitor _myPartMonitor;
private boolean _playing;
/**
* the automatic timer we are using
*/
private MWC.Utilities.Timer.Timer _myTimer;
/**
* the editor the user is currently working with (assigned alongside the time-provider object)
*/
protected transient IEditorPart _currentEditor;
/**
* listen out for new times
*/
final private PropertyChangeListener _temporalListener =
new NewTimeListener();
/**
* the temporal dataset controlling the narrative entry currently displayed
*/
private TimeProvider _myTemporalDataset;
/**
* the "write" interface for the plot which tracks the narrative, where avaialable
*/
private ControllableTime _controllableTime;
/**
* an object that gets stepped, not one that we can slide backwards & forwards through
*
*/
private SteppableTime _steppableTime;
/**
* the "write" interface for indicating a selected time period
*/
private ControllablePeriod _controllablePeriod;
/**
* label showing the current time
*/
private Label _timeLabel;
private Label _recordingLabel;
/**
* the set of layers we control through the range selector
*/
private Layers _myLayers;
/**
* the parent object for the time controller. It is at this level that we enable/disable the
* controls
*/
private Composite _wholePanel;
/**
* the holder for the VCR controls
*
*/
private Composite _btnPanel;
/**
* the people listening to us
*/
private Vector<ISelectionChangedListener> _selectionListeners;
/**
* and the preferences for time control
*/
private TimeControlProperties _myStepperProperties;
// private MenuItem _doExportItem;
/**
* module to look after the limits of the slider
*/
private SliderRangeManagement _slideManager = null;
/**
* when the user clicks on us, we set our properties as a selection. Remember the set of
* properties
*/
private StructuredSelection _propsAsSelection = null;
/**
* our fancy time range selector
*/
private DTGBiSlider _dtgRangeSlider;
/**
* whether the user wants to trim to time period after bislider change
*/
private Action _filterToSelectionAction;
/**
* the slider control - remember it because we're always changing the limits, etc
*/
private Scale _tNowSlider;
/**
* the play button, obviously.
*/
private Button _playButton;
/**
* the record button
*/
private Button _recordButton;
private PropertyChangeListener _myDateFormatListener = null;
/**
* name of property storing slider step size, used for saving state
*/
private final String SLIDER_STEP_SIZE = "SLIDER_STEP_SIZE";
/**
* make the forward button visible at a class level so that we can fire it in testing
*/
private Button _forwardButton;
/**
* utility class to help us plot relative plots
*/
private RelativeProjectionParent _relativeProjector;
/**
* the projection we're going to set to relative mode, as we wish
*/
private PlainProjection _targetProjection;
private TrackDataProvider.TrackDataListener _theTrackDataListener;
/**
* keep track of the list of play buttons, since on occasion we may want to hide some of them
*
*/
private HashMap<String, Button> _buttonList;
private CoordinateRecorder _coordinateRecorder;
private AnimatedGif animatedGif;
private boolean _alreadyProcessingChange = false;
private boolean _firingNewTime = false;
/**
* any default size to use for the slider threshold (read in as part of the 'init' operation
* before we actually create the slider)
*/
private Integer _defaultSliderResolution;
/**
* keep track of what tracks are open - we may want to use them for our exporting calc data to
* clipboard
*/
protected TrackDataProvider _myTrackProvider;
/**
* the list of operations that the current plot wants us to display
*
*/
protected TimeControllerOperation.TimeControllerOperationStore _timeOperations;
private Vector<Action> _legacyTimeOperations;
/**
* the first of the relative plotting modes - absolute north oriented plt
*/
private Action _normalPlottingMode;
/**
* first custom plotting mode: - always centre the plot on ownship, and orient the plot along
* ownship heading
*/
private Action _primaryCentredPrimaryOrientedPlottingMode;
/**
* second custom plotting mode: always centre the plot on ownship, but keep north-oriented.
*/
private Action _primaryCentredNorthOrientedPlottingMode;
protected LayerPainterManager _layerPainterManager;
/**
* @param menuManager
*/
private void addBiSliderResolution(final IMenuManager menuManager)
{
// ok, second menu for the DTG formats
final MenuManager formatMenu = new MenuManager("Time slider increment");
// and store it
menuManager.add(formatMenu);
// and now the date formats
final Object[][] stepSizes =
{
{"1 sec", new Long(1000)},
{"1 min", new Long(60 * 1000)},
{"5 min", new Long(5 * 60 * 1000)},
{"15 min", new Long(15 * 60 * 1000)},
{"1 hour", new Long(60 * 60 * 1000)},};
for (int i = 0; i < stepSizes.length; i++)
{
final String sizeLabel = (String) stepSizes[i][0];
final Long thisSize = (Long) stepSizes[i][1];
// and create a new action to represent the change
final Action newFormat = new Action(sizeLabel, IAction.AS_RADIO_BUTTON)
{
@Override
public void run()
{
super.run();
_dtgRangeSlider.setStepSize(thisSize.longValue());
// ok, update the ranges of the slider
_dtgRangeSlider.updateOuterRanges(_myTemporalDataset.getPeriod());
}
};
formatMenu.add(newFormat);
}
}
/**
* @param menuManager
*/
private void addDateFormats(final IMenuManager menuManager)
{
// ok, second menu for the DTG formats
final MenuManager formatMenu = new MenuManager("DTG Format");
// and store it
menuManager.add(formatMenu);
// and now the date formats
final String[] formats = DateFormatPropertyEditor.getTagList();
for (int i = 0; i < formats.length; i++)
{
final String thisFormat = formats[i];
// the properties manager is expecting the integer index of the new
// format, not the string value.
// so store it as an integer index
final Integer thisIndex = new Integer(i);
// and create a new action to represent the change
final Action newFormat = new Action(thisFormat, IAction.AS_RADIO_BUTTON)
{
@Override
public void run()
{
super.run();
_myStepperProperties.setPropertyValue(
TimeControlProperties.DTG_FORMAT_ID, thisIndex);
// todo: we need to tell the plot that it's changed - fake
// this by
// firing a quick formatting change
_myLayers.fireReformatted(null);
}
};
formatMenu.add(newFormat);
}
}
protected void addMarker()
{
try
{
// right, do we have an editor with a file?
final IEditorInput input = _currentEditor.getEditorInput();
if (input instanceof IFileEditorInput)
{
// aaah, and is there a file present?
final IFileEditorInput ife = (IFileEditorInput) input;
final IResource file = ife.getFile();
final String currentText = _timeLabel.getText();
final long tNow = _myTemporalDataset.getTime().getMicros();
if (file != null)
{
// yup, get the description
final InputDialog inputD = new InputDialog(getViewSite().getShell(),
"Add bookmark at this DTG", "Enter description of this bookmark",
currentText, null);
inputD.open();
final String content = inputD.getValue();
if (content != null)
{
final IMarker marker = file.createMarker(IMarker.BOOKMARK);
final Map<String, Object> attributes = new HashMap<String, Object>(
4);
attributes.put(IMarker.MESSAGE, content);
attributes.put(IMarker.LOCATION, currentText);
attributes.put(IMarker.LINE_NUMBER, "" + tNow);
attributes.put(IMarker.USER_EDITABLE, Boolean.FALSE);
marker.setAttributes(attributes);
}
}
}
}
catch (final CoreException e)
{
e.printStackTrace();
}
}
@Override
public void addSelectionChangedListener(
final ISelectionChangedListener listener)
{
if (_selectionListeners == null)
_selectionListeners = new Vector<ISelectionChangedListener>(0, 1);
// see if we don't already contain it..
if (!_selectionListeners.contains(listener))
_selectionListeners.add(listener);
}
/**
* ok - put in our bits
*
* @param parent
*/
private void buildInterface(final Composite parent)
{
// ok, draw our wonderful GUI.
_wholePanel = new Composite(parent, SWT.BORDER);
final GridLayout onTop = new GridLayout();
onTop.horizontalSpacing = 0;
onTop.verticalSpacing = 0;
onTop.marginHeight = 0;
onTop.marginWidth = 0;
_wholePanel.setLayout(onTop);
// stick in the long list of VCR buttons
createVCRbuttons();
final Composite timePanel = new Composite(_wholePanel, SWT.NONE);
timePanel.setLayout(new GridLayout(2, false));
timePanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
timePanel.setBackground(bColor);
_recordingLabel = new Label(timePanel, SWT.NONE);
final GridData recordingGrid = new GridData(GridData.FILL_HORIZONTAL);
recordingGrid.minimumWidth = 24;
_recordingLabel.setLayoutData(recordingGrid);
_recordingLabel.setFont(arialFont);
_recordingLabel.setForeground(fColor);
_recordingLabel.setBackground(bColor);
_recordingLabel.setVisible(false);
_timeLabel = new Label(timePanel, SWT.NONE);
final GridData labelGrid = new GridData(GridData.FILL_HORIZONTAL);
_timeLabel.setLayoutData(labelGrid);
_timeLabel.setAlignment(SWT.LEFT);
_timeLabel.setText(DUFF_TIME_TEXT);
// _timeLabel.setFont(new Font(Display.getDefault(), "OCR A Extended",
// SWT.NONE));
_timeLabel.setFont(arialFont);
_timeLabel.setForeground(fColor);
_timeLabel.setBackground(bColor);
// next create the time slider holder
_tNowSlider = new Scale(_wholePanel, SWT.NONE);
final GridData sliderGrid = new GridData(GridData.FILL_HORIZONTAL);
_tNowSlider.setLayoutData(sliderGrid);
_tNowSlider.setMinimum(0);
_tNowSlider.setMaximum(100);
_tNowSlider.addSelectionListener(new SelectionListener()
{
@Override
public void widgetDefaultSelected(final SelectionEvent e)
{
}
@Override
public void widgetSelected(final SelectionEvent e)
{
_alreadyProcessingChange = true;
try
{
final int index = _tNowSlider.getSelection();
final HiResDate newDTG = _slideManager.fromSliderUnits(index,
_dtgRangeSlider.getStepSize());
fireNewTime(newDTG);
}
catch (final Exception ex)
{
System.err.println("Tripped in step forward:" + ex);
}
finally
{
_alreadyProcessingChange = false;
}
}
});
_tNowSlider.addListener(SWT.MouseWheel, new WheelMovedEvent());
/**
* declare the handler we use for if the user double-clicks on a slider marker
*
*/
final DoFineControl fineControl = new DoFineControl()
{
@Override
public void adjust(final boolean isMax)
{
doFineControl(isMax);
}
};
_dtgRangeSlider = new DTGBiSlider(_wholePanel, fineControl)
{
@Override
public void rangeChanged(final TimePeriod period)
{
super.rangeChanged(period);
selectPeriod(period);
}
};
if (_defaultSliderResolution != null)
_dtgRangeSlider.setStepSize(_defaultSliderResolution.intValue());
// hmm, do we have a default step size for the slider?
final GridData biGrid = new GridData(GridData.FILL_BOTH);
_dtgRangeSlider.getControl().setLayoutData(biGrid);
}
/**
* convenience method to make the panel enabled if we have a time controller and a valid time
*/
private void checkTimeEnabled()
{
boolean enable = false;
if (_steppableTime != null)
{
// this is our 'fancy' situation - just enable it
enable = true;
}
else
{
// normal, Debrief-style situation, check we've got
// what we're after
if (_myTemporalDataset != null && (_controllableTime != null)
&& (_myTemporalDataset.getTime() != null))
{
enable = true;
}
}
final boolean finalEnabled = enable;
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
if (!_wholePanel.isDisposed())
{
// aaah, if we're clearing the panel, set the text to
// "pending"
if (_myTemporalDataset == null)
{
_timeLabel.setText("
_dtgRangeSlider.setShowLabels(false);
_dtgRangeSlider.resetMinMaxPointers();
}
_wholePanel.setEnabled(finalEnabled);
_dtgRangeSlider.setShowLabels(finalEnabled);
}
}
});
}
/**
* @param myLayerPainterManager
* @param menuManager
* @param provider
*/
private void createHighlighterOptions(
final LayerPainterManager myLayerPainterManager,
final IMenuManager menuManager, final ISelectionProvider provider)
{
// right, first the drop-down for the display-er
// ok, second menu for the DTG formats
final MenuManager highlighterMenu = new MenuManager("Highlight Mode");
// and store it
menuManager.add(highlighterMenu);
// and the range highlighters
final SWTPlotHighlighter[] highlighterList = myLayerPainterManager
.getHighlighterList();
final String curHighlighterName = myLayerPainterManager
.getCurrentHighlighter().getName();
// add the items
for (int i = 0; i < highlighterList.length; i++)
{
// ok, next painter
final SWTPlotHighlighter highlighter = highlighterList[i];
// create an action for it
final Action thisOne = new Action(highlighter.toString(),
IAction.AS_RADIO_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
myLayerPainterManager.setCurrentHighlighter(highlighter);
// and redo this list (deferred until the current processing
// is complete...
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
populateDropDownList(myLayerPainterManager);
}
});
}
};
String descPath = "icons/" + highlighter.toString().toLowerCase()
+ ".png";
descPath = descPath.replace(" ", "_");
thisOne.setImageDescriptor(org.mwc.debrief.core.DebriefPlugin
.getImageDescriptor(descPath));
// hmm, and see if this is our current painter
if (highlighter.getName().equals(curHighlighterName))
thisOne.setChecked(true);
// and store it on both menus
highlighterMenu.add(thisOne);
}
// ok, now for the current highlighter
final SWTPlotHighlighter currentHighlighter = myLayerPainterManager
.getCurrentHighlighter();
// create an action for it
final IWorkbenchPart myPart = this;
final Action highlighterProperties = new Action("Edit current highlighter:"
+ currentHighlighter.getName(), IAction.AS_PUSH_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
// ok - get the info object for this painter
if (currentHighlighter.hasEditor())
{
final EditableWrapper pw = new EditableWrapper(currentHighlighter,
_myLayers);
CorePlugin.editThisInProperties(_selectionListeners,
new StructuredSelection(pw), provider, myPart);
}
}
};
highlighterProperties.setImageDescriptor(CorePlugin.getImageDescriptor(
ICON_PROPERTIES));
// and store it on both menus
highlighterMenu.add(highlighterProperties);
}
/**
* @param myLayerPainterManager
* @param menuManager
* @param toolManager
* @param provider
*/
private void createPainterOptions(
final LayerPainterManager myLayerPainterManager,
final IMenuManager menuManager, final IToolBarManager toolManager,
final ISelectionProvider provider)
{
// right, first the drop-down for the display-er
// ok, second menu for the DTG formats
MenuManager displayMenu = new MenuManager("Display Mode");
// and store it
menuManager.add(displayMenu);
// ok, what are the painters we know about
final TemporalLayerPainter[] painterList = myLayerPainterManager
.getPainterList();
// add the items
for (int i = 0; i < painterList.length; i++)
{
// ok, next painter
final TemporalLayerPainter painter = painterList[i];
// create an action for it
final Action changePainter = new Action(painter.toString(),
IAction.AS_RADIO_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
myLayerPainterManager.setCurrentPainter(painter);
// and redo this list (deferred until the current processing
// is complete...
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
populateDropDownList(myLayerPainterManager);
}
});
}
};
final String descPath = "icons/16/" + painter.toString().toLowerCase()
+ ".png";
changePainter.setImageDescriptor(org.mwc.debrief.core.DebriefPlugin
.getImageDescriptor(descPath));
// hmm, and see if this is our current painter
if (painter.getName().equals(myLayerPainterManager.getCurrentPainter()
.getName()))
{
changePainter.setChecked(true);
}
// and store it on both menus
displayMenu.add(changePainter);
toolManager.add(changePainter);
}
// put the display painter property editor into this one
final TemporalLayerPainter currentPainter = myLayerPainterManager
.getCurrentPainter();
// create an action for it
final IWorkbenchPart myPart = this;
final Action currentPainterProperties = new Action("Edit current painter:"
+ currentPainter.getName(), IAction.AS_PUSH_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
// ok - get the info object for this painter
if (currentPainter.hasEditor())
{
final EditableWrapper pw = new EditableWrapper(currentPainter,
_myLayers);
CorePlugin.editThisInProperties(_selectionListeners,
new StructuredSelection(pw), provider, myPart);
}
}
};
currentPainterProperties.setImageDescriptor(CorePlugin.getImageDescriptor(
ICON_PROPERTIES));
// and store it on both menus
displayMenu.add(currentPainterProperties);
// lastly, sort out the relative projection mode
// right, first the drop-down for the display-er
// ok, second menu for the DTG formats
displayMenu = new MenuManager("Plotting mode");
// and store it
menuManager.add(displayMenu);
_normalPlottingMode = new Action("Normal", IAction.AS_RADIO_BUTTON)
{
@Override
public void run()
{
setRelativeMode(false, false);
}
};
_normalPlottingMode.setImageDescriptor(TimeControllerPlugin
.getImageDescriptor(ICON_LOCK_VIEW));
displayMenu.add(_normalPlottingMode);
_primaryCentredNorthOrientedPlottingMode = new Action(
"Primary centred/North oriented", IAction.AS_RADIO_BUTTON)
{
@Override
public void run()
{
// see if we have a primary track...
if (_myTrackProvider != null)
{
if (_myTrackProvider.getPrimaryTrack() == null)
{
CorePlugin.showMessage("Primary Centred Plotting",
"A Primary Track must be specified to use this mode");
_normalPlottingMode.setChecked(true);
_primaryCentredNorthOrientedPlottingMode.setChecked(false);
}
else
setRelativeMode(true, false);
}
}
};
_primaryCentredNorthOrientedPlottingMode.setImageDescriptor(
TimeControllerPlugin.getImageDescriptor(ICON_LOCK_VIEW1));
displayMenu.add(_primaryCentredNorthOrientedPlottingMode);
_primaryCentredPrimaryOrientedPlottingMode = new Action(
"Primary centred/Primary oriented", IAction.AS_RADIO_BUTTON)
{
@Override
public void run()
{
setRelativeMode(true, true);
}
};
_primaryCentredPrimaryOrientedPlottingMode.setImageDescriptor(
TimeControllerPlugin.getImageDescriptor(ICON_LOCK_VIEW2));
// no, let's not offer primary centred, primary oriented view
// displayMenu.add(_primaryCentredPrimaryOrientedPlottingMode);
}
/**
* This is a callback that will allow us to create the viewer and initialize it.
*/
@Override
public void createPartControl(final Composite parent)
{
// and declare our context sensitive help
CorePlugin.declareContextHelp(parent,
"org.mwc.debrief.help.TimeController");
// also sort out the slider conversion bits. We do it at the start,
// because
// callbacks
// created during initialisation may need to use/reset it
_slideManager = new SliderRangeManagement()
{
@Override
public void setEnabled(final boolean val)
{
if (!_tNowSlider.isDisposed())
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
_tNowSlider.setEnabled(val);
}
});
}
@Override
public void setMaxVal(final int max)
{
if (!_tNowSlider.isDisposed())
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
_tNowSlider.setMaximum(max);
}
});
}
@Override
public void setMinVal(final int min)
{
if (!_tNowSlider.isDisposed())
{
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
_tNowSlider.setMinimum(min);
}
});
}
}
@Override
public void setTickSize(final int small, final int large, final int drag)
{
if (!_tNowSlider.isDisposed())
{
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
_tNowSlider.setIncrement(small);
_tNowSlider.setPageIncrement(large);
}
});
}
}
};
// and fill in the interface
buildInterface(parent);
// of course though, we start off with the buttons not enabled
_wholePanel.setEnabled(false);
// and start listing for any part action
setupListeners();
// ok we're all ready now. just try and see if the current part is valid
_myPartMonitor.fireActivePart(getSite().getWorkbenchWindow()
.getActivePage());
// say that we're a selection provider
getSite().setSelectionProvider(this);
}
private void createVCRbuttons()
{
// first create the button holder
_btnPanel = new Composite(_wholePanel, SWT.BORDER);
_btnPanel.setLayout(new GridLayout(8, false));
final Button eBwd = new Button(_btnPanel, SWT.NONE);
addTimeButtonListener(eBwd, new RepeatingTimeButtonListener(false,
STEP_SIZE.END, false));
eBwd.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_BEGINNING));
eBwd.setToolTipText("Move to start of dataset");
final Button lBwd = new Button(_btnPanel, SWT.NONE);
lBwd.setToolTipText("Move backward large step (hold to repeat)");
lBwd.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_REWIND));
RepeatingTimeButtonListener listener = new RepeatingTimeButtonListener(
false, STEP_SIZE.LARGE, true);
addTimeButtonListener(lBwd, listener);
final Button sBwd = new Button(_btnPanel, SWT.NONE);
sBwd.setToolTipText("Move backward small step (hold to repeat)");
sBwd.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_BACK));
listener = new RepeatingTimeButtonListener(false, STEP_SIZE.NORMAL, true);
addTimeButtonListener(sBwd, listener);
_playButton = new Button(_btnPanel, SWT.TOGGLE | SWT.NONE);
// configure the drop-down menu
/*
* Menu exportMenu = new Menu(_playButton); _doExportItem = new MenuItem(exportMenu, SWT.CHECK);
* _doExportItem.setText("Export to PPTX");
* _doExportItem.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_PPTX));
*
* _playButton.setMenu(exportMenu);
*/
_playButton.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_PLAY));
_playButton.setToolTipText(PLAY_TEXT);
_playButton.addSelectionListener(new PlayButtonListener());
// _playButton.addSplitButtonSelectionListener(new MySplitButtonListener());
_recordButton = new Button(_btnPanel, SWT.TOGGLE | SWT.NONE);
_recordButton.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_RECORD));
_recordButton.addSelectionListener(new RecordButtonListener());
_recordButton.setToolTipText(RECORD_TEXT);
_forwardButton = new Button(_btnPanel, SWT.NONE);
_forwardButton.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_FORWARD));
listener = new RepeatingTimeButtonListener(true, STEP_SIZE.NORMAL, true);
addTimeButtonListener(_forwardButton, listener);
_forwardButton.setToolTipText("Move forward small step (hold to repeat)");
final Button lFwd = new Button(_btnPanel, SWT.NONE);
lFwd.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_FAST_FORWARD));
lFwd.setToolTipText("Move forward large step (hold to repeat)");
listener = new RepeatingTimeButtonListener(true, STEP_SIZE.LARGE, true);
addTimeButtonListener(lFwd, listener);
final Button eFwd = new Button(_btnPanel, SWT.NONE);
addTimeButtonListener(eFwd, new RepeatingTimeButtonListener(true,
STEP_SIZE.END, false));
eFwd.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_END));
eFwd.setToolTipText("Move to end of dataset");
final GridDataFactory btnGd = GridDataFactory.fillDefaults().grab(true,
false);
btnGd.applyTo(eBwd);
btnGd.applyTo(lBwd);
btnGd.applyTo(sBwd);
btnGd.applyTo(_playButton);
btnGd.applyTo(_forwardButton);
btnGd.applyTo(lFwd);
btnGd.applyTo(eFwd);
// and apply it to the whole panel
btnGd.applyTo(_btnPanel);
_buttonList = new HashMap<String, Button>();
_buttonList.put("eBwd", eBwd);
_buttonList.put("lBwd", lBwd);
_buttonList.put("sBwd", sBwd);
_buttonList.put(PLAY_BUTTON_KEY, _playButton);
_buttonList.put(RECORD_BUTTON_KEY, _recordButton);
_buttonList.put("sFwd", _forwardButton);
_buttonList.put("lFwd", lFwd);
_buttonList.put("eFwd", eFwd);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
@Override
@SuppressWarnings("deprecation")
public void dispose()
{
super.dispose();
// and ditch the timer
_myTimer = null;
// and stop listening for part activity
_myPartMonitor.dispose(getSite().getWorkbenchWindow().getPartService());
// also stop listening for time events
if (_myTemporalDataset != null)
{
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.PERIOD_CHANGED_PROPERTY_NAME);
}
}
/**
* user has double-clicked on one of the slider markers, allow detailed edit
*
* @param doMinVal
* whether it was the min or max value
*/
public void doFineControl(final boolean doMinVal)
{
final FineTuneStepperProps fineTunerProperties = new FineTuneStepperProps(
_dtgRangeSlider, doMinVal);
final EditableWrapper wrappedEditable = new EditableWrapper(
fineTunerProperties);
final StructuredSelection _propsAsSelection1 = new StructuredSelection(
wrappedEditable);
CorePlugin.editThisInProperties(_selectionListeners, _propsAsSelection1,
this, this);
}
/**
* provide some support for external testing
*/
public void doTests()
{
// check we have some data
TestCase.assertNotNull("check we have time to control", _controllableTime);
TestCase.assertNotNull("check we have time provider", _myTemporalDataset);
TestCase.assertNotNull("check we have period to control",
_controllablePeriod);
final Object oldDtgFormat = _myStepperProperties.getPropertyValue(
TimeControlProperties.DTG_FORMAT_ID);
try
{
_myStepperProperties.setPropertyValue(TimeControlProperties.DTG_FORMAT_ID,
new Integer(4));
final HiResDate tDemanded = new HiResDate(0, 818748000000000L);
// note - time equates to: 120600:00
// ok, try stepping forward. get the current time
final HiResDate tNow = _myTemporalDataset.getTime();
// step forward one
final Event ev = new Event();
_forwardButton.notifyListeners(SWT.Selection, ev);
// find the new time
final HiResDate tNew = _myTemporalDataset.getTime();
TestCase.assertNotSame("time has changed", "" + tNew.getMicros(), ""
+ tNow.getMicros());
// ok, go back to the demanded time (in case we loaded the plot with a
// different saved time)
_controllableTime.setTime(new Integer(111), tDemanded, true);
// have a look at the date
final String timeStr = _timeLabel.getText();
// check it's what we're expecting
TestCase.assertEquals("time is correct", timeStr, "120600:00");
}
finally
{
_myStepperProperties.setPropertyValue(TimeControlProperties.DTG_FORMAT_ID,
oldDtgFormat);
}
}
/**
* zoom the plot (in response to a control-mouse drag)
*
* @param zoomFactor
*/
public void doZoom(final double zoomFactor)
{
// ok, get the plot, and do some zooming
if (_currentEditor instanceof PlotEditor)
{
final PlotEditor plot = (PlotEditor) _currentEditor;
plot.getChart().getCanvas().getProjection().zoom(zoomFactor);
plot.getChart().update();
}
}
/**
* Passing the focus request to the viewer's control.
*/
private void editMeInProperties(final PropertyChangeSupport props)
{
// do we have any data?
if (props != null)
{
// get the editable thingy
if (_propsAsSelection == null)
_propsAsSelection = new StructuredSelection(props);
CorePlugin.editThisInProperties(_selectionListeners, _propsAsSelection,
this, this);
_propsAsSelection = null;
}
else
{
System.out.println("we haven't got any properties yet");
}
}
protected void expandTimeSliderRangeToFull()
{
// hey - check we've got some data first....
if (_myTemporalDataset != null)
{
final TimePeriod period = _myTemporalDataset.getPeriod();
// do we know our period?
if (period != null)
{
_slideManager.resetRange(period.getStartDTG(), period.getEndDTG());
}
}
}
private void fireNewTime(final HiResDate dtg)
{
if (!_firingNewTime)
{
_firingNewTime = true;
try
{
_controllableTime.setTime(this, dtg, true);
if (_coordinateRecorder != null)
{
_coordinateRecorder.newTime(dtg);
}
}
finally
{
_firingNewTime = false;
}
}
}
@SuppressWarnings(
{"rawtypes"})
@Override
public Object getAdapter(final Class adapter)
{
Object res = null;
if (adapter == TimePeriod.class)
{
// NOTE: xy plot plugin relies on getting this time period value from the
// time controller
res = getPeriod();
}
else
res = super.getAdapter(adapter);
return res;
}
private String getFormattedDate(final HiResDate newDTG)
{
String newVal = "n/a";
// hmm, we may have heard about the new date before hearing about the
// plot's stepper properties. check they arrived
if (_myStepperProperties != null)
{
final String dateFormat = _myStepperProperties.getDTGFormat();
// store.getString(PreferenceConstants.P_STRING);
try
{
newVal = toStringHiRes(newDTG, dateFormat);
// see if we're recording
if (_coordinateRecorder != null && _coordinateRecorder.isRecording())
{
if(animatedGif == null) {
animatedGif = new AnimatedGif(_recordingLabel, ICON_PULSATING_GIF);
if (_recordingLabel.getImage() == null)
{
_recordingLabel.setImage(animatedGif.getImage());
}
animatedGif.animate();
}
else {
animatedGif.resume(_recordingLabel.getBounds());
}
_recordingLabel.setVisible(true);
newVal += " [REC]";
}
else
{
if (animatedGif != null)
{
animatedGif.cancel();
}
_recordingLabel.setVisible(false);
}
}
catch (final IllegalArgumentException e)
{
e.printStackTrace();
System.err.println("Invalid date format in preferences");
}
}
return newVal;
}
// reset the buttons and labels are recording is done.
private void resetRecordingLabel()
{
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
final String newVal = getFormattedDate(_myTemporalDataset.getTime());
_timeLabel.setText(newVal);
if (animatedGif != null)
{
animatedGif.cancel();
}
_recordingLabel.setVisible(false);
}
});
}
@Override
public double getHeading()
{
double res = 0;
if (_relativeProjector != null)
res = _relativeProjector.getHeading();
return res;
}
@Override
public WorldLocation getLocation()
{
WorldLocation res = null;
if (_relativeProjector != null)
res = _relativeProjector.getLocation();
return res;
}
/**
* provide the currently selected period
*
* @return
*/
public TimePeriod getPeriod()
{
return getPeriodSlider().getPeriod();
}
/**
* accessor to the slider (used for testing the view)
*
* @return the slider control
*/
public DTGBiSlider getPeriodSlider()
{
return _dtgRangeSlider;
}
@Override
public ISelection getSelection()
{
return null;
}
public TimeProvider getTimeProvider()
{
return _myTemporalDataset;
}
private MWC.Utilities.Timer.Timer getTimer()
{
// have we created it yet?
if (_myTimer == null)
{
// nope, better go for it.
/**
* the timer-related settings
*/
_myTimer = new MWC.Utilities.Timer.Timer();
_myTimer.stop();
_myTimer.setDelay(1000);
_myTimer.addTimerListener(this);
}
return _myTimer;
}
public Scale getTimeSlider()
{
return _tNowSlider;
}
/**
* @param site
* @param memento
* @throws PartInitException
*/
@Override
public void init(final IViewSite site, final IMemento memento)
throws PartInitException
{
super.init(site, memento);
if (memento != null)
{
// try the slider step size
final Integer stepSize = memento.getInteger(SLIDER_STEP_SIZE);
if (stepSize != null)
{
_defaultSliderResolution = stepSize;
}
}
}
@Override
public void onTime(final ActionEvent event)
{
// temporarily remove ourselves, to prevent being called twice
getTimer().removeTimerListener(this);
// catch any exceptions raised here, it doesn't really
// matter if we miss a time step
try
{
// pass the step operation on to our parent
processClick(STEP_SIZE.NORMAL, true);
}
catch (final Exception e)
{
CorePlugin.logError(IStatus.ERROR, "Error on auto-time stepping", e);
}
// register ourselves as a time again
getTimer().addTimerListener(this);
}
/**
* ok - put in the stepper mode buttons - and any others we think of.
*/
private void populateDropDownList(
final LayerPainterManager myLayerPainterManager)
{
// clear the list
final IMenuManager menuManager = getViewSite().getActionBars()
.getMenuManager();
final IToolBarManager toolManager = getViewSite().getActionBars()
.getToolBarManager();
// ok, remove the existing items
menuManager.removeAll();
toolManager.removeAll();
if(_myTemporalDataset!=null) {
// create a host for when we're populating the properties window
final ISelectionProvider provider = this;
// right, do we have something with editable layer details?
if (myLayerPainterManager != null)
{
// ok - add the painter selectors/editors
createPainterOptions(myLayerPainterManager, menuManager, toolManager,
provider);
// ok, let's have a separator
toolManager.add(new Separator());
// now add the highlighter options/editors
createHighlighterOptions(myLayerPainterManager, menuManager, provider);
// and another separator
menuManager.add(new Separator());
}
// add the list of DTG formats for the DTG slider
addDateFormats(menuManager);
// add the list of DTG formats for the DTG slider
addBiSliderResolution(menuManager);
// and another separator
menuManager.add(new Separator());
// and another separator
toolManager.add(new Separator());
// let user indicate whether we should be filtering to window
_filterToSelectionAction = new FilterToPeriodAction();
_filterToSelectionAction.setImageDescriptor(CorePlugin.getImageDescriptor(
ICON_FILTER_TO_PERIOD));
_filterToSelectionAction.setToolTipText(
"Filter plot data to selected time period");
_filterToSelectionAction.setChecked(true);
menuManager.add(_filterToSelectionAction);
toolManager.add(_filterToSelectionAction);
// and another separator
menuManager.add(new Separator());
// now the add-bookmark item
final Action _setAsBookmarkAction = new Action("Add DTG as bookmark",
IAction.AS_PUSH_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
addMarker();
}
};
_setAsBookmarkAction.setImageDescriptor(CorePlugin.getImageDescriptor(
ICON_BKMRK_NAV));
_setAsBookmarkAction.setToolTipText(
"Add this DTG to the list of bookmarks");
_setAsBookmarkAction.setId(OP_LIST_MARKER_ID); // give
// can
menuManager.add(_setAsBookmarkAction);
// refer to this later on.
// and another separator
menuManager.add(new Separator());
// now our own menu editor
final Action toolboxProperties = new Action(
"Edit Time controller properties", IAction.AS_PUSH_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
editMeInProperties(_myStepperProperties);
}
};
toolboxProperties.setToolTipText("Edit Time Controller properties");
toolboxProperties.setImageDescriptor(CorePlugin.getImageDescriptor(
ICON_PROPERTIES));
menuManager.add(toolboxProperties);
toolManager.add(toolboxProperties);
// now our own menu editor
final Action viewTimeBar = new Action("View Time Bar",
IAction.AS_PUSH_BUTTON)
{
@Override
public void runWithEvent(final Event event)
{
CorePlugin.openView(CorePlugin.TIME_BAR);
}
};
viewTimeBar.setToolTipText("Show Time Bar view");
viewTimeBar.setImageDescriptor(CorePlugin.getImageDescriptor(
ICON_TIME_BARS));
toolManager.add(new Separator());
toolManager.add(viewTimeBar);
// and sort out our specific items
refreshTimeOperations();
// and the help link
menuManager.add(new Separator());
menuManager.add(CorePlugin.createOpenHelpAction(
"org.mwc.debrief.help.TimeController", null, this));
// ok - get the action bars to re-populate themselves, otherwise we
// don't
// see our changes
}
getViewSite().getActionBars().updateActionBars();
}
private void processClick(final STEP_SIZE step, final boolean fwd)
{
// CorePlugin.logError(Status.INFO, "Starting step", null);
// check that we have a current time (on initialisation some plots may
// not
// contain data)
if (_myTemporalDataset == null)
{
stopPlayingTimer();
return;
}
final HiResDate tNow = _myTemporalDataset.getTime();
if (tNow != null)
{
// just check if we've got a simulation running, in which case we just
// fire a step
if (_steppableTime != null)
// see if the user has pressed 'back to start', in which case we will
// rewind
if ((step == STEP_SIZE.END) && (fwd == false))
_steppableTime.restart(this, true);
else
_steppableTime.step(this, true);
else
{
// yup, time is there. work with it baby
long micros = tNow.getMicros();
// right, special case for when user wants to go straight to the end
// which
// case there is a zero in the scale
if (step == STEP_SIZE.END)
{
// right, fwd or bwd
if (fwd)
micros = _myTemporalDataset.getPeriod().getEndDTG().getMicros();
else
micros = _myTemporalDataset.getPeriod().getStartDTG().getMicros();
}
else
{
final long size;
// normal processing..
if (step == STEP_SIZE.LARGE)
{
// do large step
size = (long) _myStepperProperties.getLargeStep().getValueIn(
Duration.MICROSECONDS);
}
else if (step == STEP_SIZE.NORMAL)
{
// and the small size step
size = (long) _myStepperProperties.getSmallStep().getValueIn(
Duration.MICROSECONDS);
}
else
{
// and the small size step
size = (long) _myStepperProperties.getSmallStep().getValueIn(
Duration.MICROSECONDS) / 10;
}
// right, either move forwards or backwards.
if (fwd)
micros += size;
else
micros -= size;
}
final HiResDate newDTG = new HiResDate(0, micros);
// find the extent of the current dataset
/*
* RIGHT, until JAN 2007 this next line had been commented out - replaced by the line
* immediately after it. We've switched back to this implementation. This implementation
* lets the time-slider select a time for which there aren't any points visible. This makes
* sense because in it's successor implementation when the DTG slipped outside the visible
* time period, the event was rejected, and the time- controller buttons appeared to break.
* It remains responsive this way...
*/
TimePeriod timeP = _myTemporalDataset.getPeriod();
if (_filterToSelectionAction != null && _filterToSelectionAction
.isChecked())
{
final TimePeriod filteredPeriod = _controllablePeriod.getPeriod();
if (filteredPeriod != null)
{
timeP = filteredPeriod;
}
}
if (timeP != null)
{
// do we represent a valid time?
if (timeP.contains(newDTG))
{
// yes, fire the new DTG
fireNewTime(newDTG);
}
else
{
final HiResDate timeToUse;
if (newDTG.greaterThan(timeP.getEndDTG()))
{
// ok, we've passed the end, use the last point
timeToUse = timeP.getEndDTG();
}
else
{
// ok, we're before the start, use the first point
timeToUse = timeP.getStartDTG();
}
fireNewTime(timeToUse);
// and stop recording
stopRecording(timeToUse);
stopPlayingTimer();
}
}
}
}
// CorePlugin.logError(Status.INFO, "Step complete", null);
}
/**
* we may be listening to an object that cannot be rewound, that does not support backward
* stepping. If so, let us reformat ourselves accordingly
*
* @param canRewind
* whether this time-dataset can rewind
*/
protected void reformatUI(final boolean canRewind)
{
_tNowSlider.setVisible(canRewind);
_dtgRangeSlider.getControl().setVisible(canRewind);
// and now the play buttons
_buttonList.get("lBwd").setVisible(canRewind);
_buttonList.get("sBwd").setVisible(canRewind);
_buttonList.get("lFwd").setVisible(canRewind);
_buttonList.get("eFwd").setVisible(canRewind);
final GridData gd1 = (GridData) _buttonList.get("lBwd").getLayoutData();
final GridData gd2 = (GridData) _buttonList.get("sBwd").getLayoutData();
final GridData gd3 = (GridData) _buttonList.get("lFwd").getLayoutData();
final GridData gd4 = (GridData) _buttonList.get("eFwd").getLayoutData();
gd1.exclude = !canRewind;
gd2.exclude = !canRewind;
gd3.exclude = !canRewind;
gd4.exclude = !canRewind;
// also reduce the number of columns if we have to
final GridLayout gl = (GridLayout) _btnPanel.getLayout();
if (canRewind)
{
gl.numColumns = 8;
}
else
{
gl.numColumns = 4;
}
// tell the parent that some buttons have changed, and that it probably
// wants to do a re-layout
_btnPanel.pack(true);
// sort out the dropdowns
populateDropDownList(null);
}
protected void refreshTimeOperations()
{
// ok, loop through them, deleting them
final IMenuManager menuManager = getViewSite().getActionBars()
.getMenuManager();
// do we have any legacy time operations
if (_legacyTimeOperations == null)
{
_legacyTimeOperations = new Vector<Action>();
}
else
{
// yup, we do have one - better ditch the old ones
final Iterator<Action> iter = _legacyTimeOperations.iterator();
while (iter.hasNext())
{
final Action action = iter.next();
menuManager.remove((IContributionItem) action);
}
// and clear the list
_legacyTimeOperations.removeAllElements();
}
// ok, now add the new ones
if (_timeOperations != null)
{
final Iterator<TimeControllerOperation> newOps = _timeOperations
.iterator();
while (newOps.hasNext())
{
final TimeControllerOperation newOp = newOps.next();
final Action newAction = new Action(newOp.getName())
{
@Override
public void run()
{
newOp.run(_myTrackProvider.getPrimaryTrack(), _myTrackProvider
.getSecondaryTracks(), getPeriod());
}
};
// give it an id, so we can look for it shortly.
newAction.setId(newAction.getText());
final ImageDescriptor id = newOp.getDescriptor();
if (id != null)
newAction.setImageDescriptor(id);
// see if we already contain it
if (menuManager.find(newAction.getId()) != null)
{
// ignore, we already know about it
}
else
menuManager.insertBefore(OP_LIST_MARKER_ID, newAction);
}
}
}
@Override
public void removeSelectionChangedListener(
final ISelectionChangedListener listener)
{
_selectionListeners.remove(listener);
}
/**
* @param memento
*/
@Override
public void saveState(final IMemento memento)
{
super.saveState(memento);
// // ok, store me bits
// start off with the time step
memento.putInteger(SLIDER_STEP_SIZE, (int) _dtgRangeSlider.getStepSize());
// first the
}
/**
* user has selected a time period, indicate it to the controllable
*
* @param period
*/
protected void selectPeriod(final TimePeriod period)
{
if (_controllablePeriod != null)
{
// updating the text items has to be done in the UI thread. make it
// so. We do it "sync" rather than "aSync" because
// much higher up the call tree we switch off
// _filterToSelection, run this action, then switch that
// setting back on. If we do this async, the previous
// method reverts the setting, then calls this, which
// has no benefit.
Display.getDefault().syncExec(new Runnable()
{
@Override
public void run()
{
// just do a double-check that we have a controllable
// period,
// - after this process is being run as async, we may have
// lost the controllable
// period since starting the manoeuvre.
if (_controllablePeriod == null)
{
CorePlugin.logError(IStatus.ERROR,
"Maintainer problem: In TimeController, we have lost our controllable period in async call",
null);
return;
}
_controllablePeriod.setPeriod(period);
// are we set to filter?
if (_filterToSelectionAction.isChecked())
{
_controllablePeriod.performOperation(
ControllablePeriod.FILTER_TO_TIME_PERIOD);
// and trim down the range of our slider manager
// hey, what's the current dtg?
final HiResDate currentDTG = _slideManager.fromSliderUnits(
_tNowSlider.getSelection(), _dtgRangeSlider.getStepSize());
// update the range of the slider
_slideManager.resetRange(period.getStartDTG(), period.getEndDTG());
// hey - remember the updated time range (largely so
// that we can
// restore from file later on)
_myStepperProperties.setSliderStartTime(period.getStartDTG());
_myStepperProperties.setSliderEndTime(period.getEndDTG());
// do we need to move the slider back into a valid
// point?
// hmm, was it too late?
HiResDate trimmedDTG = null;
if (currentDTG.greaterThan(period.getEndDTG()))
{
trimmedDTG = period.getEndDTG();
}
else if (currentDTG.lessThan(period.getStartDTG()))
{
trimmedDTG = period.getStartDTG();
}
else
{
if (!_alreadyProcessingChange)
if (!_tNowSlider.isDisposed())
{
_tNowSlider.setSelection(_slideManager.toSliderUnits(
currentDTG));
}
}
// did we have to move them?
if (trimmedDTG != null)
{
fireNewTime(trimmedDTG);
}
}
}
});
}
}
@Override
public void setFocus()
{
// ok - put the cursor on the time sldier
if (!_tNowSlider.isDisposed())
{
_tNowSlider.setFocus();
}
}
private void setRelativeMode(final boolean primaryCentred,
final boolean primaryOriented)
{
_targetProjection.setRelativeMode(primaryCentred, primaryOriented);
// and trigger redraw
final IWorkbench wb = PlatformUI.getWorkbench();
final IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
final IWorkbenchPage page = win.getActivePage();
final IEditorPart editor = page.getActiveEditor();
if (editor instanceof CorePlotEditor)
{
final CorePlotEditor plot = (CorePlotEditor) editor;
plot.update();
}
}
@Override
public void setSelection(final ISelection selection)
{
}
// AND PROPERTY EDITORS FOR THE
private void setupListeners()
{
// try to add ourselves to listen out for page changes
// getSite().getWorkbenchWindow().getPartService().addPartListener(this);
_myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow()
.getPartService());
_myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (_myTemporalDataset != part)
{
// ok, stop listening to the old one
if (_myTemporalDataset != null)
{
// right, we were looking at something, and now
// we're not.
// stop playing (if we were)
if (getTimer().isRunning())
{
// un-depress the play button
_playButton.setSelection(false);
// and tell the button's listeners (which
// will stop the timer
// and update the image)
_playButton.notifyListeners(SWT.Selection, new Event());
}
// stop listening to that dataset
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.PERIOD_CHANGED_PROPERTY_NAME);
}
// implementation here.
_myTemporalDataset = (TimeProvider) part;
// and start listening to the new one
_myTemporalDataset.addListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_myTemporalDataset.addListener(_temporalListener,
TimeProvider.PERIOD_CHANGED_PROPERTY_NAME);
// also configure for the current time
final HiResDate newDTG = _myTemporalDataset.getTime();
timeUpdated(newDTG);
// and initialise the current time
final TimePeriod timeRange = _myTemporalDataset.getPeriod();
if (timeRange != null)
{
// we wish to cancel filtering to selection when
// we update the sliders, since it hides/reveals
// data
// remember the filter-to-window mode
final boolean filtering;
if (_filterToSelectionAction != null)
{
filtering = _filterToSelectionAction.isChecked();
// switch it off
_filterToSelectionAction.setChecked(false);
}
else
{
filtering = false;
}
// and our range selector - first the outer
// ranges
_dtgRangeSlider.updateOuterRanges(timeRange);
// ok, now the user ranges...
_dtgRangeSlider.updateSelectedRanges(timeRange.getStartDTG(),
timeRange.getEndDTG());
// and the time slider range
_slideManager.resetRange(timeRange.getStartDTG(), timeRange
.getEndDTG());
// and restore the original value
if (_filterToSelectionAction != null)
{
_filterToSelectionAction.setChecked(filtering);
}
}
checkTimeEnabled();
// hmm, do we want to store this part?
if (parentPart instanceof IEditorPart)
{
_currentEditor = (IEditorPart) parentPart;
}
}
}
});
_myPartMonitor.addPartListener(PlotEditor.class, PartMonitor.CLOSED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(String type, Object part,
IWorkbenchPart parentPart)
{
if(part == _currentEditor) {
populateDropDownList(_layerPainterManager);
}
}
});
_myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// was it our one?
if (_myTemporalDataset == part)
{
// ok, stop listening to this object (just in case
// we were,
// anyway).
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.PERIOD_CHANGED_PROPERTY_NAME);
_myTemporalDataset = null;
}
// and sort out whether we should be active or not.
checkTimeEnabled();
}
});
_myPartMonitor.addPartListener(TimeControllerOperationStore.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part != _timeOperations)
{
_timeOperations = (TimeControllerOperationStore) part;
// and refresh the dropdown menu
refreshTimeOperations();
}
}
});
_myPartMonitor.addPartListener(SteppableTime.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (_steppableTime != part)
{
_steppableTime = (SteppableTime) part;
// enable the ui, if we have to.
checkTimeEnabled();
}
}
});
_myPartMonitor.addPartListener(SteppableTime.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (_steppableTime != part)
{
_steppableTime = null;
// disable the ui, if we have to.
checkTimeEnabled();
}
}
});
_myPartMonitor.addPartListener(Layers.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// implementation here.
final Layers newLayers = (Layers) part;
if (newLayers != _myLayers)
{
_myLayers = newLayers;
// initialize after mylayers are initialized
// _coordinateRecorder = new
// CoordinateRecorder(_myLayers,_targetProjection,_myStepperProperties);
}
}
});
_myPartMonitor.addPartListener(Layers.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part == _myLayers)
_myLayers = null;
}
});
_myPartMonitor.addPartListener(RelativeProjectionParent.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// implementation here.
final RelativeProjectionParent relProjector =
(RelativeProjectionParent) part;
if (relProjector != _relativeProjector)
{
// ok, better store it
storeProjectionParent(relProjector);
}
}
});
_myPartMonitor.addPartListener(RelativeProjectionParent.class,
PartMonitor.CLOSED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part == _relativeProjector)
_relativeProjector = null;
}
});
_myPartMonitor.addPartListener(PlainProjection.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// implementation here.
final PlainProjection newProjection = (PlainProjection) part;
if (newProjection != _targetProjection)
{
storeNewProjection(newProjection);
}
}
});
_myPartMonitor.addPartListener(PlainProjection.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part == _targetProjection)
_targetProjection = null;
}
});
_myPartMonitor.addPartListener(ControllableTime.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (_controllableTime != part)
{
// implementation here.
final ControllableTime ct = (ControllableTime) part;
_controllableTime = ct;
checkTimeEnabled();
}
}
});
_myPartMonitor.addPartListener(ControllableTime.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part == _controllableTime)
{
_controllableTime = null;
checkTimeEnabled();
}
}
});
_myPartMonitor.addPartListener(ControllablePeriod.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (_controllablePeriod != part)
{
// right, we're clearly not running a simulation here, clear the
// simulation object
// that gets uses as a flag
_steppableTime = null;
// implementation here.
final ControllablePeriod ct = (ControllablePeriod) part;
_controllablePeriod = ct;
checkTimeEnabled();
// ok, we've got all the normal controls, make the ui do it's
// stuff
reformatUI(true);
}
}
});
_myPartMonitor.addPartListener(ControllablePeriod.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part == _controllablePeriod)
{
_controllablePeriod = null;
checkTimeEnabled();
}
}
});
_myPartMonitor.addPartListener(TrackDataProvider.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// sort out our listener
if (_theTrackDataListener == null)
_theTrackDataListener = new TrackDataProvider.TrackDataListener()
{
@Override
public void tracksUpdated(final WatchableList primary,
final WatchableList[] secondaries)
{
// ok - make sure we're seeing the full time
// period
// NO: don't bother, since adding an annotation causes the
// filter to reset
// expandTimeSliderRangeToFull();
// and the controls are enabled (if we know
// time data)
checkTimeEnabled();
}
};
final TrackDataProvider thisTrackProvider =
(TrackDataProvider) part;
if (thisTrackProvider != _myTrackProvider)
{
// do we have one already?
if (_myTrackProvider != null)
{
// ok, ditch existing provider
_myTrackProvider.removeTrackDataListener(_theTrackDataListener);
}
// remember the new one
_myTrackProvider = thisTrackProvider;
_myTrackProvider.addTrackDataListener(_theTrackDataListener);
}
}
});
_myPartMonitor.addPartListener(TrackDataProvider.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part == _myTrackProvider)
{
_myTrackProvider = null;
}
}
});
_myPartMonitor.addPartListener(LayerPainterManager.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (!part.equals(_layerPainterManager))
{
// ok, insert the painter mode actions, together with
// our standard
// ones
_layerPainterManager = (LayerPainterManager) part;
populateDropDownList(_layerPainterManager);
}
}
});
_myPartMonitor.addPartListener(LayerPainterManager.class,
PartMonitor.CLOSED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
if (part.equals(_layerPainterManager))
{
_layerPainterManager = null;
}
}
});
_myPartMonitor.addPartListener(TimeControlPreferences.class,
PartMonitor.ACTIVATED, new PartMonitor.ICallback()
{
@Override
public void eventTriggered(final String type, final Object part,
final IWorkbenchPart parentPart)
{
// just check we're not already managing this plot
if (!part.equals(_myStepperProperties))
{
// ok, ignore the old one, if we have one
if (_myStepperProperties != null)
{
_myStepperProperties.removePropertyChangeListener(
_myDateFormatListener);
_myStepperProperties = null;
}
_myStepperProperties = (TimeControlProperties) part;
if (_myDateFormatListener == null)
_myDateFormatListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
// right, see if the user is changing
// the DTG format
if (evt.getPropertyName().equals(
TimeControlProperties.DTG_FORMAT_ID))
{
// ok, refresh the DTG
final String newVal = getFormattedDate(_myTemporalDataset
.getTime());
_timeLabel.setText(newVal);
// hmm, also set the bi-slider to
// repaint so we get fresh
// labels
_dtgRangeSlider.update();
}
else if (evt.getPropertyName().equals(
TimeControlProperties.STEP_INTERVAL_ID))
{
// hey, if we're stepping, we'd
// better change the size of
// the time step
if (getTimer().isRunning())
{
final Duration theDelay = (Duration) evt.getNewValue();
getTimer().setDelay((long) theDelay.getValueIn(
Duration.MILLISECONDS));
}
}
}
};
// also, listen out for changes in the DTG formatter
_myStepperProperties.addPropertyChangeListener(
_myDateFormatListener);
// and update the slider ranges
// do we have start/stop times?
final HiResDate startDTG = _myStepperProperties
.getSliderStartTime();
if ((startDTG != null) && (_myTemporalDataset != null))
{
// cool - update the slider to our data settings
final HiResDate startTime = _myStepperProperties
.getSliderStartTime();
final HiResDate endTime = _myStepperProperties
.getSliderEndTime();
// ok, set the filtered time period
_slideManager.resetRange(startTime, endTime);
// ok, set the slider ranges...
_dtgRangeSlider.updateSelectedRanges(startTime, endTime);
// and set the time again - the slider has
// probably forgotten
timeUpdated(_myTemporalDataset.getTime());
}
}
}
});
}
protected void setVCREnabled(final boolean enable)
{
for (final String key : _buttonList.keySet())
{
final Button item = _buttonList.get(key);
if ((!key.equals(PLAY_BUTTON_KEY) && _playing) || (!key.equals(
RECORD_BUTTON_KEY) && !_playing))
{
item.setEnabled(enable);
}
}
}
/**
* ok, start auto-stepping forward through the serial
*/
private void startPlaying()
{
// hey - set a practical minimum step size, 1/4 second is a fair start
// point
final long delayToUse = Math.max(_myStepperProperties.getAutoInterval()
.getMillis(), 250);
// ok - make sure the time has the right time
getTimer().setDelay(delayToUse);
getTimer().start();
}
private void startRecording()
{
_coordinateRecorder = new CoordinateRecorder(_myLayers, _targetProjection,
_myStepperProperties);
_coordinateRecorder.startStepping(getTimeProvider().getTime());
setVCREnabled(false);
_recordButton.setToolTipText(STOP_TEXT);
_recordButton.setImage(TimeControllerPlugin.getImage(
ICON_MEDIA_STOP_RECORD));
}
private void stopPlaying()
{
/**
* give the event to our child class, in case it's a scenario
*
*/
if (_steppableTime != null)
_steppableTime.pause(this, true);
getTimer().stop();
}
// RELATIVE PROJECTION-RELATED BITS
private void stopPlayingTimer()
{
if (getTimer().isRunning())
{
stopPlaying();
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
_playButton.setToolTipText(PLAY_TEXT);
_playButton.setImage(TimeControllerPlugin.getImage(ICON_MEDIA_PLAY));
// and update the VCR buttons
setVCREnabled(true);
}
});
}
}
private void stopRecording(final HiResDate timeNow)
{
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
// switch the button
_recordButton.setToolTipText(RECORD_TEXT);
_recordButton.setImage(TimeControllerPlugin.getImage(
ICON_MEDIA_RECORD));
// and update the VCR buttons
setVCREnabled(true);
}
});
if (_coordinateRecorder != null)
{
_coordinateRecorder.stopStepping(timeNow);
resetRecordingLabel();
_coordinateRecorder = null;
}
}
protected void storeNewProjection(final PlainProjection newProjection)
{
// ok, remember the projection
_targetProjection = newProjection;
// and tell it we're here
_targetProjection.setRelativeProjectionParent(this);
// and reflect it's current status
if (_targetProjection.getNonStandardPlotting())
{
if (_targetProjection.getPrimaryOriented())
{
_primaryCentredPrimaryOrientedPlottingMode.setChecked(true);
}
else
{
_primaryCentredNorthOrientedPlottingMode.setChecked(true);
}
}
else
_normalPlottingMode.setChecked(true);
}
/**
* remember the new relative projection provider
*
* @param relProjector
*/
protected void storeProjectionParent(
final RelativeProjectionParent relProjector)
{
// ok, this isn't us, is it?
if (relProjector != this)
{
// ok, store it
_relativeProjector = relProjector;
}
}
/**
* the data we are looking at has updated. If we're set to follow that time, update ourselves
*/
private void timeUpdated(final HiResDate newDTG)
{
if (newDTG != null)
{
// display the correct time.
if (!_timeLabel.isDisposed())
{
// updating the text items has to be done in the UI thread. make
// it so
// note - we use 'syncExec'. When we were using asyncExec, we
// would have
// a back-log
// of events waiting to fire.
final Runnable nextEvent = new Runnable()
{
@Override
public void run()
{
// display the correct time.
final String newVal = getFormattedDate(newDTG);
if (!_timeLabel.isDisposed())
_timeLabel.setText(newVal);
// there's a (slim) chance that the temp dataset has
// already been
// cleared, or
// hasn't been caught yet. just check we still know
// about it
if (!_alreadyProcessingChange && _myTemporalDataset != null)
{
final TimePeriod dataPeriod = _myTemporalDataset.getPeriod();
if (dataPeriod != null)
{
final int newIndex = _slideManager.toSliderUnits(newDTG);
// did we find a valid time?
if (newIndex != -1)
{
// yes, go for it.
if (!_tNowSlider.isDisposed())
{
_tNowSlider.setSelection(newIndex);
}
}
}
}
}
};
Display.getDefault().syncExec(nextEvent);
}
}
else
{
System.out.println("null DTG received by time controller");
// updating the text items has to be done in the UI thread. make it
Display.getDefault().asyncExec(new Runnable()
{
@Override
public void run()
{
_timeLabel.setText(DUFF_TIME_TEXT);
}
});
}
}
}
|
package it.unibz.inf.ontop.reformulation.tests;
import com.google.common.collect.ImmutableList;
import it.unibz.inf.ontop.model.*;
import it.unibz.inf.ontop.pivotalrepr.*;
import it.unibz.inf.ontop.pivotalrepr.equivalence.IQSyntacticEquivalenceChecker;
import it.unibz.inf.ontop.pivotalrepr.impl.ImmutableQueryModifiersImpl;
import it.unibz.inf.ontop.pivotalrepr.proposal.NodeCentricOptimizationResults;
import it.unibz.inf.ontop.pivotalrepr.proposal.impl.InnerJoinOptimizationProposalImpl;
import it.unibz.inf.ontop.sql.*;
import org.junit.Ignore;
import org.junit.Test;
import java.sql.Types;
import java.util.Optional;
import static it.unibz.inf.ontop.OptimizationTestingTools.DATA_FACTORY;
import static it.unibz.inf.ontop.OptimizationTestingTools.IQ_FACTORY;
import static it.unibz.inf.ontop.OptimizationTestingTools.createQueryBuilder;
import static it.unibz.inf.ontop.model.ExpressionOperation.NEQ;
import static junit.framework.TestCase.assertTrue;
/**
* Elimination of redundant self-joins using a non unique functional constraint
*/
@Ignore
public class NonUniqueFunctionalConstraintTest {
private final static AtomPredicate TABLE1_PREDICATE;
private final static AtomPredicate TABLE2_PREDICATE;
private final static AtomPredicate ANS1_PREDICATE_AR_1 = DATA_FACTORY.getAtomPredicate("ans1", 1);
private final static AtomPredicate ANS1_PREDICATE_AR_2 = DATA_FACTORY.getAtomPredicate("ans1", 2);
private final static AtomPredicate ANS1_PREDICATE_AR_3 = DATA_FACTORY.getAtomPredicate("ans1", 3);
private final static Variable X = DATA_FACTORY.getVariable("x");
private final static Variable Y = DATA_FACTORY.getVariable("y");
private final static Variable Z = DATA_FACTORY.getVariable("z");
private final static Variable A = DATA_FACTORY.getVariable("a");
private final static Variable B = DATA_FACTORY.getVariable("b");
private final static Variable C = DATA_FACTORY.getVariable("c");
private final static Variable D = DATA_FACTORY.getVariable("d");
private final static Variable E = DATA_FACTORY.getVariable("e");
private final static Variable F = DATA_FACTORY.getVariable("f");
private final static Variable G = DATA_FACTORY.getVariable("g");
private final static Constant ONE = DATA_FACTORY.getConstantLiteral("1");
private final static Constant TWO = DATA_FACTORY.getConstantLiteral("2");
private final static Constant THREE = DATA_FACTORY.getConstantLiteral("3");
private final static ImmutableQueryModifiers DISTINCT_MODIFIER = new ImmutableQueryModifiersImpl(true, -1, -1, ImmutableList.of()) ;
private static final DBMetadata METADATA;
static{
BasicDBMetadata dbMetadata = DBMetadataTestingTools.createDummyMetadata();
QuotedIDFactory idFactory = dbMetadata.getQuotedIDFactory();
/**
* Table 1: PK + non-unique functional constraint + 2 dependent fields + 1 independent
*/
DatabaseRelationDefinition table1Def = dbMetadata.createDatabaseRelation(idFactory.createRelationID(null,"table1"));
Attribute col1T1 = table1Def.addAttribute(idFactory.createAttributeID("col1"), Types.INTEGER, null, false);
Attribute col2T1 = table1Def.addAttribute(idFactory.createAttributeID("col2"), Types.INTEGER, null, false);
Attribute col3T1 = table1Def.addAttribute(idFactory.createAttributeID("col3"), Types.INTEGER, null, false);
Attribute col4T1 = table1Def.addAttribute(idFactory.createAttributeID("col4"), Types.INTEGER, null, false);
// Independent
table1Def.addAttribute(idFactory.createAttributeID("col5"), Types.INTEGER, null, false);
table1Def.addUniqueConstraint(UniqueConstraint.primaryKeyOf(col1T1));
table1Def.addNonUniqueFunctionalConstraint(NonUniqueFunctionalConstraint.defaultBuilder()
.addDeterminant(col2T1)
.addDependent(col3T1)
.addDependent(col4T1)
.build());
TABLE1_PREDICATE = Relation2DatalogPredicate.createAtomPredicateFromRelation(table1Def);
/**
* Table 2: non-composite unique constraint and regular field
*/
DatabaseRelationDefinition table2Def = dbMetadata.createDatabaseRelation(idFactory.createRelationID(null,"table2"));
table2Def.addAttribute(idFactory.createAttributeID("col1"), Types.INTEGER, null, false);
Attribute col2T2 = table2Def.addAttribute(idFactory.createAttributeID("col2"), Types.INTEGER, null, false);
table2Def.addAttribute(idFactory.createAttributeID("col3"), Types.INTEGER, null, false);
table2Def.addUniqueConstraint(UniqueConstraint.primaryKeyOf(col2T2));
TABLE2_PREDICATE = Relation2DatalogPredicate.createAtomPredicateFromRelation(table2Def);
dbMetadata.freeze();
METADATA = dbMetadata;
}
@Test
public void testRedundantSelfJoin1() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, C, D));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, E, A, Y, F, G));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQueryBuilder expectedQueryBuilder = createQueryBuilder(METADATA);
expectedQueryBuilder.init(projectionAtom, rootNode);
ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, Y, C, D));
expectedQueryBuilder.addChild(rootNode, dataNode3);
IntermediateQuery expectedQuery = expectedQueryBuilder.build();
optimizeAndCompare(query, expectedQuery, joinNode);
}
@Test
public void testRedundantSelfJoin2() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_3,
X, Y, Z);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, Z, C));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, E, A, Y, F, G));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQueryBuilder expectedQueryBuilder = createQueryBuilder(METADATA);
expectedQueryBuilder.init(projectionAtom, rootNode);
ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, Y, Z, C));
expectedQueryBuilder.addChild(rootNode, dataNode3);
IntermediateQuery expectedQuery = expectedQueryBuilder.build();
optimizeAndCompare(query, expectedQuery, joinNode);
}
@Test
public void testRedundantSelfJoin3() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_3,
X, Y, Z);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, D, A, Z, B, C));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, Y, F, G));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQueryBuilder expectedQueryBuilder = createQueryBuilder(METADATA);
ConstructionNode newRootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(Z, Y), Optional.of(DISTINCT_MODIFIER));
expectedQueryBuilder.init(projectionAtom, newRootNode);
ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, Y, F, G));
expectedQueryBuilder.addChild(newRootNode, dataNode3);
IntermediateQuery expectedQuery = expectedQueryBuilder.build();
optimizeAndCompare(query, expectedQuery, joinNode);
}
@Test
public void testRedundantSelfJoin4() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, C, D));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, E, A, Y, X, F));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQueryBuilder expectedQueryBuilder = createQueryBuilder(METADATA);
expectedQueryBuilder.init(projectionAtom, rootNode);
ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, Y, X, D));
expectedQueryBuilder.addChild(rootNode, dataNode3);
IntermediateQuery expectedQuery = expectedQueryBuilder.build();
optimizeAndCompare(query, expectedQuery, joinNode);
}
@Test
public void testRedundantSelfJoin5() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_3, X, Y, Z);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, C, Y));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, D, A, E, Z, G));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQueryBuilder expectedQueryBuilder = createQueryBuilder(METADATA);
expectedQueryBuilder.init(projectionAtom, rootNode);
ExtensionalDataNode dataNode3 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, Z, Y));
expectedQueryBuilder.addChild(rootNode, dataNode3);
IntermediateQuery expectedQuery = expectedQueryBuilder.build();
optimizeAndCompare(query, expectedQuery, joinNode);
}
/**
* Y --> from an independent attribute
*/
@Test
public void testNonRedundantSelfJoin1() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, C, D));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, E, A, F, G, Y));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQuery expectedQuery = query.createSnapshot();
optimizeAndCompare(query, expectedQuery, joinNode);
}
@Test
public void testNonRedundantSelfJoin2() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, Y, C, D));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, Y, A, Y, E, F));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
IntermediateQuery expectedQuery = query.createSnapshot();
optimizeAndCompare(query, expectedQuery, joinNode);
}
@Test(expected = EmptyQueryException.class)
public void testRejectedJoin1() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode();
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, ONE, B, C));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, D, A, TWO, E, Y));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
System.out.println("\nBefore optimization: \n" + query);
query.applyProposal(new InnerJoinOptimizationProposalImpl(joinNode));
}
@Test(expected = EmptyQueryException.class)
public void testRejectedJoin2() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(DATA_FACTORY.getImmutableExpression(NEQ, B, TWO));
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, C, D));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, E, A, TWO, F, Y));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
System.out.println("\nBefore optimization: \n" + query);
query.applyProposal(new InnerJoinOptimizationProposalImpl(joinNode));
}
@Test(expected = EmptyQueryException.class)
public void testRejectedJoin3() throws EmptyQueryException {
DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE_AR_2, X, Y);
ConstructionNode rootNode = IQ_FACTORY.createConstructionNode(projectionAtom.getVariables(),
DATA_FACTORY.getSubstitution(), Optional.of(DISTINCT_MODIFIER));
IntermediateQueryBuilder queryBuilder = createQueryBuilder(METADATA);
queryBuilder.init(projectionAtom, rootNode);
InnerJoinNode joinNode = IQ_FACTORY.createInnerJoinNode(DATA_FACTORY.getImmutableExpression(NEQ, F, TWO));
queryBuilder.addChild(rootNode, joinNode);
ExtensionalDataNode dataNode1 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, A, B, B, D));
queryBuilder.addChild(joinNode, dataNode1);
ExtensionalDataNode dataNode2 = IQ_FACTORY.createExtensionalDataNode(
DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, E, A, TWO, F, Y));
queryBuilder.addChild(joinNode, dataNode2);
IntermediateQuery query = queryBuilder.build();
System.out.println("\nBefore optimization: \n" + query);
query.applyProposal(new InnerJoinOptimizationProposalImpl(joinNode));
}
private static NodeCentricOptimizationResults<InnerJoinNode> optimizeAndCompare(IntermediateQuery query,
IntermediateQuery expectedQuery,
InnerJoinNode joinNode)
throws EmptyQueryException {
System.out.println("\nBefore optimization: \n" + query);
System.out.println("\n Expected query: \n" + expectedQuery);
NodeCentricOptimizationResults<InnerJoinNode> results = query.applyProposal(
new InnerJoinOptimizationProposalImpl(joinNode));
System.out.println("\n After optimization: \n" + query);
assertTrue(IQSyntacticEquivalenceChecker.areEquivalent(query, expectedQuery));
return results;
}
}
|
package org.osgi.test.cases.monitor.tbc;
import org.osgi.service.permissionadmin.PermissionInfo;
public class PermissionWorker extends Thread {
private MonitorTestControl tbc;
private PermissionInfo[] permissions;
private String location;
public PermissionWorker(MonitorTestControl tbc) {
this.tbc = tbc;
}
public synchronized void run() {
while (true) {
try {
this.wait();
tbc.getPermissionAdmin().setPermissions(location, permissions);
this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* @return Returns the location.
*/
public String getLocation() {
return location;
}
/**
* @param location The location to set.
*/
public void setLocation(String location) {
this.location = location;
}
public PermissionInfo[] getPermissions() {
return permissions;
}
public void setPermissions(PermissionInfo[] permissions) {
this.permissions = permissions;
}
}
|
package authoring.concretefeatures;
import gamedata.action.Action;
import gamedata.gamecomponents.Patch;
import gamedata.gamecomponents.Piece;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import authoring.abstractfeatures.PopupWindow;
import authoring_environment.LibraryView;
public class ActionCheck extends PopupWindow {
private final int HEIGHT = 400;
private final int WIDTH = 400;
private final String ACTION = "Action";
private final String NAME = "Available Actions for Units";
private final String ACTION_TYPE = "Action Type";
private final String ACTOR = "Actor";
private final String RECEIVER = "Receiver";
private LibraryView myLibrary;
private List<Action> myActions;
private List<String> myPieces = new ArrayList<String>();
private List<Patch> myPatches;
private Map<String, Map> Conclusion;
private static final String STYLESHEET = "/resources/stylesheets/actioncreator_layout.css";
/**
* Constructor for ActionCheck popup window
*
* @param actionLst List of all the actions
* @param pieceLst List of pieces
* @param patchLst List of patches
*/
// public ActionCheck (List<Action> actionLst, List<Piece> pieceLst, List<Patch> patchLst) {
// myActions = actionLst;
// myPieces = pieceLst;
// myPatches = patchLst;
// setHeight(HEIGHT);
// setWidth(WIDTH);
// setTitle(NAME);
// initialize();
public ActionCheck () {
setHeight(HEIGHT);
setWidth(WIDTH);
setTitle(NAME);
initialize();
}
@Override
protected void initialize () {
myPieces.add("Piece A");
myPieces.add("Piece B");
myPieces.add("Piece C");
ScrollPane root = new ScrollPane();
Scene scene = new Scene(root, WIDTH, HEIGHT);
scene.getStylesheets().add(STYLESHEET);
VBox mainVBox = new VBox();
mainVBox.getStyleClass().add("vbox");
mainVBox.setId("vbox-main");
VBox actionNameVBox = new VBox();
VBox posActorVBox = new VBox();
VBox posReceiverVBox = new VBox();
ChoiceBox<String> actionTypes = new ChoiceBox<String>();
initActionChooser(actionNameVBox, actionTypes);
ChoiceBox<String> posActors = new ChoiceBox<String>();
initActorChooser(posActorVBox, posActors);
initReceiverChooser(posReceiverVBox, posActors, actionTypes);
mainVBox.getChildren().addAll(actionNameVBox, new Separator(), posActorVBox,
new Separator(), posReceiverVBox);
root.setContent(mainVBox);
setScene(scene);
}
private void initReceiverChooser (VBox posReceiverVBox,
ChoiceBox<String> posActors,
ChoiceBox<String> actionTypes) {
Label posReceiverLabel = new Label(RECEIVER);
Button posReceiversbtn = new Button("Possible Receivers");
posReceiversbtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle (ActionEvent event) {
PopupWindow receiversChooser =
new ReceiverEditor(myPieces, posActors.getValue().toString(), actionTypes
.getValue().toString());
receiversChooser.show();
}
});
posReceiverVBox.getChildren().addAll(posReceiverLabel, posReceiversbtn);
}
private void initActorChooser (VBox posActorVBox, ChoiceBox<String> posActors) {
// TODO Auto-generated method stub
Label actorLabel = new Label(ACTOR);
posActors.getItems().addAll("Piece A", "Piece B", "Piece C");
HBox actorsHbox = new HBox();
actorsHbox.getChildren().addAll(posActors);
posActorVBox.getChildren().addAll(actorLabel, actorsHbox);
}
private void initActionChooser (VBox nameVBox, ChoiceBox<String> actionTypes) {
// TODO: actionTypes needs to get List<String> that contains names of all the action types
Label targetLabel = new Label(ACTION_TYPE);
actionTypes.getItems().addAll("Attack", "Heal", "AlltheRest");
HBox actionsHBox = new HBox();
actionsHBox.getChildren().addAll(actionTypes);
nameVBox.getChildren().addAll(targetLabel, actionsHBox);
}
}
|
package org.pac4j.cas.credentials.authenticator;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.cas.profile.CasProfile;
import org.pac4j.cas.profile.CasProxyProfile;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.TokenCredentials;
import org.pac4j.core.credentials.authenticator.Authenticator;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.http.CallbackUrlResolver;
import org.pac4j.core.profile.ProfileHelper;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.core.util.InitializableWebObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* CAS authenticator which validates the service ticket.
*
* @author Jerome Leleu
* @since 1.9.2
*/
public class CasAuthenticator extends InitializableWebObject implements Authenticator<TokenCredentials> {
private final static Logger logger = LoggerFactory.getLogger(CasAuthenticator.class);
private CasConfiguration configuration;
private String callbackUrl;
public CasAuthenticator() {}
public CasAuthenticator(final CasConfiguration configuration, final String callbackUrl) {
this.configuration = configuration;
this.callbackUrl = callbackUrl;
}
@Override
protected void internalInit(final WebContext context) {
CommonHelper.assertNotNull("configuration", configuration);
CommonHelper.assertNotBlank("callbackUrl", callbackUrl);
configuration.init(context);
}
@Override
public void validate(final TokenCredentials credentials, final WebContext context) throws HttpAction {
init(context);
final String ticket = credentials.getToken();
try {
String finalCallbackUrl = callbackUrl;
final CallbackUrlResolver callbackUrlResolver = configuration.getCallbackUrlResolver();
if (callbackUrlResolver != null) {
finalCallbackUrl = callbackUrlResolver.compute(finalCallbackUrl, context);
}
final Assertion assertion = configuration.getTicketValidator().validate(ticket, finalCallbackUrl);
final AttributePrincipal principal = assertion.getPrincipal();
logger.debug("principal: {}", principal);
final CasProfile casProfile;
if (configuration.getProxyReceptor() != null) {
casProfile = new CasProxyProfile();
((CasProxyProfile) casProfile).setPrincipal(principal);
} else {
casProfile = new CasProfile();
}
casProfile.setId(principal.getName());
// restore attributes
final Map<String, Object> attributes = principal.getAttributes();
if (attributes != null) {
for (final Map.Entry<String, Object> entry : attributes.entrySet()){
final String key = entry.getKey();
final Object value = entry.getValue();
final Object restored = ProfileHelper.getInternalAttributeHandler().restore(value);
casProfile.addAttribute(key, restored);
}
}
logger.debug("casProfile: {}", casProfile);
credentials.setUserProfile(casProfile);
} catch (final TicketValidationException e) {
String message = "cannot validate CAS ticket: " + ticket;
throw new TechnicalException(message, e);
}
}
public CasConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(CasConfiguration configuration) {
this.configuration = configuration;
}
public String getCallbackUrl() {
return callbackUrl;
}
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl;
}
@Override
public String toString() {
return CommonHelper.toString(this.getClass(), "configuration", configuration, "callbackUrl", callbackUrl);
}
}
|
package org.opentosca.yamlconverter.yamlmodel.yaml.element;
import java.util.HashMap;
import java.util.Map;
public class NodeTemplate extends YAMLElement {
private String type;
private Map<String, Object> properties = new HashMap<>();
public NodeTemplate() {
this.type = "";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
}
|
package org.pac4j.core.engine;
import org.junit.Before;
import org.junit.Test;
import org.pac4j.core.client.Clients;
import org.pac4j.core.client.IndirectClient;
import org.pac4j.core.client.MockDirectClient;
import org.pac4j.core.client.MockIndirectClient;
import org.pac4j.core.config.Config;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.context.Pac4jConstants;
import org.pac4j.core.credentials.MockCredentials;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.http.HttpActionAdapter;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.util.TestsConstants;
import org.pac4j.core.util.TestsHelper;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests {@link J2ERenewSessionCallbackLogic}.
*
* @author Jerome Leleu
* @since 1.9.0
*/
public final class J2ERenewSessionCallbackLogicTests implements TestsConstants {
private CallbackLogic<Object, J2EContext> logic;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected MockFilterChain filterChain;
private J2EContext context;
private Config config;
private HttpActionAdapter<Object, J2EContext> httpActionAdapter;
private String defaultUrl;
private Boolean renewSession;
@Before
public void setUp() {
logic = new J2ERenewSessionCallbackLogic();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
filterChain = new MockFilterChain();
context = new J2EContext(request, response);
config = new Config();
httpActionAdapter = (code, ctx) -> null;
defaultUrl = null;
renewSession = null;
}
private void call() {
logic.perform(context, config, httpActionAdapter, defaultUrl, null, renewSession);
}
@Test
public void testNullConfig() {
config = null;
TestsHelper.expectException(() -> call(), TechnicalException.class, "config cannot be null");
}
@Test
public void testNullContext() {
context = null;
TestsHelper.expectException(() -> call(), TechnicalException.class, "context cannot be null");
}
@Test
public void testNullHttpActionAdapter() {
httpActionAdapter = null;
TestsHelper.expectException(() -> call(), TechnicalException.class, "httpActionAdapter cannot be null");
}
@Test
public void testBlankDefaultUrl() {
defaultUrl = "";
TestsHelper.expectException(() -> call(), TechnicalException.class, "defaultUrl cannot be blank");
}
@Test
public void testNullClients() {
config.setClients(null);
TestsHelper.expectException(() -> call(), TechnicalException.class, "clients cannot be null");
}
@Test
public void testDirectClient() throws Exception {
request.addParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
final MockDirectClient directClient = new MockDirectClient(NAME, new MockCredentials(), new CommonProfile());
config.setClients(new Clients(directClient));
TestsHelper.expectException(() -> call(), TechnicalException.class, "only indirect clients are allowed on the callback url");
}
@Test
public void testCallback() throws Exception {
final String originalSessionId = request.getSession().getId();
request.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
final CommonProfile profile = new CommonProfile();
final IndirectClient indirectClient = new MockIndirectClient(NAME, null, new MockCredentials(), profile);
config.setClients(new Clients(CALLBACK_URL, indirectClient));
call();
final HttpSession session = request.getSession();
final String newSessionId = session.getId();
final LinkedHashMap<String, CommonProfile> profiles = (LinkedHashMap<String, CommonProfile>) session.getAttribute(Pac4jConstants.USER_PROFILES);
assertTrue(profiles.containsValue(profile));
assertEquals(1, profiles.size());
assertNotEquals(newSessionId, originalSessionId);
assertEquals(302, response.getStatus());
assertEquals(Pac4jConstants.DEFAULT_URL_VALUE, response.getRedirectedUrl());
}
@Test
public void testCallbackWithOriginallyRequestedUrl() throws Exception {
HttpSession session = request.getSession();
final String originalSessionId = session.getId();
session.setAttribute(Pac4jConstants.REQUESTED_URL, PAC4J_URL);
request.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
final CommonProfile profile = new CommonProfile();
final IndirectClient indirectClient = new MockIndirectClient(NAME, null, new MockCredentials(), profile);
config.setClients(new Clients(CALLBACK_URL, indirectClient));
call();
session = request.getSession();
final String newSessionId = session.getId();
final LinkedHashMap<String, CommonProfile> profiles = (LinkedHashMap<String, CommonProfile>) session.getAttribute(Pac4jConstants.USER_PROFILES);
assertTrue(profiles.containsValue(profile));
assertEquals(1, profiles.size());
assertNotEquals(newSessionId, originalSessionId);
assertEquals(302, response.getStatus());
assertEquals(PAC4J_URL, response.getRedirectedUrl());
}
@Test
public void testCallbackNoRenew() throws Exception {
final String originalSessionId = request.getSession().getId();
request.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
final CommonProfile profile = new CommonProfile();
final IndirectClient indirectClient = new MockIndirectClient(NAME, null, new MockCredentials(), profile);
config.setClients(new Clients(CALLBACK_URL, indirectClient));
renewSession = false;
call();
final HttpSession session = request.getSession();
final String newSessionId = session.getId();
final LinkedHashMap<String, CommonProfile> profiles = (LinkedHashMap<String, CommonProfile>) session.getAttribute(Pac4jConstants.USER_PROFILES);
assertTrue(profiles.containsValue(profile));
assertEquals(1, profiles.size());
assertEquals(newSessionId, originalSessionId);
assertEquals(302, response.getStatus());
assertEquals(Pac4jConstants.DEFAULT_URL_VALUE, response.getRedirectedUrl());
}
}
|
package org.pocketcampus.plugin.transport.android;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.pocketcampus.R;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.core.PluginView;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCEntryAdapter;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCEntryItem;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCItem;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCSectionItem;
import org.pocketcampus.android.platform.sdk.ui.adapter.RichLabeledArrayAdapter;
import org.pocketcampus.android.platform.sdk.ui.element.ButtonElement;
import org.pocketcampus.android.platform.sdk.ui.labeler.ILabeler;
import org.pocketcampus.android.platform.sdk.ui.labeler.IRichLabeler;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledDoubleLayout;
import org.pocketcampus.android.platform.sdk.ui.list.RichLabeledListViewElement;
import org.pocketcampus.plugin.transport.android.iface.ITransportView;
import org.pocketcampus.plugin.transport.shared.Connection;
import org.pocketcampus.plugin.transport.shared.Location;
import org.pocketcampus.plugin.transport.shared.QueryConnectionsResult;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
/**
* The Main View of the Transport plugin, first displayed when accessing
* Transport.
*
* Displays the next departures for the destinations that the user set as
* preferred destinations
*
* @author Oriane <oriane.rodriguez@epfl.ch>
* @author Pascal <pascal.scheiben@epfl.ch>
* @author Florian <florian.laurent@epfl.ch>
*
*/
public class TransportMainView extends PluginView implements ITransportView {
/* MVC */
/** The plugin controller */
private TransportController mController;
/** The plugin model */
private TransportModel mModel;
/* Layout */
/** The main Layout */
private StandardTitledDoubleLayout mLayout;
/** The text displayed if the user has no destination set yet */
private TextView mText;
/** The listView to display next departures */
private RichLabeledListViewElement mDestinationsList;
/** The ListView to display next departures */
private ListView mListView;
/** The items */
private ArrayList<PCItem> items;
/** The adapter to contain the destinations displayed in the list */
private RichLabeledArrayAdapter mAdapter;
/** Displayed locations */
private HashMap<String, List<Connection>> mDisplayedLocations;
/* Preferences */
/** The pointer to access and modify preferences stored on the phone */
private SharedPreferences mDestPrefs;
/** Interface to modify values in SharedPreferences object */
private Editor mDestPrefsEditor;
/** The name under which the preferences are stored on the phone */
private static final String DEST_PREFS_NAME = "TransportDestinationsPrefs";
/* Labelers */
/** The labeler that says how to display a Location */
private ILabeler<Location> mLocationLabeler = new ILabeler<Location>() {
@Override
public String getLabel(Location dest) {
return dest.getName();
}
};
/** The labeler that says how to display a Location */
private IRichLabeler<Connection> mConnectionLabeler = new IRichLabeler<Connection>() {
@Override
public String getLabel(Connection dest) {
return "";
}
@Override
public String getTitle(Connection obj) {
return obj.getTo().getName();
}
@Override
public String getDescription(Connection obj) {
return timeString(obj.getDepartureTime());
}
@Override
public double getValue(Connection obj) {
return -1;
}
@Override
public Date getDate(Connection obj) {
return null;
}
};
/* Constants */
/** The EPFL Station ID */
private static final int EPFL_STATION_ID = 8501214;
/**
* Defines what the main controller is for this view.
*/
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return TransportController.class;
}
/**
* Called once the view is connected to the controller. If you don't
* implement <code>getMainControllerClass()</code> then the controller given
* here will simply be <code>null</code>.
*/
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
mController = (TransportController) controller;
mModel = (TransportModel) mController.getModel();
mDestPrefs = getSharedPreferences(DEST_PREFS_NAME, 0);
mLayout = new StandardTitledDoubleLayout(this);
mLayout.setTitle(getResources().getString(
R.string.transport_plugin_name));
mLayout.hideTitle();
setContentView(mLayout);
Map<String, Integer> prefs = (Map<String, Integer>) mDestPrefs.getAll();
if (prefs == null || prefs.isEmpty()) {
Log.d("TRANSPORT", "Prefs were null");
// mText = new TextView(this);
// mText.setText(getResources().getString(
// R.string.transport_main_no_destinations));
// mLayout.addFillerView(mText);
/** If no destinations are set, redirect to TransportTimeView */
Intent i = new Intent(this, TransportTimeView.class);
startActivity(i);
} else {
Set<String> set = prefs.keySet();
List<String> list = new ArrayList<String>();
for (String s : set) {
Log.d("TRANSPORT", s + " was in prefs");
list.add(s);
}
mController.getLocationsFromNames(list);
}
}
/**
* Called when this view is accessed after already having been initialized
* before
*/
// @Override
// protected void onRestart() {
// super.onRestart();
// Log.d("ACTIVITY", "onRestart");
// displayDestinations();
/**
* Main Transport Options menu contains access to the preferred destinations
* and the settings
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.transport_menu, menu);
return true;
}
/**
* Decides what happens when the options menu is opened and an option is
* chosen (what view to display)
*/
@Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
int id = item.getItemId();
if (id == R.id.transport_destinations) {
Intent i = new Intent(this, TransportTimeView.class);
startActivity(i);
} /*
* else if (id == R.id.transport_settings) { Log.d("TRANSPORT",
* "Settings");
*
* }
*/
return true;
}
/**
* Ask the server for connections in order to display the list of preferred
* destinations along with the next departures to go there
*/
private void displayDestinations() {
/** Button "Add Destination" */
ButtonElement b = new ButtonElement(this);
b.setId(1);
b.setText(getResources().getString(R.string.transport_add_destination));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
b.setLayoutParams(params);
b.setOnClickListener(new OnClickListener() {
/**
* Starts the TransportTimeView
*/
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
TransportTimeView.class);
startActivity(i);
}
});
mLayout.addFirstLayoutFillerView(b);
/** List of next departures */
List<Location> locations = mModel.getPreferredDestinations();
if (locations != null && !locations.isEmpty()) {
items = new ArrayList<PCItem>();
mDisplayedLocations = new HashMap<String, List<Connection>>();
for (Location loc : locations) {
Log.d("TRANSPORT", "Added section " + loc.getName());
mDisplayedLocations.put(loc.getName(),
new ArrayList<Connection>());
mController.nextDeparturesFromEPFL(loc.getName());
}
mListView = new ListView(this);
mLayout.removeSecondLayoutFillerView();
mLayout.addSecondLayoutFillerView(mListView);
setItemsToDisplay();
}
}
/**
* Called by the model when the data for the resulted connection has been
* updated
*/
@Override
public void connectionUpdated(QueryConnectionsResult result) {
Log.d("TRANSPORT", "Connection Updated (view)");
if (result != null) {
List<Connection> connections = result.getConnections();
if (connections != null && !connections.isEmpty()) {
int i = 0;
for (Connection c : connections) {
if(c != null) {
if (i < 3) {
i++;
Log.d("TRANSPORT",
"Added item " + timeString(c.getArrivalTime()));
List<Connection> list = mDisplayedLocations.get(c.getTo().getName());
if (list == null) {
mDisplayedLocations.put(c.getTo().getName(), new ArrayList<Connection>());
}
mDisplayedLocations.get(c.getTo().getName()).add(c);
}
}
}
setItemsToDisplay();
}
} else {
Log.d("TRANSPORT", "Bouuuuhouhou ! (view)");
}
}
/**
* Called by the model when the list of preferred destinations has been
* updated and refreshes the view
*/
@Override
public void destinationsUpdated() {
Log.d("TRANSPORT", "Destinations updated (view)");
displayDestinations();
}
/**
* Called by the model when the locations from the destinations names have
* been updated and display the next departures
*/
@Override
public void locationsFromNamesUpdated(List<Location> result) {
Log.d("TRANSPORT", "Locations from Names updated (view)");
displayDestinations();
}
/**
* Displays a toast when an error happens upon contacting the server
*/
@Override
public void networkErrorHappened() {
Log.d("TRANSPORT", "Network error (view)");
Toast toast = Toast.makeText(getApplicationContext(), "Network error!",
Toast.LENGTH_SHORT);
toast.show();
}
/**
* Not used in this view
*/
@Override
public void autoCompletedDestinationsUpdated() {
}
/**
* Returns a string representing the date by its hours and minutes
*
* @param millisec
* @return textDate The string representing the date as hours and minutes
*/
private String timeString(long millisec) {
String textDate = "";
Date now = new Date();
Date date = new Date();
date.setTime(millisec);
Date minutes = new Date();
minutes.setTime(date.getTime() - now.getTime());
textDate = "in " + (minutes.getHours() - 1) + " hours, "
+ minutes.getMinutes() + " minutes";
return textDate;
}
private void setItemsToDisplay() {
Set<String> set = mDisplayedLocations.keySet();
items = new ArrayList<PCItem>();
for (String l : set) {
if(!mDisplayedLocations.get(l).isEmpty()) {
items.add(new PCSectionItem(l));
int i = 0;
for (Connection c : mDisplayedLocations.get(l)) {
if (i < 3) {
i++;
items.add(new PCEntryItem(timeString(c.getArrivalTime()),
""));
}
}
}
}
PCEntryAdapter adapter = new PCEntryAdapter(this, items);
mListView.setAdapter(adapter);
mListView.invalidate();
}
}
|
package org.pocketcampus.plugin.transport.android;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.pocketcampus.R;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.core.PluginView;
import org.pocketcampus.android.platform.sdk.tracker.Tracker;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCEntryAdapter;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCEntryItem;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCItem;
import org.pocketcampus.android.platform.sdk.ui.PCSectionedList.PCSectionItem;
import org.pocketcampus.android.platform.sdk.ui.element.ButtonElement;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout;
import org.pocketcampus.plugin.transport.android.iface.ITransportView;
import org.pocketcampus.plugin.transport.android.ui.TransportTripDetailsDialog;
import org.pocketcampus.plugin.transport.android.utils.DestinationFormatter;
import org.pocketcampus.plugin.transport.android.utils.TransportFormatter;
import org.pocketcampus.plugin.transport.shared.QueryTripsResult;
import org.pocketcampus.plugin.transport.shared.TransportConnection;
import org.pocketcampus.plugin.transport.shared.TransportStation;
import org.pocketcampus.plugin.transport.shared.TransportTrip;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
/**
* The main view of the Transport plugin, first displayed when accessing
* Transport.
*
* Displays the next departures for the stations that the user has set as
* favorite stations. The favorite stations are stored in the android
* <code>SharedPreferences</code> and displayed each time the user accesses the
* Transport plugin. He can go to the <code>TransportEditView Activity</code> to
* delete them or add more stations.
*
* @author Oriane <oriane.rodriguez@epfl.ch>
* @author Pascal <pascal.scheiben@epfl.ch>
* @author Florian <florian.laurent@epfl.ch>
*
*/
public class TransportMainView extends PluginView implements ITransportView {
/* MVC */
/** The plugin controller. */
private TransportController mController;
/** The plugin model. */
private TransportModel mModel;
/* Layout */
/** The <code>ActionBar</code>. */
private ActionBar mActionBar;
/** Refresh action in the action bar. */
private RefreshAction mRefreshAction;
/** Change direction action in the action bar. */
private ChangeDirectionAction mDirectionAction;
/** The main Layout consisting of two inner layouts and a title. */
private StandardTitledLayout mLayout;
/** The list to display next departures. */
private ListView mListView;
/** The pointer to access and modify preferences stored on the phone. */
private SharedPreferences mDestPrefs;
/** Interface to modify values in the <code>SharedPreferences</code> object. */
private Editor mDestPrefsEditor;
/** The name under which the preferences are stored on the phone. */
private static final String DEST_PREFS_NAME = "TransportDestinationsPrefs";
/** A <code>Boolean</code> telling which direction is shown. */
private boolean mFromEpfl;
/** The name of the EPFL station. */
private final String M_EPFL_STATION = "EPFL";
/**
* Defines what the main controller is for this view.
*/
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return TransportController.class;
}
/**
* Called when first displaying the view. Retrieves the model and the
* controller and calls the methods setting up the layout, the action bar
* and the stations with next departures.
*/
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
// Tracker
Tracker.getInstance().trackPageView("transport");
mController = (TransportController) controller;
mModel = (TransportModel) mController.getModel();
mDestPrefs = getSharedPreferences(DEST_PREFS_NAME, 0);
mDestPrefsEditor = mDestPrefs.edit();
mFromEpfl = true;
// Set up the main layout and the list view
setUpLayout();
setUpListView();
// Set up the action bar with a button
setUpActionBar();
// Set up destinations that will be displayed
mModel.freeDestinations();
setUpDestinations();
}
/**
* Called when this view is accessed after already having been initialized
* before. Refreshes the next departures.
*/
@Override
protected void onRestart() {
super.onRestart();
mModel.freeDestinations();
mLayout.hideText();
setUpDestinations();
}
/**
* Main Transport Options Menu containing access to the favorite stations.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.transport_menu, menu);
return true;
}
/**
* Decides what happens when the Options Menu is opened and an option is
* chosen (which view to display).
*/
@Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
int id = item.getItemId();
if (id == R.id.transport_stations) {
mFromEpfl = true;
Intent i = new Intent(this, TransportEditView.class);
startActivity(i);
}
return true;
}
/**
* Sets up the main layout of the plugin.
*/
private void setUpLayout() {
// Main layout
mLayout = new StandardTitledLayout(this);
mLayout.setTitle(getResources().getString(
R.string.transport_plugin_name));
mLayout.hideTitle();
setContentView(mLayout);
}
/**
* Sets up the list of stations found in the <code>SharedPreferences</code>
* along with their next departures.
*/
private void setUpListView() {
// Creates the list view and sets its click listener
mListView = new ListView(this);
mListView.setId(1234);
mListView.setOnItemClickListener(new OnItemClickListener() {
/**
* When the user clicks on a departure, shows a dialog with
* connections details about the whole trip.
*/
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Find the name and departure time as a string
String txt = ((PCEntryItem) ((ListView) arg0)
.getItemAtPosition(arg2)).id;
// Separate into name and departure time
String[] s = txt.split(":");
String name = s[0];
long depTime = Long.valueOf(s[1]);
long arrTime = Long.valueOf(s[2]);
// Find the destination in the ones from the model
List<TransportTrip> trips = mModel.getFavoriteStations().get(
name);
for (TransportTrip trip : trips) {
if (trip.getDepartureTime() == depTime
&& trip.getArrivalTime() == arrTime) {
TransportTripDetailsDialog dialog = new TransportTripDetailsDialog(
TransportMainView.this, trip);
// Tracker
Tracker.getInstance().trackPageView(
"transport/dialog/" + trip.getFrom().getName()
+ "/" + trip.getTo().getName());
dialog.show();
break;
}
}
}
});
// Adds it to the layout
mLayout.addFillerView(mListView);
}
/**
* Retrieves the action bar and adds a refresh action to it.
*/
private void setUpActionBar() {
mActionBar = getActionBar();
if (mActionBar != null) {
mRefreshAction = new RefreshAction();
mActionBar.addAction(mRefreshAction, 0);
}
}
/**
* Sets up which stations have to be displayed. First checks if there are
* stations in the <code>SharedPreferences</code>. If yes, asks for next
* departures, and if not, displays a button to let the user add a station.
*/
@SuppressWarnings("unchecked")
private void setUpDestinations() {
Map<String, Integer> prefs = (Map<String, Integer>) mDestPrefs.getAll();
// If no stations set, display a button that redirects to the add
// view of the plugin
if (prefs == null || prefs.isEmpty()) {
if (mActionBar == null) {
mActionBar = getActionBar();
}
if (mDirectionAction != null) {
mActionBar.removeAction(mDirectionAction);
}
ButtonElement addButton = new ButtonElement(this, getResources()
.getString(R.string.transport_add_station));
LayoutParams l = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
l.addRule(RelativeLayout.CENTER_IN_PARENT);
addButton.setLayoutParams(l);
addButton.setOnClickListener(new OnClickListener() {
/**
* When the user clicks on the add button, opens the
* <code>TransportAddView Activity</code>.
*/
@Override
public void onClick(View v) {
// Tracker
Tracker.getInstance().trackPageView("transport/button/add");
mFromEpfl = true;
Intent add = new Intent(getApplicationContext(),
TransportAddView.class);
startActivity(add);
}
});
mLayout.removeFillerView();
mLayout.addFillerView(addButton);
} else {
// If station(s) are in the shared preferences, remove the
// button of the main layout and adds the list view
mLayout.removeFillerView();
mLayout.addFillerView(mListView);
Set<String> set = prefs.keySet();
List<String> list = new ArrayList<String>();
for (String s : set) {
list.add(s);
}
// Binds the names with actual TransportStation objects
mController.getStationsFromNames(list);
}
}
/**
* Asks the server for connections in order to display the list of favorite
* stations along with the next departures.
*/
private void displayDestinations() {
mLayout.hideText();
// Gets the user's preferred destinations from the model
HashMap<String, List<TransportTrip>> locations = mModel
.getFavoriteStations();
if (locations != null && !locations.isEmpty()) {
// The user wants to leave EPFL
if (mFromEpfl) {
for (String loc : locations.keySet()) {
mController.nextDepartures(M_EPFL_STATION, loc);
}
// The user wants to go to EPFL
} else {
for (String loc : locations.keySet()) {
mController.nextDepartures(loc, M_EPFL_STATION);
}
}
}
}
/**
* Called by the model when the data for the resulted connections has been
* updated.
*/
@Override
public void connectionsUpdated(QueryTripsResult result) {
if (mActionBar != null) {
mActionBar = getActionBar();
}
if (mDirectionAction == null) {
mDirectionAction = new ChangeDirectionAction();
}
mActionBar.removeAction(mDirectionAction);
mActionBar.addAction(mDirectionAction, 0);
HashMap<String, List<TransportTrip>> mDisplayedLocations = mModel
.getFavoriteStations();
// In case the button is still here
mLayout.removeFillerView();
mLayout.addFillerView(mListView);
// Fill in the list view with the next departures
setItemsToDisplay(mDisplayedLocations);
}
/**
* Called by the model when the list of favorite stations has been updated
* and refreshes the view.
*/
@Override
public void favoriteStationsUpdated() {
displayDestinations();
}
/**
* Called by the model when the stations from the names have been updated
* and displays the next departures.
*/
@Override
public void stationsFromNamesUpdated(List<TransportStation> result) {
displayDestinations();
}
/**
* Displays a message when an error happens upon contacting the server.
*/
@Override
public void networkErrorHappened() {
Log.d("TRANSPORT", "ERROR");
// Tracker
Tracker.getInstance().trackPageView("transport/network_error");
if (!mDestPrefs.getAll().isEmpty()) {
Log.d("TRANSPORT", "EMPTY");
mLayout.removeFillerView();
mLayout.setText(getResources().getString(
R.string.transport_network_error));
}
}
/**
* Called when connections are received from the server. Creates the items
* to be displayed (Station name with time until departure) and updates the
* shared preferences. (This is not done before getting the result, to make
* sure we store the correct station name in the preferences).
*/
private void setItemsToDisplay(
HashMap<String, List<TransportTrip>> mDisplayedLocations) {
Set<String> set = mDisplayedLocations.keySet();
ArrayList<PCItem> items = new ArrayList<PCItem>();
for (String l : set) {
if (!mDisplayedLocations.get(l).isEmpty()) {
String from = DestinationFormatter
.getNiceName(mDisplayedLocations.get(l).get(0)
.getFrom());
String to = DestinationFormatter
.getNiceName(mDisplayedLocations.get(l).get(0).getTo());
items.add(new PCSectionItem(from + " - " + to));
int i = 0;
for (TransportTrip c : mDisplayedLocations.get(l)) {
if (i < 3) {
Date dep = new Date();
dep.setTime(c.getDepartureTime());
Date now = new Date();
if (dep.after(now)) {
i++;
// Updates the shared preferences
if (mFromEpfl) {
if (!c.getTo().getName()
.equals("Ecublens VD, EPFL")) {
mDestPrefsEditor.putInt(
c.getTo().getName(), c.getTo()
.getId());
mDestPrefsEditor.commit();
}
} else {
if (!c.getFrom().getName()
.equals("Ecublens VD, EPFL")) {
mDestPrefsEditor.putInt(c.getFrom()
.getName(), c.getFrom().getId());
mDestPrefsEditor.commit();
}
}
// String representing the type of transport
String logo = "";
for (TransportConnection p : c.parts) {
if (!p.foot && p.line != null) {
logo = p.line.getName();
break;
}
}
logo = TransportFormatter.getNiceName(logo);
if (mFromEpfl) {
PCEntryItem entry = new PCEntryItem(
timeString(c.getDepartureTime()), logo,
c.getTo().getName() + ":"
+ c.getDepartureTime() + ":"
+ c.getArrivalTime() + ":"
+ c.getId());
items.add(entry);
} else {
PCEntryItem entry = new PCEntryItem(
timeString(c.getDepartureTime()), logo,
c.getFrom().getName() + ":"
+ c.getDepartureTime() + ":"
+ c.getArrivalTime() + ":"
+ c.getId());
items.add(entry);
}
// Add this departure
}
}
}
}
}
PCEntryAdapter adapter = new PCEntryAdapter(this, items);
// Update the list view
mListView.setAdapter(adapter);
mListView.invalidate();
}
/**
* Takes the time before next departures in milliseconds and transforms it
* to a text in the form : "In x hour(s), y minute(s)."
*
* @param milliseconds
* The time until the next departure.
* @return s The <code>String</code> representation of the time left until
* the departure.
*/
private String timeString(long milliseconds) {
String s = getResources().getString(R.string.transport_in);
Date now = new Date();
Date then = new Date();
then.setTime(milliseconds);
long diff = then.getTime() - now.getTime();
Date timeTillDeparture = new Date();
timeTillDeparture.setTime(diff);
diff = diff / 1000; // seconds
int minutes = (int) diff / 60; // minutes
int hours = (int) diff / 3660; // hours
if (hours > 0) {
if (hours == 1) {
s = s.concat(" " + hours + " "
+ getResources().getString(R.string.transport_hour)
+ ",");
} else {
s = s.concat(" " + hours + " "
+ getResources().getString(R.string.transport_hours)
+ ",");
}
}
while (minutes > 60) {
minutes = minutes - 60;
}
if (minutes > 0) {
if (minutes == 1) {
s = s.concat(" " + minutes + " "
+ getResources().getString(R.string.transport_minute));
} else {
s = s.concat(" " + minutes + " "
+ getResources().getString(R.string.transport_minutes));
}
}
if (hours == 0 && minutes == 0) {
s = getResources().getString(R.string.transport_departure_now);
}
return s;
}
/**
* Refreshes the next departures when clicking on the action bar refresh
* button.
*
* @author Oriane <oriane.rodriguez@epfl.ch>
*
*/
private class RefreshAction implements Action {
/**
* Class constructor which doesn't do anything.
*/
RefreshAction() {
}
/**
* Returns the resource for the icon of the button in the action bar.
*/
@Override
public int getDrawable() {
return R.drawable.sdk_action_bar_refresh;
}
/**
* Refreshes the departures when the user clicks on the button in the
* action bar.
*/
@Override
public void performAction(View view) {
// Tracker
Tracker.getInstance().trackPageView("transport/refresh");
mLayout.removeFillerView();
// mLayout.addFillerView(mListView);
mModel.freeConnections();
if (mModel.getFavoriteStations() == null
|| mModel.getFavoriteStations().isEmpty()) {
setUpDestinations();
} else {
displayDestinations();
}
}
}
/**
* Change the direction of the trips when clicking on the action bar change
* direction button.
*
* @author Oriane <oriane.rodriguez@epfl.ch>
*
*/
private class ChangeDirectionAction implements Action {
/**
* The constructor which doesn't do anything
*/
ChangeDirectionAction() {
}
/**
* Returns the resource for the icon of the button in the action bar.
*/
@Override
public int getDrawable() {
return R.drawable.transport_action_bar_change_direction;
}
/**
* Changes direction and refreshes the departures when the user clicks
* on the button in the action bar.
*/
@Override
public void performAction(View view) {
// Tracker
Tracker.getInstance().trackPageView("transport/changed/direction");
if (mFromEpfl) {
mFromEpfl = false;
} else {
mFromEpfl = true;
}
mModel.freeConnections();
if (mModel.getFavoriteStations() == null
|| mModel.getFavoriteStations().isEmpty()) {
setUpDestinations();
} else {
displayDestinations();
}
}
}
/**
* Not used in this view.
*/
@Override
public void autoCompletedStationsUpdated() {
}
}
|
package com.sometrik.framework;
import java.util.ArrayList;
import com.sometrik.framework.NativeCommand.Selector;
import android.graphics.Bitmap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
public class FWPager extends ViewPager implements NativeCommandHandler {
private FrameWork frame;
private FWPagerAdapter adapter;
ViewStyleManager normalStyle, activeStyle, currentStyle, linkStyle;
private DetailOnPageChangeListener pageChangeListener;
float x1 = 0, x2, y1 = 0, y2, dx, dy;
public FWPager(final FrameWork frame) {
super(frame);
this.frame = frame;
final float scale = getContext().getResources().getDisplayMetrics().density;
this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true);
this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
this.linkStyle = new ViewStyleManager(frame.bitmapCache, scale, false);
adapter = new FWPagerAdapter();
setAdapter(adapter);
pageChangeListener = new DetailOnPageChangeListener();
this.setOnPageChangeListener(pageChangeListener);
this.setNestedScrollingEnabled(false);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (getChildCount() == 0) {
return false;
}
// getParent().requestDisallowInterceptTouchEvent(true);
return super.onTouchEvent(ev);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
View currentView = adapter.currentItem;
if (currentView != null) {
currentView.measure(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(currentView.getMeasuredHeight(), View.MeasureSpec.EXACTLY));
return;
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
public void addView(View view) {
super.addView(view);
if (view instanceof NativeCommandHandler) {
System.out.println("Pager adding view. Applying styles");
((NativeCommandHandler)view).applyStyles();
System.out.println("Pager adding view. styles done");
}
}
@Override
public void onScreenOrientationChange(boolean isLandscape) {
// TODO Auto-generated method stub
}
@Override
public void addChild(View view) {
adapter.addToList(view);
}
public void removeViewFromPager(int childId) {
System.out.println("FWPager removeView " + childId);
adapter.removeFromList(childId);
}
public void reorderChild(int childId, int newPosition) {
adapter.reorderView(childId, newPosition);
setAdapter(adapter);
setCurrentItem(pageChangeListener.currentPage);
invalidate();
}
@Override
public void addOption(int optionId, String text) {
// TODO Auto-generated method stub
}
@Override
public void addColumn(String text, int columnType) {
// TODO Auto-generated method stub
}
@Override
public void addData(String text, int row, int column, int sheet) {
// TODO Auto-generated method stub
}
@Override
public void setValue(String v) {
// TODO Auto-generated method stub
}
@Override
public void setBitmap(Bitmap bitmap) {
// TODO Auto-generated method stub
}
@Override
public void addImageUrl(String url, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void setValue(int v) {
setCurrentItem(v);
}
@Override
public void reshape(int value, int size) {
// TODO Auto-generated method stub
}
@Override
public void reshape(int size) {
// TODO Auto-generated method stub
}
@Override
public void setViewVisibility(boolean visible) {
// TODO Auto-generated method stub
}
@Override
public void setStyle(Selector selector, String key, String value) {
if (key.equals("page-margin")) {
this.setPageMargin(Integer.parseInt(value));
return;
}
if (selector == Selector.NORMAL) {
normalStyle.setStyle(key, value);
} else if (selector == Selector.ACTIVE) {
activeStyle.setStyle(key, value);
} else if (selector == Selector.LINK) {
linkStyle.setStyle(key, value);
}
}
@Override
public void applyStyles() {
currentStyle.apply(this);
linkStyle.applyLinkColor(this);
}
@Override
public void setError(boolean hasError, String errorText) {
// TODO Auto-generated method stub
}
@Override
public void clear() {
System.out.println("FWPager clear");
adapter.viewList = new ArrayList<View>();
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void deinitialize() {
// TODO Auto-generated method stub
}
@Override
public int getElementId() {
return getId();
}
private class FWPagerAdapter extends PagerAdapter {
private ArrayList<View> viewList;
private View currentItem;
public FWPagerAdapter() {
viewList = new ArrayList<View>();
}
public void removeFromList(int childId) {
for (int i = 0; i < viewList.size(); i++) {
if (viewList.get(i).getId() == childId) {
System.out.println("FWPager adapter removed " + i);
viewList.remove(i);
break;
}
}
notifyDataSetChanged();
}
public void addToList(View view) {
viewList.add(view);
notifyDataSetChanged();
}
public void addToList(View view, int position) {
if (position < viewList.size()) {
viewList.add(position, view);
} else {
viewList.add(view);
}
notifyDataSetChanged();
}
public void reorderView(int viewId, int newPosition) {
for (int i = 0; i < viewList.size(); i++) {
View view = viewList.get(i);
if (view.getId() == viewId) {
viewList.remove(view);
if (newPosition < viewList.size()) {
viewList.add(newPosition, view);
} else {
viewList.add(view);
}
System.out.println("View " + view.getId() + " moved to " + newPosition);
break;
}
}
notifyDataSetChanged();
}
@Override
public int getCount() {
System.out.println("adapter getCount " + viewList.size());
return viewList.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object ) {
super.setPrimaryItem(container, position, object);
if (object instanceof View) {
currentItem = (View) object;
System.out.println("Primary item: " + currentItem.getId() + " position: " + position);
}
}
@Override
public void startUpdate(ViewGroup container) {
super.startUpdate(container);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
System.out.println("instantiateItem position: " + position + " viewList size: " + viewList.size());
container.addView(viewList.get(position));
return viewList.get(position);
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
private int currentPage;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
System.out.println("Pager page scrolled " + positionOffset);
// getParent().requestDisallowInterceptTouchEvent(true);
}
@Override
public void onPageSelected(int position) {
System.out.println("Pager change page " + getElementId());
frame.sendNativeValueEvent(getElementId(), position, 0);
currentPage = position;
}
public final int getCurrentPage() {
return currentPage;
}
}
}
|
package com.artifex.mupdf;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ViewSwitcher;
class SearchTaskResult {
public final String txt;
public final int pageNumber;
public final RectF searchBoxes[];
static private SearchTaskResult singleton;
SearchTaskResult(String _txt, int _pageNumber, RectF _searchBoxes[]) {
txt = _txt;
pageNumber = _pageNumber;
searchBoxes = _searchBoxes;
}
static public SearchTaskResult get() {
return singleton;
}
static public void set(SearchTaskResult r) {
singleton = r;
}
}
class ProgressDialogX extends ProgressDialog {
public ProgressDialogX(Context context) {
super(context);
}
private boolean mCancelled = false;
public boolean isCancelled() {
return mCancelled;
}
@Override
public void cancel() {
mCancelled = true;
super.cancel();
}
}
public class MuPDFActivity extends Activity
{
/* The core rendering instance */
private enum LinkState {DEFAULT, HIGHLIGHT, INHIBIT};
private final int TAP_PAGE_MARGIN = 5;
private static final int SEARCH_PROGRESS_DELAY = 200;
private MuPDFCore core;
private String mFileName;
private ReaderView mDocView;
private View mButtonsView;
private boolean mButtonsVisible;
private EditText mPasswordView;
private TextView mFilenameView;
private SeekBar mPageSlider;
private TextView mPageNumberView;
private ImageButton mSearchButton;
private ImageButton mCancelButton;
private ImageButton mOutlineButton;
private ViewSwitcher mTopBarSwitcher;
// XXX private ImageButton mLinkButton;
private boolean mTopBarIsSearch;
private ImageButton mSearchBack;
private ImageButton mSearchFwd;
private EditText mSearchText;
private SafeAsyncTask<Integer,Integer,SearchTaskResult> mSearchTask;
//private SearchTaskResult mSearchTaskResult;
private AlertDialog.Builder mAlertBuilder;
private LinkState mLinkState = LinkState.DEFAULT;
private final Handler mHandler = new Handler();
private MuPDFCore openFile(String path)
{
int lastSlashPos = path.lastIndexOf('/');
mFileName = new String(lastSlashPos == -1
? path
: path.substring(lastSlashPos+1));
System.out.println("Trying to open "+path);
try
{
core = new MuPDFCore(path);
// New file: drop the old outline data
OutlineActivityData.set(null);
}
catch (Exception e)
{
System.out.println(e);
return null;
}
return core;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mAlertBuilder = new AlertDialog.Builder(this);
if (core == null) {
core = (MuPDFCore)getLastNonConfigurationInstance();
if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
mFileName = savedInstanceState.getString("FileName");
}
}
if (core == null) {
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
if (uri.toString().startsWith("content://media/external/file")) {
// Handle view requests from the Transformer Prime's file manager
// Hopefully other file managers will use this same scheme, if not
// using explicit paths.
Cursor cursor = getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
if (cursor.moveToFirst()) {
uri = Uri.parse(cursor.getString(0));
}
}
core = openFile(Uri.decode(uri.getEncodedPath()));
}
if (core != null && core.needsPassword()) {
requestPassword(savedInstanceState);
return;
}
}
if (core == null)
{
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.open_failed);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
createUI(savedInstanceState);
}
public void requestPassword(final Bundle savedInstanceState) {
mPasswordView = new EditText(this);
mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
mPasswordView.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog alert = mAlertBuilder.create();
alert.setTitle(R.string.enter_password);
alert.setView(mPasswordView);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (core.authenticatePassword(mPasswordView.getText().toString())) {
createUI(savedInstanceState);
} else {
requestPassword(savedInstanceState);
}
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
public void createUI(Bundle savedInstanceState) {
if (core == null)
return;
// Now create the UI.
// First create the document view making use of the ReaderView's internal
// gesture recognition
mDocView = new ReaderView(this) {
private boolean showButtonsDisabled;
public boolean onSingleTapUp(MotionEvent e) {
if (e.getX() < super.getWidth()/TAP_PAGE_MARGIN) {
super.moveToPrevious();
} else if (e.getX() > super.getWidth()*(TAP_PAGE_MARGIN-1)/TAP_PAGE_MARGIN) {
super.moveToNext();
} else if (!showButtonsDisabled) {
int linkPage = -1;
if (mLinkState != LinkState.INHIBIT) {
MuPDFPageView pageView = (MuPDFPageView) mDocView.getDisplayedView();
if (pageView != null) {
// XXX linkPage = pageView.hitLinkPage(e.getX(), e.getY());
}
}
if (linkPage != -1) {
mDocView.setDisplayedViewIndex(linkPage);
} else {
if (!mButtonsVisible) {
showButtons();
} else {
hideButtons();
}
}
}
return super.onSingleTapUp(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (!showButtonsDisabled)
hideButtons();
return super.onScroll(e1, e2, distanceX, distanceY);
}
public boolean onScaleBegin(ScaleGestureDetector d) {
// Disabled showing the buttons until next touch.
// Not sure why this is needed, but without it
// pinch zoom can make the buttons appear
showButtonsDisabled = true;
return super.onScaleBegin(d);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
showButtonsDisabled = false;
return super.onTouchEvent(event);
}
protected void onChildSetup(int i, View v) {
if (SearchTaskResult.get() != null && SearchTaskResult.get().pageNumber == i)
((PageView)v).setSearchBoxes(SearchTaskResult.get().searchBoxes);
else
((PageView)v).setSearchBoxes(null);
((PageView)v).setLinkHighlighting(mLinkState == LinkState.HIGHLIGHT);
}
protected void onMoveToChild(int i) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d/%d", i+1, core.countPages()));
mPageSlider.setMax(core.countPages()-1);
mPageSlider.setProgress(i);
if (SearchTaskResult.get() != null && SearchTaskResult.get().pageNumber != i) {
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
}
protected void onSettle(View v) {
// When the layout has settled ask the page to render
// in HQ
((PageView)v).addHq();
}
protected void onUnsettle(View v) {
// When something changes making the previous settled view
// no longer appropriate, tell the page to remove HQ
((PageView)v).removeHq();
}
@Override
protected void onNotInUse(View v) {
((PageView)v).releaseResources();
}
};
mDocView.setAdapter(new MuPDFPageAdapter(this, core));
// Make the buttons overlay, and store all its
// controls in variables
makeButtonsView();
// Set the file-name text
mFilenameView.setText(mFileName);
// Activate the seekbar
mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
mDocView.setDisplayedViewIndex(seekBar.getProgress());
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePageNumView(progress);
}
});
// Activate the search-preparing button
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOn();
}
});
mCancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchModeOff();
}
});
// Search invoking buttons are disabled while there is no text specified
mSearchBack.setEnabled(false);
mSearchFwd.setEnabled(false);
// React to interaction with the text widget
mSearchText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
boolean haveText = s.toString().length() > 0;
mSearchBack.setEnabled(haveText);
mSearchFwd.setEnabled(haveText);
// Remove any previous search results
if (SearchTaskResult.get() != null && !mSearchText.getText().toString().equals(SearchTaskResult.get().txt)) {
SearchTaskResult.set(null);
mDocView.resetupChildren();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
//React to Done button on keyboard
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE)
search(1);
return false;
}
});
mSearchText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
search(1);
return false;
}
});
// Activate search invoking buttons
mSearchBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
search(-1);
}
});
mSearchFwd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
search(1);
}
});
/* XXX
mLinkButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(mLinkState) {
case DEFAULT:
mLinkState = LinkState.HIGHLIGHT;
mLinkButton.setImageResource(R.drawable.ic_hl_link);
//Inform pages of the change.
mDocView.resetupChildren();
break;
case HIGHLIGHT:
mLinkState = LinkState.INHIBIT;
mLinkButton.setImageResource(R.drawable.ic_nolink);
//Inform pages of the change.
mDocView.resetupChildren();
break;
case INHIBIT:
mLinkState = LinkState.DEFAULT;
mLinkButton.setImageResource(R.drawable.ic_link);
break;
}
}
});
*/
if (core.hasOutline()) {
mOutlineButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OutlineItem outline[] = core.getOutline();
if (outline != null) {
OutlineActivityData.get().items = outline;
Intent intent = new Intent(MuPDFActivity.this, OutlineActivity.class);
startActivityForResult(intent, 0);
}
}
});
} else {
mOutlineButton.setVisibility(View.GONE);
}
// Reenstate last state if it was recorded
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
mDocView.setDisplayedViewIndex(prefs.getInt("page"+mFileName, 0));
if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false))
showButtons();
if(savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false))
searchModeOn();
// Stick the document view and the buttons overlay into a parent view
RelativeLayout layout = new RelativeLayout(this);
layout.addView(mDocView);
layout.addView(mButtonsView);
layout.setBackgroundResource(R.drawable.tiled_background);
//layout.setBackgroundResource(R.color.canvas);
setContentView(layout);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode >= 0)
mDocView.setDisplayedViewIndex(resultCode);
super.onActivityResult(requestCode, resultCode, data);
}
public Object onRetainNonConfigurationInstance()
{
MuPDFCore mycore = core;
core = null;
return mycore;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFileName != null && mDocView != null) {
outState.putString("FileName", mFileName);
// Store current page in the prefs against the file name,
// so that we can pick it up each time the file is loaded
// Other info is needed only for screen-orientation change,
// so it can go in the bundle
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
if (!mButtonsVisible)
outState.putBoolean("ButtonsHidden", true);
if (mTopBarIsSearch)
outState.putBoolean("SearchMode", true);
}
@Override
protected void onPause() {
super.onPause();
killSearch();
if (mFileName != null && mDocView != null) {
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("page"+mFileName, mDocView.getDisplayedViewIndex());
edit.commit();
}
}
public void onDestroy()
{
if (core != null)
core.onDestroy();
core = null;
super.onDestroy();
}
void showButtons() {
if (core == null)
return;
if (!mButtonsVisible) {
mButtonsVisible = true;
// Update page number text and slider
int index = mDocView.getDisplayedViewIndex();
updatePageNumView(index);
mPageSlider.setMax(core.countPages()-1);
mPageSlider.setProgress(index);
if (mTopBarIsSearch) {
mSearchText.requestFocus();
showKeyboard();
}
Animation anim = new TranslateAnimation(0, 0, -mTopBarSwitcher.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mTopBarSwitcher.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, mPageSlider.getHeight(), 0);
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageSlider.setVisibility(View.VISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageNumberView.setVisibility(View.VISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void hideButtons() {
if (mButtonsVisible) {
mButtonsVisible = false;
hideKeyboard();
Animation anim = new TranslateAnimation(0, 0, 0, -mTopBarSwitcher.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mTopBarSwitcher.setVisibility(View.INVISIBLE);
}
});
mTopBarSwitcher.startAnimation(anim);
anim = new TranslateAnimation(0, 0, 0, mPageSlider.getHeight());
anim.setDuration(200);
anim.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
mPageNumberView.setVisibility(View.INVISIBLE);
}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
mPageSlider.setVisibility(View.INVISIBLE);
}
});
mPageSlider.startAnimation(anim);
}
}
void searchModeOn() {
if (!mTopBarIsSearch) {
mTopBarIsSearch = true;
//Focus on EditTextWidget
mSearchText.requestFocus();
showKeyboard();
mTopBarSwitcher.showNext();
}
}
void searchModeOff() {
if (mTopBarIsSearch) {
mTopBarIsSearch = false;
hideKeyboard();
mTopBarSwitcher.showPrevious();
SearchTaskResult.set(null);
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
}
}
void updatePageNumView(int index) {
if (core == null)
return;
mPageNumberView.setText(String.format("%d/%d", index+1, core.countPages()));
}
void makeButtonsView() {
mButtonsView = getLayoutInflater().inflate(R.layout.buttons,null);
mFilenameView = (TextView)mButtonsView.findViewById(R.id.docNameText);
mPageSlider = (SeekBar)mButtonsView.findViewById(R.id.pageSlider);
mPageNumberView = (TextView)mButtonsView.findViewById(R.id.pageNumber);
mSearchButton = (ImageButton)mButtonsView.findViewById(R.id.searchButton);
mCancelButton = (ImageButton)mButtonsView.findViewById(R.id.cancel);
mOutlineButton = (ImageButton)mButtonsView.findViewById(R.id.outlineButton);
mTopBarSwitcher = (ViewSwitcher)mButtonsView.findViewById(R.id.switcher);
mSearchBack = (ImageButton)mButtonsView.findViewById(R.id.searchBack);
mSearchFwd = (ImageButton)mButtonsView.findViewById(R.id.searchForward);
mSearchText = (EditText)mButtonsView.findViewById(R.id.searchText);
// XXX mLinkButton = (ImageButton)mButtonsView.findViewById(R.id.linkButton);
mTopBarSwitcher.setVisibility(View.INVISIBLE);
mPageNumberView.setVisibility(View.INVISIBLE);
mPageSlider.setVisibility(View.INVISIBLE);
}
void showKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(mSearchText, 0);
}
void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
}
void killSearch() {
if (mSearchTask != null) {
mSearchTask.cancel(true);
mSearchTask = null;
}
}
void search(int direction) {
hideKeyboard();
if (core == null)
return;
killSearch();
final ProgressDialogX progressDialog = new ProgressDialogX(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle(getString(R.string.searching_));
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
killSearch();
}
});
progressDialog.setMax(core.countPages());
mSearchTask = new SafeAsyncTask<Integer,Integer,SearchTaskResult>() {
@Override
protected SearchTaskResult doInBackground(Integer... params) {
int index;
if (SearchTaskResult.get() == null)
index = mDocView.getDisplayedViewIndex();
else
index = SearchTaskResult.get().pageNumber + params[0].intValue();
while (0 <= index && index < core.countPages() && !isCancelled()) {
publishProgress(index);
RectF searchHits[] = core.searchPage(index, mSearchText.getText().toString());
if (searchHits != null && searchHits.length > 0)
return new SearchTaskResult(mSearchText.getText().toString(), index, searchHits);
index += params[0].intValue();
}
return null;
}
@Override
protected void onPostExecute(SearchTaskResult result) {
progressDialog.cancel();
if (result != null) {
// Ask the ReaderView to move to the resulting page
mDocView.setDisplayedViewIndex(result.pageNumber);
SearchTaskResult.set(result);
// Make the ReaderView act on the change to mSearchTaskResult
// via overridden onChildSetup method.
mDocView.resetupChildren();
} else {
mAlertBuilder.setTitle(R.string.text_not_found);
AlertDialog alert = mAlertBuilder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
(DialogInterface.OnClickListener)null);
alert.show();
}
}
@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.cancel();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0].intValue());
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mHandler.postDelayed(new Runnable() {
public void run() {
if (!progressDialog.isCancelled())
progressDialog.show();
}
}, SEARCH_PROGRESS_DELAY);
}
};
mSearchTask.safeExecute(new Integer(direction));
}
@Override
public boolean onSearchRequested() {
showButtons();
searchModeOn();
return super.onSearchRequested();
}
}
|
package com.mercadopago.android.px.internal.features.providers;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.mercadopago.android.px.BuildConfig;
import com.mercadopago.android.px.R;
import com.mercadopago.android.px.internal.callbacks.TaggedCallback;
import com.mercadopago.android.px.internal.datasource.MercadoPagoServicesAdapter;
import com.mercadopago.android.px.internal.di.Session;
import com.mercadopago.android.px.internal.tracker.MPTrackingContext;
import com.mercadopago.android.px.model.BankDeal;
import com.mercadopago.android.px.model.CardToken;
import com.mercadopago.android.px.model.IdentificationType;
import com.mercadopago.android.px.model.Installment;
import com.mercadopago.android.px.model.Issuer;
import com.mercadopago.android.px.model.Token;
import java.math.BigDecimal;
import java.util.List;
public class GuessingCardProviderImpl implements GuessingCardProvider {
private final Context context;
private final MercadoPagoServicesAdapter mercadoPago;
private final String publicKey;
private MPTrackingContext trackingContext;
public GuessingCardProviderImpl(@NonNull final Context context) {
this.context = context;
final Session session = Session.getSession(context);
publicKey = session.getConfigurationModule().getPaymentSettings().getPublicKey();
mercadoPago = session.getMercadoPagoServiceAdapter();
}
@Override
public MPTrackingContext getTrackingContext() {
if (trackingContext == null) {
trackingContext = new MPTrackingContext.Builder(context, publicKey)
.setVersion(BuildConfig.VERSION_NAME)
.build();
}
return trackingContext;
}
@Override
public void createTokenAsync(final CardToken cardToken, final TaggedCallback<Token> taggedCallback) {
mercadoPago.createToken(cardToken, taggedCallback);
}
@Override
public void getIssuersAsync(final String paymentMethodId, final String bin,
final TaggedCallback<List<Issuer>> taggedCallback) {
mercadoPago.getIssuers(paymentMethodId, bin, taggedCallback);
}
@Override
public void getInstallmentsAsync(final String bin,
final BigDecimal amount,
final Long issuerId,
final String paymentMethodId,
@Nullable final Integer differentialPricingId,
final TaggedCallback<List<Installment>> taggedCallback) {
mercadoPago.getInstallments(bin, amount, issuerId, paymentMethodId, differentialPricingId, taggedCallback);
}
@Override
public void getIdentificationTypesAsync(final TaggedCallback<List<IdentificationType>> taggedCallback) {
mercadoPago.getIdentificationTypes(taggedCallback);
}
@Override
public void getBankDealsAsync(final TaggedCallback<List<BankDeal>> taggedCallback) {
mercadoPago.getBankDeals(taggedCallback);
}
@Override
public String getMissingInstallmentsForIssuerErrorMessage() {
return context.getString(R.string.px_error_message_missing_installment_for_issuer);
}
@Override
public String getMultipleInstallmentsForIssuerErrorMessage() {
return context.getString(R.string.px_error_message_multiple_installments_for_issuer);
}
@Override
public String getMissingPayerCostsErrorMessage() {
return context.getString(R.string.px_error_message_missing_payer_cost);
}
@Override
public String getMissingIdentificationTypesErrorMessage() {
return context.getString(R.string.px_error_message_missing_identification_types);
}
@Override
public String getInvalidIdentificationNumberErrorMessage() {
return context.getString(R.string.px_invalid_identification_number);
}
@Override
public String getInvalidExpiryDateErrorMessage() {
return context.getString(R.string.px_invalid_expiry_date);
}
@Override
public String getInvalidEmptyNameErrorMessage() {
return context.getString(R.string.px_invalid_empty_name);
}
@Override
public String getSettingNotFoundForBinErrorMessage() {
return context.getString(R.string.px_error_message_missing_setting_for_bin);
}
@Override
public String getInvalidFieldErrorMessage() {
return context.getString(R.string.px_invalid_field);
}
}
|
package imagej;
// OTHER WAY
//import java.util.ArrayList;
import imagej.process.ImageUtils;
import imagej.process.Index;
import imagej.process.Span;
import imagej.process.TypeManager;
import imagej.process.operation.SetPlaneOperation;
import imagej.process.operation.SetPlaneOperation.DataType;
import mpicbg.imglib.container.ContainerFactory;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.type.numeric.RealType;
import mpicbg.imglib.type.numeric.integer.ByteType;
import mpicbg.imglib.type.numeric.integer.IntType;
import mpicbg.imglib.type.numeric.integer.LongType;
import mpicbg.imglib.type.numeric.integer.ShortType;
import mpicbg.imglib.type.numeric.integer.UnsignedByteType;
import mpicbg.imglib.type.numeric.integer.UnsignedIntType;
import mpicbg.imglib.type.numeric.integer.UnsignedShortType;
import mpicbg.imglib.type.numeric.real.DoubleType;
import mpicbg.imglib.type.numeric.real.FloatType;
public class PlaneStack<T extends RealType<T>>
{
/* OTHER WAY
this.stack = new ArrayList<Image<T>>();
this.stack.add(newPlane);
*/
}
else // we already have some entries in stack
{
// need to type check against existing planes
// ONE WAY
RealType<?> myType = ImageUtils.getType(this.stack);
// OTHER WAY
// RealType<?> myType = ImageUtils.getType(this.stack.get(0));
if ( ! (TypeManager.sameKind(desiredType, myType)) )
throw new IllegalArgumentException("insertPlane(): type clash - " + myType + " & " + desiredType);
/* ONE WAY
*/
int[] newDims = new int[]{this.planeWidth, this.planeHeight, this.getEndPosition()+1};
Image<T> newStack = ImageUtils.createImage(desiredType, this.factory, newDims);
copyPlanesFromTo(atPosition, this.stack, 0, newStack, 0);
copyPlanesFromTo(1, newPlane, 0, newStack, atPosition);
copyPlanesFromTo(getEndPosition()-atPosition, this.stack, atPosition, newStack, atPosition+1);
this.stack = newStack;
// OTHER WAY
// this.stack.add(atPosition, newPlane);
}
}
private void insertUnsignedPlane(int atPosition, byte[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new UnsignedByteType(), DataType.UBYTE);
}
private void insertSignedPlane(int atPosition, byte[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new ByteType(), DataType.BYTE);
}
private void insertUnsignedPlane(int atPosition, short[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new UnsignedShortType(), DataType.USHORT);
}
private void insertSignedPlane(int atPosition, short[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new ShortType(), DataType.SHORT);
}
private void insertUnsignedPlane(int atPosition, int[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new UnsignedIntType(), DataType.UINT);
}
private void insertSignedPlane(int atPosition, int[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new IntType(), DataType.INT);
}
private void insertUnsignedPlane(int atPosition, long[] data)
{
throw new IllegalArgumentException("PlaneStack::insertUnsignedPlane(long[]): unsigned long data not supported");
}
private void insertSignedPlane(int atPosition, long[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new LongType(), DataType.LONG);
}
private void insertPlane(int atPosition, float[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new FloatType(), DataType.FLOAT);
}
private void insertPlane(int atPosition, double[] data)
{
insertPlane(atPosition, data, data.length, (RealType) new DoubleType(), DataType.DOUBLE);
}
/* OTHER WAY
public Image<T> getStorage(int i)
{
if (this.stack == null)
return null;
return this.stack.get(i);
}
*/
public long getNumPlanes()
{
if (this.stack == null)
return 0;
//ONE WAY
return ImageUtils.getTotalPlanes(getStorage().getDimensions());
// OTHER WAY
//return this.stack.size();
}
public int getEndPosition()
{
long totalPlanes = getNumPlanes();
if (totalPlanes > Integer.MAX_VALUE)
throw new IllegalArgumentException("PlaneStack()::getEndPosition() - too many planes");
return (int) totalPlanes;
}
public void insertPlane(int atPosition, boolean unsigned, Object data)
{
if (data instanceof byte[])
{
if (unsigned)
insertUnsignedPlane(atPosition,(byte[])data);
else
insertSignedPlane(atPosition,(byte[])data);
}
else if (data instanceof short[])
{
if (unsigned)
insertUnsignedPlane(atPosition,(short[])data);
else
insertSignedPlane(atPosition,(short[])data);
}
else if (data instanceof int[])
{
if (unsigned)
insertUnsignedPlane(atPosition,(int[])data);
else
insertSignedPlane(atPosition,(int[])data);
}
else if (data instanceof long[])
{
if (unsigned)
insertUnsignedPlane(atPosition,(long[])data);
else
insertSignedPlane(atPosition,(long[])data);
}
else if (data instanceof float[])
{
insertPlane(atPosition,(float[])data);
}
else if (data instanceof double[])
{
insertPlane(atPosition,(double[])data);
}
else
throw new IllegalArgumentException("PlaneStack::insertPlane(Object): unknown data type passed in - "+data.getClass());
}
public void addPlane(boolean unsigned, Object data)
{
insertPlane(getEndPosition(), unsigned, data);
}
public void deletePlane(int planeNumber) // since multidim an int could be too small but can't avoid
{
if (this.stack == null)
throw new IllegalArgumentException("PlaneStack::deletePlane() - cannot delete from empty stack");
int endPosition = getEndPosition();
if ((planeNumber < 0) || (planeNumber >= endPosition))
throw new IllegalArgumentException("PlaneStack::deletePlane() - planeNumber out of bounds - "+planeNumber+" outside [0,"+endPosition+")");
/* ONE WAY
this.stack.remove(planeNumber);
*/
/* OTHER WAY
*/
int[] newDims = new int[]{this.planeWidth, this.planeHeight, this.stack.getDimension(2)-1};
if (newDims[2] == 0)
{
this.stack = null;
return;
}
// create a new image one plane smaller than existing
Image<T> newImage = ImageUtils.createImage((RealType<T>)this.type, this.stack.getContainerFactory(), newDims);
copyPlanesFromTo(planeNumber, this.stack, 0, newImage, 0);
copyPlanesFromTo(getEndPosition()-planeNumber-1, this.stack, planeNumber+1, newImage, planeNumber);
this.stack = newImage;
}
}
|
package it.unibz.krdb.obda.owlrefplatform.core.basicoperations;
import it.unibz.krdb.obda.model.AlgebraOperatorPredicate;
import it.unibz.krdb.obda.model.BooleanOperationPredicate;
import it.unibz.krdb.obda.model.CQIE;
import it.unibz.krdb.obda.model.Constant;
import it.unibz.krdb.obda.model.DatalogProgram;
import it.unibz.krdb.obda.model.Function;
import it.unibz.krdb.obda.model.OBDADataFactory;
import it.unibz.krdb.obda.model.OBDAQueryModifiers;
import it.unibz.krdb.obda.model.Predicate;
import it.unibz.krdb.obda.model.Predicate.COL_TYPE;
import it.unibz.krdb.obda.model.Term;
import it.unibz.krdb.obda.model.Variable;
import it.unibz.krdb.obda.model.impl.FunctionalTermImpl;
import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl;
import it.unibz.krdb.obda.model.impl.OBDAVocabulary;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/***
* Implements several transformations on the rules of a datalog program that
* make it easier to evaluate query containment, or to translate into SQL.
*
* @author Mariano Rodriguez Muro <mariano.muro@gmail.com>
*
*/
public class DatalogNormalizer {
private final static OBDADataFactory fac = OBDADataFactoryImpl.getInstance();
/***
* Normalizes all the rules in a Datalog program, pushing equalities into
* the atoms of the queries, when possible
*
* @param dp
*/
public static DatalogProgram normalizeDatalogProgram(DatalogProgram dp) {
DatalogProgram clone = fac.getDatalogProgram();
clone.setQueryModifiers(dp.getQueryModifiers());
for (CQIE cq : dp.getRules()) {
CQIE normalized = normalizeCQIE(cq);
if (normalized != null) {
clone.appendRule(normalized);
}
}
return clone;
}
public static CQIE normalizeCQIE(CQIE query) {
CQIE result = unfoldANDTrees(query);
// result = normalizeEQ(result);
result = unfoldJoinTrees(result);
result = pullUpNestedReferences(result, true);
if (result == null)
return null;
return result;
}
/***
* This expands all AND trees into individual comparison atoms in the body
* of the query. Nested AND trees inside Join or LeftJoin atoms are not
* touched.
*
* @param query
* @return
*/
public static CQIE unfoldANDTrees(CQIE query) {
CQIE result = query.clone();
List<Function> body = result.getBody();
/* Collecting all necessary conditions */
for (int i = 0; i < body.size(); i++) {
Function currentAtom = body.get(i);
if (currentAtom.getPredicate() == OBDAVocabulary.AND) {
body.remove(i);
body.addAll(getUnfolderAtomList(currentAtom));
}
}
return result;
}
/***
* This expands all Join that can be directly added as conjuncts to a
* query's body. Nested Join trees inside left joins are not touched.
*
* @param query
* @return
*/
public static CQIE unfoldJoinTrees(CQIE query) {
return unfoldJoinTrees(query, true);
}
/***
* This expands all Join that can be directly added as conjuncts to a
* query's body. Nested Join trees inside left joins are not touched.
*
* @param query
* @return
*/
public static CQIE unfoldJoinTrees(CQIE query, boolean clone) {
if (clone)
query = query.clone();
List body = query.getBody();
unfoldJoinTrees(body, true);
return query;
}
/***
* This expands all Join that can be directly added as conjuncts to a
* query's body. Nested Join trees inside left joins are not touched.
* <p>
* In addition, we will remove any Join atoms that only contain one single
* data atom, i.e., the join is not a join, but a table reference with
* conditions. These kind of atoms can result from the partial evaluation
* process and should be eliminated. The elimination takes all the atoms in
* the join (the single data atom plus possibly extra boolean conditions and
* adds them to the node that is the parent of the join).
*
* @param query
* @return
*/
public static void unfoldJoinTrees(List body, boolean isJoin) {
/* Collecting all necessary conditions */
for (int i = 0; i < body.size(); i++) {
Function currentAtom = (Function) body.get(i);
if (!currentAtom.isAlgebraFunction())
continue;
if (currentAtom.getFunctionSymbol() == OBDAVocabulary.SPARQL_LEFTJOIN)
unfoldJoinTrees(currentAtom.getTerms(), false);
if (currentAtom.getFunctionSymbol() == OBDAVocabulary.SPARQL_JOIN) {
unfoldJoinTrees(currentAtom.getTerms(), true);
int dataAtoms = countDataItems(currentAtom.getTerms());
if (isJoin || dataAtoms == 1) {
body.remove(i);
for (int j = currentAtom.getTerms().size() - 1; j >= 0; j
Term term = currentAtom.getTerm(j);
Function asAtom = (Function) term;
if (!body.contains(asAtom))
body.add(i, asAtom);
}
i -= 1;
}
}
}
}
public static CQIE foldJoinTrees(CQIE query, boolean clone) {
if (clone)
query = query.clone();
List body = query.getBody();
foldJoinTrees(body, false);
return query;
}
public static void foldJoinTrees(List atoms, boolean isJoin) {
List<Function> dataAtoms = new LinkedList<Function>();
List<Function> booleanAtoms = new LinkedList<Function>();
/*
* Collecting all data and boolean atoms for later processing. Calling
* recursively fold Join trees on any algebra function.
*/
for (Object o : atoms) {
Function atom = (Function) o;
if (atom.isBooleanFunction()) {
booleanAtoms.add(atom);
} else {
dataAtoms.add(atom);
if (atom.getFunctionSymbol() == OBDAVocabulary.SPARQL_LEFTJOIN)
foldJoinTrees(atom.getTerms(), false);
if (atom.getFunctionSymbol() == OBDAVocabulary.SPARQL_JOIN)
foldJoinTrees(atom.getTerms(), true);
}
}
if (!isJoin || dataAtoms.size() <= 2)
return;
/*
* We process all atoms in dataAtoms to make only BINARY joins. Taking
* two at a time and replacing them for JOINs, until only two are left.
* All boolean conditions of the original join go into the first join
* generated. It always merges from the left to the right.
*/
while (dataAtoms.size() > 2) {
Function joinAtom = fac.getFunction(OBDAVocabulary.SPARQL_JOIN, dataAtoms.remove(0), dataAtoms.remove(0));
joinAtom.getTerms().addAll(booleanAtoms);
booleanAtoms.clear();
dataAtoms.add(0, joinAtom);
}
atoms.clear();
atoms.addAll(dataAtoms);
}
/***
* Counts the number of data atoms in this list of terms. Not recursive.
*
* @param terms
* @return
*/
public static int countDataItems(List<Term> terms) {
int count = 0;
for (Term lit : terms) {
Function currentAtom = (Function) lit;
if (!currentAtom.isBooleanFunction())
count += 1;
}
return count;
}
/***
* Enforces all equalities in the query, that is, for every equivalence
* class (among variables) defined by a set of equialities, it chooses one
* representive variable and replaces all other variables in the equivalence
* class for with the representative varible. For example, if the query body
* is R(x,y,z), x=y, y=z. It will choose x and produce the following body
* R(x,x,x).
* <p>
* Note the process will also remove from the body all the equalities that
* here processed.
*
*
* @param result
* @param clone
* Indicates if the query should be cloned and the changes done
* on the clone only, or if the changes are done 'in place'. The
* first case returns a NEW query object, the second case returns
* the ORIGINAL query object.
* @return
*/
public static CQIE enforceEqualities(CQIE result, boolean clone) {
if (clone)
result = result.clone();
List<Function> body = result.getBody();
Map<Variable, Term> mgu = new HashMap<Variable, Term>();
/* collecting all equalities as substitutions */
for (int i = 0; i < body.size(); i++) {
Function atom = body.get(i);
Unifier.applyUnifier(atom, mgu);
if (atom.getFunctionSymbol() == OBDAVocabulary.EQ) {
Substitution s = Unifier.getSubstitution(atom.getTerm(0), atom.getTerm(1));
if (s == null) {
continue;
} else if (!(s instanceof NeutralSubstitution)) {
Unifier.composeUnifiers(mgu, s);
}
body.remove(i);
i -= 1;
}
}
result = Unifier.applyUnifier(result, mgu, false);
return result;
}
/***
* See {@link #enforceEqualities(CQIE, boolean)}
*
* @param dp
* @return
* @see #enforceEqualities(CQIE, boolean)
*/
public static DatalogProgram enforceEqualities(DatalogProgram dp) {
return enforceEqualities(dp, true);
}
/***
* Enforces equalities in the variables of the queries in the Datalog
* program returning a copy of the program with all the equalities enforced.
* {@link #enforceEqualities(CQIE, boolean) enforceEqualities}
*
* @param dp
* @return
* @see #enforceEqualities(CQIE, boolean)
*/
public static DatalogProgram enforceEqualities(DatalogProgram dp, boolean clone) {
List<CQIE> queries = dp.getRules();
if (clone) {
OBDAQueryModifiers queryModifiers = dp.getQueryModifiers();
dp = fac.getDatalogProgram();
dp.setQueryModifiers(queryModifiers);
}
for (CQIE cq : queries) {
cq = enforceEqualities(cq, clone);
if (clone) {
dp.appendRule(cq);
}
}
return dp;
}
/***
* This method introduces new variable names in each data atom and
* equalities to account for JOIN operations. This method is called before
* generating SQL queries and allows to avoid cross refrences in nested
* JOINs, which generate wrong ON or WHERE conditions.
*
*
* @param currentTerms
* @param substitutions
*/
public static void pullOutEqualities(CQIE query) {
Map<Variable, Term> substitutions = new HashMap<Variable, Term>();
int[] newVarCounter = { 1 };
Set<Function> booleanAtoms = new HashSet<Function>();
List<Function> equalities = new LinkedList<Function>();
pullOutEqualities(query.getBody(), substitutions, equalities, newVarCounter, false);
@SuppressWarnings("rawtypes")
List body = query.getBody();
body.addAll(equalities);
/*
* All new variables have been generated, the substitutions also, we
* need to apply them to the equality atoms and to the head of the
* query.
*/
Unifier.applyUnifier(query, substitutions, false);
}
private static BranchDepthSorter sorter = new BranchDepthSorter();
/***
* Compares two atoms by the depth of their JOIN/LEFT JOIN branches. This is
* used to sort atoms in a query bodybased on the depth, to assure the
* depesth branches are visited first.
*
* @author mariano
*
*/
private static class BranchDepthSorter implements Comparator<Function> {
public int getDepth(Function term) {
int max = 0;
if (term.isDataFunction() || term.isBooleanFunction() || term.isDataTypeFunction()) {
return 0;
} else {
List<Term> innerTerms = term.getTerms();
for (Term innerTerm : innerTerms) {
int depth = getDepth((Function) innerTerm);
max = Math.max(max, depth);
}
max += 1;
}
// System.out.println("MAX: " + max);
return max;
}
@Override
public int compare(Function arg0, Function arg1) {
return getDepth(arg1) - getDepth(arg0);
}
}
/***
* Adds a trivial equality to a LeftJoin in case the left join doesn't have
* at least one boolean condition. This is necessary to have syntactically
* correct LeftJoins in SQL.
*
* @param leftJoin
*/
private static void addMinimalEqualityToLeftJoin(Function leftJoin) {
int booleanAtoms = 0;
boolean isLeftJoin = leftJoin.isAlgebraFunction();
for (Term term : leftJoin.getTerms()) {
Function f = (Function) term;
if (f.isAlgebraFunction()) {
addMinimalEqualityToLeftJoin(f);
}
if (f.isBooleanFunction())
booleanAtoms += 1;
}
if (isLeftJoin && booleanAtoms == 0) {
Function trivialEquality = fac.getFunctionEQ(fac.getConstantLiteral("1", COL_TYPE.INTEGER),
fac.getConstantLiteral("1", COL_TYPE.INTEGER));
leftJoin.getTerms().add(trivialEquality);
}
}
public static void addMinimalEqualityToLeftJoin(CQIE query) {
for (Function f : query.getBody()) {
if (f.isAlgebraFunction()) {
addMinimalEqualityToLeftJoin(f);
}
}
}
/***
* This method introduces new variable names in each data atom and
* equalities to account for JOIN operations. This method is called before
* generating SQL queries and allows to avoid cross references in nested
* JOINs, which generate wrong ON or WHERE conditions.
*
*
* @param currentTerms
* @param substitutions
*/
private static void pullOutEqualities(List currentTerms, Map<Variable, Term> substitutions, List<Function> eqList, int[] newVarCounter,
boolean isLeftJoin) {
for (int i = 0; i < currentTerms.size(); i++) {
Term term = (Term) currentTerms.get(i);
/*
* We don't expect any functions as terms, data atoms will only have
* variables or constants at this level. This method is only called
* exactly before generating the SQL query.
*/
if (!(term instanceof Function))
throw new RuntimeException("Unexpected term found while normalizing (pulling out equalities) the query.");
Function atom = (Function) term;
List<Term> subterms = atom.getTerms();
if (atom.isAlgebraFunction()) {
if (atom.getFunctionSymbol() == OBDAVocabulary.SPARQL_LEFTJOIN)
pullOutEqualities(subterms, substitutions, eqList, newVarCounter, true);
else
pullOutEqualities(subterms, substitutions, eqList, newVarCounter, false);
} else if (atom.isBooleanFunction()) {
continue;
}
// rename/substitute variables
for (int j = 0; j < subterms.size(); j++) {
Term subTerm = subterms.get(j);
if (subTerm instanceof Variable) {
renameVariable(substitutions, eqList, newVarCounter, atom, subterms, j, (Variable) subTerm);
} else if (subTerm instanceof Constant) {
/*
* This case was necessary for query 7 in BSBM
*/
/**
* A('c') Replacing the constant with a fresh variable x and
* adding an quality atom ,e.g., A(x), x = 'c'
*/
// only relevant if in data function?
if (atom.isDataFunction()) {
Variable var = fac.getVariable("f" + newVarCounter[0]);
newVarCounter[0] += 1;
Function equality = fac.getFunctionEQ(var, subTerm);
subterms.set(j, var);
eqList.add(equality);
}
} else if (subTerm instanceof Function) {
Predicate head = ((Function) subTerm).getFunctionSymbol();
if (head.isDataTypePredicate()) {
// This case is for the ans atoms that might have
// functions in the head. Check if it is needed.
Set<Variable> subtermsset = subTerm
.getReferencedVariables();
// Right now we support only unary functions!!
for (Variable var : subtermsset) {
renameTerm(substitutions, eqList, newVarCounter,
atom, subterms, j, (Function) subTerm, var);
}
}
}
} // end for subterms
currentTerms.addAll(i + 1, eqList);
i = i + eqList.size();
eqList.clear();
}
}
private static void renameTerm(Map<Variable, Term> substitutions, List<Function> eqList, int[] newVarCounter, Function atom,
List<Term> subterms, int j, Function subTerm, Variable var1) {
Predicate head = subTerm.getFunctionSymbol();
Variable var2 = (Variable) substitutions.get(var1);
if (var2 == null) {
/*
* No substitution exists, hence, no action but generate a new
* variable and register in the substitutions, and replace the
* current value with a fresh one.
*/
var2 = fac.getVariable(var1.getName() + "f" + newVarCounter[0]);
FunctionalTermImpl newFuncTerm = (FunctionalTermImpl) fac.getFunction(head, var1);
subterms.set(j, var2);
Function equality = fac.getFunctionEQ(var2, newFuncTerm);
eqList.add(equality);
} else {
/*
* There already exists one, so we generate a fresh, replace the
* current value, and add an equality between the substitution and
* the new value.
*/
if (atom.isDataFunction()) {
Variable newVariable = fac.getVariable(var1.getName() + newVarCounter[0]);
subterms.set(j, newVariable);
FunctionalTermImpl newFuncTerm = (FunctionalTermImpl) fac.getFunction(head, var2);
Function equality = fac.getFunctionEQ(newVariable, newFuncTerm);
eqList.add(equality);
} else { // if its not data function, just replace
// variable
subterms.set(j, var2);
}
}
newVarCounter[0] += 1;
}
private static void renameVariable(Map<Variable, Term> substitutions, List<Function> eqList, int[] newVarCounter, Function atom,
List<Term> subterms, int j, Term subTerm) {
Variable var1 = (Variable) subTerm;
Variable var2 = (Variable) substitutions.get(var1);
if (var2 == null) {
/*
* No substitution exists, hence, no action but generate a new
* variable and register in the substitutions, and replace the
* current value with a fresh one.
*/
var2 = fac.getVariable(var1.getName() + "f" + newVarCounter[0]);
substitutions.put(var1, var2);
subterms.set(j, var2);
} else {
/*
* There already exists one, so we generate a fresh, replace the
* current value, and add an equality between the substitution and
* the new value.
*/
if (atom.isDataFunction()) {
Variable newVariable = fac.getVariable(var1.getName() + newVarCounter[0]);
subterms.set(j, newVariable);
Function equality = fac.getFunctionEQ(var2, newVariable);
eqList.add(equality);
} else { // if its not data function, just replace
// variable
subterms.set(j, var2);
}
}
newVarCounter[0] += 1;
}
// Saturate equalities list to explicitly state JOIN conditions and
// therefore avoid having
// to rely on DBMS for nested JOIN optimisations (PostgreSQL case for BSBM
private static void saturateEqualities(Set<Function> boolSet) {
List<Set> equalitySets = new ArrayList();
Iterator<Function> iter = boolSet.iterator();
while (iter.hasNext()) {
Function eq = iter.next();
if (eq.getFunctionSymbol() != OBDAVocabulary.EQ)
continue;
Term v1 = eq.getTerm(0);
Term v2 = eq.getTerm(1);
if (equalitySets.size() == 0) {
Set firstSet = new LinkedHashSet();
firstSet.add(v1);
firstSet.add(v2);
equalitySets.add(firstSet);
continue;
}
for (int k = 0; k < equalitySets.size(); k++) {
Set set = equalitySets.get(k);
if (set.contains(v1)) {
set.add(v2);
continue;
}
if (set.contains(v2)) {
set.add(v1);
continue;
}
if (k == equalitySets.size() - 1) {
Set newSet = new LinkedHashSet();
newSet.add(v1);
newSet.add(v2);
equalitySets.add(newSet);
break;
}
}
}
for (int k = 0; k < equalitySets.size(); k++) {
List varList = new ArrayList(equalitySets.get(k));
for (int i = 0; i < varList.size() - 1; i++) {
for (int j = i + 1; j < varList.size(); j++) {
Function equality = fac.getFunctionEQ((Term) varList.get(i), (Term) varList.get(j));
boolSet.add(equality);
}
}
}
}
/****
* Gets all the variables that are defined in this list of atoms, except in
* atom i
*
* @param atoms
* @return
*/
private static Set<Variable> getDefinedVariables(List atoms) {
Set<Variable> currentLevelVariables = new HashSet<Variable>();
for (Object l : atoms) {
Function atom = (Function) l;
if (atom.isBooleanFunction()) {
continue;
} else if (atom.isAlgebraFunction()) {
currentLevelVariables.addAll(getDefinedVariables(atom.getTerms()));
} else {
currentLevelVariables.addAll(atom.getReferencedVariables());
}
}
return currentLevelVariables;
}
/***
* Collects all the variables that appear in all other branches (these are
* atoms in the list of atoms) except in focusBranch.
* <p>
* Variables are considered problematic because they are out of the scope of
* focusBranch. There are not visible in an SQL algebra tree.
* <p>
* Note that this method should only be called after callin pushEqualities
* and pullOutEqualities on the CQIE. This is to assure that there are no
* transitive equalities to take care of and that each variable in a data
* atom is unique.
*
* @param atoms
* @param branch
* @return
*/
private static Set<Variable> getProblemVariablesForBranchN(List atoms, int focusBranch) {
Set<Variable> currentLevelVariables = new HashSet<Variable>();
for (int i = 0; i < atoms.size(); i++) {
if (i == focusBranch)
continue;
Function atom = (Function) atoms.get(i);
if (atom.isDataFunction()) {
currentLevelVariables.addAll(atom.getReferencedVariables());
} else if (atom.isAlgebraFunction()) {
currentLevelVariables.addAll(getDefinedVariables(atom.getTerms()));
} else {
// noop
}
}
return currentLevelVariables;
}
/***
* This will
*
* @param query
* @return
*/
public static CQIE pullUpNestedReferences(CQIE query, boolean clone) {
if (clone)
query = query.clone();
List<Function> body = query.getBody();
Function head = query.getHead();
/*
* This set is only for reference
*/
Set<Variable> currentLevelVariables = new HashSet<Variable>();
/*
* This set will be modified in the process
*/
Set<Function> resultingBooleanConditions = new HashSet<Function>();
/*
* Analyze each atom that is a Join or LeftJoin, the process will
* replace everything needed.
*/
int[] freshVariableCount = { 0 };
pullUpNestedReferences(body, head, currentLevelVariables, resultingBooleanConditions, freshVariableCount);
/*
* Adding any remiding boolean conditions to the top level.
*/
for (Function condition : resultingBooleanConditions) {
body.add(condition);
}
return query;
}
private static void pullUpNestedReferences(List currentLevelAtoms, Function head, Set<Variable> problemVariables,
Set<Function> booleanConditions, int[] freshVariableCount) {
/*
* Call recursively on each atom that is a Join or a LeftJoin passing
* the variables of this level
*/
for (int focusBranch = 0; focusBranch < currentLevelAtoms.size(); focusBranch++) {
Object l = currentLevelAtoms.get(focusBranch);
Function atom = (Function) l;
if (!(atom.getFunctionSymbol() instanceof AlgebraOperatorPredicate))
continue;
// System.out
List<Term> terms = atom.getTerms();
Set<Variable> nestedProblemVariables = new HashSet<Variable>();
nestedProblemVariables.addAll(problemVariables);
nestedProblemVariables.addAll(getProblemVariablesForBranchN(currentLevelAtoms, focusBranch));
pullUpNestedReferences(terms, head, nestedProblemVariables, booleanConditions, freshVariableCount);
}
// Here we need to saturate Equalities
saturateEqualities(booleanConditions);
/*
* Add the resulting equalities that belong to the current level. An
* equality belongs to this level if ALL its variables are defined at
* the current level and not at the upper levels.
*/
Set<Function> removedBooleanConditions = new HashSet<Function>();
// System.out.println("Checking boolean conditions: "
// + booleanConditions.size());
for (Function equality : booleanConditions) {
Set<Variable> atomVariables = equality.getReferencedVariables();
boolean belongsToThisLevel = true;
for (Variable var : atomVariables) {
if (!problemVariables.contains(var))
continue;
belongsToThisLevel = false;
}
if (!belongsToThisLevel)
continue;
currentLevelAtoms.add(equality);
removedBooleanConditions.add(equality);
}
booleanConditions.removeAll(removedBooleanConditions);
/*
* Review the atoms of the current level and generate any variables,
* equalities needed at this level (no further recursive calls).
* Generate new variables for each variable that appears at this level,
* and also appears at a top level. We do this only for data atoms.
*
* We do this by creating a substitution for each of the, and then
* applying the substitution. We also add an equality for each
* substitution we created.
*/
/*
* Review the current boolean atoms, if the refer to upper level
* variables then remove them from the current level and add them to the
* equalities set for the upper level.
*
* If an contains at least 1 variable that is mentioned in an upper
* level, then this condition is removed from the current level and
* moved forward by adding it to the booleanConditions set.
*/
for (int index = 0; index < currentLevelAtoms.size(); index++) {
// System.out.println(index);
// System.out.println(currentLevelAtoms.size());
Term l = (Term) currentLevelAtoms.get(index);
Function atom = (Function) l;
// System.out
// .println(atom.getFunctionSymbol().getClass() + " " + atom);
if (!(atom.getFunctionSymbol() instanceof BooleanOperationPredicate))
continue;
Set<Variable> variables = atom.getReferencedVariables();
boolean belongsUp = false;
search: for (Variable var : variables) {
if (problemVariables.contains(var)) {
// /*
// * looking for an equality that might indicate that in
// fact,
// * the atom doesn't belong up because there is an equality
// * at this level that mentiones the "unsafe variable" and
// a
// * "safe variable" at the same time. (this pattern happens
// * due to the call to
// DatalogNormalizer.pullOutEqualities()
// * that happens before pullingUp
// */
// for (int idx2 = 0; idx2 < currentLevelAtoms.size();
// idx2++) {
// NewLiteral l2 = (NewLiteral) currentLevelAtoms
// .get(idx2);
// if (!(l2 instanceof Function))
// continue;
// Function f2 = (Function) l2;
// if (f2.getPredicate() != OBDAVocabulary.EQ)
// continue;
// List<NewLiteral> equalityVariables = f2.getTerms();
// if (equalityVariables.contains(var)) {
// // NewLiteral var2 = equalityVariables.get(0);
// // if (!(var2 instanceof Variable))
// // continue;
// if (!(problemVariables
// .containsAll(equalityVariables))) {
// /*
// * we found that var is acutally safe, there is
// * an equality that bounds it to a data atom in
// * the current level
// */
// continue search;
belongsUp = true;
break;
}
}
if (!belongsUp)
continue;
// Belongs up, removing and pushing up
// System.out.println("REMOVED!!!!");
currentLevelAtoms.remove(index);
index -= 1;
booleanConditions.add(atom);
}
}
/***
* Takes an AND atom and breaks it into a list of individual condition
* atoms.
*
* @param atom
* @return
*/
public static List<Function> getUnfolderAtomList(Function atom) {
if (atom.getPredicate() != OBDAVocabulary.AND) {
throw new InvalidParameterException();
}
List<Term> innerFunctionalTerms = new LinkedList<Term>();
for (Term term : atom.getTerms()) {
innerFunctionalTerms.addAll(getUnfolderTermList((Function) term));
}
List<Function> newatoms = new LinkedList<Function>();
for (Term innerterm : innerFunctionalTerms) {
Function f = (Function) innerterm;
Function newatom = fac.getFunction(f.getFunctionSymbol(), f.getTerms());
newatoms.add(newatom);
}
return newatoms;
}
/***
* Takes an AND atom and breaks it into a list of individual condition
* atoms.
*
* @param atom
* @return
*/
public static List<Term> getUnfolderTermList(Function term) {
List<Term> result = new LinkedList<Term>();
if (term.getFunctionSymbol() != OBDAVocabulary.AND) {
result.add(term);
} else {
List<Term> terms = term.getTerms();
for (Term currentterm : terms) {
if (currentterm instanceof Function) {
result.addAll(getUnfolderTermList((Function) currentterm));
} else {
result.add(currentterm);
}
}
}
return result;
}
// THE FOLLOWING COMMENT IS TAKEN FROM THE CODE ABOVE, THE FUNCTIONALITY IT
// DESCRIBES
// WAS IMPLEMENTED BELLOW
/*
* Here we collect boolean atoms that have conditions of atoms on the left
* of left joins. These cannot be put in the conditions of LeftJoin(...)
* atoms as inside terms, since these conditions have to be applied no
* matter what. Keeping them there makes them "optional", i.e., or else
* return NULL. Hence these conditions have to be pulled up to the nearest
* JOIN in the upper levels in the branches. The pulloutEqualities method
* iwll do this, however if there are still remaiing some by the time it
* finish, we must add them to the body of the CQIE as normal conditions to
* the query (WHERE clauses)
*/
public static void pullOutLeftJoinConditions(CQIE query) {
Set<Function> booleanAtoms = new HashSet<Function>();
Set<Function> tempBooleans = new HashSet<Function>();
List body = query.getBody();
Function f = (Function) body.get(0);
pullOutLJCond(body, booleanAtoms, false, tempBooleans, false);
body.addAll(booleanAtoms);
}
private static void pullOutLJCond(List currentTerms, Set<Function> leftConditionBooleans, boolean isLeftJoin,
Set<Function> currentBooleans, boolean isSecondJoin) {
boolean firstDataAtomFound = false;
boolean secondDataAtomFound = false;
boolean is2 = false;
List tempTerms = new LinkedList();
tempTerms.addAll(currentTerms);
Set<Function> tempConditionBooleans = new HashSet<Function>();
Term firstT = (Term) currentTerms.get(0);
if (!(firstT instanceof Function))
throw new RuntimeException("Unexpected term found while normalizing (pulling out conditions) the query.");
Function f = (Function) firstT;
for (int i = 0; i < currentTerms.size(); i++) {
Term term = (Term) currentTerms.get(i);
Function atom = (Function) term;
List<Term> subterms = atom.getTerms();
// if we are in left join then pull out boolean conditions that
// correspond to first data atom
if (atom.isDataFunction() || atom.isAlgebraFunction()) {
// if an atom is a Join then go inside, otherwise its
// Data Function
if (atom.isAlgebraFunction()) {
if (i != 0)
is2 = true;
if (atom.getFunctionSymbol() == OBDAVocabulary.SPARQL_LEFTJOIN)
pullOutLJCond(subterms, leftConditionBooleans, true, currentBooleans, is2);
else
pullOutLJCond(subterms, leftConditionBooleans, false, currentBooleans, is2);
}
// if first data atom is found already then this is the second
if (firstDataAtomFound)
secondDataAtomFound = true;
// if both are false then its the first data atom
if (!firstDataAtomFound && !secondDataAtomFound) {
firstDataAtomFound = true;
}
// I changed this, booleans were not being added !!
if (secondDataAtomFound && !isLeftJoin) {
System.err.println("DatalogNormalizer: I changed this!!");
tempTerms.addAll(currentBooleans);
}
} else { // its boolean atom
if (firstDataAtomFound && !secondDataAtomFound) {
// they need to be pulled out of LEFT
// JOINs ON clause
if (isLeftJoin) {
tempTerms.remove(atom);
// currentTerms.remove(atom);
tempConditionBooleans.add(atom);
// leftConditionBooleans.add(atom);
}
}
}
} // end for current terms
// tempTerms is currentTerms with "bad" boolean conditions removed
// now add all these removed conditions at the end
// and update current terms
// if we are at the top level Left Join then push booleans into
// where clause
// otherwise push it into upper Left Join ON clause
// if we are in a Join that is a second data atom, then dont push it all
// the way up
if (!isSecondJoin) {
System.err.println("DatalogNormalizer: THIS LINE DOES NOT WORK !!");
leftConditionBooleans.addAll(tempConditionBooleans);
}
currentTerms.clear();
currentTerms.addAll(tempTerms);
// currentTerms.addAll(currentBooleans);
currentBooleans.clear();
currentBooleans.addAll(tempConditionBooleans);
}
}
|
package xhl.core.validator;
import java.util.List;
import xhl.core.Error;
import xhl.core.SymbolTable;
import xhl.core.elements.*;
import xhl.core.validator.Validator.ValidationResult;
import static com.google.common.collect.Lists.newArrayList;
public class ElementSchema {
private final Symbol symbol;
private List<ParamSpec> params = newArrayList();
private Type type = Type.Null;
private final List<DefSpec> defines = newArrayList();
public ElementSchema(Symbol sym) {
this.symbol = sym;
}
public boolean isVariadic() {
return params.get(params.size()-1).variadic;
}
public SymbolTable<Type> definedSymbols(SList args, boolean onlyForward) {
SymbolTable<Type> symbols = new SymbolTable<Type>();
for (DefSpec def : defines) {
if (onlyForward && !def.forward)
continue;
ParamSpec argspec = params.get(def.arg - 1);
if (argspec.method == PassingMethod.SYM
&& argspec.type == Type.Symbol) {
Expression arg = args.get(def.arg - 1);
if (!(arg instanceof Symbol))
continue;
Symbol name = (Symbol) arg;
Type type = def.type;
symbols.put(name, type);
} else if (argspec.method == PassingMethod.SYM
&& argspec.type == Type.Map) {
Expression arg = args.get(def.arg - 1);
if (!(arg instanceof SMap))
continue;
SMap map = (SMap) arg;
Type type = def.type;
for (Expression key : map.keySet()) {
Symbol sym = (Symbol) key;
symbols.put(sym, type);
}
}
}
return symbols;
}
public ValidationResult checkCombination(Validator validator, SList tail) {
List<Error> errors = newArrayList();
// Check number of arguments
int minArgsSize = isVariadic() ? params.size() - 1 : params.size();
if (tail.size() < minArgsSize
|| (!isVariadic() && tail.size() > minArgsSize)) {
errors.add(new Error(tail.getPosition(),
"Wrong number of arguments"));
return new ValidationResult(type, errors);
}
// Check arguments types
for (int i = 0; i < minArgsSize; i++) {
errors.addAll(checkArgument(validator, params.get(i), tail.get(i)));
}
// Variadic arguments
if (isVariadic()) {
List<Expression> varargs = tail.subList(params.size(), tail.size());
ParamSpec spec = params.get(params.size()-1);
for (Expression arg : varargs)
errors.addAll(checkArgument(validator, spec, arg));
}
return new ValidationResult(type, errors);
}
private List<Error> checkArgument(Validator validator, ParamSpec spec,
Expression arg) {
List<Error> errors = newArrayList();
Type argtype;
if (spec.method == PassingMethod.SYM)
argtype = Type.typeOfElement(arg);
else
argtype = validator.check(arg);
if (!argtype.is(spec.type))
errors.add(new Error(arg.getPosition(),
"Wrong type of an argument (expected " + spec.type
+ ", found " + argtype + ")"));
return errors;
}
public Symbol getSymbol() {
return symbol;
}
public List<ParamSpec> getParams() {
return params;
}
public void setParams(List<ParamSpec> params) {
this.params = params;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public List<DefSpec> getDefines() {
return defines;
}
public void addDefine(DefSpec spec) {
defines.add(spec);
}
public static enum PassingMethod { VAL, SYM }
public static class ParamSpec {
/** Argument specification */
public final Type type;
public final PassingMethod method;
public final boolean variadic;
public final boolean block;
public static ParamSpec val(Type type) {
return new ParamSpec(PassingMethod.VAL, type, false, false);
}
public static ParamSpec sym(Type type) {
return new ParamSpec(PassingMethod.SYM, type, false, false);
}
public static ParamSpec variadic(ParamSpec spec) {
return new ParamSpec(spec.method, spec.type, true, false);
}
public static ParamSpec block(ParamSpec spec) {
return new ParamSpec(spec.method, spec.type, false, true);
}
private ParamSpec(PassingMethod method, Type type, boolean variadic,
boolean block) {
this.method = method;
this.type = type;
this.variadic = variadic;
this.block = block;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ParamSpec))
return false;
ParamSpec that = (ParamSpec) obj;
return this.type.equals(that.type)
&& this.method.equals(that.method);
}
}
public static class DefSpec {
public final Type type;
public final int arg;
public final boolean forward;
public DefSpec(int arg, Type type) {
this(arg, type, false);
}
public DefSpec(int arg, Type type, boolean forward) {
this.arg = arg;
this.type = type;
this.forward = forward;
}
}
}
|
package com.planet_ink.coffee_mud.Abilities;
import com.planet_ink.coffee_mud.interfaces.*;
import com.planet_ink.coffee_mud.common.*;
import com.planet_ink.coffee_mud.utils.*;
import java.util.*;
public class StdAbility implements Ability, Cloneable
{
protected String myID=this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.')+1);
protected String name="an ability";
protected String description="&";
protected boolean borrowed=false;
public String displayText="What they see when affected.";
public String miscText="";
protected MOB invoker=null;
protected Vector triggerStrings=new Vector();
protected int uses=Integer.MAX_VALUE;
protected int profficiency=0;
protected boolean isAnAutoEffect=false;
protected EnvStats envStats=new DefaultEnvStats();
protected EnvStats baseEnvStats=new DefaultEnvStats();
protected Environmental affected=null;
protected boolean canBeUninvoked=true;
protected boolean isAutoinvoked=false;
protected boolean unInvoked=false;
protected boolean putInCommandlist=true;
protected int quality=Ability.INDIFFERENT;
protected long tickDown=-1;
public StdAbility()
{
}
public boolean qualifies(MOB student)
{
int level=qualifyingLevel(student);
if(level<0) return false;
if(student.envStats().level()>=level)
return true;
else
return false;
}
public boolean isAnAutoEffect()
{ return isAnAutoEffect; }
public boolean isBorrowed(Environmental toMe)
{ return borrowed; }
public void setBorrowed(Environmental toMe, boolean truefalse)
{ borrowed=truefalse; }
public void startTickDown(Environmental affected, long tickTime)
{
if(affected.fetchAffect(this.ID())==null)
affected.addAffect(this);
if(affected instanceof MOB)
((MOB)affected).location().recoverRoomStats();
else
{
if(affected instanceof Room)
((Room)affected).recoverRoomStats();
else
affected.recoverEnvStats();
ExternalPlay.startTickDown(this,Host.MOB_TICK,1);
}
tickDown=tickTime;
}
public boolean putInCommandlist()
{
return putInCommandlist;
}
public int qualifyingLevel(MOB student)
{
if(student==null) return -1;
if(student.charStats().getMyClass()==null)
return -1;
if(student.isASysOp(null))
return CMAble.lowestQualifyingLevel(ID());
return CMAble.getQualifyingLevel(student.charStats().getMyClass().ID(),ID());
}
public MOB getTarget(MOB mob, Vector commands, Environmental givenTarget)
{ return getTarget(mob,commands,givenTarget,false); }
public MOB getTarget(MOB mob, Vector commands, Environmental givenTarget, boolean quiet)
{
String targetName=Util.combine(commands,0);
MOB target=null;
if((givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
else
if((targetName.length()==0)&&(mob.isInCombat())&&(quality==Ability.MALICIOUS)&&(mob.getVictim()!=null))
target=mob.getVictim();
else
if((targetName.length()==0)&&(quality!=Ability.MALICIOUS))
target=mob;
else
if(targetName.length()>0)
{
target=mob.location().fetchInhabitant(targetName);
if(target==null)
{
Environmental t=mob.location().fetchFromRoomFavorItems(null,targetName);
if((t!=null)&&(!(t instanceof MOB)))
{
if(!quiet)
mob.tell("You can't do that to '"+targetName+"'.");
return null;
}
}
}
if(target!=null)
targetName=target.name();
if((target==null)||((!Sense.canBeSeenBy(target,mob))&&((!Sense.canBeHeardBy(target,mob))||(!target.isInCombat()))))
{
if(!quiet)
{
if(targetName.trim().length()==0)
mob.tell("You don't see them here.");
else
mob.tell("You don't see '"+targetName+"' here.");
}
return null;
}
if(target.fetchAffect(this.ID())!=null)
{
if(!quiet)
{
if(target==mob)
mob.tell("You are already affected by "+name()+".");
else
mob.tell(target.name()+" is already affected by "+name()+".");
}
return null;
}
return target;
}
public Environmental getAnyTarget(MOB mob, Vector commands, Environmental givenTarget)
{
String targetName=Util.combine(commands,0);
Environmental target=null;
if(givenTarget!=null)
target=givenTarget;
else
if((targetName.length()==0)&&(mob.isInCombat())&&(quality==Ability.MALICIOUS)&&(mob.getVictim()!=null))
target=mob.getVictim();
else
{
target=mob.location().fetchFromRoomFavorMOBs(null,targetName);
if(target==null)
target=mob.location().fetchFromMOBRoomFavorsItems(mob,null,targetName);
}
if(target!=null) targetName=target.name();
if((target==null)||((!Sense.canBeSeenBy(target,mob))&&((!Sense.canBeHeardBy(target,mob))||((target instanceof MOB)&&(!((MOB)target).isInCombat())))))
{
if(targetName.trim().length()==0)
mob.tell("You don't see that here.");
else
mob.tell("You don't see '"+targetName+"' here.");
return null;
}
if(target.fetchAffect(this.ID())!=null)
{
if(target==mob)
mob.tell("You are already affected by "+name()+".");
else
mob.tell(targetName+" is already affected by "+name()+".");
return null;
}
return target;
}
public Item getTarget(MOB mob, Room location, Environmental givenTarget, Vector commands)
{
String targetName=Util.combine(commands,0);
Environmental target=null;
if((givenTarget!=null)&&(givenTarget instanceof Item))
target=givenTarget;
if(location!=null)
target=location.fetchFromRoomFavorItems(null,targetName);
if(target==null)
{
if(location!=null)
target=location.fetchFromMOBRoomFavorsItems(mob,null,targetName);
else
target=mob.fetchCarried(null,targetName);
}
if(target!=null) targetName=target.name();
if((target==null)||((target!=null)&&((!Sense.canBeSeenBy(target,mob))||(!(target instanceof Item)))))
{
if(targetName.length()==0)
mob.tell("You need to be more specific.");
else
if((target==null)||(target instanceof Item))
{
if(targetName.trim().length()==0)
mob.tell("You don't see that here.");
else
mob.tell("You don't see '"+targetName+"' here.");
}
else
mob.tell("You can't do that to '"+targetName+"'.");
return null;
}
return (Item)target;
}
public int classificationCode()
{
return Ability.SKILL;
}
public String ID()
{
return myID;
}
public String name(){ return name;}
public void setName(String newName){name=newName;}
public EnvStats envStats()
{
return envStats;
}
public EnvStats baseEnvStats()
{
return baseEnvStats;
}
public void recoverEnvStats()
{
envStats=baseEnvStats.cloneStats();
}
public void setBaseEnvStats(EnvStats newBaseEnvStats)
{
baseEnvStats=newBaseEnvStats.cloneStats();
}
public Environmental newInstance()
{
return new StdAbility();
}
private void cloneFix(Ability E)
{
baseEnvStats=E.baseEnvStats().cloneStats();
envStats=E.envStats().cloneStats();
}
public Environmental copyOf()
{
try
{
StdAbility E=(StdAbility)this.clone();
E.cloneFix(this);
return E;
}
catch(CloneNotSupportedException e)
{
return this.newInstance();
}
}
public String displayText()
{ return displayText;}
public void setDisplayText(String newDisplayText)
{ displayText=newDisplayText;}
public void setMiscText(String newMiscText)
{ miscText=newMiscText;}
public String text()
{ return miscText;}
public String description()
{ return description;}
public void setDescription(String newDescription)
{ description=newDescription;}
public int profficiency(){ return profficiency;}
public void setProfficiency(int newProfficiency)
{
profficiency=newProfficiency;
if(profficiency>100) profficiency=100;
}
public boolean profficiencyCheck(int adjustment, boolean auto)
{
if(auto)
{
this.isAnAutoEffect=true;
this.setProfficiency(100);
return true;
}
isAnAutoEffect=false;
int pctChance=profficiency();
if(pctChance>95) pctChance=95;
if(pctChance<5) pctChance=5;
if(adjustment>=0)
pctChance+=adjustment;
else
if(Dice.rollPercentage()>(100+adjustment))
return false;
return (Dice.rollPercentage()<pctChance);
}
public Environmental affecting()
{
return affected;
}
public void setAffectedOne(Environmental being)
{
affected=being;
}
public void unInvoke()
{
unInvoked=true;
if(affected==null) return;
Environmental being=affected;
if(canBeUninvoked)
{
being.delAffect(this);
if(being instanceof Room)
((Room)being).recoverRoomStats();
else
if(being instanceof MOB)
{
if(((MOB)being).location()!=null)
((MOB)being).location().recoverRoomStats();
else
{
being.recoverEnvStats();
((MOB)being).recoverCharStats();
((MOB)being).recoverMaxState();
}
}
else
being.recoverEnvStats();
}
}
public boolean canBeUninvoked()
{
return canBeUninvoked;
}
public int usesRemaining()
{
return uses;
}
public void setUsesRemaining(int newUses)
{
uses=newUses;
}
public void affectEnvStats(Environmental affected, EnvStats affectableStats)
{}
public void affectCharStats(MOB affectedMob, CharStats affectableStats)
{}
public void affectCharState(MOB affectedMob, CharState affectableMaxState)
{}
public MOB invoker()
{
return invoker;
}
public Vector triggerStrings()
{
return triggerStrings;
}
public void helpProfficiency(MOB mob)
{
Ability A=(Ability)mob.fetchAbility(this.ID());
if(A==null) return;
if(A.profficiency()<100)
{
if(Math.round((Util.div(mob.charStats().getIntelligence(),18.0))*100.0*Math.random())>50)
{
// very important, since these can be autoinvoked affects (copies)!
A.setProfficiency(A.profficiency()+1);
if((this!=A)&&(profficiency()<100))
setProfficiency(profficiency()+1);
}
}
else
A.setProfficiency(100);
}
public boolean invoke(MOB mob, Environmental target, boolean auto)
{
Vector V=new Vector();
if(target!=null)
V.addElement(target.name());
return invoke(mob,V,target,auto);
}
public boolean invoke(MOB mob, Vector commands, Environmental target, boolean auto)
{
if(!auto)
{
isAnAutoEffect=false;
// if you can't move, you can't cast! Not even verbal!
if(!Sense.aliveAwakeMobile(mob,false))
return false;
Integer levelDiff=new Integer(mob.envStats().level()-envStats().level());
int manaConsumed=50-(int)Math.round(50.0*(levelDiff.doubleValue()/10.0));
if(manaConsumed<5) manaConsumed=5;
if(manaConsumed>50) manaConsumed=50;
if(mob.curState().getMana()<manaConsumed)
{
mob.tell("You don't have enough mana to do that.");
return false;
}
mob.curState().adjMana(-manaConsumed,mob.maxState());
helpProfficiency(mob);
}
else
isAnAutoEffect=true;
return true;
}
public boolean maliciousAffect(MOB mob,
Environmental target,
int tickAdjustmentFromStandard,
int additionAffectCheckCode)
{
boolean ok=true;
if(additionAffectCheckCode>=0)
{
FullMsg msg=new FullMsg(mob,target,this,Affect.NO_EFFECT,additionAffectCheckCode,Affect.NO_EFFECT,null);
if(mob.location().okAffect(msg))
{
mob.location().send(mob,msg);
ok=(!msg.wasModified());
}
else
ok=false;
}
if(ok)
{
invoker=mob;
Ability newOne=(Ability)this.copyOf();
if(tickAdjustmentFromStandard<=0)
{
tickAdjustmentFromStandard=(mob.envStats().level()*3)+15;
if(target!=null)
tickAdjustmentFromStandard-=(target.envStats().level()*2);
if(tickAdjustmentFromStandard<5)
tickAdjustmentFromStandard=5;
}
newOne.startTickDown(target,tickAdjustmentFromStandard);
}
return ok;
}
public boolean beneficialWordsFizzle(MOB mob,
Environmental target,
String message)
{
// it didn't work, but tell everyone you tried.
FullMsg msg=new FullMsg(mob,target,this,Affect.MSG_SPEAK,message);
if(mob.location().okAffect(msg))
mob.location().send(mob,msg);
return false;
}
public boolean beneficialVisualFizzle(MOB mob,
Environmental target,
String message)
{
// it didn't work, but tell everyone you tried.
FullMsg msg=new FullMsg(mob,target,this,Affect.MSG_OK_VISUAL,message);
if(mob.location().okAffect(msg))
mob.location().send(mob,msg);
return false;
}
public boolean maliciousFizzle(MOB mob,
Environmental target,
String message)
{
// it didn't work, but tell everyone you tried.
FullMsg msg=new FullMsg(mob,target,this,Affect.MSG_OK_VISUAL|Affect.MASK_MALICIOUS,message);
if(mob.location().okAffect(msg))
mob.location().send(mob,msg);
return false;
}
public boolean beneficialAffect(MOB mob,
Environmental target,
int tickAdjustmentFromStandard)
{
boolean ok=true;
if(ok)
{
invoker=mob;
Ability newOne=(Ability)this.copyOf();
if(tickAdjustmentFromStandard<=0)
tickAdjustmentFromStandard=(mob.envStats().level()*3)+30;
newOne.startTickDown(target,tickAdjustmentFromStandard);
}
return ok;
}
public boolean autoInvocation(MOB mob)
{
if(isAutoinvoked)
{
if(mob.envStats().level()>=envStats().level())
{
Ability thisAbility=mob.fetchAffect(this.ID());
if(thisAbility!=null)
return false;
Ability thatAbility=(Ability)this.copyOf();
mob.addAffect(thatAbility);
return true;
}
}
return false;
}
public void makeNonUninvokable()
{
unInvoked=false;
canBeUninvoked=false;
}
public String accountForYourself(){return name;}
public boolean canBeTaughtBy(MOB teacher, MOB student)
{
Ability yourAbility=teacher.fetchAbility(ID());
if(yourAbility!=null)
{
if(yourAbility.profficiency()<25)
{
teacher.tell("You are not profficient enough to teach '"+ID()+"'");
student.tell(teacher.name()+" is not profficient enough to teach '"+ID()+"'.");
return false;
}
return true;
}
teacher.tell("You don't know '"+name()+"'.");
student.tell(teacher.name()+" doesn't know '"+name()+"'.");
return false;
}
public boolean canBeLearnedBy(MOB teacher, MOB student)
{
if(student.getPractices()<=0)
{
teacher.tell(student.name()+" does not have enough practices to learn '"+name()+"'.");
student.tell("You do not have any practices.");
return false;
}
if(student.getTrains()<=0)
{
teacher.tell(student.name()+" does not have enough training points to learn '"+name()+"'.");
student.tell("You do not have any training points.");
return false;
}
int qLevel=qualifyingLevel(student);
if(qLevel<0)
{
teacher.tell(student.name()+" is not the right class to learn '"+name()+"'.");
student.tell("You are not the right class to learn '"+name()+"'.");
return false;
}
if((qLevel>student.envStats().level()))
{
teacher.tell(student.name()+" is not high enough level to learn '"+name()+"'.");
student.tell("You are not high enough level to learn '"+name()+"'.");
return false;
}
if(qLevel>student.charStats().getIntelligence()+7)
{
teacher.tell(student.name()+" is too stupid to learn '"+name()+"'.");
student.tell("You are not of high enough intelligence to learn '"+name()+"'.");
return false;
}
Ability yourAbility=student.fetchAbility(ID());
Ability teacherAbility=teacher.fetchAbility(ID());
if(yourAbility!=null)
{
teacher.tell(student.name()+" already knows '"+name()+"'.");
student.tell("You already know '"+name()+"'.");
return false;
}
if(teacherAbility!=null)
{
if(teacherAbility.profficiency()<25)
{
teacher.tell("You aren't profficient enough to teach '"+name()+"'.");
student.tell(teacher.name()+" isn't profficient enough to teach you '"+name()+"'.");
return false;
}
}
else
{
student.tell(teacher.name()+" does not know anything about that.");
teacher.tell("You don't know that.");
return false;
}
return true;
}
public boolean canBePracticedBy(MOB teacher, MOB student)
{
if(student.getPractices()==0)
{
teacher.tell(student.name()+" does not have enough practices to practice '"+name()+"'.");
student.tell("You do not have any practices.");
return false;
}
Ability yourAbility=student.fetchAbility(ID());
Ability teacherAbility=teacher.fetchAbility(ID());
if((yourAbility==null)||(yourAbility.qualifyingLevel(student)<0))
{
teacher.tell(student.name()+" has not learned '"+name()+"' yet.");
student.tell("You havn't learned '"+name()+"' yet.");
return false;
}
if(yourAbility.qualifyingLevel(student)>student.envStats().level())
{
teacher.tell(student.name()+" is not high enough level to practice '"+name()+"'.");
student.tell("You are not high enough level to practice '"+name()+"'.");
return false;
}
if(teacherAbility==null)
{
student.tell(teacher.name()+" does not know anything about '"+name()+"'.");
teacher.tell("You don't know '"+name()+"'.");
return false;
}
if(yourAbility.profficiency()>teacherAbility.profficiency())
{
teacher.tell("You aren't profficient enough to teach any more about '"+name()+"'.");
student.tell(teacher.name()+" isn't profficient enough to teach any more about '"+name()+"'.");
return false;
}
else
if(yourAbility.profficiency()>74)
{
teacher.tell("You can't teach "+student.charStats().himher()+" any more about '"+name()+"'.");
student.tell("You can't learn any more about '"+name()+"' except through dilligence.");
return false;
}
if(teacherAbility.profficiency()<25)
{
teacher.tell("You aren't profficient enough to teach '"+name()+"'.");
student.tell(teacher.name()+" isn't profficient enough to teach you '"+name()+"'.");
return false;
}
return true;
}
public void teach(MOB teacher, MOB student)
{
if(student.getPractices()==0)
return;
if(student.getTrains()==0)
return;
if(student.fetchAbility(ID())==null)
{
student.setPractices(student.getPractices()-1);
student.setTrains(student.getTrains()-1);
Ability newAbility=(Ability)newInstance();
newAbility.setProfficiency((int)Math.round(Util.mul(profficiency(),((Util.div(teacher.charStats().getWisdom()+student.charStats().getIntelligence(),100.0))))));
if(newAbility.profficiency()>75)
newAbility.setProfficiency(75);
int qLevel=qualifyingLevel(student);
if(qLevel<1) qLevel=1;
newAbility.envStats().setLevel(qLevel);
student.addAbility(newAbility);
newAbility.autoInvocation(student);
}
}
public void practice(MOB teacher, MOB student)
{
if(student.getPractices()==0)
return;
Ability yourAbility=student.fetchAbility(ID());
if(yourAbility!=null)
{
if(yourAbility.profficiency()<75)
{
student.setPractices(student.getPractices()-1);
yourAbility.setProfficiency(yourAbility.profficiency()+(int)Math.round(25.0*(Util.div(teacher.charStats().getWisdom()+student.charStats().getIntelligence(),36.0))));
if(yourAbility.profficiency()>75)
yourAbility.setProfficiency(75);
}
}
}
public void makeLongLasting()
{
tickDown=Integer.MAX_VALUE;
}
public int quality(){return this.quality;}
/** this method defines how this thing responds
* to environmental changes. It may handle any
* and every affect listed in the Affect class
* from the given Environmental source */
public void affect(Affect affect)
{
return;
}
/** this method is used to tell the system whether
* a PENDING affect may take place
*/
public boolean okAffect(Affect affect)
{
return true;
}
/**
* this method allows any environmental object
* to behave according to a timed response. by
* default, it will never be called unless the
* object uses the ServiceEngine to setup service.
* The tickID allows granularity with the type
* of service being requested.
*/
public boolean tick(int tickID)
{
if((unInvoked)&&(canBeUninvoked))
return false;
if((tickID==Host.MOB_TICK)
&&(tickDown!=Integer.MAX_VALUE))
{
if(tickDown<0)
return !unInvoked;
else
{
tickDown-=1;
if(tickDown<=0)
{
tickDown=-1;
this.unInvoke();
return false;
}
}
}
return true;
}
public boolean appropriateToMyAlignment(MOB mob){return true;}
public void addAffect(Ability to){}
public void addNonUninvokableAffect(Ability to){}
public void delAffect(Ability to){}
public int numAffects(){ return 0;}
public Ability fetchAffect(int index){return null;}
public Ability fetchAffect(String ID){return null;}
public void addBehavior(Behavior to){}
public void delBehavior(Behavior to){}
public int numBehaviors(){return 0;}
public Behavior fetchBehavior(int index){return null;}
public boolean isGeneric(){return false;}
}
|
package bisq.common.config;
import org.bitcoinj.core.NetworkParameters;
import joptsimple.AbstractOptionSpec;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.HelpFormatter;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import joptsimple.OptionSpecBuilder;
import joptsimple.util.PathConverter;
import joptsimple.util.PathProperties;
import joptsimple.util.RegexMatcher;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import ch.qos.logback.classic.Level;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static java.util.stream.Collectors.toList;
/**
* Parses and provides access to all Bisq configuration options specified at the command
* line and/or via the {@value DEFAULT_CONFIG_FILE_NAME} config file, including any
* default values. Constructing a {@link Config} instance is generally side-effect free,
* with one key exception being that {@value APP_DATA_DIR} and its subdirectories will
* be created if they do not already exist. Care is taken to avoid inadvertent creation or
* modification of the actual system user data directory and/or the production Bisq
* application data directory. Calling code must explicitly specify these values; they are
* never assumed.
* <p/>
* Note that this class deviates from typical JavaBean conventions in that fields
* representing configuration options are public and have no corresponding accessor
* ("getter") method. This is because all such fields are final and therefore not subject
* to modification by calling code and because eliminating the accessor methods means
* eliminating hundreds of lines of boilerplate code and one less touchpoint to deal with
* when adding or modifying options. Furthermore, while accessor methods are often useful
* when mocking an object in a testing context, this class is designed for testability
* without needing to be mocked. See {@code ConfigTests} for examples.
* @see #Config(String...)
* @see #Config(String, File, String...)
*/
public class Config {
// Option name constants
public static final String HELP = "help";
public static final String APP_NAME = "appName";
public static final String USER_DATA_DIR = "userDataDir";
public static final String APP_DATA_DIR = "appDataDir";
public static final String CONFIG_FILE = "configFile";
public static final String MAX_MEMORY = "maxMemory";
public static final String LOG_LEVEL = "logLevel";
public static final String BANNED_BTC_NODES = "bannedBtcNodes";
public static final String BANNED_PRICE_RELAY_NODES = "bannedPriceRelayNodes";
public static final String BANNED_SEED_NODES = "bannedSeedNodes";
public static final String BASE_CURRENCY_NETWORK = "baseCurrencyNetwork";
public static final String REFERRAL_ID = "referralId";
public static final String USE_DEV_MODE = "useDevMode";
public static final String TOR_DIR = "torDir";
public static final String STORAGE_DIR = "storageDir";
public static final String KEY_STORAGE_DIR = "keyStorageDir";
public static final String WALLET_DIR = "walletDir";
public static final String USE_DEV_PRIVILEGE_KEYS = "useDevPrivilegeKeys";
public static final String DUMP_STATISTICS = "dumpStatistics";
public static final String IGNORE_DEV_MSG = "ignoreDevMsg";
public static final String PROVIDERS = "providers";
public static final String SEED_NODES = "seedNodes";
public static final String BAN_LIST = "banList";
public static final String NODE_PORT = "nodePort";
public static final String USE_LOCALHOST_FOR_P2P = "useLocalhostForP2P";
public static final String MAX_CONNECTIONS = "maxConnections";
public static final String SOCKS_5_PROXY_BTC_ADDRESS = "socks5ProxyBtcAddress";
public static final String SOCKS_5_PROXY_HTTP_ADDRESS = "socks5ProxyHttpAddress";
public static final String USE_TOR_FOR_BTC = "useTorForBtc";
public static final String TORRC_FILE = "torrcFile";
public static final String TORRC_OPTIONS = "torrcOptions";
public static final String TOR_CONTROL_PORT = "torControlPort";
public static final String TOR_CONTROL_PASSWORD = "torControlPassword";
public static final String TOR_CONTROL_COOKIE_FILE = "torControlCookieFile";
public static final String TOR_CONTROL_USE_SAFE_COOKIE_AUTH = "torControlUseSafeCookieAuth";
public static final String TOR_STREAM_ISOLATION = "torStreamIsolation";
public static final String MSG_THROTTLE_PER_SEC = "msgThrottlePerSec";
public static final String MSG_THROTTLE_PER_10_SEC = "msgThrottlePer10Sec";
public static final String SEND_MSG_THROTTLE_TRIGGER = "sendMsgThrottleTrigger";
public static final String SEND_MSG_THROTTLE_SLEEP = "sendMsgThrottleSleep";
public static final String IGNORE_LOCAL_BTC_NODE = "ignoreLocalBtcNode";
public static final String BITCOIN_REGTEST_HOST = "bitcoinRegtestHost";
public static final String BTC_NODES = "btcNodes";
public static final String SOCKS5_DISCOVER_MODE = "socks5DiscoverMode";
public static final String USE_ALL_PROVIDED_NODES = "useAllProvidedNodes";
public static final String USER_AGENT = "userAgent";
public static final String NUM_CONNECTIONS_FOR_BTC = "numConnectionsForBtc";
public static final String RPC_USER = "rpcUser";
public static final String RPC_PASSWORD = "rpcPassword";
public static final String RPC_HOST = "rpcHost";
public static final String RPC_PORT = "rpcPort";
public static final String RPC_BLOCK_NOTIFICATION_PORT = "rpcBlockNotificationPort";
public static final String RPC_BLOCK_NOTIFICATION_HOST = "rpcBlockNotificationHost";
public static final String DUMP_BLOCKCHAIN_DATA = "dumpBlockchainData";
public static final String FULL_DAO_NODE = "fullDaoNode";
public static final String GENESIS_TX_ID = "genesisTxId";
public static final String GENESIS_BLOCK_HEIGHT = "genesisBlockHeight";
public static final String GENESIS_TOTAL_SUPPLY = "genesisTotalSupply";
public static final String DAO_ACTIVATED = "daoActivated";
public static final String DUMP_DELAYED_PAYOUT_TXS = "dumpDelayedPayoutTxs";
public static final String ALLOW_FAULTY_DELAYED_TXS = "allowFaultyDelayedTxs";
// Default values for certain options
public static final int UNSPECIFIED_PORT = -1;
public static final String DEFAULT_REGTEST_HOST = "localhost";
public static final int DEFAULT_NUM_CONNECTIONS_FOR_BTC = 9; // down from BitcoinJ default of 12
public static final boolean DEFAULT_FULL_DAO_NODE = false;
static final String DEFAULT_CONFIG_FILE_NAME = "bisq.properties";
// Static fields that provide access to Config properties in locations where injecting
// a Config instance is not feasible. See Javadoc for corresponding static accessors.
private static File APP_DATA_DIR_VALUE;
private static BaseCurrencyNetwork BASE_CURRENCY_NETWORK_VALUE = BaseCurrencyNetwork.BTC_MAINNET;
// Default "data dir properties", i.e. properties that can determine the location of
// Bisq's application data directory (appDataDir)
public final String defaultAppName;
public final File defaultUserDataDir;
public final File defaultAppDataDir;
public final File defaultConfigFile;
// Options supported only at the command-line interface (cli)
public final boolean helpRequested;
public final File configFile;
// Options supported both at the cli and in the config file
public final String appName;
public final File userDataDir;
public final File appDataDir;
public final int nodePort;
public final int maxMemory;
public final String logLevel;
public final List<String> bannedBtcNodes;
public final List<String> bannedPriceRelayNodes;
public final List<String> bannedSeedNodes;
public final BaseCurrencyNetwork baseCurrencyNetwork;
public final NetworkParameters baseCurrencyNetworkParameters;
public final boolean ignoreLocalBtcNode;
public final String bitcoinRegtestHost;
public final boolean daoActivated;
public final String referralId;
public final boolean useDevMode;
public final boolean useDevPrivilegeKeys;
public final boolean dumpStatistics;
public final boolean ignoreDevMsg;
public final List<String> providers;
public final List<String> seedNodes;
public final List<String> banList;
public final boolean useLocalhostForP2P;
public final int maxConnections;
public final String socks5ProxyBtcAddress;
public final String socks5ProxyHttpAddress;
public final File torrcFile;
public final String torrcOptions;
public final int torControlPort;
public final String torControlPassword;
public final File torControlCookieFile;
public final boolean useTorControlSafeCookieAuth;
public final boolean torStreamIsolation;
public final int msgThrottlePerSec;
public final int msgThrottlePer10Sec;
public final int sendMsgThrottleTrigger;
public final int sendMsgThrottleSleep;
public final String btcNodes;
public final boolean useTorForBtc;
public final boolean useTorForBtcOptionSetExplicitly;
public final String socks5DiscoverMode;
public final boolean useAllProvidedNodes;
public final String userAgent;
public final int numConnectionsForBtc;
public final String rpcUser;
public final String rpcPassword;
public final String rpcHost;
public final int rpcPort;
public final int rpcBlockNotificationPort;
public final String rpcBlockNotificationHost;
public final boolean dumpBlockchainData;
public final boolean fullDaoNode;
public final boolean fullDaoNodeOptionSetExplicitly;
public final String genesisTxId;
public final int genesisBlockHeight;
public final long genesisTotalSupply;
public final boolean dumpDelayedPayoutTxs;
public final boolean allowFaultyDelayedTxs;
// Properties derived from options but not exposed as options themselves
public final File torDir;
public final File walletDir;
public final File storageDir;
public final File keyStorageDir;
// The parser that will be used to parse both cli and config file options
private final OptionParser parser = new OptionParser();
/**
* Create a new {@link Config} instance using a randomly-generated default
* {@value APP_NAME} and a newly-created temporary directory as the default
* {@value USER_DATA_DIR} along with any command line arguments. This constructor is
* primarily useful in test code, where no references or modifications should be made
* to the actual system user data directory and/or real Bisq application data
* directory. Most production use cases will favor calling the
* {@link #Config(String, File, String...)} constructor directly.
* @param args zero or more command line arguments in the form "--optName=optValue"
* @throws ConfigException if any problems are encountered during option parsing
* @see #Config(String, File, String...)
*/
public Config(String... args) {
this(randomAppName(), tempUserDataDir(), args);
}
/**
* Create a new {@link Config} instance with the given default {@value APP_NAME} and
* {@value USER_DATA_DIR} values along with any command line arguments, typically
* those supplied via a Bisq application's main() method.
* <p/>
* This constructor performs all parsing of command line options and config file
* options, assuming the default config file exists or a custom config file has been
* specified via the {@value CONFIG_FILE} option and exists. For any options that
* are present both at the command line and in the config file, the command line value
* will take precedence. Note that the {@value HELP} and {@value CONFIG_FILE} options
* are supported only at the command line and are disallowed within the config file
* itself.
* @param defaultAppName typically "Bisq" or similar
* @param defaultUserDataDir typically the OS-specific user data directory location
* @param args zero or more command line arguments in the form "--optName=optValue"
* @throws ConfigException if any problems are encountered during option parsing
*/
public Config(String defaultAppName, File defaultUserDataDir, String... args) {
this.defaultAppName = defaultAppName;
this.defaultUserDataDir = defaultUserDataDir;
this.defaultAppDataDir = new File(defaultUserDataDir, defaultAppName);
this.defaultConfigFile = absoluteConfigFile(defaultAppDataDir, DEFAULT_CONFIG_FILE_NAME);
AbstractOptionSpec<Void> helpOpt =
parser.accepts(HELP, "Print this help text")
.forHelp();
ArgumentAcceptingOptionSpec<String> configFileOpt =
parser.accepts(CONFIG_FILE, format("Specify configuration file. " +
"Relative paths will be prefixed by %s location.", APP_DATA_DIR))
.withRequiredArg()
.ofType(String.class)
.defaultsTo(DEFAULT_CONFIG_FILE_NAME);
ArgumentAcceptingOptionSpec<String> appNameOpt =
parser.accepts(APP_NAME, "Application name")
.withRequiredArg()
.ofType(String.class)
.defaultsTo(this.defaultAppName);
ArgumentAcceptingOptionSpec<File> userDataDirOpt =
parser.accepts(USER_DATA_DIR, "User data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(this.defaultUserDataDir);
ArgumentAcceptingOptionSpec<File> appDataDirOpt =
parser.accepts(APP_DATA_DIR, "Application data directory")
.withRequiredArg()
.ofType(File.class)
.defaultsTo(defaultAppDataDir);
ArgumentAcceptingOptionSpec<Integer> nodePortOpt =
parser.accepts(NODE_PORT, "Port to listen on")
.withRequiredArg()
.ofType(Integer.class)
.defaultsTo(9999);
ArgumentAcceptingOptionSpec<Integer> maxMemoryOpt =
parser.accepts(MAX_MEMORY, "Max. permitted memory (used only by headless versions)")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(1200);
ArgumentAcceptingOptionSpec<String> logLevelOpt =
parser.accepts(LOG_LEVEL, "Set logging level")
.withRequiredArg()
.ofType(String.class)
.describedAs("OFF|ALL|ERROR|WARN|INFO|DEBUG|TRACE")
.defaultsTo(Level.INFO.levelStr);
ArgumentAcceptingOptionSpec<String> bannedBtcNodesOpt =
parser.accepts(BANNED_BTC_NODES, "List Bitcoin nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedPriceRelayNodesOpt =
parser.accepts(BANNED_PRICE_RELAY_NODES, "List Bisq price nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> bannedSeedNodesOpt =
parser.accepts(BANNED_SEED_NODES, "List Bisq seed nodes to ban")
.withRequiredArg()
.ofType(String.class)
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
//noinspection rawtypes
ArgumentAcceptingOptionSpec<Enum> baseCurrencyNetworkOpt =
parser.accepts(BASE_CURRENCY_NETWORK, "Base currency network")
.withRequiredArg()
.ofType(BaseCurrencyNetwork.class)
.withValuesConvertedBy(new EnumValueConverter(BaseCurrencyNetwork.class))
.defaultsTo(BaseCurrencyNetwork.BTC_MAINNET);
ArgumentAcceptingOptionSpec<Boolean> ignoreLocalBtcNodeOpt =
parser.accepts(IGNORE_LOCAL_BTC_NODE,
"If set to true a Bitcoin Core node running locally will be ignored")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> bitcoinRegtestHostOpt =
parser.accepts(BITCOIN_REGTEST_HOST, "Bitcoin Core node when using BTC_REGTEST network")
.withRequiredArg()
.ofType(String.class)
.describedAs("host[:port]")
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> referralIdOpt =
parser.accepts(REFERRAL_ID, "Optional Referral ID (e.g. for API users or pro market makers)")
.withRequiredArg()
.ofType(String.class)
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> useDevModeOpt =
parser.accepts(USE_DEV_MODE,
"Enables dev mode which is used for convenience for developer testing")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> useDevPrivilegeKeysOpt =
parser.accepts(USE_DEV_PRIVILEGE_KEYS, "If set to true all privileged features requiring a private " +
"key to be enabled are overridden by a dev key pair (This is for developers only!)")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> dumpStatisticsOpt =
parser.accepts(DUMP_STATISTICS, "If set to true dump trade statistics to a json file in appDataDir")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> ignoreDevMsgOpt =
parser.accepts(IGNORE_DEV_MSG, "If set to true all signed " +
"network_messages from bisq developers are ignored (Global " +
"alert, Version update alert, Filters for offers, nodes or " +
"trading account data)")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> providersOpt =
parser.accepts(PROVIDERS, "List custom pricenodes")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> seedNodesOpt =
parser.accepts(SEED_NODES, "Override hard coded seed nodes as comma separated list e.g. " +
"'rxdkppp3vicnbgqt.onion:8002,mfla72c4igh5ta2t.onion:8002'")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<String> banListOpt =
parser.accepts(BAN_LIST, "Nodes to exclude from network connections.")
.withRequiredArg()
.withValuesSeparatedBy(',')
.describedAs("host:port[,...]");
ArgumentAcceptingOptionSpec<Boolean> useLocalhostForP2POpt =
parser.accepts(USE_LOCALHOST_FOR_P2P, "Use localhost P2P network for development. Only available for non-BTC_MAINNET configuration.")
.availableIf(BASE_CURRENCY_NETWORK)
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Integer> maxConnectionsOpt =
parser.accepts(MAX_CONNECTIONS, "Max. connections a peer will try to keep")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(12);
ArgumentAcceptingOptionSpec<String> socks5ProxyBtcAddressOpt =
parser.accepts(SOCKS_5_PROXY_BTC_ADDRESS, "A proxy address to be used for Bitcoin network.")
.withRequiredArg()
.describedAs("host:port")
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> socks5ProxyHttpAddressOpt =
parser.accepts(SOCKS_5_PROXY_HTTP_ADDRESS,
"A proxy address to be used for Http requests (should be non-Tor)")
.withRequiredArg()
.describedAs("host:port")
.defaultsTo("");
ArgumentAcceptingOptionSpec<Path> torrcFileOpt =
parser.accepts(TORRC_FILE, "An existing torrc-file to be sourced for Tor. Note that torrc-entries, " +
"which are critical to Bisq's correct operation, cannot be overwritten.")
.withRequiredArg()
.describedAs("File")
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
ArgumentAcceptingOptionSpec<String> torrcOptionsOpt =
parser.accepts(TORRC_OPTIONS, "A list of torrc-entries to amend to Bisq's torrc. Note that " +
"torrc-entries, which are critical to Bisq's flawless operation, cannot be overwritten. " +
"[torrc options line, torrc option, ...]")
.withRequiredArg()
.withValuesConvertedBy(RegexMatcher.regex("^([^\\s,]+\\s[^,]+,?\\s*)+$"))
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> torControlPortOpt =
parser.accepts(TOR_CONTROL_PORT,
"The control port of an already running Tor service to be used by Bisq.")
.availableUnless(TORRC_FILE, TORRC_OPTIONS)
.withRequiredArg()
.ofType(int.class)
.describedAs("port")
.defaultsTo(UNSPECIFIED_PORT);
ArgumentAcceptingOptionSpec<String> torControlPasswordOpt =
parser.accepts(TOR_CONTROL_PASSWORD, "The password for controlling the already running Tor service.")
.availableIf(TOR_CONTROL_PORT)
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Path> torControlCookieFileOpt =
parser.accepts(TOR_CONTROL_COOKIE_FILE, "The cookie file for authenticating against the already " +
"running Tor service. Use in conjunction with --" + TOR_CONTROL_USE_SAFE_COOKIE_AUTH)
.availableIf(TOR_CONTROL_PORT)
.availableUnless(TOR_CONTROL_PASSWORD)
.withRequiredArg()
.describedAs("File")
.withValuesConvertedBy(new PathConverter(PathProperties.FILE_EXISTING, PathProperties.READABLE));
OptionSpecBuilder torControlUseSafeCookieAuthOpt =
parser.accepts(TOR_CONTROL_USE_SAFE_COOKIE_AUTH,
"Use the SafeCookie method when authenticating to the already running Tor service.")
.availableIf(TOR_CONTROL_COOKIE_FILE);
OptionSpecBuilder torStreamIsolationOpt =
parser.accepts(TOR_STREAM_ISOLATION, "Use stream isolation for Tor [experimental!].");
ArgumentAcceptingOptionSpec<Integer> msgThrottlePerSecOpt =
parser.accepts(MSG_THROTTLE_PER_SEC, "Message throttle per sec for connection class")
.withRequiredArg()
.ofType(int.class)
// With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 40MB/sec or 5 mbit/sec
.defaultsTo(200);
ArgumentAcceptingOptionSpec<Integer> msgThrottlePer10SecOpt =
parser.accepts(MSG_THROTTLE_PER_10_SEC, "Message throttle per 10 sec for connection class")
.withRequiredArg()
.ofType(int.class)
// With PERMITTED_MESSAGE_SIZE of 200kb results in bandwidth of 20MB/sec or 2.5 mbit/sec
.defaultsTo(1000);
ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleTriggerOpt =
parser.accepts(SEND_MSG_THROTTLE_TRIGGER, "Time in ms when we trigger a sleep if 2 messages are sent")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(20); // Time in ms when we trigger a sleep if 2 messages are sent
ArgumentAcceptingOptionSpec<Integer> sendMsgThrottleSleepOpt =
parser.accepts(SEND_MSG_THROTTLE_SLEEP, "Pause in ms to sleep if we get too many messages to send")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(50); // Pause in ms to sleep if we get too many messages to send
ArgumentAcceptingOptionSpec<String> btcNodesOpt =
parser.accepts(BTC_NODES, "Custom nodes used for BitcoinJ as comma separated IP addresses.")
.withRequiredArg()
.describedAs("ip[,...]")
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> useTorForBtcOpt =
parser.accepts(USE_TOR_FOR_BTC, "If set to true BitcoinJ is routed over tor (socks 5 proxy).")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> socks5DiscoverModeOpt =
parser.accepts(SOCKS5_DISCOVER_MODE, "Specify discovery mode for Bitcoin nodes. " +
"One or more of: [ADDR, DNS, ONION, ALL] (comma separated, they get OR'd together).")
.withRequiredArg()
.describedAs("mode[,...]")
.defaultsTo("ALL");
ArgumentAcceptingOptionSpec<Boolean> useAllProvidedNodesOpt =
parser.accepts(USE_ALL_PROVIDED_NODES,
"Set to true if connection of bitcoin nodes should include clear net nodes")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<String> userAgentOpt =
parser.accepts(USER_AGENT,
"User agent at btc node connections")
.withRequiredArg()
.defaultsTo("Bisq");
ArgumentAcceptingOptionSpec<Integer> numConnectionsForBtcOpt =
parser.accepts(NUM_CONNECTIONS_FOR_BTC, "Number of connections to the Bitcoin network")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(DEFAULT_NUM_CONNECTIONS_FOR_BTC);
ArgumentAcceptingOptionSpec<String> rpcUserOpt =
parser.accepts(RPC_USER, "Bitcoind rpc username")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> rpcPasswordOpt =
parser.accepts(RPC_PASSWORD, "Bitcoind rpc password")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<String> rpcHostOpt =
parser.accepts(RPC_HOST, "Bitcoind rpc host")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> rpcPortOpt =
parser.accepts(RPC_PORT, "Bitcoind rpc port")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(UNSPECIFIED_PORT);
ArgumentAcceptingOptionSpec<Integer> rpcBlockNotificationPortOpt =
parser.accepts(RPC_BLOCK_NOTIFICATION_PORT, "Bitcoind rpc port for block notifications")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(UNSPECIFIED_PORT);
ArgumentAcceptingOptionSpec<String> rpcBlockNotificationHostOpt =
parser.accepts(RPC_BLOCK_NOTIFICATION_HOST,
"Bitcoind rpc accepted incoming host for block notifications")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Boolean> dumpBlockchainDataOpt =
parser.accepts(DUMP_BLOCKCHAIN_DATA, "If set to true the blockchain data " +
"from RPC requests to Bitcoin Core are stored as json file in the data dir.")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> fullDaoNodeOpt =
parser.accepts(FULL_DAO_NODE, "If set to true the node requests the blockchain data via RPC requests " +
"from Bitcoin Core and provide the validated BSQ txs to the network. It requires that the " +
"other RPC properties are set as well.")
.withRequiredArg()
.ofType(Boolean.class)
.defaultsTo(DEFAULT_FULL_DAO_NODE);
ArgumentAcceptingOptionSpec<String> genesisTxIdOpt =
parser.accepts(GENESIS_TX_ID, "Genesis transaction ID when not using the hard coded one")
.withRequiredArg()
.defaultsTo("");
ArgumentAcceptingOptionSpec<Integer> genesisBlockHeightOpt =
parser.accepts(GENESIS_BLOCK_HEIGHT,
"Genesis transaction block height when not using the hard coded one")
.withRequiredArg()
.ofType(int.class)
.defaultsTo(-1);
ArgumentAcceptingOptionSpec<Long> genesisTotalSupplyOpt =
parser.accepts(GENESIS_TOTAL_SUPPLY, "Genesis total supply when not using the hard coded one")
.withRequiredArg()
.ofType(long.class)
.defaultsTo(-1L);
ArgumentAcceptingOptionSpec<Boolean> daoActivatedOpt =
parser.accepts(DAO_ACTIVATED, "Developer flag. If true it enables dao phase 2 features.")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(true);
ArgumentAcceptingOptionSpec<Boolean> dumpDelayedPayoutTxsOpt =
parser.accepts(DUMP_DELAYED_PAYOUT_TXS, "Dump delayed payout transactions to file")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
ArgumentAcceptingOptionSpec<Boolean> allowFaultyDelayedTxsOpt =
parser.accepts(ALLOW_FAULTY_DELAYED_TXS, "Allow completion of trades with faulty delayed " +
"payout transactions")
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(false);
try {
CompositeOptionSet options = new CompositeOptionSet();
// Parse command line options
OptionSet cliOpts = parser.parse(args);
options.addOptionSet(cliOpts);
// Option parsing is strict at the command line, but we relax it now for any
// subsequent config file processing. This is for compatibility with pre-1.2.6
// versions that allowed unrecognized options in the bisq.properties config
// file and because it follows suit with Bitcoin Core's config file behavior.
parser.allowsUnrecognizedOptions();
// Parse config file specified at the command line only if it was specified as
// an absolute path. Otherwise, the config file will be processed later below.
File configFile = null;
OptionSpec<?>[] disallowedOpts = new OptionSpec<?>[]{helpOpt, configFileOpt};
final boolean cliHasConfigFileOpt = cliOpts.has(configFileOpt);
boolean configFileHasBeenProcessed = false;
if (cliHasConfigFileOpt) {
configFile = new File(cliOpts.valueOf(configFileOpt));
if (configFile.isAbsolute()) {
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, disallowedOpts);
if (configFileOpts.isPresent()) {
options.addOptionSet(configFileOpts.get());
configFileHasBeenProcessed = true;
}
}
}
// Assign values to the following "data dir properties". If a
// relatively-pathed config file was specified at the command line, any
// entries it has for these options will be ignored, as it has not been
// processed yet.
this.appName = options.valueOf(appNameOpt);
this.userDataDir = options.valueOf(userDataDirOpt);
this.appDataDir = mkAppDataDir(options.has(appDataDirOpt) ?
options.valueOf(appDataDirOpt) :
new File(userDataDir, appName));
// If the config file has not yet been processed, either because a relative
// path was provided at the command line, or because no value was provided at
// the command line, attempt to process the file now, falling back to the
// default config file location if none was specified at the command line.
if (!configFileHasBeenProcessed) {
configFile = cliHasConfigFileOpt && !configFile.isAbsolute() ?
absoluteConfigFile(appDataDir, configFile.getPath()) :
absoluteConfigFile(appDataDir, DEFAULT_CONFIG_FILE_NAME);
Optional<OptionSet> configFileOpts = parseOptionsFrom(configFile, disallowedOpts);
configFileOpts.ifPresent(options::addOptionSet);
}
// Assign all remaining properties, with command line options taking
// precedence over those provided in the config file (if any)
this.helpRequested = options.has(helpOpt);
this.configFile = configFile;
this.nodePort = options.valueOf(nodePortOpt);
this.maxMemory = options.valueOf(maxMemoryOpt);
this.logLevel = options.valueOf(logLevelOpt);
this.bannedBtcNodes = options.valuesOf(bannedBtcNodesOpt);
this.bannedPriceRelayNodes = options.valuesOf(bannedPriceRelayNodesOpt);
this.bannedSeedNodes = options.valuesOf(bannedSeedNodesOpt);
this.baseCurrencyNetwork = (BaseCurrencyNetwork) options.valueOf(baseCurrencyNetworkOpt);
this.baseCurrencyNetworkParameters = baseCurrencyNetwork.getParameters();
this.ignoreLocalBtcNode = options.valueOf(ignoreLocalBtcNodeOpt);
this.bitcoinRegtestHost = options.valueOf(bitcoinRegtestHostOpt);
this.torrcFile = options.has(torrcFileOpt) ? options.valueOf(torrcFileOpt).toFile() : null;
this.torrcOptions = options.valueOf(torrcOptionsOpt);
this.torControlPort = options.valueOf(torControlPortOpt);
this.torControlPassword = options.valueOf(torControlPasswordOpt);
this.torControlCookieFile = options.has(torControlCookieFileOpt) ?
options.valueOf(torControlCookieFileOpt).toFile() : null;
this.useTorControlSafeCookieAuth = options.has(torControlUseSafeCookieAuthOpt);
this.torStreamIsolation = options.has(torStreamIsolationOpt);
this.referralId = options.valueOf(referralIdOpt);
this.useDevMode = options.valueOf(useDevModeOpt);
this.useDevPrivilegeKeys = options.valueOf(useDevPrivilegeKeysOpt);
this.dumpStatistics = options.valueOf(dumpStatisticsOpt);
this.ignoreDevMsg = options.valueOf(ignoreDevMsgOpt);
this.providers = options.valuesOf(providersOpt);
this.seedNodes = options.valuesOf(seedNodesOpt);
this.banList = options.valuesOf(banListOpt);
this.useLocalhostForP2P = this.baseCurrencyNetwork.isMainnet() ? false : options.valueOf(useLocalhostForP2POpt);
this.maxConnections = options.valueOf(maxConnectionsOpt);
this.socks5ProxyBtcAddress = options.valueOf(socks5ProxyBtcAddressOpt);
this.socks5ProxyHttpAddress = options.valueOf(socks5ProxyHttpAddressOpt);
this.msgThrottlePerSec = options.valueOf(msgThrottlePerSecOpt);
this.msgThrottlePer10Sec = options.valueOf(msgThrottlePer10SecOpt);
this.sendMsgThrottleTrigger = options.valueOf(sendMsgThrottleTriggerOpt);
this.sendMsgThrottleSleep = options.valueOf(sendMsgThrottleSleepOpt);
this.btcNodes = options.valueOf(btcNodesOpt);
this.useTorForBtc = options.valueOf(useTorForBtcOpt);
this.useTorForBtcOptionSetExplicitly = options.has(useTorForBtcOpt);
this.socks5DiscoverMode = options.valueOf(socks5DiscoverModeOpt);
this.useAllProvidedNodes = options.valueOf(useAllProvidedNodesOpt);
this.userAgent = options.valueOf(userAgentOpt);
this.numConnectionsForBtc = options.valueOf(numConnectionsForBtcOpt);
this.rpcUser = options.valueOf(rpcUserOpt);
this.rpcPassword = options.valueOf(rpcPasswordOpt);
this.rpcHost = options.valueOf(rpcHostOpt);
this.rpcPort = options.valueOf(rpcPortOpt);
this.rpcBlockNotificationPort = options.valueOf(rpcBlockNotificationPortOpt);
this.rpcBlockNotificationHost = options.valueOf(rpcBlockNotificationHostOpt);
this.dumpBlockchainData = options.valueOf(dumpBlockchainDataOpt);
this.fullDaoNode = options.valueOf(fullDaoNodeOpt);
this.fullDaoNodeOptionSetExplicitly = options.has(fullDaoNodeOpt);
this.genesisTxId = options.valueOf(genesisTxIdOpt);
this.genesisBlockHeight = options.valueOf(genesisBlockHeightOpt);
this.genesisTotalSupply = options.valueOf(genesisTotalSupplyOpt);
this.daoActivated = options.valueOf(daoActivatedOpt);
this.dumpDelayedPayoutTxs = options.valueOf(dumpDelayedPayoutTxsOpt);
this.allowFaultyDelayedTxs = options.valueOf(allowFaultyDelayedTxsOpt);
} catch (OptionException ex) {
throw new ConfigException("problem parsing option '%s': %s",
ex.options().get(0),
ex.getCause() != null ?
ex.getCause().getMessage() :
ex.getMessage());
}
// Create all appDataDir subdirectories and assign to their respective properties
File btcNetworkDir = mkdir(appDataDir, baseCurrencyNetwork.name().toLowerCase());
this.keyStorageDir = mkdir(btcNetworkDir, "keys");
this.storageDir = mkdir(btcNetworkDir, "db");
this.torDir = mkdir(btcNetworkDir, "tor");
this.walletDir = mkdir(btcNetworkDir, "wallet");
// Assign values to special-case static fields
APP_DATA_DIR_VALUE = appDataDir;
BASE_CURRENCY_NETWORK_VALUE = baseCurrencyNetwork;
}
private static File absoluteConfigFile(File parentDir, String relativeConfigFilePath) {
return new File(parentDir, relativeConfigFilePath);
}
private Optional<OptionSet> parseOptionsFrom(File configFile, OptionSpec<?>[] disallowedOpts) {
if (!configFile.exists()) {
if (!configFile.equals(absoluteConfigFile(appDataDir, DEFAULT_CONFIG_FILE_NAME)))
throw new ConfigException("The specified config file '%s' does not exist.", configFile);
return Optional.empty();
}
ConfigFileReader configFileReader = new ConfigFileReader(configFile);
String[] optionLines = configFileReader.getOptionLines().stream()
.map(o -> "--" + o) // prepend dashes expected by jopt parser below
.collect(toList())
.toArray(new String[]{});
OptionSet configFileOpts = parser.parse(optionLines);
for (OptionSpec<?> disallowedOpt : disallowedOpts)
if (configFileOpts.has(disallowedOpt))
throw new ConfigException("The '%s' option is disallowed in config files",
disallowedOpt.options().get(0));
return Optional.of(configFileOpts);
}
public void printHelp(OutputStream sink, HelpFormatter formatter) {
try {
parser.formatHelpWith(formatter);
parser.printHelpOn(sink);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private static String randomAppName() {
try {
File file = Files.createTempFile("Bisq", "Temp").toFile();
file.delete();
return file.toPath().getFileName().toString();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private static File tempUserDataDir() {
try {
return Files.createTempDirectory("BisqTempUserData").toFile();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
/**
* Creates {@value APP_DATA_DIR} including any nonexistent parent directories. Does
* nothing if the directory already exists.
* @return the given directory, now guaranteed to exist
*/
private static File mkAppDataDir(File dir) {
if (!dir.exists()) {
try {
Files.createDirectories(dir.toPath());
} catch (IOException ex) {
throw new UncheckedIOException(format("Application data directory '%s' could not be created", dir), ex);
}
}
return dir;
}
/**
* Creates child directory assuming parent directories already exist. Does nothing if
* the directory already exists.
* @return the child directory, now guaranteed to exist
*/
private static File mkdir(File parent, String child) {
File dir = new File(parent, child);
if (!dir.exists()) {
try {
Files.createDirectory(dir.toPath());
} catch (IOException ex) {
throw new UncheckedIOException(format("Directory '%s' could not be created", dir), ex);
}
}
return dir;
}
/**
* Static accessor that returns the same value as the non-static
* {@link #appDataDir} property. For use only in the {@code Overlay} class, where
* because of its large number of subclasses, injecting the Guice-managed
* {@link Config} class is not worth the effort. {@link #appDataDir} should be
* favored in all other cases.
* @throws NullPointerException if the static value has not yet been assigned, i.e. if
* the Guice-managed {@link Config} class has not yet been instantiated elsewhere.
* This should never be the case, as Guice wiring always happens before any
* {@code Overlay} class is instantiated.
*/
public static File appDataDir() {
return checkNotNull(APP_DATA_DIR_VALUE, "The static appDataDir has not yet " +
"been assigned. A Config instance must be instantiated (usually by " +
"Guice) before calling this method.");
}
/**
* Static accessor that returns either the default base currency network value of
* {@link BaseCurrencyNetwork#BTC_MAINNET} or the value assigned via the
* {@value BASE_CURRENCY_NETWORK} option. The non-static
* {@link #baseCurrencyNetwork} property should be favored whenever possible and
* this static accessor should be used only in code locations where it is infeasible
* or too cumbersome to inject the normal Guice-managed singleton {@link Config}
* instance.
*/
public static BaseCurrencyNetwork baseCurrencyNetwork() {
return BASE_CURRENCY_NETWORK_VALUE;
}
public static NetworkParameters baseCurrencyNetworkParameters() {
return BASE_CURRENCY_NETWORK_VALUE.getParameters();
}
}
|
package io.shardingsphere.proxy.transport.mysql.packet.handshake;
import org.junit.Before;
import org.junit.Test;
public class HandshakePacketTest {
@Before
public void setUp() throws Exception {
}
@Test
public void assertWrite() {
}
@Test
public void assertGetProtocolVersion() {
}
@Test
public void assertGetServerVersion() {
}
@Test
public void assertGetCapabilityFlagsLower() {
}
@Test
public void assertGetCharacterSet() {
}
@Test
public void assertGetStatusFlag() {
}
@Test
public void assertGetCapabilityFlagsUpper() {
}
@Test
public void assertGetSequenceId() {
}
@Test
public void assertGetConnectionId() {
}
@Test
public void assertGetAuthPluginData() {
}
}
|
package org.zstack.kvm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;
import org.zstack.compute.host.HostBase;
import org.zstack.compute.host.HostSystemTags;
import org.zstack.compute.host.MigrateNetworkExtensionPoint;
import org.zstack.compute.vm.IsoOperator;
import org.zstack.compute.vm.VmGlobalConfig;
import org.zstack.compute.vm.VmSystemTags;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.MessageCommandRecorder;
import org.zstack.core.Platform;
import org.zstack.core.ansible.AnsibleGlobalProperty;
import org.zstack.core.ansible.AnsibleRunner;
import org.zstack.core.ansible.SshFileMd5Checker;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.Constants;
import org.zstack.header.core.AsyncLatch;
import org.zstack.header.core.Completion;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy;
import org.zstack.header.image.ImagePlatform;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.network.l2.*;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.tag.SystemTagInventory;
import org.zstack.header.vm.*;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.header.volume.VolumeType;
import org.zstack.header.volume.VolumeVO;
import org.zstack.kvm.KVMAgentCommands.*;
import org.zstack.kvm.KVMConstant.KvmVmState;
import org.zstack.tag.SystemTagCreator;
import org.zstack.tag.TagManager;
import org.zstack.utils.*;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import org.zstack.utils.path.PathUtil;
import org.zstack.utils.ssh.Ssh;
import org.zstack.utils.ssh.SshResult;
import org.zstack.utils.ssh.SshShell;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.*;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
public class KVMHost extends HostBase implements Host {
private static final CLogger logger = Utils.getLogger(KVMHost.class);
@Autowired
@Qualifier("KVMHostFactory")
private KVMHostFactory factory;
@Autowired
private RESTFacade restf;
@Autowired
private KVMExtensionEmitter extEmitter;
@Autowired
private ErrorFacade errf;
@Autowired
private TagManager tagmgr;
@Autowired
private ApiTimeoutManager timeoutManager;
@Autowired
private PluginRegistry pluginRegistry;
private KVMHostContext context;
// ///////////////////// REST URL //////////////////////////
private String baseUrl;
private String connectPath;
private String pingPath;
private String checkPhysicalNetworkInterfacePath;
private String startVmPath;
private String stopVmPath;
private String pauseVmPath;
private String resumeVmPath;
private String rebootVmPath;
private String destroyVmPath;
private String attachDataVolumePath;
private String detachDataVolumePath;
private String echoPath;
private String attachNicPath;
private String detachNicPath;
private String migrateVmPath;
private String snapshotPath;
private String mergeSnapshotPath;
private String hostFactPath;
private String attachIsoPath;
private String detachIsoPath;
private String checkVmStatePath;
private String getConsolePortPath;
private String onlineIncreaseCpuPath;
private String onlineIncreaseMemPath;
private String deleteConsoleFirewall;
private String updateHostOSPath;
private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME;
KVMHost(KVMHostVO self, KVMHostContext context) {
super(self);
this.context = context;
baseUrl = context.getBaseUrl();
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONNECT_PATH);
connectPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PING_PATH);
pingPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH);
checkPhysicalNetworkInterfacePath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_VM_PATH);
startVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_STOP_VM_PATH);
stopVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PAUSE_VM_PATH);
pauseVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_RESUME_VM_PATH);
resumeVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REBOOT_VM_PATH);
rebootVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DESTROY_VM_PATH);
destroyVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_VOLUME);
attachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_VOLUME);
detachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ECHO_PATH);
echoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_NIC_PATH);
attachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_NIC_PATH);
detachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MIGRATE_VM_PATH);
migrateVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH);
snapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH);
mergeSnapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_FACT_PATH);
hostFactPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_ISO_PATH);
attachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_ISO_PATH);
detachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_CHECK_STATE);
checkVmStatePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH);
getConsolePortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_CPU);
onlineIncreaseCpuPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_MEMORY);
onlineIncreaseMemPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
deleteConsoleFirewall = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_OS_PATH);
updateHostOSPath = ub.build().toString();
}
class Http<T> {
String path;
AgentCommand cmd;
Class<T> responseClass;
String commandStr;
TimeUnit unit;
Long timeout;
public Http(String path, String cmd, Class<T> rspClz, TimeUnit unit, Long timeout) {
this.path = path;
this.commandStr = cmd;
this.responseClass = rspClz;
this.unit = unit;
this.timeout = timeout;
}
public Http(String path, AgentCommand cmd, Class<T> rspClz) {
this.path = path;
this.cmd = cmd;
this.responseClass = rspClz;
}
void call(ReturnValueCompletion<T> completion) {
call(null, completion);
}
void call(String resourceUuid, ReturnValueCompletion<T> completion) {
Map<String, String> header = new HashMap<>();
header.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, resourceUuid == null ? self.getUuid() : resourceUuid);
runBeforeAsyncJsonPostExts(header);
if (commandStr != null) {
restf.asyncJsonPost(path, commandStr, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
completion.success(ret);
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}, unit, timeout);
} else {
restf.asyncJsonPost(path, cmd, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
completion.success(ret);
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}); // DO NOT pass unit, timeout here, they are null
}
}
void runBeforeAsyncJsonPostExts(Map<String, String> header) {
if (commandStr == null) {
commandStr = JSONObjectUtil.toJsonString(cmd);
}
if (commandStr == null || commandStr.isEmpty()) {
logger.warn(String.format("commandStr is empty, path: %s, header: %s", path, header));
return;
}
LinkedHashMap commandMap = JSONObjectUtil.toObject(commandStr, LinkedHashMap.class);
LinkedHashMap kvmHostAddon = new LinkedHashMap();
for (KVMBeforeAsyncJsonPostExtensionPoint extp : pluginRegistry.getExtensionList(KVMBeforeAsyncJsonPostExtensionPoint.class)) {
LinkedHashMap tmpHashMap = extp.kvmBeforeAsyncJsonPostExtensionPoint(path, commandMap, header);
if (tmpHashMap != null && !tmpHashMap.isEmpty()) {
tmpHashMap.keySet().stream().forEachOrdered((key -> {
kvmHostAddon.put(key, tmpHashMap.get(key));
}));
}
}
unit = unit == null ? TimeUnit.MILLISECONDS : unit;
if (timeout == null) {
int defaultTimeout = CoreGlobalProperty.REST_FACADE_READ_TIMEOUT;
timeout = cmd == null ? defaultTimeout : timeoutManager.getTimeout(cmd.getClass(), defaultTimeout);
}
if (commandStr.equals("{}")) {
commandStr = commandStr.replaceAll("\\}$",
String.format("\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
} else {
commandStr = commandStr.replaceAll("\\}$",
String.format(",\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
}
}
}
@Override
protected void handleApiMessage(APIMessage msg) {
super.handleApiMessage(msg);
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof CheckNetworkPhysicalInterfaceMsg) {
handle((CheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof StartVmOnHypervisorMsg) {
handle((StartVmOnHypervisorMsg) msg);
} else if (msg instanceof CreateVmOnHypervisorMsg) {
handle((CreateVmOnHypervisorMsg) msg);
} else if (msg instanceof StopVmOnHypervisorMsg) {
handle((StopVmOnHypervisorMsg) msg);
} else if (msg instanceof RebootVmOnHypervisorMsg) {
handle((RebootVmOnHypervisorMsg) msg);
} else if (msg instanceof DestroyVmOnHypervisorMsg) {
handle((DestroyVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) {
handle((AttachVolumeToVmOnHypervisorMsg) msg);
} else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) {
handle((DetachVolumeFromVmOnHypervisorMsg) msg);
} else if (msg instanceof VmAttachNicOnHypervisorMsg) {
handle((VmAttachNicOnHypervisorMsg) msg);
} else if (msg instanceof MigrateVmOnHypervisorMsg) {
handle((MigrateVmOnHypervisorMsg) msg);
} else if (msg instanceof TakeSnapshotOnHypervisorMsg) {
handle((TakeSnapshotOnHypervisorMsg) msg);
} else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) {
handle((MergeVolumeSnapshotOnKvmMsg) msg);
} else if (msg instanceof KVMHostAsyncHttpCallMsg) {
handle((KVMHostAsyncHttpCallMsg) msg);
} else if (msg instanceof KVMHostSyncHttpCallMsg) {
handle((KVMHostSyncHttpCallMsg) msg);
} else if (msg instanceof DetachNicFromVmOnHypervisorMsg) {
handle((DetachNicFromVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachIsoOnHypervisorMsg) {
handle((AttachIsoOnHypervisorMsg) msg);
} else if (msg instanceof DetachIsoOnHypervisorMsg) {
handle((DetachIsoOnHypervisorMsg) msg);
} else if (msg instanceof CheckVmStateOnHypervisorMsg) {
handle((CheckVmStateOnHypervisorMsg) msg);
} else if (msg instanceof GetVmConsoleAddressFromHostMsg) {
handle((GetVmConsoleAddressFromHostMsg) msg);
} else if (msg instanceof KvmRunShellMsg) {
handle((KvmRunShellMsg) msg);
} else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) {
handle((VmDirectlyDestroyOnHypervisorMsg) msg);
} else if (msg instanceof IncreaseVmCpuMsg) {
handle((IncreaseVmCpuMsg) msg);
} else if (msg instanceof IncreaseVmMemoryMsg) {
handle((IncreaseVmMemoryMsg) msg);
} else if (msg instanceof PauseVmOnHypervisorMsg) {
handle((PauseVmOnHypervisorMsg) msg);
} else if (msg instanceof ResumeVmOnHypervisorMsg) {
handle((ResumeVmOnHypervisorMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
private void handle(final IncreaseVmCpuMsg msg) {
IncreaseVmCpuReply reply = new IncreaseVmCpuReply();
IncreaseCpuCmd cmd = new IncreaseCpuCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setCpuNum(msg.getCpuNum());
new Http<>(onlineIncreaseCpuPath, cmd, IncreaseCpuResponse.class).call(new ReturnValueCompletion<IncreaseCpuResponse>(msg) {
@Override
public void success(IncreaseCpuResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setCpuNum(ret.getCpuNum());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final IncreaseVmMemoryMsg msg) {
IncreaseVmMemoryReply reply = new IncreaseVmMemoryReply();
IncreaseMemoryCmd cmd = new IncreaseMemoryCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setMemorySize(msg.getMemorySize());
new Http<>(onlineIncreaseMemPath, cmd, IncreaseMemoryResponse.class).call(new ReturnValueCompletion<IncreaseMemoryResponse>(msg) {
@Override
public void success(IncreaseMemoryResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setMemorySize(ret.getMemorySize());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(msg.getVmUuid());
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(completion) {
@Override
public void success(DestroyVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
directlyDestroy(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid());
}
});
}
private SshResult runShell(String script) {
Ssh ssh = new Ssh();
ssh.setHostname(self.getManagementIp());
ssh.setPort(getSelf().getPort());
ssh.setUsername(getSelf().getUsername());
ssh.setPassword(getSelf().getPassword());
ssh.shell(script);
return ssh.runAndClose();
}
private void handle(KvmRunShellMsg msg) {
SshResult result = runShell(msg.getScript());
KvmRunShellReply reply = new KvmRunShellReply();
if (result.isSshFailure()) {
reply.setError(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," +
" please check if username/password is wrong; %s",
self.getManagementIp(), getSelf().getUsername(),
getSelf().getPort(), result.getExitErrorMessage()));
} else {
reply.setStdout(result.getStdout());
reply.setStderr(result.getStderr());
reply.setReturnCode(result.getReturnCode());
}
bus.reply(msg, reply);
}
private void handle(final GetVmConsoleAddressFromHostMsg msg) {
final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply();
GetVncPortCmd cmd = new GetVncPortCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
new Http<>(getConsolePortPath, cmd, GetVncPortResponse.class).call(new ReturnValueCompletion<GetVncPortResponse>(msg) {
@Override
public void success(GetVncPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setHostIp(self.getManagementIp());
reply.setProtocol(ret.getProtocol());
reply.setPort(ret.getPort());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final CheckVmStateOnHypervisorMsg msg) {
final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
// NOTE: don't run this message in the sync task
// there can be many such kind of messages
// running in the sync task may cause other tasks starved
CheckVmStateCmd cmd = new CheckVmStateCmd();
cmd.vmUuids = msg.getVmInstanceUuids();
cmd.hostUuid = self.getUuid();
new Http<>(checkVmStatePath, cmd, CheckVmStateRsp.class).call(new ReturnValueCompletion<CheckVmStateRsp>(msg) {
@Override
public void success(CheckVmStateRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
Map<String, String> m = new HashMap<>();
for (Map.Entry<String, String> e : ret.states.entrySet()) {
m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString());
}
reply.setStates(m);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final DetachIsoOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
detachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply();
DetachIsoCmd cmd = new DetachIsoCmd();
cmd.isoUuid = msg.getIsoUuid();
cmd.vmUuid = msg.getVmInstanceUuid();
cmd.deviceId = IsoOperator.getIsoDeviceId(msg.getVmInstanceUuid(), msg.getIsoUuid());
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) {
ext.preDetachIsoExtensionPoint(inv, cmd);
}
new Http<>(detachIsoPath, cmd, DetachIsoRsp.class).call(new ReturnValueCompletion<DetachIsoRsp>(msg, completion) {
@Override
public void success(DetachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachIsoOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
attachIso(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply();
IsoTO iso = new IsoTO();
iso.setImageUuid(msg.getIsoSpec().getImageUuid());
iso.setPath(msg.getIsoSpec().getInstallPath());
iso.setDeviceId(msg.getIsoSpec().getDeviceId());
AttachIsoCmd cmd = new AttachIsoCmd();
cmd.vmUuid = msg.getVmInstanceUuid();
cmd.iso = iso;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) {
ext.preAttachIsoExtensionPoint(inv, cmd);
}
new Http<>(attachIsoPath, cmd, AttachIsoRsp.class).call(new ReturnValueCompletion<AttachIsoRsp>(msg, completion) {
@Override
public void success(AttachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachNicFromVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
detachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return "detach-nic-on-kvm-host-" + self.getUuid();
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply();
NicTO to = completeNicInfo(msg.getNic());
DetachNicCommand cmd = new DetachNicCommand();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setNic(to);
new Http<>(detachNicPath, cmd, DetachNicRsp.class).call(new ReturnValueCompletion<DetachNicRsp>(msg, completion) {
@Override
public void success(DetachNicRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final KVMHostSyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
executeSyncHttpCall(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, self.getUuid());
LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), headers, LinkedHashMap.class);
KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply();
reply.setResponse(rsp);
bus.reply(msg, reply);
completion.done();
}
private void handle(final KVMHostAsyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
executeAsyncHttpCall(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private String buildUrl(String path) {
UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME);
ub.host(self.getManagementIp());
ub.port(KVMGlobalProperty.AGENT_PORT);
if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) {
ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH);
}
ub.path(path);
return ub.build().toUriString();
}
private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
new Http<>(url, msg.getCommand(), LinkedHashMap.class, TimeUnit.MILLISECONDS, msg.getCommandTimeout())
.call(new ReturnValueCompletion<LinkedHashMap>(msg, completion) {
@Override
public void success(LinkedHashMap ret) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
reply.setResponse(ret);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) {
reply.setError(errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "cannot do the operation on the KVM host", err));
} else {
reply.setError(err);
}
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final MergeVolumeSnapshotOnKvmMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply();
VolumeInventory volume = msg.getTo();
if (volume.getVmInstanceUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid());
VmInstanceState state = q.findValue();
if (state != VmInstanceState.Stopped && state != VmInstanceState.Running) {
throw new OperationFailureException(operr("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." +
" The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state));
}
if (state == VmInstanceState.Running) {
String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN);
if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) {
throw new OperationFailureException(operr("live volume snapshot merge needs libvirt version greater than %s," +
" current libvirt version is %s. Please stop vm and redo the operation or detach the volume if it's data volume",
KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion));
}
}
}
VolumeSnapshotInventory snapshot = msg.getFrom();
MergeSnapshotCmd cmd = new MergeSnapshotCmd();
cmd.setFullRebase(msg.isFullRebase());
cmd.setDestPath(volume.getInstallPath());
cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath());
cmd.setVmUuid(volume.getVmInstanceUuid());
cmd.setDeviceId(volume.getDeviceId());
extEmitter.beforeMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(mergeSnapshotPath, cmd, MergeSnapshotRsp.class)
.call(new ReturnValueCompletion<MergeSnapshotRsp>(msg, completion) {
@Override
public void success(MergeSnapshotRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
}
extEmitter.afterMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final TakeSnapshotOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
takeSnapshot(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("take-snapshot-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply();
TakeSnapshotCmd cmd = new TakeSnapshotCmd();
if (msg.getVmUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid());
VmInstanceState vmState = q.findValue();
if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) {
throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState));
}
if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) {
if (vmState != VmInstanceState.Stopped) {
throw new OperationFailureException(errf.instantiateErrorCode(SysErrors.NO_CAPABILITY_ERROR,
String.format("kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again",
self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid())
));
}
}
cmd.setVolumeUuid(msg.getVolume().getUuid());
cmd.setVmUuid(msg.getVmUuid());
cmd.setDeviceId(msg.getVolume().getDeviceId());
}
cmd.setVolumeInstallPath(msg.getVolume().getInstallPath());
cmd.setInstallPath(msg.getInstallPath());
cmd.setFullSnapshot(msg.isFullSnapshot());
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("before-take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
extEmitter.beforeTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
new Http<>(snapshotPath, cmd, TakeSnapshotResponse.class).call(new ReturnValueCompletion<TakeSnapshotResponse>(msg, trigger) {
@Override
public void success(TakeSnapshotResponse ret) {
if (ret.isSuccess()) {
extEmitter.afterTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, ret);
reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath());
reply.setSnapshotInstallPath(ret.getSnapshotInstallPath());
reply.setSize(ret.getSize());
} else {
ErrorCode err = operr("operation error, because:%s", ret.getError());
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, ret, err);
reply.setError(err);
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, null, errorCode);
reply.setError(errorCode);
trigger.fail(errorCode);
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
bus.reply(msg, reply);
completion.done();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
completion.done();
}
}).start();
}
private void migrateVm(final Iterator<MigrateStruct> it, final Completion completion) {
final String dstHostMigrateIp, dstHostMnIp, dstHostUuid;
final String vmUuid;
final StorageMigrationPolicy storageMigrationPolicy;
final boolean migrateFromDestination;
final String srcHostMigrateIp, srcHostMnIp, srcHostUuid;
synchronized (it) {
if (!it.hasNext()) {
completion.success();
return;
}
MigrateStruct s = it.next();
vmUuid = s.vmUuid;
dstHostMigrateIp = s.dstHostMigrateIp;
dstHostMnIp = s.dstHostMnIp;
dstHostUuid = s.dstHostUuid;
storageMigrationPolicy = s.storageMigrationPolicy;
migrateFromDestination = s.migrateFromDestition;
srcHostMigrateIp = s.srcHostMigrateIp;
srcHostMnIp = s.srcHostMnIp;
srcHostUuid = s.srcHostUuid;
}
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.internalId);
q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid);
final Long vmInternalId = q.findValue();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
MigrateVmCmd cmd = new MigrateVmCmd();
cmd.setDestHostIp(dstHostMigrateIp);
cmd.setSrcHostIp(srcHostMigrateIp);
cmd.setMigrateFromDestination(migrateFromDestination);
cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString());
cmd.setVmUuid(vmUuid);
cmd.setUseNuma(VmGlobalConfig.NUMA.value(Boolean.class));
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(migrateVmPath);
ub.host(migrateFromDestination ? dstHostMnIp : srcHostMnIp);
String migrateUrl = ub.build().toString();
new Http<>(migrateUrl, cmd, MigrateVmResponse.class).call(migrateFromDestination ? dstHostUuid : srcHostUuid, new ReturnValueCompletion<MigrateVmResponse>(trigger) {
@Override
public void success(MigrateVmResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = errf.instantiateErrorCode(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR,
String.format("failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s",
vmUuid, self.getUuid(), self.getManagementIp(), dstHostMigrateIp, ret.getError())
);
trigger.fail(err);
} else {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, self.getUuid(), self.getManagementIp(), dstHostMigrateIp);
logger.debug(info);
trigger.next();
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "harden-vm-console-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
HardenVmConsoleCmd cmd = new HardenVmConsoleCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = dstHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(dstHostUuid, new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
//TODO: add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, errorCode));
// continue
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vm-console-firewall-on-source-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = srcHostMnIp;
new Http<>(deleteConsoleFirewall, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, self.getUuid(), self.getManagementIp(), errorCode));
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, self.getUuid(), self.getManagementIp(), dstHostMigrateIp);
logger.debug(info);
migrateVm(it, completion);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final MigrateVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
migrateVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("migrate-vm-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
class MigrateStruct {
String vmUuid;
String dstHostMigrateIp;
String dstHostMnIp;
String dstHostUuid;
StorageMigrationPolicy storageMigrationPolicy;
boolean migrateFromDestition;
String srcHostMigrateIp;
String srcHostMnIp;
String srcHostUuid;
}
private MigrateStruct buildMigrateStuct(final MigrateVmOnHypervisorMsg msg){
MigrateStruct s = new MigrateStruct();
s.vmUuid = msg.getVmInventory().getUuid();
s.srcHostUuid = msg.getSrcHostUuid();
s.dstHostUuid = msg.getDestHostInventory().getUuid();
s.storageMigrationPolicy = msg.getStorageMigrationPolicy();
s.migrateFromDestition = msg.isMigrateFromDestination();
MigrateNetworkExtensionPoint.MigrateInfo migrateIpInfo = null;
for (MigrateNetworkExtensionPoint ext: pluginRgty.getExtensionList(MigrateNetworkExtensionPoint.class)) {
MigrateNetworkExtensionPoint.MigrateInfo r = ext.getMigrationAddressForVM(s.srcHostUuid, s.dstHostUuid);
if (r == null) {
continue;
}
migrateIpInfo = r;
}
s.dstHostMnIp = msg.getDestHostInventory().getManagementIp();
s.dstHostMigrateIp = migrateIpInfo == null ? s.dstHostMnIp : migrateIpInfo.dstMigrationAddress;
s.srcHostMnIp = Q.New(HostVO.class).eq(HostVO_.uuid, msg.getSrcHostUuid()).select(HostVO_.managementIp).findValue();
s.srcHostMigrateIp = migrateIpInfo == null ? s.srcHostMnIp : migrateIpInfo.srcMigrationAddress;
return s;
}
private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
List<MigrateStruct> lst = new ArrayList<>();
MigrateStruct s = buildMigrateStuct(msg);
lst.add(s);
final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply();
migrateVm(lst.iterator(), new Completion(msg, completion) {
@Override
public void success() {
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmAttachNicOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
attachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("attach-nic-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
NicTO to = completeNicInfo(msg.getNicInventory());
final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply();
AttachNicCommand cmd = new AttachNicCommand();
cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) {
ext.preAttachNicExtensionPoint(inv, cmd);
}
new Http<>(attachNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
detachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("detach-volume-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
VolumeTO to = new VolumeTO();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
to.setInstallPath(vol.getInstallPath());
if (vol.getDeviceId() != null) {
to.setDeviceId(vol.getDeviceId());
}
to.setDeviceType(getVolumeTOType(vol));
to.setVolumeUuid(vol.getUuid());
// volumes can only be attached on Windows if the virtio is enabled
// so for Windows, use virtio as well
to.setUseVirtio(ImagePlatform.Windows.toString().equals(vm.getPlatform()) ||
ImagePlatform.valueOf(vm.getPlatform()).isParaVirtualization());
to.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(vol.getUuid()));
to.setWwn(setVolumeWwn(vol.getUuid()));
to.setShareable(vol.isShareable());
final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply();
final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(vm.getUuid());
extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
new Http<>(detachDataVolumePath, cmd, DetachDataVolumeResponse.class).call(new ReturnValueCompletion<DetachDataVolumeResponse>(msg, completion) {
@Override
public void success(DetachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = operr("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s",
vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError());
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
} else {
extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err);
completion.done();
}
});
}
private void handle(final AttachVolumeToVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
attachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("attach-volume-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private String setVolumeWwn(String volumeUUid) {
String wwn;
String tag = KVMSystemTags.VOLUME_WWN.getTag(volumeUUid);
if (tag != null) {
wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(tag, KVMSystemTags.VOLUME_WWN_TOKEN);
} else {
SystemTagCreator creator = KVMSystemTags.VOLUME_WWN.newSystemTagCreator(volumeUUid);
creator.ignoreIfExisting = true;
creator.inherent = true;
creator.setTagByTokens(map(e(KVMSystemTags.VOLUME_WWN_TOKEN, new WwnUtils().getRandomWwn())));
SystemTagInventory inv = creator.create();
wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(inv.getTag(), KVMSystemTags.VOLUME_WWN_TOKEN);
}
DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid));
return wwn;
}
private String makeAndSaveVmSystemSerialNumber(String vmUuid) {
String serialNumber;
String tag = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTag(vmUuid);
if (tag != null) {
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(tag, VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
} else {
SystemTagCreator creator = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.newSystemTagCreator(vmUuid);
creator.ignoreIfExisting = true;
creator.inherent = true;
creator.setTagByTokens(map(e(VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN, UUID.randomUUID().toString())));
SystemTagInventory inv = creator.create();
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(inv.getTag(), VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
}
return serialNumber;
}
private void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
VolumeTO to = new VolumeTO();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
to.setInstallPath(vol.getInstallPath());
to.setDeviceId(vol.getDeviceId());
to.setDeviceType(getVolumeTOType(vol));
to.setVolumeUuid(vol.getUuid());
// volumes can only be attached on Windows if the virtio is enabled
// so for Windows, use virtio as well
to.setUseVirtio(ImagePlatform.Windows.toString().equals(vm.getPlatform()) ||
ImagePlatform.valueOf(vm.getPlatform()).isParaVirtualization());
to.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(vol.getUuid()));
to.setWwn(setVolumeWwn(vol.getUuid()));
to.setShareable(vol.isShareable());
to.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply();
final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(msg.getVmInventory().getUuid());
Map data = new HashMap();
extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd, data);
new Http<>(attachDataVolumePath, cmd, AttachDataVolumeResponse.class).call(new ReturnValueCompletion<AttachDataVolumeResponse>(msg, completion) {
@Override
public void success(AttachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" +
" on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(),
getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()));
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError(), data);
} else {
extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err, data);
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DestroyVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
destroyVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("destroy-vm-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
ErrorCode err = operr("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(vminv.getUuid());
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(msg, completion) {
@Override
public void success(DestroyVmResponse ret) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (!ret.isSuccess()) {
String err = String.format("unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError());
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, err));
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid()));
extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR, SysErrors.TIMEOUT)) {
err = errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to destroy a vm", err);
}
reply.setError(err);
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final RebootVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
rebootVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("reboot-vm-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private List<String> toKvmBootDev(List<String> order) {
List<String> ret = new ArrayList<String>();
for (String o : order) {
if (VmBootDevice.HardDisk.toString().equals(o)) {
ret.add(BootDev.hd.toString());
} else if (VmBootDevice.CdRom.toString().equals(o)) {
ret.add(BootDev.cdrom.toString());
} else {
throw new CloudRuntimeException(String.format("unknown boot device[%s]", o));
}
}
return ret;
}
private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
logger.warn(err, e);
throw new OperationFailureException(operr(err));
}
RebootVmCmd cmd = new RebootVmCmd();
long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout());
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(timeout);
cmd.setBootDev(toKvmBootDev(msg.getBootOrders()));
new Http<>(rebootVmPath, cmd, RebootVmResponse.class).call(new ReturnValueCompletion<RebootVmResponse>(msg, completion) {
@Override
public void success(RebootVmResponse ret) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
if (!ret.isSuccess()) {
String err = String.format("unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError());
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, err));
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
reply.setError(err);
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final StopVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
stopVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("stop-vm-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
ErrorCode err = operr("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
StopVmCmd cmd = new StopVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setType(msg.getType());
cmd.setTimeout(120);
new Http<>(stopVmPath, cmd, StopVmResponse.class).call(new ReturnValueCompletion<StopVmResponse>(msg, completion) {
@Override
public void success(StopVmResponse ret) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (!ret.isSuccess()) {
String err = String.format("unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError());
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err));
logger.warn(err);
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) {
err = errf.instantiateErrorCode(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, "unable to stop a vm", err);
}
reply.setError(err);
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
@Transactional
private void setDataVolumeUseVirtIOSCSI(final VmInstanceSpec spec) {
String vmUuid = spec.getVmInventory().getUuid();
Map<String, Integer> diskOfferingUuid_Num = new HashMap<>();
List<Map<String, String>> tokenList = KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI.getTokensOfTagsByResourceUuid(vmUuid);
for (Map<String, String> tokens : tokenList) {
String diskOfferingUuid = tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_TOKEN);
Integer num = Integer.parseInt(tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_NUM_TOKEN));
diskOfferingUuid_Num.put(diskOfferingUuid, num);
}
for (VolumeInventory volumeInv : spec.getDestDataVolumes()) {
if (volumeInv.getType().equals(VolumeType.Root.toString())) {
continue;
}
if (diskOfferingUuid_Num.containsKey(volumeInv.getDiskOfferingUuid())
&& diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) > 0) {
tagmgr.createNonInherentSystemTag(volumeInv.getUuid(),
KVMSystemTags.VOLUME_VIRTIO_SCSI.getTagFormat(),
VolumeVO.class.getSimpleName());
diskOfferingUuid_Num.put(volumeInv.getDiskOfferingUuid(),
diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) - 1);
}
}
}
private void handle(final CreateVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
setDataVolumeUseVirtIOSCSI(msg.getVmSpec());
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("start-vm-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
@Transactional
private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) {
String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)";
TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class);
query.setParameter("l3NetworkUuid", l3NetworkUuid);
L2NetworkVO l2vo = query.getSingleResult();
return L2NetworkInventory.valueOf(l2vo);
}
private NicTO completeNicInfo(VmNicInventory nic) {
L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid());
KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType()));
NicTO to = extp.completeNicInformation(l2inv, nic);
if (to.getUseVirtio() == null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.platform);
q.add(VmInstanceVO_.uuid, Op.EQ, nic.getVmInstanceUuid());
String platform = q.findValue();
to.setUseVirtio(ImagePlatform.valueOf(platform).isParaVirtualization());
if (!(nic.getIp().isEmpty() || nic.getIp() == null) && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class)) {
to.setIp(nic.getIp());
}
}
return to;
}
private String getVolumeTOType(VolumeInventory vol) {
return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE;
}
private void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final StartVmCmd cmd = new StartVmCmd();
boolean virtio;
String consoleMode;
String nestedVirtualization;
String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() :
spec.getVmInventory().getPlatform();
if (ImagePlatform.Windows.toString().equals(platform)) {
virtio = VmSystemTags.WINDOWS_VOLUME_ON_VIRTIO.hasTag(spec.getVmInventory().getUuid());
} else {
virtio = ImagePlatform.valueOf(platform).isParaVirtualization();
}
int cpuNum = spec.getVmInventory().getCpuNum();
cmd.setCpuNum(cpuNum);
int socket;
int cpuOnSocket;
//TODO: this is a HACK!!!
if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) {
if (cpuNum == 1) {
socket = 1;
cpuOnSocket = 1;
} else if (cpuNum % 2 == 0) {
socket = 2;
cpuOnSocket = cpuNum / 2;
} else {
socket = cpuNum;
cpuOnSocket = 1;
}
} else {
socket = 1;
cpuOnSocket = cpuNum;
}
cmd.setSocketNum(socket);
cmd.setCpuOnSocket(cpuOnSocket);
cmd.setVmName(spec.getVmInventory().getName());
cmd.setVmInstanceUuid(spec.getVmInventory().getUuid());
cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed());
cmd.setMemory(spec.getVmInventory().getMemorySize());
cmd.setMaxMemory(self.getCapacity().getTotalPhysicalMemory());
cmd.setUseVirtio(virtio);
cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc");
cmd.setVideoType(VmGlobalConfig.VM_VIDEO_TYPE.value(String.class));
cmd.setInstanceOfferingOnlineChange(VmSystemTags.INSTANCEOFFERING_ONLIECHANGE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN) != null);
cmd.setKvmHiddenState(VmGlobalConfig.KVM_HIDDEN_STATE.value(Boolean.class));
cmd.setSpiceStreamingMode(VmGlobalConfig.VM_SPICE_STREAMING_MODE.value(String.class));
cmd.setEmulateHyperV(VmGlobalConfig.EMULATE_HYPERV.value(Boolean.class));
cmd.setApplianceVm(spec.getVmInventory().getType().equals("ApplianceVm"));
cmd.setSystemSerialNumber(makeAndSaveVmSystemSerialNumber(spec.getVmInventory().getUuid()));
VolumeTO rootVolume = new VolumeTO();
rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath());
rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId());
rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume()));
rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid());
rootVolume.setUseVirtio(virtio);
rootVolume.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid()));
rootVolume.setWwn(setVolumeWwn(spec.getDestRootVolume().getUuid()));
rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
nestedVirtualization = KVMGlobalConfig.NESTED_VIRTUALIZATION.value(String.class);
cmd.setNestedVirtualization(nestedVirtualization);
cmd.setRootVolume(rootVolume);
cmd.setUseBootMenu(VmGlobalConfig.VM_BOOT_MENU.value(Boolean.class));
List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size());
for (VolumeInventory data : spec.getDestDataVolumes()) {
VolumeTO v = new VolumeTO();
v.setInstallPath(data.getInstallPath());
v.setDeviceId(data.getDeviceId());
v.setDeviceType(getVolumeTOType(data));
v.setVolumeUuid(data.getUuid());
// always use virtio driver for data volume
v.setUseVirtio(true);
v.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(data.getUuid()));
v.setWwn(setVolumeWwn(data.getUuid()));
v.setShareable(data.isShareable());
v.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
dataVolumes.add(v);
}
dataVolumes.sort(Comparator.comparing(VolumeTO::getDeviceId));
cmd.setDataVolumes(dataVolumes);
cmd.setVmInternalId(spec.getVmInventory().getInternalId());
List<NicTO> nics = new ArrayList<>(spec.getDestNics().size());
for (VmNicInventory nic : spec.getDestNics()) {
NicTO to = completeNicInfo(nic);
if (!spec.getVmInventory().getType().equals(VmInstanceConstant.USER_VM_TYPE) && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class)) {
to.setIp("");
}
nics.add(to);
}
nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList());
cmd.setNics(nics);
for (VmInstanceSpec.IsoSpec isoSpec : spec.getDestIsoList()) {
IsoTO bootIso = new IsoTO();
bootIso.setPath(isoSpec.getInstallPath());
bootIso.setImageUuid(isoSpec.getImageUuid());
bootIso.setDeviceId(IsoOperator.getIsoDeviceId(spec.getVmInventory().getUuid(), isoSpec.getImageUuid()));
cmd.getBootIso().add(bootIso);
}
cmd.setBootDev(toKvmBootDev(spec.getBootOrders()));
cmd.setHostManagementIp(self.getManagementIp());
cmd.setConsolePassword(spec.getConsolePassword());
cmd.setUsbRedirect(spec.getUsbRedirect());
cmd.setVDIMonitorNumber(Integer.valueOf(spec.getVDIMonitorNumber()));
cmd.setUseNuma(VmGlobalConfig.NUMA.value(Boolean.class));
cmd.setVmPortOff(VmGlobalConfig.VM_PORT_OFF.value(Boolean.class));
cmd.setConsoleMode("vnc");
cmd.setTimeout(TimeUnit.MINUTES.toSeconds(5));
if (spec.isCreatePaused()) {
cmd.setCreatePaused(true);
}
addons(spec, cmd);
KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf());
try {
extEmitter.beforeStartVmOnKvm(khinv, spec, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
extEmitter.addOn(khinv, spec, cmd);
new Http<>(startVmPath, cmd, StartVmResponse.class).call(new ReturnValueCompletion<StartVmResponse>(msg, completion) {
@Override
public void success(StartVmResponse ret) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
if (ret.isSuccess()) {
String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp());
logger.debug(info);
extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec);
} else {
String err = String.format("failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp(), ret.getError());
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, err));
logger.warn(err);
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
reply.setError(err);
reply.setSuccess(false);
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void addons(final VmInstanceSpec spec, StartVmCmd cmd) {
KVMAddons.Channel chan = new KVMAddons.Channel();
chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid()));
chan.setTargetName("org.qemu.guest_agent.0");
cmd.getAddons().put(KVMAddons.Channel.NAME, chan);
logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName()));
}
private String makeChannelSocketPath(String apvmuuid) {
return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid));
}
private void handle(final StartVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("start-vm-on-kvm-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void handle(final CheckNetworkPhysicalInterfaceMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
checkPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("check-network-physical-interface-on-host-%s", self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void pauseVm(final PauseVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply();
PauseVmCmd cmd = new PauseVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(pauseVmPath, cmd, PauseVmResponse.class).call(new ReturnValueCompletion<PauseVmResponse>(msg, completion) {
@Override
public void success(PauseVmResponse ret) {
if (!ret.isSuccess()) {
String err = String.format("unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError());
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err));
logger.warn(err);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final PauseVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
pauseVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("pause-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void handle(final ResumeVmOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(final SyncTaskChain chain) {
resumeVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
}
@Override
public String getName() {
return String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid());
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
});
}
private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply();
ResumeVmCmd cmd = new ResumeVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(resumeVmPath, cmd, ResumeVmResponse.class).call(new ReturnValueCompletion<ResumeVmResponse>(msg, completion) {
@Override
public void success(ResumeVmResponse ret) {
if (!ret.isSuccess()) {
String err = String.format("unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError());
reply.setError(errf.instantiateErrorCode(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, err));
logger.warn(err);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
cmd.addInterfaceName(msg.getPhysicalInterface());
CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("%s, failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
rsp.getError(), msg.getPhysicalInterface(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void handleMessage(Message msg) {
try {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
} catch (Exception e) {
bus.logExceptionWithMessageDump(msg, e);
bus.replyErrorByMessageType(msg, e);
}
}
@Override
public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) {
}
@Override
public void deleteHook() {
}
@Override
protected HostInventory getSelfInventory() {
return KVMHostInventory.valueOf(getSelf());
}
@Override
protected void pingHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("ping-kvm-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "ping-host";
@AfterDone
List<Runnable> afterDone = new ArrayList<>();
@Override
public void run(FlowTrigger trigger, Map data) {
PingCmd cmd = new PingCmd();
cmd.hostUuid = self.getUuid();
restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(PingResponse ret) {
if (ret.isSuccess()) {
if (!self.getUuid().equals(ret.getHostUuid())) {
afterDone.add(() -> {
String info = i18n("detected abnormal status[host uuid change, expected: %s but: %s] of kvmagent," +
"it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon", self.getUuid(), ret.getHostUuid());
logger.warn(info);
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
});
}
trigger.next();
} else {
trigger.fail(operr(ret.getError()));
}
}
@Override
public Class<PingResponse> getReturnClass() {
return PingResponse.class;
}
},TimeUnit.SECONDS, 60);
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-no-failure-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class);
if (exts.isEmpty()) {
trigger.next();
return;
}
AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
trigger.next();
}
});
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPingAgentNoFailureExtensionPoint ext : exts) {
ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) {
@Override
public void done() {
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class);
Iterator<KVMPingAgentExtensionPoint> it = exts.iterator();
callPlugin(it, trigger);
}
private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) {
if (!it.hasNext()) {
trigger.next();
return;
}
KVMPingAgentExtensionPoint ext = it.next();
logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass()));
ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) {
@Override
public void success() {
callPlugin(it, trigger);
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected int getVmMigrateQuantity() {
return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class);
}
private ErrorCode connectToAgent() {
ErrorCode errCode = null;
try {
ConnectCmd cmd = new ConnectCmd();
cmd.setHostUuid(self.getUuid());
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES);
ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class);
if (!rsp.isSuccess() || !rsp.isIptablesSucc()) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(), connectPath,
rsp.getError());
} else {
VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion());
VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion());
boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0
&& qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0;
String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN);
//liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class));
if (liveSnapshot) {
logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]",
hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion()));
SystemTagCreator creator = HostSystemTags.LIVE_SNAPSHOT.newSystemTagCreator(self.getUuid());
creator.recreate = true;
creator.create();
} else {
HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid());
}
}
} catch (RestClientException e) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(),
connectPath, e.getMessage());
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
errCode = errf.throwableToInternalError(t);
}
return errCode;
}
private KVMHostVO getSelf() {
return (KVMHostVO) self;
}
private void continueConnect(final boolean newAdded, final Completion completion) {
ErrorCode errCode = connectToAgent();
if (errCode != null) {
throw new OperationFailureException(errCode);
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid()));
for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) {
KVMHostConnectedContext ctx = new KVMHostConnectedContext();
ctx.setInventory((KVMHostInventory) getSelfInventory());
ctx.setNewAddedHost(newAdded);
chain.then(extp.createKvmHostConnectingFlow(ctx));
}
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
if (noStorageAccessible()){
completion.fail(operr("host can not access any primary storage, please check network"));
} else {
completion.success();
}
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
String err = String.format("connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(),
self.getManagementIp());
completion.fail(errf.instantiateErrorCode(HostErrors.CONNECTION_ERROR, err, errCode));
}
}).start();
}
@Transactional(readOnly = true)
private boolean noStorageAccessible(){
// detach ps will delete PrimaryStorageClusterRefVO first.
List<String> attachedPsUuids = Q.New(PrimaryStorageClusterRefVO.class)
.select(PrimaryStorageClusterRefVO_.primaryStorageUuid)
.eq(PrimaryStorageClusterRefVO_.clusterUuid, self.getClusterUuid())
.listValues();
long attachedPsCount = attachedPsUuids.size();
long inaccessiblePsCount = attachedPsCount == 0 ? 0 : Q.New(PrimaryStorageHostRefVO.class)
.eq(PrimaryStorageHostRefVO_.hostUuid, self.getUuid())
.eq(PrimaryStorageHostRefVO_.status, PrimaryStorageHostStatus.Disconnected)
.in(PrimaryStorageHostRefVO_.primaryStorageUuid, attachedPsUuids)
.count();
return inaccessiblePsCount == attachedPsCount && attachedPsCount > 0;
}
private void createHostVersionSystemTags(String distro, String release, String version) {
SystemTagCreator creator = HostSystemTags.OS_DISTRIBUTION.newSystemTagCreator(self.getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(HostSystemTags.OS_DISTRIBUTION_TOKEN, distro)));
creator.create();
creator = HostSystemTags.OS_RELEASE.newSystemTagCreator(self.getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(HostSystemTags.OS_RELEASE_TOKEN, release)));
creator.create();
creator = HostSystemTags.OS_VERSION.newSystemTagCreator(self.getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(HostSystemTags.OS_VERSION_TOKEN, version)));
creator.create();
}
@Override
public void connectHook(final ConnectHostInfo info, final Completion complete) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
if (info.isNewAdded()) {
SystemTagCreator creator;
createHostVersionSystemTags("zstack", "kvmSimulator", "0.1");
if (null == KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN)) {
creator = KVMSystemTags.LIBVIRT_VERSION.newSystemTagCreator(self.getUuid());
creator.inherent = true;
creator.setTagByTokens(map(e(KVMSystemTags.LIBVIRT_VERSION_TOKEN, "1.2.9")));
creator.create();
}
if (null == KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN)) {
creator = KVMSystemTags.QEMU_IMG_VERSION.newSystemTagCreator(self.getUuid());
creator.inherent = true;
creator.setTagByTokens(map(e(KVMSystemTags.QEMU_IMG_VERSION_TOKEN, "2.0.0")));
creator.create();
}
if (null == KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN)) {
creator = KVMSystemTags.CPU_MODEL_NAME.newSystemTagCreator(self.getUuid());
creator.setTagByTokens(map(e(KVMSystemTags.CPU_MODEL_NAME_TOKEN, "Broadwell")));
creator.inherent = true;
creator.create();
}
if (!checkQemuLibvirtVersionOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
}
continueConnect(info.isNewAdded(), complete);
} else {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
if (info.isNewAdded()) {
if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) {
flow(new NoRollbackFlow() {
String __name__ = "ping-DNS-check-list";
@Override
public void run(FlowTrigger trigger, Map data) {
String checkList;
if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.ALI_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_ALIYUN.value();
} else if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.NETEASE_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_163.value();
} else {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value();
}
checkList = checkList.replaceAll(",", " ");
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh",
map(e("dnsCheckList", checkList)));
if (ret.isSshFailure()) {
trigger.fail(operr("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
trigger.fail(operr("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet", checkList));
} else {
trigger.next();
}
}
});
}
}
flow(new NoRollbackFlow() {
String __name__ = "check-if-host-can-reach-management-node";
@Override
public void run(FlowTrigger trigger, Map data) {
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp()));
SshResult ret = sshShell.runCommand(String.format("curl --connect-timeout 10 %s", restf.getCallbackUrl()));
if (ret.isSshFailure()) {
throw new OperationFailureException(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," +
"please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
throw new OperationFailureException(operr("the KVM host[ip:%s] cannot access the management node's callback url. It seems" +
" that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), restf.getHostName(),
ret.getStderr(), ret.getExitErrorMessage()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "apply-ansible-playbook";
@Override
public void run(final FlowTrigger trigger, Map data) {
String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath();
String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName);
SshFileMd5Checker checker = new SshFileMd5Checker();
checker.setUsername(getSelf().getUsername());
checker.setPassword(getSelf().getPassword());
checker.setSshPort(getSelf().getPort());
checker.setTargetIp(getSelf().getManagementIp());
checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME));
checker.addSrcDestPair(srcPath, destPath);
AnsibleRunner runner = new AnsibleRunner();
runner.installChecker(checker);
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME);
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
if (info.isNewAdded()) {
runner.putArgument("init", "true");
runner.setFullDeploy(true);
}
runner.putArgument("pkg_kvmagent", agentPackageName);
runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-")));
if (CoreGlobalProperty.CHRONY_SERVERS != null && !CoreGlobalProperty.CHRONY_SERVERS.isEmpty()) {
runner.putArgument("chrony_servers", String.join(",", CoreGlobalProperty.CHRONY_SERVERS));
}
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString());
String postUrl = ub.build().toString();
runner.putArgument("post_url", postUrl);
runner.run(new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "echo-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "collect-kvm-host-facts";
@Override
public void run(final FlowTrigger trigger, Map data) {
HostFactCmd cmd = new HostFactCmd();
cmd.setIgnoreMsrs(KVMGlobalConfig.KVM_IGNORE_MSRS.value(Boolean.class));
new Http<>(hostFactPath, cmd, HostFactResponse.class)
.call(new ReturnValueCompletion<HostFactResponse>(trigger) {
@Override
public void success(HostFactResponse ret) {
if (!ret.isSuccess()) {
trigger.fail(operr("operation error, because:%s", ret.getError()));
return;
}
if (ret.getHvmCpuFlag() == null) {
trigger.fail(operr("cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting"));
return;
}
// create system tags of os::version etc
createHostVersionSystemTags(ret.getOsDistribution(), ret.getOsRelease(), ret.getOsVersion());
SystemTagCreator creator = KVMSystemTags.QEMU_IMG_VERSION.newSystemTagCreator(self.getUuid());
creator.setTagByTokens(map(e(KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion())));
creator.recreate = true;
creator.create();
creator = KVMSystemTags.LIBVIRT_VERSION.newSystemTagCreator(self.getUuid());
creator.setTagByTokens(map(e(KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion())));
creator.recreate = true;
creator.create();
creator = KVMSystemTags.HVM_CPU_FLAG.newSystemTagCreator(self.getUuid());
creator.setTagByTokens(map(e(KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag())));
creator.recreate = true;
creator.create();
creator = KVMSystemTags.CPU_MODEL_NAME.newSystemTagCreator(self.getUuid());
creator.setTagByTokens(map(e(KVMSystemTags.CPU_MODEL_NAME_TOKEN, ret.getCpuModelName())));
creator.recreate = true;
creator.create();
if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) {
creator = KVMSystemTags.VIRTIO_SCSI.newSystemTagCreator(self.getUuid());
creator.recreate = true;
creator.create();
}
List<String> ips = ret.getIpAddresses();
if (ips != null) {
ips.remove(self.getManagementIp());
if (!ips.isEmpty()) {
creator = HostSystemTags.EXTRA_IPS.newSystemTagCreator(self.getUuid());
creator.setTagByTokens(map(e(HostSystemTags.EXTRA_IPS_TOKEN, StringUtils.join(ips, ","))));
creator.recreate = true;
creator.create();
} else {
HostSystemTags.EXTRA_IPS.delete(self.getUuid());
}
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
if (info.isNewAdded()) {
flow(new NoRollbackFlow() {
String __name__ = "check-qemu-libvirt-version";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!checkQemuLibvirtVersionOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
}
});
}
flow(new NoRollbackFlow() {
String __name__ = "prepare-host-env";
@Override
public void run(FlowTrigger trigger, Map data) {
String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true";
runShell(script);
trigger.next();
}
});
error(new FlowErrorHandler(complete) {
@Override
public void handle(ErrorCode errCode, Map data) {
complete.fail(errCode);
}
});
done(new FlowDoneHandler(complete) {
@Override
public void handle(Map data) {
continueConnect(info.isNewAdded(), complete);
}
});
}
}).start();
}
}
private boolean checkCpuModelOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> cpuModelNames = KVMSystemTags.CPU_MODEL_NAME.getTags(hostUuidsInCluster);
if (cpuModelNames != null && cpuModelNames.size() != 0) {
String clusterCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByTag(
cpuModelNames.values().iterator().next().get(0),
KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
String hostCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
if (clusterCpuModelName != null && !clusterCpuModelName.equals(hostCpuModelName)) {
return false;
}
}
return true;
}
@Override
protected void updateOsHook(String exclude, Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("update-operating-system-for-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
// is the host in maintenance already?
HostState oldState = self.getState();
boolean maintenance = oldState == HostState.Maintenance;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "double-check-host-state-status";
@Override
public void run(FlowTrigger trigger, Map data) {
if (self.getState() == HostState.PreMaintenance) {
trigger.fail(Platform.operr("host is in the premaintenance state, cannot update os"));
} else if (self.getStatus() != HostStatus.Connected) {
trigger.fail(Platform.operr("host is not in the connected status, cannot update os"));
} else {
trigger.next();
}
}
});
flow(new Flow() {
String __name__ = "make-host-in-maintenance";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// enter maintenance, but donot stop/migrate vm on the host
ChangeHostStateMsg cmsg = new ChangeHostStateMsg();
cmsg.setUuid(self.getUuid());
cmsg.setStateEvent(HostStateEvent.preMaintain.toString());
bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (maintenance) {
trigger.rollback();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-host-os";
@Override
public void run(FlowTrigger trigger, Map data) {
UpdateHostOSCmd cmd = new UpdateHostOSCmd();
cmd.hostUuid = self.getUuid();
cmd.excludePackages = exclude;
new Http<>(updateHostOSPath, cmd, UpdateHostOSRsp.class)
.call(new ReturnValueCompletion<UpdateHostOSRsp>(trigger) {
@Override
public void success(UpdateHostOSRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr(ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "recover-host-state";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "auto-reconnect-host";
@Override
public void run(FlowTrigger trigger, Map data) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info("successfully reconnected host " + self.getUuid());
} else {
logger.error("failed to reconnect host " + self.getUuid());
}
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
logger.debug(String.format("successfully updated operating system for host[uuid:%s]", self.getUuid()));
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to updated operating system for host[uuid:%s] because %s",
self.getUuid(), errCode.getDetails()));
completion.fail(errCode);
}
});
}
}).start();
}
private boolean checkMigrateNetworkCidrOfHost(String cidr) {
if (NetworkUtils.isIpv4InCidr(self.getManagementIp(), cidr)) {
return true;
}
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
self.getUuid(), HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.error(String.format("Host[uuid:%s] has no IPs in migrate network", self.getUuid()));
return false;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return true;
}
}
return false;
}
private boolean checkQemuLibvirtVersionOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> qemuVersions = KVMSystemTags.QEMU_IMG_VERSION.getTags(hostUuidsInCluster);
if (qemuVersions != null && qemuVersions.size() != 0) {
String clusterQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(
qemuVersions.values().iterator().next().get(0),
KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
String hostQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
if (clusterQemuVer != null && !clusterQemuVer.equals(hostQemuVer)) {
return false;
}
}
Map<String, List<String>> libvirtVersions = KVMSystemTags.LIBVIRT_VERSION.getTags(hostUuidsInCluster);
if (libvirtVersions != null && libvirtVersions.size() != 0) {
String clusterLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByTag(
libvirtVersions.values().iterator().next().get(0),
KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
String hostLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
if (clusterLibvirtVer != null && !clusterLibvirtVer.equals(hostLibvirtVer)) {
return false;
}
}
return true;
}
@Override
protected int getHostSyncLevel() {
return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class);
}
@Override
protected HostVO updateHost(APIUpdateHostMsg msg) {
if (!(msg instanceof APIUpdateKVMHostMsg)) {
return super.updateHost(msg);
}
KVMHostVO vo = (KVMHostVO) super.updateHost(msg);
vo = vo == null ? getSelf() : vo;
APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg;
if (umsg.getUsername() != null) {
vo.setUsername(umsg.getUsername());
}
if (umsg.getPassword() != null) {
vo.setPassword(umsg.getPassword());
}
if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) {
vo.setPort(umsg.getSshPort());
}
return vo;
}
}
|
package com.splicemachine.derby.impl.sql.execute.actions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import com.google.common.io.Closeables;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import com.splicemachine.db.catalog.IndexDescriptor;
import com.splicemachine.db.catalog.UUID;
import com.splicemachine.db.catalog.types.IndexDescriptorImpl;
import com.splicemachine.db.iapi.error.StandardException;
import com.splicemachine.db.iapi.reference.SQLState;
import com.splicemachine.db.iapi.services.io.FormatableBitSet;
import com.splicemachine.db.iapi.services.sanity.SanityManager;
import com.splicemachine.db.iapi.sql.Activation;
import com.splicemachine.db.iapi.sql.PreparedStatement;
import com.splicemachine.db.iapi.sql.ResultSet;
import com.splicemachine.db.iapi.sql.conn.LanguageConnectionContext;
import com.splicemachine.db.iapi.sql.depend.DependencyManager;
import com.splicemachine.db.iapi.sql.dictionary.ColumnDescriptor;
import com.splicemachine.db.iapi.sql.dictionary.ColumnDescriptorList;
import com.splicemachine.db.iapi.sql.dictionary.ConglomerateDescriptor;
import com.splicemachine.db.iapi.sql.dictionary.ConglomerateDescriptorList;
import com.splicemachine.db.iapi.sql.dictionary.ConstraintDescriptor;
import com.splicemachine.db.iapi.sql.dictionary.ConstraintDescriptorList;
import com.splicemachine.db.iapi.sql.dictionary.DataDescriptorGenerator;
import com.splicemachine.db.iapi.sql.dictionary.DataDictionary;
import com.splicemachine.db.iapi.sql.dictionary.IndexLister;
import com.splicemachine.db.iapi.sql.dictionary.IndexRowGenerator;
import com.splicemachine.db.iapi.sql.dictionary.SchemaDescriptor;
import com.splicemachine.db.iapi.sql.dictionary.TableDescriptor;
import com.splicemachine.db.iapi.sql.execute.ConstantAction;
import com.splicemachine.db.iapi.sql.execute.ExecIndexRow;
import com.splicemachine.db.iapi.sql.execute.ExecRow;
import com.splicemachine.db.iapi.store.access.ColumnOrdering;
import com.splicemachine.db.iapi.store.access.ConglomerateController;
import com.splicemachine.db.iapi.store.access.GroupFetchScanController;
import com.splicemachine.db.iapi.store.access.RowLocationRetRowSource;
import com.splicemachine.db.iapi.store.access.RowSource;
import com.splicemachine.db.iapi.store.access.RowUtil;
import com.splicemachine.db.iapi.store.access.ScanController;
import com.splicemachine.db.iapi.store.access.TransactionController;
import com.splicemachine.db.iapi.types.DataValueDescriptor;
import com.splicemachine.db.iapi.types.RowLocation;
import com.splicemachine.db.impl.sql.execute.ColumnInfo;
import com.splicemachine.db.impl.sql.execute.IndexColumnOrder;
import com.splicemachine.derby.ddl.DDLChangeType;
import com.splicemachine.derby.ddl.TentativeAddConstraintDesc;
import com.splicemachine.derby.ddl.TentativeDropPKConstraintDesc;
import com.splicemachine.derby.ddl.TentativeIndexDesc;
import com.splicemachine.derby.hbase.SpliceDriver;
import com.splicemachine.derby.impl.job.JobInfo;
import com.splicemachine.derby.impl.job.altertable.AlterTableJob;
import com.splicemachine.derby.impl.job.altertable.PopulateConglomerateJob;
import com.splicemachine.derby.impl.job.coprocessor.CoprocessorJob;
import com.splicemachine.derby.impl.store.access.SpliceAccessManager;
import com.splicemachine.derby.impl.store.access.SpliceTransactionManager;
import com.splicemachine.derby.impl.store.access.hbase.HBaseRowLocation;
import com.splicemachine.derby.management.OperationInfo;
import com.splicemachine.derby.management.StatementInfo;
import com.splicemachine.derby.utils.DataDictionaryUtils;
import com.splicemachine.derby.utils.SpliceUtils;
import com.splicemachine.job.JobFuture;
import com.splicemachine.pipeline.ddl.DDLChange;
import com.splicemachine.pipeline.ddl.TransformingDDLDescriptor;
import com.splicemachine.pipeline.exception.ErrorState;
import com.splicemachine.pipeline.exception.Exceptions;
import com.splicemachine.primitives.BooleanArrays;
import com.splicemachine.si.api.Txn;
import com.splicemachine.si.api.TxnLifecycleManager;
import com.splicemachine.si.api.TxnView;
import com.splicemachine.si.impl.TransactionLifecycle;
import com.splicemachine.utils.SpliceLogUtils;
import com.splicemachine.uuid.Snowflake;
/**
* This class describes actions that are ALWAYS performed for an
* ALTER TABLE Statement at Execution time.
*
*/
public class AlterTableConstantOperation extends IndexConstantOperation implements RowLocationRetRowSource {
private static final Logger LOG = Logger.getLogger(AlterTableConstantOperation.class);
// copied from constructor args and stored locally.
protected SchemaDescriptor sd;
protected String tableName;
protected UUID schemaId;
protected ColumnInfo[] columnInfo;
protected ConstantAction[] constraintActions;
private char lockGranularity;
protected int behavior;
protected String indexNameForStatistics;
private int numIndexes;
private long[] indexConglomerateNumbers;
private ConglomerateController compressHeapCC;
private ExecIndexRow[] indexRows;
private GroupFetchScanController compressHeapGSC;
protected IndexRowGenerator[] compressIRGs;
private ColumnOrdering[][] ordering;
private int[][] collation;
// CONSTRUCTORS
/**
* Make the AlterAction for an ALTER TABLE statement.
*
* @param sd descriptor for the table's schema.
* @param tableName Name of table.
* @param tableId UUID of table
* @param columnInfo Information on all the columns in the table.
* @param constraintActions ConstraintConstantAction[] for constraints
* @param lockGranularity The lock granularity.
* @param behavior drop behavior for dropping column
* @param indexNameForStatistics Will name the index whose statistics
*/
public AlterTableConstantOperation(
SchemaDescriptor sd,
String tableName,
UUID tableId,
ColumnInfo[] columnInfo,
ConstantAction[] constraintActions,
char lockGranularity,
int behavior,
String indexNameForStatistics) {
super(tableId);
if (LOG.isTraceEnabled())
SpliceLogUtils.trace(LOG, "instantiating AlterTableConstantOperation for table {%s.%s} with ColumnInfo {%s} and constraintActions {%s}",sd!=null?sd.getSchemaName():"default",tableName, Arrays.toString(columnInfo), Arrays.toString(constraintActions));
this.sd = sd;
this.tableName = tableName;
this.columnInfo = columnInfo;
this.constraintActions = constraintActions;
this.lockGranularity = lockGranularity;
this.behavior = behavior;
this.indexNameForStatistics = indexNameForStatistics;
if (SanityManager.DEBUG)
SanityManager.ASSERT(sd != null, "schema descriptor is null");
}
public String toString() {
return "ALTER TABLE " + tableName;
}
/**
* Run this constant action.
*
* @param activation the activation in which to run the action
* @throws StandardException if an error happens during execution
* of the action
*/
@Override
public void executeConstantAction(Activation activation) throws StandardException {
SpliceLogUtils.trace(LOG, "executeConstantAction with activation %s",activation);
executeConstantActionBody(activation);
}
/**
* @see RowSource#getValidColumns
*/
public FormatableBitSet getValidColumns() {
SpliceLogUtils.trace(LOG, "getValidColumns");
// All columns are valid
return null;
}
/*private helper methods*/
protected void executeConstantActionBody(Activation activation) throws StandardException {
SpliceLogUtils.trace(LOG, "executeConstantActionBody with activation %s",activation);
// Save references to the main structures we need.
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
DataDictionary dd = lcc.getDataDictionary();
DependencyManager dm = dd.getDependencyManager();
/*
** Inform the data dictionary that we are about to write to it.
** There are several calls to data dictionary "get" methods here
** that might be done in "read" mode in the data dictionary, but
** it seemed safer to do this whole operation in "write" mode.
**
** We tell the data dictionary we're done writing at the end of
** the transaction.
*/
dd.startWriting(lcc);
// now do the real work
// get an exclusive lock of the heap, to avoid deadlock on rows of
// SYSCOLUMNS etc datadictionary tables and phantom table
// descriptor, in which case table shape could be changed by a
// concurrent thread doing add/drop column.
// older version (or at target) has to get td first, potential deadlock
TableDescriptor td = getTableDescriptor(lcc);
dm.invalidateFor(td, DependencyManager.ALTER_TABLE, lcc);
// Save the TableDescriptor off in the Activation
activation.setDDLTableDescriptor(td);
/*
** If the schema descriptor is null, then we must have just read
** ourselves in. So we will get the corresponding schema descriptor
** from the data dictionary.
*/
if (sd == null) {
sd = getAndCheckSchemaDescriptor(dd, schemaId, "ALTER TABLE");
}
/* Prepare all dependents to invalidate. (This is their chance
* to say that they can't be invalidated. For example, an open
* cursor referencing a table/view that the user is attempting to
* alter.) If no one objects, then invalidate any dependent objects.
*/
//TODO -sf- do we need to invalidate twice?
dm.invalidateFor(td, DependencyManager.ALTER_TABLE, lcc);
int numRows = 0;
// adjust dependencies on user defined types
adjustUDTDependencies(activation, columnInfo, false );
executeConstraintActions(activation, numRows);
adjustLockGranularity(activation);
}
protected void adjustLockGranularity(Activation activation) throws StandardException {
// Are we changing the lock granularity?
if (lockGranularity != '\0') {
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
DataDictionary dd = lcc.getDataDictionary();
TableDescriptor td = activation.getDDLTableDescriptor();
if (SanityManager.DEBUG) {
if (lockGranularity != 'T' && lockGranularity != 'R') {
SanityManager.THROWASSERT("lockGranularity expected to be 'T'or 'R', not " + lockGranularity);
}
}
// update the TableDescriptor
td.setLockGranularity(lockGranularity);
// update the DataDictionary
dd.updateLockGranularity(td, sd, lockGranularity, lcc.getTransactionExecute());
}
}
protected void executeConstraintActions(Activation activation, int numRows) throws StandardException {
if(constraintActions==null || constraintActions.length == 0) return; //no constraints to apply, so nothing to do
TransactionController tc = activation.getTransactionController();
DataDictionary dd = activation.getLanguageConnectionContext().getDataDictionary();
TableDescriptor td = activation.getDDLTableDescriptor();
boolean tableScanned = numRows>=0;
if(numRows<0)
numRows = 0;
List<CreateConstraintConstantOperation> fkConstraints = new ArrayList<>(constraintActions.length);
for (ConstantAction ca : constraintActions) {
if (ca instanceof CreateConstraintConstantOperation) {
CreateConstraintConstantOperation cca = (CreateConstraintConstantOperation) ca;
int constraintType = cca.getConstraintType();
/* Some constraint types require special checking:
* Check - table must be empty, for now
* Primary Key - table cannot already have a primary key
*/
switch (constraintType) {
case DataDictionary.PRIMARYKEY_CONSTRAINT:
// Check to see if a constraint of the same type
// already exists
ConstraintDescriptorList cdl = dd.getConstraintDescriptors(td);
if (cdl.getPrimaryKey() != null) {
throw StandardException.newException(SQLState.LANG_ADD_PRIMARY_KEY_FAILED1, td.getQualifiedName());
}
// create the PK constraint
createUniquenessConstraint(activation, DDLChangeType.ADD_PRIMARY_KEY, "AddPrimaryKey", cca);
break;
case DataDictionary.UNIQUE_CONSTRAINT:
// create the unique constraint
createUniquenessConstraint(activation, DDLChangeType.ADD_UNIQUE_CONSTRAINT, "AddUniqueConstraint", cca);
break;
case DataDictionary.FOREIGNKEY_CONSTRAINT:
// Do everything but FK constraints first, then FK constraints on 2nd pass.
fkConstraints.add(cca);
break;
case DataDictionary.CHECK_CONSTRAINT:
if (!tableScanned){
tableScanned = true;
numRows = getSemiRowCount(tc,td);
}
if (numRows > 0){
/*
** We are assuming that there will only be one
** check constraint that we are adding, so it
** is ok to do the check now rather than try
** to lump together several checks.
*/
ConstraintConstantOperation.validateConstraint(
cca.getConstraintName(), cca.getConstraintText(),
td, activation.getLanguageConnectionContext(), true);
}
break;
}
} else {
// It's a DropConstraintConstantOperation (there are only two types)
if (SanityManager.DEBUG) {
if (!(ca instanceof DropConstraintConstantOperation)) {
if (ca == null) {
SanityManager.THROWASSERT("constraintAction expected to be instanceof " +
"DropConstraintConstantOperation not null.");
}
assert ca != null;
SanityManager.THROWASSERT("constraintAction expected to be instanceof " +
"DropConstraintConstantOperation not " +ca.getClass().getName());
}
}
@SuppressWarnings("ConstantConditions") DropConstraintConstantOperation dcc = (DropConstraintConstantOperation)ca;
if (dcc.getConstraintName() == null) {
// Sadly, constraintName == null is the only way to know if constraint op is drop PK
// Handle dropping Primary Key
executeDropPrimaryKey(activation, DDLChangeType.DROP_PRIMARY_KEY, "DropPrimaryKey", dcc);
} else {
// Handle drop constraint
//noinspection ConstantConditions
executeDropConstraint(activation, DDLChangeType.DROP_CONSTRAINT, "DropConstraint", dcc);
}
}
}
// now handle all foreign key constraints
for (ConstraintConstantOperation constraintAction : fkConstraints) {
constraintAction.executeConstantAction(activation);
}
}
private void executeDropPrimaryKey(Activation activation, DDLChangeType changeType, String changeMsg,
DropConstraintConstantOperation constraint) throws StandardException {
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
DataDictionary dd = lcc.getDataDictionary();
TransactionController tc = lcc.getTransactionExecute();
TableDescriptor tableDescriptor = activation.getDDLTableDescriptor();
ConstraintDescriptor cd = dd.getConstraintDescriptors(tableDescriptor).getPrimaryKey();
SanityManager.ASSERT(cd != null,tableDescriptor.getSchemaName()+"."+tableName+
" does not have a Primary Key to drop.");
List<String> constraintColumnNames = Arrays.asList(cd.getColumnDescriptors().getColumnNames());
ColumnDescriptorList columnDescriptorList = tableDescriptor.getColumnDescriptorList();
int nColumns = columnDescriptorList.size();
// o create row template to tell the store what type of rows this
// table holds.
// o create array of collation id's to tell collation id of each
// column in table.
ExecRow template = com.splicemachine.db.impl.sql.execute.RowUtil.getEmptyValueRow(columnDescriptorList.size(), lcc);
TxnView parentTxn = ((SpliceTransactionManager)tc).getActiveStateTxn();
// How were the columns ordered before?
int[] oldColumnOrdering = DataDictionaryUtils.getColumnOrdering(parentTxn, tableId);
// We're adding a uniqueness constraint. Column sort order will change.
int[] collation_ids = new int[nColumns];
ColumnOrdering[] columnSortOrder = new IndexColumnOrder[0];
int j=0;
for (int ix = 0; ix < nColumns; ix++) {
ColumnDescriptor col_info = columnDescriptorList.get(ix);
// Get a template value for each column
if (col_info.getDefaultValue() != null) {
/* If there is a default value, use it, otherwise use null */
template.setColumn(ix + 1, col_info.getDefaultValue());
}
else {
template.setColumn(ix + 1, col_info.getType().getNull());
}
// get collation info for each column.
collation_ids[ix] = col_info.getType().getCollationType();
}
/*
* Inform the data dictionary that we are about to write to it.
* There are several calls to data dictionary "get" methods here
* that might be done in "read" mode in the data dictionary, but
* it seemed safer to do this whole operation in "write" mode.
*
* We tell the data dictionary we're done writing at the end of
* the transaction.
*/
dd.startWriting(lcc);
// Get the properties on the old heap
long oldCongNum = tableDescriptor.getHeapConglomerateId();
ConglomerateController compressHeapCC =
tc.openConglomerate(
oldCongNum,
false,
TransactionController.OPENMODE_FORUPDATE,
TransactionController.MODE_TABLE,
TransactionController.ISOLATION_SERIALIZABLE);
Properties properties = new Properties();
compressHeapCC.getInternalTablePropertySet(properties);
compressHeapCC.close();
int tableType = tableDescriptor.getTableType();
long newCongNum = tc.createConglomerate(
"heap", // we're requesting a heap conglomerate
template.getRowArray(), // row template
columnSortOrder, //column sort order
collation_ids,
properties, // properties
tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ?
(TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT) :
TransactionController.IS_DEFAULT);
// follow thru with remaining constraint actions, create, store, etc.
constraint.executeConstantAction(activation);
/*
* modify the conglomerate descriptor with the new conglomId
*/
updateTableConglomerateDescriptor(tableDescriptor,
newCongNum,
sd,
lcc,
constraint);
// refresh the activation's TableDescriptor now that we've modified it
activation.setDDLTableDescriptor(tableDescriptor);
// Start a tentative txn to demarcate the DDL change
Txn tentativeTransaction;
try {
TxnLifecycleManager lifecycleManager = TransactionLifecycle.getLifecycleManager();
tentativeTransaction =
lifecycleManager.beginChildTransaction(parentTxn, Bytes.toBytes(Long.toString(oldCongNum)));
} catch (IOException e) {
LOG.error("Couldn't start transaction for tentative Drop Primary Key operation");
throw Exceptions.parseException(e);
}
String tableVersion = DataDictionaryUtils.getTableVersion(lcc, tableId);
int[] newColumnOrdering = DataDictionaryUtils.getColumnOrdering(parentTxn, tableId);
ColumnInfo[] newColumnInfo = DataDictionaryUtils.getColumnInfo(tableDescriptor);
TransformingDDLDescriptor interceptColumnDesc = new TentativeDropPKConstraintDesc(tableVersion,
newCongNum,
oldCongNum,
oldColumnOrdering,
newColumnOrdering,
newColumnInfo);
DDLChange ddlChange = new DDLChange(tentativeTransaction, changeType);
// set descriptor on the ddl change
ddlChange.setTentativeDDLDesc(interceptColumnDesc);
// Initiate the copy from old conglomerate to new conglomerate and the interception
// from old schema writes to new table with new column appended
try (HTableInterface hTable = SpliceAccessManager.getHTable(Long.toString(oldCongNum).getBytes())) {
String schemaName = tableDescriptor.getSchemaName();
String tableName = tableDescriptor.getName();
//Add a handler to intercept writes to old schema on all regions and forward them to new
startCoprocessorJob(activation,
changeMsg,
schemaName,
tableName,
constraintColumnNames,
new AlterTableJob(hTable, ddlChange),
parentTxn);
//wait for all past txns to complete
Txn populateTxn = getChainedTransaction(tc, tentativeTransaction, oldCongNum, changeMsg+"(" +
constraintColumnNames + ")");
// Populate new table with additional column with data from old table
CoprocessorJob populateJob = new PopulateConglomerateJob(hTable,
tableDescriptor.getNumberOfColumns(),
populateTxn.getBeginTimestamp(),
ddlChange);
startCoprocessorJob(activation,
changeMsg,
schemaName,
tableName,
constraintColumnNames,
populateJob,
parentTxn);
populateTxn.commit();
} catch (IOException e) {
throw Exceptions.parseException(e);
}
//notify other servers of the change
notifyMetadataChangeAndWait(ddlChange);
}
private void executeDropConstraint(Activation activation,
DDLChangeType changeType,
String changeMsg,
DropConstraintConstantOperation constraint) throws StandardException {
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
DataDictionary dd = lcc.getDataDictionary();
TransactionController tc = lcc.getTransactionExecute();
TableDescriptor tableDescriptor = activation.getDDLTableDescriptor();
// try to find constraint descriptor using table's schema first
SchemaDescriptor sd = tableDescriptor.getSchemaDescriptor();
ConstraintDescriptor cd = dd.getConstraintDescriptorByName(tableDescriptor, sd,
constraint.getConstraintName(), true);
if (cd == null) {
// give it another shot since constraint may not be in the same schema as the table
for (ConstraintDescriptor pcd : tableDescriptor.getConstraintDescriptorList()) {
if (pcd.getSchemaDescriptor().getSchemaName().equals(constraint.getSchemaName()) &&
pcd.getConstraintName().equals(constraint.getSchemaName())) {
cd = pcd;
break;
}
}
}
SanityManager.ASSERT(cd != null,tableDescriptor.getSchemaName()+"."+tableName+
" does not have a constraint to drop named "+constraint.getConstraintName());
List<String> constraintColumnNames = Arrays.asList(cd.getColumnDescriptors().getColumnNames());
TxnView parentTxn = ((SpliceTransactionManager)tc).getActiveStateTxn();
// How were the columns ordered before?
int[] oldColumnOrdering = DataDictionaryUtils.getColumnOrdering(parentTxn, tableId);
/*
* Inform the data dictionary that we are about to write to it.
* There are several calls to data dictionary "get" methods here
* that might be done in "read" mode in the data dictionary, but
* it seemed safer to do this whole operation in "write" mode.
*
* We tell the data dictionary we're done writing at the end of
* the transaction.
*/
dd.startWriting(lcc);
// Get the properties on the old heap
long oldCongNum = tableDescriptor.getHeapConglomerateId();
// refresh the activation's TableDescriptor now that we've modified it
activation.setDDLTableDescriptor(tableDescriptor);
// follow thru with remaining constraint actions, create, store, etc.
constraint.executeConstantAction(activation);
long indexConglomerateId = constraint.getIndexConglomerateId();
// Start a tentative txn to demarcate the DDL change
Txn tentativeTransaction;
try {
TxnLifecycleManager lifecycleManager = TransactionLifecycle.getLifecycleManager();
tentativeTransaction =
lifecycleManager.beginChildTransaction(parentTxn, Bytes.toBytes(Long.toString(oldCongNum)));
} catch (IOException e) {
LOG.error("Couldn't start transaction for tentative Drop Constraint operation");
throw Exceptions.parseException(e);
}
String tableVersion = DataDictionaryUtils.getTableVersion(lcc, tableId);
int[] newColumnOrdering = DataDictionaryUtils.getColumnOrdering(parentTxn, tableId);
ColumnInfo[] newColumnInfo = DataDictionaryUtils.getColumnInfo(tableDescriptor);
TransformingDDLDescriptor interceptColumnDesc = new TentativeAddConstraintDesc(tableVersion,
oldCongNum,
oldCongNum,
indexConglomerateId,
oldColumnOrdering,
newColumnOrdering,
newColumnInfo);
DDLChange ddlChange = new DDLChange(tentativeTransaction, changeType);
// set descriptor on the ddl change
ddlChange.setTentativeDDLDesc(interceptColumnDesc);
// Initiate the copy from old conglomerate to new conglomerate and the interception
// from old schema writes to new table with new column appended
try (HTableInterface hTable = SpliceAccessManager.getHTable(Long.toString(oldCongNum).getBytes())) {
String schemaName = tableDescriptor.getSchemaName();
String tableName = tableDescriptor.getName();
//Add a handler to intercept writes to old schema on all regions and forward them to new
startCoprocessorJob(activation,
changeMsg,
schemaName,
tableName,
constraintColumnNames,
new AlterTableJob(hTable, ddlChange),
parentTxn);
// wait for all in-flight txns to complete
// FIXME: JC - just commit tentative txn after wait
Txn populateTxn = getChainedTransaction(tc, tentativeTransaction, oldCongNum, changeMsg+"("+constraintColumnNames+")");
populateTxn.commit();
} catch (IOException e) {
throw Exceptions.parseException(e);
}
//notify other servers of the change
notifyMetadataChangeAndWait(ddlChange);
}
private void createUniquenessConstraint(Activation activation,
DDLChangeType changeType,
String changeMsg,
CreateConstraintConstantOperation newConstraint) throws StandardException {
List<String> constraintColumnNames = Arrays.asList(newConstraint.columnNames);
if (constraintColumnNames.isEmpty()) {
return;
}
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
DataDictionary dd = lcc.getDataDictionary();
TransactionController tc = lcc.getTransactionExecute();
TableDescriptor tableDescriptor = activation.getDDLTableDescriptor();
ColumnDescriptorList columnDescriptorList = tableDescriptor.getColumnDescriptorList();
int nColumns = columnDescriptorList.size();
// o create row template to tell the store what type of rows this
// table holds.
// o create array of collation id's to tell collation id of each
// column in table.
ExecRow template = com.splicemachine.db.impl.sql.execute.RowUtil.getEmptyValueRow(columnDescriptorList.size(), lcc);
TxnView parentTxn = ((SpliceTransactionManager)tc).getActiveStateTxn();
// How were the columns ordered before?
int[] oldColumnOrdering = DataDictionaryUtils.getColumnOrdering(parentTxn, tableId);
// We're adding a uniqueness constraint. Column sort order will change.
int[] collation_ids = new int[nColumns];
ColumnOrdering[] columnSortOrder = new IndexColumnOrder[constraintColumnNames.size()];
int j=0;
for (int ix = 0; ix < nColumns; ix++) {
ColumnDescriptor col_info = columnDescriptorList.get(ix);
if (constraintColumnNames.contains(col_info.getColumnName())) {
columnSortOrder[j++] = new IndexColumnOrder(ix);
}
// Get a template value for each column
if (col_info.getDefaultValue() != null) {
/* If there is a default value, use it, otherwise use null */
template.setColumn(ix + 1, col_info.getDefaultValue());
}
else {
template.setColumn(ix + 1, col_info.getType().getNull());
}
// get collation info for each column.
collation_ids[ix] = col_info.getType().getCollationType();
}
/*
* Inform the data dictionary that we are about to write to it.
* There are several calls to data dictionary "get" methods here
* that might be done in "read" mode in the data dictionary, but
* it seemed safer to do this whole operation in "write" mode.
*
* We tell the data dictionary we're done writing at the end of
* the transaction.
*/
dd.startWriting(lcc);
// Get the properties on the old heap
long oldCongNum = tableDescriptor.getHeapConglomerateId();
ConglomerateController compressHeapCC =
tc.openConglomerate(
oldCongNum,
false,
TransactionController.OPENMODE_FORUPDATE,
TransactionController.MODE_TABLE,
TransactionController.ISOLATION_SERIALIZABLE);
Properties properties = new Properties();
compressHeapCC.getInternalTablePropertySet(properties);
compressHeapCC.close();
int tableType = tableDescriptor.getTableType();
long newCongNum = tc.createConglomerate(
"heap", // we're requesting a heap conglomerate
template.getRowArray(), // row template
columnSortOrder, //column sort order - not required for heap
collation_ids,
properties, // properties
tableType == TableDescriptor.GLOBAL_TEMPORARY_TABLE_TYPE ?
(TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT) :
TransactionController.IS_DEFAULT);
/*
* modify the conglomerate descriptor with the new conglomId
*/
updateTableConglomerateDescriptor(tableDescriptor,
newCongNum,
sd,
lcc,
newConstraint);
// refresh the activation's TableDescriptor now that we've modified it
activation.setDDLTableDescriptor(tableDescriptor);
// follow thru with remaining constraint actions, create, store, etc.
newConstraint.executeConstantAction(activation);
// Start a tentative txn to demarcate the DDL change
Txn tentativeTransaction;
try {
TxnLifecycleManager lifecycleManager = TransactionLifecycle.getLifecycleManager();
tentativeTransaction =
lifecycleManager.beginChildTransaction(parentTxn, Bytes.toBytes(Long.toString(oldCongNum)));
} catch (IOException e) {
LOG.error("Couldn't start transaction for tentative Add Constraint operation");
throw Exceptions.parseException(e);
}
String tableVersion = DataDictionaryUtils.getTableVersion(lcc, tableId);
int[] newColumnOrdering = DataDictionaryUtils.getColumnOrdering(parentTxn, tableId);
ColumnInfo[] newColumnInfo = DataDictionaryUtils.getColumnInfo(tableDescriptor);
TransformingDDLDescriptor interceptColumnDesc = new TentativeAddConstraintDesc(tableVersion,
newCongNum,
oldCongNum,
-1l,
oldColumnOrdering,
newColumnOrdering,
newColumnInfo);
DDLChange ddlChange = new DDLChange(tentativeTransaction, changeType);
// set descriptor on the ddl change
ddlChange.setTentativeDDLDesc(interceptColumnDesc);
// Initiate the copy from old conglomerate to new conglomerate and the interception
// from old schema writes to new table with new column appended
try (HTableInterface hTable = SpliceAccessManager.getHTable(Long.toString(oldCongNum).getBytes())) {
String schemaName = tableDescriptor.getSchemaName();
String tableName = tableDescriptor.getName();
//Add a handler to intercept writes to old schema on all regions and forward them to new
startCoprocessorJob(activation,
changeMsg,
schemaName,
tableName,
constraintColumnNames,
new AlterTableJob(hTable, ddlChange),
parentTxn);
//wait for all past txns to complete
Txn populateTxn = getChainedTransaction(tc, tentativeTransaction, oldCongNum, changeMsg+"(" +
constraintColumnNames + ")");
// Populate new table with additional column with data from old table
CoprocessorJob populateJob = new PopulateConglomerateJob(hTable,
tableDescriptor.getNumberOfColumns(),
populateTxn.getBeginTimestamp(),
ddlChange);
startCoprocessorJob(activation,
changeMsg,
schemaName,
tableName,
constraintColumnNames,
populateJob,
parentTxn);
populateTxn.commit();
} catch (IOException e) {
throw Exceptions.parseException(e);
}
//notify other servers of the change
notifyMetadataChangeAndWait(ddlChange);
}
protected void updateAllIndexes(Activation activation,
long newHeapConglom,
TableDescriptor td,
TransactionController tc) throws StandardException {
/*
* Update all of the indexes on a table when doing a bulk insert
* on an empty table.
*/
SpliceLogUtils.trace(LOG, "updateAllIndexes on new heap conglom %d",newHeapConglom);
long[] newIndexCongloms = new long[numIndexes];
for (int index = 0; index < numIndexes; index++) {
updateIndex(newHeapConglom, activation, tc, td,index, newIndexCongloms);
}
}
protected void updateIndex(long newHeapConglom, Activation activation,
TransactionController tc, TableDescriptor td, int index, long[] newIndexCongloms)
throws StandardException {
SpliceLogUtils.trace(LOG, "updateIndex on new heap conglom %d for index %d with newIndexCongloms %s",
newHeapConglom, index, Arrays.toString(newIndexCongloms));
// Get the ConglomerateDescriptor for the index
ConglomerateDescriptor cd = td.getConglomerateDescriptor(indexConglomerateNumbers[index]);
// Build the properties list for the new conglomerate
ConglomerateController indexCC =
tc.openConglomerate(
indexConglomerateNumbers[index],
false,
TransactionController.OPENMODE_FORUPDATE,
TransactionController.MODE_TABLE,
TransactionController.ISOLATION_SERIALIZABLE);
Properties properties = getIndexProperties(newHeapConglom, index, cd, indexCC);
// We can finally drain the sorter and rebuild the index
// Populate the index.
DataValueDescriptor[] rowArray = indexRows[index].getRowArray();
ColumnOrdering[] columnOrder = ordering[index];
int[] collationIds = collation[index];
DataDictionary dd = activation.getLanguageConnectionContext().getDataDictionary();
doIndexUpdate(dd,td,tc, index, newIndexCongloms, cd, properties, false,rowArray,columnOrder,collationIds);
try{
// Populate indexes
IndexRowGenerator indexDescriptor = cd.getIndexDescriptor();
boolean[] isAscending = indexDescriptor.isAscending();
int[] baseColumnPositions = indexDescriptor.baseColumnPositions();
boolean unique = indexDescriptor.isUnique();
boolean uniqueWithDuplicateNulls = indexDescriptor.isUniqueWithDuplicateNulls();
boolean[] descColumns = BooleanArrays.not(isAscending);
byte[] writeTable = Long.toString(newHeapConglom).getBytes();
TxnView parentTxn = ((SpliceTransactionManager) tc).getActiveStateTxn();
Txn tentativeTransaction;
try {
tentativeTransaction = TransactionLifecycle.getLifecycleManager().beginChildTransaction(parentTxn, Txn.IsolationLevel.SNAPSHOT_ISOLATION,writeTable);
} catch (IOException e) {
LOG.error("Couldn't start transaction for tentative DDL operation");
throw Exceptions.parseException(e);
}
TentativeIndexDesc tentativeIndexDesc = new TentativeIndexDesc(newIndexCongloms[index], newHeapConglom,
baseColumnPositions, unique,
uniqueWithDuplicateNulls,
SpliceUtils.bitSetFromBooleanArray(descColumns));
DDLChange ddlChange = new DDLChange(tentativeTransaction,
DDLChangeType.CREATE_INDEX);
ddlChange.setTentativeDDLDesc(tentativeIndexDesc);
notifyMetadataChangeAndWait(ddlChange);
try (HTableInterface table = SpliceAccessManager.getHTable(writeTable)) {
// Add the indexes to the exisiting regions
createIndex(activation, ddlChange, table, td);
Txn indexTransaction = getIndexTransaction(tc, tentativeTransaction, newHeapConglom);
populateIndex(activation, baseColumnPositions, descColumns,
newHeapConglom, table,tc,
indexTransaction, tentativeTransaction.getCommitTimestamp(),tentativeIndexDesc);
//only commit the index transaction if the job actually completed
indexTransaction.commit();
}
}catch (Throwable t) {
throw Exceptions.parseException(t);
}
/* Update the DataDictionary
*
* Update sys.sysconglomerates with new conglomerate #, we need to
* update all (if any) duplicate index entries sharing this same
* conglomerate.
*/
activation.getLanguageConnectionContext().getDataDictionary().updateConglomerateDescriptor(
td.getConglomerateDescriptors(indexConglomerateNumbers[index]),
newIndexCongloms[index],
tc);
// Drop the old conglomerate
tc.dropConglomerate(indexConglomerateNumbers[index]);
}
protected void doIndexUpdate(DataDictionary dd,
TableDescriptor td,
TransactionController tc,
int index, long[] newIndexCongloms,
ConglomerateDescriptor cd, Properties properties,
boolean statisticsExist,
DataValueDescriptor[] rowArray,
ColumnOrdering[] columnOrder,
int[] collationIds) throws StandardException {
// RowLocationRetRowSource cCount;
// sorters[index].completedInserts();
// sorters[index] = null;
// if (td.statisticsExist(cd)) {
// cCount = new CardinalityCounter( tc.openSortRowSource(sortIds[index]));
// statisticsExist = true;
// } else {
// cCount = new CardinalityCounter( tc.openSortRowSource(sortIds[index]));
newIndexCongloms[index] =
tc.createAndLoadConglomerate(
"BTREE",
rowArray,
columnOrder,
collationIds,
properties,
TransactionController.IS_DEFAULT,
null,
null);
//For an index, if the statistics already exist, then drop them.
//The statistics might not exist for an index if the index was
//created when the table was empty.
//For all alter table actions, including ALTER TABLE COMPRESS,
//for both kinds of indexes (ie. one with preexisting statistics
//and with no statistics), create statistics for them if the table
//is not empty.
if (statisticsExist)
dd.dropStatisticsDescriptors(td.getUUID(), cd.getUUID(), tc);
// long numRows;
// if ((numRows = ((CardinalityCounter)cCount).getRowCount()) > 0) {
// long[] c = ((CardinalityCounter)cCount).getCardinality();
// for (int i = 0; i < c.length; i++) {
// StatisticsDescriptor statDesc =
// new StatisticsDescriptor(
// dd.getUUIDFactory().createUUID(),
// cd.getUUID(),
// td.getUUID(),
// new StatisticsImpl(numRows, c[i]),
// i + 1);
// dd.addDescriptor(
// statDesc,
// null, // no parent descriptor
// DataDictionary.SYSSTATISTICS_CATALOG_NUM,
// true, // no error on duplicate.
}
private Properties getIndexProperties(long newHeapConglom, int index, ConglomerateDescriptor cd, ConglomerateController indexCC) throws StandardException {
// Get the properties on the old index
Properties properties = new Properties();
indexCC.getInternalTablePropertySet(properties);
/* Create the properties that language supplies when creating the
* the index. (The store doesn't preserve these.)
*/
int indexRowLength = indexRows[index].nColumns();
properties.put("baseConglomerateId", Long.toString(newHeapConglom));
if (cd.getIndexDescriptor().isUnique()) {
properties.put( "nUniqueColumns", Integer.toString(indexRowLength - 1));
} else {
properties.put( "nUniqueColumns", Integer.toString(indexRowLength));
}
if(cd.getIndexDescriptor().isUniqueWithDuplicateNulls()) {
properties.put( "uniqueWithDuplicateNulls", Boolean.toString(true));
}
properties.put( "rowLocationColumn", Integer.toString(indexRowLength - 1));
properties.put("nKeyFields", Integer.toString(indexRowLength));
indexCC.close();
return properties;
}
/**
* Get info on the indexes on the table being compressed.
*
* @exception StandardException Thrown on error
*/
protected int getAffectedIndexes(TableDescriptor td) throws StandardException {
SpliceLogUtils.trace(LOG, "getAffectedIndexes");
IndexLister indexLister = td.getIndexLister( );
/* We have to get non-distinct index row generaters and conglom numbers
* here and then compress it to distinct later because drop column
* will need to change the index descriptor directly on each index
* entry in SYSCONGLOMERATES, on duplicate indexes too.
*/
compressIRGs = indexLister.getIndexRowGenerators();
numIndexes = compressIRGs.length;
indexConglomerateNumbers = indexLister.getIndexConglomerateNumbers();
ExecRow emptyHeapRow = td.getEmptyExecRow();
if(numIndexes > 0) {
indexRows = new ExecIndexRow[numIndexes];
ordering = new ColumnOrdering[numIndexes][];
collation = new int[numIndexes][];
for (int index = 0; index < numIndexes; index++) {
IndexRowGenerator curIndex = compressIRGs[index];
RowLocation rl = new HBaseRowLocation(); //TODO -sf- don't explicitly depend on this
// create a single index row template for each index
indexRows[index] = curIndex.getIndexRowTemplate();
curIndex.getIndexRow(emptyHeapRow,
rl,
indexRows[index],
null);
/* For non-unique indexes, we order by all columns + the RID.
* For unique indexes, we just order by the columns.
* No need to try to enforce uniqueness here as
* index should be valid.
*/
int[] baseColumnPositions = curIndex.baseColumnPositions();
boolean[] isAscending = curIndex.isAscending();
int numColumnOrderings = baseColumnPositions.length + 1;
ordering[index] = new ColumnOrdering[numColumnOrderings];
for (int ii =0; ii < numColumnOrderings - 1; ii++) {
ordering[index][ii] = new IndexColumnOrder(ii, isAscending[ii]);
}
ordering[index][numColumnOrderings - 1] = new IndexColumnOrder(numColumnOrderings - 1);
collation[index] = curIndex.getColumnCollationIds(td.getColumnDescriptorList());
}
}
//// if (! (compressTable)) // then it's drop column
// ArrayList newCongloms = new ArrayList();
// for (int i = 0; i < compressIRGs.length; i++)
// int[] baseColumnPositions = compressIRGs[i].baseColumnPositions();
// int j;
// for (j = 0; j < baseColumnPositions.length; j++)
// if (baseColumnPositions[j] == droppedColumnPosition) break;
// if (j == baseColumnPositions.length) // not related
// continue;
// if (baseColumnPositions.length == 1 ||
// (behavior == StatementType.DROP_CASCADE && compressIRGs[i].isUnique()))
// numIndexes--;
// /* get first conglomerate with this conglom number each time
// * and each duplicate one will be eventually all dropped
// */
// ConglomerateDescriptor cd = td.getConglomerateDescriptor
// (indexConglomerateNumbers[i]);
// dropConglomerate(cd, td, true, newCongloms, activation,
// activation.getLanguageConnectionContext());
// compressIRGs[i] = null; // mark it
// continue;
// // give an error for unique index on multiple columns including
// // the column we are to drop (restrict), such index is not for
// // a constraint, because constraints have already been handled
// if (compressIRGs[i].isUnique())
// ConglomerateDescriptor cd = td.getConglomerateDescriptor
// (indexConglomerateNumbers[i]);
// throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_OBJECT,
// dm.getActionString(DependencyManager.DROP_COLUMN),
// columnInfo[0].name, "UNIQUE INDEX",
// cd.getConglomerateName() );
// /* If there are new backing conglomerates which must be
// * created to replace a dropped shared conglomerate
// * (where the shared conglomerate was dropped as part
// * of a "drop conglomerate" call above), then create
// * them now. We do this *after* dropping all dependent
// * conglomerates because we don't want to waste time
// * creating a new conglomerate if it's just going to be
// * dropped again as part of another "drop conglomerate"
// * call.
// */
// createNewBackingCongloms(newCongloms, indexConglomerateNumbers);
// IndexRowGenerator[] newIRGs = new IndexRowGenerator[numIndexes];
// long[] newIndexConglomNumbers = new long[numIndexes];
// for (int i = 0, j = 0; i < numIndexes; i++, j++)
// while (compressIRGs[j] == null)
// int[] baseColumnPositions = compressIRGs[j].baseColumnPositions();
// newIRGs[i] = compressIRGs[j];
// newIndexConglomNumbers[i] = indexConglomerateNumbers[j];
// boolean[] isAscending = compressIRGs[j].isAscending();
// boolean reMakeArrays = false;
// int size = baseColumnPositions.length;
// for (int k = 0; k < size; k++)
// if (baseColumnPositions[k] > droppedColumnPosition)
// baseColumnPositions[k]--;
// else if (baseColumnPositions[k] == droppedColumnPosition)
// baseColumnPositions[k] = 0; // mark it
// reMakeArrays = true;
// if (reMakeArrays)
// size--;
// int[] newBCP = new int[size];
// boolean[] newIsAscending = new boolean[size];
// for (int k = 0, step = 0; k < size; k++)
// if (step == 0 && baseColumnPositions[k + step] == 0)
// step++;
// newBCP[k] = baseColumnPositions[k + step];
// newIsAscending[k] = isAscending[k + step];
// IndexDescriptor id = compressIRGs[j].getIndexDescriptor();
// id.setBaseColumnPositions(newBCP);
// id.setIsAscending(newIsAscending);
// id.setNumberOfOrderedColumns(id.numberOfOrderedColumns() - 1);
// compressIRGs = newIRGs;
// indexConglomerateNumbers = newIndexConglomNumbers;
// /* Now we are done with updating each index descriptor entry directly
// * in SYSCONGLOMERATES (for duplicate index as well), from now on, our
// * work should apply ONLY once for each real conglomerate, so we
// * compress any duplicate indexes now.
// */
// Object[] compressIndexResult =
// compressIndexArrays(indexConglomerateNumbers, compressIRGs);
// if (compressIndexResult != null)
// indexConglomerateNumbers = (long[]) compressIndexResult[1];
// compressIRGs = (IndexRowGenerator[]) compressIndexResult[2];
// numIndexes = indexConglomerateNumbers.length;
// getIndexedColumns(index,td);
return numIndexes;
}
private FormatableBitSet getIndexedColumns(int index,TableDescriptor td) {
FormatableBitSet indexedCols = new FormatableBitSet(getIndexedColumnSize(td));
// for (int index = 0; index < numIndexes; index++) {
int[] colIds = compressIRGs[index].getIndexDescriptor().baseColumnPositions();
for (int colId : colIds) {
indexedCols.set(colId);
}
return indexedCols;
}
protected int getIndexedColumnSize(TableDescriptor td) {
return td.getNumberOfColumns();
}
// RowSource interface
/**
* @see RowSource#getNextRowFromRowSource
* @exception StandardException on error
*/
public DataValueDescriptor[] getNextRowFromRowSource() throws StandardException {
return null;
// SpliceLogUtils.trace(LOG, "getNextRowFromRowSource");
// currentRow = null;
// // Time for a new bulk fetch?
// if ((! doneScan) &&
// (currentCompressRow == bulkFetchSize || !validRow[currentCompressRow]))
// int bulkFetched;
// bulkFetched = compressHeapGSC.fetchNextGroup(baseRowArray, compressRL);
// doneScan = (bulkFetched != bulkFetchSize);
// currentCompressRow = 0;
// for (int index = 0; index < bulkFetched; index++)
// validRow[index] = true;
// for (int index = bulkFetched; index < bulkFetchSize; index++)
// validRow[index] = false;
// if (validRow[currentCompressRow])
//// if (compressTable)
//// currentRow = baseRow[currentCompressRow];
//// else
// if (currentRow == null)
// currentRow =
// activation.getExecutionFactory().getValueRow(
// baseRowArray[currentCompressRow].length - 1);
// for (int i = 0; i < currentRow.nColumns(); i++)
// currentRow.setColumn(
// i + 1,
// i < droppedColumnPosition - 1 ?
// baseRow[currentCompressRow].getColumn(i+1) :
// baseRow[currentCompressRow].getColumn(i+1+1));
// currentCompressRow++;
// if (currentRow != null)
// /* Let the target preprocess the row. For now, this
// * means doing an in place clone on any indexed columns
// * to optimize cloning and so that we don't try to drain
// * a stream multiple times.
// */
// if (compressIRGs.length > 0)
// /* Do in-place cloning of all of the key columns */
// currentRow = currentRow.getClone(indexedCols);
// return currentRow.getRowArray();
// return null;
}
/**
* @see RowSource#needsToClone
*/
public boolean needsToClone() {
SpliceLogUtils.trace(LOG, "needsToClone");
return(true);
}
/**
* @see RowSource#closeRowSource
*/
public void closeRowSource() {
SpliceLogUtils.trace(LOG, "closeRowSource");
// Do nothing here - actual work will be done in close()
}
// RowLocationRetRowSource interface
/**
* @see RowLocationRetRowSource#needsRowLocation
*/
public boolean needsRowLocation() {
SpliceLogUtils.trace(LOG, "needsRowLocation");
// Only true if table has indexes
return (numIndexes > 0);
}
/**
* @see RowLocationRetRowSource#rowLocation
* @exception StandardException on error
*/
public void rowLocation(RowLocation rl)
throws StandardException
{
// SpliceLogUtils.trace(LOG, "rowLocation");
// /* Set up sorters, etc. if 1st row and there are indexes */
// if (compressIRGs.length > 0)
// objectifyStreamingColumns();
// /* Put the row into the indexes. If sequential,
// * then we only populate the 1st sorter when compressing
// * the heap.
// */
// int maxIndex = compressIRGs.length;
// if (maxIndex > 1 && sequential)
// maxIndex = 1;
// for (int index = 0; index < maxIndex; index++)
// insertIntoSorter(index, rl);
}
protected void cleanUp() throws StandardException {
if (compressHeapCC != null) {
compressHeapCC.close();
compressHeapCC = null;
}
if (compressHeapGSC != null) {
closeBulkFetchScan();
}
// Close each sorter
// if (sorters != null) {
// for (int index = 0; index < compressIRGs.length; index++) {
// if (sorters[index] != null) {
// sorters[index].completedInserts();
// sorters[index] = null;
// if (needToDropSort != null) {
// for (int index = 0; index < needToDropSort.length; index++) {
// if (needToDropSort[index]) {
// tc.dropSort(sortIds[index]);
// needToDropSort[index] = false;
}
protected TableDescriptor getTableDescriptor(LanguageConnectionContext lcc) throws StandardException {
TableDescriptor td;
td = DataDictionaryUtils.getTableDescriptor(lcc, tableId);
if (td == null) {
throw StandardException.newException(SQLState.LANG_TABLE_NOT_FOUND_DURING_EXECUTION, tableName);
}
return td;
}
// class implementation
/**
* Return the "semi" row count of a table. We are only interested in
* whether the table has 0, 1 or > 1 rows.
*
*
* @return Number of rows (0, 1 or > 1) in table.
*
* @exception StandardException Thrown on failure
*/
protected int getSemiRowCount(TransactionController tc,TableDescriptor td) throws StandardException {
SpliceLogUtils.trace(LOG, "getSemiRowCount");
int numRows = 0;
ScanController sc = tc.openScan(td.getHeapConglomerateId(),
false, // hold
0, // open read only
TransactionController.MODE_TABLE,
TransactionController.ISOLATION_SERIALIZABLE,
RowUtil.EMPTY_ROW_BITSET, // scanColumnList
null, // start position
ScanController.GE, // startSearchOperation
null, // scanQualifier
null, //stop position - through last row
ScanController.GT); // stopSearchOperation
while (sc.next()) {
numRows++;
// We're only interested in whether the table has 0, 1 or > 1 rows
if (numRows == 2) {
break;
}
}
sc.close();
return numRows;
}
protected static void executeUpdate(LanguageConnectionContext lcc, String updateStmt) throws StandardException {
SpliceLogUtils.trace(LOG, "executeUpdate with statement {%s}", updateStmt);
PreparedStatement ps = lcc.prepareInternalStatement(updateStmt);
// This is a substatement; for now, we do not set any timeout
// for it. We might change this behaviour later, by linking
// timeout to its parent statement's timeout settings.
ResultSet rs = ps.executeSubStatement(lcc, true, 0L);
rs.close();
}
private void closeBulkFetchScan() throws StandardException {
compressHeapGSC.close();
compressHeapGSC = null;
}
/**
* Get rid of duplicates from a set of index conglomerate numbers and
* index descriptors.
*
* @param indexCIDS array of index conglomerate numbers
* @param irgs array of index row generaters
*
* @return value: If no duplicates, returns NULL; otherwise,
* a size-3 array of objects, first element is an
* array of duplicates' indexes in the input arrays;
* second element is the compact indexCIDs; third
* element is the compact irgs.
*/
private Object[] compressIndexArrays( long[] indexCIDS, IndexRowGenerator[] irgs) {
SpliceLogUtils.trace(LOG, "compressIndexArrays");
/* An efficient way to compress indexes. From one end of workSpace,
* we save unique conglom IDs; and from the other end we save
* duplicate indexes' indexes. We save unique conglom IDs so that
* we can do less amount of comparisons. This is efficient in
* space as well. No need to use hash table.
*/
long[] workSpace = new long[indexCIDS.length];
int j = 0, k = indexCIDS.length - 1;
for (int i = 0; i < indexCIDS.length; i++) {
int m;
for (m = 0; m < j; m++){ // look up our unique set
if (indexCIDS[i] == workSpace[m]){ // it's a duplicate
workSpace[k--] = i; // save dup index's index
break;
}
}
if (m == j)
workSpace[j++] = indexCIDS[i]; // save unique conglom id
}
if(j>=indexCIDS.length) return null; //no duplicates
long[] newIndexCIDS = new long[j];
IndexRowGenerator[] newIrgs = new IndexRowGenerator[j];
int[] duplicateIndexes = new int[indexCIDS.length - j];
k = 0;
// do everything in one loop
for (int m = 0, n = indexCIDS.length - 1; m < indexCIDS.length; m++) {
// we already gathered our indexCIDS and duplicateIndexes
if (m < j)
newIndexCIDS[m] = workSpace[m];
else
duplicateIndexes[indexCIDS.length - m - 1] = (int) workSpace[m];
// stack up our irgs, indexSCOCIs, indexDCOCIs
if ((n >= j) && (m == (int) workSpace[n]))
n
else {
newIrgs[k] = irgs[m];
k++;
}
}
// construct return value
Object[] returnValue = new Object[3]; // [indexSCOCIs == null ? 3 : 5];
returnValue[0] = duplicateIndexes;
returnValue[1] = newIndexCIDS;
returnValue[2] = newIrgs;
return returnValue;
}
/**
* Do what's necessary to update a table descriptor that's been modified due to alter table
* actions. Sometimes an action only requires changing the conglomerate number since a new
* conglomerate has been created to replaced the old. Other times the table descriptor's
* main conglomerate descriptor needs to be dropped and recreated.
* @param tableDescriptor the table descriptor that's being effected.
* @param newConglomNum the conglomerate number of the conglomerate that's been created to
* replace the old.
* @param sd descriptor for the schema in which the new conglomerate lives.
* @param lcc language connection context required for coordination.
* @param constraintAction constraint being created, dropped, etc
* @return the modified conglomerate descriptor.
* @throws StandardException
*/
protected ConglomerateDescriptor updateTableConglomerateDescriptor(TableDescriptor tableDescriptor,
long newConglomNum,
SchemaDescriptor sd,
LanguageConnectionContext lcc,
ConstraintConstantOperation constraintAction) throws StandardException {
// We invalidate all statements that use the old conglomerates
TransactionController tc = lcc.getTransactionExecute();
DataDictionary dd = lcc.getDataDictionary();
DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator();
dd.getDependencyManager().invalidateFor(tableDescriptor, DependencyManager.ALTER_TABLE, lcc);
ConglomerateDescriptor modifiedConglomerateDescriptor = null;
if(constraintAction.getConstraintType()== DataDictionary.PRIMARYKEY_CONSTRAINT) {
// Adding a PK - need to drop the old conglomerate descriptor and
// create a new one with an IndexRowGenerator to replace the old
// get the column positions for the new PK to
// create the PK IndexDescriptor and new conglomerate
int [] pkColumns =
((CreateConstraintConstantOperation)constraintAction).genColumnPositions(tableDescriptor, true);
boolean[] ascending = new boolean[pkColumns.length];
for(int i=0;i<ascending.length;i++){
ascending[i] = true;
}
IndexDescriptor indexDescriptor =
new IndexDescriptorImpl("PRIMARYKEY",true,false,pkColumns,ascending,pkColumns.length);
IndexRowGenerator irg = new IndexRowGenerator(indexDescriptor);
// Replace old table conglomerate with new one with the new PK conglomerate
ConglomerateDescriptorList conglomerateList = tableDescriptor.getConglomerateDescriptorList();
modifiedConglomerateDescriptor =
conglomerateList.getConglomerateDescriptor(tableDescriptor.getHeapConglomerateId());
dd.dropConglomerateDescriptor(modifiedConglomerateDescriptor, tc);
conglomerateList.dropConglomerateDescriptor(tableDescriptor.getUUID(), modifiedConglomerateDescriptor);
// Create a new conglomerate descriptor with new IndexRowGenerator
ConglomerateDescriptor cgd = ddg.newConglomerateDescriptor(newConglomNum,
null,//modifiedConglomerateDescriptor.getConglomerateName(),
false,
irg,
false,
null,
tableDescriptor.getUUID(),
sd.getUUID());
dd.addDescriptor(cgd, sd, DataDictionary.SYSCONGLOMERATES_CATALOG_NUM, false, tc);
// add the newly crated conglomerate to the table descriptor
conglomerateList.add(cgd);
// update the conglomerate in the data dictionary so that, when asked for TableDescriptor,
// it's built with the new PK conglomerate
ConglomerateDescriptor[] conglomerateArray = conglomerateList.getConglomerateDescriptors(newConglomNum);
dd.updateConglomerateDescriptor(conglomerateArray, newConglomNum, tc);
} else //noinspection StatementWithEmptyBody
if (constraintAction.getConstraintType()== DataDictionary.UNIQUE_CONSTRAINT) {
// Do nothing for creating unique constraint. Index creation will handle
} else if (constraintAction.getConstraintType() == DataDictionary.DROP_CONSTRAINT) {
if (constraintAction.getConstraintName() == null) {
// Unfortunately, this is the only way we have to know if we're dropping a PK
long heapConglomId = tableDescriptor.getHeapConglomerateId();
ConglomerateDescriptorList conglomerateList = tableDescriptor.getConglomerateDescriptorList();
modifiedConglomerateDescriptor =
conglomerateList.getConglomerateDescriptor(heapConglomId);
dd.dropConglomerateDescriptor(modifiedConglomerateDescriptor, tc);
conglomerateList.dropConglomerateDescriptor(tableDescriptor.getUUID(), modifiedConglomerateDescriptor);
// Create a new conglomerate descriptor
ConglomerateDescriptor cgd = ddg.newConglomerateDescriptor(newConglomNum,
null,//modifiedConglomerateDescriptor.getConglomerateName(),
false,
null,
false,
null,
tableDescriptor.getUUID(),
sd.getUUID());
dd.addDescriptor(cgd, sd, DataDictionary.SYSCONGLOMERATES_CATALOG_NUM, false, tc);
// add the newly crated conglomerate to the table descriptor
conglomerateList.add(cgd);
// update the conglomerate in the data dictionary so that, when asked for TableDescriptor,
// it's built with the new PK conglomerate
ConglomerateDescriptor[] conglomerateArray = conglomerateList.getConglomerateDescriptors(newConglomNum);
dd.updateConglomerateDescriptor(conglomerateArray, newConglomNum, tc);
}
}
return modifiedConglomerateDescriptor;
}
protected void startCoprocessorJob(Activation activation,
String actionName, // "Add Column", "Drop Column", "Add Primary Key", etc
String schemaName,
String tableName,
Collection<String> columnNames,
CoprocessorJob job,
TxnView txn) throws StandardException {
LanguageConnectionContext lcc = activation.getLanguageConnectionContext();
String user = lcc.getSessionUserId();
Snowflake snowflake = SpliceDriver.driver().getUUIDGenerator();
long sId = snowflake.nextUUID();
if (activation.isTraced()) {
activation.getLanguageConnectionContext().setXplainStatementId(sId);
}
StatementInfo statementInfo = new StatementInfo(String.format("alter table %s.%s %s %s",
schemaName,
tableName,
actionName,
columnNames),
user,txn, 1, sId);
OperationInfo opInfo = new OperationInfo(SpliceDriver.driver().getUUIDGenerator().nextUUID(),
statementInfo.getStatementUuid(),
String.format("Alter Table %s", actionName),
null, false, -1l);
statementInfo.setOperationInfo(Collections.singletonList(opInfo));
SpliceDriver.driver().getStatementManager().addStatementInfo(statementInfo);
JobFuture future = null;
JobInfo info;
try{
long start = System.currentTimeMillis();
future = SpliceDriver.driver().getJobScheduler().submit(job);
info = new JobInfo(job.getJobId(),future.getNumTasks(),start);
info.setJobFuture(future);
statementInfo.addRunningJob(opInfo.getOperationUuid(),info);
try{
future.completeAll(info);
}catch(ExecutionException e){
info.failJob();
throw e;
}catch(CancellationException ce){
throw Exceptions.parseException(ce);
}
statementInfo.completeJob(info);
} catch (ExecutionException e) {
throw Exceptions.parseException(e.getCause());
} catch (InterruptedException e) {
throw Exceptions.parseException(e);
}finally {
if (future!=null) {
try {
future.cleanup();
} catch (ExecutionException e) {
//noinspection ThrowFromFinallyBlock
throw Exceptions.parseException(e.getCause());
}
}
try {
SpliceDriver.driver().getStatementManager().completedStatement(statementInfo, activation.isTraced(),txn);
} catch (IOException e) {
//noinspection ThrowFromFinallyBlock
throw Exceptions.parseException(e);
}
}
}
protected Txn getChainedTransaction(TransactionController tc,
Txn txnToWaitFor,
long tableConglomId,
String alterTableActionName)
throws StandardException {
final TxnView wrapperTxn = ((SpliceTransactionManager)tc).getActiveStateTxn();
/*
* We have an additional waiting transaction that we use to ensure that all elements
* which commit after the demarcation point are committed BEFORE the populate part.
*/
byte[] tableBytes = Long.toString(tableConglomId).getBytes();
Txn waitTxn;
try{
waitTxn =
TransactionLifecycle.getLifecycleManager().chainTransaction(wrapperTxn,
Txn.IsolationLevel.SNAPSHOT_ISOLATION,
false,tableBytes,txnToWaitFor);
}catch(IOException ioe){
LOG.error("Could not create a wait transaction",ioe);
throw Exceptions.parseException(ioe);
}
//get the absolute user transaction
TxnView uTxn = wrapperTxn;
TxnView n = uTxn.getParentTxnView();
while(n.getTxnId()>=0){
uTxn = n;
n = n.getParentTxnView();
}
// Wait for past transactions to complete
long oldestActiveTxn;
try {
oldestActiveTxn = waitForConcurrentTransactions(waitTxn, uTxn,tableConglomId);
} catch (IOException e) {
LOG.error("Unexpected error while waiting for past transactions to complete", e);
throw Exceptions.parseException(e);
}
if (oldestActiveTxn>=0) {
throw ErrorState.DDL_ACTIVE_TRANSACTIONS.newException(alterTableActionName,oldestActiveTxn);
}
Txn populateTxn;
try{
/*
* We need to make the populateTxn a child of the wrapper, so that we can be sure
* that the write pipeline is able to see the conglomerate descriptor. However,
* this makes the SI logic more complex during the populate phase.
*/
populateTxn = TransactionLifecycle.getLifecycleManager().chainTransaction(
wrapperTxn, Txn.IsolationLevel.SNAPSHOT_ISOLATION, true, tableBytes,waitTxn);
} catch (IOException e) {
LOG.error("Couldn't commit transaction for tentative DDL operation");
// TODO cleanup tentative DDL change?
throw Exceptions.parseException(e);
}
return populateTxn;
}
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/**
* Returns the nth value from the Stern-Brocot sequence.
*
* @author Andrei Muntean
*/
public class SternBrocotNumbers
{
// The list of known values from the Stern-Brocot sequence.
private static ArrayList<Double> sequence;
private static boolean isPositiveNumber(String input)
{
try
{
int number = Integer.parseInt(input);
if (number >= 0)
{
return true;
}
else
{
throw new Exception();
}
}
catch (Exception exception)
{
return false;
}
}
// Calculates the nth number from the Stern-Brocot sequence,
// stores it in a list and returns the value.
private static double sternBrocot(int nthSternBrocotNumber)
{
while (sequence.size() <= nthSternBrocotNumber)
{
// The current size of the sequence.
int size = sequence.size();
sequence.add(sequence.get(size / 2 - 1) + sequence.get(size / 2));
sequence.add(sequence.get(size / 2));
}
return sequence.get(nthSternBrocotNumber);
}
/**
* The main method. Reads values from the standard input via the Scanner.
*/
public static void main(String[] args)
{
// Initializes the sequence.
sequence = new ArrayList<>(Arrays.asList(1.0, 1.0));
// Initializes the scanner and waits for input.
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
while (isPositiveNumber(input))
{
int nthSternBrocotNumber = Integer.parseInt(input);
// Shows the nth value from the Stern-Brocot sequence.
System.out.println(sternBrocot(nthSternBrocotNumber));
// Waits for input.
input = scanner.next();
}
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.test.integration;
import com.google.common.net.HttpHeaders;
import com.jayway.restassured.response.Response;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import java.util.HashMap;
import java.util.Map;
import static com.jayway.restassured.RestAssured.*;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Integration tests for projects.
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public class ProjectIntegrationTest {
private static final String PROJECTS = "/projects";
/**
* If I try to issue a create request for an object with an invalid field name, the server should respond with 400.
*/
@Test
public void testCreateProjectBadFieldName() {
Response r = given().body("{ \"projectName\": \"some stupid project\" }").
expect().response().statusCode(HttpStatus.BAD_REQUEST.value()).when().post(PROJECTS);
assertTrue(r.getBody().asString().contains("Unrecognized property [projectName]"));
}
/**
* Field names should be quoted. We should handle that failure gracefully.
*/
@Test
public void testCreateProjectNoQuotes() {
Response r = given().body("{ name: \"some stupid project\" }").
expect().response().statusCode(HttpStatus.BAD_REQUEST.value()).when().post(PROJECTS);
assertTrue(r.getBody().asString().contains("double quotes"));
}
@Test
public void testCreateProject() {
Map<String, String> project = new HashMap<>();
project.put("name", "new project");
Response r = given().body(project).expect().response()
.statusCode(HttpStatus.CREATED.value()).when().post(PROJECTS);
String location = r.getHeader(HttpHeaders.LOCATION);
assertNotNull(location);
assertTrue(location.startsWith("http://localhost:8080/api/projects/"));
}
@Test
public void testGetProject() {
Map<String, String> project = new HashMap<>();
String projectName = "new project";
project.put("name", projectName);
Response r = given().body(project).post(PROJECTS);
String location = r.getHeader(HttpHeaders.LOCATION);
expect().body("resource.name", equalTo(projectName)).and()
.body("resource.links.rel", hasItems("self", "project/users", "project/samples", "project/sequenceFiles"))
.when().get(location);
}
@Test
public void testUpdateProjectName() {
Map<String, String> project = new HashMap<>();
String projectName = "new project";
String updatedName = "updated new project";
project.put("name", projectName);
Response r = given().body(project).post(PROJECTS);
String location = r.getHeader(HttpHeaders.LOCATION);
project.put("name", updatedName);
given().body(project).expect().statusCode(HttpStatus.OK.value()).when().patch(location);
expect().body("resource.name", equalTo(updatedName)).when().get(location);
}
@Test
public void testGetProjects() {
// first page shouldn't have prev link, default view returns 20 projects
String[] expectedProjectNames = new String[20];
for (int i = 0; i < expectedProjectNames.length; i++) {
expectedProjectNames[i] = "Project " + (i + 1);
}
expect().body("resource.links.rel", hasItems("self", "first", "next", "last")).and()
.body("resource.links.rel", not(hasItem("prev"))).and()
.body("resource.totalResources", isA(Integer.class)).and()
.body("resource.resources.name", hasItems(expectedProjectNames)).when().get(PROJECTS);
}
@Test
public void testDeleteProject() {
String projectUri = "http://localhost:8080/api/projects/59106ae3-e20e-4e80-b559-d9ce9f7e348d";
expect().body("resource.links.rel", hasItems("collection")).and()
.body("resource.links.href", hasItems("http://localhost:8080/api/projects")).when().delete(projectUri);
}
@Test
public void verifyRelatedResources() {
// project should have the following related resource names: samples, users, sequenceFiles
String projectUri = "http://localhost:8080/api/projects/abb5b630-4db5-4899-9487-1d8d38b5c752";
expect().body("relatedResources.samples.links.rel", hasItem("project/samples")).and()
.body("relatedResources.users.links.rel", hasItem("project/users")).and()
.body("relatedResources.sequenceFiles.links.rel", hasItem("project/sequenceFiles")).when().get(projectUri);
}
}
|
package step.migration.tasks;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.jongo.Mapper;
import org.jongo.marshall.Unmarshaller;
import org.jongo.marshall.jackson.JacksonMapper;
import com.mongodb.BasicDBObject;
import ch.exense.commons.app.ArgumentParser;
import ch.exense.commons.app.Configuration;
import step.artefacts.CallPlan;
import step.core.GlobalContext;
import step.core.Version;
import step.core.accessors.AccessorLayerJacksonMapperProvider;
import step.core.accessors.MongoClientSession;
import step.core.accessors.PlanAccessorImpl;
import step.core.artefacts.AbstractArtefact;
import step.core.execution.model.Execution;
import step.core.execution.model.ExecutionAccessorImpl;
import step.core.plans.Plan;
import step.core.scheduler.ExecutionTaskAccessorImpl;
import step.core.scheduler.ExecutiontTaskParameters;
import step.functions.accessor.FunctionAccessorImpl;
import step.functions.accessor.FunctionCRUDAccessor;
import step.migration.MigrationTask;
import step.plugins.functions.types.CompositeFunction;
/**
* This task migrates the collection 'artefacts' to the collection 'plans' which has been introduced in 3.13
*
*/
public class MigrateArtefactsToPlans extends MigrationTask {
private static final String CHILDREN_ID_FIELD = "childrenIDs";
private com.mongodb.client.MongoCollection<Document> artefactCollection;
private com.mongodb.client.MongoCollection<Document> functionCollection;
private com.mongodb.client.MongoCollection<Document> executionCollection;
private com.mongodb.client.MongoCollection<Document> tasksCollection;
private PlanAccessorImpl planAccessor;
private ExecutionAccessorImpl executionAccessor;
private ExecutionTaskAccessorImpl executionTaskAccessor;
private FunctionCRUDAccessor functionAccessor;
private Mapper dbLayerObjectMapper;
private Map<ObjectId, ObjectId> artefactIdToPlanId;
private Unmarshaller unmarshaller;
public MigrateArtefactsToPlans() {
super(new Version(3,13,0));
}
@Override
protected void setContext(GlobalContext context) {
super.setContext(context);
init(context.getMongoClientSession());
context.put(MigrateArtefactsToPlans.class, this);
}
protected void init(MongoClientSession mongoClientSession) {
artefactCollection = mongoClientSession.getMongoDatabase().getCollection("artefacts");
executionCollection = mongoClientSession.getMongoDatabase().getCollection("executions");
functionCollection = mongoClientSession.getMongoDatabase().getCollection("functions");
tasksCollection = mongoClientSession.getMongoDatabase().getCollection("tasks");
JacksonMapper.Builder builder2 = new JacksonMapper.Builder();
AccessorLayerJacksonMapperProvider.getModules().forEach(m->builder2.registerModule(m));
dbLayerObjectMapper = builder2.build();
unmarshaller = dbLayerObjectMapper.getUnmarshaller();
planAccessor = new PlanAccessorImpl(mongoClientSession);
executionAccessor = new ExecutionAccessorImpl(mongoClientSession);
executionTaskAccessor = new ExecutionTaskAccessorImpl(mongoClientSession);
functionAccessor = new FunctionAccessorImpl(mongoClientSession);
artefactIdToPlanId = new HashMap<>();
}
@Override
public void runUpgradeScript() {
int count = generatePlanIds();
logger.info("Found "+count+" root artefacts to be migrated. Starting migration...");
migrateArtefactsToPlans();
migrateCompositeFunctionsFunctions();
migrateExecutions();
migrateSchedulerTasks();
}
private int generatePlanIds() {
logger.info("Searching for root artefacts to be migrated...");
AtomicInteger count = new AtomicInteger();
Document filterRootArtefacts = new Document("root", true);
artefactCollection.find(filterRootArtefacts, BasicDBObject.class).iterator().forEachRemaining(t -> {
ObjectId objectId = t.getObjectId("_id");
artefactIdToPlanId.put(objectId, new ObjectId());
count.incrementAndGet();
});
return count.get();
}
private void migrateArtefactsToPlans() {
AtomicInteger successCount = new AtomicInteger();
AtomicInteger errorCount = new AtomicInteger();
Document filterRootArtefacts = new Document("root", true);
artefactCollection.find(filterRootArtefacts, BasicDBObject.class).iterator().forEachRemaining(t -> {
migrateArtefactToPlan(successCount, errorCount, t);
});
logger.info("Migrated "+successCount.get()+" artefacts successfully.");
if(errorCount.get()>0) {
logger.error(errorCount.get() + " artefacts couldn't be migrated. See error logs for details");
}
successCount.set(0);
errorCount.set(0);
}
protected Plan migrateArtefactToPlan(BasicDBObject t) {
return migrateArtefactToPlan(null, null, t);
}
protected Plan migrateArtefactToPlan(AtomicInteger successCount, AtomicInteger errorCount, BasicDBObject t) {
Map<String, String> attributes = new HashMap<>();
try {
BasicDBObject document = (BasicDBObject)t.get("attributes");
if(document != null) {
document.keySet().forEach(key->{
attributes.put(key, document.getString(key));
});
}
AbstractArtefact artefact = unmarshallArtefact(t);
Plan plan = new Plan();
plan.setId(artefactIdToPlanId.get(artefact.getId()));
plan.setAttributes(attributes);
plan.setRoot(artefact);
plan.setVisible(true);
logger.info("Migrated plan "+attributes);
plan = planAccessor.save(plan);
if(successCount != null) {
successCount.incrementAndGet();
}
return plan;
} catch(Exception e) {
logger.error("Error while migrating plan "+attributes, e);
if(errorCount != null) {
errorCount.incrementAndGet();
}
return null;
}
}
@SuppressWarnings("unchecked")
private AbstractArtefact unmarshallArtefact(BasicDBObject t) {
List<ObjectId> childrendIDs = null;
if(t.containsField(CHILDREN_ID_FIELD)) {
childrendIDs = (List<ObjectId>) t.get(CHILDREN_ID_FIELD);
}
t.remove(CHILDREN_ID_FIELD);
AbstractArtefact artefact = unmarshaller.unmarshall(org.jongo.bson.Bson.createDocument(t), AbstractArtefact.class);
if(artefact instanceof CallPlan) {
String artefactId = t.getString("artefactId");
if(artefactId!=null) {
ObjectId referencedPlanId = artefactIdToPlanId.get(new ObjectId(artefactId));
if(referencedPlanId != null) {
((CallPlan) artefact).setPlanId(referencedPlanId.toString());
} else {
logger.warn("The artefact "+artefactId+" referenced by the artefact (call plan) "+t.getObjectId("_id").toString()+" doesn't exist");
}
} else {
// Call by attributes => nothing to do as we're assigning the attributes of the root artefact to the plan
}
}
if(childrendIDs!=null) {
childrendIDs.forEach(childID->{
BasicDBObject child = artefactCollection.find(new Document("_id", childID), BasicDBObject.class).first();
AbstractArtefact artefactChild = unmarshallArtefact(child);
artefact.getChildren().add(artefactChild);
});
}
return artefact;
}
private void migrateCompositeFunctionsFunctions() {
AtomicInteger successCount = new AtomicInteger();
AtomicInteger errorCount = new AtomicInteger();
Document filterCompositeFunction = new Document("type", CompositeFunction.class.getName());
functionCollection.find(filterCompositeFunction, BasicDBObject.class).iterator().forEachRemaining(t -> {
try {
if(t.containsField("artefactId")) {
String id = t.getString("_id");
String artefactId = t.getString("artefactId");
BasicDBObject rootArtefact = artefactCollection.find(new Document("_id", new ObjectId(artefactId)), BasicDBObject.class).first();
if(rootArtefact != null) {
Plan plan = migrateArtefactToPlan(rootArtefact);
if(plan != null) {
ObjectId planId = plan.getId();
t.put("planId", planId);
t.remove("artefactId");
CompositeFunction compositeFunction = unmarshaller.unmarshall(org.jongo.bson.Bson.createDocument(t), CompositeFunction.class);
functionAccessor.save(compositeFunction);
successCount.incrementAndGet();
} else {
errorCount.incrementAndGet();
logger.error("Error while migrating plan for composite function " + id + " with artefactId "+artefactId);
}
} else {
errorCount.incrementAndGet();
logger.error("Unable to find root artefact for composite function " + id + " with artefactId "+artefactId);
}
}
} catch (Exception e) {
errorCount.incrementAndGet();
logger.error("Unexpected error while migrating composite function " + t, e);
}
});
logger.info("Migrated "+successCount.get()+" composite functions successfully.");
if(errorCount.get()>0) {
logger.error("Got "+errorCount+" errors while migrating composite functions. See previous error logs for details.");
}
}
private void migrateExecutions() {
AtomicInteger successCount = new AtomicInteger();
AtomicInteger errorCount = new AtomicInteger();
logger.info("Searching for executions be migrated...");
executionCollection.find(BasicDBObject.class).iterator().forEachRemaining(t -> {
try {
BasicDBObject object = (BasicDBObject) t.get("executionParameters");
ExecutionParametersMigrationResult executionParameterMigrationResult = migrateExecutionParameter(object);
if(executionParameterMigrationResult.executionParametersUpdated) {
// ... and save the result while ensuring integrity by unmarshalling as POJO
Execution execution = unmarshaller.unmarshall(org.jongo.bson.Bson.createDocument(t), Execution.class);
execution.setPlanId(executionParameterMigrationResult.planId);
executionAccessor.save(execution);
successCount.incrementAndGet();
}
} catch (Exception e) {
errorCount.incrementAndGet();
logger.error("Error while migrating execution " + t, e);
}
});
logger.info("Migrated "+successCount.get()+" executions successfully.");
if(errorCount.get()>0) {
logger.error("Got "+errorCount+" errors while migrating executions. See previous error logs for details.");
}
}
protected static class ExecutionParametersMigrationResult {
boolean executionParametersUpdated;
String planId;
}
protected ExecutionParametersMigrationResult migrateExecutionParameter(BasicDBObject object) {
ExecutionParametersMigrationResult result = new ExecutionParametersMigrationResult();
if(object != null) {
BasicDBObject artefact = (BasicDBObject) object.get("artefact");
if(artefact != null) {
// Rename the field "repositoryParameters.artefactid" to "repositoryParameters.planid"
String planIdString = migrateRepositoryObjectReference(artefact);
result.planId = planIdString;
// Rename the field "artefact" to "repositoryObject"
object.put("repositoryObject", artefact);
object.remove("artefact");
result.executionParametersUpdated = true;
}
}
return result;
}
protected String migrateRepositoryObjectReference(BasicDBObject artefact) {
String result = null;
ObjectId planId;
BasicDBObject repositoryParameters = (BasicDBObject) artefact.get("repositoryParameters");
if(repositoryParameters != null) {
String artefactId = repositoryParameters.getString("artefactid");
if(artefactId != null) {
planId = artefactIdToPlanId.get(new ObjectId(artefactId));
if(planId != null) {
String planIdString = planId.toString();
repositoryParameters.put("planid", planIdString);
result = planIdString;
}
repositoryParameters.remove("artefactid");
}
}
return result;
}
private void migrateSchedulerTasks() {
tasksCollection.find(BasicDBObject.class).iterator().forEachRemaining(t -> {
BasicDBObject executionsParameters = (BasicDBObject) t.get("executionsParameters");
ExecutionParametersMigrationResult executionParameterMigrationResult = migrateExecutionParameter(executionsParameters);
if(executionParameterMigrationResult.executionParametersUpdated) {
ExecutiontTaskParameters executionTaskParameters = unmarshaller.unmarshall(org.jongo.bson.Bson.createDocument(t), ExecutiontTaskParameters.class);
executionTaskAccessor.save(executionTaskParameters);
}
});
}
public static void main(String[] args) throws IOException {
ArgumentParser arguments = new ArgumentParser(args);
Configuration configuration;
if(arguments.hasOption("config")) {
configuration = new Configuration(new File(arguments.getOption("config")));
} else {
configuration = new Configuration();
configuration.putProperty("db.host", "localhost");
}
MongoClientSession mongoClientSession = new MongoClientSession(configuration);
MigrateArtefactsToPlans task = new MigrateArtefactsToPlans();
task.init(mongoClientSession);
task.runUpgradeScript();
}
@Override
public void runDowngradeScript() {
}
}
|
package info.bitrich.xchangestream.service.netty;
import info.bitrich.xchangestream.service.ConnectableService;
import info.bitrich.xchangestream.service.exception.NotConnectedException;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketClientExtensionHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.proxy.Socks5ProxyHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.internal.SocketUtils;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.subjects.PublishSubject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class NettyStreamingService<T> extends ConnectableService {
private final Logger LOG = LoggerFactory.getLogger(this.getClass());
protected static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(10);
protected static final Duration DEFAULT_RETRY_DURATION = Duration.ofSeconds(15);
protected static final int DEFAULT_IDLE_TIMEOUT = 0;
private class Subscription {
final ObservableEmitter<T> emitter;
final String channelName;
final Object[] args;
public Subscription(ObservableEmitter<T> emitter, String channelName, Object[] args) {
this.emitter = emitter;
this.channelName = channelName;
this.args = args;
}
}
private final int maxFramePayloadLength;
private final URI uri;
private final AtomicBoolean isManualDisconnect = new AtomicBoolean();
private Channel webSocketChannel;
private final Duration retryDuration;
private final Duration connectionTimeout;
private final int idleTimeoutSeconds;
private volatile NioEventLoopGroup eventLoopGroup;
protected final Map<String, Subscription> channels = new ConcurrentHashMap<>();
private boolean compressedMessages = false;
private final List<ObservableEmitter<Throwable>> reconnFailEmitters = new LinkedList<>();
private final List<ObservableEmitter<Object>> connectionSuccessEmitters = new LinkedList<>();
private final PublishSubject<Object> subjectIdle = PublishSubject.create();
// debugging
private boolean acceptAllCertificates = false;
private boolean enableLoggingHandler = false;
private boolean disableNettyReconnect = false;
private LogLevel loggingHandlerLevel = LogLevel.DEBUG;
private String socksProxyHost;
private Integer socksProxyPort;
public NettyStreamingService(String apiUrl) {
this(apiUrl, 65536);
}
public NettyStreamingService(String apiUrl, int maxFramePayloadLength) {
this(apiUrl, maxFramePayloadLength, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_RETRY_DURATION);
}
public NettyStreamingService(
String apiUrl,
int maxFramePayloadLength,
Duration connectionTimeout,
Duration retryDuration) {
this(
apiUrl,
maxFramePayloadLength,
connectionTimeout,
retryDuration,
DEFAULT_IDLE_TIMEOUT);
}
public NettyStreamingService(
String apiUrl,
int maxFramePayloadLength,
Duration connectionTimeout,
Duration retryDuration,
int idleTimeoutSeconds) {
this.maxFramePayloadLength = maxFramePayloadLength;
this.retryDuration = retryDuration;
this.connectionTimeout = connectionTimeout;
this.idleTimeoutSeconds = idleTimeoutSeconds;
try {
this.uri = new URI(apiUrl);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Error parsing URI " + apiUrl, e);
}
}
@Override
protected Completable openConnection() {
return Completable.create(
completable -> {
try {
LOG.info("Connecting to {}", uri.toString());
String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
String host = uri.getHost();
if (host == null) {
throw new IllegalArgumentException("Host cannot be null.");
}
final int port;
if (uri.getPort() == -1) {
if ("ws".equalsIgnoreCase(scheme)) {
port = 80;
} else if ("wss".equalsIgnoreCase(scheme)) {
port = 443;
} else {
port = -1;
}
} else {
port = uri.getPort();
}
if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
throw new IllegalArgumentException("Only WS(S) is supported.");
}
final boolean ssl = "wss".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
if (acceptAllCertificates) {
sslContextBuilder =
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
}
sslCtx = sslContextBuilder.build();
} else {
sslCtx = null;
}
final WebSocketClientHandler handler =
getWebSocketClientHandler(
WebSocketClientHandshakerFactory.newHandshaker(
uri,
WebSocketVersion.V13,
null,
true,
getCustomHeaders(),
maxFramePayloadLength),
this::messageHandler);
if (eventLoopGroup == null || eventLoopGroup.isShutdown()) {
eventLoopGroup = new NioEventLoopGroup(2);
}
new Bootstrap()
.group(eventLoopGroup)
.option(
ChannelOption.CONNECT_TIMEOUT_MILLIS,
java.lang.Math.toIntExact(connectionTimeout.toMillis()))
.option(ChannelOption.SO_KEEPALIVE, true)
.channel(NioSocketChannel.class)
.handler(
new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (socksProxyHost != null) {
p.addLast(
new Socks5ProxyHandler(
SocketUtils.socketAddress(socksProxyHost, socksProxyPort)));
}
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
}
p.addLast(new HttpClientCodec());
if (enableLoggingHandler)
p.addLast(new LoggingHandler(loggingHandlerLevel));
if (compressedMessages)
p.addLast(WebSocketClientCompressionHandler.INSTANCE);
p.addLast(new HttpObjectAggregator(8192));
if (idleTimeoutSeconds > 0)
p.addLast(new IdleStateHandler(idleTimeoutSeconds, 0, 0));
WebSocketClientExtensionHandler clientExtensionHandler =
getWebSocketClientExtensionHandler();
if (clientExtensionHandler != null) {
p.addLast(clientExtensionHandler);
}
p.addLast(handler);
}
})
.connect(uri.getHost(), port)
.addListener(
(ChannelFuture channelFuture) -> {
webSocketChannel = channelFuture.channel();
if (channelFuture.isSuccess()) {
handler
.handshakeFuture()
.addListener(
handshakeFuture -> {
if (handshakeFuture.isSuccess()) {
completable.onComplete();
} else {
webSocketChannel
.disconnect()
.addListener(
x -> {
completable.onError(handshakeFuture.cause());
});
}
});
} else {
scheduleReconnect();
completable.onError(channelFuture.cause());
}
});
} catch (Exception throwable) {
scheduleReconnect();
completable.onError(throwable);
}
})
.doOnError(
t -> {
if (t instanceof WebSocketHandshakeException) {
LOG.warn("Problem with connection: {} - {}", t.getClass(), t.getMessage());
} else {
LOG.warn("Problem with connection", t);
}
reconnFailEmitters.forEach(emitter -> emitter.onNext(t));
})
.doOnComplete(
() -> {
LOG.warn("Resubscribing channels");
resubscribeChannels();
connectionSuccessEmitters.forEach(emitter -> emitter.onNext(new Object()));
});
}
private void scheduleReconnect() {
if (disableNettyReconnect) {
reconnFailEmitters.forEach(emitter -> emitter.onNext(new Exception("Netty reconnection disabled")));
} else {
LOG.info("Scheduling reconnection");
webSocketChannel.eventLoop().schedule(
() -> connect().subscribe(),
retryDuration.toMillis(),
TimeUnit.MILLISECONDS);
}
}
protected DefaultHttpHeaders getCustomHeaders() {
return new DefaultHttpHeaders();
}
public Completable disconnect() {
isManualDisconnect.set(true);
return Completable.create(
completable -> {
if (webSocketChannel != null && webSocketChannel.isOpen()) {
CloseWebSocketFrame closeFrame = new CloseWebSocketFrame();
webSocketChannel
.writeAndFlush(closeFrame)
.addListener(
future -> {
channels.clear();
eventLoopGroup
.shutdownGracefully(2, 30, TimeUnit.SECONDS)
.addListener(
f -> {
LOG.info("Disconnected");
completable.onComplete();
});
});
} else {
LOG.warn("Disconnect called but already disconnected");
completable.onComplete();
}
});
}
protected abstract String getChannelNameFromMessage(T message) throws IOException;
public abstract String getSubscribeMessage(String channelName, Object... args) throws IOException;
public abstract String getUnsubscribeMessage(String channelName) throws IOException;
public String getSubscriptionUniqueId(String channelName, Object... args) {
return channelName;
}
/**
* Handler that receives incoming messages.
*
* @param message Content of the message from the server.
*/
public abstract void messageHandler(String message);
public void sendMessage(String message) {
LOG.debug("Sending message: {}", message);
if (webSocketChannel == null || !webSocketChannel.isOpen()) {
LOG.warn("WebSocket is not open! Call connect first.");
return;
}
if (!webSocketChannel.isWritable()) {
LOG.warn("Cannot send data to WebSocket as it is not writable.");
return;
}
if (message != null) {
WebSocketFrame frame = new TextWebSocketFrame(message);
webSocketChannel.writeAndFlush(frame);
}
}
public Observable<Throwable> subscribeReconnectFailure() {
return Observable.create(reconnFailEmitters::add);
}
public Observable<Object> subscribeConnectionSuccess() {
return Observable.create(connectionSuccessEmitters::add);
}
public Observable<T> subscribeChannel(String channelName, Object... args) {
final String channelId = getSubscriptionUniqueId(channelName, args);
LOG.info("Subscribing to channel {}", channelId);
return Observable.<T>create(
e -> {
if (webSocketChannel == null || !webSocketChannel.isOpen()) {
e.onError(new NotConnectedException());
}
channels.computeIfAbsent(
channelId,
cid -> {
Subscription newSubscription = new Subscription(e, channelName, args);
try {
sendMessage(getSubscribeMessage(channelName, args));
} catch (IOException throwable) {
e.onError(throwable);
}
return newSubscription;
});
})
.doOnDispose(
() -> {
if (channels.remove(channelId) != null) {
sendMessage(getUnsubscribeMessage(channelId));
}
})
.share();
}
public void resubscribeChannels() {
for (Entry<String, Subscription> entry : channels.entrySet()) {
try {
Subscription subscription = entry.getValue();
sendMessage(getSubscribeMessage(subscription.channelName, subscription.args));
} catch (IOException e) {
LOG.error("Failed to reconnect channel: {}", entry.getKey());
}
}
}
protected String getChannel(T message) {
String channel;
try {
channel = getChannelNameFromMessage(message);
} catch (IOException e) {
LOG.error("Cannot parse channel from message: {}", message);
return "";
}
return channel;
}
protected void handleMessage(T message) {
String channel = getChannel(message);
handleChannelMessage(channel, message);
}
protected void handleError(T message, Throwable t) {
String channel = getChannel(message);
handleChannelError(channel, t);
}
protected void handleIdle(ChannelHandlerContext ctx) {
// No-op
}
private void onIdle(ChannelHandlerContext ctx) {
subjectIdle.onNext(1);
handleIdle(ctx);
}
/**
* Observable which fires if the websocket is deemed idle, only fired if <code>
* idleTimeoutSeconds != 0</code>.
*/
public Observable<Object> subscribeIdle() {
return subjectIdle.share();
}
protected void handleChannelMessage(String channel, T message) {
NettyStreamingService<T>.Subscription subscription = channels.get(channel);
if (subscription == null) {
LOG.debug("Channel has been closed {}.", channel);
return;
}
ObservableEmitter<T> emitter = subscription.emitter;
if (emitter == null) {
LOG.debug("No subscriber for channel {}.", channel);
return;
}
emitter.onNext(message);
}
protected void handleChannelError(String channel, Throwable t) {
NettyStreamingService<T>.Subscription subscription = channels.get(channel);
if (subscription == null) {
LOG.debug("Channel {} has been closed.", channel);
return;
}
ObservableEmitter<T> emitter = subscription.emitter;
if (emitter == null) {
LOG.debug("No subscriber for channel {}.", channel);
return;
}
emitter.onError(t);
}
protected WebSocketClientExtensionHandler getWebSocketClientExtensionHandler() {
return WebSocketClientCompressionHandler.INSTANCE;
}
protected WebSocketClientHandler getWebSocketClientHandler(
WebSocketClientHandshaker handshaker,
WebSocketClientHandler.WebSocketMessageHandler handler) {
return new NettyWebSocketClientHandler(handshaker, handler);
}
protected class NettyWebSocketClientHandler extends WebSocketClientHandler {
protected NettyWebSocketClientHandler(
WebSocketClientHandshaker handshaker, WebSocketMessageHandler handler) {
super(handshaker, handler);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
if (isManualDisconnect.compareAndSet(true, false)) {
// Don't attempt to reconnect
} else {
super.channelInactive(ctx);
LOG.info("Reopening websocket because it was closed");
scheduleReconnect();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (!(evt instanceof IdleStateEvent)) {
return;
}
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state().equals(IdleState.READER_IDLE)) {
onIdle(ctx);
}
}
}
public boolean isSocketOpen() {
return webSocketChannel != null && webSocketChannel.isOpen();
}
public void useCompressedMessages(boolean compressedMessages) {
this.compressedMessages = compressedMessages;
}
public void setAcceptAllCertificates(boolean acceptAllCertificates) {
this.acceptAllCertificates = acceptAllCertificates;
}
public void setEnableLoggingHandler(boolean enableLoggingHandler) {
this.enableLoggingHandler = enableLoggingHandler;
}
public void setLoggingHandlerLevel(LogLevel loggingHandlerLevel) {
this.loggingHandlerLevel = loggingHandlerLevel;
}
public void setSocksProxyHost(String socksProxyHost) {
this.socksProxyHost = socksProxyHost;
}
public void setSocksProxyPort(Integer socksProxyPort) {
this.socksProxyPort = socksProxyPort;
}
public void setDisableNettyReconnect(boolean noRetry) {
this.disableNettyReconnect = noRetry;
}
}
|
package org.opendaylight.yangtools.yang.model.api.stmt;
import com.google.common.annotations.Beta;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
/**
* Effective view of a {@link ModuleStatement}.
*/
@Beta
// FIXME: 4.0.0: we should reshuffle the String here, as module name is in reality a YANG identifier, e.g. not just
// an ordinary String. We really want this to be a QName, so that we do not need the localQNameModule
// bit, but that may be problematic with ModuleStatement, which is getting created before we even know
// the namespace :( A type capture of the string may just be sufficient.
public interface ModuleEffectiveStatement extends DataTreeAwareEffectiveStatement<String, ModuleStatement> {
/**
* Namespace mapping all known prefixes in a module to their modules. Note this namespace includes the module
* in which it is instantiated.
*/
abstract class PrefixToEffectiveModuleNamespace
implements IdentifierNamespace<String, @NonNull ModuleEffectiveStatement> {
private PrefixToEffectiveModuleNamespace() {
// This class should never be subclassed
}
}
/**
* Namespace mapping all known {@link QNameModule}s to their encoding prefixes. This includes the declaration
* from prefix/namespace/revision and all imports as they were resolved.
*/
abstract class QNameModuleToPrefixNamespace implements IdentifierNamespace<QNameModule, @NonNull String> {
private QNameModuleToPrefixNamespace() {
// This class should never be subclassed
}
}
/**
* Namespace mapping all included submodules. The namespaces is keyed by submodule name.
*/
abstract class NameToEffectiveSubmoduleNamespace
implements IdentifierNamespace<String, @NonNull SubmoduleEffectiveStatement> {
private NameToEffectiveSubmoduleNamespace() {
// This class should never be subclassed
}
}
/**
* Get the local QNameModule of this module. All implementations need to override this default method.
*
* @return Local QNameModule
*/
@NonNull QNameModule localQNameModule();
}
|
package org.firstinspires.ftc.team7316.util.commands.drive;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.LightSensor;
import org.firstinspires.ftc.team7316.util.Alliance;
import org.firstinspires.ftc.team7316.util.Loopable;
import org.firstinspires.ftc.team7316.util.hardware.Hardware;
public class LineFollowDoubleSensor implements Loopable {
enum State {
CLAMPED,
NOTCLAMPED
}
private State state = State.NOTCLAMPED;
private LightSensor leftLightSensor;
private LightSensor rightLightSensor;
private DcMotor leftMotor;
private DcMotor rightMotor;
private int counter = 0;
private double p = 0; //ratio of error to turn
private double i = 0; //ration of sum of errors to turn
private double d = 0; //ratio of delta to turn
private double deltaError = 0;
private double lastError = 0;
private double errorSum = 0;
private int sumCounts = 0;
private final double clampedThreshold = 0.2; //both sensors must be higher than this value
private final double unclampedThreshold = 1.5; //this is based on the sum of the sensors
private final double clampedP = 0.6;
private final double clampedI = 0;
private final double clampedD = 1;
private final double unclampedP = 0.6;
private final double unclampedI = 0;
private final double unclampedD = 2;
private double wantedPower;
private final double wantedSensorSum = 0.5;
public LineFollowDoubleSensor (DcMotor leftMotor, DcMotor rightMotor, LightSensor leftSensor, LightSensor rightSensor, double wantedPower) {
this(leftMotor, rightMotor, leftSensor, rightSensor, wantedPower, Alliance.BLUE);
}
public LineFollowDoubleSensor (DcMotor leftMotor, DcMotor rightMotor, LightSensor leftSensor, LightSensor rightSensor, double wantedPower, Alliance color) {
this.leftLightSensor = leftSensor;
this.rightLightSensor = rightSensor;
this.leftMotor = leftMotor;
this.rightMotor = rightMotor;
this.wantedPower = wantedPower;
}
@Override
public void init() {
state = State.NOTCLAMPED;
this.deltaError = 0;
this.lastError = 0;
this.errorSum = 0;
this.counter = 0;
this.sumCounts = 0;
leftLightSensor.enableLed(true);
rightLightSensor.enableLed(true);
}
@Override
public void loop() {
double error = 0;
Hardware.log(Hardware.tag, "Left: " + leftLightSensor.getLightDetected());
Hardware.log(Hardware.tag, "Right: " + rightLightSensor.getLightDetected());
//check which state we are in
if (state == State.NOTCLAMPED) { //this state will use the difference in the sensors as the error
if (leftLightSensor.getLightDetected() > this.clampedThreshold && rightLightSensor.getLightDetected() > this.clampedThreshold) { //both sensors must be higher than a value WAYNE DID THIS
state = State.CLAMPED;
resetPID();
error = unclampedError();
} else {
error = clampedError();
}
} else if (state == State.CLAMPED) {
if (error > this.clampedThreshold) { //the combined error must be higher than a threshold, then we are off the line WAYNE IS SO COOL
state = State.NOTCLAMPED;
resetPID();
error = clampedError();
} else {
error = unclampedError();
}
}
//pid engine
double leftPower = p * error + i * errorSum + d * deltaError;
double rightPower = p * error + i * errorSum + d * deltaError;
//I PROBABLY DID THIS ALL WRONG - <3 Wayne
this.errorSum += error;
if (counter % 3 == 0) {
this.deltaError = 0;
}
this.deltaError += error - this.lastError;
counter++;
lastError = error;
}
@Override
public boolean shouldRemove() {
return false;
}
@Override
public void terminate() {
leftMotor.setPower(0);
rightMotor.setPower(0);
leftLightSensor.enableLed(false);
rightLightSensor.enableLed(false);
}
public double clampedError() {
double leftVal = invertSensor(leftLightSensor.getLightDetected());
double rightVal = invertSensor(rightLightSensor.getLightDetected());
return rightVal - leftVal; //1 means turn right, -1 means turn left
}
public double unclampedError() {
double leftVal = invertSensor(leftLightSensor.getLightDetected()); //THIS CODE WILL NOT WORK IF THE LIGHT SENSORS ARE TOO FAR APART
double rightVal = invertSensor(rightLightSensor.getLightDetected());
return leftVal + rightVal - wantedSensorSum;
}
public double invertSensor(double sensorValue) { //assuming sensor goes from 0 to 1
return 1 - sensorValue;
}
public void resetPID() {
this.deltaError = 0;
this.lastError = 0;
this.errorSum = 0;
this.counter = 0;
this.sumCounts = 0;
if (state == State.NOTCLAMPED) {
this.p = this.unclampedP;
this.i = this.unclampedI;
this.d = this.unclampedD;
} else if (state == State.CLAMPED) {
this.p = this.clampedP;
this.i = this.clampedI;
this.d = this.clampedD;
}
}
}
|
package org.splevo.jamopp.extraction;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.emftext.language.java.JavaClasspath;
import org.emftext.language.java.JavaPackage;
import org.emftext.language.java.resource.JavaSourceOrClassFileResourceFactoryImpl;
import org.emftext.language.java.resource.java.IJavaOptions;
import org.splevo.extraction.SoftwareModelExtractionException;
import org.splevo.extraction.SoftwareModelExtractor;
import org.splevo.jamopp.extraction.cache.ReferenceCache;
import com.google.common.collect.Lists;
/**
* Software Model Extractor for the Java technology based on the Java Model Parser and Printer
* (JaMoPP).
*/
public class JaMoPPSoftwareModelExtractor implements SoftwareModelExtractor {
private static Logger logger = Logger.getLogger(JaMoPPSoftwareModelExtractor.class);
private static final String EXTRACTOR_ID = "JaMoPPSoftwareModelExtractor";
private static final String EXTRACTOR_LABEL = "JaMoPP Software Model Extractor";
/** Option to resolve all proxies in the model immediately after resource loading. */
private boolean resolveProxiesImmediately = false;
/** Use the reference resolution caching */
private boolean useCache = true;
/**
* Extract the source model of a list of java projects. One project is the main project while a
* list of additional projects to analyze can be specified. The reason for one main project is,
* that this one is used for example for the naming of the root inventory produced etc.
*
* @param projectPaths
* Source Paths of the projects to be extracted.
* @param monitor
* The monitor to report the progress to.
* @return The set of resources containing the extracted model.
* @throws SoftwareModelExtractionException
* Identifies the extraction was not successful.
*/
public ResourceSet extractSoftwareModel(List<URI> projectPaths, IProgressMonitor monitor)
throws SoftwareModelExtractionException {
return extractSoftwareModel(projectPaths, monitor, null);
}
/**
* Extract all java files and referenced resources to a file named according to
* {@link JaMoPPSoftwareModelExtractor#XMI_FILE_SEGMENT} within the provided targetURI.
*
* <p>
* If the targetUri is null, the extracted model will not be persisted and the resourceSet of
* the last projectURI will be returned.
* </p>
* {@inheritDoc}
*/
@Override
public ResourceSet extractSoftwareModel(List<URI> projectPaths, IProgressMonitor monitor, URI targetURI)
throws SoftwareModelExtractionException {
ResourceSet targetResourceSet = setUpResourceSet();
JavaClasspath cp = JavaClasspath.get(targetResourceSet);
for (URI projectPathURI : projectPaths) {
String projectPath = projectPathURI.toFileString();
cp.getURIMap().put(projectPathURI, URI.createURI(""));
File srcFolder = new File(projectPath);
try {
srcFolder.isDirectory();
int jarCount = addAllJarFilesToClassPath(srcFolder, cp);
int javaCount = loadAllJavaFilesInResourceSet(srcFolder, targetResourceSet);
logger.info(String.format("%d Java and %d Jar Files added to resource set", javaCount, jarCount));
} catch (Exception e) {
throw new SoftwareModelExtractionException("Failed to extract software model.", e);
}
}
if (useCache && targetURI != null) {
String cacheFile = targetURI.toFileString() + File.separator + projectPaths.hashCode() + ".cache";
logger.info("Use cache file: " + cacheFile);
ReferenceCache referenceCache = new ReferenceCache(cacheFile);
referenceCache.load();
int notResolvedFromCacheCount = 0;
List<Resource> resources = Lists.newArrayList(targetResourceSet.getResources());
for (Resource resource : resources) {
referenceCache.resolve(resource);
notResolvedFromCacheCount += EcoreUtil.ProxyCrossReferencer.find(resource).size();
}
referenceCache.save();
logger.info("Proxies not resolved from cache: " + notResolvedFromCacheCount);
logger.info("Use cache file: " + cacheFile);
}
if (resolveProxiesImmediately) {
logger.info("Resolve all proxies");
if (!resolveAllProxies(targetResourceSet)) {
handleFailedProxyResolution(targetResourceSet);
}
}
return targetResourceSet;
}
/**
* Resolve all proxies of the loaded sources.
*
* This is a slightly modified version of the JaMoPPCC proxy resolution. It is not called
* recursively because the extractor ensures all available resources have been loaded in
* advance.<br>
* The code has also been cleaned up.
*
* Note: The same result could also be achieved by calling {@link EcoreUtil} resolveAll() but
* this would not allow to track any non resolved proxies.
*
* @param rs
* The resource set to resolve the proxies in.
* @return True/False if the resolving was successful or not.
*/
private boolean resolveAllProxies(ResourceSet rs) {
boolean failure = false;
for (Iterator<Notifier> i = rs.getAllContents(); i.hasNext();) {
Notifier next = i.next();
if (next instanceof InternalEObject) {
failure = resolveProxyReferences(rs, (InternalEObject) next);
}
}
return !failure;
}
/**
* Resolve the proxies of all cross referenced eobjects of an internal object.
*
* @param rs
* The resource set to resolve the proxies.
* @param internalEObject
* The internal object to process the cross references of.
* @return True if one or more proxy resolutions failed.
*/
private boolean resolveProxyReferences(ResourceSet rs, InternalEObject internalEObject) {
boolean failure = false;
for (EObject crElement : internalEObject.eCrossReferences()) {
if (crElement.eIsProxy()) {
crElement = EcoreUtil.resolve(crElement, rs);
if (crElement.eIsProxy()) {
failure = true;
logger.warn("Can not find referenced element in classpath: "
+ ((InternalEObject) crElement).eProxyURI());
}
}
}
return failure;
}
/**
* Handle any failed proxy resolution.
*
* @param rs
* The resource set to prove for any un-handled proxies.
*/
private void handleFailedProxyResolution(ResourceSet rs) {
logger.error("Resolution of some Proxies failed...");
Iterator<Notifier> it = rs.getAllContents();
while (it.hasNext()) {
Notifier next = it.next();
if (next instanceof EObject) {
EObject o = (EObject) next;
if (o.eIsProxy()) {
try {
it.remove();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
logger.info("Error during unresolved proxy handling", e);
}
}
}
}
}
/**
* Register all jars contained in the project.
*
* @param projectDirectory
* The base directory to find jar files in.
* @param classPath
* The virtual class path for the parser.
* @return the number of jar files added to the Classpath
* @throws IOException
* Any exception during jar access.
*/
private int addAllJarFilesToClassPath(File projectDirectory, JavaClasspath classPath) throws IOException {
Collection<File> jarFiles = FileUtils.listFiles(projectDirectory, new String[] { "jar" }, true);
for (File jarPath : jarFiles) {
if (jarPath.exists()) {
classPath.registerClassifierJar(URI.createFileURI(jarPath.getCanonicalPath()));
}
}
return jarFiles.size();
}
/**
* Load a all files as resource in a specific folder and it's sub folders.
*
* @param rootFolder
* The root folder to recursively load all resources from.
* @param rs
* The resource set to add it to.
* @return The number of loaded java files.
* @throws IOException
* An exception during resource access.
*/
private int loadAllJavaFilesInResourceSet(File rootFolder, ResourceSet rs) throws IOException {
Collection<File> javaFiles = FileUtils.listFiles(rootFolder, new String[] { "java" }, true);
for (File javaFile : javaFiles) {
parseResource(javaFile, rs);
}
return javaFiles.size();
}
/**
* Load a specific resource.
*
* @param file
* The file object to load as resource.
* @param rs
* The resource set to add it to.
* @throws IOException
* An exception during resource access.
*/
private void parseResource(File file, ResourceSet rs) throws IOException {
loadResource(file.getCanonicalPath(), rs);
}
/**
* Load a specific resource.
*
* @param filePath
* The path of the file to load.
* @param rs
* The resource set to add it to.
* @throws IOException
* An exception during resource access.
*/
private void loadResource(String filePath, ResourceSet rs) throws IOException {
loadResource(URI.createFileURI(filePath), rs);
}
/**
* Load a specific resource.
*
* @param uri
* The uri of the resource.
* @param rs
* The resource set to add it to.
* @throws IOException
* An exception during resource access.
*/
private void loadResource(URI uri, ResourceSet rs) throws IOException {
rs.getResource(uri, true);
}
/**
* Setup the JaMoPP resource set and prepare the parsing options for the java resource type.
*
* @return The initialized resource set.
*/
private ResourceSet setUpResourceSet() {
ResourceSet rs = new ResourceSetImpl();
Map<Object, Object> options = rs.getLoadOptions();
options.put(IJavaOptions.DISABLE_LAYOUT_INFORMATION_RECORDING, Boolean.TRUE);
options.put(IJavaOptions.DISABLE_LOCATION_MAP, Boolean.TRUE);
options.put(JavaClasspath.OPTION_USE_LOCAL_CLASSPATH, Boolean.TRUE);
EPackage.Registry.INSTANCE.put("http:
Map<String, Object> factoryMap = rs.getResourceFactoryRegistry().getExtensionToFactoryMap();
factoryMap.put("java", new JavaSourceOrClassFileResourceFactoryImpl());
factoryMap.put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
return rs;
}
@Override
public String getId() {
return EXTRACTOR_ID;
}
@Override
public String getLabel() {
return EXTRACTOR_LABEL;
}
}
|
package cc.hughes.droidchatty;
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.Html;
import android.text.Spanned;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class SingleThreadView extends ListActivity {
static final String THREAD_ID = "THREAD_ID";
static final String THREAD_CONTENT = "THREAD_CONTENT";
static final String THREAD_AUTHOR = "THREAD_AUTHOR";
static final String THREAD_POSTED = "THREAD_POSTED";
private int _currentThreadId;
private int _rootThreadId;
private ProgressDialog _progressDialog = null;
private ArrayList<Thread> _posts = null;
private ThreadAdapter _adapter;
private Runnable _retrieveThreads = new Runnable()
{
public void run()
{
getPosts();
}
};
private Runnable _displayThreads = new Runnable()
{
public void run()
{
if (_posts != null && _posts.size() > 0)
{
// remove the elements, and add in all the new ones
_adapter.clear();
for (Thread t : _posts)
{
_adapter.add(t);
}
_progressDialog.dismiss();
_adapter.notifyDataSetChanged();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread_view);
_posts = new ArrayList<Thread>();
_adapter = new ThreadAdapter(this, R.layout.thread_row, _posts);
setListAdapter(_adapter);
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayPost(_posts.get(position));
lv.setSelection(position);
}
});
Bundle extras = getIntent().getExtras();
_rootThreadId = extras.getInt(THREAD_ID);
String content = extras.getString(THREAD_CONTENT);
String author = extras.getString(THREAD_AUTHOR);
String posted = extras.getString(THREAD_POSTED);
Thread thread = new Thread();
thread.setThreadID(_rootThreadId);
thread.setContent(content);
thread.setPostedTime(posted);
thread.setUserName(author);
displayPost(thread);
startRefresh();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.thread_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.refresh:
startRefresh();
return true;
case R.id.copyUrl:
copyCurrentPostUrl();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void copyCurrentPostUrl()
{
String url = "http:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(url);
}
private void displayPost(Thread thread)
{
TextView tvAuthor = (TextView)findViewById(R.id.textUserName);
TextView tvContent = (TextView)findViewById(R.id.textContent);
TextView tvPosted = (TextView)findViewById(R.id.textPostedTime);
tvAuthor.setText(thread.getUserName());
tvPosted.setText(thread.getPostedTime());
tvContent.setText(fixContent(thread.getContent()));
Linkify.addLinks(tvContent, Linkify.ALL);
tvContent.setClickable(false);
_currentThreadId = thread.getThreadID();
}
private void startRefresh()
{
java.lang.Thread thread = new java.lang.Thread(null, _retrieveThreads, "Background");
thread.start();
_progressDialog = ProgressDialog.show(this, "Please wait...", "Retrieving posts...", true);
}
private void getPosts()
{
try
{
_posts = ShackApi.getThread(_rootThreadId);
} catch (Exception ex)
{
ex.printStackTrace();
}
runOnUiThread(_displayThreads);
}
private Spanned fixContent(String content)
{
// convert shack's css into real font colors since Html.fromHtml doesn't supporty css of any kind
content = content.replaceAll("<span class=\"jt_red\">(.*?)</span>", "<font color=\"#ff0000\">$1</font>");
content = content.replaceAll("<span class=\"jt_green\">(.*?)</span>", "<font color=\"#8dc63f\">$1</font>");
content = content.replaceAll("<span class=\"jt_pink\">(.*?)</span>", "<font color=\"#f49ac1\">$1</font>");
content = content.replaceAll("<span class=\"jt_olive\">(.*?)</span>", "<font color=\"#808000\">$1</font>");
content = content.replaceAll("<span class=\"jt_fuchsia\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>");
content = content.replaceAll("<span class=\"jt_yellow\">(.*?)</span>", "<font color=\"#ffde00\">$1</font>");
content = content.replaceAll("<span class=\"jt_blue\">(.*?)</span>", "<font color=\"#44aedf\">$1</font>");
content = content.replaceAll("<span class=\"jt_lime\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>");
content = content.replaceAll("<span class=\"jt_orange\">(.*?)</span>", "<font color=\"#f7941c\">$1</font>");
content = content.replaceAll("<span class=\"jt_bold\">(.*?)</span>", "<b>$1</b>");
content = content.replaceAll("<span class=\"jt_italic\">(.*?)</span>", "<i>$1</i>");
content = content.replaceAll("<span class=\"jt_underline\">(.*?)</span>", "<u>$1</u>");
content = content.replaceAll("<span class=\"jt_strike\">(.*?)</span>", "<del>1</del>");
return Html.fromHtml(content);
}
class ThreadAdapter extends ArrayAdapter<Thread> {
private ArrayList<Thread> items;
public ThreadAdapter(Context context, int textViewResourceId, ArrayList<Thread> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.thread_row, null);
}
// get the thread to display and populate all the data into the layout
Thread t = items.get(position);
if (t != null)
{
TextView tvContent = (TextView)v.findViewById(R.id.textPreview);
if (tvContent != null)
{
tvContent.setPadding(15 * t.getLevel(), 0, 0, 0);
tvContent.setText(fixContent(t.getContent()));
}
}
return v;
}
private Spanned fixContent(String content)
{
// convert shack's css into real font colors since Html.fromHtml doesn't supporty css of any kind
content = content.replaceAll("<span class=\"jt_red\">(.*?)</span>", "<font color=\"#ff0000\">$1</font>");
content = content.replaceAll("<span class=\"jt_green\">(.*?)</span>", "<font color=\"#8dc63f\">$1</font>");
content = content.replaceAll("<span class=\"jt_pink\">(.*?)</span>", "<font color=\"#f49ac1\">$1</font>");
content = content.replaceAll("<span class=\"jt_olive\">(.*?)</span>", "<font color=\"#808000\">$1</font>");
content = content.replaceAll("<span class=\"jt_fuchsia\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>");
content = content.replaceAll("<span class=\"jt_yellow\">(.*?)</span>", "<font color=\"#ffde00\">$1</font>");
content = content.replaceAll("<span class=\"jt_blue\">(.*?)</span>", "<font color=\"#44aedf\">$1</font>");
content = content.replaceAll("<span class=\"jt_lime\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>");
content = content.replaceAll("<span class=\"jt_orange\">(.*?)</span>", "<font color=\"#f7941c\">$1</font>");
content = content.replaceAll("<span class=\"jt_bold\">(.*?)</span>", "<b>$1</b>");
content = content.replaceAll("<span class=\"jt_italic\">(.*?)</span>", "<i>$1</i>");
content = content.replaceAll("<span class=\"jt_underline\">(.*?)</span>", "<u>$1</u>");
content = content.replaceAll("<span class=\"jt_strike\">(.*?)</span>", "<del>1</del>");
content = content.replaceAll("<br />", " ");
return Html.fromHtml(content);
}
}
}
|
package cc.mallet.classify.tui;
import java.util.logging.*;
import java.io.*;
import cc.mallet.classify.*;
import cc.mallet.pipe.*;
import cc.mallet.pipe.iterator.*;
import cc.mallet.types.*;
import cc.mallet.util.*;
/**
* Diagnostic facilities for a classifier.
@author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
public class Classifier2Info
{
private static Logger logger = MalletLogger.getLogger(Classifier2Info.class.getName());
static CommandOption.File classifierFile = new CommandOption.File
(Classifier2Info.class, "classifier", "FILE", true, new File("-"),
"Read the saved classifier from this file.", null);
public static void main (String[] args) throws FileNotFoundException, IOException
{
// Process the command-line options
CommandOption.setSummary (Classifier2Info.class,
"A tool for printing information about saved classifiers.");
CommandOption.process (Classifier2Info.class, args);
// Print some helpful messages for error cases
if (args.length == 0) {
CommandOption.getList(Classifier2Info.class).printUsage(false);
System.exit (-1);
}
// Read in the classifier
Classifier classifier;
try {
ObjectInputStream ois = new ObjectInputStream (new FileInputStream (classifierFile.value));
classifier = (Classifier) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException ("Couldn't read classifier "+classifierFile.value);
}
classifier.print ();
}
}
|
package cc.mallet.topics;
import cc.mallet.examples.*;
import cc.mallet.util.*;
import cc.mallet.types.*;
import cc.mallet.pipe.*;
//import cc.mallet.pipe.iterator.*;
//import cc.mallet.topics.*;
//import cc.mallet.util.Maths;
//import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectIntMap;
//import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import java.util.*;
//import java.util.regex.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;
public class iMixTopicModelExample {
public enum ExperimentType {
Authors,
Grants,
DBLP,
PM_pdb,
DBLP_ACM,
ACM,
FullGrants,
FETGrants,
HEALTHTender
}
public enum SimilarityType {
cos,
Jen_Sha_Div,
symKL
}
public iMixTopicModelExample() throws IOException {
Logger logger = MalletLogger.getLogger(iMixTopicModelExample.class.getName());
int topWords = 10;
int topLabels = 10;
byte numModalities = 4;
//int numIndependentTopics = 0;
double docTopicsThreshold = 0.03;
int docTopicsMax = -1;
//boolean ignoreLabels = true;
boolean calcSimilarities = true;
boolean runTopicModelling = true;
//iMixParallelTopicModel.SkewType skewOn = iMixParallelTopicModel.SkewType.None;
//boolean ignoreSkewness = true;
int numTopics = 100;
int maxNumTopics = 100;
int numIterations = 1000; //Max 2000
int independentIterations = 0;
int burnIn = 150;
int optimizeInterval = 50;
ExperimentType experimentType = ExperimentType.ACM;
int pruneCnt = 10; //Reduce features to those that occur more than N times
int pruneLblCnt = 7;
double pruneMaxPerc = 0.5;//Remove features that occur in more than (X*100)% of documents. 0.05 is equivalent to IDF of 3.0.
SimilarityType similarityType = SimilarityType.cos; //Cosine 1 jensenShannonDivergence 2 symmetric KLP
boolean ACMAuthorSimilarity = false;
//boolean runParametric = true;
boolean DBLP_PPR = false;
//String addedExpId = (experimentType == ExperimentType.ACM ? (ACMAuthorSimilarity ? "Author" : "Category") : "");
String experimentId = experimentType.toString() + "_" + numTopics + "T_" + (maxNumTopics > numTopics + 1 ? maxNumTopics + "maxT_" : "")
+ numIterations + "IT_" + independentIterations + "IIT_" + burnIn + "B_" + numModalities + "M_" + similarityType.toString(); // + "_" + skewOn.toString();
String experimentDescription = "";
String SQLLitedb = "jdbc:sqlite:C:/projects/OpenAIRE/fundedarxiv.db";
if (experimentType == ExperimentType.Grants) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/fundedarxiv.db";
} else if (experimentType == ExperimentType.DBLP) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/DBLPManage/citation-network2.db";
} else if (experimentType == ExperimentType.PM_pdb) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/europepmc.db";
} else if (experimentType == ExperimentType.DBLP_ACM) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/DBLPManage/acm_output.db";
} else if (experimentType == ExperimentType.ACM) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/acmdata1.db";
} else if (experimentType == ExperimentType.FullGrants) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/openairedb.db";
} else if (experimentType == ExperimentType.FETGrants) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/openairedb.db";
} else if (experimentType == ExperimentType.HEALTHTender) {
SQLLitedb = "jdbc:sqlite:C:/projects/Datasets/OpenAIRE/openairedb.db";
}
Connection connection = null;
//createRefACMTables(SQLLitedb);
// create a database connection
//Reader fileReader = new InputStreamReader(new FileInputStream(new File(args[0])), "UTF-8");
//instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),
//3, 2, 1)); // data, label, name fields
String inputDir = "C:\\UoA\\OpenAire\\Datasets\\NIPS\\AuthorsNIPS12raw";
ArrayList<ArrayList<Instance>> instanceBuffer = new ArrayList<ArrayList<Instance>>(numModalities);
if (runTopicModelling) {
//createCitationGraphFile("C:\\projects\\Datasets\\DBLPManage\\acm_output_NET.csv", "jdbc:sqlite:C:/projects/Datasets/DBLPManage/acm_output.db");
for (byte m = 0; m < numModalities; m++) {
instanceBuffer.add(new ArrayList<Instance>());
}
try {
connection = DriverManager.getConnection(SQLLitedb);
//String sql = "select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,\"\t\") as GrantIds from Doc inner join GrantPerDoc on Doc.DocId=GrantPerDoc.DocId where Doc.source='pubmed' and grantPerDoc.grantId like 'ec%' Group By Doc.DocId, Doc.text";
//String docSource = "pubmed";
String docSource = "arxiv";
String grantType = "FP7";
String sql = "";
if (experimentType == ExperimentType.Grants) {
experimentDescription = "Topic modeling based on:\n1)Full text publications related to " + grantType + "\n2)Research Areas\n3)Venues (e.g., PubMed, Arxiv, ACM)\n4)Grants per Publication Links\n SimilarityType:" + similarityType.toString();
sql = "select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds,GROUP_CONCAT(Grant.Category2,'\t') as Areas, Doc.Source \n"
+ " from Doc inner join \n"
+ " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId\n"
+ " INNER JOIN Grant on Grant.GrantId= GrantPerDoc.GrantId\n"
+ " where \n"
+ " Grant.Category0='" + grantType + "'\n"
+ " Group By Doc.DocId, Doc.text"
+ " LIMIT 10000";
// " select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds "
// + " from Doc inner join "
// + " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId "
// // + " where "
// // + " Doc.source='" + docSource + "' and "
// // + " grantPerDoc.grantId like '" + grantType + "' "
// + " Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.FullGrants) {
grantType = "FP7";
experimentDescription += "Topic modeling analyzing:\n1)Abstracts of publications and project descriptions related to " + grantType + "\n2)Research Areas\n3)Venues (e.g., PubMed, Arxiv, ACM)\n4)Grants per Publication Links\n SimilarityType:" + similarityType.toString();
sql = "select pubs.originalid AS DocId, \n"
+ " CASE WHEN IFNULL(pubs.abstract,'')='' THEN pubtitle||' '||pubs.fulltext ELSE pubtitle||' '||pubs.abstract END AS TEXT,\n"
+ " GROUP_CONCAT(links.project_code,'\t') as GrantIds,"
+ " GROUP_CONCAT(Category2,'\t') as Areas, \n"
+ " CASE WHEN IFNULL(journal,'')='' THEN pubs.repository else Journal END as Venue, \n"
+ " 'PubAbstract' AS TEXTType \n"
+ " from pubs \n"
+ " inner join links on links.OriginalId = pubs.originalid and links.funder='FP7'\n"
+ " inner join projectView on links.project_code=projectView.GrantId and links.funder='FP7' \n"
+ " Group By pubs.originalid, pubs.fulltext, pubs.abstract, repository, journal \n"
+ " \n"
+ " UNION \n"
+ " \n"
+ " select 'FP7_'||projectView.GrantId AS DocId, projectView.ABSTRACT AS TEXT, projectView.GrantId AS GrantIds ,"
+ " projectView.Category2 AS Areas, \n"
+ " '' AS Venue, \n"
+ " 'ProjectAbstract' AS TEXTType \n"
+ " from projectView\n"
+ " where IFNULL(abstract,'')<>'' and (projectView.GrantID in (SELECT links.project_code from Links where links.funder='FP7'))\n";
// + " LIMIT 10000";
// " select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds "
// + " from Doc inner join "
// + " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId "
// // + " where "
// // + " Doc.source='" + docSource + "' and "
// // + " grantPerDoc.grantId like '" + grantType + "' "
// + " Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.FETGrants) {
sql = "select pubs.originalid AS DocId, \n"
+ " CASE WHEN IFNULL(pubs.fulltext,'')='' THEN pubs.abstract ELSE pubs.fulltext END AS TEXT,\n"
+ " GROUP_CONCAT(links.project_code,'\t') as GrantIds,"
+ " GROUP_CONCAT(Category3,'\t') as Areas, \n"
+ " CASE WHEN IFNULL(journal,'')='' THEN pubs.repository else Journal END as Venue, \n"
+ " CASE WHEN IFNULL(pubs.fulltext,'')='' THEN 'PubAbstract' ELSE 'PubFullText' END AS TEXTType \n"
+ " from pubs \n"
+ " inner join links on links.OriginalId = pubs.originalid and links.funder='FP7'\n"
+ " inner join projectView on links.project_code=projectView.GrantId and links.funder='FP7' \n"
+ " and projectView.Category1<>'NONFET'\n"
+ " Group By pubs.originalid, pubs.fulltext, pubs.abstract, repository, journal \n"
+ " \n"
+ " UNION \n"
+ " \n"
+ " select 'FP7_'||projectView.GrantId AS DocId, projectView.ABSTRACT AS TEXT, projectView.GrantId AS GrantIds ,"
+ " projectView.Category3 AS Areas, \n"
+ " '' AS Venue, \n"
+ " 'ProjectAbstract' AS TEXTType \n"
+ " from projectView\n"
+ " where IFNULL(abstract,'')<>'' and (projectView.GrantID in (SELECT links.project_code from Links where links.funder='FP7'))\n"
+ " and projectView.Category1<>'NONFET'\n";
experimentDescription = (maxNumTopics > numTopics + 1) ? "Non Parametric" : "";
String sqlTextType = "select TEXTType, count(*) as Cnt from ( " + sql + " ) group by TEXTType";
grantType = "FP7 FET";
Statement statement = connection.createStatement();
statement.setQueryTimeout(60); // set timeout to 30 sec.
experimentDescription += "Topic modeling analyzing:\n 1)";
ResultSet rs = statement.executeQuery(sqlTextType);
while (rs.next()) {
experimentDescription += rs.getInt("Cnt")+" ";
experimentDescription += rs.getString("TEXTType") +", " ;
}
experimentDescription += " related to " + grantType + "\n2)Related Research Areas\n3)Publication Venues (e.g., PubMed, Arxiv, ACM, Specific Journals)\n4)Grants per Publication \n SimilarityType:" + similarityType.toString();
// + " LIMIT 10000";
// " select Doc.DocId, Doc.text, GROUP_CONCAT(GrantPerDoc.GrantId,'\t') as GrantIds "
// + " from Doc inner join "
// + " GrantPerDoc on Doc.DocId=GrantPerDoc.DocId "
// // + " where "
// // + " Doc.source='" + docSource + "' and "
// // + " grantPerDoc.grantId like '" + grantType + "' "
// + " Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.HEALTHTender) {
grantType = "FP7 HEALTH";
experimentDescription = (maxNumTopics > numTopics + 1) ? "Non Parametric" : "";
experimentDescription += "Topic modeling analyzing:\n1)Full Text of publications and project descriptions related to " + grantType + "\n2)Research Areas\n3)Venues (e.g., PubMed, Arxiv, ACM)\n4)Grants per Publication Links\n SimilarityType:" + similarityType.toString();
sql = "Select pubs.originalid AS DocId,\n"
+ " CASE WHEN IFNULL(pubs.fulltext,'')='' THEN pubs.abstract ELSE pubs.fulltext END AS TEXT,\n"
+ " --GROUP_CONCAT(CASE WHEN IFNULL(pubs.abstract,'')='' THEN pubs.fulltext ELSE pubs.abstract END,' ') AS TEXT,\n"
+ " GROUP_CONCAT(GrantId,'\t') as GrantIds,\n"
+ " GROUP_CONCAT(Category3,'\t') as Areas, \n"
+ " GROUP_CONCAT(Category3Descr,'\t') as AreasDescr, \n"
+ " CASE WHEN IFNULL(journal,'')='' THEN pubs.repository else Journal END as Venue, \n"
+ " IFNULL(GROUP_CONCAT(descriptorText,'\t'),'') as MESHdescriptors\n"
+ " -- GROUP_CONCAT(qualifier,'\t') as MESHqualifiers\n"
+ " from pubs \n"
+ " inner join links on links.OriginalId = pubs.originalid and links.funder='FP7' \n"
+ " inner join projectView on links.project_code=projectView.GrantId and links.funder='FP7' and Category2='HEALTH'\n"
+ " --LEFT OUTER join pmcmetadata on pmcmetadata.pmcid=pubs.originalid \n"
+ " LEFT OUTER join MeshTermsPerDoc on MeshTermsPerDoc.pmcid=pubs.originalid \n"
+ " Group By pubs.originalid, pubs.fulltext, pubs.abstract, repository, journal \n"
+ " UNION \n"
+ " select 'FP7_'||projectView.GrantId AS DocId, \n"
+ " projectView.ABSTRACT AS TEXT, \n"
+ " projectView.GrantId AS GrantIds , \n"
+ " projectView.Category3 AS Areas,\n"
+ " projectView.Category3Descr AS AreasDescr,\n"
+ " '' AS Venue,\n"
+ " '' AS MESHdescriptors\n"
+ " --'' AS MESHqualifiers\n"
+ " from projectView\n"
+ " where IFNULL(abstract,'')<>'' and Category2='HEALTH' \n"
+ " --and (projectView.GrantID in (SELECT links.project_code from Links where links.funder='FP7'))\n"
+ " UNION \n"
+ " select 'FP7RPT_'||ProjectId AS DocId, \n"
+ " Results||' '||ContextObjectives||' '||PotentialImpact AS TEXT, \n"
+ " ProjectId AS GrantIds, \n"
+ " projectView.Category3 AS Areas,\n"
+ " projectView.Category3Descr AS AreasDescr,\n"
+ " '' AS Venue,\n"
+ " '' AS MESHdescriptors\n"
+ " -- '' AS MESHqualifiers\n"
+ " from FP7FinalReports\n"
+ " inner join projectView on ProjectId=projectView.GrantId and Category2='HEALTH' ";
} else if (experimentType == ExperimentType.Authors) {
experimentDescription = "Topic modeling based on:\n 1)Full text NIPS publications\n2)Authors per publication links ";
sql = " select Doc.DocId,Doc.text, GROUP_CONCAT(AuthorPerDoc.authorID,'\t') as AuthorIds \n"
+ "from Doc \n"
+ "inner join AuthorPerDoc on Doc.DocId=AuthorPerDoc.DocId \n"
+ "Where \n"
+ "Doc.source='NIPS' \n"
+ "Group By Doc.DocId, Doc.text";
} else if (experimentType == ExperimentType.DBLP) {
sql = " \n"
+ " select id, title||' '||abstract AS text, Authors, \n"
+ " GROUP_CONCAT(citation.Target,',') as citations\n"
+ " --GROUP_CONCAT(prLinks.Target,',') as citations, GROUP_CONCAT(prLinks.Counts,',') as citationsCnt \n"
+ " from papers\n"
+ "--inner join prLinks on prLinks.Source= papers.id \n"
+ "--AND prLinks.Counts>50\n"
+ "left outer join citation on citation.Source= papers.id \n"
+ " WHERE \n"
+ " (abstract IS NOT NULL) AND (abstract<>'') \n"
+ " Group By papers.id, papers.title, papers.abstract, papers.Authors";
// " select id, title||' '||abstract AS text, Authors, GROUP_CONCAT(prLinks.Target,',') as citations, GROUP_CONCAT(prLinks.Counts,',') as citationsCnt from papers\n"
// + "inner join prLinks on prLinks.Source= papers.id AND prLinks.Counts>50 \n"
// + " WHERE (abstract IS NOT NULL) AND (abstract<>'') \n"
// + " Group By papers.id, papers.title, papers.abstract, papers.Authors\n"
// + " LIMIT 200000"
} else if (experimentType == ExperimentType.PM_pdb) {
sql = " select pubdoc.pmcId, pubdoc.abstract, pubdoc.body, GROUP_CONCAT(pdblink.pdbCode,'\t') as pbdCodes \n"
+ " from pubdoc inner join \n"
+ " pdblink on pdblink.pmcId=pubdoc.pmcId \n"
+ " Group By pubdoc.pmcId, pubdoc.abstract, pubdoc.body";
} else if (experimentType == ExperimentType.DBLP_ACM) {
sql = " select id, title||' '||abstract AS text, Authors, \n"
+ " ref_id as citations\n"
+ " from papers\n"
+ " WHERE \n"
+ " (abstract IS NOT NULL) AND (abstract<>'') \n " //+" AND ref_Id IS NOT NULL AND ref_id<>'' \n"
// + " LIMIT 20000"
;
} else if (experimentType == ExperimentType.ACM) {
experimentDescription = "Topic modeling based on:\n1)Abstracts from ACM publications \n2)Authors\n3)Citations\n4)ACMCategories\n SimilarityType:"
+ similarityType.toString()
+ "\n Similarity on Authors & Categories";
//+ (ACMAuthorSimilarity ? "Authors" : "Categories");
sql = " select articleid as id, title||' '||abstract AS text, authors_id AS Authors, \n" +
" ref_objid as citations \n" +
" ,GROUP_CONCAT(Category,'\t') AS categories\n" +
" from ACMData1 \n" +
" INNER JOIN PubCategoryView on PubCategoryView.PubId = ArticleId\n" +
" Group by articleid \n"
+ " LIMIT 50000";
}
// String sql = "select fundedarxiv.file from fundedarxiv inner join funds on file=filename Group By fundedarxiv.file LIMIT 10" ;
Statement statement = connection.createStatement();
statement.setQueryTimeout(60); // set timeout to 30 sec.
ResultSet rs = statement.executeQuery(sql);
String txt = "";
while (rs.next()) {
// read the result set
//String lblStr = "[" + rs.getString("GrantIds") + "]" ;//+ rs.getString("text");
//String str = "[" + rs.getString("GrantIds") + "]" + rs.getString("text");
//System.out.println("name = " + rs.getString("file"));
//System.out.println("name = " + rs.getString("fundings"));
//int cnt = rs.getInt("grantsCnt");
switch (experimentType) {
case Grants:
instanceBuffer.get(0).add(new Instance(rs.getString("text"), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("GrantIds"), null, rs.getString("DocId"), "grant"));
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Areas"), null, rs.getString("DocId"), "area"));
}
;
if (numModalities > 3) {
instanceBuffer.get(3).add(new Instance(rs.getString("Source"), null, rs.getString("DocId"), "source"));
}
;
break;
case FullGrants:
txt = rs.getString("text");
instanceBuffer.get(0).add(new Instance(txt.substring(0, Math.min(txt.length() - 1, 15000)), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("GrantIds"), null, rs.getString("DocId"), "grant"));
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Areas"), null, rs.getString("DocId"), "area"));
}
;
if (numModalities > 3) {
if (!rs.getString("Venue").equals("")) {
instanceBuffer.get(3).add(new Instance(rs.getString("Venue"), null, rs.getString("DocId"), "Venue"));
}
}
;
break;
case FETGrants:
txt = rs.getString("text");
instanceBuffer.get(0).add(new Instance(txt.substring(0, Math.min(txt.length() - 1, 150000)), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("GrantIds"), null, rs.getString("DocId"), "grant"));
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Areas"), null, rs.getString("DocId"), "area"));
}
;
if (numModalities > 3) {
if (!rs.getString("Venue").equals("")) {
instanceBuffer.get(3).add(new Instance(rs.getString("Venue"), null, rs.getString("DocId"), "Venue"));
}
}
;
break;
case HEALTHTender:
txt = rs.getString("text");
instanceBuffer.get(0).add(new Instance(txt.substring(0, Math.min(txt.length() - 1, 150000)), null, rs.getString("DocId"), "Text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("GrantIds"), null, rs.getString("DocId"), "Grant"));
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Areas"), null, rs.getString("DocId"), "Area"));
}
;
if (numModalities > 3) {
if (!rs.getString("Venue").equals("")) {
instanceBuffer.get(3).add(new Instance(rs.getString("Venue"), null, rs.getString("DocId"), "Venue"));
}
}
if (numModalities > 4) {
if (!rs.getString("MESHdescriptors").equals("")) {
instanceBuffer.get(4).add(new Instance(rs.getString("MESHdescriptors"), null, rs.getString("DocId"), "MESHdescriptor"));
}
}
// if (numModalities > 5) {
// if (!rs.getString("MESHqualifiers").equals("")) {
// instanceBuffer.get(5).add(new Instance(rs.getString("MESHqualifiers"), null, rs.getString("DocId"), "MESHqualifier"));
;
break;
case Authors:
instanceBuffer.get(0).add(new Instance(rs.getString("text"), null, rs.getString("DocId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("AuthorIds"), null, rs.getString("DocId"), "author"));
}
break;
case DBLP:
instanceBuffer.get(0).add(new Instance(rs.getString("Text"), null, rs.getString("Id"), "text"));
if (numModalities > 1) {
if (DBLP_PPR) {
String tmpStr = rs.getString("Citations");
String[] citationsCnt = null;
String[] citations = null;
if (tmpStr != null) {
citations = tmpStr.split(",");
citationsCnt = rs.getString("CitationsCnt").split(",");
String citationStr = "";
int index = 0;
while (index < citationsCnt.length) {
int cnt = Integer.parseInt(citationsCnt[index]);
for (int i = 1; i <= cnt / 50; i++) {
if (citationStr != "") {
citationStr += ",";
}
citationStr += citations[index];
}
index++;
}
instanceBuffer.get(1).add(new Instance(citationStr, null, rs.getString("Id"), "citations"));
}
} else {
String tmpStr = rs.getString("Citations");
if (tmpStr != null) {
instanceBuffer.get(1).add(new Instance(tmpStr, null, rs.getString("Id"), "author"));
}
}
}
if (numModalities > 2) {
instanceBuffer.get(2).add(new Instance(rs.getString("Authors"), null, rs.getString("Id"), "author"));
}
break;
case PM_pdb:
//instanceBuffer.get(0).add(new Instance(rs.getString("abstract") + " " + rs.getString("body"), null, rs.getString("pmcId"), "text"));
instanceBuffer.get(0).add(new Instance(rs.getString("abstract"), null, rs.getString("pmcId"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("pbdCodes"), null, rs.getString("pmcId"), "pbdCode"));
}
break;
case DBLP_ACM:
instanceBuffer.get(0).add(new Instance(rs.getString("Text"), null, rs.getString("Id"), "text"));
if (numModalities > 1) {
instanceBuffer.get(1).add(new Instance(rs.getString("Authors"), null, rs.getString("Id"), "citation"));
}
if (numModalities > 2) {
String tmpStr = rs.getString("Citations").replace("\t", ",");
instanceBuffer.get(2).add(new Instance(tmpStr, null, rs.getString("Id"), "author"));
}
break;
case ACM:
instanceBuffer.get(0).add(new Instance(rs.getString("Text"), null, rs.getString("Id"), "text"));
if (numModalities > 1) {
String tmpStr = rs.getString("Citations");//.replace("\t", ",");
instanceBuffer.get(1).add(new Instance(tmpStr, null, rs.getString("Id"), "citation"));
}
if (numModalities > 2) {
String tmpStr = rs.getString("Categories");//.replace("\t", ",");
instanceBuffer.get(2).add(new Instance(tmpStr, null, rs.getString("Id"), "category"));
}
if (numModalities > 3) {
String tmpAuthorsStr = rs.getString("Authors");//.replace("\t", ",");
instanceBuffer.get(3).add(new Instance(tmpAuthorsStr, null, rs.getString("Id"), "author"));
}
break;
default:
}
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
logger.info("Read " + instanceBuffer.get(0).size() + " instances modality: " + instanceBuffer.get(0).get(0).getSource().toString());
//numModalities = 2;
// Begin by importing documents from text to feature sequences
ArrayList<Pipe> pipeListText = new ArrayList<Pipe>();
// Pipes: lowercase, tokenize, remove stopwords, map to features
pipeListText.add(new Input2CharSequence(false)); //homer
pipeListText.add(new CharSequenceLowercase());
SimpleTokenizer tokenizer = new SimpleTokenizer(new File("stoplists/en.txt"));
GenerateStoplist(tokenizer, instanceBuffer.get(0), pruneCnt, pruneMaxPerc, false);
tokenizer.stop("cid");
tokenizer.stop("null");
//tokenizer.
pipeListText.add(tokenizer);
Alphabet alphabet = new Alphabet();
pipeListText.add(new StringList2FeatureSequence(alphabet));
/*
Alphabet alphabet = new Alphabet();
CharSequenceLowercase csl = new CharSequenceLowercase();
StringList2FeatureSequence sl2fs = new StringList2FeatureSequence(alphabet);
if (!preserveCase.value) {
pipes.add(csl);
}
pipes.add(prunedTokenizer);
pipes.add(sl2fs);
Pipe serialPipe = new SerialPipes(pipes);
InstanceList instances = new InstanceList(serialPipe);
instances.addThruPipe(reader);
*/
/* orig
pipeListText.add(new CharSequence2TokenSequence(Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")));// Original --> replaced by simpletokenizer in order to use prunedStopiList
pipeListText.add(new TokenSequenceRemoveStopwords(new File("stoplists/en.txt"), "UTF-8", false, false, false)); //Original --> replaced by simpletokenizer
pipeListText.add(new TokenSequence2FeatureSequence());
*/
// Other Modalities
ArrayList<Pipe> pipeListCSV = new ArrayList<Pipe>();
if (experimentType == ExperimentType.DBLP || experimentType == ExperimentType.DBLP_ACM) {
pipeListCSV.add(new CSV2FeatureSequence(","));
} else {
pipeListCSV.add(new CSV2FeatureSequence());
}
InstanceList[] instances = new InstanceList[numModalities];
instances[0] = new InstanceList(new SerialPipes(pipeListText));
instances[0].addThruPipe(instanceBuffer.get(0).iterator());
for (byte m = 1; m < numModalities; m++) {
logger.info("Read " + instanceBuffer.get(m).size() + " instances modality: " + (instanceBuffer.get(m).size() > 0 ? instanceBuffer.get(m).get(0).getSource().toString() : m));
instances[m] = new InstanceList(new SerialPipes(pipeListCSV));
instances[m].addThruPipe(instanceBuffer.get(m).iterator());
}
logger.info(" instances added through pipe");
// pruning for all other modalities no text
for (byte m = 1; m < numModalities; m++) {
if ((m == 0 && pruneCnt > 0) || (m > 0 && pruneLblCnt > 0)) {
// Check which type of data element the instances contain
Instance firstInstance = instances[m].get(0);
if (firstInstance.getData() instanceof FeatureSequence) {
// Version for feature sequences
Alphabet oldAlphabet = instances[m].getDataAlphabet();
Alphabet newAlphabet = new Alphabet();
// It's necessary to create a new instance list in
// order to make sure that the data alphabet is correct.
Noop newPipe = new Noop(newAlphabet, instances[m].getTargetAlphabet());
InstanceList newInstanceList = new InstanceList(newPipe);
// Iterate over the instances in the old list, adding
// up occurrences of features.
int numFeatures = oldAlphabet.size();
double[] counts = new double[numFeatures];
for (int ii = 0; ii < instances[m].size(); ii++) {
Instance instance = instances[m].get(ii);
FeatureSequence fs = (FeatureSequence) instance.getData();
fs.addFeatureWeightsTo(counts);
}
Instance instance;
// Next, iterate over the same list again, adding
// each instance to the new list after pruning.
while (instances[m].size() > 0) {
instance = instances[m].get(0);
FeatureSequence fs = (FeatureSequence) instance.getData();
fs.prune(counts, newAlphabet, m == 0 ? pruneCnt : pruneLblCnt);
newInstanceList.add(newPipe.instanceFrom(new Instance(fs, instance.getTarget(),
instance.getName(),
instance.getSource())));
instances[m].remove(0);
}
// logger.info("features: " + oldAlphabet.size()
// + " -> " + newAlphabet.size());
// Make the new list the official list.
instances[m] = newInstanceList;
} else {
throw new UnsupportedOperationException("Pruning features from "
+ firstInstance.getClass().getName()
+ " is not currently supported");
}
}
}
logger.info(" instances pruned");
boolean splitCorpus = false;
InstanceList[] testInstances = null;
InstanceList[] trainingInstances = instances;
if (splitCorpus) {
//instances.addThruPipe(new FileIterator(inputDir));
//instances.addThruPipe (new FileIterator ("C:\\UoA\\OpenAire\\Datasets\\YIpapersTXT\\YIpapersTXT"));
//instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),
// Create a model with 100 topics, alpha_t = 0.01, beta_w = 0.01
// Note that the first parameter is passed as the sum over topics, while
// the second is
testInstances = new InstanceList[numModalities];
trainingInstances = new InstanceList[numModalities];
TObjectIntMap<String> entityPosition = new TObjectIntHashMap<String>();
int index = 0;
for (byte m = 0; m < numModalities; m++) {
Noop newPipe = new Noop(instances[m].getDataAlphabet(), instances[m].getTargetAlphabet());
InstanceList newInstanceList = new InstanceList(newPipe);
testInstances[m] = newInstanceList;
InstanceList newInstanceList2 = new InstanceList(newPipe);
trainingInstances[m] = newInstanceList2;
for (int i = 0; i < instances[m].size(); i++) {
Instance instance = instances[m].get(i);
String entityId = (String) instance.getName();
if (i < instances[m].size() * 0.8 && m == 0) {
entityPosition.put(entityId, index);
trainingInstances[m].add(instance);
index++;
} else if (m != 0 && entityPosition.containsKey(entityId)) {
trainingInstances[m].add(instance);
} else {
testInstances[m].add(instance);
}
}
}
}
String outputDir = "C:\\projects\\OpenAIRE\\OUT\\" + experimentId;
File outPath = new File(outputDir);
outPath.mkdir();
String stateFile = outputDir + File.separator + "output_state";
String outputDocTopicsFile = outputDir + File.separator + "output_doc_topics.csv";
String outputTopicPhraseXMLReport = outputDir + File.separator + "topicPhraseXMLReport.xml";
String topicKeysFile = outputDir + File.separator + "output_topic_keys.csv";
String topicWordWeightsFile = outputDir + File.separator + "topicWordWeightsFile.csv";
String stateFileZip = outputDir + File.separator + "output_state.gz";
String modelEvaluationFile = outputDir + File.separator + "model_evaluation.txt";
String modelDiagnosticsFile = outputDir + File.separator + "model_diagnostics.xml";
boolean runNPModel = false;
if (runNPModel) {
NPTopicModel npModel = new NPTopicModel(5.0, 10.0, 0.1);
npModel.addInstances(instances[0], 50);
npModel.setTopicDisplay(20, 10);
npModel.sample(100);
FileWriter fwrite = new FileWriter(outputDir + File.separator + "output_NP_topics.csv");
BufferedWriter NP_Topics_out = new BufferedWriter(fwrite);
NP_Topics_out.write(npModel.topWords(10) + "\n");
NP_Topics_out.flush();
npModel.printState(new File(outputDir + File.separator + "NP_output_state.gz"));
}
boolean runHDPModel = false;
if (runHDPModel) {
//setup HDP parameters(alpha, beta, gamma, initialTopics)
HDP hdp = new HDP(1.0, 0.1, 4.0, numTopics);
hdp.initialize(instances[0]);
//set number of iterations, and display result or not
hdp.estimate(numIterations);
//get topic distribution for first instance
double[] distr = hdp.topicDistribution(0);
//print out
for (int j = 0; j < distr.length; j++) {
System.out.print(distr[j] + " ");
}
//for inferencer
HDPInferencer inferencer = hdp.getInferencer();
inferencer.setInstance(testInstances[0]);
inferencer.estimate(100);
//get topic distribution for first test instance
distr = inferencer.topicDistribution(0);
//print out
for (int j = 0; j < distr.length; j++) {
System.out.print(distr[j] + " ");
}
//get preplexity
double prep = inferencer.getPreplexity();
System.out.println("preplexity for the test set=" + prep);
//10-folds cross validation, with 1000 iteration for each test.
hdp.runCrossValidation(10, 1000);
}
boolean runOrigParallelModel = false;
if (runOrigParallelModel) {
ParallelTopicModel modelOrig = new ParallelTopicModel(numTopics, 1.0, 0.01);
modelOrig.addInstances(instances[0]);
// Use two parallel samplers, which each look at one half the corpus and combine
// statistics after every iteration.
modelOrig.setNumThreads(4);
// Run the model for 50 iterations and stop (this is for testing only,
// for real applications, use 1000 to 2000 iterations)
modelOrig.setNumIterations(numIterations);
modelOrig.optimizeInterval = optimizeInterval;
modelOrig.burninPeriod = burnIn;
//model.optimizeInterval = 0;
//model.burninPeriod = 0;
//model.saveModelInterval=250;
modelOrig.estimate();
}
double[] beta = new double[numModalities];
Arrays.fill(beta, 0.01);
double[] alphaSum = new double[numModalities];
Arrays.fill(alphaSum, 1);
double[] gamma = new double[numModalities];
Arrays.fill(gamma, 1);
double gammaRoot = 4;
//Non parametric model
//iMixLDAParallelTopicModel model = new iMixLDAParallelTopicModel(maxNumTopics, numTopics, numModalities, gamma, gammaRoot, beta, numIterations);
//parametric model
MixLDAParallelTopicModel model = new MixLDAParallelTopicModel(numTopics, numModalities, alphaSum, beta, numIterations);
// ParallelTopicModel model = new ParallelTopicModel(numTopics, 1.0, 0.01);
//model.setNumIterations(numIterations);
model.setIndependentIterations(independentIterations);
model.optimizeInterval = optimizeInterval;
model.burninPeriod = burnIn;
model.addInstances(instances);//trainingInstances);//instances);
logger.info(" instances added");
// Use two parallel samplers, which each look at one half the corpus and combine
// statistics after every iteration.
model.setNumThreads(4);
// Run the model for 50 iterations and stop (this is for testing only,
// for real applications, use 1000 to 2000 iterations)
//model.optimizeInterval = 0;
//model.burninPeriod = 0;
//model.saveModelInterval=250;
model.estimate();
logger.info("Model estimated");
model.saveTopics(SQLLitedb, experimentId);
logger.info("Topics Saved");
model.printTopWords(
new File(topicKeysFile), topWords, topLabels, false);
logger.info("Top words printed");
//model.printTopWords(new File(topicKeysFile), topWords, false);
//model.printTopicWordWeights(new File(topicWordWeightsFile));
//model.printTopicLabelWeights(new File(topicLabelWeightsFile));
//No printing state
//model.printState(
// new File(stateFileZip));
// logger.info("printState finished");
PrintWriter outState = null;// new PrintWriter(new FileWriter((new File(outputDocTopicsFile))));
model.printDocumentTopics(outState, docTopicsThreshold, docTopicsMax, SQLLitedb, experimentId,
0.1);
if (outState != null) {
outState.close();
}
logger.info("printDocumentTopics finished");
logger.info("Model Metadata: \n" + model.getExpMetadata());
model.saveExperiment(SQLLitedb, experimentId, experimentDescription);
PrintWriter outXMLPhrase = new PrintWriter(new FileWriter((new File(outputTopicPhraseXMLReport))));
model.topicPhraseXMLReport(outXMLPhrase, topWords);
//outState.close();
logger.info("topicPhraseXML report finished");
// GunZipper g = new GunZipper(new File(stateFileZip));
// g.unzip(
// new File(stateFile));
// try {
// // outputCsvFiles(outputDir, true, inputDir, numTopics, stateFile, outputDocTopicsFile, topicKeysFile);
// logger.info("outputCsvFiles finished");
// } catch (Exception e) {
// // if the error message is "out of memory",
// // it probably means no database file is found
// System.err.println(e.getMessage());
if (modelEvaluationFile != null) {
try {
// ObjectOutputStream oos =
// new ObjectOutputStream(new FileOutputStream(modelEvaluationFile));
// oos.writeObject(model.getProbEstimator());
// oos.close();
PrintStream docProbabilityStream = null;
docProbabilityStream = new PrintStream(modelEvaluationFile);
//TODO...
double perplexity = 0;
if (splitCorpus) {
perplexity = model.getProbEstimator().evaluateLeftToRight(testInstances[0], 10, false, docProbabilityStream);
}
// System.out.println("perplexity for the test set=" + perplexity);
logger.info("perplexity calculation finished");
//iMixLDATopicModelDiagnostics diagnostics = new iMixLDATopicModelDiagnostics(model, topWords);
MixLDATopicModelDiagnostics diagnostics = new MixLDATopicModelDiagnostics(model, topWords);
diagnostics.saveToDB(SQLLitedb, experimentId, perplexity);
logger.info("full diagnostics calculation finished");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
if (calcSimilarities) {
//calc similarities
logger.info("similarities calculation Started");
try {
// create a database connection
//connection = DriverManager.getConnection(SQLLitedb);
connection = DriverManager.getConnection(SQLLitedb);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
// statement.executeUpdate("drop table if exists person");
// statement.executeUpdate("create table person (id integer, name string)");
// statement.executeUpdate("insert into person values(1, 'leo')");
// statement.executeUpdate("insert into person values(2, 'yui')");
// ResultSet rs = statement.executeQuery("select * from person");
String sql = "";
switch (experimentType) {
case Grants:
sql = "select GrantId, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join GrantPerDoc on topicsPerDoc.DocId= GrantPerDoc.DocId"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By GrantId , TopicId order by GrantId , TopicId";
break;
case FullGrants:
sql = "select project_code, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join links on topicsPerDoc.DocId= links.OriginalId "
+ " where weight>0.02 AND ExperimentId='" + experimentId
+ "' group By project_code , TopicId order by project_code, TopicId";
break;
case FETGrants:
sql = "select project_code, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join links on topicsPerDoc.DocId= links.OriginalId "
+ " inner join projectView on links.project_code=projectView.GrantId and links.funder='FP7' and Category1<>'NONFET'\n"
+ " where weight>0.02 AND ExperimentId='" + experimentId
+ "' group By project_code , TopicId order by project_code, TopicId";
break;
case HEALTHTender:
sql = "select project_code, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join links on topicsPerDoc.DocId= links.OriginalId "
+ " inner join projectView on links.project_code=projectView.GrantId and links.funder='FP7' and Category2='HEALTH'\n"
+ " where weight>0.02 AND ExperimentId='" + experimentId
+ "' group By project_code , TopicId order by project_code, TopicId";
break;
case Authors:
sql = "select AuthorId, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join AuthorPerDoc on topicsPerDoc.DocId= AuthorPerDoc.DocId"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By AuthorId , TopicId order by AuthorId , TopicId";
break;
case ACM:
if (ACMAuthorSimilarity) {
sql = "select PubAuthor.AuthorId, TopicId, AVG(weight) as Weight from topicsPerDoc \n"
+ "Inner Join PubAuthor on topicsPerDoc.DocId= PubAuthor.PubId \n"
+ "INNER JOIN (Select AuthorId FROM PubAuthor\n"
+ "GROUP BY AuthorId HAVING Count(*)>10) catCnts1 ON catCnts1.AuthorId = PubAuthor.AuthorId "
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By PubAuthor.AuthorId, TopicId order by PubAuthor.AuthorId ,weight desc, TopicId";
} else {
sql = "select PubCategoryView.Category as Category, TopicId, AVG(weight) as Weight from topicsPerDoc \n"
+ "Inner Join PubCategoryView on topicsPerDoc.DocId= PubCategoryView.PubId \n"
+ "INNER JOIN (Select Category FROM PubCategoryView\n"
+ "GROUP BY Category HAVING Count(*)>10) catCnts1 ON catCnts1.Category = PubCategoryView.category\n"
+ "where weight>0.02 AND ExperimentId='" + experimentId + "' group By PubCategoryView.Category , TopicId order by PubCategoryView.Category, Weight desc, TopicId";
}
break;
case PM_pdb:
sql = "select pdbCode, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join pdblink on topicsPerDoc.DocId= pdblink.pmcId"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By pdbCode , TopicId order by pdbCode , TopicId";
break;
case DBLP:
sql = "select Source, TopicId, AVG(weight) as Weight from topicsPerDoc Inner Join prlinks on topicsPerDoc.DocId= prlinks.source"
+ " where weight>0.02 AND ExperimentId='" + experimentId + "' group By Source , TopicId order by Source , TopicId";
break;
default:
}
// String sql = "select fundedarxiv.file from fundedarxiv inner join funds on file=filename Group By fundedarxiv.file LIMIT 10" ;
ResultSet rs = statement.executeQuery(sql);
HashMap<String, SparseVector> labelVectors = null;
HashMap<String, double[]> similarityVectors = null;
if (similarityType == SimilarityType.cos) {
labelVectors = new HashMap<String, SparseVector>();
} else {
similarityVectors = new HashMap<String, double[]>();
}
String labelId = "";
int[] topics = new int[maxNumTopics];
double[] weights = new double[maxNumTopics];
int cnt = 0;
double a;
while (rs.next()) {
String newLabelId = "";
switch (experimentType) {
case Grants:
newLabelId = rs.getString("GrantId");
break;
case FullGrants:
case FETGrants:
case HEALTHTender:
newLabelId = rs.getString("project_code");
break;
case Authors:
newLabelId = rs.getString("AuthorId");
break;
case ACM:
if (ACMAuthorSimilarity) {
newLabelId = rs.getString("AuthorId");
} else {
newLabelId = rs.getString("Category");
}
break;
case PM_pdb:
newLabelId = rs.getString("pdbCode");
break;
case DBLP:
newLabelId = rs.getString("Source");
break;
default:
}
if (!newLabelId.equals(labelId) && !labelId.isEmpty()) {
if (similarityType == SimilarityType.cos) {
labelVectors.put(labelId, new SparseVector(topics, weights, topics.length, topics.length, true, true, true));
} else {
similarityVectors.put(labelId, weights);
}
topics = new int[maxNumTopics];
weights = new double[maxNumTopics];
cnt = 0;
}
labelId = newLabelId;
topics[cnt] = rs.getInt("TopicId");
weights[cnt] = rs.getDouble("Weight");
cnt++;
}
cnt = 0;
double similarity = 0;
double similarityThreshold = 0.15;
NormalizedDotProductMetric cosineSimilarity = new NormalizedDotProductMetric();
int entityType = experimentType.ordinal();
if (experimentType == ExperimentType.ACM && !ACMAuthorSimilarity) {
entityType = 100 + entityType;
};
statement.executeUpdate("create table if not exists EntitySimilarity (EntityType int, EntityId1 nvarchar(50), EntityId2 nvarchar(50), Similarity double, ExperimentId nvarchar(50)) ");
String deleteSQL = String.format("Delete from EntitySimilarity where ExperimentId = '%s' and entityType=%d", experimentId, entityType);
statement.executeUpdate(deleteSQL);
PreparedStatement bulkInsert = null;
sql = "insert into EntitySimilarity values(?,?,?,?,?);";
try {
connection.setAutoCommit(false);
bulkInsert = connection.prepareStatement(sql);
if (similarityType == SimilarityType.Jen_Sha_Div) {
for (String fromGrantId : similarityVectors.keySet()) {
boolean startCalc = false;
for (String toGrantId : similarityVectors.keySet()) {
if (!fromGrantId.equals(toGrantId) && !startCalc) {
continue;
} else {
startCalc = true;
similarity = Maths.jensenShannonDivergence(similarityVectors.get(fromGrantId), similarityVectors.get(toGrantId)); // the function returns distance not similarity
if (similarity > similarityThreshold && !fromGrantId.equals(toGrantId)) {
bulkInsert.setInt(1, entityType);
bulkInsert.setString(2, fromGrantId);
bulkInsert.setString(3, toGrantId);
bulkInsert.setDouble(4, (double) Math.round(similarity * 1000) / 1000);
bulkInsert.setString(5, experimentId);
bulkInsert.executeUpdate();
}
}
}
}
} else if (similarityType == SimilarityType.cos) {
for (String fromGrantId : labelVectors.keySet()) {
boolean startCalc = false;
for (String toGrantId : labelVectors.keySet()) {
if (!fromGrantId.equals(toGrantId) && !startCalc) {
continue;
} else {
startCalc = true;
similarity = 1 - Math.abs(cosineSimilarity.distance(labelVectors.get(fromGrantId), labelVectors.get(toGrantId))); // the function returns distance not similarity
if (similarity > similarityThreshold && !fromGrantId.equals(toGrantId)) {
bulkInsert.setInt(1, entityType);
bulkInsert.setString(2, fromGrantId);
bulkInsert.setString(3, toGrantId);
bulkInsert.setDouble(4, (double) Math.round(similarity * 1000) / 1000);
bulkInsert.setString(5, experimentId);
bulkInsert.executeUpdate();
}
}
}
}
}
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException excep) {
System.err.print("Error in insert grantSimilarity");
}
}
} finally {
if (bulkInsert != null) {
bulkInsert.close();
}
connection.setAutoCommit(true);
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
logger.info("similarities calculation finished");
}
// if (modelDiagnosticsFile
// != null) {
// PrintWriter out = new PrintWriter(modelDiagnosticsFile);
// MixTopicModelDiagnostics diagnostics = new MixTopicModelDiagnostics(model, topWords, perplexity);
// diagnostics.saveToDB(SQLLitedb, experimentId);
// out.println(diagnostics.toXML()); //preferable than XML???
// out.close();
//If any value in <tt>p2</tt> is <tt>0.0</tt> then the KL-divergence
//double a = Maths.klDivergence();
//model.printTypeTopicCounts(new File (wordTopicCountsFile.value));
// Show the words and topics in the first instance
// The data alphabet maps word IDs to strings
/* Alphabet dataAlphabet = instances.getDataAlphabet();
FeatureSequence tokens = (FeatureSequence) model.getData().get(0).instance.getData();
LabelSequence topics = model.getData().get(0).topicSequence;
Formatter out = new Formatter(new StringBuilder(), Locale.US);
for (int posit= 0; position < tokens.getLength(); position++) {
out.format("%s-%d ", dataAlphabet.lookupObject(tokens.getIndexAtPosition(position)), topics.getIndexAtPosition(position));
}
System.out.println(out);
// Estimate the topic distribution of the first instance,
// given the current Gibbs state.
double[] topicDistribution = model.getTopicProbabilities(0);
// Get an array of sorted sets of word ID/count pairs
ArrayList<TreeSet<IDSorter>> topicSortedWords = model.getSortedWords();
// Show top 5 words in topics with proportions for the first document
for (int topic = 0; topic < numTopics; topic++) {
Iterator<IDSorter> iterator = topicSortedWords.get(topic).iterator();
out = new Formatter(new StringBuilder(), Locale.US);
out.format("%d\t%.3f\t", topic, topicDistribution[topic]);
int rank = 0;
while (iterator.hasNext() && rank < 5) {
IDSorter idCountPair = iterator.next();
out.format("%s (%.0f) ", dataAlphabet.lookupObject(idCountPair.getID()), idCountPair.getWeight());
rank++;
}
System.out.println(out);
}
// Create a new instance with high probability of topic 0
StringBuilder topicZeroText = new StringBuilder();
Iterator<IDSorter> iterator = topicSortedWords.get(0).iterator();
int rank = 0;
while (iterator.hasNext() && rank < 5) {
IDSorter idCountPair = iterator.next();
topicZeroText.append(dataAlphabet.lookupObject(idCountPair.getID()) + " ");
rank++;
}
// Create a new instance named "test instance" with empty target and source fields.
InstanceList testing = new InstanceList(instances.getPipe());
testing.addThruPipe(new Instance(topicZeroText.toString(), null, "test instance", null));
TopicInferencer inferencer = model.getInferencer();
double[] testProbabilities = inferencer.getSampledDistribution(testing.get(0), 10, 1, 5);
System.out.println("0\t" + testProbabilities[0]);
*/
}
private void GenerateStoplist(SimpleTokenizer prunedTokenizer, ArrayList<Instance> instanceBuffer, int pruneCount, double docProportionCutoff, boolean preserveCase)
throws IOException {
ArrayList<Instance> input = new ArrayList<Instance>();
for (Instance instance : instanceBuffer) {
input.add((Instance) instance.clone());
}
ArrayList<Pipe> pipes = new ArrayList<Pipe>();
Alphabet alphabet = new Alphabet();
CharSequenceLowercase csl = new CharSequenceLowercase();
SimpleTokenizer st = prunedTokenizer.deepClone();
StringList2FeatureSequence sl2fs = new StringList2FeatureSequence(alphabet);
FeatureCountPipe featureCounter = new FeatureCountPipe(alphabet, null);
FeatureDocFreqPipe docCounter = new FeatureDocFreqPipe(alphabet, null);
pipes.add(new Input2CharSequence(false)); //homer
if (!preserveCase) {
pipes.add(csl);
}
pipes.add(st);
pipes.add(sl2fs);
if (pruneCount > 0) {
pipes.add(featureCounter);
}
if (docProportionCutoff < 1.0) {
pipes.add(docCounter);
}
Pipe serialPipe = new SerialPipes(pipes);
Iterator<Instance> iterator = serialPipe.newIteratorFrom(input.iterator());
int count = 0;
// We aren't really interested in the instance itself,
// just the total feature counts.
while (iterator.hasNext()) {
count++;
if (count % 100000 == 0) {
System.out.println(count);
}
iterator.next();
}
Iterator<String> wordIter = alphabet.iterator();
while (wordIter.hasNext()) {
String word = (String) wordIter.next();
if (word.contains("cidcid") || word.contains("nullnull") || word.contains("usepackage")|| word.contains("fig")) {
prunedTokenizer.stop(word);
}
}
if (pruneCount > 0) {
featureCounter.addPrunedWordsToStoplist(prunedTokenizer, pruneCount);
}
if (docProportionCutoff < 1.0) {
docCounter.addPrunedWordsToStoplist(prunedTokenizer, docProportionCutoff);
}
}
private void outputCsvFiles(String outputDir, Boolean htmlOutputFlag, String inputDir, int numTopics, String stateFile, String outputDocTopicsFile, String topicKeysFile) {
CsvBuilder cb = new CsvBuilder();
cb.createCsvFiles(numTopics, outputDir, stateFile, outputDocTopicsFile, topicKeysFile);
if (htmlOutputFlag) {
HtmlBuilder hb = new HtmlBuilder(cb.getNtd(), new File(inputDir));
hb.createHtmlFiles(new File(outputDir));
}
//clearExtrafiles(outputDir);
}
private void clearExtrafiles(String outputDir) {
String[] fileNames = {"topic-input.mallet", "output_topic_keys.csv", "output_state.gz",
"output_doc_topics.csv", "output_state"};
for (String f : fileNames) {
if (!(new File(outputDir, f).canWrite())) {
System.out.println(f);
}
Boolean b = new File(outputDir, f).delete();
}
}
public void createCitationGraphFile(String outputCsv, String SQLLitedb) {
//String SQLLitedb = "jdbc:sqlite:C:/projects/OpenAIRE/fundedarxiv.db";
Connection connection = null;
try {
FileWriter fwrite = new FileWriter(outputCsv);
BufferedWriter out = new BufferedWriter(fwrite);
String header = "# DBLP citation graph \n"
+ "# fromNodeId, toNodeId \n";
out.write(header);
connection = DriverManager.getConnection(SQLLitedb);
String sql = "select id, ref_id from papers where ref_num >0 ";
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// read the result set
int Id = rs.getInt("Id");
String citationNums = rs.getString("ref_id");
String csvLine = "";//Id + "\t" + citationNums;
String[] str = citationNums.split("\t");
for (int i = 0; i < str.length - 1; i++) {
csvLine = Id + "\t" + str[i];
out.write(csvLine + "\n");
}
}
out.flush();
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println("File input error");
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
}
public void createRefACMTables(String SQLLitedb) {
//String SQLLitedb = "jdbc:sqlite:C:/projects/OpenAIRE/fundedarxiv.db";
Connection connection = null;
try {
connection = DriverManager.getConnection(SQLLitedb);
Statement statement = connection.createStatement();
statement.executeUpdate("create table if not exists Author (AuthorId nvarchar(50), FirstName nvarchar(50), LastName nvarchar(50), MiddleName nvarchar(10), Affilication TEXT) ");
String deleteSQL = String.format("Delete from Author ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists Citation (CitationId nvarchar(50), Reference TEXT) ");
deleteSQL = String.format("Delete from Citation ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists Category (Category TEXT) ");
deleteSQL = String.format("Delete from Category ");
statement.executeUpdate(deleteSQL);
statement = connection.createStatement();
statement.executeUpdate("create table if not exists PubAuthor (PubId nvarchar(50), AuthorId nvarchar(50)) ");
deleteSQL = String.format("Delete from PubAuthor ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists PubCitation (PubId nvarchar(50), CitationId nvarchar(50)) ");
deleteSQL = String.format("Delete from PubCitation ");
statement.executeUpdate(deleteSQL);
statement.executeUpdate("create table if not exists PubCategory (PubId nvarchar(50), Category TEXT) ");
deleteSQL = String.format("Delete from PubCategory ");
statement.executeUpdate(deleteSQL);
PreparedStatement authorBulkInsert = null;
PreparedStatement citationBulkInsert = null;
PreparedStatement categoryBulkInsert = null;
PreparedStatement pubAuthorBulkInsert = null;
PreparedStatement pubCitationBulkInsert = null;
PreparedStatement pubCategoryBulkInsert = null;
String authorInsertsql = "insert into Author values(?,?,?,?,?);";
String citationInsertsql = "insert into Citation values(?,?);";
String categoryInsertsql = "insert into Category values(?);";
String pubAuthorInsertsql = "insert into pubAuthor values(?,?);";
String pubCitationInsertsql = "insert into pubCitation values(?,?);";
String pubCategoryInsertsql = "insert into pubCategory values(?,?);";
TObjectIntHashMap<String> authorsLst = new TObjectIntHashMap<String>();
TObjectIntHashMap<String> citationsLst = new TObjectIntHashMap<String>();
TObjectIntHashMap<String> categorysLst = new TObjectIntHashMap<String>();
try {
connection.setAutoCommit(false);
authorBulkInsert = connection.prepareStatement(authorInsertsql);
citationBulkInsert = connection.prepareStatement(citationInsertsql);
categoryBulkInsert = connection.prepareStatement(categoryInsertsql);
pubAuthorBulkInsert = connection.prepareStatement(pubAuthorInsertsql);
pubCitationBulkInsert = connection.prepareStatement(pubCitationInsertsql);
pubCategoryBulkInsert = connection.prepareStatement(pubCategoryInsertsql);
String sql = " Select articleid,authors_id,authors_firstname,authors_lastname,authors_middlename,authors_affiliation,authors_role, \n"
+ " ref_objid,reftext,primarycategory,othercategory \n"
+ " from ACMData1 \n";
// + " LIMIT 10";
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// read the result set
String Id = rs.getString("articleid");
String authorIdsStr = rs.getString("authors_id");
String[] authorIds = authorIdsStr.split("\t");
String authors_firstnamesStr = rs.getString("authors_firstname");
String[] authors_firstnames = authors_firstnamesStr.split("\t");
String authors_lastnamesStr = rs.getString("authors_lastname");
String[] authors_lastnames = authors_lastnamesStr.split("\t");
String authors_middlenamesStr = rs.getString("authors_middlename");
String[] authors_middlenames = authors_middlenamesStr.split("\t");
String authors_affiliationsStr = rs.getString("authors_affiliation");
String[] authors_affiliations = authors_affiliationsStr.split("\t");
for (int i = 0; i < authorIds.length - 1; i++) {
String authorId = authorIds[i];
if (!authorsLst.containsKey(authorId)) {
authorsLst.put(authorId, 1);
String lstName = authors_lastnames.length - 1 > i ? authors_lastnames[i] : "";
String fstName = authors_firstnames.length - 1 > i ? authors_firstnames[i] : "";
String mName = authors_middlenames.length - 1 > i ? authors_middlenames[i] : "";
String affiliation = authors_affiliations.length - 1 > i ? authors_affiliations[i] : "";
authorBulkInsert.setString(1, authorId);
authorBulkInsert.setString(2, lstName);
authorBulkInsert.setString(3, fstName);
authorBulkInsert.setString(4, mName);
authorBulkInsert.setString(5, affiliation);
authorBulkInsert.executeUpdate();
}
pubAuthorBulkInsert.setString(1, Id);
pubAuthorBulkInsert.setString(2, authorId);
pubAuthorBulkInsert.executeUpdate();
}
String citationIdsStr = rs.getString("ref_objid");
String[] citationIds = citationIdsStr.split("\t");
String citationsStr = rs.getString("reftext");
String[] citations = citationsStr.split("\t");
for (int i = 0; i < citationIds.length - 1; i++) {
String citationId = citationIds[i];
if (!citationsLst.containsKey(citationId)) {
citationsLst.put(citationId, 1);
String ref = citations.length - 1 > i ? citations[i] : "";
citationBulkInsert.setString(1, citationId);
citationBulkInsert.setString(2, ref);
citationBulkInsert.executeUpdate();
}
pubCitationBulkInsert.setString(1, Id);
pubCitationBulkInsert.setString(2, citationId);
pubCitationBulkInsert.executeUpdate();
}
String prCategoriesStr = rs.getString("primarycategory");
String[] prCategories = prCategoriesStr.split("\t");
String categoriesStr = rs.getString("othercategory");
String[] categories = categoriesStr.split("\t");
for (int i = 0; i < prCategories.length - 1; i++) {
String category = prCategories[i];
if (!categorysLst.containsKey(category)) {
categorysLst.put(category, 1);
categoryBulkInsert.setString(1, category);
categoryBulkInsert.executeUpdate();
}
pubCategoryBulkInsert.setString(1, Id);
pubCategoryBulkInsert.setString(2, category);
pubCategoryBulkInsert.executeUpdate();
}
for (int i = 0; i < categories.length - 1; i++) {
String category = categories[i];
if (!categorysLst.containsKey(category)) {
categorysLst.put(category, 1);
categoryBulkInsert.setString(1, category);
categoryBulkInsert.executeUpdate();
}
pubCategoryBulkInsert.setString(1, Id);
pubCategoryBulkInsert.setString(2, category);
pubCategoryBulkInsert.executeUpdate();
}
}
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
System.err.print("Transaction is being rolled back");
connection.rollback();
} catch (SQLException excep) {
System.err.print("Error in ACMReferences extraction");
}
}
} finally {
if (authorBulkInsert != null) {
authorBulkInsert.close();
}
if (categoryBulkInsert != null) {
categoryBulkInsert.close();
}
if (citationBulkInsert != null) {
citationBulkInsert.close();
}
connection.setAutoCommit(true);
}
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println("File input error");
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
}
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
iMixTopicModelExample trainer = new iMixTopicModelExample();
}
}
|
package org.bouncycastle.pkcs.jcajce;
import java.io.OutputStream;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.bc.BCObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.EncryptionScheme;
import org.bouncycastle.asn1.pkcs.KeyDerivationFunc;
import org.bouncycastle.asn1.pkcs.PBES2Parameters;
import org.bouncycastle.asn1.pkcs.PBKDF2Params;
import org.bouncycastle.asn1.pkcs.PKCS12PBEParams;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.jcajce.PKCS12KeyWithParameters;
import org.bouncycastle.jcajce.util.DefaultJcaJceHelper;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.jcajce.util.ProviderJcaJceHelper;
import org.bouncycastle.operator.DefaultSecretKeySizeProvider;
import org.bouncycastle.operator.GenericKey;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.OutputEncryptor;
import org.bouncycastle.operator.SecretKeySizeProvider;
public class JcePKCSPBEOutputEncryptorBuilder
{
private JcaJceHelper helper = new DefaultJcaJceHelper();
private ASN1ObjectIdentifier algorithm;
private ASN1ObjectIdentifier keyEncAlgorithm;
private SecureRandom random;
private SecretKeySizeProvider keySizeProvider = DefaultSecretKeySizeProvider.INSTANCE;
private int iterationCount = 1024;
private AlgorithmIdentifier prf = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA1, DERNull.INSTANCE);
public JcePKCSPBEOutputEncryptorBuilder(ASN1ObjectIdentifier algorithm)
{
if (isPKCS12(algorithm))
{
this.algorithm = algorithm;
this.keyEncAlgorithm = algorithm;
}
else
{
this.algorithm = PKCSObjectIdentifiers.id_PBES2;
this.keyEncAlgorithm = algorithm;
}
}
public JcePKCSPBEOutputEncryptorBuilder setProvider(Provider provider)
{
this.helper = new ProviderJcaJceHelper(provider);
return this;
}
public JcePKCSPBEOutputEncryptorBuilder setProvider(String providerName)
{
this.helper = new NamedJcaJceHelper(providerName);
return this;
}
/**
* Set the PRF to use for key generation. By default this is HmacSHA1.
*
* @param prf algorithm id for PRF.
*
* @return the current builder.
*/
public JcePKCSPBEOutputEncryptorBuilder setPRF(AlgorithmIdentifier prf)
{
this.prf = prf;
return this;
}
/**
* Set the lookup provider of AlgorithmIdentifier returning key_size_in_bits used to
* handle PKCS5 decryption.
*
* @param keySizeProvider a provider of integer secret key sizes.
*
* @return the current builder.
*/
public JcePKCSPBEOutputEncryptorBuilder setKeySizeProvider(SecretKeySizeProvider keySizeProvider)
{
this.keySizeProvider = keySizeProvider;
return this;
}
/**
* Set the iteration count for the PBE calculation.
*
* @param iterationCount the iteration count to apply to the key creation.
* @return the current builder.
*/
public JcePKCSPBEOutputEncryptorBuilder setIterationCount(int iterationCount)
{
this.iterationCount = iterationCount;
return this;
}
public OutputEncryptor build(final char[] password)
throws OperatorCreationException
{
final Cipher cipher;
SecretKey key;
if (random == null)
{
random = new SecureRandom();
}
final AlgorithmIdentifier encryptionAlg;
try
{
if (isPKCS12(algorithm))
{
byte[] salt = new byte[20];
random.nextBytes(salt);
cipher = helper.createCipher(algorithm.getId());
cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount));
encryptionAlg = new AlgorithmIdentifier(algorithm, new PKCS12PBEParams(salt, iterationCount));
}
else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2))
{
byte[] salt = new byte[JceUtils.getSaltSize(prf.getAlgorithm())];
random.nextBytes(salt);
SecretKeyFactory keyFact = helper.createSecretKeyFactory(JceUtils.getAlgorithm(prf.getAlgorithm()));
key = keyFact.generateSecret(new PBEKeySpec(password, salt, iterationCount, keySizeProvider.getKeySize(new AlgorithmIdentifier(keyEncAlgorithm))));
cipher = helper.createCipher(keyEncAlgorithm.getId());
cipher.init(Cipher.ENCRYPT_MODE, key, random);
PBES2Parameters algParams = new PBES2Parameters(
new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount, prf)),
new EncryptionScheme(keyEncAlgorithm, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
encryptionAlg = new AlgorithmIdentifier(algorithm, algParams);
}
else
{
throw new OperatorCreationException("unrecognised algorithm");
}
return new OutputEncryptor()
{
public AlgorithmIdentifier getAlgorithmIdentifier()
{
return encryptionAlg;
}
public OutputStream getOutputStream(OutputStream out)
{
return new CipherOutputStream(out, cipher);
}
public GenericKey getKey()
{
if (isPKCS12(encryptionAlg.getAlgorithm()))
{
return new GenericKey(encryptionAlg, PKCS12PasswordToBytes(password));
}
else
{
return new GenericKey(encryptionAlg, PKCS5PasswordToBytes(password));
}
}
};
}
catch (Exception e)
{
throw new OperatorCreationException("unable to create OutputEncryptor: " + e.getMessage(), e);
}
}
private boolean isPKCS12(ASN1ObjectIdentifier algorithm)
{
return algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)
|| algorithm.on(BCObjectIdentifiers.bc_pbe_sha1_pkcs12)
|| algorithm.on(BCObjectIdentifiers.bc_pbe_sha256_pkcs12);
}
/**
* converts a password to a byte array according to the scheme in
* PKCS5 (ascii, no padding)
*
* @param password a character array representing the password.
* @return a byte array representing the password.
*/
private static byte[] PKCS5PasswordToBytes(
char[] password)
{
if (password != null)
{
byte[] bytes = new byte[password.length];
for (int i = 0; i != bytes.length; i++)
{
bytes[i] = (byte)password[i];
}
return bytes;
}
else
{
return new byte[0];
}
}
/**
* converts a password to a byte array according to the scheme in
* PKCS12 (unicode, big endian, 2 zero pad bytes at the end).
*
* @param password a character array representing the password.
* @return a byte array representing the password.
*/
private static byte[] PKCS12PasswordToBytes(
char[] password)
{
if (password != null && password.length > 0)
{
// +1 for extra 2 pad bytes.
byte[] bytes = new byte[(password.length + 1) * 2];
for (int i = 0; i != password.length; i ++)
{
bytes[i * 2] = (byte)(password[i] >>> 8);
bytes[i * 2 + 1] = (byte)password[i];
}
return bytes;
}
else
{
return new byte[0];
}
}
}
|
package org.postgresql.ds.common;
import javax.naming.*;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* Base class for data sources and related classes.
*
* @author Aaron Mulder (ammulder@chariotsolutions.com)
*/
public abstract class BaseDataSource implements Referenceable
{
// Load the normal driver, since we'll use it to actually connect to the
// database. That way we don't have to maintain the connecting code in
// multiple places.
static {
try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e)
{
System.err.println("PostgreSQL DataSource unable to load PostgreSQL JDBC Driver");
}
}
// Needed to implement the DataSource/ConnectionPoolDataSource interfaces
private transient PrintWriter logger;
// Standard properties, defined in the JDBC 2.0 Optional Package spec
private String serverName = "localhost";
private String databaseName;
private String user;
private String password;
private int portNumber = 0;
private int prepareThreshold = 5;
private int unknownLength = Integer.MAX_VALUE;
private boolean binaryTransfer = true;
private String binaryTransferEnable = "";
private String binaryTransferDisable = "";
private int loginTimeout = 0; // in seconds
private int socketTimeout = 0; // in seconds
private boolean ssl = false;
private String sslfactory;
private boolean tcpKeepAlive = false;
private String compatible;
private int logLevel = 0;
private int protocolVersion = 0;
private String applicationName;
/**
* Gets a connection to the PostgreSQL database. The database is identified by the
* DataSource properties serverName, databaseName, and portNumber. The user to
* connect as is identified by the DataSource properties user and password.
*
* @return A valid database connection.
* @throws SQLException
* Occurs when the database connection cannot be established.
*/
public Connection getConnection() throws SQLException
{
return getConnection(user, password);
}
/**
* Gets a connection to the PostgreSQL database. The database is identified by the
* DataSource properties serverName, databaseName, and portNumber. The user to
* connect as is identified by the arguments user and password, which override
* the DataSource properties by the same name.
*
* @return A valid database connection.
* @throws SQLException
* Occurs when the database connection cannot be established.
*/
public Connection getConnection(String user, String password) throws SQLException
{
try
{
Connection con = DriverManager.getConnection(getUrl(), user, password);
if (logger != null)
{
logger.println("Created a non-pooled connection for " + user + " at " + getUrl());
}
return con;
}
catch (SQLException e)
{
if (logger != null)
{
logger.println("Failed to create a non-pooled connection for " + user + " at " + getUrl() + ": " + e);
}
throw e;
}
}
/**
* @return the login timeout, in seconds.
*/
public int getLoginTimeout() throws SQLException
{
return loginTimeout;
}
/**
* Set the login timeout, in seconds.
*/
public void setLoginTimeout(int i) throws SQLException
{
this.loginTimeout = i;
}
/**
* Gets the log writer used to log connections opened.
*/
public PrintWriter getLogWriter() throws SQLException
{
return logger;
}
/**
* The DataSource will note every connection opened to the provided log writer.
*/
public void setLogWriter(PrintWriter printWriter) throws SQLException
{
logger = printWriter;
}
/**
* Gets the name of the host the PostgreSQL database is running on.
*/
public String getServerName()
{
return serverName;
}
/**
* Sets the name of the host the PostgreSQL database is running on. If this
* is changed, it will only affect future calls to getConnection. The default
* value is <tt>localhost</tt>.
*/
public void setServerName(String serverName)
{
if (serverName == null || serverName.equals(""))
{
this.serverName = "localhost";
}
else
{
this.serverName = serverName;
}
}
public String getCompatible()
{
return compatible;
}
public void setCompatible(String compatible)
{
this.compatible = compatible;
}
public int getLogLevel()
{
return logLevel;
}
public void setLogLevel(int logLevel)
{
this.logLevel = logLevel;
}
public int getProtocolVersion()
{
return protocolVersion;
}
public void setProtocolVersion(int protocolVersion)
{
this.protocolVersion = protocolVersion;
}
/**
* Gets the name of the PostgreSQL database, running on the server identified
* by the serverName property.
*/
public String getDatabaseName()
{
return databaseName;
}
/**
* Sets the name of the PostgreSQL database, running on the server identified
* by the serverName property. If this is changed, it will only affect
* future calls to getConnection.
*/
public void setDatabaseName(String databaseName)
{
this.databaseName = databaseName;
}
/**
* Gets a description of this DataSource-ish thing. Must be customized by
* subclasses.
*/
public abstract String getDescription();
/**
* Gets the user to connect as by default. If this is not specified, you must
* use the getConnection method which takes a user and password as parameters.
*/
public String getUser()
{
return user;
}
/**
* Sets the user to connect as by default. If this is not specified, you must
* use the getConnection method which takes a user and password as parameters.
* If this is changed, it will only affect future calls to getConnection.
*/
public void setUser(String user)
{
this.user = user;
}
/**
* Gets the password to connect with by default. If this is not specified but a
* password is needed to log in, you must use the getConnection method which takes
* a user and password as parameters.
*/
public String getPassword()
{
return password;
}
/**
* Sets the password to connect with by default. If this is not specified but a
* password is needed to log in, you must use the getConnection method which takes
* a user and password as parameters. If this is changed, it will only affect
* future calls to getConnection.
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* Gets the port which the PostgreSQL server is listening on for TCP/IP
* connections.
*
* @return The port, or 0 if the default port will be used.
*/
public int getPortNumber()
{
return portNumber;
}
/**
* Gets the port which the PostgreSQL server is listening on for TCP/IP
* connections. Be sure the -i flag is passed to postmaster when PostgreSQL
* is started. If this is not set, or set to 0, the default port will be used.
*/
public void setPortNumber(int portNumber)
{
this.portNumber = portNumber;
}
/**
* Sets the default threshold for enabling server-side prepare.
* See {@link org.postgresql.PGConnection#setPrepareThreshold(int)} for details.
*
* @param count the number of times a statement object must be reused before server-side
* prepare is enabled.
*/
public void setPrepareThreshold(int count)
{
this.prepareThreshold = count;
}
/**
* Gets the default threshold for enabling server-side prepare.
*
* @see #setPrepareThreshold(int)
*/
public int getPrepareThreshold()
{
return prepareThreshold;
}
public void setUnknownLength(int unknownLength)
{
this.unknownLength = unknownLength;
}
public int getUnknownLength()
{
return unknownLength;
}
/**
* Sets the socket timeout (SOTimeout), in seconds
*/
public void setSocketTimeout(int seconds)
{
this.socketTimeout = seconds;
}
/**
* @return the socket timeout (SOTimeout), in seconds
*/
public int getSocketTimeout()
{
return this.socketTimeout;
}
/**
* Set whether the connection will be SSL encrypted or not.
*
* @param enabled if <CODE>true</CODE>, connect with SSL.
*/
public void setSsl(boolean enabled)
{
this.ssl = enabled;
}
/**
* Gets SSL encryption setting.
*
* @return <CODE>true</CODE> if connections will be encrypted with SSL.
*/
public boolean getSsl()
{
return this.ssl;
}
/**
* Set the name of the {@link javax.net.ssl.SSLSocketFactory} to use for connections.
* Use <CODE>org.postgresql.ssl.NonValidatingFactory</CODE> if you don't want certificate validation.
*
* @param classname name of a subclass of <CODE>javax.net.ssl.SSLSocketFactory</CODE> or <CODE>null</CODE> for the default implementation.
*/
public void setSslfactory(String classname)
{
this.sslfactory = classname;
}
/**
* Gets the name of the {@link javax.net.ssl.SSLSocketFactory} used for connections.
*
* @return name of the class or <CODE>null</CODE> if the default implementation is used.
*/
public String getSslfactory()
{
return this.sslfactory;
}
public void setApplicationName(String applicationName)
{
this.applicationName = applicationName;
}
public String getApplicationName()
{
return applicationName;
}
public void setTcpKeepAlive(boolean enabled)
{
tcpKeepAlive = enabled;
}
public boolean getTcpKeepAlive()
{
return tcpKeepAlive;
}
/**
* Sets protocol transfer mode.
*
* @param enabled True if the binary transfer mode is used for supported field types,
* false if text based transfer is used.
*/
public void setBinaryTransfer(boolean enabled)
{
this.binaryTransfer = enabled;
}
/**
* Gets the protocol transfer mode.
*
* @see #setBinaryTransfer(boolean)
*/
public boolean getBinaryTransfer()
{
return binaryTransfer;
}
/**
* Add types to the override set of {@link org.postgresql.core.Oid} values used for binary transfer.
*
* @param oidList The comma separated list of Oids. Either textual or numeric value.
*/
public void setBinaryTransferEnable(String oidList)
{
this.binaryTransferEnable = oidList;
}
/**
* Gets override set of Oid values that have binary transfer enabled.
*
* @see #setBinaryTransferEnable(String)
*/
public String getBinaryTransferEnable()
{
return binaryTransferEnable;
}
/**
* Add types to the override set of {@link org.postgresql.core.Oid} values that will not be used for binary transfer.
* This overrides any values in the driver detault set or values set with {@link #setBinaryTransferEnable(String)}.
*
* @param oidList The comma separated list of Oids. Either textual or numeric value.
*/
public void setBinaryTransferDisable(String oidList)
{
this.binaryTransferDisable = oidList;
}
/**
* Gets override set of Oid values that have binary transfer disabled.
*
* @see #setBinaryTransferDisable(String)
*/
public String getBinaryTransferDisable()
{
return binaryTransferDisable;
}
/**
* Generates a DriverManager URL from the other properties supplied.
*/
private String getUrl()
{
StringBuffer sb = new StringBuffer(100);
sb.append("jdbc:postgresql:
sb.append(serverName);
if (portNumber != 0) {
sb.append(":").append(portNumber);
}
sb.append("/").append(databaseName);
sb.append("?loginTimeout=").append(loginTimeout);
sb.append("&socketTimeout=").append(socketTimeout);
sb.append("&prepareThreshold=").append(prepareThreshold);
sb.append("&unknownLength=").append(unknownLength);
sb.append("&loglevel=").append(logLevel);
if (protocolVersion != 0) {
sb.append("&protocolVersion=").append(protocolVersion);
}
if (ssl) {
sb.append("&ssl=true");
if (sslfactory != null) {
sb.append("&sslfactory=").append(sslfactory);
}
}
sb.append("&tcpkeepalive=").append(tcpKeepAlive);
if (compatible != null) {
sb.append("&compatible="+compatible);
}
if (applicationName != null) {
sb.append("&ApplicationName=");
sb.append(applicationName);
}
if (binaryTransfer) {
sb.append("&binaryTransfer=true");
}
return sb.toString();
}
/**
* Generates a reference using the appropriate object factory.
*/
protected Reference createReference() {
return new Reference(
getClass().getName(),
PGObjectFactory.class.getName(),
null);
}
public Reference getReference() throws NamingException
{
Reference ref = createReference();
ref.add(new StringRefAddr("serverName", serverName));
if (portNumber != 0)
{
ref.add(new StringRefAddr("portNumber", Integer.toString(portNumber)));
}
ref.add(new StringRefAddr("databaseName", databaseName));
if (user != null)
{
ref.add(new StringRefAddr("user", user));
}
if (password != null)
{
ref.add(new StringRefAddr("password", password));
}
ref.add(new StringRefAddr("prepareThreshold", Integer.toString(prepareThreshold)));
ref.add(new StringRefAddr("unknownLength", Integer.toString(unknownLength)));
ref.add(new StringRefAddr("binaryTransfer", Boolean.toString(binaryTransfer)));
ref.add(new StringRefAddr("loginTimeout", Integer.toString(loginTimeout)));
ref.add(new StringRefAddr("socketTimeout", Integer.toString(socketTimeout)));
ref.add(new StringRefAddr("ssl", Boolean.toString(ssl)));
ref.add(new StringRefAddr("sslfactory", sslfactory));
ref.add(new StringRefAddr("tcpKeepAlive", Boolean.toString(tcpKeepAlive)));
if (compatible != null)
{
ref.add(new StringRefAddr("compatible", compatible));
}
ref.add(new StringRefAddr("logLevel", Integer.toString(logLevel)));
ref.add(new StringRefAddr("protocolVersion", Integer.toString(protocolVersion)));
ref.add(new StringRefAddr("ApplicationName", applicationName));
return ref;
}
protected void writeBaseObject(ObjectOutputStream out) throws IOException
{
out.writeObject(serverName);
out.writeObject(databaseName);
out.writeObject(user);
out.writeObject(password);
out.writeInt(portNumber);
out.writeInt(prepareThreshold);
out.writeInt(unknownLength);
out.writeInt(loginTimeout);
out.writeInt(socketTimeout);
out.writeBoolean(ssl);
out.writeObject(sslfactory);
out.writeBoolean(tcpKeepAlive);
out.writeObject(compatible);
out.writeInt(logLevel);
out.writeInt(protocolVersion);
out.writeObject(applicationName);
out.writeBoolean(binaryTransfer);
out.writeObject(binaryTransferEnable);
out.writeObject(binaryTransferDisable);
}
protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
serverName = (String)in.readObject();
databaseName = (String)in.readObject();
user = (String)in.readObject();
password = (String)in.readObject();
portNumber = in.readInt();
prepareThreshold = in.readInt();
unknownLength = in.readInt();
loginTimeout = in.readInt();
socketTimeout = in.readInt();
ssl = in.readBoolean();
sslfactory = (String)in.readObject();
tcpKeepAlive = in.readBoolean();
compatible = (String)in.readObject();
logLevel = in.readInt();
protocolVersion = in.readInt();
applicationName = (String)in.readObject();
binaryTransfer = in.readBoolean();
binaryTransferEnable = (String)in.readObject();
binaryTransferDisable = (String)in.readObject();
}
public void initializeFrom(BaseDataSource source) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
source.writeBaseObject(oos);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
readBaseObject(ois);
}
}
|
package com.cloud.api.response;
import java.util.Date;
import com.cloud.api.ApiConstants;
import com.cloud.api.IdentityProxy;
import com.cloud.host.Host;
import com.cloud.host.Status;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class HostResponse extends BaseResponse {
@SerializedName(ApiConstants.ID) @Param(description="the ID of the host")
private IdentityProxy id = new IdentityProxy("host");
@SerializedName(ApiConstants.NAME) @Param(description="the name of the host")
private String name;
@SerializedName(ApiConstants.STATE) @Param(description="the state of the host")
private Status state;
@SerializedName("disconnected") @Param(description="true if the host is disconnected. False otherwise.")
private Date disconnectedOn;
@SerializedName(ApiConstants.TYPE) @Param(description="the host type")
private Host.Type hostType;
@SerializedName("oscategoryid") @Param(description="the OS category ID of the host")
private IdentityProxy osCategoryId = new IdentityProxy("guest_os_category");
@SerializedName("oscategoryname") @Param(description="the OS category name of the host")
private String osCategoryName;
@SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the IP address of the host")
private String ipAddress;
@SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the host")
private IdentityProxy zoneId = new IdentityProxy("data_center");
@SerializedName("zonename") @Param(description="the Zone name of the host")
private String zoneName;
@SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID of the host")
private IdentityProxy podId = new IdentityProxy("host_pod_ref");
@SerializedName("podname") @Param(description="the Pod name of the host")
private String podName;
@SerializedName("version") @Param(description="the host version")
private String version;
@SerializedName(ApiConstants.HYPERVISOR) @Param(description="the host hypervisor")
private HypervisorType hypervisor;
@SerializedName("cpunumber") @Param(description="the CPU number of the host")
private Integer cpuNumber;
@SerializedName("cpuspeed") @Param(description="the CPU speed of the host")
private Long cpuSpeed;
@SerializedName("cpuallocated") @Param(description="the amount of the host's CPU currently allocated")
private String cpuAllocated;
@SerializedName("cpuused") @Param(description="the amount of the host's CPU currently used")
private String cpuUsed;
@SerializedName("cpuwithoverprovisioning") @Param(description="the amount of the host's CPU after applying the cpu.overprovisioning.factor ")
private String cpuWithOverprovisioning;
@SerializedName("averageload") @Param(description="the cpu average load on the host")
private Long averageLoad;
@SerializedName("networkkbsread") @Param(description="the incoming network traffic on the host")
private Long networkKbsRead;
@SerializedName("networkkbswrite") @Param(description="the outgoing network traffic on the host")
private Long networkKbsWrite;
@SerializedName("memorytotal") @Param(description="the memory total of the host")
private Long memoryTotal;
@SerializedName("memoryallocated") @Param(description="the amount of the host's memory currently allocated")
private Long memoryAllocated;
@SerializedName("memoryused") @Param(description="the amount of the host's memory currently used")
private Long memoryUsed;
@SerializedName("disksizetotal") @Param(description="the total disk size of the host")
private Long diskSizeTotal;
@SerializedName("disksizeallocated") @Param(description="the host's currently allocated disk size")
private Long diskSizeAllocated;
@SerializedName("capabilities") @Param(description="capabilities of the host")
private String capabilities;
@SerializedName("lastpinged") @Param(description="the date and time the host was last pinged")
private Date lastPinged;
@SerializedName("managementserverid") @Param(description="the management server ID of the host")
private Long managementServerId;
@SerializedName("clusterid") @Param(description="the cluster ID of the host")
private IdentityProxy clusterId = new IdentityProxy("cluster");
@SerializedName("clustername") @Param(description="the cluster name of the host")
private String clusterName;
@SerializedName("clustertype") @Param(description="the cluster type of the cluster that host belongs to")
private String clusterType;
@SerializedName("islocalstorageactive") @Param(description="true if local storage is active, false otherwise")
private Boolean localStorageActive;
@SerializedName(ApiConstants.CREATED) @Param(description="the date and time the host was created")
private Date created;
@SerializedName("removed") @Param(description="the date and time the host was removed")
private Date removed;
@SerializedName("events") @Param(description="events available for the host")
private String events;
@SerializedName("hosttags") @Param(description="comma-separated list of tags for the host")
private String hostTags;
@SerializedName("hasenoughcapacity") @Param(description="true if this host has enough CPU and RAM capacity to migrate a VM to it, false otherwise")
private Boolean hasEnoughCapacity;
@SerializedName("suitableformigration") @Param(description="true if this host is suitable(has enough capacity and satisfies all conditions like hosttags, max guests vm limit etc) to migrate a VM to it , false otherwise")
private Boolean suitableForMigration;
@SerializedName("resourcestate") @Param(description="the resource state of the host")
private String resourceState;
@SerializedName(ApiConstants.HYPERVISOR_VERSION) @Param(description="the hypervisor version")
private String hypervisorVersion;
@Override
public Long getObjectId() {
return getId();
}
public Long getId() {
return id.getValue();
}
public void setId(Long id) {
this.id.setValue(id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Status getState() {
return state;
}
public void setState(Status state) {
this.state = state;
}
public Date getDisconnectedOn() {
return disconnectedOn;
}
public void setDisconnectedOn(Date disconnectedOn) {
this.disconnectedOn = disconnectedOn;
}
public Host.Type getHostType() {
return hostType;
}
public void setHostType(Host.Type hostType) {
this.hostType = hostType;
}
public Long getOsCategoryId() {
return osCategoryId.getValue();
}
public void setOsCategoryId(Long osCategoryId) {
this.osCategoryId.setValue(osCategoryId);
}
public String getOsCategoryName() {
return osCategoryName;
}
public void setOsCategoryName(String osCategoryName) {
this.osCategoryName = osCategoryName;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public Long getZoneId() {
return zoneId.getValue();
}
public void setZoneId(Long zoneId) {
this.zoneId.setValue(zoneId);
}
public String getZoneName() {
return zoneName;
}
public void setZoneName(String zoneName) {
this.zoneName = zoneName;
}
public Long getPodId() {
return podId.getValue();
}
public void setPodId(Long podId) {
this.podId.setValue(podId);
}
public String getPodName() {
return podName;
}
public void setPodName(String podName) {
this.podName = podName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public HypervisorType getHypervisor() {
return hypervisor;
}
public void setHypervisor(HypervisorType hypervisor) {
this.hypervisor = hypervisor;
}
public Integer getCpuNumber() {
return cpuNumber;
}
public void setCpuNumber(Integer cpuNumber) {
this.cpuNumber = cpuNumber;
}
public Long getCpuSpeed() {
return cpuSpeed;
}
public void setCpuSpeed(Long cpuSpeed) {
this.cpuSpeed = cpuSpeed;
}
public String getCpuAllocated() {
return cpuAllocated;
}
public void setCpuAllocated(String cpuAllocated) {
this.cpuAllocated = cpuAllocated;
}
public String getCpuUsed() {
return cpuUsed;
}
public void setCpuUsed(String cpuUsed) {
this.cpuUsed = cpuUsed;
}
public Long getAverageLoad() {
return averageLoad;
}
public void setAverageLoad(Long averageLoad) {
this.averageLoad = averageLoad;
}
public Long getNetworkKbsRead() {
return networkKbsRead;
}
public void setNetworkKbsRead(Long networkKbsRead) {
this.networkKbsRead = networkKbsRead;
}
public Long getNetworkKbsWrite() {
return networkKbsWrite;
}
public void setNetworkKbsWrite(Long networkKbsWrite) {
this.networkKbsWrite = networkKbsWrite;
}
public Long getMemoryTotal() {
return memoryTotal;
}
public void setMemoryTotal(Long memoryTotal) {
this.memoryTotal = memoryTotal;
}
public Long getMemoryAllocated() {
return memoryAllocated;
}
public void setMemoryAllocated(Long memoryAllocated) {
this.memoryAllocated = memoryAllocated;
}
public Long getMemoryUsed() {
return memoryUsed;
}
public void setMemoryUsed(Long memoryUsed) {
this.memoryUsed = memoryUsed;
}
public Long getDiskSizeTotal() {
return diskSizeTotal;
}
public void setDiskSizeTotal(Long diskSizeTotal) {
this.diskSizeTotal = diskSizeTotal;
}
public Long getDiskSizeAllocated() {
return diskSizeAllocated;
}
public void setDiskSizeAllocated(Long diskSizeAllocated) {
this.diskSizeAllocated = diskSizeAllocated;
}
public String getCapabilities() {
return capabilities;
}
public void setCapabilities(String capabilities) {
this.capabilities = capabilities;
}
public Date getLastPinged() {
return lastPinged;
}
public void setLastPinged(Date lastPinged) {
this.lastPinged = lastPinged;
}
public Long getManagementServerId() {
return managementServerId;
}
public void setManagementServerId(Long managementServerId) {
this.managementServerId = managementServerId;
}
public Long getClusterId() {
return clusterId.getValue();
}
public void setClusterId(Long clusterId) {
this.clusterId.setValue(clusterId);
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getClusterType() {
return clusterType;
}
public void setClusterType(String clusterType) {
this.clusterType = clusterType;
}
public Boolean isLocalStorageActive() {
return localStorageActive;
}
public void setLocalStorageActive(Boolean localStorageActive) {
this.localStorageActive = localStorageActive;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getRemoved() {
return removed;
}
public void setRemoved(Date removed) {
this.removed = removed;
}
public String getEvents() {
return events;
}
public void setEvents(String events) {
this.events = events;
}
public String getHostTags() {
return hostTags;
}
public void setHostTags(String hostTags) {
this.hostTags = hostTags;
}
public Boolean hasEnoughCapacity() {
return hasEnoughCapacity;
}
public void setHasEnoughCapacity(Boolean hasEnoughCapacity) {
this.hasEnoughCapacity = hasEnoughCapacity;
}
public Boolean isSuitableForMigration() {
return suitableForMigration;
}
public void setSuitableForMigration(Boolean suitableForMigration) {
this.suitableForMigration = suitableForMigration;
}
public String getResourceState() {
return resourceState;
}
public void setResourceState(String resourceState) {
this.resourceState = resourceState;
}
public String getCpuWithOverprovisioning() {
return cpuWithOverprovisioning;
}
public void setCpuWithOverprovisioning(String cpuWithOverprovisioning) {
this.cpuWithOverprovisioning = cpuWithOverprovisioning;
}
public void setHypervisorVersion(String hypervisorVersion) {
this.hypervisorVersion = hypervisorVersion;
}
public String getHypervisorVersion() {
return hypervisorVersion;
}
}
|
package com.intellij.codeInsight.lookup;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.openapi.util.ClassConditionKey;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
/**
* @author peter
*
* @see com.intellij.codeInsight.completion.PrioritizedLookupElement
*/
public abstract class LookupElementDecorator<T extends LookupElement> extends LookupElement {
private final @NotNull T myDelegate;
protected LookupElementDecorator(@NotNull T delegate) {
myDelegate = delegate;
myDelegate.copyUserDataTo(this);
}
public @NotNull T getDelegate() {
return myDelegate;
}
@Override
public boolean isValid() {
return myDelegate.isValid() && super.isValid();
}
@Override
@NotNull
public String getLookupString() {
return myDelegate.getLookupString();
}
@Override
public Set<String> getAllLookupStrings() {
return myDelegate.getAllLookupStrings();
}
@NotNull
@Override
public Object getObject() {
return myDelegate.getObject();
}
@Override
public void handleInsert(@NotNull InsertionContext context) {
myDelegate.handleInsert(context);
}
@Override
public AutoCompletionPolicy getAutoCompletionPolicy() {
return myDelegate.getAutoCompletionPolicy();
}
@Override
public String toString() {
return myDelegate.toString();
}
@Override
public void renderElement(LookupElementPresentation presentation) {
myDelegate.renderElement(presentation);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LookupElementDecorator that = (LookupElementDecorator)o;
if (!myDelegate.equals(that.myDelegate)) return false;
return true;
}
@Override
public int hashCode() {
return myDelegate.hashCode();
}
@NotNull
public static <T extends LookupElement> LookupElementDecorator<T> withInsertHandler(@NotNull T element, @NotNull final InsertHandler<? super LookupElementDecorator<T>> insertHandler) {
return new InsertingDecorator<>(element, insertHandler);
}
@NotNull
public static <T extends LookupElement> LookupElementDecorator<T> withRenderer(@NotNull final T element, @NotNull final LookupElementRenderer<? super LookupElementDecorator<T>> visagiste) {
return new VisagisteDecorator<>(element, visagiste);
}
@Override
public <T> T as(ClassConditionKey<T> conditionKey) {
final T t = super.as(conditionKey);
return t == null ? myDelegate.as(conditionKey) : t;
}
@Override
public <T> T as(Class<T> clazz) {
final T t = super.as(clazz);
return t == null ? myDelegate.as(clazz) : t;
}
@Override
public boolean isCaseSensitive() {
return myDelegate.isCaseSensitive();
}
@Override
public boolean isWorthShowingInAutoPopup() {
return myDelegate.isWorthShowingInAutoPopup();
}
@Nullable
@Override
public PsiElement getPsiElement() {
return myDelegate.getPsiElement();
}
private static class InsertingDecorator<T extends LookupElement> extends LookupElementDecorator<T> {
private final InsertHandler<? super LookupElementDecorator<T>> myInsertHandler;
InsertingDecorator(T element, InsertHandler<? super LookupElementDecorator<T>> insertHandler) {
super(element);
myInsertHandler = insertHandler;
}
@Override
public void handleInsert(@NotNull InsertionContext context) {
myInsertHandler.handleInsert(context, this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
InsertingDecorator that = (InsertingDecorator)o;
if (!myInsertHandler.equals(that.myInsertHandler)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + myInsertHandler.hashCode();
return result;
}
}
private static class VisagisteDecorator<T extends LookupElement> extends LookupElementDecorator<T> {
private final LookupElementRenderer<? super LookupElementDecorator<T>> myVisagiste;
VisagisteDecorator(T element, LookupElementRenderer<? super LookupElementDecorator<T>> visagiste) {
super(element);
myVisagiste = visagiste;
}
@Override
public void renderElement(final LookupElementPresentation presentation) {
myVisagiste.renderElement(this, presentation);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
VisagisteDecorator that = (VisagisteDecorator)o;
if (!myVisagiste.getClass().equals(that.myVisagiste.getClass())) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + myVisagiste.getClass().hashCode();
return result;
}
}
}
|
package org.xbill.DNS.utils;
import java.io.*;
import java.math.BigInteger;
/**
* An extension of ByteArrayInputStream to support directly reading types
* used by DNS routines.
* @see DataByteOutputStream
*
* @author Brian Wellington
*/
public class DataByteInputStream extends ByteArrayInputStream {
/**
* Creates a new DataByteInputStream
* @param b The byte array to read from
*/
public
DataByteInputStream(byte [] b) {
super(b);
}
/**
* Read data from the stream.
* @param b The array to read into
* @return The number of bytes read
*/
public int
read(byte [] b) throws IOException {
if (b.length == 0) {
return 0;
}
int n = read(b, 0, b.length);
if (n < b.length)
throw new IOException("end of input");
return n;
}
/**
* Read data from the stream.
* @param b The array to read into
* @param pos The starting position
* @param len The number of bytes to read
* @return The number of bytes read
*/
public int
readArray(byte [] b, int pos, int len) throws IOException {
if (len == 0) {
return 0;
}
int n = read(b, pos, len);
if (n < len)
throw new IOException("end of input");
return n;
}
/**
* Read a byte from the stream
* @return The byte
*/
public byte
readByte() throws IOException {
int i = read();
if (i == -1)
throw new IOException("end of input");
return (byte) i;
}
/**
* Read an unsigned byte from the stream
* @return The unsigned byte as an int
*/
public int
readUnsignedByte() throws IOException {
int i = read();
if (i == -1)
throw new IOException("end of input");
return i;
}
/**
* Read a short from the stream
* @return The short
*/
public short
readShort() throws IOException {
int c1 = read();
int c2 = read();
if (c1 == -1 || c2 == -1)
throw new IOException("end of input");
return (short)((c1 << 8) + c2);
}
/**
* Read an unsigned short from the stream
* @return The unsigned short as an int
*/
public int
readUnsignedShort() throws IOException {
int c1 = read();
int c2 = read();
if (c1 == -1 || c2 == -1)
throw new IOException("end of input");
return ((c1 << 8) + c2);
}
/**
* Read an int from the stream
* @return The int
*/
public int
readInt() throws IOException {
int c1 = read();
int c2 = read();
int c3 = read();
int c4 = read();
if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1)
throw new IOException("end of input");
return ((c1 << 24) + (c2 << 16) + (c3 << 8) + c4);
}
/**
* Read an unsigned int from the stream
* @return The unsigned int, as a long.
*/
public long
readUnsignedInt() throws IOException {
int c1 = read();
int c2 = read();
int c3 = read();
int c4 = read();
if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1)
throw new IOException("end of input");
return (((long)c1 << 24) + (c2 << 16) + (c3 << 8) + c4);
}
/**
* Read a long from the stream
* @return The long
*/
public long
readLong() throws IOException {
int c1 = read();
int c2 = read();
int c3 = read();
int c4 = read();
int c5 = read();
int c6 = read();
int c7 = read();
int c8 = read();
if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1 ||
c5 == -1 || c6 == -1 || c7 == -1 || c8 == -1)
throw new IOException("end of input");
return ((c1 << 56) + (c2 << 48) + (c3 << 40) + (c4 << 32) +
(c5 << 24) + (c6 << 16) + (c7 << 8) + c8);
}
/**
* Read a String from the stream, represented as a length byte followed by data,
* and encode it in a byte array.
* @return The array
*/
public byte []
readStringIntoArray() throws IOException {
int len = read();
if (len == -1)
throw new IOException("end of input");
byte [] b = new byte[len];
int n = read(b);
if (n < len)
throw new IOException("end of input");
return b;
}
/**
* Read a String from the stream, represented as a length byte followed by data
* @return The String
*/
public String
readString() throws IOException {
byte [] b = readStringIntoArray();
return new String(b);
}
/**
* Read a BigInteger from the stream, encoded as binary data. A 0 byte is
* prepended so that the value is always positive.
* @param len The number of bytes to read
* @return The BigInteger
*/
public BigInteger
readBigInteger(int len) throws IOException {
byte [] b = new byte[len + 1];
int n = read(b, 1, len);
if (n < len)
throw new IOException("end of input");
return new BigInteger(b);
}
/**
* Read and ignore bytes from the stream
* @param n The number of bytes to skip
*/
public void
skipBytes(int n) throws IOException {
skip(n);
}
/**
* Get the current position in the stream
* @return The current position
*/
public int
getPos() {
return pos;
}
/**
* Sets the current position in the stream
*/
public void
setPos(int pos) {
this.pos = pos;
}
}
|
package im.actor.sdk.controllers.fragment;
import android.app.Activity;
import android.support.v7.widget.ChatLinearLayoutManager;
import android.support.v7.widget.CustomItemAnimator;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import im.actor.runtime.generic.mvvm.BindedDisplayList;
import im.actor.runtime.generic.mvvm.DisplayList;
import im.actor.sdk.R;
import im.actor.sdk.view.adapters.HeaderViewRecyclerAdapter;
import im.actor.runtime.android.view.BindedListAdapter;
import im.actor.runtime.bser.BserObject;
import im.actor.runtime.storage.ListEngineItem;
public abstract class DisplayListFragment<T extends BserObject & ListEngineItem,
V extends RecyclerView.ViewHolder> extends BaseFragment implements DisplayList.Listener {
private RecyclerView collection;
// private View emptyCollection;
private BindedDisplayList<T> displayList;
private BindedListAdapter<T, V> adapter;
private RecyclerView.OnScrollListener onScrollListener;
protected View inflate(LayoutInflater inflater, ViewGroup container, int resource, BindedDisplayList<T> displayList) {
View res = inflater.inflate(resource, container, false);
afterViewInflate(res, displayList);
return res;
}
protected void afterViewInflate(View view, BindedDisplayList<T> displayList) {
collection = (RecyclerView) view.findViewById(R.id.collection);
if (displayList.getSize() == 0) {
collection.setVisibility(View.INVISIBLE);
} else {
collection.setVisibility(View.VISIBLE);
}
setAnimationsEnabled(true);
this.displayList = displayList;
configureRecyclerView(collection);
// emptyCollection = res.findViewById(R.id.emptyCollection);
adapter = onCreateAdapter(displayList, getActivity());
collection.setAdapter(adapter);
if (onScrollListener != null) {
collection.addOnScrollListener(onScrollListener);
}
// if (emptyCollection != null) {
// emptyCollection.setVisibility(View.GONE);
}
public void setAnimationsEnabled(boolean isEnabled) {
if (isEnabled) {
CustomItemAnimator itemAnimator = new CustomItemAnimator();
itemAnimator.setSupportsChangeAnimations(false);
itemAnimator.setMoveDuration(200);
itemAnimator.setAddDuration(150);
itemAnimator.setRemoveDuration(200);
collection.setItemAnimator(itemAnimator);
} else {
collection.setItemAnimator(null);
}
}
protected void configureRecyclerView(RecyclerView recyclerView) {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(
new ChatLinearLayoutManager(getActivity(), ChatLinearLayoutManager.VERTICAL, false));
}
protected void addHeaderView(View header) {
if (collection.getAdapter() instanceof HeaderViewRecyclerAdapter) {
HeaderViewRecyclerAdapter h = (HeaderViewRecyclerAdapter) collection.getAdapter();
h.addHeaderView(header);
} else {
HeaderViewRecyclerAdapter headerViewRecyclerAdapter = new HeaderViewRecyclerAdapter(adapter);
headerViewRecyclerAdapter.addHeaderView(header);
collection.setAdapter(headerViewRecyclerAdapter);
}
}
protected void addFooterView(View header) {
if (collection.getAdapter() instanceof HeaderViewRecyclerAdapter) {
HeaderViewRecyclerAdapter h = (HeaderViewRecyclerAdapter) collection.getAdapter();
h.addFooterView(header);
} else {
HeaderViewRecyclerAdapter headerViewRecyclerAdapter = new HeaderViewRecyclerAdapter(adapter);
headerViewRecyclerAdapter.addFooterView(header);
collection.setAdapter(headerViewRecyclerAdapter);
}
}
protected abstract BindedListAdapter<T, V> onCreateAdapter(BindedDisplayList<T> displayList, Activity activity);
public BindedListAdapter<T, V> getAdapter() {
return adapter;
}
public BindedDisplayList<T> getDisplayList() {
return displayList;
}
public RecyclerView getCollection() {
return collection;
}
public void setOnScrollListener(RecyclerView.OnScrollListener onScrollListener) {
this.onScrollListener = onScrollListener;
}
@Override
public void onResume() {
super.onResume();
adapter.resume();
displayList.addListener(this);
if (displayList.getSize() == 0) {
hideView(collection, false);
} else {
showView(collection, false);
}
}
@Override
public void onCollectionChanged() {
if (displayList.getSize() == 0) {
hideView(collection);
} else {
showView(collection);
}
}
@Override
public void onPause() {
super.onPause();
adapter.pause();
displayList.removeListener(this);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (adapter != null) {
if (!adapter.isGlobalList()) {
adapter.dispose();
}
adapter = null;
}
// emptyCollection = null;
collection = null;
}
}
|
package com.intellij.util.indexing.contentQueue;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.InvalidVirtualFileAccessException;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem;
import com.intellij.util.PathUtil;
import com.intellij.util.indexing.FileBasedIndexImpl;
import com.intellij.util.indexing.diagnostic.FileIndexingStatistics;
import com.intellij.util.indexing.diagnostic.IndexingJobStatistics;
import com.intellij.util.indexing.diagnostic.TooLargeForIndexingFile;
import com.intellij.util.progress.SubTaskProgressIndicator;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@ApiStatus.Internal
public final class IndexUpdateRunner {
private static final long SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY = 20 * FileUtilRt.MEGABYTE;
private static final CopyOnWriteArrayList<IndexingJob> ourIndexingJobs = new CopyOnWriteArrayList<>();
private final FileBasedIndexImpl myFileBasedIndex;
private final ExecutorService myIndexingExecutor;
private final int myNumberOfIndexingThreads;
/**
* Memory optimization to prevent OutOfMemory on loading file contents.
* <p>
* "Soft" total limit of bytes loaded into memory in the whole application is {@link #SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}.
* It is "soft" because one (and only one) "indexable" file can exceed this limit.
* <p>
* "Indexable" file is any file for which {@link FileBasedIndexImpl#isTooLarge(VirtualFile)} returns {@code false}.
* Note that this method may return {@code false} even for relatively big files with size greater than {@link #SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}.
* This is because for some files (or file types) the size limit is ignored.
* <p>
* So in its maximum we will load {@code SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY + <size of not "too large" file>}, which seems acceptable,
* because we have to index this "not too large" file anyway (even if its size is 4 Gb), and {@code SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY}
* additional bytes are insignificant.
*/
private static long ourTotalBytesLoadedIntoMemory = 0;
private static final Lock ourLoadedBytesLimitLock = new ReentrantLock();
private static final Condition ourLoadedBytesAreReleasedCondition = ourLoadedBytesLimitLock.newCondition();
public IndexUpdateRunner(@NotNull FileBasedIndexImpl fileBasedIndex,
@NotNull ExecutorService indexingExecutor,
int numberOfIndexingThreads) {
myFileBasedIndex = fileBasedIndex;
myIndexingExecutor = indexingExecutor;
myNumberOfIndexingThreads = numberOfIndexingThreads;
}
@NotNull
public IndexingJobStatistics indexFiles(@NotNull Project project,
@NotNull Collection<VirtualFile> files,
@NotNull ProgressIndicator indicator) {
indicator.checkCanceled();
indicator.setIndeterminate(false);
CachedFileContentLoader contentLoader = new CurrentProjectHintedCachedFileContentLoader(project);
IndexingJob indexingJob = new IndexingJob(project, indicator, contentLoader, files);
if (ApplicationManager.getApplication().isWriteAccessAllowed()) {
// If the current thread has acquired the write lock, we can't grant it to worker threads, so we must do the work in the current thread.
while (!indexingJob.areAllFilesProcessed()) {
indexOneFileOfJob(indexingJob);
}
}
else {
ourIndexingJobs.add(indexingJob);
try {
AtomicInteger numberOfRunningWorkers = new AtomicInteger();
Runnable worker = () -> {
try {
indexJobsFairly();
}
finally {
numberOfRunningWorkers.decrementAndGet();
}
};
for (int i = 0; i < myNumberOfIndexingThreads; i++) {
myIndexingExecutor.execute(worker);
numberOfRunningWorkers.incrementAndGet();
}
while (!project.isDisposed() && !indexingJob.areAllFilesProcessed() && indexingJob.myError.get() == null) {
// Add a worker if the previous died for whatever reason, to avoid waiting for nothing.
if (numberOfRunningWorkers.get() < myNumberOfIndexingThreads) {
myIndexingExecutor.execute(worker);
numberOfRunningWorkers.incrementAndGet();
}
indicator.checkCanceled();
try {
if (indexingJob.myAllFilesAreProcessedLatch.await(100, TimeUnit.MILLISECONDS)) {
break;
}
}
catch (InterruptedException e) {
throw new ProcessCanceledException(e);
}
}
Throwable error = indexingJob.myError.get();
if (error instanceof ProcessCanceledException) {
throw (ProcessCanceledException) error;
}
if (error != null) {
throw new RuntimeException("Indexing of " + project.getName() + " has failed", error);
}
}
finally {
ourIndexingJobs.remove(indexingJob);
}
}
return indexingJob.myStatistics;
}
// Index jobs one by one while there are some. Jobs may belong to different projects, and we index them fairly.
// Drops finished, cancelled and failed jobs from {@code ourIndexingJobs}. Does not throw exceptions.
private void indexJobsFairly() {
while (!ourIndexingJobs.isEmpty()) {
for (IndexingJob job : ourIndexingJobs) {
if (job.myProject.isDisposed()
|| job.myNoMoreFilesInQueue.get()
|| job.myIndicator.isCanceled()
|| job.myError.get() != null) {
ourIndexingJobs.remove(job);
continue;
}
try {
indexOneFileOfJob(job);
}
catch (Throwable e) {
job.myError.compareAndSet(null, e);
ourIndexingJobs.remove(job);
}
}
}
}
private void indexOneFileOfJob(@NotNull IndexingJob indexingJob) throws ProcessCanceledException {
long contentLoadingTime = System.nanoTime();
ContentLoadingResult loadingResult;
try {
loadingResult = loadNextContent(indexingJob, indexingJob.myIndicator);
}
catch (TooLargeContentException e) {
indexingJob.oneMoreFileProcessed();
indexingJob.myStatistics.getNumberOfTooLargeForIndexingFiles().incrementAndGet();
indexingJob.myStatistics.getTooLargeForIndexingFiles().addElement(new TooLargeForIndexingFile(e.getFile().getName(), e.getFile().getLength()));
FileBasedIndexImpl.LOG.info("File: " + e.getFile().getUrl() + " is too large for indexing");
return;
}
catch (FailedToLoadContentException e) {
indexingJob.oneMoreFileProcessed();
logFailedToLoadContentException(e);
return;
}
finally {
contentLoadingTime = System.nanoTime() - contentLoadingTime;
}
if (loadingResult == null) {
indexingJob.myNoMoreFilesInQueue.set(true);
return;
}
CachedFileContent fileContent = loadingResult.cachedFileContent;
VirtualFile file = fileContent.getVirtualFile();
try {
indexingJob.setLocationBeingIndexed(file);
if (!file.isDirectory()) {
FileIndexingStatistics fileIndexingStatistics = ReadAction
.nonBlocking(() -> myFileBasedIndex.indexFileContent(indexingJob.myProject, fileContent))
.expireWith(indexingJob.myProject)
.wrapProgress(indexingJob.myIndicator)
.executeSynchronously();
indexingJob.myStatistics.addFileStatistics(fileIndexingStatistics, contentLoadingTime, loadingResult.fileLength);
}
indexingJob.oneMoreFileProcessed();
}
catch (ProcessCanceledException e) {
// Push back the file.
indexingJob.myQueueOfFiles.add(file);
throw e;
}
catch (Throwable e) {
indexingJob.oneMoreFileProcessed();
FileBasedIndexImpl.LOG.error("Error while indexing " + file.getPresentableUrl() + "\n" +
"To reindex this file IDEA has to be restarted", e);
}
finally {
signalThatFileIsUnloaded(loadingResult.fileLength);
}
}
@Nullable
private IndexUpdateRunner.ContentLoadingResult loadNextContent(@NotNull IndexingJob indexingJob,
@NotNull ProgressIndicator indicator) throws FailedToLoadContentException,
TooLargeContentException,
ProcessCanceledException {
VirtualFile file = indexingJob.myQueueOfFiles.poll();
if (file == null) {
return null;
}
if (myFileBasedIndex.isTooLarge(file)) {
throw new TooLargeContentException(file);
}
try {
long fileLength = file.getLength();
waitForFreeMemoryToLoadFileContent(indicator, fileLength);
CachedFileContent fileContent = indexingJob.myContentLoader.loadContent(file);
return new ContentLoadingResult(fileContent, fileLength);
}
catch (ProcessCanceledException e) {
indexingJob.myQueueOfFiles.add(file);
throw e;
}
}
private static class ContentLoadingResult {
final @NotNull CachedFileContent cachedFileContent;
final long fileLength;
private ContentLoadingResult(@NotNull CachedFileContent cachedFileContent, long fileLength) {
this.cachedFileContent = cachedFileContent;
this.fileLength = fileLength;
}
}
private static void waitForFreeMemoryToLoadFileContent(@NotNull ProgressIndicator indicator, long fileLength) {
ourLoadedBytesLimitLock.lock();
try {
while (ourTotalBytesLoadedIntoMemory >= SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY) {
indicator.checkCanceled();
try {
ourLoadedBytesAreReleasedCondition.await(100, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
throw new ProcessCanceledException(e);
}
}
ourTotalBytesLoadedIntoMemory += fileLength;
}
finally {
ourLoadedBytesLimitLock.unlock();
}
}
private static void signalThatFileIsUnloaded(long fileLength) {
ourLoadedBytesLimitLock.lock();
try {
assert ourTotalBytesLoadedIntoMemory >= fileLength;
ourTotalBytesLoadedIntoMemory -= fileLength;
if (ourTotalBytesLoadedIntoMemory < SOFT_MAX_TOTAL_BYTES_LOADED_INTO_MEMORY) {
ourLoadedBytesAreReleasedCondition.signalAll();
}
}
finally {
ourLoadedBytesLimitLock.unlock();
}
}
private static void logFailedToLoadContentException(@NotNull FailedToLoadContentException e) {
Throwable cause = e.getCause();
VirtualFile file = e.getFile();
String fileUrl = "File: " + file.getUrl();
if (cause instanceof FileNotFoundException) {
// It is possible to not observe file system change until refresh finish, we handle missed file properly anyway.
FileBasedIndexImpl.LOG.debug(fileUrl, e);
}
else if (cause instanceof IndexOutOfBoundsException || cause instanceof InvalidVirtualFileAccessException) {
FileBasedIndexImpl.LOG.info(fileUrl, e);
}
else {
FileBasedIndexImpl.LOG.error(fileUrl, e);
}
}
@NotNull
public static String getPresentableLocationBeingIndexed(@NotNull Project project, @NotNull VirtualFile file) {
VirtualFile actualFile = file;
if (actualFile.getFileSystem() instanceof ArchiveFileSystem) {
actualFile = VfsUtil.getLocalFile(actualFile);
}
return FileUtil.toSystemDependentName(getProjectRelativeOrAbsolutePath(project, actualFile));
}
@NotNull
private static String getProjectRelativeOrAbsolutePath(@NotNull Project project, @NotNull VirtualFile file) {
String projectBase = project.getBasePath();
if (StringUtil.isNotEmpty(projectBase)) {
String filePath = file.getPath();
if (FileUtil.isAncestor(projectBase, filePath, true)) {
String projectDirName = PathUtil.getFileName(projectBase);
String relativePath = FileUtil.getRelativePath(projectBase, filePath, '/');
if (StringUtil.isNotEmpty(projectDirName) && StringUtil.isNotEmpty(relativePath)) {
return projectDirName + "/" + relativePath;
}
}
}
return file.getPath();
}
private static class IndexingJob {
final Project myProject;
final CachedFileContentLoader myContentLoader;
final BlockingQueue<VirtualFile> myQueueOfFiles;
final ProgressIndicator myIndicator;
final int myTotalFiles;
final AtomicBoolean myNoMoreFilesInQueue = new AtomicBoolean();
final CountDownLatch myAllFilesAreProcessedLatch;
final IndexingJobStatistics myStatistics = new IndexingJobStatistics();
final AtomicReference<Throwable> myError = new AtomicReference<>();
IndexingJob(@NotNull Project project,
@NotNull ProgressIndicator indicator,
@NotNull CachedFileContentLoader contentLoader,
@NotNull Collection<VirtualFile> files) {
myProject = project;
myIndicator = indicator;
myTotalFiles = files.size();
myContentLoader = contentLoader;
myQueueOfFiles = new ArrayBlockingQueue<>(files.size(), false, files);
myAllFilesAreProcessedLatch = new CountDownLatch(files.size());
}
public void oneMoreFileProcessed() {
myAllFilesAreProcessedLatch.countDown();
double newFraction = 1.0 - myAllFilesAreProcessedLatch.getCount() / (double) myTotalFiles;
try {
myIndicator.setFraction(newFraction);
}
catch (Exception ignored) {
//Unexpected here. A misbehaved progress indicator must not break our code flow.
}
}
boolean areAllFilesProcessed() {
return myAllFilesAreProcessedLatch.getCount() == 0;
}
public void setLocationBeingIndexed(@NotNull VirtualFile virtualFile) {
String presentableLocation = getPresentableLocationBeingIndexed(myProject, virtualFile);
if (myIndicator instanceof SubTaskProgressIndicator) {
myIndicator.setText(presentableLocation);
}
else {
myIndicator.setText2(presentableLocation);
}
}
}
}
|
package com.intellij.ide.plugins;
import com.google.gson.stream.JsonToken;
import com.intellij.icons.AllIcons;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.DataManager;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.newui.*;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.idea.IdeaApplication;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.updateSettings.impl.PluginDownloader;
import com.intellij.openapi.updateSettings.impl.UpdateChecker;
import com.intellij.openapi.updateSettings.impl.UpdateSettings;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.components.JBOptionButton;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextField;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.ui.components.labels.LinkListener;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.HttpRequests;
import com.intellij.util.io.URLUtil;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.ui.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.JsonReaderEx;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
/**
* @author Alexander Lobas
*/
public class PluginManagerConfigurableNew
implements SearchableConfigurable, Configurable.NoScroll, Configurable.NoMargin, Configurable.TopComponentProvider {
public static final String ID = "preferences.pluginManager";
private static final String SELECTION_TAB_KEY = "PluginConfigurable.selectionTab";
private static final int TRENDING_TAB = 0;
private static final int INSTALLED_TAB = 1;
private static final int UPDATES_TAB = 2;
private static final int TRENDING_SEARCH_TAB = 3;
private static final int INSTALLED_SEARCH_TAB = 4;
private static final int UPDATES_SEARCH_TAB = 5;
private static final int ITEMS_PER_GROUP = 9;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMM dd, yyyy");
private static final DecimalFormat K_FORMAT = new DecimalFormat("
private static final DecimalFormat M_FORMAT = new DecimalFormat("
@SuppressWarnings("UseJBColor")
public static final Color MAIN_BG_COLOR = new JBColor(() -> JBColor.isBright() ? UIUtil.getListBackground() : new Color(0x313335));
private final TagBuilder myTagBuilder;
private LinkListener<IdeaPluginDescriptor> myNameListener;
private LinkListener<String> mySearchListener;
private CardLayoutPanel<Object, Object, JComponent> myCardPanel;
private TabHeaderComponent myTabHeaderComponent;
private CountTabName myUpdatesTabName;
private TopComponentController myTopController;
private final PluginSearchTextField mySearchTextField;
private final Alarm mySearchUpdateAlarm = new Alarm();
private PluginsGroupComponent myInstalledPanel;
private PluginsGroupComponent myUpdatesPanel;
private SearchResultPanel myTrendingSearchPanel;
private SearchResultPanel myInstalledSearchPanel;
private SearchResultPanel myUpdatesSearchPanel;
private SearchResultPanel myCurrentSearchPanel;
private final MyPluginModel myPluginsModel = new MyPluginModel();
private Runnable myShutdownCallback;
private List<IdeaPluginDescriptor> myAllRepositoriesList;
private Map<String, IdeaPluginDescriptor> myAllRepositoriesMap;
private Map<String, List<IdeaPluginDescriptor>> myCustomRepositoriesMap;
private final Object myRepositoriesLock = new Object();
private List<String> myAllTagSorted;
public PluginManagerConfigurableNew() {
myTagBuilder = new TagBuilder() {
@NotNull
@Override
public TagComponent createTagComponent(@NotNull String tag) {
Color color;
String tooltip = null;
if ("EAP".equals(tag)) {
color = new JBColor(0xF2D2CF, 0xF2D2CF);
tooltip = "The EAP version does not guarantee the stability\nand availability of the plugin.";
}
else {
color = new JBColor(0xEAEAEC, 0x4D4D4D);
}
return installTiny(new TagComponent(tag, tooltip, color));
}
};
mySearchTextField = new PluginSearchTextField() {
@Override
protected boolean preprocessEventForTextField(KeyEvent event) {
int keyCode = event.getKeyCode();
int id = event.getID();
if (keyCode == KeyEvent.VK_ENTER || event.getKeyChar() == '\n') {
if (id == KeyEvent.KEY_PRESSED &&
(myCurrentSearchPanel.controller == null || !myCurrentSearchPanel.controller.handleEnter(event))) {
String text = mySearchTextField.getText();
if (!text.isEmpty()) {
if (myCurrentSearchPanel.controller != null) {
myCurrentSearchPanel.controller.hidePopup();
}
showSearchPanel(text);
}
}
return true;
}
if ((keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_UP) && id == KeyEvent.KEY_PRESSED &&
myCurrentSearchPanel.controller != null && myCurrentSearchPanel.controller.handleUpDown(event)) {
return true;
}
return super.preprocessEventForTextField(event);
}
@Override
protected boolean toClearTextOnEscape() {
new AnAction() {
{
setEnabledInModalContext(true);
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(!getText().isEmpty());
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (myCurrentSearchPanel.controller != null && myCurrentSearchPanel.controller.isPopupShow()) {
myCurrentSearchPanel.controller.hidePopup();
}
else {
setText("");
}
}
}.registerCustomShortcutSet(CommonShortcuts.ESCAPE, this);
return false;
}
@Override
protected void onFieldCleared() {
hideSearchPanel();
}
};
mySearchTextField.setBorder(JBUI.Borders.customLine(new JBColor(0xC5C5C5, 0x515151)));
JBTextField editor = mySearchTextField.getTextEditor();
editor.putClientProperty("JTextField.Search.Gap", JBUI.scale(-24));
editor.putClientProperty("JTextField.Search.GapEmptyText", JBUI.scale(-1));
editor.putClientProperty("StatusVisibleFunction", (BooleanFunction<JBTextField>)field -> field.getText().isEmpty());
editor.setBorder(JBUI.Borders.empty(0, 25));
editor.setOpaque(true);
editor.setBackground(MAIN_BG_COLOR);
}
@NotNull
@Override
public String getId() {
return ID;
}
@Nls
@Override
public String getDisplayName() {
return IdeBundle.message("title.plugins");
}
@Override
public JComponent getPreferredFocusedComponent() {
return mySearchTextField.getTextEditor();
}
@Nullable
@Override
public JComponent createComponent() {
JPanel panel = new JPanel(new BorderLayout());
panel.setMinimumSize(new JBDimension(580, 380));
DefaultActionGroup actions = new DefaultActionGroup();
actions.add(new DumbAwareAction("Manage Plugin Repositories...") {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (ShowSettingsUtil.getInstance().editConfigurable(panel, new PluginHostsConfigurable())) {
// TODO: Auto-generated method stub
}
}
});
actions.add(new DumbAwareAction(IdeBundle.message("button.http.proxy.settings")) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
if (HttpConfigurable.editConfigurable(panel)) {
// TODO: Auto-generated method stub
}
}
});
actions.addSeparator();
actions.add(new DumbAwareAction("Install Plugin from Disk...") {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
InstalledPluginsManagerMain.chooseAndInstall(myPluginsModel, pair -> myPluginsModel.appendOrUpdateDescriptor(pair.second), panel);
}
});
panel.add(mySearchTextField, BorderLayout.NORTH);
myNameListener = (label, descriptor) -> {
int detailBackTabIndex = -1;
if (label == null) {
if (myPluginsModel.detailPanel != null) {
detailBackTabIndex = myPluginsModel.detailPanel.backTabIndex;
}
removeDetailsPanel();
}
assert myPluginsModel.detailPanel == null;
JButton backButton = new JButton("Plugins");
configureBackButton(backButton);
int currentTab = detailBackTabIndex == -1 ? myTabHeaderComponent.getSelectionTab() : detailBackTabIndex;
backButton.addActionListener(event -> {
removeDetailsPanel();
myCardPanel.select(myCurrentSearchPanel.isEmpty() ? currentTab : myCurrentSearchPanel.tabIndex, true);
storeSelectionTab(currentTab);
myTabHeaderComponent.setSelection(currentTab);
});
myCardPanel.select(Pair.create(descriptor, label != null && currentTab == UPDATES_TAB), true);
myPluginsModel.detailPanel.backTabIndex = currentTab;
myTopController.setLeftComponent(backButton);
myTabHeaderComponent.clearSelection();
};
mySearchListener = (_0, query) -> {
removeDetailsPanel();
mySearchTextField.setTextIgnoreEvents(query);
IdeFocusManager.getGlobalInstance()
.doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(mySearchTextField, true));
showSearchPanel(query);
};
mySearchTextField.getTextEditor().addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if (myCurrentSearchPanel.controller == null) {
return;
}
if (StringUtil.isEmptyOrSpaces(mySearchTextField.getText())) {
myCurrentSearchPanel.controller.showAttributesPopup(null);
}
else {
myCurrentSearchPanel.controller.handleShowPopup();
}
}
@Override
public void focusLost(FocusEvent e) {
if (myCurrentSearchPanel.controller != null) {
myCurrentSearchPanel.controller.hidePopup();
}
}
});
mySearchTextField.getTextEditor().getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
if (!mySearchTextField.isSkipDocumentEvents()) {
mySearchUpdateAlarm.cancelAllRequests();
mySearchUpdateAlarm.addRequest(this::searchOnTheFly, 100, ModalityState.stateForComponent(mySearchTextField));
}
}
private void searchOnTheFly() {
String text = mySearchTextField.getText();
if (StringUtil.isEmptyOrSpaces(text)) {
hideSearchPanel();
}
else if (myCurrentSearchPanel.controller == null) {
showSearchPanel(text);
}
else {
myCurrentSearchPanel.controller.handleShowPopup();
}
}
});
myCardPanel = new CardLayoutPanel<Object, Object, JComponent>() {
@Override
public ActionCallback select(Object key, boolean now) {
ActionCallback callback = super.select(key, now);
callback.doWhenDone(() -> {
panel.doLayout();
panel.revalidate();
panel.repaint();
});
return callback;
}
@Override
protected Object prepare(Object key) {
return key;
}
@Override
protected JComponent create(Object key) {
if (key instanceof Integer) {
Integer index = (Integer)key;
if (index == TRENDING_TAB) {
return createTrendingPanel();
}
if (index == INSTALLED_TAB) {
return createInstalledPanel();
}
if (index == UPDATES_TAB) {
return createUpdatesPanel();
}
if (index == TRENDING_SEARCH_TAB) {
return myTrendingSearchPanel.createScrollPane();
}
if (index == INSTALLED_SEARCH_TAB) {
return myInstalledSearchPanel.createScrollPane();
}
if (index == UPDATES_SEARCH_TAB) {
return myUpdatesSearchPanel.createScrollPane();
}
}
//noinspection ConstantConditions,unchecked
return createDetailsPanel((Pair<IdeaPluginDescriptor, Boolean>)key);
}
};
panel.add(myCardPanel);
myTabHeaderComponent = new TabHeaderComponent(actions, index -> {
removeDetailsPanel();
myCardPanel.select(index, true);
storeSelectionTab(index);
updateSearchForSelectedTab(index);
if (!myCurrentSearchPanel.isEmpty()) {
myCardPanel.select(myCurrentSearchPanel.tabIndex, true);
}
});
myTabHeaderComponent.addTab("Marketplace");
myTabHeaderComponent.addTab("Installed");
myTabHeaderComponent.addTab(myUpdatesTabName = new CountTabName(myTabHeaderComponent, "Updates"));
createSearchPanels();
int selectionTab = getStoredSelectionTab();
myTabHeaderComponent.setSelection(selectionTab);
myCardPanel.select(selectionTab, true);
updateSearchForSelectedTab(selectionTab);
return panel;
}
@Nullable
@Override
public Runnable enableSearch(String option) {
if (StringUtil.isEmpty(option) && myCurrentSearchPanel.isEmpty()) {
return null;
}
return () -> {
hideSearchPanel();
if (myTabHeaderComponent.getSelectionTab() != INSTALLED_TAB) {
myTabHeaderComponent.setSelectionWithEvents(INSTALLED_TAB);
}
mySearchTextField.setTextIgnoreEvents(option);
if (!StringUtil.isEmpty(option)) {
showSearchPanel(option);
}
};
}
private void updateSearchForSelectedTab(int index) {
String text;
String historyPropertyName;
SearchResultPanel searchPanel;
if (index == TRENDING_TAB) {
text = "Search plugins in marketplace";
if (!UpdateSettings.getInstance().getPluginHosts().isEmpty()) {
text += " and custom repositories";
}
searchPanel = myTrendingSearchPanel;
historyPropertyName = "TrendingPluginsSearchHistory";
}
else if (index == INSTALLED_TAB) {
text = "Search installed plugins";
searchPanel = myInstalledSearchPanel;
historyPropertyName = "InstalledPluginsSearchHistory";
}
else {
text = "Search available updates";
searchPanel = myUpdatesSearchPanel;
historyPropertyName = "UpdatePluginsSearchHistory";
}
StatusText emptyText = mySearchTextField.getTextEditor().getEmptyText();
emptyText.clear();
emptyText.appendText(text, new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, CellPluginComponent.GRAY_COLOR));
myCurrentSearchPanel = searchPanel;
mySearchTextField.addCurrentTextToHistory();
mySearchTextField.setHistoryPropertyName(historyPropertyName);
mySearchTextField.setTextIgnoreEvents(searchPanel.getQuery());
}
private void showSearchPanel(@NotNull String query) {
if (myCurrentSearchPanel.isEmpty()) {
myCardPanel.select(myCurrentSearchPanel.tabIndex, true);
}
myCurrentSearchPanel.setQuery(query);
}
private void hideSearchPanel() {
if (!myCurrentSearchPanel.isEmpty()) {
myCardPanel.select(myCurrentSearchPanel.backTabIndex, true);
myCurrentSearchPanel.setQuery("");
}
if (myCurrentSearchPanel.controller != null) {
myCurrentSearchPanel.controller.hidePopup();
}
}
private void removeDetailsPanel() {
if (myPluginsModel.detailPanel != null) {
mySearchTextField.setVisible(true);
myPluginsModel.detailPanel.close();
myPluginsModel.detailPanel = null;
myTopController.setLeftComponent(null);
myCardPanel.remove(myCardPanel.getComponentCount() - 1);
}
}
private static int getStoredSelectionTab() {
return PropertiesComponent.getInstance().getInt(SELECTION_TAB_KEY, TRENDING_TAB);
}
private static void storeSelectionTab(int value) {
PropertiesComponent.getInstance().setValue(SELECTION_TAB_KEY, value, TRENDING_TAB);
}
@Override
public void disposeUIResources() {
myPluginsModel.toBackground();
Disposer.dispose(mySearchUpdateAlarm);
myTrendingSearchPanel.dispose();
if (myShutdownCallback != null) {
myShutdownCallback.run();
myShutdownCallback = null;
}
}
@Override
public void apply() throws ConfigurationException {
Map<PluginId, Set<PluginId>> dependencies = new HashMap<>(myPluginsModel.getDependentToRequiredListMap());
for (Iterator<Entry<PluginId, Set<PluginId>>> I = dependencies.entrySet().iterator(); I.hasNext(); ) {
Entry<PluginId, Set<PluginId>> entry = I.next();
boolean hasNonModuleDeps = false;
for (PluginId pluginId : entry.getValue()) {
if (!PluginManagerCore.isModuleDependency(pluginId)) {
hasNonModuleDeps = true;
break;
}
}
if (!hasNonModuleDeps) {
I.remove();
}
}
if (!dependencies.isEmpty()) {
throw new ConfigurationException("<html><body style=\"padding: 5px;\">Unable to apply changes: plugin" +
(dependencies.size() == 1 ? " " : "s ") +
StringUtil.join(dependencies.keySet(), pluginId -> {
IdeaPluginDescriptor descriptor = PluginManager.getPlugin(pluginId);
return "\"" + (descriptor == null ? pluginId.getIdString() : descriptor.getName()) + "\"";
}, ", ") +
" won't be able to load.</body></html>");
}
int rowCount = myPluginsModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
IdeaPluginDescriptor descriptor = myPluginsModel.getObjectAt(i);
descriptor.setEnabled(myPluginsModel.isEnabled(descriptor.getPluginId()));
}
List<String> disableIds = new ArrayList<>();
for (Entry<PluginId, Boolean> entry : myPluginsModel.getEnabledMap().entrySet()) {
Boolean enabled = entry.getValue();
if (enabled != null && !enabled) {
disableIds.add(entry.getKey().getIdString());
}
}
try {
PluginManagerCore.saveDisabledPlugins(disableIds, false);
}
catch (IOException e) {
PluginManagerMain.LOG.error(e);
}
if (myShutdownCallback == null && myPluginsModel.createShutdownCallback) {
myShutdownCallback = () -> ApplicationManager.getApplication().invokeLater(
() -> PluginManagerConfigurable.shutdownOrRestartApp(IdeBundle.message("update.notifications.title")), ModalityState.any());
}
}
@Override
public boolean isModified() {
if (myPluginsModel.needRestart) {
return true;
}
List<String> disabledPlugins = PluginManagerCore.getDisabledPlugins();
int rowCount = myPluginsModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
IdeaPluginDescriptor descriptor = myPluginsModel.getObjectAt(i);
PluginId pluginId = descriptor.getPluginId();
boolean enabledInTable = myPluginsModel.isEnabled(pluginId);
if (descriptor.isEnabled() != enabledInTable) {
if (enabledInTable && !disabledPlugins.contains(pluginId.getIdString())) {
continue; // was disabled automatically on startup
}
return true;
}
}
for (Entry<PluginId, Boolean> entry : myPluginsModel.getEnabledMap().entrySet()) {
Boolean enabled = entry.getValue();
if (enabled != null && !enabled && !disabledPlugins.contains(entry.getKey().getIdString())) {
return true;
}
}
return false;
}
@NotNull
@Override
public Component getCenterComponent(@NotNull TopComponentController controller) {
myTopController = controller;
myPluginsModel.setTopController(controller);
return myTabHeaderComponent;
}
@NotNull
private JComponent createTrendingPanel() {
PluginsGroupComponentWithProgress panel =
new PluginsGroupComponentWithProgress(new PluginsGridLayout(), EventHandler.EMPTY, myNameListener, mySearchListener,
descriptor -> new GridCellPluginComponent(myPluginsModel, descriptor, myTagBuilder));
panel.getEmptyText().setText("Marketplace plugins are not loaded.")
.appendSecondaryText("Check the internet connection.", StatusText.DEFAULT_ATTRIBUTES, null);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
List<PluginsGroup> groups = new ArrayList<>();
try {
Pair<Map<String, IdeaPluginDescriptor>, Map<String, List<IdeaPluginDescriptor>>> pair = loadPluginRepositories();
Map<String, IdeaPluginDescriptor> allRepositoriesMap = pair.first;
Map<String, List<IdeaPluginDescriptor>> customRepositoriesMap = pair.second;
Set<String> excludeDescriptors = new HashSet<>();
addGroup(groups, excludeDescriptors, allRepositoriesMap, "Featured", "is_featured_search=true", "sortBy:featured");
addGroup(groups, excludeDescriptors, allRepositoriesMap, "New and Updated", "orderBy=update+date", "sortBy:updated");
addGroup(groups, excludeDescriptors, allRepositoriesMap, "Top Downloads", "orderBy=downloads", "sortBy:downloads");
addGroup(groups, excludeDescriptors, allRepositoriesMap, "Top Rated", "orderBy=rating", "sortBy:rating");
for (String host : UpdateSettings.getInstance().getPluginHosts()) {
List<IdeaPluginDescriptor> allDescriptors = customRepositoriesMap.get(host);
if (allDescriptors != null) {
addGroup(groups, "Repository: " + host, "repository:\"" + host + "\"", descriptors -> {
descriptors.addAll(allDescriptors.subList(0, Math.min(ITEMS_PER_GROUP, allDescriptors.size())));
PluginsGroup.sortByName(descriptors);
});
}
}
}
catch (IOException e) {
PluginManagerMain.LOG.info(e);
}
finally {
ApplicationManager.getApplication().invokeLater(() -> {
panel.stopLoading();
panel.dispose();
for (PluginsGroup group : groups) {
panel.addGroup(group);
}
panel.doLayout();
panel.initialSelection();
}, ModalityState.any());
}
});
return createScrollPane(panel, false);
}
@NotNull
private JComponent createInstalledPanel() {
PluginsGroupComponent panel =
new PluginsGroupComponent(new PluginsListLayout(), new MultiSelectionEventHandler(), myNameListener, mySearchListener,
descriptor -> new ListPluginComponent(myPluginsModel, descriptor, false));
registerCopyProvider(panel);
PluginsGroup installing = new PluginsGroup("Installing");
installing.descriptors.addAll(MyPluginModel.getInstallingPlugins());
if (!installing.descriptors.isEmpty()) {
installing.sortByName();
installing.titleWithCount();
panel.addGroup(installing);
}
PluginsGroup downloaded = new PluginsGroup("Downloaded");
PluginsGroup bundled = new PluginsGroup("Bundled");
downloaded.descriptors.addAll(InstalledPluginsState.getInstance().getInstalledPlugins());
ApplicationInfoEx appInfo = ApplicationInfoEx.getInstanceEx();
int bundledEnabled = 0;
int downloadedEnabled = 0;
for (IdeaPluginDescriptor descriptor : PluginManagerCore.getPlugins()) {
if (!appInfo.isEssentialPlugin(descriptor.getPluginId().getIdString())) {
if (descriptor.isBundled()) {
bundled.descriptors.add(descriptor);
if (descriptor.isEnabled()) {
bundledEnabled++;
}
}
else {
downloaded.descriptors.add(descriptor);
if (descriptor.isEnabled()) {
downloadedEnabled++;
}
}
}
}
if (!downloaded.descriptors.isEmpty()) {
downloaded.sortByName();
downloaded.titleWithCount(downloadedEnabled);
panel.addGroup(downloaded);
myPluginsModel.addEnabledGroup(downloaded);
}
myPluginsModel.setDownloadedGroup(panel, downloaded, installing);
bundled.sortByName();
bundled.titleWithCount(bundledEnabled);
panel.addGroup(bundled);
myPluginsModel.addEnabledGroup(bundled);
myInstalledPanel = panel;
return createScrollPane(panel, true);
}
@NotNull
private JComponent createUpdatesPanel() {
PluginsGroupComponentWithProgress panel =
new PluginsGroupComponentWithProgress(new PluginsListLayout(), new MultiSelectionEventHandler(), myNameListener, mySearchListener,
descriptor -> new ListPluginComponent(myPluginsModel, descriptor, true));
panel.getEmptyText().setText("No updates available.");
registerCopyProvider(panel);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
Collection<PluginDownloader> updates = UpdateChecker.getPluginUpdates();
ApplicationManager.getApplication().invokeLater(() -> {
panel.stopLoading();
panel.dispose();
if (ContainerUtil.isEmpty(updates)) {
myUpdatesTabName.setCount(0);
}
else {
PluginsGroup group = new PluginsGroup("Available Updates") {
@Override
public void titleWithCount() {
int count = 0;
for (CellPluginComponent component : ui.plugins) {
if (((ListPluginComponent)component).myUpdateButton != null) {
count++;
}
}
title = myTitlePrefix + " (" + count + ")";
updateTitle();
rightAction.setVisible(count > 0);
myUpdatesTabName.setCount(count);
}
};
group.rightAction = new LinkLabel<>("Update All", null);
group.rightAction.setListener(new LinkListener<Object>() {
@Override
public void linkSelected(LinkLabel aSource, Object aLinkData) {
for (CellPluginComponent component : group.ui.plugins) {
((ListPluginComponent)component).updatePlugin();
}
}
}, null);
for (PluginDownloader toUpdateDownloader : updates) {
group.descriptors.add(toUpdateDownloader.getDescriptor());
}
group.sortByName();
panel.addGroup(group);
group.titleWithCount();
myPluginsModel.setUpdateGroup(group);
}
panel.doLayout();
panel.initialSelection();
}, ModalityState.any());
});
myUpdatesPanel = panel;
return createScrollPane(panel, false);
}
private void createSearchPanels() {
SearchPopupController trendingController = new SearchPopupController(mySearchTextField) {
@NotNull
@Override
protected List<String> getAttributes() {
List<String> attributes = new ArrayList<>();
attributes.add("tag:");
if (!UpdateSettings.getInstance().getPluginHosts().isEmpty()) {
attributes.add("repository:");
}
attributes.add("sortBy:");
return attributes;
}
@Nullable
@Override
protected List<String> getValues(@NotNull String attribute) {
switch (attribute) {
case "tag:":
if (ContainerUtil.isEmpty(myAllTagSorted)) {
Set<String> allTags = new HashSet<>();
for (IdeaPluginDescriptor descriptor : getPluginRepositories()) {
if (descriptor instanceof PluginNode) {
List<String> tags = ((PluginNode)descriptor).getTags();
if (!ContainerUtil.isEmpty(tags)) {
allTags.addAll(tags);
}
}
}
myAllTagSorted = ContainerUtil.sorted(allTags, String::compareToIgnoreCase);
}
return myAllTagSorted;
case "repository:":
return UpdateSettings.getInstance().getPluginHosts();
case "sortBy:":
return ContainerUtil.list("downloads", "name", "rating", "featured", "updated");
}
return null;
}
@Override
protected void showPopupForQuery() {
String query = mySearchTextField.getText();
if (mySearchTextField.getTextEditor().getCaretPosition() < query.length()) {
hidePopup();
return;
}
List<IdeaPluginDescriptor> result = loadSuggestPlugins(query);
if (result.isEmpty()) {
hidePopup();
return;
}
boolean async = myPopup != null;
boolean update = myPopup != null && myPopup.type == SearchPopup.Type.SearchQuery && myPopup.isValid();
if (update) {
myPopup.model.replaceAll(result);
}
else {
hidePopup();
createPopup(new CollectionListModel<>(result), SearchPopup.Type.SearchQuery);
}
myPopup.data = query;
if (update) {
myPopup.update();
return;
}
Consumer<IdeaPluginDescriptor> callback = descriptor -> {
hidePopup();
myNameListener.linkSelected(null, descriptor);
};
ColoredListCellRenderer renderer = new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(@NotNull JList list, Object value, int index, boolean selected, boolean hasFocus) {
IdeaPluginDescriptor descriptor = (IdeaPluginDescriptor)value;
String splitter = (String)myPopup.data;
for (String partName : SearchQueryParser.split(descriptor.getName(), splitter)) {
append(partName, partName.equalsIgnoreCase(splitter)
? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES
: SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
if (isJBPlugin(descriptor)) {
append(" by JetBrains", SimpleTextAttributes.GRAY_ATTRIBUTES);
}
else {
String vendor = descriptor.getVendor();
if (!StringUtil.isEmptyOrSpaces(vendor)) {
append(" by " + StringUtil.shortenPathWithEllipsis(vendor, 50), SimpleTextAttributes.GRAY_ATTRIBUTES);
}
}
}
};
myPopup.createAndShow(callback, renderer, async);
}
@NotNull
private List<IdeaPluginDescriptor> loadSuggestPlugins(@NotNull String query) {
Set<IdeaPluginDescriptor> result = new LinkedHashSet<>();
try {
ApplicationManager.getApplication().executeOnPooledThread(() -> {
try {
Pair<Map<String, IdeaPluginDescriptor>, Map<String, List<IdeaPluginDescriptor>>> p = loadPluginRepositories();
Map<String, IdeaPluginDescriptor> allRepositoriesMap = p.first;
Map<String, List<IdeaPluginDescriptor>> customRepositoriesMap = p.second;
if (query.length() > 1) {
try {
for (String pluginId : requestToPluginRepository(createSearchSuggestUrl(query), forceHttps())) {
IdeaPluginDescriptor descriptor = allRepositoriesMap.get(pluginId);
if (descriptor != null) {
result.add(descriptor);
}
}
}
catch (IOException ignore) {
}
}
for (List<IdeaPluginDescriptor> descriptors : customRepositoriesMap.values()) {
for (IdeaPluginDescriptor descriptor : descriptors) {
if (StringUtil.containsIgnoreCase(descriptor.getName(), query)) {
result.add(descriptor);
}
}
}
}
catch (IOException e) {
PluginManagerMain.LOG.info(e);
}
}).get(300, TimeUnit.MILLISECONDS);
}
catch (Exception ignore) {
}
return ContainerUtil.newArrayList(result);
}
};
myTrendingSearchPanel =
new SearchResultPanel(trendingController, createSearchPanelComponentWithProgress(), TRENDING_SEARCH_TAB, TRENDING_TAB) {
@Override
protected void handleQuery(@NotNull String query, @NotNull PluginsGroup result) {
try {
Pair<Map<String, IdeaPluginDescriptor>, Map<String, List<IdeaPluginDescriptor>>> p = loadPluginRepositories();
Map<String, IdeaPluginDescriptor> allRepositoriesMap = p.first;
Map<String, List<IdeaPluginDescriptor>> customRepositoriesMap = p.second;
SearchQueryParser.Trending parser = new SearchQueryParser.Trending(query);
if (!parser.repositories.isEmpty()) {
for (String repository : parser.repositories) {
List<IdeaPluginDescriptor> descriptors = customRepositoriesMap.get(repository);
if (descriptors == null) {
continue;
}
if (parser.searchQuery == null) {
result.descriptors.addAll(descriptors);
}
else {
for (IdeaPluginDescriptor descriptor : descriptors) {
if (StringUtil.containsIgnoreCase(descriptor.getName(), parser.searchQuery)) {
result.descriptors.add(descriptor);
}
}
}
}
result.sortByName();
return;
}
for (String pluginId : requestToPluginRepository(createSearchUrl(parser.getUrlQuery(), 10000), forceHttps())) {
IdeaPluginDescriptor descriptor = allRepositoriesMap.get(pluginId);
if (descriptor != null) {
result.descriptors.add(descriptor);
}
}
if (parser.searchQuery != null) {
for (List<IdeaPluginDescriptor> descriptors : customRepositoriesMap.values()) {
for (IdeaPluginDescriptor descriptor : descriptors) {
if (StringUtil.containsIgnoreCase(descriptor.getName(), parser.searchQuery)) {
result.descriptors.add(descriptor);
}
}
}
}
}
catch (IOException e) {
PluginManagerMain.LOG.info(e);
ApplicationManager.getApplication().invokeLater(() -> myPanel.getEmptyText().setText("Search result are not loaded.")
.appendSecondaryText("Check the internet connection.", StatusText.DEFAULT_ATTRIBUTES, null), ModalityState.any());
}
}
};
SearchPopupController installedController = new SearchPopupController(mySearchTextField) {
@NotNull
@Override
protected List<String> getAttributes() {
return ContainerUtil.list("#disabled", "#enabled", "#bundled", "#custom", "#inactive", "#invalid", "#outdated", "#uninstalled");
}
@Nullable
@Override
protected List<String> getValues(@NotNull String attribute) {
return null;
}
@Override
protected void handleAppendToQuery() {
showPopupForQuery();
}
@Override
protected void handleAppendAttributeValue() {
showPopupForQuery();
}
@Override
protected void showPopupForQuery() {
showSearchPanel(mySearchTextField.getText());
}
};
myInstalledSearchPanel =
new SearchResultPanel(installedController, createLocalSearchPanelComponent(false), INSTALLED_SEARCH_TAB, INSTALLED_TAB) {
@Override
protected void handleQuery(@NotNull String query, @NotNull PluginsGroup result) {
InstalledPluginsState state = InstalledPluginsState.getInstance();
SearchQueryParser.Installed parser = new SearchQueryParser.Installed(query);
for (UIPluginGroup uiGroup : myInstalledPanel.getGroups()) {
for (CellPluginComponent plugin : uiGroup.plugins) {
if (parser.attributes) {
if (parser.enabled != null && parser.enabled != myPluginsModel.isEnabled(plugin.myPlugin)) {
continue;
}
if (parser.bundled != null && parser.bundled != plugin.myPlugin.isBundled()) {
continue;
}
if (parser.invalid != null && parser.invalid != myPluginsModel.hasErrors(plugin.myPlugin)) {
continue;
}
if (parser.deleted != null) {
if (plugin.myPlugin instanceof IdeaPluginDescriptorImpl) {
if (parser.deleted != ((IdeaPluginDescriptorImpl)plugin.myPlugin).isDeleted()) {
continue;
}
}
else if (parser.deleted) {
continue;
}
}
PluginId pluginId = plugin.myPlugin.getPluginId();
if (parser.needUpdate != null && parser.needUpdate != state.hasNewerVersion(pluginId)) {
continue;
}
if (parser.needRestart != null) {
if (parser.needRestart != (state.wasInstalled(pluginId) || state.wasUpdated(pluginId))) {
continue;
}
}
}
if (parser.searchQuery != null && !StringUtil.containsIgnoreCase(plugin.myPlugin.getName(), parser.searchQuery)) {
continue;
}
result.descriptors.add(plugin.myPlugin);
}
}
}
};
myUpdatesSearchPanel = new SearchResultPanel(null, createLocalSearchPanelComponent(true), UPDATES_SEARCH_TAB, UPDATES_TAB) {
@Override
protected void handleQuery(@NotNull String query, @NotNull PluginsGroup result) {
for (UIPluginGroup uiGroup : myUpdatesPanel.getGroups()) {
for (CellPluginComponent plugin : uiGroup.plugins) {
if (StringUtil.containsIgnoreCase(plugin.myPlugin.getName(), query)) {
result.descriptors.add(plugin.myPlugin);
}
}
}
}
};
}
@NotNull
private JComponent createDetailsPanel(@NotNull Pair<IdeaPluginDescriptor, Boolean> data) {
myPluginsModel.detailPanel = new DetailsPagePluginComponent(myPluginsModel, myTagBuilder, mySearchListener, data.first, data.second);
mySearchTextField.setVisible(false);
return myPluginsModel.detailPanel;
}
@NotNull
private static JComponent createScrollPane(@NotNull PluginsGroupComponent panel, boolean initSelection) {
JBScrollPane pane = new JBScrollPane(panel);
pane.setBorder(JBUI.Borders.empty());
if (initSelection) {
panel.initialSelection();
}
return pane;
}
private void addGroup(@NotNull List<PluginsGroup> groups,
@NotNull String name,
@NotNull String showAllQuery,
@NotNull ThrowableConsumer<List<IdeaPluginDescriptor>, IOException> consumer) throws IOException {
PluginsGroup group = new PluginsGroup(name);
consumer.consume(group.descriptors);
if (!group.descriptors.isEmpty()) {
//noinspection unchecked
group.rightAction = new LinkLabel("Show All", null, mySearchListener, showAllQuery);
groups.add(group);
}
}
private void addGroup(@NotNull List<PluginsGroup> groups,
@NotNull Set<String> excludeDescriptors,
@NotNull Map<String, IdeaPluginDescriptor> allRepositoriesMap,
@NotNull String name,
@NotNull String query,
@NotNull String showAllQuery) throws IOException {
addGroup(groups, name, showAllQuery, descriptors -> loadPlugins(descriptors, allRepositoriesMap, excludeDescriptors, query));
}
@NotNull
private Pair<Map<String, IdeaPluginDescriptor>, Map<String, List<IdeaPluginDescriptor>>> loadPluginRepositories() throws IOException {
synchronized (myRepositoriesLock) {
if (myAllRepositoriesMap != null) {
return Pair.create(myAllRepositoriesMap, myCustomRepositoriesMap);
}
}
List<IdeaPluginDescriptor> list = new ArrayList<>();
Map<String, IdeaPluginDescriptor> map = new HashMap<>();
Map<String, List<IdeaPluginDescriptor>> custom = new HashMap<>();
IOException exception = null;
for (String host : RepositoryHelper.getPluginHosts()) {
try {
List<IdeaPluginDescriptor> descriptors = RepositoryHelper.loadPlugins(host, null);
if (host != null) {
custom.put(host, descriptors);
}
for (IdeaPluginDescriptor plugin : descriptors) {
String id = plugin.getPluginId().getIdString();
if (!map.containsKey(id)) {
list.add(plugin);
map.put(id, plugin);
}
}
}
catch (IOException e) {
if (host == null) {
exception = e;
}
else {
PluginManagerMain.LOG.info(host, e);
}
}
}
if (exception != null) {
throw exception;
}
ApplicationManager.getApplication().invokeLater(() -> {
InstalledPluginsState state = InstalledPluginsState.getInstance();
for (IdeaPluginDescriptor descriptor : list) {
state.onDescriptorDownload(descriptor);
}
});
synchronized (myRepositoriesLock) {
if (myAllRepositoriesList == null) {
myAllRepositoriesList = list;
myAllRepositoriesMap = map;
myCustomRepositoriesMap = custom;
}
return Pair.create(myAllRepositoriesMap, myCustomRepositoriesMap);
}
}
private static void loadPlugins(@NotNull List<IdeaPluginDescriptor> descriptors,
@NotNull Map<String, IdeaPluginDescriptor> allDescriptors,
@NotNull Set<String> excludeDescriptors,
@NotNull String query) throws IOException {
boolean forceHttps = forceHttps();
Url baseUrl = createSearchUrl(query, ITEMS_PER_GROUP);
Url offsetUrl = baseUrl;
Map<String, String> offsetParameters = new HashMap<>();
int offset = 0;
while (true) {
List<String> pluginIds = requestToPluginRepository(offsetUrl, forceHttps);
if (pluginIds.isEmpty()) {
return;
}
for (String pluginId : pluginIds) {
IdeaPluginDescriptor descriptor = allDescriptors.get(pluginId);
if (descriptor != null && excludeDescriptors.add(pluginId) && PluginManager.getPlugin(descriptor.getPluginId()) == null) {
descriptors.add(descriptor);
if (descriptors.size() == ITEMS_PER_GROUP) {
return;
}
}
}
offset += pluginIds.size();
offsetParameters.put("offset", Integer.toString(offset));
offsetUrl = baseUrl.addParameters(offsetParameters);
}
}
@NotNull
private static List<String> requestToPluginRepository(@NotNull Url url, boolean forceHttps) throws IOException {
List<String> ids = new ArrayList<>();
HttpRequests.request(url).forceHttps(forceHttps).throwStatusCodeException(false).productNameAsUserAgent().connect(request -> {
URLConnection connection = request.getConnection();
if (connection instanceof HttpURLConnection && ((HttpURLConnection)connection).getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
try (JsonReaderEx json = new JsonReaderEx(FileUtil.loadTextAndClose(request.getReader()))) {
if (json.peek() == JsonToken.BEGIN_OBJECT) {
json.beginObject();
json.nextName(); // query
json.nextString(); // query value
json.nextName(); // suggestions
}
json.beginArray();
while (json.hasNext()) {
ids.add(json.nextString());
}
}
return null;
});
return ids;
}
@NotNull
private static Url createSearchUrl(@NotNull String query, int count) {
return Urls.newFromEncoded("http://plugins.jetbrains.com/api/search?" + query +
"&build=" + URLUtil.encodeURIComponent(ApplicationInfoImpl.getShadowInstance().getApiVersion()) +
"&max=" + count);
}
@NotNull
private static Url createSearchSuggestUrl(@NotNull String query) {
return Urls.newFromEncoded("http://plugins.jetbrains.com/api/searchSuggest?term=" +
URLUtil.encodeURIComponent(query) +
"&productCode=" +
URLUtil.encodeURIComponent(ApplicationInfoImpl.getShadowInstance().getBuild().getProductCode()));
}
private static boolean forceHttps() {
return IdeaApplication.isLoaded() && UpdateSettings.getInstance().canUseSecureConnection();
}
@NotNull
private List<IdeaPluginDescriptor> getPluginRepositories() {
synchronized (myRepositoriesLock) {
if (myAllRepositoriesList != null) {
return myAllRepositoriesList;
}
}
try {
List<IdeaPluginDescriptor> list = RepositoryHelper.loadCachedPlugins();
if (list != null) {
return list;
}
}
catch (IOException e) {
PluginManagerMain.LOG.info(e);
}
return Collections.emptyList();
}
@NotNull
public static String getErrorMessage(@NotNull InstalledPluginsTableModel pluginsModel,
@NotNull PluginDescriptor pluginDescriptor,
@NotNull Ref<Boolean> enableAction) {
String message;
Set<PluginId> requiredPlugins = pluginsModel.getRequiredPlugins(pluginDescriptor.getPluginId());
if (ContainerUtil.isEmpty(requiredPlugins)) {
message = "Incompatible with the current " + ApplicationNamesInfo.getInstance().getFullProductName() + " version.";
}
else if (requiredPlugins.contains(PluginId.getId("com.intellij.modules.ultimate"))) {
message = "The plugin requires IntelliJ IDEA Ultimate.";
}
else {
String deps = StringUtil.join(requiredPlugins, id -> {
IdeaPluginDescriptor plugin = PluginManager.getPlugin(id);
if (plugin == null && PluginManagerCore.isModuleDependency(id)) {
for (IdeaPluginDescriptor descriptor : PluginManagerCore.getPlugins()) {
if (descriptor instanceof IdeaPluginDescriptorImpl) {
List<String> modules = ((IdeaPluginDescriptorImpl)descriptor).getModules();
if (modules != null && modules.contains(id.getIdString())) {
plugin = descriptor;
break;
}
}
}
}
return plugin != null ? plugin.getName() : id.getIdString();
}, ", ");
message = IdeBundle.message("new.plugin.manager.incompatible.deps.tooltip", requiredPlugins.size(), deps);
enableAction.set(Boolean.TRUE);
}
return message;
}
@NotNull
public static List<String> getTags(@NotNull IdeaPluginDescriptor plugin) {
List<String> tags = null;
if (plugin instanceof PluginNode) {
tags = ((PluginNode)plugin).getTags();
}
if (ContainerUtil.isEmpty(tags)) {
return Collections.emptyList();
}
int eap = tags.indexOf("EAP");
if (eap > 0) {
tags = new ArrayList<>(tags);
tags.remove(eap);
tags.add(0, "EAP");
}
return tags;
}
@Nullable
public static synchronized String getDownloads(@NotNull IdeaPluginDescriptor plugin) {
String downloads = ((PluginNode)plugin).getDownloads();
if (!StringUtil.isEmptyOrSpaces(downloads)) {
try {
Long value = Long.valueOf(downloads);
if (value > 1000) {
return value < 1000000 ? K_FORMAT.format(value / 1000D) : M_FORMAT.format(value / 1000000D);
}
return value.toString();
}
catch (NumberFormatException ignore) {
}
}
return null;
}
@Nullable
public static synchronized String getLastUpdatedDate(@NotNull IdeaPluginDescriptor plugin) {
long date = ((PluginNode)plugin).getDate();
return date > 0 && date != Long.MAX_VALUE ? DATE_FORMAT.format(new Date(date)) : null;
}
@Nullable
public static String getRating(@NotNull IdeaPluginDescriptor plugin) {
String rating = ((PluginNode)plugin).getRating();
if (rating != null) {
try {
if (Double.valueOf(rating) > 0) {
return StringUtil.trimEnd(rating, ".0");
}
}
catch (NumberFormatException ignore) {
}
}
return null;
}
private static class CountTabName implements Computable<String> {
private final TabHeaderComponent myTabComponent;
private final String myBaseName;
private int myCount = -1;
CountTabName(@NotNull TabHeaderComponent component, @NotNull String baseName) {
myTabComponent = component;
myBaseName = baseName;
}
public void setCount(int count) {
if (myCount != count) {
myCount = count;
myTabComponent.update();
}
}
@Override
public String compute() {
return myCount == -1 ? myBaseName : myBaseName + " (" + myCount + ")";
}
}
private static void registerCopyProvider(@NotNull PluginsGroupComponent component) {
CopyProvider copyProvider = new CopyProvider() {
@Override
public void performCopy(@NotNull DataContext dataContext) {
StringBuilder result = new StringBuilder();
for (CellPluginComponent pluginComponent : component.getSelection()) {
result.append(pluginComponent.myPlugin.getName()).append(" (").append(pluginComponent.myPlugin.getVersion()).append(")\n");
}
CopyPasteManager.getInstance().setContents(new TextTransferable(result.substring(0, result.length() - 1)));
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return !component.getSelection().isEmpty();
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
};
DataManager.registerDataProvider(component, dataId -> PlatformDataKeys.COPY_PROVIDER.is(dataId) ? copyProvider : null);
}
public static int getParentWidth(@NotNull Container parent) {
int width = parent.getWidth();
if (width > 0) {
Container container = parent.getParent();
int parentWidth = container.getWidth();
if (container instanceof JViewport && parentWidth < width) {
width = parentWidth;
}
}
return width;
}
@NotNull
public static <T extends Component> T installTiny(@NotNull T component) {
return SystemInfo.isMac ? RelativeFont.TINY.install(component) : component;
}
public static int offset5() {
return JBUI.scale(5);
}
public static final Color DisabledColor = new JBColor(0xB1B1B1, 0x696969);
private static void configureBackButton(@NotNull JButton button) {
button.setIcon(new Icon() {
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
AllIcons.Actions.Back.paintIcon(c, g, x + JBUI.scale(7), y);
}
@Override
public int getIconWidth() {
return AllIcons.Actions.Back.getIconWidth() + JBUI.scale(7);
}
@Override
public int getIconHeight() {
return AllIcons.Actions.Back.getIconHeight();
}
});
button.setHorizontalAlignment(SwingConstants.LEFT);
Dimension size = button.getPreferredSize();
size.width -= JBUI.scale(15);
button.setPreferredSize(size);
}
public static void setWidth72(@NotNull JButton button) {
int width = JBUI.scale(72);
if (button instanceof JBOptionButton && button.getComponentCount() == 2) {
width += button.getComponent(1).getPreferredSize().width;
}
else {
Border border = button.getBorder();
if (border != null) {
Insets insets = border.getBorderInsets(button);
width += insets.left + insets.right;
}
}
button.setPreferredSize(new Dimension(width, button.getPreferredSize().height));
}
public static boolean isJBPlugin(@NotNull IdeaPluginDescriptor plugin) {
return plugin.isBundled() || PluginManagerMain.isDevelopedByJetBrains(plugin);
}
@Nullable
public static String getShortDescription(@NotNull IdeaPluginDescriptor plugin, boolean shortSize) {
return PluginSiteUtils.preparePluginDescription(plugin.getDescription(), shortSize);
}
@NotNull
private PluginsGroupComponent createLocalSearchPanelComponent(boolean pluginForUpdate) {
PluginsGroupComponent component =
new PluginsGroupComponent(new PluginsListLayout(), new MultiSelectionEventHandler(), myNameListener, mySearchListener,
descriptor -> new ListPluginComponent(myPluginsModel, descriptor, pluginForUpdate));
registerCopyProvider(component);
return component;
}
@NotNull
private PluginsGroupComponent createSearchPanelComponentWithProgress() {
return new PluginsGroupComponentWithProgress(new PluginsGridLayout(), EventHandler.EMPTY, myNameListener, mySearchListener,
descriptor -> new GridCellPluginComponent(myPluginsModel, descriptor, myTagBuilder));
}
}
|
package gov.nih.nci.cabig.caaers.service.migrator.report;
import gov.nih.nci.cabig.caaers.dao.AnatomicSiteDao;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.migrator.Migrator;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class DiseaseHistoryMigrator implements Migrator<ExpeditedAdverseEventReport> {
public AnatomicSiteDao getAnatomicSiteDao() {
return anatomicSiteDao;
}
public void setAnatomicSiteDao(AnatomicSiteDao anatomicSiteDao) {
this.anatomicSiteDao = anatomicSiteDao;
}
private AnatomicSiteDao anatomicSiteDao ;
public void migrate(ExpeditedAdverseEventReport aeReportSrc, ExpeditedAdverseEventReport aeReportDest, DomainObjectImportOutcome<ExpeditedAdverseEventReport> outcome) {
DiseaseHistory srcDisHis = aeReportSrc.getDiseaseHistory();
DiseaseHistory destDisHis = aeReportDest.getDiseaseHistory();
if ( destDisHis == null ) {
destDisHis = new DiseaseHistory();
}
Participant participant = aeReportDest.getParticipant();
StudySite site = null;
if ( aeReportDest.getReportingPeriod() != null && aeReportDest.getReportingPeriod().getAssignment() != null ) {
site = aeReportDest.getReportingPeriod().getAssignment().getStudySite();
}
if ( site == null ) {
outcome.addError("ER-DHM-1", "Study Site is missing in the source");
return;
}
if ( participant == null ) {
outcome.addError("ER-DHM-2", "Participant is missing in the destination");
return;
}
StudyParticipantAssignment assignment = participant.getStudyParticipantAssignment(site);
StudyParticipantDiseaseHistory history = assignment.getDiseaseHistory();
if ( history != null ) {
copyFromStudyParticipantDiseaseHistory(history, destDisHis);
}
// After copying it from the patient make sure we have removed it from the srcDisHis object to remove the duplicates.
removeDuplicateMetaStaticSites(srcDisHis, destDisHis);
copyDiseaseHistory(srcDisHis, destDisHis, outcome);
//copy new ones to the SPA
copyToStudyParticipantDiseaseHistory(destDisHis, history);
}
/**
* Copy Disease History details from Input to the Domain Object.
* @param srcDisHis
* @param destDisHis
*/
private void copyDiseaseHistory(DiseaseHistory srcDisHis, DiseaseHistory destDisHis, DomainObjectImportOutcome<ExpeditedAdverseEventReport> outcome) {
if ( srcDisHis.getMetastaticDiseaseSites().size() > 0) {
List<String> anatomicSites = new ArrayList<String>();
for ( MetastaticDiseaseSite diseaseSite : srcDisHis.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
anatomicSites.add(diseaseSite.getCodedSite().getName());
}
}
String[] anatomicSitesArr = anatomicSites.toArray(new String[anatomicSites.size()]);
List<AnatomicSite> anaSites = anatomicSiteDao.getBySubnames(anatomicSitesArr);
for ( MetastaticDiseaseSite diseaseSite : srcDisHis.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
AnatomicSite result = findAnatomicSiteByName(anaSites, diseaseSite.getCodedSite());
MetastaticDiseaseSite mds = new MetastaticDiseaseSite();
mds.setCodedSite(result);
destDisHis.getMetastaticDiseaseSites().add(mds);
}
}
}
if (StringUtils.isNotEmpty(srcDisHis.getCodedPrimaryDiseaseSite().getName()) ) {
AnatomicSite anatomicSite = srcDisHis.getCodedPrimaryDiseaseSite();
String[] codedPrimaryAnatomicSite = new String[1];
codedPrimaryAnatomicSite[0] = anatomicSite.getName();
List<AnatomicSite> codedPrimaryAnaSites = anatomicSiteDao.getBySubnames(codedPrimaryAnatomicSite);
AnatomicSite result = findAnatomicSiteByName(codedPrimaryAnaSites, anatomicSite);
if ( result != null) {
destDisHis.setCodedPrimaryDiseaseSite(result);
} else {
// Output with Error.
outcome.addError("ER-DHM-2", "Primary Site of Disease is not found " + anatomicSite.getName() );
return;
}
// Copy the other Disease site if provided.
if (StringUtils.isNotBlank(srcDisHis.getOtherPrimaryDiseaseSite()))
destDisHis.setOtherPrimaryDiseaseSite(srcDisHis.getOtherPrimaryDiseaseSite());
}
destDisHis.setDiagnosisDate(srcDisHis.getDiagnosisDate());
if ( destDisHis.getReport().getStudy().hasCtepEsysIdentifier() && StringUtils.isNotEmpty( ((DiseaseTerm)srcDisHis.getAbstractStudyDisease().getTerm()).getTerm()) ) {
List<CtepStudyDisease> ctepStudyDiseases = destDisHis.getReport().getStudy().getActiveCtepStudyDiseases();
boolean studyDiesaseFound = false;
for ( CtepStudyDisease disease : ctepStudyDiseases) {
if ( disease.getTermName().equals(srcDisHis.getAbstractStudyDisease().getTermName())) {
destDisHis.setAbstractStudyDisease(disease);
studyDiesaseFound = true;
break;
}
}
if ( !studyDiesaseFound ) { // If not found throw the error back to user.
outcome.addError("ER-DHM-3", "Primary Disease is not found on the Study " + srcDisHis.getAbstractStudyDisease().getTermName() );
return;
}
} else {
List<MeddraStudyDisease> meddraStudyDiseases = destDisHis.getReport().getStudy().getActiveMeddraStudyDiseases();
boolean studyDiesaseFound = false;
for ( MeddraStudyDisease disease : meddraStudyDiseases) {
if ( disease.getTermName().equals(srcDisHis.getAbstractStudyDisease().getTermName())) {
destDisHis.setAbstractStudyDisease(disease);
studyDiesaseFound = true;
break;
}
}
if ( !studyDiesaseFound ) { // If not found throw the error back to user.
outcome.addError("ER-DHM-3", "Primary Disease is not found on the Study " + srcDisHis.getAbstractStudyDisease().getTermName() );
return;
}
}
// Copy the other Primary disease site.
if (StringUtils.isNotBlank(srcDisHis.getOtherPrimaryDisease()) )
destDisHis.setOtherPrimaryDisease(srcDisHis.getOtherPrimaryDisease());
}
private void removeDuplicateMetaStaticSites(DiseaseHistory srcDisHis, DiseaseHistory destDisHis) {
for (MetastaticDiseaseSite destSite: destDisHis.getMetastaticDiseaseSites()) {
int index = findIndexMetastaticSite(srcDisHis.getMetastaticDiseaseSites(), destSite);
if ( index >= 0 ) srcDisHis.getMetastaticDiseaseSites().remove(index);
}
}
private int findIndexMetastaticSite(List<MetastaticDiseaseSite> srcMetaStaticSites, MetastaticDiseaseSite destSite) {
int index = -1;
for ( MetastaticDiseaseSite site: srcMetaStaticSites ) {
index ++;
if ( site.getCodedSite().getName().equals(destSite.getCodedSite().getName())) { // Found a duplicate.
break;
}
}
return index;
}
private AnatomicSite findAnatomicSiteByName(List<AnatomicSite> anaSites, AnatomicSite site) {
AnatomicSite result = null;
for ( AnatomicSite anaSite : anaSites) {
if ( anaSite.getName().equals(site.getName()) ) {
result = anaSite;
break;
}
}
return result;
}
/**
* Copy the Details from the Participant Object.
* @param history
* @param destHistory
*/
private void copyFromStudyParticipantDiseaseHistory(StudyParticipantDiseaseHistory history, DiseaseHistory destHistory) {
destHistory.setVersion(history.getVersion());
destHistory.setOtherPrimaryDisease(history.getOtherPrimaryDisease());
destHistory.setOtherPrimaryDiseaseSite(history.getOtherPrimaryDiseaseSite());
destHistory.setMeddraStudyDisease(history.getMeddraStudyDisease());
for (StudyParticipantMetastaticDiseaseSite studyParticipantMetastaticDiseaseSite : history.getMetastaticDiseaseSites()) {
destHistory.addMetastaticDiseaseSite(MetastaticDiseaseSite.createReportMetastaticDiseaseSite(studyParticipantMetastaticDiseaseSite));
}
destHistory.setDiagnosisDate(history.getDiagnosisDate());
destHistory.setCodedPrimaryDiseaseSite(history.getCodedPrimaryDiseaseSite());
destHistory.setCtepStudyDisease(history.getCtepStudyDisease());
destHistory.setAbstractStudyDisease(history.getAbstractStudyDisease());
}
/**
* Copy the Details from the Participant Object.
* @param history
* @param destHistory
*/
private void copyToStudyParticipantDiseaseHistory(DiseaseHistory history, StudyParticipantDiseaseHistory destHistory) {
if ( history.getMetastaticDiseaseSites().size() > 0) {
List<String> anatomicSites = new ArrayList<String>();
for ( MetastaticDiseaseSite diseaseSite : history.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
anatomicSites.add(diseaseSite.getCodedSite().getName());
}
}
String[] anatomicSitesArr = anatomicSites.toArray(new String[anatomicSites.size()]);
List<AnatomicSite> anaSites = anatomicSiteDao.getBySubnames(anatomicSitesArr);
for ( MetastaticDiseaseSite diseaseSite : history.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
AnatomicSite result = findAnatomicSiteByName(anaSites, diseaseSite.getCodedSite());
MetastaticDiseaseSite mds = new MetastaticDiseaseSite();
mds.setCodedSite(result);
destHistory.addMetastaticDiseaseSite(StudyParticipantMetastaticDiseaseSite.createAssignmentMetastaticDiseaseSite(mds));
}
}
}
}
}
|
package gov.nih.nci.cabig.caaers.service.migrator.report;
import gov.nih.nci.cabig.caaers.dao.AnatomicSiteDao;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.migrator.Migrator;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class DiseaseHistoryMigrator implements Migrator<ExpeditedAdverseEventReport> {
public AnatomicSiteDao getAnatomicSiteDao() {
return anatomicSiteDao;
}
public void setAnatomicSiteDao(AnatomicSiteDao anatomicSiteDao) {
this.anatomicSiteDao = anatomicSiteDao;
}
private AnatomicSiteDao anatomicSiteDao ;
public void migrate(ExpeditedAdverseEventReport aeReportSrc, ExpeditedAdverseEventReport aeReportDest, DomainObjectImportOutcome<ExpeditedAdverseEventReport> outcome) {
DiseaseHistory srcDisHis = aeReportSrc.getDiseaseHistory();
DiseaseHistory destDisHis = aeReportDest.getDiseaseHistory();
if ( destDisHis == null ) {
destDisHis = new DiseaseHistory();
}
Participant participant = aeReportDest.getParticipant();
StudySite site = null;
if ( aeReportDest.getReportingPeriod() != null && aeReportDest.getReportingPeriod().getAssignment() != null ) {
site = aeReportDest.getReportingPeriod().getAssignment().getStudySite();
}
if ( site == null ) {
outcome.addError("ER-DHM-1", "Study Site is missing in the source");
return;
}
if ( participant == null ) {
outcome.addError("ER-DHM-2", "Participant is missing in the destination");
return;
}
StudyParticipantAssignment assignment = participant.getStudyParticipantAssignment(site);
StudyParticipantDiseaseHistory history = assignment.getDiseaseHistory();
if ( history != null ) {
copyFromStudyParticipantDiseaseHistory(history, destDisHis);
}
// After copying it from the patient make sure we have removed it from the srcDisHis object to remove the duplicates.
removeDuplicateMetaStaticSites(srcDisHis, destDisHis);
copyDiseaseHistory(srcDisHis, destDisHis, outcome);
//copy new ones to the SPA after checking for duplicates
copyToStudyParticipantDiseaseHistory(destDisHis, history);
}
/**
* Copy Disease History details from Input to the Domain Object.
* @param srcDisHis
* @param destDisHis
*/
private void copyDiseaseHistory(DiseaseHistory srcDisHis, DiseaseHistory destDisHis, DomainObjectImportOutcome<ExpeditedAdverseEventReport> outcome) {
if ( srcDisHis.getMetastaticDiseaseSites().size() > 0) {
List<String> anatomicSites = new ArrayList<String>();
for ( MetastaticDiseaseSite diseaseSite : srcDisHis.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
anatomicSites.add(diseaseSite.getCodedSite().getName());
}
}
String[] anatomicSitesArr = anatomicSites.toArray(new String[anatomicSites.size()]);
List<AnatomicSite> anaSites = anatomicSiteDao.getBySubnames(anatomicSitesArr);
for ( MetastaticDiseaseSite diseaseSite : srcDisHis.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
AnatomicSite result = findAnatomicSiteByName(anaSites, diseaseSite.getCodedSite());
MetastaticDiseaseSite mds = new MetastaticDiseaseSite();
mds.setCodedSite(result);
destDisHis.getMetastaticDiseaseSites().add(mds);
}
}
}
if (StringUtils.isNotEmpty(srcDisHis.getCodedPrimaryDiseaseSite().getName()) ) {
AnatomicSite anatomicSite = srcDisHis.getCodedPrimaryDiseaseSite();
String[] codedPrimaryAnatomicSite = new String[1];
codedPrimaryAnatomicSite[0] = anatomicSite.getName();
List<AnatomicSite> codedPrimaryAnaSites = anatomicSiteDao.getBySubnames(codedPrimaryAnatomicSite);
AnatomicSite result = findAnatomicSiteByName(codedPrimaryAnaSites, anatomicSite);
if ( result != null) {
destDisHis.setCodedPrimaryDiseaseSite(result);
} else {
// Output with Error.
outcome.addError("ER-DHM-2", "Primary Site of Disease is not found " + anatomicSite.getName() );
return;
}
// Copy the other Disease site if provided.
if (StringUtils.isNotBlank(srcDisHis.getOtherPrimaryDiseaseSite()))
destDisHis.setOtherPrimaryDiseaseSite(srcDisHis.getOtherPrimaryDiseaseSite());
}
destDisHis.setDiagnosisDate(srcDisHis.getDiagnosisDate());
if ( destDisHis.getReport().getStudy().hasCtepEsysIdentifier() && StringUtils.isNotEmpty( ((DiseaseTerm)srcDisHis.getAbstractStudyDisease().getTerm()).getTerm()) ) {
List<CtepStudyDisease> ctepStudyDiseases = destDisHis.getReport().getStudy().getActiveCtepStudyDiseases();
boolean studyDiesaseFound = false;
for ( CtepStudyDisease disease : ctepStudyDiseases) {
if ( disease.getTermName().equals(srcDisHis.getAbstractStudyDisease().getTermName())) {
destDisHis.setAbstractStudyDisease(disease);
studyDiesaseFound = true;
break;
}
}
if ( !studyDiesaseFound ) { // If not found throw the error back to user.
outcome.addError("ER-DHM-3", "Primary Disease is not found on the Study " + srcDisHis.getAbstractStudyDisease().getTermName() );
return;
}
} else {
List<MeddraStudyDisease> meddraStudyDiseases = destDisHis.getReport().getStudy().getActiveMeddraStudyDiseases();
boolean studyDiesaseFound = false;
for ( MeddraStudyDisease disease : meddraStudyDiseases) {
if ( disease.getTermName().equals(srcDisHis.getAbstractStudyDisease().getTermName())) {
destDisHis.setAbstractStudyDisease(disease);
studyDiesaseFound = true;
break;
}
}
if ( !studyDiesaseFound ) { // If not found throw the error back to user.
outcome.addError("ER-DHM-3", "Primary Disease is not found on the Study " + srcDisHis.getAbstractStudyDisease().getTermName() );
return;
}
}
// Copy the other Primary disease site.
if (StringUtils.isNotBlank(srcDisHis.getOtherPrimaryDisease()) )
destDisHis.setOtherPrimaryDisease(srcDisHis.getOtherPrimaryDisease());
}
private void removeDuplicateMetaStaticSites(DiseaseHistory srcDisHis, DiseaseHistory destDisHis) {
for (MetastaticDiseaseSite destSite: destDisHis.getMetastaticDiseaseSites()) {
int index = findIndexMetastaticSite(srcDisHis.getMetastaticDiseaseSites(), destSite);
if ( index > -1 ) srcDisHis.getMetastaticDiseaseSites().remove(index);
}
}
private int findIndexMetastaticSite(List<MetastaticDiseaseSite> srcMetaStaticSites, MetastaticDiseaseSite destSite) {
int index = -1;
for ( MetastaticDiseaseSite site: srcMetaStaticSites ) {
index ++;
if ( site.getCodedSite().getName().equals(destSite.getCodedSite().getName())) { // Found a duplicate.
return index;
}
}
return -1;
}
private int findIndexStudyParticipantMetastaticSite(List<StudyParticipantMetastaticDiseaseSite> srcMetaStaticSites, MetastaticDiseaseSite destSite) {
int index = -1;
for ( StudyParticipantMetastaticDiseaseSite site: srcMetaStaticSites ) {
index ++;
if ( site.getCodedSite().getName().equals(destSite.getCodedSite().getName())) { // Found a duplicate.
return index;
}
}
return -1;
}
private AnatomicSite findAnatomicSiteByName(List<AnatomicSite> anaSites, AnatomicSite site) {
AnatomicSite result = null;
for ( AnatomicSite anaSite : anaSites) {
if ( anaSite.getName().equals(site.getName()) ) {
result = anaSite;
break;
}
}
return result;
}
/**
* Copy the Details from the Participant Object.
* @param history
* @param destHistory
*/
private void copyFromStudyParticipantDiseaseHistory(StudyParticipantDiseaseHistory history, DiseaseHistory destHistory) {
destHistory.setVersion(history.getVersion());
destHistory.setOtherPrimaryDisease(history.getOtherPrimaryDisease());
destHistory.setOtherPrimaryDiseaseSite(history.getOtherPrimaryDiseaseSite());
destHistory.setMeddraStudyDisease(history.getMeddraStudyDisease());
for (StudyParticipantMetastaticDiseaseSite studyParticipantMetastaticDiseaseSite : history.getMetastaticDiseaseSites()) {
destHistory.addMetastaticDiseaseSite(MetastaticDiseaseSite.createReportMetastaticDiseaseSite(studyParticipantMetastaticDiseaseSite));
}
destHistory.setDiagnosisDate(history.getDiagnosisDate());
destHistory.setCodedPrimaryDiseaseSite(history.getCodedPrimaryDiseaseSite());
destHistory.setCtepStudyDisease(history.getCtepStudyDisease());
destHistory.setAbstractStudyDisease(history.getAbstractStudyDisease());
}
/**
* Copy the Details from the Participant Object.
* @param history
* @param destHistory
*/
private void copyToStudyParticipantDiseaseHistory(DiseaseHistory history, StudyParticipantDiseaseHistory destHistory) {
if ( history.getMetastaticDiseaseSites().size() > 0) {
List<String> anatomicSites = new ArrayList<String>();
for ( MetastaticDiseaseSite diseaseSite : history.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
anatomicSites.add(diseaseSite.getCodedSite().getName());
}
}
if(history.getCodedPrimaryDiseaseSite() != null){
List<AnatomicSite> primaryDiseaseSites = anatomicSiteDao.getBySubnames(new String[]{history.getCodedPrimaryDiseaseSite().getName()});
if(primaryDiseaseSites != null && !primaryDiseaseSites.isEmpty()){
destHistory.setCodedPrimaryDiseaseSite(primaryDiseaseSites.get(0));
}
}
String[] anatomicSitesArr = anatomicSites.toArray(new String[anatomicSites.size()]);
List<AnatomicSite> anaSites = anatomicSiteDao.getBySubnames(anatomicSitesArr);
for ( MetastaticDiseaseSite diseaseSite : history.getMetastaticDiseaseSites()) {
if ( diseaseSite.getCodedSite() != null ) {
AnatomicSite result = findAnatomicSiteByName(anaSites, diseaseSite.getCodedSite());
MetastaticDiseaseSite mds = new MetastaticDiseaseSite();
mds.setCodedSite(result);
if(findIndexStudyParticipantMetastaticSite(destHistory.getMetastaticDiseaseSites(), mds) == -1) {
destHistory.addMetastaticDiseaseSite(
StudyParticipantMetastaticDiseaseSite.createAssignmentMetastaticDiseaseSite(mds));
}
}
}
}
}
}
|
package org.openhealthtools.mdht.uml.cda.dita;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import org.eclipse.core.runtime.IPath;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Stereotype;
import org.openhealthtools.mdht.uml.cda.core.util.CDAModelUtil;
import org.openhealthtools.mdht.uml.cda.dita.internal.Logger;
import org.openhealthtools.mdht.uml.cda.resources.util.CDAProfileUtil;
import org.openhealthtools.mdht.uml.cda.resources.util.ICDAProfileConstants;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
public class TransformClass extends TransformAbstract {
public TransformClass(DitaTransformerOptions options) {
super(options);
}
@Override
public Object caseClass(Class umlClass) {
String pathFolder = "classes";
String fileName = umlClass.getName() + ".dita";
IPath filePath = transformerOptions.getOutputPath().append(pathFolder)
.addTrailingSeparator().append(umlClass.getName()).addFileExtension("dita");
File file = filePath.toFile();
PrintWriter writer = null;
if (!file.exists()) {
try {
file.createNewFile();
writer = new PrintWriter(file);
appendHeader(writer, umlClass);
appendBody(writer, umlClass);
} catch (FileNotFoundException e) {
Logger.logException(e);
} catch (IOException e1) {
Logger.logException(e1);
} finally {
if (writer != null) {
writer.close();
}
}
}
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(umlClass,
ICDAProfileConstants.CDA_TEMPLATE);
Class cdaClass = CDAModelUtil.getCDAClass(umlClass);
if (hl7Template != null && cdaClass != null) {
if ("ClinicalDocument".equals(cdaClass.getName()))
transformerOptions.getDocumentList().add(fileName);
else if ("Section".equals(cdaClass.getName()))
transformerOptions.getSectionList().add(fileName);
else
transformerOptions.getClinicalStatementList().add(fileName);
}
else {
transformerOptions.getClassList().add(fileName);
}
return umlClass;
}
private void appendHeader(PrintWriter writer, Class umlClass) {
String className = umlClass.getName();
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<!DOCTYPE topic PUBLIC \"-//OASIS//DTD DITA Topic//EN\" \"topic.dtd\">");
writer.println("<topic id=\"classId\" xml:lang=\"en-us\">");
writer.print("<title>");
writer.print(UMLUtil.splitName(umlClass));
writer.println("</title>");
writer.println("<shortdesc conref=\"generated/_" + className + ".dita#classId/shortdesc\"></shortdesc>");
writer.println("<prolog conref=\"generated/_" + className + ".dita#classId/prolog\"></prolog>");
}
private void appendBody(PrintWriter writer, Class umlClass) {
Stereotype hl7Template = CDAProfileUtil.getAppliedCDAStereotype(umlClass,
ICDAProfileConstants.CDA_TEMPLATE);
String className = umlClass.getName();
writer.println("<body>");
if (umlClass.getOwnedComments().isEmpty()) {
writer.println("<p>TODO: add class description</p>");
}
else {
for (Comment comment : umlClass.getOwnedComments()) {
String body = comment.getBody().trim();
if (body.startsWith("<p>")) {
writer.println(comment.getBody());
}
else {
writer.println("<p>" + comment.getBody() + "</p>");
}
}
}
writer.println();
writer.println("<ol conref=\"generated/_" + className + ".dita#classId/conformance\">");
// writer.println("<ol conref=\"generated/_" + className + ".dita#classId/aggregate\">");
writer.println("<li></li>");
writer.println("</ol>");
// if (hl7Template != null) {
writer.println("<fig>");
writer.println("<title>" + UMLUtil.splitName(umlClass) + " example</title>");
writer.println("<codeblock conref=\"generated/_" + className + ".dita#classId/example\">");
writer.println("</codeblock>");
writer.println("</fig>");
writer.println("</body>");
writer.println("</topic>");
}
}
|
package com.intellij.openapi.editor.impl;
import com.intellij.codeInsight.daemon.GutterMark;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.Inlay;
import com.intellij.openapi.editor.TextAnnotationGutterProvider;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.markup.ActiveGutterRenderer;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.LineMarkerRenderer;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.JBColor;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.accessibility.SimpleAccessible;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.accessibility.AccessibleContext;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.function.Consumer;
import java.util.List;
import static com.intellij.util.ObjectUtils.*;
/**
* A panel which provides a11y for the current line in a gutter.
* The panel contains {@link AccessibleGutterElement} components each of them represents a particular element in the gutter.
* The panel can be shown and focused via {@code EditorFocusGutter} action.
*
* @author tav
*/
class AccessibleGutterLine extends JPanel {
private final EditorGutterComponentImpl myGutter;
private AccessibleGutterElement mySelectedElement;
// [tav] todo: soft-wrap doesn't work correctly
private final int myLogicalLineNum;
private final int myVisualLineNum;
private static boolean actionHandlerInstalled;
private static class MyShortcuts {
static final CustomShortcutSet MOVE_RIGHT = new CustomShortcutSet(
new KeyboardShortcut(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), null),
new KeyboardShortcut(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), null));
static final CustomShortcutSet MOVE_LEFT = new CustomShortcutSet(
new KeyboardShortcut(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), null),
new KeyboardShortcut(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_DOWN_MASK), null));
}
public static AccessibleGutterLine createAndActivate(@NotNull EditorGutterComponentImpl gutter) {
return new AccessibleGutterLine(gutter);
}
public void escape(boolean requestFocusToEditor) {
myGutter.remove(this);
myGutter.repaint();
myGutter.setCurrentAccessibleLine(null);
if (requestFocusToEditor) {
IdeFocusManager.getGlobalInstance().requestFocus(myGutter.getEditor().getContentComponent(), true);
}
}
@Override
public void paint(Graphics g) {
mySelectedElement.paint(g);
}
public static void installListeners(@NotNull EditorGutterComponentImpl gutter) {
if (!actionHandlerInstalled) {
// [tav] todo: when the API is stable and open move it to ShowGutterIconTooltipAction
actionHandlerInstalled = true;
EditorActionManager.getInstance().setActionHandler("EditorShowGutterIconTooltip", new EditorActionHandler() {
@Override
protected void doExecute(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) {
AccessibleGutterLine line = ((EditorGutterComponentImpl)editor.getGutter()).getCurrentAccessibleLine();
if (line != null) line.showTooltipIfPresent();
}
});
}
gutter.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
gutter.setCurrentAccessibleLine(createAndActivate(gutter));
}
});
gutter.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
gutter.escapeCurrentAccessibleLine();
}
});
gutter.getEditor().getCaretModel().addCaretListener(new CaretListener() {
@Override
public void caretPositionChanged(@NotNull CaretEvent event) {
AccessibleGutterLine line = gutter.getCurrentAccessibleLine();
if (line != null) line.maybeLineChanged();
}
});
}
private void moveRight() {
IdeFocusManager.getGlobalInstance().requestFocus(getFocusTraversalPolicy().getComponentAfter(this, mySelectedElement), true);
}
private void pressEnter(AnActionEvent e) {
int cX = IdeFocusManager.getGlobalInstance().getFocusOwner().getX();
List<GutterMark> row = myGutter.getGutterRenderers(myVisualLineNum);
myGutter.processIconsRow(myVisualLineNum, row, (x, y, renderer) -> {
Icon icon = myGutter.scaleIcon(renderer.getIcon());
int iconWidth = icon.getIconWidth();
if (x <= cX && cX <= x + iconWidth) {
GutterIconRenderer result = (GutterIconRenderer)renderer;
AnAction action = result.getClickAction();
if (action != null) {
action.actionPerformed(e);
}
} // end check coordinates
});
}
private void moveLeft() {
IdeFocusManager.getGlobalInstance().requestFocus(getFocusTraversalPolicy().getComponentBefore(this, mySelectedElement), true);
}
public void showTooltipIfPresent() {
mySelectedElement.showTooltip();
}
private AccessibleGutterLine(@NotNull EditorGutterComponentImpl gutter) {
super(null);
EditorImpl editor = gutter.getEditor();
int lineHeight = editor.getLineHeight();
myGutter = gutter;
myLogicalLineNum = editor.getCaretModel().getPrimaryCaret().getLogicalPosition().line;
myVisualLineNum = editor.getCaretModel().getPrimaryCaret().getVisualPosition().line;
/* line numbers */
if (myGutter.isLineNumbersShown()) {
addNewElement(new SimpleAccessible() {
@NotNull
@Override
public String getAccessibleName() {
return "line " + (myLogicalLineNum + 1);
}
@Override
public String getAccessibleTooltipText() {
return null;
}
}, myGutter.getLineNumberAreaOffset(), 0, myGutter.getLineNumberAreaWidth(), lineHeight);
}
/* annotations */
if (myGutter.isAnnotationsShown()) {
int x = myGutter.getAnnotationsAreaOffset();
int width = 0;
String tooltipText = null;
StringBuilder buf = new StringBuilder("annotation: ");
for (int i = 0; i < myGutter.myTextAnnotationGutters.size(); i++) {
TextAnnotationGutterProvider gutterProvider = myGutter.myTextAnnotationGutters.get(i);
if (tooltipText == null) tooltipText = gutterProvider.getToolTip(myLogicalLineNum, editor); // [tav] todo: take first non-null?
int annotationSize = myGutter.myTextAnnotationGutterSizes.get(i);
buf.append(notNull(gutterProvider.getLineText(myLogicalLineNum, editor), ""));
width += annotationSize;
}
if (buf.length() > 0) {
String tt = tooltipText;
addNewElement(new SimpleAccessible() {
@NotNull
@Override
public String getAccessibleName() {
return buf.toString();
}
@Override
public String getAccessibleTooltipText() {
return tt;
}
}, x, 0, width, lineHeight);
}
}
/* icons */
if (myGutter.areIconsShown()) {
List<GutterMark> row = myGutter.getGutterRenderers(myVisualLineNum);
myGutter.processIconsRow(myVisualLineNum, row, (x, y, renderer) -> {
Icon icon = myGutter.scaleIcon(renderer.getIcon());
addNewElement(new SimpleAccessible() {
@NotNull
@Override
public String getAccessibleName() {
if (renderer instanceof SimpleAccessible) {
return ((SimpleAccessible)renderer).getAccessibleName();
}
return "icon: " + renderer.getClass().getSimpleName();
}
@Override
public String getAccessibleTooltipText() {
return renderer.getTooltipText();
}
}, x, 0, icon.getIconWidth(), lineHeight);
});
}
/* active markers */
if (myGutter.isLineMarkersShown()) {
int firstVisibleOffset = editor.visualLineStartOffset(myVisualLineNum);
int lastVisibleOffset = editor.visualLineStartOffset(myVisualLineNum + 1);
myGutter.processRangeHighlighters(firstVisibleOffset, lastVisibleOffset, highlighter -> {
LineMarkerRenderer renderer = highlighter.getLineMarkerRenderer();
if (renderer instanceof ActiveGutterRenderer) {
Rectangle rect = myGutter.getLineRendererRectangle(highlighter);
if (rect != null) {
Rectangle bounds = ((ActiveGutterRenderer)renderer).calcBounds(editor, myVisualLineNum, rect);
if (bounds != null) {
addNewElement((ActiveGutterRenderer)renderer, bounds.x, 0, bounds.width, bounds.height);
}
}
}
});
}
setOpaque(false);
setFocusable(false);
setFocusCycleRoot(true);
setFocusTraversalPolicyProvider(true);
setFocusTraversalPolicy(new LayoutFocusTraversalPolicy());
setBounds(0, editor.visualLineToY(myVisualLineNum), myGutter.getWhitespaceSeparatorOffset(), lineHeight);
myGutter.add(this);
mySelectedElement = (AccessibleGutterElement)getFocusTraversalPolicy().getFirstComponent(this);
if (mySelectedElement == null) {
Rectangle b = getBounds(); // set above
mySelectedElement = addNewElement(new SimpleAccessible() {
@NotNull
@Override
public String getAccessibleName() {
return "empty";
}
@Override
public String getAccessibleTooltipText() {
return null;
}
}, 0, 0, b.width, b.height);
}
installActionHandler(CommonShortcuts.ESCAPE, () -> escape(true));
installActionHandler(CommonShortcuts.ENTER, this::pressEnter); // [tav] todo: it can do something useful, e.g. forcing Screen Reader to voice
installActionHandler(MyShortcuts.MOVE_RIGHT, this::moveRight);
installActionHandler(MyShortcuts.MOVE_LEFT, this::moveLeft);
IdeFocusManager.getGlobalInstance().requestFocus(mySelectedElement, true);
}
private void installActionHandler(ShortcutSet shortcut, Runnable action) {
DumbAwareAction.create(e -> action.run()).registerCustomShortcutSet(shortcut, this);
}
private void installActionHandler(ShortcutSet shortcut, Consumer<AnActionEvent> action) {
DumbAwareAction.create(e -> action.accept(e)).registerCustomShortcutSet(shortcut, this);
}
@SuppressWarnings("SameParameterValue")
@NotNull
private AccessibleGutterElement addNewElement(@NotNull SimpleAccessible accessible, int x, int y, int width, int height) {
AccessibleGutterElement obj = new AccessibleGutterElement(accessible, new Rectangle(x, y, width, height));
add(obj);
return obj;
}
@Override
public void removeNotify() {
repaint();
super.removeNotify();
}
private void maybeLineChanged() {
if (myLogicalLineNum == myGutter.getEditor().getCaretModel().getPrimaryCaret().getLogicalPosition().line) return;
myGutter.remove(this);
myGutter.setCurrentAccessibleLine(createAndActivate(myGutter));
}
@Override
public void repaint() {
if (myGutter == null) return;
int y = myGutter.getEditor().visualLineToY(myVisualLineNum);
myGutter.repaint(0, y, myGutter.getWhitespaceSeparatorOffset(), y + myGutter.getEditor().getLineHeight());
}
private boolean isActive() {
return this == myGutter.getCurrentAccessibleLine();
}
public static boolean isAccessibleGutterElement(Object element) {
return element instanceof SimpleAccessible;
}
/**
* A component which represents a particular element in the gutter like a line number, an icon, a marker, etc.
* The component is transparent, placed above the element and is made focusable. It's possible to navigate the
* components in the current gutter line via the left/right arrow keys. Also, it's possible to show a tooltip
* (when available) above an element via {@code EditorShowGutterIconTooltip} action.
*
* @author tav
*/
private class AccessibleGutterElement extends JLabel {
private @NotNull final SimpleAccessible myAccessible;
AccessibleGutterElement(@NotNull SimpleAccessible accessible, @NotNull Rectangle bounds) {
myAccessible = accessible;
setFocusable(true);
setBounds(bounds.x, bounds.y, bounds.width, myGutter.getEditor().getLineHeight());
setOpaque(false);
setText(myAccessible.getAccessibleName());
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
mySelectedElement = AccessibleGutterElement.this;
getParent().repaint();
}
@Override
public void focusLost(FocusEvent e) {
if (!(e.getOppositeComponent() instanceof AccessibleGutterElement) && isActive()) {
escape(false);
}
}
});
}
@Override
public void paint(Graphics g) {
if (mySelectedElement != this) return;
Color oldColor = g.getColor();
try {
g.setColor(JBColor.blue);
Point parentLoc = getParent().getLocation();
Rectangle bounds = getBounds();
bounds.setLocation(parentLoc.x + bounds.x, parentLoc.y + bounds.y);
int y = bounds.y + bounds.height - JBUIScale.scale(1);
LinePainter2D.paint((Graphics2D)g, bounds.x, y, bounds.x + bounds.width, y,
LinePainter2D.StrokeType.INSIDE, JBUIScale.scale(1));
} finally {
g.setColor(oldColor);
}
}
public void showTooltip() {
if (myAccessible.getAccessibleTooltipText() != null) {
Rectangle bounds = getBounds();
Rectangle pBounds = getParent().getBounds();
int x = pBounds.x + bounds.x + bounds.width / 2;
int y = pBounds.y + bounds.y + bounds.height / 2;
myGutter.showToolTip(myAccessible.getAccessibleTooltipText(), new Point(x, y), Balloon.Position.atRight);
}
}
@Override
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJLabel() {
@Override
public String getAccessibleName() {
return getText();
}
};
}
return accessibleContext;
}
}
}
|
package com.intellij.openapi.fileEditor;
import com.intellij.codeHighlighting.BackgroundEditorHighlighter;
import com.intellij.icons.AllIcons;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.ex.EditorGutterComponentEx;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.JBSplitter;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Konstantin Bulenkov
*/
public class TextEditorWithPreview extends UserDataHolderBase implements FileEditor {
protected final TextEditor myEditor;
protected final FileEditor myPreview;
@NotNull
private final MyListenersMultimap myListenersGenerator = new MyListenersMultimap();
private Layout myLayout;
private JComponent myComponent;
private SplitEditorToolbar myToolbarWrapper;
private final String myName;
public TextEditorWithPreview(@NotNull TextEditor editor, @NotNull FileEditor preview, @NotNull String editorName) {
myEditor = editor;
myPreview = preview;
myName = editorName;
}
public TextEditorWithPreview(@NotNull TextEditor editor, @NotNull FileEditor preview) {
this(editor, preview, "TextEditorWithPreview");
}
@Nullable
@Override
public BackgroundEditorHighlighter getBackgroundHighlighter() {
return myEditor.getBackgroundHighlighter();
}
@Nullable
@Override
public FileEditorLocation getCurrentLocation() {
return myEditor.getCurrentLocation();
}
@Nullable
@Override
public StructureViewBuilder getStructureViewBuilder() {
return myEditor.getStructureViewBuilder();
}
@Override
public void dispose() {
Disposer.dispose(myEditor);
Disposer.dispose(myPreview);
}
@Override
public void selectNotify() {
myEditor.selectNotify();
myPreview.selectNotify();
}
@Override
public void deselectNotify() {
myEditor.deselectNotify();
myPreview.deselectNotify();
}
@NotNull
@Override
public JComponent getComponent() {
if (myComponent == null) {
final JBSplitter splitter = new JBSplitter(false, 0.5f, 0.15f, 0.85f);
splitter.setSplitterProportionKey(getSplitterProportionKey());
splitter.setFirstComponent(myEditor.getComponent());
splitter.setSecondComponent(myPreview.getComponent());
myToolbarWrapper = new SplitEditorToolbar(splitter);
myToolbarWrapper.addGutterToTrack(((EditorGutterComponentEx)(myEditor).getEditor().getGutter()));
if (myPreview instanceof TextEditor) {
myToolbarWrapper.addGutterToTrack(((EditorGutterComponentEx)((TextEditor)myPreview).getEditor().getGutter()));
}
if (myLayout == null) {
String lastUsed = PropertiesComponent.getInstance().getValue(getLayoutPropertyName());
myLayout = Layout.fromName(lastUsed, Layout.SHOW_EDITOR_AND_PREVIEW);
}
adjustEditorsVisibility();
myComponent = JBUI.Panels.simplePanel(splitter).addToTop(myToolbarWrapper);
}
return myComponent;
}
@Override
public void setState(@NotNull FileEditorState state) {
if (state instanceof MyFileEditorState) {
final MyFileEditorState compositeState = (MyFileEditorState)state;
if (compositeState.getFirstState() != null) {
myEditor.setState(compositeState.getFirstState());
}
if (compositeState.getSecondState() != null) {
myPreview.setState(compositeState.getSecondState());
}
if (compositeState.getSplitLayout() != null) {
myLayout = compositeState.getSplitLayout();
invalidateLayout();
}
}
}
private void adjustEditorsVisibility() {
myEditor.getComponent().setVisible(myLayout == Layout.SHOW_EDITOR || myLayout == Layout.SHOW_EDITOR_AND_PREVIEW);
myPreview.getComponent().setVisible(myLayout == Layout.SHOW_PREVIEW || myLayout == Layout.SHOW_EDITOR_AND_PREVIEW);
}
private void invalidateLayout() {
adjustEditorsVisibility();
myToolbarWrapper.refresh();
myComponent.repaint();
final JComponent focusComponent = getPreferredFocusedComponent();
if (focusComponent != null) {
IdeFocusManager.findInstanceByComponent(focusComponent).requestFocus(focusComponent, true);
}
}
@NotNull
protected String getSplitterProportionKey() {
return "TextEditorWithPreview.SplitterProportionKey";
}
@Nullable
@Override
public JComponent getPreferredFocusedComponent() {
switch (myLayout) {
case SHOW_EDITOR_AND_PREVIEW:
case SHOW_EDITOR:
return myEditor.getPreferredFocusedComponent();
case SHOW_PREVIEW:
return myPreview.getPreferredFocusedComponent();
default:
throw new IllegalStateException(myLayout.myName);
}
}
@NotNull
@Override
public String getName() {
return myName;
}
@NotNull
@Override
public FileEditorState getState(@NotNull FileEditorStateLevel level) {
return new MyFileEditorState(myLayout, myEditor.getState(level), myPreview.getState(level));
}
@Override
public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
myEditor.addPropertyChangeListener(listener);
myPreview.addPropertyChangeListener(listener);
final DoublingEventListenerDelegate delegate = myListenersGenerator.addListenerAndGetDelegate(listener);
myEditor.addPropertyChangeListener(delegate);
myPreview.addPropertyChangeListener(delegate);
}
@Override
public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
myEditor.removePropertyChangeListener(listener);
myPreview.removePropertyChangeListener(listener);
final DoublingEventListenerDelegate delegate = myListenersGenerator.removeListenerAndGetDelegate(listener);
if (delegate != null) {
myEditor.removePropertyChangeListener(delegate);
myPreview.removePropertyChangeListener(delegate);
}
}
static class MyFileEditorState implements FileEditorState {
private final Layout mySplitLayout;
private final FileEditorState myFirstState;
private final FileEditorState mySecondState;
public MyFileEditorState(Layout layout, FileEditorState firstState, FileEditorState secondState) {
mySplitLayout = layout;
myFirstState = firstState;
mySecondState = secondState;
}
@Nullable
public Layout getSplitLayout() {
return mySplitLayout;
}
@Nullable
public FileEditorState getFirstState() {
return myFirstState;
}
@Nullable
public FileEditorState getSecondState() {
return mySecondState;
}
@Override
public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
return otherState instanceof MyFileEditorState
&& (myFirstState == null || myFirstState.canBeMergedWith(((MyFileEditorState)otherState).myFirstState, level))
&& (mySecondState == null || mySecondState.canBeMergedWith(((MyFileEditorState)otherState).mySecondState, level));
}
}
@Override
public boolean isModified() {
return myEditor.isModified() || myPreview.isModified();
}
@Override
public boolean isValid() {
return myEditor.isValid() && myPreview.isValid();
}
private class DoublingEventListenerDelegate implements PropertyChangeListener {
@NotNull
private final PropertyChangeListener myDelegate;
private DoublingEventListenerDelegate(@NotNull PropertyChangeListener delegate) {
myDelegate = delegate;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
myDelegate.propertyChange(new PropertyChangeEvent(TextEditorWithPreview.this, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()));
}
}
private class MyListenersMultimap {
private final Map<PropertyChangeListener, Pair<Integer, DoublingEventListenerDelegate>> myMap = new HashMap<>();
@NotNull
public DoublingEventListenerDelegate addListenerAndGetDelegate(@NotNull PropertyChangeListener listener) {
if (!myMap.containsKey(listener)) {
myMap.put(listener, Pair.create(1, new DoublingEventListenerDelegate(listener)));
}
else {
final Pair<Integer, DoublingEventListenerDelegate> oldPair = myMap.get(listener);
myMap.put(listener, Pair.create(oldPair.getFirst() + 1, oldPair.getSecond()));
}
return myMap.get(listener).getSecond();
}
@Nullable
public DoublingEventListenerDelegate removeListenerAndGetDelegate(@NotNull PropertyChangeListener listener) {
final Pair<Integer, DoublingEventListenerDelegate> oldPair = myMap.get(listener);
if (oldPair == null) {
return null;
}
if (oldPair.getFirst() == 1) {
myMap.remove(listener);
}
else {
myMap.put(listener, Pair.create(oldPair.getFirst() - 1, oldPair.getSecond()));
}
return oldPair.getSecond();
}
}
public class SplitEditorToolbar extends JPanel implements Disposable {
private final ActionToolbar myRightToolbar;
private final List<EditorGutterComponentEx> myGutters = new ArrayList<>();
private final ComponentAdapter myAdjustToGutterListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
adjustSpacing();
}
@Override
public void componentShown(ComponentEvent e) {
adjustSpacing();
}
@Override
public void componentHidden(ComponentEvent e) {
adjustSpacing();
}
};
public SplitEditorToolbar(@NotNull final JComponent targetComponentForActions) {
super(new BorderLayout());
final ActionToolbar leftToolbar = createToolbar();
if (leftToolbar != null) {
leftToolbar.setTargetComponent(targetComponentForActions);
add(leftToolbar.getComponent(), BorderLayout.WEST);
}
ActionGroup group = new DefaultActionGroup(
new ChangeViewModeAction(Layout.SHOW_EDITOR),
new ChangeViewModeAction(Layout.SHOW_EDITOR_AND_PREVIEW),
new ChangeViewModeAction(Layout.SHOW_PREVIEW)
);
myRightToolbar = ActionManager.getInstance().createActionToolbar("TextEditorWithPreview", group, true);
myRightToolbar.setTargetComponent(targetComponentForActions);
add(myRightToolbar.getComponent(), BorderLayout.EAST);
addComponentListener(myAdjustToGutterListener);
}
public void addGutterToTrack(@NotNull EditorGutterComponentEx gutterComponentEx) {
myGutters.add(gutterComponentEx);
gutterComponentEx.addComponentListener(myAdjustToGutterListener);
}
public void refresh() {
adjustSpacing();
myRightToolbar.updateActionsImmediately();
}
private void adjustSpacing() {
EditorGutterComponentEx leftMostGutter = null;
for (EditorGutterComponentEx gutter : myGutters) {
if (!gutter.isShowing()) {
continue;
}
if (leftMostGutter == null || leftMostGutter.getX() > gutter.getX()) {
leftMostGutter = gutter;
}
}
revalidate();
repaint();
}
@Override
public void dispose() {
removeComponentListener(myAdjustToGutterListener);
for (EditorGutterComponentEx gutter : myGutters) {
gutter.removeComponentListener(myAdjustToGutterListener);
}
}
}
@Nullable
protected ActionToolbar createToolbar() {
return null;
}
public enum Layout {
SHOW_EDITOR("Editor only", AllIcons.General.LayoutEditorOnly),
SHOW_PREVIEW("Preview only", AllIcons.General.LayoutPreviewOnly),
SHOW_EDITOR_AND_PREVIEW("Editor and Preview", AllIcons.General.LayoutEditorPreview);
private final String myName;
private final Icon myIcon;
Layout(String name, Icon icon) {
myName = name;
myIcon = icon;
}
public static Layout fromName(String name, Layout defaultValue) {
for (Layout layout : Layout.values()) {
if (layout.myName.equals(name)) {
return layout;
}
}
return defaultValue;
}
public String getName() {
return myName;
}
public Icon getIcon() {
return myIcon;
}
}
private class ChangeViewModeAction extends ToggleAction implements DumbAware {
private final Layout myActionLayout;
public ChangeViewModeAction(Layout layout) {
super(layout.getName(), layout.getName(), layout.getIcon());
myActionLayout = layout;
}
@Override
public boolean isSelected(AnActionEvent e) {
return myLayout == myActionLayout;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
if (state) {
myLayout = myActionLayout;
PropertiesComponent.getInstance().setValue(getLayoutPropertyName(), myLayout.myName, Layout.SHOW_EDITOR_AND_PREVIEW.myName);
adjustEditorsVisibility();
}
}
}
@NotNull
private String getLayoutPropertyName() {
return myName + "Layout";
}
}
|
package io.cattle.platform.docker.service.impl;
import static io.cattle.platform.core.model.tables.EnvironmentTable.*;
import static io.cattle.platform.core.model.tables.ServiceTable.*;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.core.model.Environment;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.model.ServiceExposeMap;
import io.cattle.platform.docker.process.dao.ComposeDao;
import io.cattle.platform.docker.process.lock.ComposeProjectLock;
import io.cattle.platform.docker.process.lock.ComposeServiceLock;
import io.cattle.platform.docker.process.util.DockerConstants;
import io.cattle.platform.docker.service.ComposeManager;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.lock.LockCallback;
import io.cattle.platform.lock.LockCallbackNoReturn;
import io.cattle.platform.lock.LockManager;
import io.cattle.platform.lock.definition.DefaultMultiLockDefinition;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.servicediscovery.api.constants.ServiceDiscoveryConstants;
import io.cattle.platform.servicediscovery.api.dao.ServiceExposeMapDao;
import io.cattle.platform.servicediscovery.deployment.impl.unit.DefaultDeploymentUnitInstance;
import io.github.ibuildthecloud.gdapi.condition.Condition;
import io.github.ibuildthecloud.gdapi.condition.ConditionType;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
public class ComposeManagerImpl implements ComposeManager {
public static final String SERVICE_LABEL = "com.docker.compose.service";
public static final String PROJECT_LABEL = "com.docker.compose.project";
@Inject
ComposeDao composeDao;
@Inject
GenericResourceDao resourceDao;
@Inject
LockManager lockManager;
@Inject
ObjectManager objectManager;
@Inject
ServiceExposeMapDao serviceExportMapDao;
@Inject
ObjectProcessManager objectProcessManager;
@Inject
JsonMapper jsonMapper;
protected String getString(Map<String, Object> labels, String key) {
Object value = labels.get(key);
return value == null ? null : value.toString();
}
@Override
public void setupServiceAndInstance(Instance instance) {
Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS);
String project = getString(labels, PROJECT_LABEL);
String service = getString(labels, SERVICE_LABEL);
if (StringUtils.isBlank(project) || StringUtils.isBlank(service)) {
return;
}
instance = setupLabels(instance, service, project);
getService(instance, service, project);
}
private Instance setupLabels(Instance instance, String service, String project) {
Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS);
setIfNot(labels, ServiceDiscoveryConstants.LABEL_SERVICE_DEPLOYMENT_UNIT, UUID.randomUUID());
setIfNot(labels, ServiceDiscoveryConstants.LABEL_SERVICE_LAUNCH_CONFIG, ServiceDiscoveryConstants.PRIMARY_LAUNCH_CONFIG_NAME);
setIfNot(labels, ServiceDiscoveryConstants.LABEL_STACK_NAME, project);
setIfNot(labels, ServiceDiscoveryConstants.LABEL_STACK_SERVICE_NAME, String.format("%s/%s", project, service));
DataAccessor.setField(instance, InstanceConstants.FIELD_LABELS, labels);
return objectManager.persist(instance);
}
protected void setIfNot(Map<String, Object> labels, String key, Object value) {
if (!labels.containsKey(key)) {
labels.put(key, value);
}
}
protected Service createService(Instance instance) {
Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS);
String project = getString(labels, PROJECT_LABEL);
String service = getString(labels, SERVICE_LABEL);
Map<String, Object> instanceData = jsonMapper.writeValueAsMap(instance);
instanceData.remove(ObjectMetaDataManager.ID_FIELD);
instanceData.remove(ObjectMetaDataManager.STATE_FIELD);
instanceData.remove("token");
instanceData.remove(ObjectMetaDataManager.DATA_FIELD);
instanceData.remove(ObjectMetaDataManager.CREATED_FIELD);
Iterator<Entry<String, Object>> iter = instanceData.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Object> entry = iter.next();
if (entry.getValue() == null || entry.getValue() instanceof Number) {
iter.remove();
}
}
Environment env = getEnvironment(instance.getAccountId(), project);
return resourceDao.createAndSchedule(Service.class,
SERVICE.NAME, service,
SERVICE.ACCOUNT_ID, instance.getAccountId(),
SERVICE.ENVIRONMENT_ID, env.getId(),
SERVICE.SELECTOR_CONTAINER, String.format("%s=%s, %s=%s", PROJECT_LABEL, project, SERVICE_LABEL, service),
ServiceDiscoveryConstants.FIELD_START_ON_CREATE, true,
ServiceDiscoveryConstants.FIELD_LAUNCH_CONFIG, instanceData,
SERVICE.KIND, "composeService");
}
protected Service getService(final Instance instance, final String name, final String projectName) {
Service service = composeDao.getComposeServiceByName(instance.getAccountId(), name, projectName);
if (service != null) {
return service;
}
return lockManager.lock(new ComposeServiceLock(instance.getAccountId(), name), new LockCallback<Service>() {
@Override
public Service doWithLock() {
Service service = composeDao.getComposeServiceByName(instance.getAccountId(), name, projectName);
if (service != null) {
return service;
}
return createService(instance);
}
});
}
protected Environment getEnvironment(final long accountId, final String project) {
Environment env = composeDao.getComposeProjectByName(accountId, project);
if (env != null) {
return env;
}
return lockManager.lock(new ComposeProjectLock(accountId, project), new LockCallback<Environment>() {
@Override
public Environment doWithLock() {
Environment env = composeDao.getComposeProjectByName(accountId, project);
if (env != null) {
return env;
}
return resourceDao.createAndSchedule(Environment.class,
ENVIRONMENT.NAME, project,
ENVIRONMENT.ACCOUNT_ID, accountId,
ENVIRONMENT.KIND, "composeProject");
}
});
}
@Override
public void cleanupResources(final Service service) {
if (!DockerConstants.TYPE_COMPOSE_SERVICE.equals(service.getKind())) {
return;
}
final Environment env = objectManager.loadResource(Environment.class, service.getEnvironmentId());
lockManager.lock(new DefaultMultiLockDefinition(new ComposeProjectLock(env.getAccountId(), env.getName()),
new ComposeServiceLock(env.getAccountId(), service.getName())), new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
checkAndDelete(service, env);
}
});
}
protected void checkAndDelete(Service service, Environment env) {
service = objectManager.reload(service);
env = objectManager.reload(env);
boolean found = false;
for (ServiceExposeMap map : serviceExportMapDao.getUnmanagedServiceInstanceMapsToRemove(service.getId())) {
found = true;
if (isRemoved(service.getRemoved(), service.getState())) {
Instance instance = objectManager.loadResource(Instance.class, map.getInstanceId());
DefaultDeploymentUnitInstance.removeInstance(instance, objectProcessManager);
}
}
if (!found && !isRemoved(service.getRemoved(), service.getState())) {
objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, service, null);
}
env = objectManager.reload(env);
if (isRemoved(env.getRemoved(), env.getState())) {
return;
}
List<Service> services = objectManager.find(Service.class,
SERVICE.ENVIRONMENT_ID, env.getId(),
ObjectMetaDataManager.STATE_FIELD, new Condition(ConditionType.NE, CommonStatesConstants.REMOVING),
ObjectMetaDataManager.REMOVED_FIELD, null);
if (services.size() == 0) {
objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, env, null);
}
}
protected boolean isRemoved(Date removed, String state) {
if (removed != null) {
return true;
}
return CommonStatesConstants.REMOVING.equals(state);
}
}
|
package com.intellij.openapi.fileEditor.impl;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.UISettingsListener;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
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.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.impl.text.FileDropHandler;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManagerListener;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.FocusWatcher;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.FrameTitleBuilder;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.openapi.wm.impl.IdePanePanel;
import com.intellij.testFramework.LightVirtualFileBase;
import com.intellij.ui.JBColor;
import com.intellij.ui.OnePixelSplitter;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.docking.DockManager;
import com.intellij.ui.tabs.JBTabs;
import com.intellij.ui.tabs.impl.JBTabsImpl;
import com.intellij.util.Alarm;
import com.intellij.util.containers.ArrayListSet;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ContainerEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.List;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
public class EditorsSplitters extends IdePanePanel implements UISettingsListener, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.EditorsSplitters");
private static final String PINNED = "pinned";
private static final String CURRENT_IN_TAB = "current-in-tab";
private static final Key<Object> DUMMY_KEY = Key.create("EditorsSplitters.dummy.key");
private EditorWindow myCurrentWindow;
private final Set<EditorWindow> myWindows = new CopyOnWriteArraySet<>();
private final FileEditorManagerImpl myManager;
private Element mySplittersElement; // temporarily used during initialization
int myInsideChange;
private final MyFocusWatcher myFocusWatcher;
private final Alarm myIconUpdaterAlarm = new Alarm();
private final UIBuilder myUIBuilder = new UIBuilder();
EditorsSplitters(final FileEditorManagerImpl manager, DockManager dockManager, boolean createOwnDockableContainer) {
super(new BorderLayout());
setBackground(JBColor.namedColor("Editor.background", IdeBackgroundUtil.getIdeBackgroundColor()));
PropertyChangeListener l = e -> {
String propName = e.getPropertyName();
if ("Editor.background".equals(propName) || "Editor.foreground".equals(propName) || "Editor.shortcutForeground".equals(propName)) {
repaint();
}
};
UIManager.getDefaults().addPropertyChangeListener(l);
Disposer.register(manager.getProject(), () -> UIManager.getDefaults().removePropertyChangeListener(l));
myManager = manager;
myFocusWatcher = new MyFocusWatcher();
setFocusTraversalPolicy(new MyFocusTraversalPolicy());
setTransferHandler(new MyTransferHandler());
clear();
if (createOwnDockableContainer) {
DockableEditorTabbedContainer dockable = new DockableEditorTabbedContainer(myManager.getProject(), this, false);
Disposer.register(manager.getProject(), dockable);
dockManager.register(dockable);
}
ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(KeymapManagerListener.TOPIC, new KeymapManagerListener() {
@Override
public void activeKeymapChanged(@Nullable Keymap keymap) {
invalidate();
repaint();
}
});
}
public FileEditorManagerImpl getManager() {
return myManager;
}
public void clear() {
for (EditorWindow window : myWindows) {
window.dispose();
}
removeAll();
myWindows.clear();
setCurrentWindow(null);
repaint (); // revalidate doesn't repaint correctly after "Close All"
}
void startListeningFocus() {
myFocusWatcher.install(this);
}
private void stopListeningFocus() {
myFocusWatcher.deinstall(this);
}
@Override
public void dispose() {
myIconUpdaterAlarm.cancelAllRequests();
stopListeningFocus();
}
@Nullable
public VirtualFile getCurrentFile() {
if (myCurrentWindow != null) {
return myCurrentWindow.getSelectedFile();
}
return null;
}
private boolean showEmptyText() {
return myCurrentWindow == null || myCurrentWindow.getFiles().length == 0;
}
@Override
protected void paintComponent(Graphics g) {
if (showEmptyText()) {
Graphics2D gg = IdeBackgroundUtil.withFrameBackground(g, this);
super.paintComponent(gg);
g.setColor(UIUtil.isUnderDarcula() ? UIUtil.getBorderColor() : new Color(0, 0, 0, 50));
g.drawLine(0, 0, getWidth(), 0);
}
}
public void writeExternal(@NotNull Element element) {
if (getComponentCount() == 0) {
return;
}
JPanel panel = (JPanel)getComponent(0);
if (panel.getComponentCount() != 0) {
try {
element.addContent(writePanel(panel.getComponent(0)));
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
LOG.error(e);
}
}
}
@SuppressWarnings("HardCodedStringLiteral")
private Element writePanel(@NotNull Component comp) {
if (comp instanceof Splitter) {
final Splitter splitter = (Splitter)comp;
final Element res = new Element("splitter");
res.setAttribute("split-orientation", splitter.getOrientation() ? "vertical" : "horizontal");
res.setAttribute("split-proportion", Float.toString(splitter.getProportion()));
final Element first = new Element("split-first");
first.addContent(writePanel(splitter.getFirstComponent().getComponent(0)));
final Element second = new Element("split-second");
second.addContent(writePanel(splitter.getSecondComponent().getComponent(0)));
res.addContent(first);
res.addContent(second);
return res;
}
else if (comp instanceof JBTabs) {
final Element res = new Element("leaf");
Integer limit = UIUtil.getClientProperty(((JBTabs)comp).getComponent(), JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY);
if (limit != null) {
res.setAttribute(JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY.toString(), String.valueOf(limit));
}
writeWindow(res, findWindowWith(comp));
return res;
}
else if (comp instanceof EditorWindow.TCompForTablessMode) {
EditorWithProviderComposite composite = ((EditorWindow.TCompForTablessMode)comp).myEditor;
Element res = new Element("leaf");
res.addContent(writeComposite(composite.getFile(), composite, false, composite));
return res;
}
else {
LOG.error(comp.getClass().getName());
return null;
}
}
private void writeWindow(@NotNull Element res, @Nullable EditorWindow window) {
if (window != null) {
EditorWithProviderComposite[] composites = window.getEditors();
for (int i = 0; i < composites.length; i++) {
VirtualFile file = window.getFileAt(i);
res.addContent(writeComposite(file, composites[i], window.isFilePinned(file), window.getSelectedEditor()));
}
}
}
@NotNull
private Element writeComposite(VirtualFile file, EditorWithProviderComposite composite, boolean pinned, EditorWithProviderComposite selectedEditor) {
Element fileElement = new Element("file");
composite.currentStateAsHistoryEntry().writeExternal(fileElement, getManager().getProject());
fileElement.setAttribute(PINNED, Boolean.toString(pinned));
fileElement.setAttribute(CURRENT_IN_TAB, Boolean.toString(composite.equals(selectedEditor)));
return fileElement;
}
public void openFiles() {
if (mySplittersElement != null) {
final JPanel comp = myUIBuilder.process(mySplittersElement, getTopPanel());
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
if (comp != null) {
removeAll();
add(comp, BorderLayout.CENTER);
mySplittersElement = null;
}
// clear empty splitters
for (EditorWindow window : getWindows()) {
if (window.getTabCount() == 0) window.removeFromSplitter();
}
});
}
}
public int getEditorsCount() {
return mySplittersElement == null ? 0 : countFiles(mySplittersElement);
}
private double myProgressStep;
public void setProgressStep(double step) { myProgressStep = step; }
private void updateProgress() {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null && !indicator.isIndeterminate()) {
indicator.setFraction(indicator.getFraction() + myProgressStep);
}
}
private static int countFiles(Element element) {
Integer value = new ConfigTreeReader<Integer>() {
@Override
protected Integer processFiles(@NotNull List<? extends Element> fileElements, Element parent, @Nullable Integer context) {
return fileElements.size();
}
@Override
protected Integer processSplitter(@NotNull Element element, @Nullable Element firstChild, @Nullable Element secondChild, @Nullable Integer context) {
Integer first = process(firstChild, null);
Integer second = process(secondChild, null);
return (first == null ? 0 : first) + (second == null ? 0 : second);
}
}.process(element, null);
return value == null ? 0 : value;
}
public void readExternal(final Element element) {
mySplittersElement = element;
}
@NotNull
public VirtualFile[] getOpenFiles() {
Set<VirtualFile> files = new ArrayListSet<>();
for (EditorWindow myWindow : myWindows) {
for (EditorWithProviderComposite editor : myWindow.getEditors()) {
files.add(editor.getFile());
}
}
return VfsUtilCore.toVirtualFileArray(files);
}
@NotNull
public VirtualFile[] getSelectedFiles() {
final Set<VirtualFile> files = new ArrayListSet<>();
for (final EditorWindow window : myWindows) {
final VirtualFile file = window.getSelectedFile();
if (file != null) {
files.add(file);
}
}
final VirtualFile[] virtualFiles = VfsUtilCore.toVirtualFileArray(files);
final VirtualFile currentFile = getCurrentFile();
if (currentFile != null) {
for (int i = 0; i != virtualFiles.length; ++i) {
if (Comparing.equal(virtualFiles[i], currentFile)) {
virtualFiles[i] = virtualFiles[0];
virtualFiles[0] = currentFile;
break;
}
}
}
return virtualFiles;
}
@NotNull
public FileEditor[] getSelectedEditors() {
Set<EditorWindow> windows = new THashSet<>(myWindows);
final EditorWindow currentWindow = getCurrentWindow();
if (currentWindow != null) {
windows.add(currentWindow);
}
List<FileEditor> editors = new ArrayList<>();
for (final EditorWindow window : windows) {
final EditorWithProviderComposite composite = window.getSelectedEditor();
if (composite != null) {
editors.add(composite.getSelectedEditor());
}
}
return editors.toArray(new FileEditor[0]);
}
public void updateFileIcon(@NotNull final VirtualFile file) {
updateFileIconLater(file);
}
private void updateFileIconImmediately(final VirtualFile file) {
final Collection<EditorWindow> windows = findWindows(file);
for (EditorWindow window : windows) {
window.updateFileIcon(file);
}
}
private final Set<VirtualFile> myFilesToUpdateIconsFor = new HashSet<>();
private void updateFileIconLater(VirtualFile file) {
myFilesToUpdateIconsFor.add(file);
myIconUpdaterAlarm.cancelAllRequests();
myIconUpdaterAlarm.addRequest(() -> {
if (myManager.getProject().isDisposed()) return;
for (VirtualFile file1 : myFilesToUpdateIconsFor) {
updateFileIconImmediately(file1);
}
myFilesToUpdateIconsFor.clear();
}, 200, ModalityState.stateForComponent(this));
}
void updateFileColor(@NotNull final VirtualFile file) {
final Collection<EditorWindow> windows = findWindows(file);
for (final EditorWindow window : windows) {
final int index = window.findEditorIndex(window.findFileComposite(file));
LOG.assertTrue(index != -1);
window.setForegroundAt(index, getManager().getFileColor(file));
window.setWaveColor(index, getManager().isProblem(file) ? JBColor.red : null);
}
}
public void trimToSize(final int editor_tab_limit) {
for (final EditorWindow window : myWindows) {
window.trimToSize(editor_tab_limit, window.getSelectedFile(), true);
}
}
public void setTabsPlacement(final int tabPlacement) {
final EditorWindow[] windows = getWindows();
for (int i = 0; i != windows.length; ++ i) {
windows[i].setTabsPlacement(tabPlacement);
}
}
void setTabLayoutPolicy(int scrollTabLayout) {
final EditorWindow[] windows = getWindows();
for (int i = 0; i != windows.length; ++ i) {
windows[i].setTabLayoutPolicy(scrollTabLayout);
}
}
void updateFileName(@Nullable VirtualFile updatedFile) {
for (EditorWindow window : getWindows()) {
for (VirtualFile file : window.getFiles()) {
if (updatedFile == null || file.getName().equals(updatedFile.getName())) {
window.updateFileName(file);
}
}
}
Project project = myManager.getProject();
IdeFrame frame = getFrame(project);
if (frame != null) {
String fileTitle = null;
File ioFile = null;
VirtualFile file = getCurrentFile();
if (file != null) {
ioFile = file instanceof LightVirtualFileBase ? null : new File(file.getPresentableUrl());
fileTitle = FrameTitleBuilder.getInstance().getFileTitle(project, file);
}
frame.setFileTitle(fileTitle, ioFile);
}
}
protected IdeFrame getFrame(Project project) {
final WindowManagerEx windowManagerEx = WindowManagerEx.getInstanceEx();
final IdeFrame frame = windowManagerEx.getFrame(project);
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode() || frame != null);
return frame;
}
boolean isInsideChange() {
return myInsideChange > 0;
}
private void setCurrentWindow(@Nullable final EditorWindow currentWindow) {
if (currentWindow != null && !myWindows.contains(currentWindow)) {
throw new IllegalArgumentException(currentWindow + " is not a member of this container");
}
myCurrentWindow = currentWindow;
}
void updateFileBackgroundColor(@NotNull VirtualFile file) {
final EditorWindow[] windows = getWindows();
for (int i = 0; i != windows.length; ++ i) {
windows [i].updateFileBackgroundColor(file);
}
}
int getSplitCount() {
if (getComponentCount() > 0) {
JPanel panel = (JPanel) getComponent(0);
return getSplitCount(panel);
}
return 0;
}
private static int getSplitCount(JComponent component) {
if (component.getComponentCount() > 0) {
final JComponent firstChild = (JComponent)component.getComponent(0);
if (firstChild instanceof Splitter) {
final Splitter splitter = (Splitter)firstChild;
return getSplitCount(splitter.getFirstComponent()) + getSplitCount(splitter.getSecondComponent());
}
return 1;
}
return 0;
}
protected void afterFileClosed(@NotNull VirtualFile file) {
}
protected void afterFileOpen(@NotNull VirtualFile file) {
}
@Nullable
JBTabs getTabsAt(RelativePoint point) {
Point thisPoint = point.getPoint(this);
Component c = SwingUtilities.getDeepestComponentAt(this, thisPoint.x, thisPoint.y);
while (c != null) {
if (c instanceof JBTabs) {
return (JBTabs)c;
}
c = c.getParent();
}
return null;
}
boolean isEmptyVisible() {
EditorWindow[] windows = getWindows();
for (EditorWindow each : windows) {
if (!each.isEmptyVisible()) {
return false;
}
}
return true;
}
@Nullable
private VirtualFile findNextFile(final VirtualFile file) {
final EditorWindow[] windows = getWindows(); // TODO: use current file as base
for (int i = 0; i != windows.length; ++i) {
final VirtualFile[] files = windows[i].getFiles();
for (final VirtualFile fileAt : files) {
if (!Comparing.equal(fileAt, file)) {
return fileAt;
}
}
}
return null;
}
void closeFile(VirtualFile file, boolean moveFocus) {
final List<EditorWindow> windows = findWindows(file);
boolean isProjectOpen = myManager.getProject().isOpen();
if (!windows.isEmpty()) {
final VirtualFile nextFile = findNextFile(file);
for (final EditorWindow window : windows) {
LOG.assertTrue(window.getSelectedEditor() != null);
window.closeFile(file, false, moveFocus);
if (window.getTabCount() == 0 && nextFile != null && isProjectOpen) {
EditorWithProviderComposite newComposite = myManager.newEditorComposite(nextFile);
window.setEditor(newComposite, moveFocus); // newComposite can be null
}
}
// cleanup windows with no tabs
for (final EditorWindow window : windows) {
if (!isProjectOpen || window.isDisposed()) {
// call to window.unsplit() which might make its sibling disposed
continue;
}
if (window.getTabCount() == 0) {
window.unsplit(false);
}
}
}
}
@Override
public void uiSettingsChanged(UISettings uiSettings) {
if (!myManager.getProject().isOpen()) return;
for (VirtualFile file : getOpenFiles()) {
updateFileBackgroundColor(file);
updateFileIcon(file);
updateFileColor(file);
}
}
private final class MyFocusTraversalPolicy extends IdeFocusTraversalPolicy {
@Override
public final Component getDefaultComponentImpl(final Container focusCycleRoot) {
if (myCurrentWindow != null) {
final EditorWithProviderComposite selectedEditor = myCurrentWindow.getSelectedEditor();
if (selectedEditor != null) {
return IdeFocusTraversalPolicy.getPreferredFocusedComponent(selectedEditor.getComponent(), this);
}
}
return IdeFocusTraversalPolicy.getPreferredFocusedComponent(EditorsSplitters.this, this);
}
}
@Nullable
public JPanel getTopPanel() {
return getComponentCount() > 0 ? (JPanel)getComponent(0) : null;
}
public EditorWindow getCurrentWindow() {
return myCurrentWindow;
}
public EditorWindow getOrCreateCurrentWindow(final VirtualFile file) {
final List<EditorWindow> windows = findWindows(file);
if (getCurrentWindow() == null) {
final Iterator<EditorWindow> iterator = myWindows.iterator();
if (!windows.isEmpty()) {
setCurrentWindow(windows.get(0), false);
}
else if (iterator.hasNext()) {
setCurrentWindow(iterator.next(), false);
}
else {
createCurrentWindow();
}
}
else if (!windows.isEmpty()) {
if (!windows.contains(getCurrentWindow())) {
setCurrentWindow(windows.get(0), false);
}
}
return getCurrentWindow();
}
void createCurrentWindow() {
LOG.assertTrue(myCurrentWindow == null);
setCurrentWindow(createEditorWindow());
add(myCurrentWindow.myPanel, BorderLayout.CENTER);
}
protected EditorWindow createEditorWindow() {
return new EditorWindow(this);
}
/**
* sets the window passed as a current ('focused') window among all splitters. All file openings will be done inside this
* current window
* @param window a window to be set as current
* @param requestFocus whether to request focus to the editor currently selected in this window
*/
void setCurrentWindow(@Nullable final EditorWindow window, final boolean requestFocus) {
final EditorWithProviderComposite newEditor = window == null ? null : window.getSelectedEditor();
Runnable fireRunnable = () -> getManager().fireSelectionChanged(newEditor);
setCurrentWindow(window);
getManager().updateFileName(window == null ? null : window.getSelectedFile());
if (window != null) {
final EditorWithProviderComposite selectedEditor = window.getSelectedEditor();
if (selectedEditor != null) {
fireRunnable.run();
}
if (requestFocus) {
window.requestFocus(true);
}
} else {
fireRunnable.run();
}
}
void addWindow(EditorWindow window) {
myWindows.add(window);
}
void removeWindow(EditorWindow window) {
myWindows.remove(window);
if (myCurrentWindow == window) {
myCurrentWindow = null;
}
}
boolean containsWindow(EditorWindow window) {
return myWindows.contains(window);
}
public EditorWithProviderComposite[] getEditorsComposites() {
List<EditorWithProviderComposite> res = new ArrayList<>();
for (final EditorWindow myWindow : myWindows) {
final EditorWithProviderComposite[] editors = myWindow.getEditors();
ContainerUtil.addAll(res, editors);
}
return res.toArray(new EditorWithProviderComposite[0]);
}
@NotNull
public List<EditorWithProviderComposite> findEditorComposites(@NotNull VirtualFile file) {
List<EditorWithProviderComposite> res = new ArrayList<>();
for (final EditorWindow window : myWindows) {
final EditorWithProviderComposite fileComposite = window.findFileComposite(file);
if (fileComposite != null) {
res.add(fileComposite);
}
}
return res;
}
@NotNull
private List<EditorWindow> findWindows(final VirtualFile file) {
List<EditorWindow> res = new ArrayList<>();
for (final EditorWindow window : myWindows) {
if (window.findFileComposite(file) != null) {
res.add(window);
}
}
return res;
}
@NotNull public EditorWindow [] getWindows() {
return myWindows.toArray(new EditorWindow[0]);
}
@NotNull
EditorWindow[] getOrderedWindows() {
final List<EditorWindow> res = new ArrayList<>();
// Collector for windows in tree ordering:
class Inner{
private void collect(final JPanel panel){
final Component comp = panel.getComponent(0);
if (comp instanceof Splitter) {
final Splitter splitter = (Splitter)comp;
collect((JPanel)splitter.getFirstComponent());
collect((JPanel)splitter.getSecondComponent());
}
else if (comp instanceof JPanel || comp instanceof JBTabs) {
final EditorWindow window = findWindowWith(comp);
if (window != null) {
res.add(window);
}
}
}
}
// get root component and traverse splitters tree:
if (getComponentCount() != 0) {
final Component comp = getComponent(0);
LOG.assertTrue(comp instanceof JPanel);
final JPanel panel = (JPanel)comp;
if (panel.getComponentCount() != 0) {
new Inner().collect (panel);
}
}
LOG.assertTrue(res.size() == myWindows.size());
return res.toArray(new EditorWindow[0]);
}
@Nullable
private EditorWindow findWindowWith(final Component component) {
if (component != null) {
for (final EditorWindow window : myWindows) {
if (SwingUtilities.isDescendingFrom(component, window.myPanel)) {
return window;
}
}
}
return null;
}
public boolean isFloating() {
return false;
}
public boolean isPreview() {
return false;
}
private final class MyFocusWatcher extends FocusWatcher {
@Override
protected void focusedComponentChanged(final Component component, final AWTEvent cause) {
EditorWindow newWindow = null;
if (component != null) {
newWindow = findWindowWith(component);
}
else if (cause instanceof ContainerEvent && cause.getID() == ContainerEvent.COMPONENT_REMOVED) {
// do not change current window in case of child removal as in JTable.removeEditor
// otherwise Escape in a toolwindow will not focus editor with JTable content
return;
}
setCurrentWindow(newWindow);
setCurrentWindow(newWindow, false);
}
}
private final class MyTransferHandler extends TransferHandler {
private final FileDropHandler myFileDropHandler = new FileDropHandler(null);
@Override
public boolean importData(JComponent comp, Transferable t) {
if (myFileDropHandler.canHandleDrop(t.getTransferDataFlavors())) {
myFileDropHandler.handleDrop(t, myManager.getProject(), myCurrentWindow);
return true;
}
return false;
}
@Override
public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
return myFileDropHandler.canHandleDrop(transferFlavors);
}
}
private abstract static class ConfigTreeReader<T> {
@Nullable
public T process(@Nullable Element element, @Nullable T context) {
if (element == null) {
return null;
}
final Element splitterElement = element.getChild("splitter");
if (splitterElement != null) {
final Element first = splitterElement.getChild("split-first");
final Element second = splitterElement.getChild("split-second");
return processSplitter(splitterElement, first, second, context);
}
final Element leaf = element.getChild("leaf");
if (leaf == null) {
return null;
}
List<Element> fileElements = leaf.getChildren("file");
final List<Element> children = new ArrayList<>(fileElements.size());
// trim to EDITOR_TAB_LIMIT, ignoring CLOSE_NON_MODIFIED_FILES_FIRST policy
int toRemove = fileElements.size() - UISettings.getInstance().getEditorTabLimit();
for (Element fileElement : fileElements) {
if (toRemove <= 0 || Boolean.valueOf(fileElement.getAttributeValue(PINNED)).booleanValue()) {
children.add(fileElement);
}
else {
toRemove
}
}
return processFiles(children, leaf, context);
}
@Nullable
abstract T processFiles(@NotNull List<? extends Element> fileElements, Element parent, @Nullable T context);
@Nullable
abstract T processSplitter(@NotNull Element element, @Nullable Element firstChild, @Nullable Element secondChild, @Nullable T context);
}
private class UIBuilder extends ConfigTreeReader<JPanel> {
@Override
protected JPanel processFiles(@NotNull List<? extends Element> fileElements, Element parent, final JPanel context) {
final Ref<EditorWindow> windowRef = new Ref<>();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> windowRef.set(context == null ? createEditorWindow() : findWindowWith(context)));
final EditorWindow window = windowRef.get();
LOG.assertTrue(window != null);
VirtualFile focusedFile = null;
for (int i = 0; i < fileElements.size(); i++) {
final Element file = fileElements.get(i);
if (i == 0) {
EditorTabbedContainer tabbedPane = window.getTabbedPane();
if (tabbedPane != null) {
try {
int limit =
Integer.parseInt(parent.getAttributeValue(JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY.toString(),
String.valueOf(JBTabsImpl.DEFAULT_MAX_TAB_WIDTH)));
UIUtil.putClientProperty(tabbedPane.getComponent(), JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY, limit);
}
catch (NumberFormatException e) {
//ignore
}
}
}
try {
final FileEditorManagerImpl fileEditorManager = getManager();
Element historyElement = file.getChild(HistoryEntry.TAG);
final HistoryEntry entry = HistoryEntry.createLight(fileEditorManager.getProject(), historyElement);
final VirtualFile virtualFile = entry.getFile();
if (virtualFile == null) throw new InvalidDataException("No file exists: " + entry.getFilePointer().getUrl());
Document document = ReadAction.compute(() -> virtualFile.isValid() ? FileDocumentManager.getInstance().getDocument(virtualFile) : null);
final boolean isCurrentInTab = Boolean.valueOf(file.getAttributeValue(CURRENT_IN_TAB)).booleanValue();
Boolean pin = Boolean.valueOf(file.getAttributeValue(PINNED));
fileEditorManager.openFileImpl4(window, virtualFile, entry, false, false, pin, i, false);
if (isCurrentInTab) {
focusedFile = virtualFile;
}
if (document != null) {
// This is just to make sure document reference is kept on stack till this point
// so that document is available for folding state deserialization in HistoryEntry constructor
document.putUserData(DUMMY_KEY, null);
}
updateProgress();
}
catch (InvalidDataException e) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
LOG.error(e);
}
}
}
if (focusedFile != null) {
getManager().addSelectionRecord(focusedFile, window);
VirtualFile finalFocusedFile = focusedFile;
UIUtil.invokeLaterIfNeeded(()->{
EditorWithProviderComposite editor = window.findFileComposite(finalFocusedFile);
if (editor != null) {
window.setEditor(editor, true, true);
}
});
}
return window.myPanel;
}
@Override
protected JPanel processSplitter(@NotNull Element splitterElement, Element firstChild, Element secondChild, final JPanel context) {
if (context == null) {
final boolean orientation = "vertical".equals(splitterElement.getAttributeValue("split-orientation"));
final float proportion = Float.valueOf(splitterElement.getAttributeValue("split-proportion")).floatValue();
final JPanel firstComponent = process(firstChild, null);
final JPanel secondComponent = process(secondChild, null);
final Ref<JPanel> panelRef = new Ref<>();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
Splitter splitter = new OnePixelSplitter(orientation, proportion, 0.1f, 0.9f);
panel.add(splitter, BorderLayout.CENTER);
splitter.setFirstComponent(firstComponent);
splitter.setSecondComponent(secondComponent);
panelRef.set(panel);
});
return panelRef.get();
}
final Ref<JPanel> firstComponent = new Ref<>();
final Ref<JPanel> secondComponent = new Ref<>();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
if (context.getComponent(0) instanceof Splitter) {
Splitter splitter = (Splitter)context.getComponent(0);
firstComponent.set((JPanel)splitter.getFirstComponent());
secondComponent.set((JPanel)splitter.getSecondComponent());
}
else {
firstComponent.set(context);
secondComponent.set(context);
}
});
process(firstChild, firstComponent.get());
process(secondChild, secondComponent.get());
return context;
}
}
}
|
package com.peterphi.configuration.service.rest.impl;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.peterphi.configuration.service.git.ConfigChangeMode;
import com.peterphi.configuration.service.git.ConfigRepository;
import com.peterphi.configuration.service.git.RepoHelper;
import com.peterphi.configuration.service.guice.LowSecuritySessionNonceStore;
import com.peterphi.configuration.service.rest.api.ConfigUIService;
import com.peterphi.std.guice.common.auth.iface.CurrentUser;
import com.peterphi.std.guice.config.rest.types.ConfigPropertyData;
import com.peterphi.std.guice.config.rest.types.ConfigPropertyValue;
import com.peterphi.std.guice.web.rest.templating.TemplateCall;
import com.peterphi.std.guice.web.rest.templating.Templater;
import com.peterphi.std.io.PropertyFile;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ConfigUIServiceImpl implements ConfigUIService
{
private static final Logger log = Logger.getLogger(ConfigUIServiceImpl.class);
private static final String NONCE_USE = "configui";
@Inject
Templater templater;
@Inject
@Named("config")
ConfigRepository repo;
@Inject
Provider<CurrentUser> userProvider;
@Inject
LowSecuritySessionNonceStore nonceStore;
private static final String REF = "HEAD";
@Override
public String getIndex()
{
final TemplateCall call = templater.template("index");
call.set("paths", repo.getPaths(REF));
call.set("commits", repo.getRecentCommits(10));
return call.process();
}
@Override
public String getRootConfigPage()
{
return getConfigPage("");
}
@Override
public String getConfigPage(final String path)
{
final ConfigPropertyData config = repo.get(REF, path);
final List<String> paths = repo.getPaths(REF);
final List<ConfigPropertyValue> inheritedProperties;
final List<ConfigPropertyValue> definedProperties;
{
// Sort alphabetically for the UI
config.properties.sort(Comparator.comparing(ConfigPropertyValue:: getName));
inheritedProperties = computeInheritedProperties(config);
definedProperties = computeDefinedProperties(config);
}
final TemplateCall call = templater.template("config-edit");
call.set("nonce", nonceStore.getValue(NONCE_USE));
call.set("repo", repo);
call.set("config", config);
call.set("inheritedProperties", inheritedProperties);
call.set("definedProperties", definedProperties);
call.set("path", config.path);
call.set("paths", paths);
call.set("children", getChildren(config.path, paths));
call.set("parent", getParent(config.path));
return call.process();
}
private List<ConfigPropertyValue> computeInheritedProperties(final ConfigPropertyData config)
{
return config.properties.stream().filter(p -> p.path.length() < config.path.length()).collect(Collectors.toList());
}
private List<ConfigPropertyValue> computeDefinedProperties(final ConfigPropertyData config)
{
return config.properties.stream().filter(p -> p.path.equals(config.path)).collect(Collectors.toList());
}
@Override
public Response getConfigPage(final String nonce, final String path, final String child)
{
nonceStore.validate(NONCE_USE, nonce);
final String newPath = RepoHelper.normalisePath(path + "/" + child);
return Response.seeOther(URI.create("/edit/" + newPath)).build();
}
@Override
public Response importPropertyFile(final String nonce,
final String path,
final boolean merge,
final String properties,
final String message)
{
nonceStore.validate(NONCE_USE, nonce);
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
map.putSingle("_path", path);
if (message != null)
map.putSingle("_message", message);
if (nonce != null)
map.putSingle("_nonce", nonce);
// If merge is enabled then merge the properties on top of the existing properties at this path
if (merge)
{
final ConfigPropertyData existing = repo.get(REF, path);
for (ConfigPropertyValue defined : computeDefinedProperties(existing))
{
map.putSingle("property." + defined.getName(), defined.getValue());
}
}
// Now put all the Property File values into the map
{
PropertyFile props = PropertyFile.fromString(properties);
for (String key : props.keySet())
{
map.putSingle("property." + key, props.get(key));
}
}
// Finally, pass over to apply changes
return applyChanges(map);
}
static List<String> getChildren(final String path, final List<String> paths)
{
if (path.isEmpty())
{
return paths.stream().filter(s -> s.length() > 0).filter(s -> s.indexOf('/') == -1).collect(Collectors.toList());
}
else
{
final String prefix = path + "/";
List<String> children = new ArrayList<>();
for (String child : paths)
{
if (child.startsWith(prefix) && child.lastIndexOf('/') == path.length())
{
children.add(child);
}
}
return children;
}
}
static String getParent(final String path)
{
if (StringUtils.isBlank(path))
return null;
else if (path.indexOf('/') == -1)
return "";
else
{
final int lastIndex = path.lastIndexOf('/');
return path.substring(0, lastIndex);
}
}
@Override
public Response applyChanges(final MultivaluedMap<String, String> fields)
{
nonceStore.validate(NONCE_USE, fields.getFirst("_nonce"));
final String name = userProvider.get().getName();
final String email = userProvider.get().getUsername();
final String path = RepoHelper.normalisePath(fields.getFirst("_path"));
final String message = StringUtils.defaultIfBlank(fields.getFirst("_message"), "No message");
Map<String, Map<String, ConfigPropertyValue>> data = parseFields(path, fields);
repo.set(name, email, data, ConfigChangeMode.WIPE_REFERENCED_PATHS, message);
return Response.seeOther(URI.create("/edit/" + path)).build();
}
@Override
public Response pullRemote()
{
repo.pull("origin");
return Response.seeOther(URI.create("/")).build();
}
private Map<String, Map<String, ConfigPropertyValue>> parseFields(final String path,
final MultivaluedMap<String, String> fields)
{
Map<String, ConfigPropertyValue> properties = new HashMap<>();
for (Map.Entry<String, List<String>> entry : fields.entrySet())
{
final String name = entry.getKey();
final String value = entry.getValue().get(0);
if (name.startsWith("_"))
continue; // Skip form param names that start with _ (they carry commit data, not property data)
else if (name.startsWith("property."))
{
final String[] nameParts = StringUtils.split(name, ".", 2);
final String propertyName = nameParts[1];
properties.put(propertyName, new ConfigPropertyValue(path, propertyName, value));
}
else
{
log.warn("Unknown property in property update form:" + name);
}
}
return Collections.singletonMap(path, properties);
}
}
|
package net.sf.mpxj.sample;
import java.text.SimpleDateFormat;
import net.sf.mpxj.Duration;
import net.sf.mpxj.ProjectCalendar;
import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.ProjectHeader;
import net.sf.mpxj.RelationType;
import net.sf.mpxj.Resource;
import net.sf.mpxj.ResourceAssignment;
import net.sf.mpxj.Task;
import net.sf.mpxj.TimeUnit;
import net.sf.mpxj.mpx.MPXWriter;
import net.sf.mpxj.mspdi.MSPDIWriter;
import net.sf.mpxj.utility.NumberUtility;
import net.sf.mpxj.writer.ProjectWriter;
/**
* This example illustrates creation of an MPX or an MSPDI file from scratch.
* The output type of the file generated by this class depends on the file
* name extension supplied by the user. A .xml extension will generate an
* MSPDI file, anything else will generate an MPX file.
*/
public class MpxjCreate
{
/**
* Main method.
*
* @param args array of command line arguments
*/
public static void main(String[] args)
{
try
{
if (args.length != 1)
{
System.out.println("Usage: MpxCreate <output file name>");
}
else
{
create(args[0]);
}
}
catch (Exception ex)
{
ex.printStackTrace(System.out);
}
}
/**
* Creates a writer which will generate the required type of output file.
*
* @param filename file name
* @return ProjectWriter instance
*/
private static ProjectWriter getWriter(String filename)
{
ProjectWriter result;
String suffix;
if (filename.length() < 4)
{
suffix = ".MPX";
}
else
{
suffix = filename.substring(filename.length() - 4).toUpperCase();
}
if (suffix.equals(".XML") == true)
{
result = new MSPDIWriter();
}
else
{
result = new MPXWriter();
}
return (result);
}
/**
* This method creates a summary task, two sub-tasks and a milestone,
* all with the appropriate constraints between them. The tasks are
* assigned to two resources. Note that Microsoft Project is fussy
* about the order in which things appear in the file. If you are going
* to assign resources to tasks, the resources must appear in the
* file before the tasks.
*
* @param filename output file name
*/
private static void create(String filename) throws Exception
{
// Create a simple date format to allow us to
// easily set date values.
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
// Create an empty MPX or MSPDI file. The filename is passed to
// this method purely to allow it to determine the type of
// file to create.
ProjectFile file = new ProjectFile();
// Uncomment these lines to test the use of alternative
// delimiters and separators for MPX file output.
//file.setDelimiter(';');
//file.setDecimalSeparator(',');
//file.setThousandsSeparator('.');
// Add a default calendar called "Standard"
ProjectCalendar calendar = file.addDefaultBaseCalendar();
// Add a holiday to the calendar to demonstrate calendar exceptions
calendar.addCalendarException(df.parse("13/03/2006"), df.parse("13/03/2006"));
// Retrieve the project header and set the start date. Note Microsoft
// Project appears to reset all task dates relative to this date, so this
// date must match the start date of the earliest task for you to see
// the expected results. If this value is not set, it will default to
// today's date.
ProjectHeader header = file.getProjectHeader();
header.setStartDate(df.parse("01/01/2003"));
// Add resources
Resource resource1 = file.addResource();
resource1.setName("Resource1");
Resource resource2 = file.addResource();
resource2.setName("Resource2");
// This next line is not required, it is here simply to test the
// output file format when alternative separators and delimiters
// are used.
resource2.setMaxUnits(Double.valueOf(50.0));
// Create a summary task
Task task1 = file.addTask();
task1.setName("Summary Task");
// Create the first sub task
Task task2 = task1.addTask();
task2.setName("First Sub Task");
task2.setDuration(Duration.getInstance(10.5, TimeUnit.DAYS));
task2.setStart(df.parse("01/01/2003"));
// We'll set this task up as being 50% complete. If we have no resource
// assignments for this task, this is enough information for MS Project.
// If we do have resource assignments, the assignment record needs to
// contain the corresponding work and actual work fields set to the
// correct values in order for MS project to mark the task as complete
// or partially complete.
task2.setPercentageComplete(NumberUtility.getDouble(50.0));
task2.setActualStart(df.parse("01/01/2003"));
// Create the second sub task
Task task3 = task1.addTask();
task3.setName("Second Sub Task");
task3.setStart(df.parse("11/01/2003"));
task3.setDuration(Duration.getInstance(10, TimeUnit.DAYS));
// Link these two tasks
task3.addPredecessor(task2, RelationType.FINISH_START, null);
// Add a milestone
Task milestone1 = task1.addTask();
milestone1.setName("Milestone");
milestone1.setStart(df.parse("21/01/2003"));
milestone1.setDuration(Duration.getInstance(0, TimeUnit.DAYS));
milestone1.addPredecessor(task3, RelationType.FINISH_START, null);
// This final task has a percent complete value, but no
// resource assignments. This is an interesting case it it requires
// special processing to generate the MSPDI file correctly.
Task task4 = file.addTask();
task4.setName("Next Task");
task4.setDuration(Duration.getInstance(8, TimeUnit.DAYS));
task4.setStart(df.parse("01/01/2003"));
task4.setPercentageComplete(NumberUtility.getDouble(70.0));
task4.setActualStart(df.parse("01/01/2003"));
// Assign resources to tasks
ResourceAssignment assignment1 = task2.addResourceAssignment(resource1);
ResourceAssignment assignment2 = task3.addResourceAssignment(resource2);
// As the first task is partially complete, and we are adding
// a resource assignment, we must set the work and actual work
// fields in the assignment to appropriate values, or MS Project
// won't recognise the task as being complete or partially complete
assignment1.setWork(Duration.getInstance(80, TimeUnit.HOURS));
assignment1.setActualWork(Duration.getInstance(40, TimeUnit.HOURS));
// If we were just generating an MPX file, we would already have enough
// attributes set to create the file correctly. If we want to generate
// an MSPDI file, we must also set the assignment start dates and
// the remaining work attribute. The assignment start dates will normally
// be the same as the task start dates.
assignment1.setRemainingWork(Duration.getInstance(40, TimeUnit.HOURS));
assignment2.setRemainingWork(Duration.getInstance(80, TimeUnit.HOURS));
assignment1.setStart(df.parse("01/01/2003"));
assignment2.setStart(df.parse("11/01/2003"));
// Write a 100% complete task
Task task5 = file.addTask();
task5.setName("Last Task");
task5.setDuration(Duration.getInstance(3, TimeUnit.DAYS));
task5.setStart(df.parse("01/01/2003"));
task5.setPercentageComplete(NumberUtility.getDouble(100.0));
task5.setActualStart(df.parse("01/01/2003"));
// Write the file
ProjectWriter writer = getWriter(filename);
writer.write(file, filename);
}
}
|
package io.quarkus.rest.deployment.processor;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.DELETE;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.GET;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.HEAD;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.OPTIONS;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.PATCH;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.POST;
import static io.quarkus.rest.deployment.framework.QuarkusRestDotNames.PUT;
import java.io.File;
import java.io.Reader;
import java.lang.reflect.Modifier;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import javax.ws.rs.BeanParam;
import javax.ws.rs.RuntimeType;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.AnnotationsTransformerBuildItem;
import io.quarkus.arc.deployment.AutoInjectAnnotationBuildItem;
import io.quarkus.arc.deployment.BeanArchiveIndexBuildItem;
import io.quarkus.arc.deployment.BeanContainerBuildItem;
import io.quarkus.arc.deployment.BeanDefiningAnnotationBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
import io.quarkus.arc.processor.BuiltinScope;
import io.quarkus.arc.runtime.BeanContainer;
import io.quarkus.deployment.Capability;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.GeneratedClassGizmoAdaptor;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.CapabilityBuildItem;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.ShutdownContextBuildItem;
import io.quarkus.deployment.recording.RecorderContext;
import io.quarkus.deployment.util.JandexUtil;
import io.quarkus.gizmo.ClassCreator;
import io.quarkus.gizmo.FieldDescriptor;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.MethodDescriptor;
import io.quarkus.gizmo.ResultHandle;
import io.quarkus.rest.deployment.framework.AdditionalReaders;
import io.quarkus.rest.deployment.framework.AdditionalWriters;
import io.quarkus.rest.deployment.framework.EndpointIndexer;
import io.quarkus.rest.deployment.framework.QuarkusRestDotNames;
import io.quarkus.rest.runtime.QuarkusRestConfig;
import io.quarkus.rest.runtime.QuarkusRestRecorder;
import io.quarkus.rest.runtime.core.ContextResolvers;
import io.quarkus.rest.runtime.core.DynamicFeatures;
import io.quarkus.rest.runtime.core.ExceptionMapping;
import io.quarkus.rest.runtime.core.Features;
import io.quarkus.rest.runtime.core.GenericTypeMapping;
import io.quarkus.rest.runtime.core.Serialisers;
import io.quarkus.rest.runtime.injection.ContextProducers;
import io.quarkus.rest.runtime.model.InjectableBean;
import io.quarkus.rest.runtime.model.MethodParameter;
import io.quarkus.rest.runtime.model.ParameterType;
import io.quarkus.rest.runtime.model.ResourceClass;
import io.quarkus.rest.runtime.model.ResourceContextResolver;
import io.quarkus.rest.runtime.model.ResourceDynamicFeature;
import io.quarkus.rest.runtime.model.ResourceExceptionMapper;
import io.quarkus.rest.runtime.model.ResourceFeature;
import io.quarkus.rest.runtime.model.ResourceInterceptors;
import io.quarkus.rest.runtime.model.ResourceMethod;
import io.quarkus.rest.runtime.model.ResourceReader;
import io.quarkus.rest.runtime.model.ResourceReaderInterceptor;
import io.quarkus.rest.runtime.model.ResourceRequestInterceptor;
import io.quarkus.rest.runtime.model.ResourceResponseInterceptor;
import io.quarkus.rest.runtime.model.ResourceWriter;
import io.quarkus.rest.runtime.model.ResourceWriterInterceptor;
import io.quarkus.rest.runtime.model.RestClientInterface;
import io.quarkus.rest.runtime.providers.serialisers.ByteArrayMessageBodyHandler;
import io.quarkus.rest.runtime.providers.serialisers.CharArrayMessageBodyHandler;
import io.quarkus.rest.runtime.providers.serialisers.FileBodyHandler;
import io.quarkus.rest.runtime.providers.serialisers.FormUrlEncodedProvider;
import io.quarkus.rest.runtime.providers.serialisers.ReaderBodyHandler;
import io.quarkus.rest.runtime.providers.serialisers.StringMessageBodyHandler;
import io.quarkus.rest.runtime.providers.serialisers.VertxBufferMessageBodyWriter;
import io.quarkus.rest.runtime.providers.serialisers.VertxJsonMessageBodyWriter;
import io.quarkus.rest.runtime.providers.serialisers.jsonb.JsonbMessageBodyReader;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.vertx.http.deployment.FilterBuildItem;
import io.quarkus.vertx.http.runtime.HttpBuildTimeConfig;
import io.vertx.core.buffer.Buffer;
public class QuarkusRestProcessor {
private static Map<DotName, String> BUILTIN_HTTP_ANNOTATIONS_TO_METHOD = new HashMap<>();
static {
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(GET, "GET");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(POST, "POST");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(HEAD, "HEAD");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(PUT, "PUT");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(DELETE, "DELETE");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(PATCH, "PATCH");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD.put(OPTIONS, "OPTIONS");
BUILTIN_HTTP_ANNOTATIONS_TO_METHOD = Collections.unmodifiableMap(BUILTIN_HTTP_ANNOTATIONS_TO_METHOD);
}
@BuildStep
public FeatureBuildItem buildSetup() {
return new FeatureBuildItem(Feature.QUARKUS_REST);
}
@BuildStep
CapabilityBuildItem capability() {
return new CapabilityBuildItem(Capability.QUARKUS_REST);
}
@BuildStep
AutoInjectAnnotationBuildItem contextInjection(
BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer) {
additionalBeanBuildItemBuildProducer
.produce(AdditionalBeanBuildItem.builder().addBeanClasses(ContextProducers.class).build());
return new AutoInjectAnnotationBuildItem(DotName.createSimple(Context.class.getName()),
DotName.createSimple(BeanParam.class.getName()));
}
@BuildStep
void scanResources(
// TODO: We need to use this index instead of BeanArchiveIndexBuildItem to avoid build cycles. It it OK?
CombinedIndexBuildItem combinedIndexBuildItem,
BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformerBuildItemBuildProducer,
BuildProducer<ResourceScanningResultBuildItem> resourceScanningResultBuildItemBuildProducer) {
IndexView index = combinedIndexBuildItem.getIndex();
Collection<AnnotationInstance> paths = index.getAnnotations(QuarkusRestDotNames.PATH);
Collection<AnnotationInstance> allPaths = new ArrayList<>(paths);
if (allPaths.isEmpty()) {
// no detected @Path, bail out
return;
}
Map<DotName, ClassInfo> scannedResources = new HashMap<>();
Map<DotName, String> scannedResourcePaths = new HashMap<>();
Map<DotName, ClassInfo> possibleSubResources = new HashMap<>();
Map<DotName, String> pathInterfaces = new HashMap<>();
Map<DotName, MethodInfo> resourcesThatNeedCustomProducer = new HashMap<>();
Set<String> beanParams = new HashSet<>();
for (AnnotationInstance beanParamAnnotation : index.getAnnotations(QuarkusRestDotNames.BEAN_PARAM)) {
AnnotationTarget target = beanParamAnnotation.target();
// FIXME: this isn't right wrt generics
switch (target.kind()) {
case FIELD:
beanParams.add(target.asField().type().toString());
break;
case METHOD:
Type setterParamType = target.asMethod().parameters().get(0);
beanParams.add(setterParamType.toString());
break;
case METHOD_PARAMETER:
MethodInfo method = target.asMethodParameter().method();
int paramIndex = target.asMethodParameter().position();
Type paramType = method.parameters().get(paramIndex);
beanParams.add(paramType.toString());
break;
default:
break;
}
}
for (AnnotationInstance annotation : allPaths) {
if (annotation.target().kind() == AnnotationTarget.Kind.CLASS) {
ClassInfo clazz = annotation.target().asClass();
if (!Modifier.isInterface(clazz.flags())) {
scannedResources.put(clazz.name(), clazz);
scannedResourcePaths.put(clazz.name(), annotation.value().asString());
} else {
pathInterfaces.put(clazz.name(), annotation.value().asString());
}
MethodInfo ctor = hasJaxRsCtorParams(clazz);
if (ctor != null) {
resourcesThatNeedCustomProducer.put(clazz.name(), ctor);
}
}
}
if (!resourcesThatNeedCustomProducer.isEmpty()) {
annotationsTransformerBuildItemBuildProducer
.produce(new AnnotationsTransformerBuildItem(
new VetoingAnnotationTransformer(resourcesThatNeedCustomProducer.keySet())));
}
for (Map.Entry<DotName, String> i : pathInterfaces.entrySet()) {
for (ClassInfo clazz : index.getAllKnownImplementors(i.getKey())) {
if (!Modifier.isAbstract(clazz.flags())) {
if ((clazz.enclosingClass() == null || Modifier.isStatic(clazz.flags())) &&
clazz.enclosingMethod() == null) {
if (!scannedResources.containsKey(clazz.name())) {
scannedResources.put(clazz.name(), clazz);
scannedResourcePaths.put(clazz.name(), i.getValue());
}
}
}
}
}
resourceScanningResultBuildItemBuildProducer.produce(new ResourceScanningResultBuildItem(scannedResources,
scannedResourcePaths, possibleSubResources, pathInterfaces, resourcesThatNeedCustomProducer, beanParams));
}
@BuildStep
void generateCustomProducer(Optional<ResourceScanningResultBuildItem> resourceScanningResultBuildItem,
BuildProducer<GeneratedBeanBuildItem> generatedBeanBuildItemBuildProducer,
BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer) {
if (!resourceScanningResultBuildItem.isPresent()) {
return;
}
Map<DotName, MethodInfo> resourcesThatNeedCustomProducer = resourceScanningResultBuildItem.get()
.getResourcesThatNeedCustomProducer();
Set<String> beanParams = resourceScanningResultBuildItem.get()
.getBeanParams();
if (!resourcesThatNeedCustomProducer.isEmpty() || !beanParams.isEmpty()) {
CustomResourceProducersGenerator.generate(resourcesThatNeedCustomProducer, beanParams,
generatedBeanBuildItemBuildProducer,
additionalBeanBuildItemBuildProducer);
}
}
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
public FilterBuildItem setupEndpoints(BeanArchiveIndexBuildItem beanArchiveIndexBuildItem,
BeanContainerBuildItem beanContainerBuildItem,
QuarkusRestConfig config,
Optional<ResourceScanningResultBuildItem> resourceScanningResultBuildItem,
BuildProducer<GeneratedClassBuildItem> generatedClassBuildItemBuildProducer,
BuildProducer<BytecodeTransformerBuildItem> bytecodeTransformerBuildItemBuildProducer,
QuarkusRestRecorder recorder,
RecorderContext recorderContext,
ShutdownContextBuildItem shutdownContext,
HttpBuildTimeConfig vertxConfig) {
if (!resourceScanningResultBuildItem.isPresent()) {
// no detected @Path, bail out
return null;
}
IndexView index = beanArchiveIndexBuildItem.getIndex();
Collection<ClassInfo> containerRequestFilters = index
.getAllKnownImplementors(QuarkusRestDotNames.CONTAINER_REQUEST_FILTER);
Collection<ClassInfo> containerResponseFilters = index
.getAllKnownImplementors(QuarkusRestDotNames.CONTAINER_RESPONSE_FILTER);
Collection<ClassInfo> readerInterceptors = index
.getAllKnownImplementors(QuarkusRestDotNames.READER_INTERCEPTOR);
Collection<ClassInfo> writerInterceptors = index
.getAllKnownImplementors(QuarkusRestDotNames.WRITER_INTERCEPTOR);
Collection<ClassInfo> exceptionMappers = index
.getAllKnownImplementors(QuarkusRestDotNames.EXCEPTION_MAPPER);
Collection<ClassInfo> writers = index
.getAllKnownImplementors(QuarkusRestDotNames.MESSAGE_BODY_WRITER);
Collection<ClassInfo> readers = index
.getAllKnownImplementors(QuarkusRestDotNames.MESSAGE_BODY_READER);
Collection<ClassInfo> contextResolvers = index
.getAllKnownImplementors(QuarkusRestDotNames.CONTEXT_RESOLVER);
Collection<ClassInfo> features = index
.getAllKnownImplementors(QuarkusRestDotNames.FEATURE);
Collection<ClassInfo> dynamicFeatures = index
.getAllKnownImplementors(QuarkusRestDotNames.DYNAMIC_FEATURE);
Collection<ClassInfo> invocationCallbacks = index
.getAllKnownImplementors(QuarkusRestDotNames.INVOCATION_CALLBACK);
Map<DotName, ClassInfo> scannedResources = resourceScanningResultBuildItem.get().getScannedResources();
Map<DotName, String> scannedResourcePaths = resourceScanningResultBuildItem.get().getScannedResourcePaths();
Map<DotName, ClassInfo> possibleSubResources = resourceScanningResultBuildItem.get().getPossibleSubResources();
Map<DotName, String> pathInterfaces = resourceScanningResultBuildItem.get().getPathInterfaces();
Map<DotName, String> httpAnnotationToMethod = new HashMap<>(BUILTIN_HTTP_ANNOTATIONS_TO_METHOD);
Collection<AnnotationInstance> httpMethodInstances = index.getAnnotations(QuarkusRestDotNames.HTTP_METHOD);
for (AnnotationInstance httpMethodInstance : httpMethodInstances) {
if (httpMethodInstance.target().kind() != AnnotationTarget.Kind.CLASS) {
continue;
}
httpAnnotationToMethod.put(httpMethodInstance.target().asClass().name(), httpMethodInstance.value().asString());
}
Map<String, String> existingConverters = new HashMap<>();
List<ResourceClass> resourceClasses = new ArrayList<>();
List<ResourceClass> subResourceClasses = new ArrayList<>();
AdditionalReaders additionalReaders = new AdditionalReaders();
AdditionalWriters additionalWriters = new AdditionalWriters();
Map<String, InjectableBean> injectableBeans = new HashMap<>();
for (ClassInfo i : scannedResources.values()) {
ResourceClass endpoints = EndpointIndexer.createEndpoints(index, i,
beanContainerBuildItem.getValue(), generatedClassBuildItemBuildProducer,
bytecodeTransformerBuildItemBuildProducer, recorder, existingConverters,
scannedResourcePaths, config, additionalReaders, httpAnnotationToMethod, injectableBeans,
additionalWriters);
if (endpoints != null) {
resourceClasses.add(endpoints);
}
}
List<RestClientInterface> clientDefinitions = new ArrayList<>();
for (Map.Entry<DotName, String> i : pathInterfaces.entrySet()) {
ClassInfo clazz = index.getClassByName(i.getKey());
//these interfaces can also be clients
//so we generate client proxies for them
RestClientInterface clientProxy = EndpointIndexer.createClientProxy(index, clazz,
generatedClassBuildItemBuildProducer, bytecodeTransformerBuildItemBuildProducer, recorder,
existingConverters,
i.getValue(), config, additionalWriters, httpAnnotationToMethod, injectableBeans, additionalReaders);
if (clientProxy != null) {
clientDefinitions.add(clientProxy);
}
}
Map<String, RuntimeValue<Function<WebTarget, ?>>> clientImplementations = generateClientInvokers(recorderContext,
clientDefinitions, generatedClassBuildItemBuildProducer);
//now index possible sub resources. These are all classes that have method annotations
//that are not annotated @Path
Deque<ClassInfo> toScan = new ArrayDeque<>();
for (DotName methodAnnotation : httpAnnotationToMethod.keySet()) {
for (AnnotationInstance instance : index.getAnnotations(methodAnnotation)) {
MethodInfo method = instance.target().asMethod();
ClassInfo classInfo = method.declaringClass();
toScan.add(classInfo);
}
}
while (!toScan.isEmpty()) {
ClassInfo classInfo = toScan.poll();
if (scannedResources.containsKey(classInfo.name()) ||
pathInterfaces.containsKey(classInfo.name()) ||
possibleSubResources.containsKey(classInfo.name())) {
continue;
}
possibleSubResources.put(classInfo.name(), classInfo);
ResourceClass endpoints = EndpointIndexer.createEndpoints(index, classInfo,
beanContainerBuildItem.getValue(), generatedClassBuildItemBuildProducer,
bytecodeTransformerBuildItemBuildProducer, recorder, existingConverters,
scannedResourcePaths, config, additionalReaders, httpAnnotationToMethod, injectableBeans,
additionalWriters);
if (endpoints != null) {
subResourceClasses.add(endpoints);
}
//we need to also look for all sub classes and interfaces
//they may have type variables that need to be handled
toScan.addAll(index.getKnownDirectImplementors(classInfo.name()));
toScan.addAll(index.getKnownDirectSubclasses(classInfo.name()));
}
ResourceInterceptors interceptors = new ResourceInterceptors();
for (ClassInfo filterClass : containerRequestFilters) {
if (filterClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceRequestInterceptor interceptor = new ResourceRequestInterceptor();
interceptor.setFactory(recorder.factory(filterClass.name().toString(),
beanContainerBuildItem.getValue()));
interceptor.setPreMatching(filterClass.classAnnotation(QuarkusRestDotNames.PRE_MATCHING) != null);
if (interceptor.isPreMatching()) {
interceptors.addResourcePreMatchInterceptor(interceptor);
} else {
Set<String> nameBindingNames = EndpointIndexer.nameBindingNames(filterClass, index);
if (nameBindingNames.isEmpty()) {
interceptors.addGlobalRequestInterceptor(interceptor);
} else {
interceptor.setNameBindingNames(nameBindingNames);
interceptors.addNameRequestInterceptor(interceptor);
}
}
AnnotationInstance priorityInstance = filterClass.classAnnotation(QuarkusRestDotNames.PRIORITY);
if (priorityInstance != null) {
interceptor.setPriority(priorityInstance.value().asInt());
}
}
}
for (ClassInfo filterClass : containerResponseFilters) {
if (filterClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceResponseInterceptor interceptor = new ResourceResponseInterceptor();
interceptor.setFactory(recorder.factory(filterClass.name().toString(),
beanContainerBuildItem.getValue()));
Set<String> nameBindingNames = EndpointIndexer.nameBindingNames(filterClass, index);
if (nameBindingNames.isEmpty()) {
interceptors.addGlobalResponseInterceptor(interceptor);
} else {
interceptor.setNameBindingNames(nameBindingNames);
interceptors.addNameResponseInterceptor(interceptor);
}
AnnotationInstance priorityInstance = filterClass.classAnnotation(QuarkusRestDotNames.PRIORITY);
if (priorityInstance != null) {
interceptor.setPriority(priorityInstance.value().asInt());
}
}
}
for (ClassInfo filterClass : writerInterceptors) {
if (filterClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceWriterInterceptor interceptor = new ResourceWriterInterceptor();
interceptor.setFactory(recorder.factory(filterClass.name().toString(),
beanContainerBuildItem.getValue()));
Set<String> nameBindingNames = EndpointIndexer.nameBindingNames(filterClass, index);
if (nameBindingNames.isEmpty()) {
interceptors.addGlobalWriterInterceptor(interceptor);
} else {
interceptor.setNameBindingNames(nameBindingNames);
interceptors.addNameWriterInterceptor(interceptor);
}
AnnotationInstance priorityInstance = filterClass.classAnnotation(QuarkusRestDotNames.PRIORITY);
if (priorityInstance != null) {
interceptor.setPriority(priorityInstance.value().asInt());
}
}
}
for (ClassInfo filterClass : readerInterceptors) {
if (filterClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceReaderInterceptor interceptor = new ResourceReaderInterceptor();
interceptor.setFactory(recorder.factory(filterClass.name().toString(),
beanContainerBuildItem.getValue()));
Set<String> nameBindingNames = EndpointIndexer.nameBindingNames(filterClass, index);
if (nameBindingNames.isEmpty()) {
interceptors.addGlobalReaderInterceptor(interceptor);
} else {
interceptor.setNameBindingNames(nameBindingNames);
interceptors.addNameReaderInterceptor(interceptor);
}
AnnotationInstance priorityInstance = filterClass.classAnnotation(QuarkusRestDotNames.PRIORITY);
if (priorityInstance != null) {
interceptor.setPriority(priorityInstance.value().asInt());
}
}
}
ExceptionMapping exceptionMapping = new ExceptionMapping();
for (ClassInfo mapperClass : exceptionMappers) {
if (mapperClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
List<Type> typeParameters = JandexUtil.resolveTypeParameters(mapperClass.name(),
QuarkusRestDotNames.EXCEPTION_MAPPER,
index);
ResourceExceptionMapper<Throwable> mapper = new ResourceExceptionMapper<>();
mapper.setFactory(recorder.factory(mapperClass.name().toString(),
beanContainerBuildItem.getValue()));
recorder.registerExceptionMapper(exceptionMapping, typeParameters.get(0).name().toString(), mapper);
}
}
ContextResolvers ctxResolvers = new ContextResolvers();
for (ClassInfo resolverClass : contextResolvers) {
if (resolverClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
List<Type> typeParameters = JandexUtil.resolveTypeParameters(resolverClass.name(),
QuarkusRestDotNames.CONTEXT_RESOLVER,
index);
ResourceContextResolver resolver = new ResourceContextResolver();
resolver.setFactory(recorder.factory(resolverClass.name().toString(),
beanContainerBuildItem.getValue()));
resolver.setMediaTypeStrings(getProducesMediaTypes(resolverClass));
recorder.registerContextResolver(ctxResolvers, typeParameters.get(0).name().toString(), resolver);
}
}
Features feats = new Features();
for (ClassInfo featureClass : features) {
if (featureClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceFeature resourceFeature = new ResourceFeature();
resourceFeature.setFactory(recorder.factory(featureClass.name().toString(),
beanContainerBuildItem.getValue()));
recorder.registerFeature(feats, resourceFeature);
}
}
DynamicFeatures dynamicFeats = new DynamicFeatures();
for (ClassInfo dynamicFeatureClass : dynamicFeatures) {
if (dynamicFeatureClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceDynamicFeature resourceFeature = new ResourceDynamicFeature();
resourceFeature.setFactory(recorder.factory(dynamicFeatureClass.name().toString(),
beanContainerBuildItem.getValue()));
recorder.registerDynamicFeature(dynamicFeats, resourceFeature);
}
}
Serialisers serialisers = new Serialisers();
for (ClassInfo writerClass : writers) {
if (writerClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
ResourceWriter writer = new ResourceWriter();
AnnotationInstance producesAnnotation = writerClass.classAnnotation(QuarkusRestDotNames.PRODUCES);
if (producesAnnotation != null) {
writer.setMediaTypeStrings(Arrays.asList(producesAnnotation.value().asStringArray()));
}
List<Type> typeParameters = JandexUtil.resolveTypeParameters(writerClass.name(),
QuarkusRestDotNames.MESSAGE_BODY_WRITER,
index);
writer.setFactory(recorder.factory(writerClass.name().toString(),
beanContainerBuildItem.getValue()));
AnnotationInstance constrainedToInstance = writerClass.classAnnotation(QuarkusRestDotNames.CONSTRAINED_TO);
if (constrainedToInstance != null) {
writer.setConstraint(RuntimeType.valueOf(constrainedToInstance.value().asEnum()));
}
recorder.registerWriter(serialisers, typeParameters.get(0).name().toString(), writer);
}
}
for (ClassInfo readerClass : readers) {
if (readerClass.classAnnotation(QuarkusRestDotNames.PROVIDER) != null) {
List<Type> typeParameters = JandexUtil.resolveTypeParameters(readerClass.name(),
QuarkusRestDotNames.MESSAGE_BODY_READER,
index);
ResourceReader reader = new ResourceReader();
reader.setFactory(recorder.factory(readerClass.name().toString(),
beanContainerBuildItem.getValue()));
AnnotationInstance constrainedToInstance = readerClass.classAnnotation(QuarkusRestDotNames.CONSTRAINED_TO);
if (constrainedToInstance != null) {
reader.setConstraint(RuntimeType.valueOf(constrainedToInstance.value().asEnum()));
}
recorder.registerReader(serialisers, typeParameters.get(0).name().toString(), reader);
}
}
GenericTypeMapping genericTypeMapping = new GenericTypeMapping();
for (ClassInfo invocationCallback : invocationCallbacks) {
try {
List<Type> typeParameters = JandexUtil.resolveTypeParameters(invocationCallback.name(),
QuarkusRestDotNames.INVOCATION_CALLBACK, index);
recorder.registerInvocationHandlerGenericType(genericTypeMapping, invocationCallback.name().toString(),
typeParameters.get(0).name().toString());
} catch (Exception ignored) {
}
}
// built-ins
// registerWriter(recorder, serialisers, Object.class, JsonbMessageBodyWriter.class, beanContainerBuildItem.getValue(),
// false);
registerWriter(recorder, serialisers, Object.class, VertxJsonMessageBodyWriter.class, beanContainerBuildItem.getValue(),
MediaType.APPLICATION_JSON);
registerWriter(recorder, serialisers, String.class, StringMessageBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN);
registerWriter(recorder, serialisers, Number.class, StringMessageBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN);
registerWriter(recorder, serialisers, Boolean.class, StringMessageBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN);
registerWriter(recorder, serialisers, Character.class, StringMessageBodyHandler.class,
beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN);
registerWriter(recorder, serialisers, Object.class, StringMessageBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.WILDCARD);
registerWriter(recorder, serialisers, char[].class, CharArrayMessageBodyHandler.class,
beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN);
registerWriter(recorder, serialisers, byte[].class, ByteArrayMessageBodyHandler.class,
beanContainerBuildItem.getValue(),
MediaType.WILDCARD);
registerWriter(recorder, serialisers, Buffer.class, VertxBufferMessageBodyWriter.class,
beanContainerBuildItem.getValue(),
MediaType.WILDCARD);
registerWriter(recorder, serialisers, MultivaluedMap.class, FormUrlEncodedProvider.class,
beanContainerBuildItem.getValue(), MediaType.APPLICATION_FORM_URLENCODED);
registerWriter(recorder, serialisers, Reader.class, ReaderBodyHandler.class,
beanContainerBuildItem.getValue(), MediaType.TEXT_PLAIN);
registerWriter(recorder, serialisers, File.class, FileBodyHandler.class,
beanContainerBuildItem.getValue(), MediaType.TEXT_PLAIN);
registerReader(recorder, serialisers, String.class, StringMessageBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.WILDCARD, null);
registerReader(recorder, serialisers, Reader.class, ReaderBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN, null);
registerReader(recorder, serialisers, File.class, FileBodyHandler.class, beanContainerBuildItem.getValue(),
MediaType.TEXT_PLAIN, null);
// the client always expects these to exist
additionalReaders.add(ByteArrayMessageBodyHandler.class, MediaType.WILDCARD, byte[].class, RuntimeType.CLIENT);
additionalReaders.add(FormUrlEncodedProvider.class, MediaType.APPLICATION_FORM_URLENCODED, MultivaluedMap.class,
RuntimeType.CLIENT);
//TODO: Do the Jsonb readers always make sense?
registerReader(recorder, serialisers, Object.class, JsonbMessageBodyReader.class, beanContainerBuildItem.getValue(),
MediaType.APPLICATION_JSON, null);
for (AdditionalReaders.Entry additionalReader : additionalReaders.get()) {
registerReader(recorder, serialisers, additionalReader.getEntityClass(), additionalReader.getReaderClass(),
beanContainerBuildItem.getValue(), additionalReader.getMediaType(), additionalReader.getConstraint());
}
for (AdditionalWriters.Entry<?> entry : additionalWriters.get()) {
registerWriter(recorder, serialisers, entry.getEntityClass(), entry.getWriterClass(),
beanContainerBuildItem.getValue(), entry.getMediaType());
}
return new FilterBuildItem(
recorder.handler(interceptors.sort(), exceptionMapping, ctxResolvers, feats, dynamicFeats,
serialisers, resourceClasses, subResourceClasses,
beanContainerBuildItem.getValue(), shutdownContext, config, vertxConfig, clientImplementations,
genericTypeMapping),
10);
}
private void registerWriter(QuarkusRestRecorder recorder, Serialisers serialisers, Class<?> entityClass,
Class<? extends MessageBodyWriter<?>> writerClass, BeanContainer beanContainer,
String mediaType) {
ResourceWriter writer = new ResourceWriter();
writer.setFactory(recorder.factory(writerClass.getName(), beanContainer));
writer.setMediaTypeStrings(Collections.singletonList(mediaType));
recorder.registerWriter(serialisers, entityClass.getName(), writer);
}
private <T> void registerReader(QuarkusRestRecorder recorder, Serialisers serialisers, Class<T> entityClass,
Class<? extends MessageBodyReader<T>> readerClass, BeanContainer beanContainer, String mediaType,
RuntimeType constraint) {
ResourceReader reader = new ResourceReader();
reader.setFactory(recorder.factory(readerClass.getName(), beanContainer));
reader.setMediaTypeStrings(Collections.singletonList(mediaType));
reader.setConstraint(constraint);
recorder.registerReader(serialisers, entityClass.getName(), reader);
}
private List<String> getProducesMediaTypes(ClassInfo classInfo) {
AnnotationInstance produces = classInfo.classAnnotation(QuarkusRestDotNames.PRODUCES);
if (produces == null) {
return Collections.emptyList();
}
return Arrays.asList(produces.value().asStringArray());
}
@BuildStep
void beanDefiningAnnotations(BuildProducer<BeanDefiningAnnotationBuildItem> beanDefiningAnnotations) {
beanDefiningAnnotations
.produce(new BeanDefiningAnnotationBuildItem(QuarkusRestDotNames.PATH, BuiltinScope.SINGLETON.getName()));
beanDefiningAnnotations
.produce(new BeanDefiningAnnotationBuildItem(QuarkusRestDotNames.APPLICATION_PATH,
BuiltinScope.SINGLETON.getName()));
beanDefiningAnnotations
.produce(new BeanDefiningAnnotationBuildItem(QuarkusRestDotNames.PROVIDER,
BuiltinScope.SINGLETON.getName()));
}
private Map<String, RuntimeValue<Function<WebTarget, ?>>> generateClientInvokers(RecorderContext recorderContext,
List<RestClientInterface> clientDefinitions,
BuildProducer<GeneratedClassBuildItem> generatedClassBuildItemBuildProducer) {
Map<String, RuntimeValue<Function<WebTarget, ?>>> ret = new HashMap<>();
for (RestClientInterface restClientInterface : clientDefinitions) {
boolean subResource = false;
//if the interface contains sub resource locator methods we ignore it
for (ResourceMethod i : restClientInterface.getMethods()) {
if (i.getHttpMethod() == null) {
subResource = true;
}
break;
}
if (subResource) {
continue;
}
String name = restClientInterface.getClassName() + "$$QuarkusRestClientInterface";
MethodDescriptor ctorDesc = MethodDescriptor.ofConstructor(name, WebTarget.class.getName());
try (ClassCreator c = new ClassCreator(new GeneratedClassGizmoAdaptor(generatedClassBuildItemBuildProducer, true),
name, null, Object.class.getName(), restClientInterface.getClassName())) {
FieldDescriptor target = FieldDescriptor.of(name, "target", WebTarget.class);
c.getFieldCreator(target).setModifiers(Modifier.FINAL);
MethodCreator ctor = c.getMethodCreator(ctorDesc);
ctor.invokeSpecialMethod(MethodDescriptor.ofConstructor(Object.class), ctor.getThis());
ResultHandle res = ctor.invokeInterfaceMethod(
MethodDescriptor.ofMethod(WebTarget.class, "path", WebTarget.class, String.class),
ctor.getMethodParam(0), ctor.load(restClientInterface.getPath()));
ctor.writeInstanceField(target, ctor.getThis(), res);
ctor.returnValue(null);
for (ResourceMethod method : restClientInterface.getMethods()) {
MethodCreator m = c.getMethodCreator(method.getName(), method.getReturnType(),
Arrays.stream(method.getParameters()).map(s -> s.type).toArray());
ResultHandle tg = m.readInstanceField(target, m.getThis());
if (method.getPath() != null) {
tg = m.invokeInterfaceMethod(MethodDescriptor.ofMethod(WebTarget.class, "path", WebTarget.class,
String.class), tg, m.load(method.getPath()));
}
for (int i = 0; i < method.getParameters().length; ++i) {
MethodParameter p = method.getParameters()[i];
if (p.parameterType == ParameterType.QUERY) {
//TODO: converters
ResultHandle array = m.newArray(Object.class, 1);
m.writeArrayValue(array, 0, m.getMethodParam(i));
tg = m.invokeInterfaceMethod(
MethodDescriptor.ofMethod(WebTarget.class, "queryParam", WebTarget.class,
String.class, Object[].class),
tg, m.load(p.name), array);
}
}
ResultHandle builder;
if (method.getProduces() == null || method.getProduces().length == 0) {
builder = m.invokeInterfaceMethod(
MethodDescriptor.ofMethod(WebTarget.class, "request", Invocation.Builder.class), tg);
} else {
ResultHandle array = m.newArray(String.class, method.getProduces().length);
for (int i = 0; i < method.getProduces().length; ++i) {
m.writeArrayValue(array, i, m.load(method.getProduces()[i]));
}
builder = m.invokeInterfaceMethod(
MethodDescriptor.ofMethod(WebTarget.class, "request", Invocation.Builder.class, String[].class),
tg, array);
}
//TODO: async return types
ResultHandle result = m
.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Invocation.Builder.class, "method", Object.class, String.class,
Class.class),
builder, m.load(method.getHttpMethod()), m.loadClass(method.getSimpleReturnType()));
m.returnValue(result);
}
}
String creatorName = restClientInterface.getClassName() + "$$QuarkusRestClientInterfaceCreator";
try (ClassCreator c = new ClassCreator(new GeneratedClassGizmoAdaptor(generatedClassBuildItemBuildProducer, true),
creatorName, null, Object.class.getName(), Function.class.getName())) {
MethodCreator apply = c
.getMethodCreator(MethodDescriptor.ofMethod(creatorName, "apply", Object.class, Object.class));
apply.returnValue(apply.newInstance(ctorDesc, apply.getMethodParam(0)));
}
ret.put(restClientInterface.getClassName(), recorderContext.newInstance(creatorName));
}
return ret;
}
private MethodInfo hasJaxRsCtorParams(ClassInfo classInfo) {
List<MethodInfo> methods = classInfo.methods();
List<MethodInfo> ctors = new ArrayList<>();
for (MethodInfo method : methods) {
if (method.name().equals("<init>")) {
ctors.add(method);
}
}
if (ctors.size() != 1) { // we only need to deal with a single ctor here
return null;
}
MethodInfo ctor = ctors.get(0);
if (ctor.parameters().size() == 0) { // default ctor - we don't need to do anything
return null;
}
boolean needsHandling = false;
for (DotName dotName : QuarkusRestDotNames.RESOURCE_CTOR_PARAMS_THAT_NEED_HANDLING) {
if (ctor.hasAnnotation(dotName)) {
needsHandling = true;
break;
}
}
return needsHandling ? ctor : null;
}
}
|
package org.ovirt.engine.ui.uicommonweb.models;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.ovirt.engine.ui.uicommonweb.models.vms.ConsoleModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.RdpConsoleModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.SpiceConsoleModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.VncConsoleModel;
/**
* Enum representing console protocol.
* Console protocol is determined by it's backing class and priority (if a VM supports more than one protocol at the
* same time, priority determines precedence of protocols).
* Protocols with higher number have higher priority.
*/
public enum ConsoleProtocol {
SPICE(SpiceConsoleModel.class, 3),
VNC(VncConsoleModel.class, 2),
RDP(RdpConsoleModel.class, 1);
private final Class<? extends ConsoleModel> model;
private final int priority;
private ConsoleProtocol(Class<? extends ConsoleModel> model, int priority) {
this.model = model;
this.priority = priority;
}
public boolean isBackedBy(Class<? extends ConsoleModel> model) {
return this.model.equals(model);
}
public static ConsoleProtocol getProtocolByModel(Class<? extends ConsoleModel> model) {
for (ConsoleProtocol value : values()) {
if (value.isBackedBy(model)) {
return value;
}
}
return null;
}
static class PriorityComparator implements Comparator<ConsoleProtocol>, Serializable {
private static final long serialVersionUID = -4511422219352593185L;
@Override
public int compare(ConsoleProtocol fst, ConsoleProtocol snd) {
if (fst == null && snd == null) {
return 0;
}
if (fst == null) {
return -1;
}
if (snd == null) {
return 1;
}
return fst.priority - snd.priority;
}
}
public static List<ConsoleProtocol> getProtocolsByPriority() {
List<ConsoleProtocol> consoleProtocols = Arrays.asList(ConsoleProtocol.values());
Collections.sort(consoleProtocols, new PriorityComparator());
return consoleProtocols;
}
public Class getBackingClass() {
return model;
}
}
|
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.AddVmTemplateParameters;
import org.ovirt.engine.core.common.action.AttachEntityToTagParameters;
import org.ovirt.engine.core.common.action.ChangeDiskCommandParameters;
import org.ovirt.engine.core.common.action.ChangeVMClusterParameters;
import org.ovirt.engine.core.common.action.MigrateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmToServerParameters;
import org.ovirt.engine.core.common.action.MoveVmParameters;
import org.ovirt.engine.core.common.action.RemoveVmParameters;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.SetHaMaintenanceParameters;
import org.ovirt.engine.core.common.action.ShutdownVmParameters;
import org.ovirt.engine.core.common.action.StopVmParameters;
import org.ovirt.engine.core.common.action.StopVmTypeEnum;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VmManagementParametersBase;
import org.ovirt.engine.core.common.action.VmOperationParameterBase;
import org.ovirt.engine.core.common.businessentities.HaMaintenanceMode;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.Tags;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VmType;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskStorageType;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.utils.ObjectUtils;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.searchbackend.SearchObjects;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.BaseCommandTarget;
import org.ovirt.engine.ui.uicommonweb.Cloner;
import org.ovirt.engine.ui.uicommonweb.ConsoleOptionsFrontendPersister.ConsoleContext;
import org.ovirt.engine.ui.uicommonweb.ErrorPopupManager;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.TagsEqualityComparer;
import org.ovirt.engine.ui.uicommonweb.TypeResolver;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.builders.BuilderExecutor;
import org.ovirt.engine.ui.uicommonweb.builders.template.UnitToAddVmTemplateParametersBuilder;
import org.ovirt.engine.ui.uicommonweb.builders.template.VmBaseToVmBaseForTemplateCompositeBaseBuilder;
import org.ovirt.engine.ui.uicommonweb.builders.vm.CommonUnitToVmBaseBuilder;
import org.ovirt.engine.ui.uicommonweb.builders.vm.UnitToGraphicsDeviceParamsBuilder;
import org.ovirt.engine.ui.uicommonweb.builders.vm.VmIconUnitAndVmToParameterBuilder;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.ConsolePopupModel;
import org.ovirt.engine.ui.uicommonweb.models.ConsolesFactory;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.HasEntity;
import org.ovirt.engine.ui.uicommonweb.models.ISupportSystemTreeContext;
import org.ovirt.engine.ui.uicommonweb.models.PublicKeyModel;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.VmConsoles;
import org.ovirt.engine.ui.uicommonweb.models.configure.ChangeCDModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.scheduling.affinity_groups.list.VmAffinityGroupListModel;
import org.ovirt.engine.ui.uicommonweb.models.tags.TagListModel;
import org.ovirt.engine.ui.uicommonweb.models.tags.TagModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.VmBaseListModel;
import org.ovirt.engine.ui.uicommonweb.models.userportal.AttachCdModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.hostdev.VmHostDeviceListModel;
import org.ovirt.engine.ui.uicommonweb.place.WebAdminApplicationPlaces;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleQueryAsyncResult;
import org.ovirt.engine.ui.uicompat.ICancelable;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleQueryAsyncCallback;
import org.ovirt.engine.ui.uicompat.ObservableCollection;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.uicompat.UIConstants;
import com.google.inject.Inject;
import com.google.inject.Provider;
public class VmListModel<E> extends VmBaseListModel<E, VM> implements ISupportSystemTreeContext, ICancelable {
public static final String CMD_CONFIGURE_VMS_TO_IMPORT = "ConfigureVmsToImport"; //$NON-NLS-1$
public static final String CMD_CANCEL = "Cancel"; //$NON-NLS-1$
private static final String CMD_BACK = "Back"; //$NON-NLS-1$
private static final String CMD_IMPORT = "Import"; //$NON-NLS-1$
private final UIConstants constants = ConstantsManager.getInstance().getConstants();
final Provider<ImportVmsModel> importVmsModelProvider;
private UICommand importVmCommand;
public UICommand getImportVmCommand() {
return importVmCommand;
}
public void setImportVmCommand(UICommand importVmCommand) {
this.importVmCommand = importVmCommand;
}
private UICommand cloneVmCommand;
public UICommand getCloneVmCommand() {
return cloneVmCommand;
}
public void setCloneVmCommand(UICommand cloneVmCommand) {
this.cloneVmCommand = cloneVmCommand;
}
private UICommand newVMCommand;
private final static String SHUTDOWN = "Shutdown"; //$NON-NLS-1$
private final static String STOP = "Stop"; //$NON-NLS-1$
private final static String REBOOT = "Reboot"; //$NON-NLS-1$
public UICommand getNewVmCommand() {
return newVMCommand;
}
private void setNewVmCommand(UICommand newVMCommand) {
this.newVMCommand = newVMCommand;
}
private UICommand privateEditCommand;
@Override
public UICommand getEditCommand() {
return privateEditCommand;
}
private void setEditCommand(UICommand value) {
privateEditCommand = value;
}
private UICommand privateRemoveCommand;
public UICommand getRemoveCommand() {
return privateRemoveCommand;
}
private void setRemoveCommand(UICommand value) {
privateRemoveCommand = value;
}
private UICommand privateRunCommand;
public UICommand getRunCommand() {
return privateRunCommand;
}
private void setRunCommand(UICommand value) {
privateRunCommand = value;
}
private UICommand privatePauseCommand;
public UICommand getPauseCommand() {
return privatePauseCommand;
}
private void setPauseCommand(UICommand value) {
privatePauseCommand = value;
}
private UICommand privateStopCommand;
public UICommand getStopCommand() {
return privateStopCommand;
}
private void setStopCommand(UICommand value) {
privateStopCommand = value;
}
private UICommand privateShutdownCommand;
public UICommand getShutdownCommand() {
return privateShutdownCommand;
}
private void setShutdownCommand(UICommand value) {
privateShutdownCommand = value;
}
private UICommand privateRebootCommand;
public UICommand getRebootCommand() {
return privateRebootCommand;
}
public void setRebootCommand(UICommand value) {
privateRebootCommand = value;
}
private UICommand privateCancelMigrateCommand;
public UICommand getCancelMigrateCommand() {
return privateCancelMigrateCommand;
}
private void setCancelMigrateCommand(UICommand value) {
privateCancelMigrateCommand = value;
}
private UICommand cancelConvertCommand;
public UICommand getCancelConvertCommand() {
return cancelConvertCommand;
}
private void setCancelConvertCommand(UICommand value) {
cancelConvertCommand = value;
}
private UICommand privateMigrateCommand;
public UICommand getMigrateCommand() {
return privateMigrateCommand;
}
private void setMigrateCommand(UICommand value) {
privateMigrateCommand = value;
}
private UICommand privateNewTemplateCommand;
public UICommand getNewTemplateCommand() {
return privateNewTemplateCommand;
}
private void setNewTemplateCommand(UICommand value) {
privateNewTemplateCommand = value;
}
private UICommand privateRunOnceCommand;
public UICommand getRunOnceCommand() {
return privateRunOnceCommand;
}
private void setRunOnceCommand(UICommand value) {
privateRunOnceCommand = value;
}
private UICommand privateExportCommand;
public UICommand getExportCommand() {
return privateExportCommand;
}
private void setExportCommand(UICommand value) {
privateExportCommand = value;
}
private UICommand privateCreateSnapshotCommand;
public UICommand getCreateSnapshotCommand() {
return privateCreateSnapshotCommand;
}
private void setCreateSnapshotCommand(UICommand value) {
privateCreateSnapshotCommand = value;
}
private UICommand privateRetrieveIsoImagesCommand;
public UICommand getRetrieveIsoImagesCommand() {
return privateRetrieveIsoImagesCommand;
}
private void setRetrieveIsoImagesCommand(UICommand value) {
privateRetrieveIsoImagesCommand = value;
}
private UICommand privateGuideCommand;
public UICommand getGuideCommand() {
return privateGuideCommand;
}
private void setGuideCommand(UICommand value) {
privateGuideCommand = value;
}
private UICommand privateChangeCdCommand;
public UICommand getChangeCdCommand() {
return privateChangeCdCommand;
}
private void setChangeCdCommand(UICommand value) {
privateChangeCdCommand = value;
}
private UICommand privateAssignTagsCommand;
public UICommand getAssignTagsCommand() {
return privateAssignTagsCommand;
}
private void setAssignTagsCommand(UICommand value) {
privateAssignTagsCommand = value;
}
private UICommand privateEnableGlobalHaMaintenanceCommand;
public UICommand getEnableGlobalHaMaintenanceCommand() {
return privateEnableGlobalHaMaintenanceCommand;
}
private void setEnableGlobalHaMaintenanceCommand(UICommand value) {
privateEnableGlobalHaMaintenanceCommand = value;
}
private UICommand privateDisableGlobalHaMaintenanceCommand;
public UICommand getDisableGlobalHaMaintenanceCommand() {
return privateDisableGlobalHaMaintenanceCommand;
}
private void setDisableGlobalHaMaintenanceCommand(UICommand value) {
privateDisableGlobalHaMaintenanceCommand = value;
}
UICommand editConsoleCommand;
public void setEditConsoleCommand(UICommand editConsoleCommand) {
this.editConsoleCommand = editConsoleCommand;
}
public UICommand getEditConsoleCommand() {
return editConsoleCommand;
}
public UICommand consoleConnectCommand;
public UICommand getConsoleConnectCommand() {
return consoleConnectCommand;
}
public void setConsoleConnectCommand(UICommand consoleConnectCommand) {
this.consoleConnectCommand = consoleConnectCommand;
}
private UICommand setConsoleKeyCommand;
public UICommand getSetConsoleKeyCommand() {
return setConsoleKeyCommand;
}
public void setSetConsoleKeyCommand(UICommand setConsoleKeyCommand) {
this.setConsoleKeyCommand = setConsoleKeyCommand;
}
public ObservableCollection<ChangeCDModel> isoImages;
public ObservableCollection<ChangeCDModel> getIsoImages() {
return isoImages;
}
private void setIsoImages(ObservableCollection<ChangeCDModel> value) {
if ((isoImages == null && value != null) || (isoImages != null && !isoImages.equals(value))) {
isoImages = value;
onPropertyChanged(new PropertyChangedEventArgs("IsoImages")); //$NON-NLS-1$
}
}
private Object privateGuideContext;
public Object getGuideContext() {
return privateGuideContext;
}
public void setGuideContext(Object value) {
privateGuideContext = value;
}
private final ConsolesFactory consolesFactory;
private ErrorPopupManager errorPopupManager;
/** The edited VM could be different than the selected VM in the grid
* when the VM has next-run configuration */
private VM editedVm;
@Inject
public VmListModel(final VmGeneralModel vmGeneralModel, final VmInterfaceListModel vmInterfaceListModel,
final VmDiskListModel vmDiskListModel, final VmSnapshotListModel vmSnapshotListModel,
final VmEventListModel vmEventListModel, final VmAppListModel<VM> vmAppListModel,
final PermissionListModel<VM> permissionListModel, final VmAffinityGroupListModel vmAffinityGroupListModel,
final VmGuestInfoModel vmGuestInfoModel, final Provider<ImportVmsModel> importVmsModelProvider,
final VmHostDeviceListModel vmHostDeviceListModel, final VmDevicesListModel vmDevicesListModel) {
setDetailList(vmGeneralModel, vmInterfaceListModel, vmDiskListModel, vmSnapshotListModel, vmEventListModel,
vmAppListModel, permissionListModel, vmAffinityGroupListModel, vmGuestInfoModel, vmHostDeviceListModel,
vmDevicesListModel);
this.importVmsModelProvider = importVmsModelProvider;
setTitle(ConstantsManager.getInstance().getConstants().virtualMachinesTitle());
setHelpTag(HelpTag.virtual_machines);
setApplicationPlace(WebAdminApplicationPlaces.virtualMachineMainTabPlace);
setHashName("virtual_machines"); //$NON-NLS-1$
setDefaultSearchString("Vms:"); //$NON-NLS-1$
setSearchString(getDefaultSearchString());
setSearchObjects(new String[] { SearchObjects.VM_OBJ_NAME, SearchObjects.VM_PLU_OBJ_NAME });
setAvailableInModes(ApplicationMode.VirtOnly);
consolesFactory = new ConsolesFactory(ConsoleContext.WA, this);
setConsoleHelpers();
setNewVmCommand(new UICommand("NewVm", this)); //$NON-NLS-1$
setImportVmCommand(new UICommand("ImportVm", this)); //$NON-NLS-1$
setCloneVmCommand(new UICommand("CloneVm", this)); //$NON-NLS-1$
setEditCommand(new UICommand("Edit", this)); //$NON-NLS-1$
setRemoveCommand(new UICommand("Remove", this)); //$NON-NLS-1$
setRunCommand(new UICommand("Run", this, true)); //$NON-NLS-1$
setPauseCommand(new UICommand("Pause", this)); //$NON-NLS-1$
setStopCommand(new UICommand("Stop", this)); //$NON-NLS-1$
setShutdownCommand(new UICommand("Shutdown", this)); //$NON-NLS-1$
setRebootCommand(new UICommand("Reboot", this)); //$NON-NLS-1$
setEditConsoleCommand(new UICommand("EditConsoleCommand", this)); //$NON-NLS-1$
setConsoleConnectCommand(new UICommand("ConsoleConnectCommand", this)); //$NON-NLS-1$
setMigrateCommand(new UICommand("Migrate", this)); //$NON-NLS-1$
setCancelMigrateCommand(new UICommand("CancelMigration", this)); //$NON-NLS-1$
setCancelConvertCommand(new UICommand("CancelConversion", this)); //$NON-NLS-1$
setNewTemplateCommand(new UICommand("NewTemplate", this)); //$NON-NLS-1$
setRunOnceCommand(new UICommand("RunOnce", this)); //$NON-NLS-1$
setExportCommand(new UICommand("Export", this)); //$NON-NLS-1$
setCreateSnapshotCommand(new UICommand("CreateSnapshot", this)); //$NON-NLS-1$
setGuideCommand(new UICommand("Guide", this)); //$NON-NLS-1$
setRetrieveIsoImagesCommand(new UICommand("RetrieveIsoImages", this)); //$NON-NLS-1$
setChangeCdCommand(new UICommand("ChangeCD", this)); //$NON-NLS-1$
setAssignTagsCommand(new UICommand("AssignTags", this)); //$NON-NLS-1$
setEnableGlobalHaMaintenanceCommand(new UICommand("EnableGlobalHaMaintenance", this)); //$NON-NLS-1$
setDisableGlobalHaMaintenanceCommand(new UICommand("DisableGlobalHaMaintenance", this)); //$NON-NLS-1$
setSetConsoleKeyCommand(new UICommand("SetConsoleKey", this)); //$NON-NLS-1$
setIsoImages(new ObservableCollection<ChangeCDModel>());
ChangeCDModel tempVar = new ChangeCDModel();
tempVar.setTitle(ConstantsManager.getInstance().getConstants().retrievingCDsTitle());
getIsoImages().add(tempVar);
updateActionsAvailability();
getSearchNextPageCommand().setIsAvailable(true);
getSearchPreviousPageCommand().setIsAvailable(true);
// Call 'IsCommandCompatible' for precaching
AsyncDataProvider.getInstance().isCommandCompatible(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
}
}), null, null, null);
}
private void setDetailList(final VmGeneralModel vmGeneralModel, final VmInterfaceListModel vmInterfaceListModel,
final VmDiskListModel vmDiskListModel, final VmSnapshotListModel vmSnapshotListModel,
final VmEventListModel vmEventListModel, final VmAppListModel<VM> vmAppListModel,
final PermissionListModel<VM> permissionListModel, final VmAffinityGroupListModel vmAffinityGroupListModel,
final VmGuestInfoModel vmGuestInfoModel, final VmHostDeviceListModel vmHostDeviceListModel,
final VmDevicesListModel vmDevicesListModel) {
List<HasEntity<VM>> list = new ArrayList<>();
list.add(vmGeneralModel);
list.add(vmInterfaceListModel);
vmDiskListModel.setSystemTreeContext(this);
list.add(vmDiskListModel);
list.add(vmSnapshotListModel);
list.add(vmEventListModel);
list.add(vmAppListModel);
list.add(vmDevicesListModel);
list.add(permissionListModel);
list.add(vmAffinityGroupListModel);
list.add(vmGuestInfoModel);
list.add(vmHostDeviceListModel);
setDetailModels(list);
}
private void setConsoleHelpers() {
this.errorPopupManager = (ErrorPopupManager) TypeResolver.getInstance().resolve(ErrorPopupManager.class);
}
private void assignTags() {
if (getWindow() != null) {
return;
}
TagListModel model = new TagListModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().assignTagsTitle());
model.setHelpTag(HelpTag.assign_tags_vms);
model.setHashName("assign_tags_vms"); //$NON-NLS-1$
getAttachedTagsToSelectedVMs(model);
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnAssignTags", this); //$NON-NLS-1$
model.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar2);
}
public Map<Guid, Boolean> attachedTagsToEntities;
public ArrayList<Tags> allAttachedTags;
public int selectedItemsCounter;
private void getAttachedTagsToSelectedVMs(TagListModel model) {
ArrayList<Guid> vmIds = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM vm = (VM) item;
vmIds.add(vm.getId());
}
attachedTagsToEntities = new HashMap<>();
allAttachedTags = new ArrayList<>();
selectedItemsCounter = 0;
for (Guid id : vmIds) {
AsyncDataProvider.getInstance().getAttachedTagsToVm(new AsyncQuery(new Object[] { this, model },
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
VmListModel<Void> vmListModel = (VmListModel<Void>) array[0];
TagListModel tagListModel = (TagListModel) array[1];
vmListModel.allAttachedTags.addAll((ArrayList<Tags>) returnValue);
vmListModel.selectedItemsCounter++;
if (vmListModel.selectedItemsCounter == vmListModel.getSelectedItems().size()) {
postGetAttachedTags(vmListModel, tagListModel);
}
}
}),
id);
}
}
private void postGetAttachedTags(VmListModel<Void> vmListModel, TagListModel tagListModel) {
if (vmListModel.getLastExecutedCommand() == getAssignTagsCommand()) {
ArrayList<Tags> attachedTags =
Linq.distinct(vmListModel.allAttachedTags, new TagsEqualityComparer());
for (Tags tag : attachedTags) {
int count = 0;
for (Tags tag2 : vmListModel.allAttachedTags) {
if (tag2.gettag_id().equals(tag.gettag_id())) {
count++;
}
}
vmListModel.attachedTagsToEntities.put(tag.gettag_id(), count == vmListModel.getSelectedItems().size());
}
tagListModel.setAttachedTagsToEntities(vmListModel.attachedTagsToEntities);
}
else if ("OnAssignTags".equals(vmListModel.getLastExecutedCommand().getName())) { //$NON-NLS-1$
vmListModel.postOnAssignTags(tagListModel.getAttachedTagsToEntities());
}
}
private void onAssignTags() {
TagListModel model = (TagListModel) getWindow();
getAttachedTagsToSelectedVMs(model);
}
public void postOnAssignTags(Map<Guid, Boolean> attachedTags) {
TagListModel model = (TagListModel) getWindow();
ArrayList<Guid> vmIds = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM vm = (VM) item;
vmIds.add(vm.getId());
}
// prepare attach/detach lists
ArrayList<Guid> tagsToAttach = new ArrayList<>();
ArrayList<Guid> tagsToDetach = new ArrayList<>();
if (model.getItems() != null && model.getItems().size() > 0) {
ArrayList<TagModel> tags = (ArrayList<TagModel>) model.getItems();
TagModel rootTag = tags.get(0);
TagModel.recursiveEditAttachDetachLists(rootTag, attachedTags, tagsToAttach, tagsToDetach);
}
ArrayList<VdcActionParametersBase> parameters = new ArrayList<>();
for (Guid a : tagsToAttach) {
parameters.add(new AttachEntityToTagParameters(a, vmIds));
}
Frontend.getInstance().runMultipleAction(VdcActionType.AttachVmsToTag, parameters);
parameters = new ArrayList<>();
for (Guid a : tagsToDetach) {
parameters.add(new AttachEntityToTagParameters(a, vmIds));
}
Frontend.getInstance().runMultipleAction(VdcActionType.DetachVmFromTag, parameters);
cancel();
}
private void guide() {
VmGuideModel model = new VmGuideModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newVirtualMachineGuideMeTitle());
model.setHelpTag(HelpTag.new_virtual_machine___guide_me);
model.setHashName("new_virtual_machine_-_guide_me"); //$NON-NLS-1$
if (getGuideContext() == null) {
VM vm = getSelectedItem();
setGuideContext(vm.getId());
}
AsyncDataProvider.getInstance().getVmById(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmListModel<Void> vmListModel = (VmListModel<Void>) target;
VmGuideModel model = (VmGuideModel) vmListModel.getWindow();
model.setEntity(returnValue);
UICommand tempVar = new UICommand("Cancel", vmListModel); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().configureLaterTitle());
tempVar.setIsDefault(true);
tempVar.setIsCancel(true);
model.getCommands().add(tempVar);
}
}), (Guid) getGuideContext());
}
@Override
public boolean isSearchStringMatch(String searchString) {
return searchString.trim().toLowerCase().startsWith("vm"); //$NON-NLS-1$
}
@Override
protected void syncSearch() {
SearchParameters tempVar = new SearchParameters(applySortOptions(getSearchString()), SearchType.VM, isCaseSensitiveSearch());
tempVar.setMaxCount(getSearchPageSize());
super.syncSearch(VdcQueryType.Search, tempVar);
}
private void newVm() {
if (getWindow() != null) {
return;
}
List<UICommand> commands = new ArrayList<>();
commands.add(UICommand.createDefaultOkUiCommand("OnSave", this)); //$NON-NLS-1$
commands.add(UICommand.createCancelUiCommand("Cancel", this)); //$NON-NLS-1$
UnitVmModel model = new UnitVmModel(new NewVmModelBehavior(), this);
setupNewVmModel(model, VmType.Server, getSystemTreeSelectedItem(), commands);
}
private void editConsole() {
if (getWindow() != null || getSelectedItem() == null) {
return;
}
final VmConsoles activeVmConsoles = consolesFactory.getVmConsolesForVm(getSelectedItem());
final ConsolePopupModel model = new ConsolePopupModel();
model.setVmConsoles(activeVmConsoles);
model.setHelpTag(HelpTag.editConsole);
model.setHashName("editConsole"); //$NON-NLS-1$
setWindow(model);
final UICommand saveCommand = UICommand.createDefaultOkUiCommand("OnEditConsoleSave", this); //$NON-NLS-1$
model.getCommands().add(saveCommand);
final UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(cancelCommand);
}
private void edit() {
VM vm = getSelectedItem();
if (vm == null) {
return;
}
if (getWindow() != null) {
return;
}
// populating VMInit
AsyncQuery getVmInitQuery = new AsyncQuery();
getVmInitQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
editedVm = (VM) result;
vmInitLoaded(editedVm);
}
};
if (vm.isNextRunConfigurationExists()) {
AsyncDataProvider.getInstance().getVmNextRunConfiguration(getVmInitQuery, vm.getId());
} else {
AsyncDataProvider.getInstance().getVmById(getVmInitQuery, vm.getId());
}
}
private void vmInitLoaded(VM vm) {
UnitVmModel model = new UnitVmModel(new ExistingVmModelBehavior(vm), this);
model.getVmType().setSelectedItem(vm.getVmType());
model.setVmAttachedToPool(vm.getVmPoolId() != null);
model.setIsAdvancedModeLocalStorageKey("wa_vm_dialog"); //$NON-NLS-1$
setWindow(model);
model.setTitle(ConstantsManager.getInstance()
.getConstants().editVmTitle());
model.setHelpTag(HelpTag.edit_vm);
model.setHashName("edit_vm"); //$NON-NLS-1$
model.setCustomPropertiesKeysList(AsyncDataProvider.getInstance().getCustomPropertiesList());
model.initialize(this.getSystemTreeSelectedItem());
model.initForemanProviders(vm.getProviderId());
VmBasedWidgetSwitchModeCommand switchModeCommand = new VmBasedWidgetSwitchModeCommand();
switchModeCommand.init(model);
model.getCommands().add(switchModeCommand);
model.getCommands().add(UICommand.createDefaultOkUiCommand("OnSave", this)); //$NON-NLS-1$
model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); //$NON-NLS-1$
}
private Map<Guid, EntityModel> vmsRemoveMap;
private void remove() {
if (getWindow() != null) {
return;
}
ConfirmationModel window = new ConfirmationModel();
setWindow(window);
window.setTitle(ConstantsManager.getInstance().getConstants().removeVirtualMachinesTitle());
window.setHelpTag(HelpTag.remove_virtual_machine);
window.setHashName("remove_virtual_machine"); //$NON-NLS-1$
vmsRemoveMap = new HashMap<>();
for (Object selectedItem : getSelectedItems()) {
VM vm = (VM) selectedItem;
EntityModel removeDisksCheckbox = new EntityModel(true);
removeDisksCheckbox.setTitle(ConstantsManager.getInstance().getConstants().removeDisksTitle());
removeDisksCheckbox.setMessage(vm.getName());
if (!Guid.Empty.equals(vm.getVmtGuid())) {
updateRemoveDisksCheckBox(removeDisksCheckbox, true, false, ConstantsManager.getInstance()
.getConstants()
.removeVmDisksTemplateMsg());
}
vmsRemoveMap.put(vm.getId(), removeDisksCheckbox);
}
window.setItems(vmsRemoveMap.entrySet());
initRemoveDisksCheckboxes(vmsRemoveMap);
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnRemove", this); //$NON-NLS-1$
window.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
window.getCommands().add(tempVar2);
}
private void updateRemoveDisksCheckBox(EntityModel model,
boolean deleteDisks,
boolean isChangable,
String changeProhibitionReason) {
model.setEntity(deleteDisks);
if (!isChangable && changeProhibitionReason != null) {
model.setChangeProhibitionReason(changeProhibitionReason);
}
model.setIsChangeable(isChangable);
}
private void initRemoveDisksCheckboxes(final Map<Guid, EntityModel> vmsMap) {
ArrayList<VdcQueryParametersBase> params = new ArrayList<>();
ArrayList<VdcQueryType> queries = new ArrayList<>();
for (Entry<Guid, EntityModel> entry : vmsMap.entrySet()) {
if (entry.getValue().getIsChangable()) { // No point in fetching VM disks from ones that already determined
// is unchangeable since they are already initialized
params.add(new IdQueryParameters(entry.getKey()));
queries.add(VdcQueryType.GetAllDisksByVmId);
}
}
// TODO: There's no point in creating a VdcQueryType list when you wanna run the same query for all parameters,
// revise when refactoring org.ovirt.engine.ui.Frontend to support runMultipleQuery with a single query
if (!params.isEmpty()) {
Frontend.getInstance().runMultipleQueries(queries, params, new IFrontendMultipleQueryAsyncCallback() {
@Override
public void executed(FrontendMultipleQueryAsyncResult result) {
for (int i = 0; i < result.getReturnValues().size(); i++) {
if (result.getReturnValues().get(i).getSucceeded()) {
Guid vmId = ((IdQueryParameters) result.getParameters().get(i)).getId();
initRemoveDisksChecboxesPost(vmId, (List<Disk>) result.getReturnValues()
.get(i)
.getReturnValue());
}
}
}
});
}
}
private void initRemoveDisksChecboxesPost(Guid vmId, List<Disk> disks) {
EntityModel model = vmsRemoveMap.get(vmId);
if (disks.isEmpty()) {
updateRemoveDisksCheckBox(model, false, false, ConstantsManager.getInstance()
.getConstants()
.removeVmDisksNoDisksMsg());
return;
}
boolean isOnlySharedDisks = true;
boolean isSnapshotExists = false;
for (Disk disk : disks) {
if (!disk.isShareable()) {
isOnlySharedDisks = false;
if (disk.getDiskStorageType() == DiskStorageType.IMAGE) {
if (((DiskImage) disk).getSnapshots().size() > 1) {
isSnapshotExists = true;
break;
}
}
}
}
if (isSnapshotExists) {
updateRemoveDisksCheckBox(model, true, false, ConstantsManager.getInstance()
.getConstants()
.removeVmDisksSnapshotsMsg());
return;
}
if (isOnlySharedDisks) {
updateRemoveDisksCheckBox(model, false, false, ConstantsManager.getInstance()
.getConstants()
.removeVmDisksAllSharedMsg());
return;
}
}
private void createSnapshot() {
VM vm = getSelectedItem();
if (vm == null || getWindow() != null) {
return;
}
SnapshotModel model = SnapshotModel.createNewSnapshotModel(this);
model.setValidateByVmSnapshots(true);
setWindow(model);
model.setVm(vm);
model.initialize();
}
@Override
protected String thereIsNoExportDomainBackupEntityAttachExportDomainToVmsDcMsg() {
return ConstantsManager.getInstance()
.getConstants()
.thereIsNoExportDomainBackupVmAttachExportDomainToVmsDcMsg();
}
@Override
protected VdcQueryType getEntityExportDomain() {
return VdcQueryType.GetVmsFromExportDomain;
}
@Override
protected String entityResideOnSeveralDCsMakeSureTheExportedVMResideOnSameDcMsg() {
return ConstantsManager.getInstance()
.getConstants()
.vmsResideOnSeveralDCsMakeSureTheExportedVMResideOnSameDcMsg();
}
@Override
protected boolean entitiesSelectedOnDifferentDataCenters() {
ArrayList<VM> vms = new ArrayList<>();
for (Object selectedItem : getSelectedItems()) {
VM a = (VM) selectedItem;
vms.add(a);
}
Map<Guid, ArrayList<VM>> t = new HashMap<>();
for (VM a : vms) {
if (!t.containsKey(a.getStoragePoolId())) {
t.put(a.getStoragePoolId(), new ArrayList<VM>());
}
ArrayList<VM> list = t.get(a.getStoragePoolId());
list.add(a);
}
return t.size() > 1;
}
@Override
protected String extractNameFromEntity(VM entity) {
return entity.getName();
}
@Override
protected boolean entititesEqualsNullSafe(VM e1, VM e2) {
return e1.getId().equals(e2.getId());
}
@Override
protected String composeEntityOnStorage(String entities) {
return ConstantsManager.getInstance()
.getMessages()
.vmsAlreadyExistOnTargetExportDomain(entities);
}
@Override
protected Iterable<VM> asIterableReturnValue(Object returnValue) {
return (List<VM>) returnValue;
}
private void getTemplatesNotPresentOnExportDomain() {
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = model.getStorage().getSelectedItem().getId();
AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmListModel<Void> vmListModel = (VmListModel<Void>) target;
ArrayList<StoragePool> storagePools =
(ArrayList<StoragePool>) returnValue;
StoragePool storagePool = storagePools.size() > 0 ? storagePools.get(0) : null;
vmListModel.postGetTemplatesNotPresentOnExportDomain(storagePool);
}
}), storageDomainId);
}
private void postGetTemplatesNotPresentOnExportDomain(StoragePool storagePool) {
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = model.getStorage().getSelectedItem().getId();
if (storagePool != null) {
AsyncDataProvider.getInstance().getAllTemplatesFromExportDomain(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmListModel<Void> vmListModel = (VmListModel<Void>) target;
HashMap<VmTemplate, ArrayList<DiskImage>> templatesDiskSet =
(HashMap<VmTemplate, ArrayList<DiskImage>>) returnValue;
HashMap<String, ArrayList<String>> templateDic =
new HashMap<>();
// check if relevant templates are already there
for (Object selectedItem : vmListModel.getSelectedItems()) {
VM vm = (VM) selectedItem;
boolean hasMatch = false;
for (VmTemplate a : templatesDiskSet.keySet()) {
if (vm.getVmtGuid().equals(a.getId())) {
hasMatch = true;
break;
}
}
if (!vm.getVmtGuid().equals(Guid.Empty) && !hasMatch) {
if (!templateDic.containsKey(vm.getVmtName())) {
templateDic.put(vm.getVmtName(), new ArrayList<String>());
}
templateDic.get(vm.getVmtName()).add(vm.getName());
}
}
String tempStr;
ArrayList<String> tempList;
ArrayList<String> missingTemplates = new ArrayList<>();
for (Map.Entry<String, ArrayList<String>> keyValuePair : templateDic.entrySet()) {
tempList = keyValuePair.getValue();
StringBuilder sb = new StringBuilder("Template " + keyValuePair.getKey() + " (for "); //$NON-NLS-1$ //$NON-NLS-2$
int i;
for (i = 0; i < tempList.size() - 1; i++) {
sb.append(tempList.get(i));
sb.append(", "); //$NON-NLS-1$
}
sb.append(tempList.get(i));
sb.append(")"); //$NON-NLS-1$
missingTemplates.add(sb.toString());
}
vmListModel.postExportGetMissingTemplates(missingTemplates);
}
}),
storagePool.getId(),
storageDomainId);
}
}
private void postExportGetMissingTemplates(ArrayList<String> missingTemplatesFromVms) {
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = model.getStorage().getSelectedItem().getId();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<>();
model.stopProgress();
for (Object a : getSelectedItems()) {
VM vm = (VM) a;
MoveVmParameters parameter = new MoveVmParameters(vm.getId(), storageDomainId);
parameter.setForceOverride(model.getForceOverride().getEntity());
parameter.setCopyCollapse(model.getCollapseSnapshots().getEntity());
parameter.setTemplateMustExists(true);
parameters.add(parameter);
}
if (!model.getCollapseSnapshots().getEntity()) {
if ((missingTemplatesFromVms == null || missingTemplatesFromVms.size() > 0)) {
ConfirmationModel confirmModel = new ConfirmationModel();
setConfirmWindow(confirmModel);
confirmModel.setTitle(ConstantsManager.getInstance()
.getConstants()
.templatesNotFoundOnExportDomainTitle());
confirmModel.setHelpTag(HelpTag.template_not_found_on_export_domain);
confirmModel.setHashName("template_not_found_on_export_domain"); //$NON-NLS-1$
confirmModel.setMessage(missingTemplatesFromVms == null ? ConstantsManager.getInstance()
.getConstants()
.couldNotReadTemplatesFromExportDomainMsg()
: ConstantsManager.getInstance()
.getConstants()
.theFollowingTemplatesAreMissingOnTargetExportDomainMsg());
confirmModel.setItems(missingTemplatesFromVms);
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnExportNoTemplates", this); //$NON-NLS-1$
confirmModel.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("CancelConfirmation", this); //$NON-NLS-1$
confirmModel.getCommands().add(tempVar2);
}
else {
if (model.getProgress() != null) {
return;
}
model.startProgress(null);
Frontend.getInstance().runMultipleAction(VdcActionType.ExportVm, parameters,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
}
else {
if (model.getProgress() != null) {
return;
}
for (VdcActionParametersBase item : parameters) {
MoveVmParameters parameter = (MoveVmParameters) item;
parameter.setTemplateMustExists(false);
}
model.startProgress(null);
Frontend.getInstance().runMultipleAction(VdcActionType.ExportVm, parameters,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
}
@Override
protected void setupExportModel(ExportVmModel model) {
super.setupExportModel(model);
model.setTitle(constants.exportVirtualMachineTitle());
model.setHelpTag(HelpTag.export_virtual_machine);
model.setHashName("export_virtual_machine"); //$NON-NLS-1$
}
public void onExport() {
ExportVmModel model = (ExportVmModel) getWindow();
if (!model.validate()) {
return;
}
model.startProgress(null);
getTemplatesNotPresentOnExportDomain();
}
private void onExportNoTemplates() {
ExportVmModel model = (ExportVmModel) getWindow();
Guid storageDomainId = model.getStorage().getSelectedItem().getId();
if (model.getProgress() != null) {
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
MoveVmParameters parameters = new MoveVmParameters(a.getId(), storageDomainId);
parameters.setForceOverride(model.getForceOverride().getEntity());
parameters.setCopyCollapse(model.getCollapseSnapshots().getEntity());
parameters.setTemplateMustExists(false);
list.add(parameters);
}
model.startProgress(null);
Frontend.getInstance().runMultipleAction(VdcActionType.ExportVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ExportVmModel localModel = (ExportVmModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
@Override
protected void sendWarningForNonExportableDisks(VM entity) {
// load VM disks and check if there is one which doesn't allow snapshot
AsyncDataProvider.getInstance().getVmDiskList(new AsyncQuery(getWindow(),
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
final ExportVmModel model = (ExportVmModel) target;
@SuppressWarnings("unchecked")
final ArrayList<Disk> vmDisks = (ArrayList<Disk>) returnValue;
VmModelHelper.sendWarningForNonExportableDisks(model,
vmDisks,
VmModelHelper.WarningType.VM_EXPORT);
}
}),
entity.getId());
}
private void runOnce() {
VM vm = getSelectedItem();
// populating VMInit
AsyncQuery getVmInitQuery = new AsyncQuery();
getVmInitQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
RunOnceModel runOnceModel = new WebadminRunOnceModel((VM) result,
VmListModel.this);
setWindow(runOnceModel);
runOnceModel.init();
}
};
AsyncDataProvider.getInstance().getVmById(getVmInitQuery, vm.getId());
}
private void newTemplate() {
VM vm = getSelectedItem();
if (vm == null || getWindow() != null) {
return;
}
UnitVmModel model = new UnitVmModel(new NewTemplateVmModelBehavior(vm), this);
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newTemplateTitle());
model.setHelpTag(HelpTag.new_template);
model.setHashName("new_template"); //$NON-NLS-1$
model.setIsNew(true);
model.getVmType().setSelectedItem(vm.getVmType());
model.setCustomPropertiesKeysList(AsyncDataProvider.getInstance().getCustomPropertiesList());
model.initialize(getSystemTreeSelectedItem());
model.getCommands().add(
new UICommand("OnNewTemplate", this) //$NON-NLS-1$
.setTitle(ConstantsManager.getInstance().getConstants().ok())
.setIsDefault(true));
model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); //$NON-NLS-1$
model.getIsHighlyAvailable().setEntity(vm.getStaticData().isAutoStartup());
}
private void onNewTemplate() {
UnitVmModel model = (UnitVmModel) getWindow();
VM vm = getSelectedItem();
if (vm == null) {
cancel();
return;
}
if (model.getProgress() != null) {
return;
}
if (!model.validate(false)) {
model.setIsValid(false);
}
else if (model.getIsSubTemplate().getEntity()) {
postNameUniqueCheck();
}
else {
String name = model.getName().getEntity();
// Check name unicitate.
AsyncDataProvider.getInstance().isTemplateNameUnique(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VmListModel<Void> vmListModel = (VmListModel<Void>) target;
boolean isNameUnique = (Boolean) returnValue;
if (!isNameUnique) {
UnitVmModel VmModel = (UnitVmModel) vmListModel.getWindow();
VmModel.getInvalidityReasons().clear();
VmModel.getName()
.getInvalidityReasons()
.add(ConstantsManager.getInstance()
.getConstants()
.nameMustBeUniqueInvalidReason());
VmModel.getName().setIsValid(false);
VmModel.setIsValid(false);
}
else {
vmListModel.postNameUniqueCheck();
}
}
}),
name, model.getSelectedDataCenter() == null ? null : model.getSelectedDataCenter().getId());
}
}
private void postNameUniqueCheck() {
UnitVmModel model = (UnitVmModel) getWindow();
VM vm = getSelectedItem();
VM newVm = buildVmOnNewTemplate(model, vm);
AddVmTemplateParameters addVmTemplateParameters =
new AddVmTemplateParameters(newVm,
model.getName().getEntity(),
model.getDescription().getEntity());
BuilderExecutor.build(model, addVmTemplateParameters, new UnitToAddVmTemplateParametersBuilder());
model.startProgress(null);
Frontend.getInstance().runAction(VdcActionType.AddVmTemplate, addVmTemplateParameters,
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
VmListModel<Void> vmListModel = (VmListModel<Void>) result.getState();
vmListModel.getWindow().stopProgress();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded()) {
vmListModel.cancel();
}
}
}, this);
}
protected static VM buildVmOnNewTemplate(UnitVmModel model, VM vm) {
VM resultVm = new VM();
resultVm.setId(vm.getId());
BuilderExecutor.build(model, resultVm.getStaticData(), new CommonUnitToVmBaseBuilder());
BuilderExecutor.build(vm.getStaticData(), resultVm.getStaticData(), new VmBaseToVmBaseForTemplateCompositeBaseBuilder());
return resultVm;
}
private void migrate() {
VM vm = getSelectedItem();
if (vm == null) {
return;
}
if (getWindow() != null) {
return;
}
MigrateModel model = new MigrateModel(this);
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().migrateVirtualMachinesTitle());
model.setHelpTag(HelpTag.migrate_virtual_machine);
model.setHashName("migrate_virtual_machine"); //$NON-NLS-1$
model.setVmsOnSameCluster(true);
model.setIsAutoSelect(true);
model.setVmList(Linq.<VM> cast(getSelectedItems()));
model.setVm(vm);
model.initializeModel();
}
private void cancelMigration() {
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
list.add(new VmOperationParameterBase(a.getId()));
}
Frontend.getInstance().runMultipleAction(VdcActionType.CancelMigrateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(
FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void cancelConversion() {
List<VdcActionParametersBase> parameters = new ArrayList<>();
for (VM vm : getSelectedItems()) {
parameters.add(new VmOperationParameterBase(vm.getId()));
}
Frontend.getInstance().runMultipleAction(VdcActionType.CancelConvertVm, parameters);
}
private void onMigrate() {
MigrateModel model = (MigrateModel) getWindow();
if (model.getProgress() != null) {
return;
}
model.startProgress(null);
Guid targetClusterId = model.getClusters().getSelectedItem() != null ? model.getClusters().getSelectedItem().getId() : null;
if (model.getIsAutoSelect()) {
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
list.add(new MigrateVmParameters(true, a.getId(), targetClusterId));
}
Frontend.getInstance().runMultipleAction(VdcActionType.MigrateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
MigrateModel localModel = (MigrateModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
else {
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
if (a.getRunOnVds().equals(model.getHosts().getSelectedItem().getId())) {
continue;
}
list.add(new MigrateVmToServerParameters(true, a.getId(), model.getHosts()
.getSelectedItem().getId(), targetClusterId));
}
Frontend.getInstance().runMultipleAction(VdcActionType.MigrateVmToServer, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
MigrateModel localModel = (MigrateModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
}
private void powerAction(final String actionName, final String title, final String message) {
Guid clusterId = getClusterIdOfSelectedVms();
if (clusterId == null) {
powerAction(actionName, title, message, false);
} else {
AsyncDataProvider.getInstance().getClusterById(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
VDSGroup cluster = (VDSGroup) returnValue;
if (cluster != null) {
powerAction(actionName, title, message, cluster.isOptionalReasonRequired());
}
}
}), clusterId);
}
}
/**
* Returns the cluster id if all vms are from the same cluster else returns null.
* @return
*/
private Guid getClusterIdOfSelectedVms() {
Guid clusterId = null;
for (Object item : getSelectedItems()) {
VM a = (VM) item;
if (clusterId == null) {
clusterId = a.getVdsGroupId();
} else if (!clusterId.equals(a.getVdsGroupId())) {
clusterId = null;
break;
}
}
return clusterId;
}
private void powerAction(String actionName, String title, String message, boolean reasonVisible) {
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle(title);
model.setReasonVisible(reasonVisible);
if (actionName.equals(SHUTDOWN)) {
model.setHelpTag(HelpTag.shutdown_virtual_machine);
model.setHashName("shutdown_virtual_machine"); //$NON-NLS-1$
}
else if (actionName.equals(STOP)) {
model.setHelpTag(HelpTag.stop_virtual_machine);
model.setHashName("stop_virtual_machine"); //$NON-NLS-1$
}
else if (actionName.equals(REBOOT)) {
model.setHelpTag(HelpTag.reboot_virtual_machine);
model.setHashName("reboot_virtual_machine"); //$NON-NLS-1$
}
model.setMessage(message);
ArrayList<String> items = new ArrayList<>();
boolean stoppingSingleVM = getSelectedItems().size() == 1 &&
(actionName.equals(SHUTDOWN) || actionName.equals(STOP));
for (Object item : getSelectedItems()) {
VM vm = (VM) item;
items.add(vm.getName());
// If a single VM in status PoweringDown is being stopped the reason field
// is populated with the current reason so the user can edit it.
if (stoppingSingleVM && reasonVisible && VMStatus.PoweringDown.equals(vm.getStatus())) {
model.getReason().setEntity(vm.getStopReason());
}
}
model.setItems(items);
UICommand tempVar = new UICommand("On" + actionName, this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar2);
}
private interface PowerActionParametersFactory<P extends VdcActionParametersBase> {
P createActionParameters(VM vm);
}
private void onPowerAction(VdcActionType actionType, PowerActionParametersFactory<?> parametersFactory) {
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null) {
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM vm = (VM) item;
list.add(parametersFactory.createActionParameters(vm));
}
model.startProgress(null);
Frontend.getInstance().runMultipleAction(actionType, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
private void shutdown() {
UIConstants constants = ConstantsManager.getInstance().getConstants();
powerAction(SHUTDOWN,
constants.shutdownVirtualMachinesTitle(),
constants.areYouSureYouWantToShutDownTheFollowingVirtualMachinesMsg());
}
private void onShutdown() {
final ConfirmationModel model = (ConfirmationModel) getWindow();
onPowerAction(VdcActionType.ShutdownVm, new PowerActionParametersFactory<VdcActionParametersBase>() {
@Override
public VdcActionParametersBase createActionParameters(VM vm) {
return new ShutdownVmParameters(vm.getId(), true, model.getReason().getEntity());
}
});
}
private void stop() {
UIConstants constants = ConstantsManager.getInstance().getConstants();
powerAction(STOP,
constants.stopVirtualMachinesTitle(),
constants.areYouSureYouWantToStopTheFollowingVirtualMachinesMsg());
}
private void onStop() {
final ConfirmationModel model = (ConfirmationModel) getWindow();
onPowerAction(VdcActionType.StopVm, new PowerActionParametersFactory<VdcActionParametersBase>() {
@Override
public VdcActionParametersBase createActionParameters(VM vm) {
return new StopVmParameters(vm.getId(), StopVmTypeEnum.NORMAL, model.getReason().getEntity());
}
});
}
private void reboot() {
UIConstants constants = ConstantsManager.getInstance().getConstants();
powerAction(REBOOT,
constants.rebootVirtualMachinesTitle(),
constants.areYouSureYouWantToRebootTheFollowingVirtualMachinesMsg(),
false);
}
private void onReboot() {
onPowerAction(VdcActionType.RebootVm, new PowerActionParametersFactory<VdcActionParametersBase>() {
@Override
public VdcActionParametersBase createActionParameters(VM vm) {
return new VmOperationParameterBase(vm.getId());
}
});
}
private void pause() {
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
list.add(new VmOperationParameterBase(a.getId()));
}
Frontend.getInstance().runMultipleAction(VdcActionType.HibernateVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void run() {
ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Object item : getSelectedItems()) {
VM a = (VM) item;
list.add(new RunVmParams(a.getId()));
}
Frontend.getInstance().runMultipleAction(VdcActionType.RunVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
}
}, null);
}
private void onRemove() {
final ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null) {
return;
}
final ArrayList<VdcActionParametersBase> list = new ArrayList<>();
for (Entry<Guid, EntityModel> entry : vmsRemoveMap.entrySet()) {
list.add(new RemoveVmParameters(entry.getKey(), false, (Boolean) entry.getValue().getEntity()));
}
model.startProgress(null);
Frontend.getInstance().runMultipleAction(VdcActionType.RemoveVm, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
private void editConsoleKey() {
PublicKeyModel model = new PublicKeyModel();
setWindow(model);
model.editConsoleKey(this);
}
private void onSetConsoleKey() {
PublicKeyModel model = (PublicKeyModel) getWindow();
model.onSetConsoleKey(this, this);
}
private void changeCD() {
final VM vm = getSelectedItem();
if (vm == null) {
return;
}
AttachCdModel model = new AttachCdModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().changeCDTitle());
model.setHelpTag(HelpTag.change_cd);
model.setHashName("change_cd"); //$NON-NLS-1$
AttachCdModel attachCdModel = (AttachCdModel) getWindow();
ArrayList<String> images1 =
new ArrayList<>(Arrays.asList(new String[] { ConstantsManager.getInstance()
.getConstants()
.noCds() }));
attachCdModel.getIsoImage().setItems(images1);
attachCdModel.getIsoImage().setSelectedItem(Linq.firstOrDefault(images1));
AsyncQuery getIrsImageListCallback = new AsyncQuery();
getIrsImageListCallback.setModel(this);
getIrsImageListCallback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
VmListModel<Void> vmListModel2 = (VmListModel<Void>) model;
AttachCdModel _attachCdModel = (AttachCdModel) vmListModel2.getWindow();
ArrayList<String> images = (ArrayList<String>) result;
images.add(0, ConsoleModel.getEjectLabel());
_attachCdModel.getIsoImage().setItems(images);
if (_attachCdModel.getIsoImage().getIsChangable()) {
String selectedIso = Linq.firstOrDefault(images, new Linq.IPredicate<String>() {
@Override
public boolean match(String s) {
return vm.getCurrentCd().equals(s);
}
});
_attachCdModel.getIsoImage().setSelectedItem(selectedIso == null ? ConsoleModel.getEjectLabel() : selectedIso);
}
}
};
AsyncDataProvider.getInstance().getIrsImageList(getIrsImageListCallback, vm.getStoragePoolId());
UICommand tempVar = UICommand.createDefaultOkUiCommand("OnChangeCD", this); //$NON-NLS-1$
model.getCommands().add(tempVar);
UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(tempVar2);
}
private void onChangeCD() {
VM vm = getSelectedItem();
if (vm == null) {
cancel();
return;
}
AttachCdModel model = (AttachCdModel) getWindow();
if (model.getProgress() != null) {
return;
}
if (ObjectUtils.objectsEqual(model.getIsoImage().getSelectedItem(), vm.getCurrentCd())) {
cancel();
return;
}
String isoName =
(ObjectUtils.objectsEqual(model.getIsoImage().getSelectedItem(), ConsoleModel.getEjectLabel())) ? "" //$NON-NLS-1$
: model.getIsoImage().getSelectedItem();
model.startProgress(null);
Frontend.getInstance().runAction(VdcActionType.ChangeDisk, new ChangeDiskCommandParameters(vm.getId(), isoName),
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
AttachCdModel attachCdModel = (AttachCdModel) result.getState();
attachCdModel.stopProgress();
cancel();
}
}, model);
}
private void setGlobalHaMaintenance(boolean enabled) {
VM vm = getSelectedItem();
if (vm == null) {
return;
}
if (!vm.isHostedEngine()) {
return;
}
SetHaMaintenanceParameters params = new SetHaMaintenanceParameters(vm.getRunOnVds(), HaMaintenanceMode.GLOBAL, enabled);
Frontend.getInstance().runAction(VdcActionType.SetHaMaintenance, params);
}
private void preSave() {
final UnitVmModel model = (UnitVmModel) getWindow();
if (model.getIsNew() == false && selectedItem == null) {
cancel();
return;
}
setcurrentVm(model.getIsNew() ? new VM() : (VM) Cloner.clone(selectedItem));
String selectedCpu = model.getCustomCpu().getSelectedItem();
if (selectedCpu != null && !selectedCpu.isEmpty() && !model.getCustomCpu().getItems().contains(selectedCpu)) {
confirmCustomCpu("PreSavePhase2"); //$NON-NLS-1$
} else {
preSavePhase2();
}
}
private void confirmCustomCpu(String phase2UiCommand) {
ConfirmationModel confirmModel = new ConfirmationModel();
confirmModel.setTitle(ConstantsManager.getInstance().getConstants().vmUnsupportedCpuTitle());
confirmModel.setMessage(ConstantsManager.getInstance().getConstants().vmUnsupportedCpuMessage());
confirmModel.setHelpTag(HelpTag.edit_unsupported_cpu);
confirmModel.setHashName("edit_unsupported_cpu"); //$NON-NLS-1$
confirmModel.getCommands().add(new UICommand(phase2UiCommand, VmListModel.this)
.setTitle(ConstantsManager.getInstance().getConstants().ok())
.setIsDefault(true));
confirmModel.getCommands().add(UICommand.createCancelUiCommand("CancelConfirmation", VmListModel.this)); //$NON-NLS-1$
setConfirmWindow(confirmModel);
}
private void preSavePhase2() {
final UnitVmModel model = (UnitVmModel) getWindow();
final String name = model.getName().getEntity();
validateVm(model, name);
}
@Override
protected void updateVM (final UnitVmModel model){
final VM selectedItem = getSelectedItem();
// explicitly pass non-editable field from the original VM
getcurrentVm().setCreatedByUserId(selectedItem.getCreatedByUserId());
getcurrentVm().setUseLatestVersion(model.getTemplateWithVersion().getSelectedItem().isLatest());
if (selectedItem.isRunningOrPaused()) {
AsyncDataProvider.getInstance().getVmChangedFieldsForNextRun(editedVm, getcurrentVm(), getUpdateVmParameters(false), new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object thisModel, Object returnValue) {
List<String> changedFields = ((VdcQueryReturnValue)returnValue).<List<String>> getReturnValue();
if (!changedFields.isEmpty()) {
VmNextRunConfigurationModel confirmModel = new VmNextRunConfigurationModel();
confirmModel.setTitle(ConstantsManager.getInstance().getConstants().editNextRunConfigurationTitle());
confirmModel.setHelpTag(HelpTag.edit_next_run_configuration);
confirmModel.setHashName("edit_next_run_configuration"); //$NON-NLS-1$
confirmModel.setChangedFields(changedFields);
confirmModel.setCpuPluggable(selectedItem.getCpuPerSocket() == getcurrentVm().getCpuPerSocket() &&
selectedItem.getNumOfSockets() != getcurrentVm().getNumOfSockets());
// currentl only hot plug memory is supported here (no hot unplug)
confirmModel.setMemoryPluggable(selectedItem.getMemSizeMb() < getcurrentVm().getMemSizeMb());
confirmModel.getCommands().add(new UICommand("updateExistingVm", VmListModel.this) //$NON-NLS-1$
.setTitle(ConstantsManager.getInstance().getConstants().ok())
.setIsDefault(true));
confirmModel.getCommands().add(UICommand.createCancelUiCommand("CancelConfirmation", VmListModel.this)); //$NON-NLS-1$
setConfirmWindow(confirmModel);
}
else {
updateExistingVm(false);
}
}
}));
}
else {
updateExistingVm(false);
}
}
private void updateExistingVm(final boolean applyCpuChangesLater) {
final UnitVmModel model = (UnitVmModel) getWindow();
if (model.getProgress() != null) {
return;
}
// runEditVM: should be true if Cluster hasn't changed or if
// Cluster has changed and Editing it in the Backend has succeeded:
VM selectedItem = getSelectedItem();
Guid oldClusterID = selectedItem.getVdsGroupId();
Guid newClusterID = model.getSelectedCluster().getId();
if (oldClusterID.equals(newClusterID) == false) {
ChangeVMClusterParameters parameters =
new ChangeVMClusterParameters(newClusterID, getcurrentVm().getId());
model.startProgress(null);
Frontend.getInstance().runAction(VdcActionType.ChangeVMCluster, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
final VmListModel<Void> vmListModel = (VmListModel<Void>) result.getState();
VdcReturnValueBase returnValueBase = result.getReturnValue();
if (returnValueBase != null && returnValueBase.getSucceeded()) {
VM vm = vmListModel.getcurrentVm();
VmManagementParametersBase updateVmParams = vmListModel.getUpdateVmParameters(applyCpuChangesLater);
Frontend.getInstance().runAction(VdcActionType.UpdateVm,
updateVmParams, new UnitVmModelNetworkAsyncCallback(model, defaultNetworkCreatingManager, vm.getId()), vmListModel);
}
else {
vmListModel.getWindow().stopProgress();
}
}
},
this);
}
else {
model.startProgress(null);
VmManagementParametersBase updateVmParams = getUpdateVmParameters(applyCpuChangesLater);
Frontend.getInstance().runAction(VdcActionType.UpdateVm, updateVmParams, new UnitVmModelNetworkAsyncCallback(model, defaultNetworkCreatingManager, getcurrentVm().getId()), this);
}
}
public VmManagementParametersBase getUpdateVmParameters(boolean applyCpuChangesLater) {
UnitVmModel model = (UnitVmModel) getWindow();
VmManagementParametersBase updateVmParams = new VmManagementParametersBase(getcurrentVm());
setVmWatchdogToParams(model, updateVmParams);
updateVmParams.setSoundDeviceEnabled(model.getIsSoundcardEnabled().getEntity());
updateVmParams.setConsoleEnabled(model.getIsConsoleDeviceEnabled().getEntity());
updateVmParams.setBalloonEnabled(balloonEnabled(model));
updateVmParams.setVirtioScsiEnabled(model.getIsVirtioScsiEnabled().getEntity());
updateVmParams.setApplyChangesLater(applyCpuChangesLater);
updateVmParams.setUpdateNuma(model.isNumaChanged());
BuilderExecutor.build(
new Pair<>((UnitVmModel) getWindow(), getSelectedItem()),
updateVmParams,
new VmIconUnitAndVmToParameterBuilder());
setRngDeviceToParams(model, updateVmParams);
BuilderExecutor.build(model, updateVmParams, new UnitToGraphicsDeviceParamsBuilder());
return updateVmParams;
}
private void retrieveIsoImages() {
Object tempVar = getSelectedItem();
VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null);
if (vm == null) {
return;
}
getIsoImages().clear();
ChangeCDModel tempVar2 = new ChangeCDModel();
tempVar2.setTitle(ConsoleModel.getEjectLabel());
ChangeCDModel ejectModel = tempVar2;
ejectModel.getExecutedEvent().addListener(this);
getIsoImages().add(ejectModel);
ChangeCDModel tempVar4 = new ChangeCDModel();
tempVar4.setTitle(ConstantsManager.getInstance().getConstants().noCds());
getIsoImages().add(tempVar4);
}
private void changeCD(Object sender, EventArgs e) {
ChangeCDModel model = (ChangeCDModel) sender;
// TODO: Patch!
String isoName = model.getTitle();
if (ObjectUtils.objectsEqual(isoName, ConstantsManager.getInstance()
.getConstants()
.noCds())) {
return;
}
Object tempVar = getSelectedItem();
VM vm = (VM) ((tempVar instanceof VM) ? tempVar : null);
if (vm == null) {
return;
}
Frontend.getInstance().runMultipleAction(VdcActionType.ChangeDisk,
new ArrayList<>(Arrays.asList(new VdcActionParametersBase[] { new ChangeDiskCommandParameters(vm.getId(),
ObjectUtils.objectsEqual(isoName, ConsoleModel.getEjectLabel()) ? "" : isoName) })), //$NON-NLS-1$
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
}
},
null);
}
@Override
public void cancel() {
cancelConfirmation();
setGuideContext(null);
setWindow(null);
updateActionsAvailability();
}
private void cancelConfirmation() {
setConfirmWindow(null);
}
@Override
protected void onSelectedItemChanged() {
super.onSelectedItemChanged();
updateActionsAvailability();
}
@Override
protected void selectedItemsChanged() {
super.selectedItemsChanged();
updateActionsAvailability();
}
@Override
protected void selectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e) {
super.selectedItemPropertyChanged(sender, e);
if (e.propertyName.equals("status")) { //$NON-NLS-1$
updateActionsAvailability();
}
}
@Override
protected void updateActionsAvailability() {
List items = getSelectedItems() != null && getSelectedItem() != null ? getSelectedItems() : new ArrayList();
boolean singleVmSelected = items.size() == 1;
boolean vmsSelected = items.size() > 0;
getCloneVmCommand().setIsExecutionAllowed(singleVmSelected);
getEditCommand().setIsExecutionAllowed(isEditCommandExecutionAllowed(items));
getRemoveCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.RemoveVm));
getRunCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecutePartially(items, VM.class, VdcActionType.RunVm));
getCloneVmCommand().setIsExecutionAllowed(singleVmSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.CloneVm));
getPauseCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecutePartially(items, VM.class, VdcActionType.HibernateVm));
getShutdownCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecutePartially(items, VM.class, VdcActionType.ShutdownVm));
getStopCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecutePartially(items, VM.class, VdcActionType.StopVm));
getRebootCommand().setIsExecutionAllowed(AsyncDataProvider.getInstance().isRebootCommandExecutionAllowed(items));
getMigrateCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecutePartially(items, VM.class, VdcActionType.MigrateVm));
getCancelMigrateCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecutePartially(items, VM.class, VdcActionType.CancelMigrateVm));
getNewTemplateCommand().setIsExecutionAllowed(singleVmSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.AddVmTemplate));
getRunOnceCommand().setIsExecutionAllowed(singleVmSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.RunVmOnce));
getExportCommand().setIsExecutionAllowed(vmsSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.ExportVm));
getCreateSnapshotCommand().setIsExecutionAllowed(singleVmSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.CreateAllSnapshotsFromVm));
getRetrieveIsoImagesCommand().setIsExecutionAllowed(singleVmSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.ChangeDisk));
getChangeCdCommand().setIsExecutionAllowed(singleVmSelected
&& VdcActionUtils.canExecute(items, VM.class, VdcActionType.ChangeDisk));
getAssignTagsCommand().setIsExecutionAllowed(vmsSelected);
updateHaMaintenanceAvailability(items);
getGuideCommand().setIsExecutionAllowed(getGuideContext() != null || singleVmSelected);
getConsoleConnectCommand().setIsExecutionAllowed(isConsoleCommandsExecutionAllowed());
getEditConsoleCommand().setIsExecutionAllowed(singleVmSelected && isConsoleEditEnabled());
getCancelConvertCommand().setIsExecutionAllowed(isSelectedVmBeingConverted());
}
private boolean isSelectedVmBeingConverted() {
List<VM> vms = getSelectedItems();
if (vms != null) {
for (VM vm : vms) {
int conversionProgress = vm.getBackgroundOperationProgress();
if (conversionProgress >= 0 && conversionProgress < 100) {
return true;
}
}
}
return false;
}
private boolean isConsoleEditEnabled() {
return getSelectedItem() != null && getSelectedItem().isRunningOrPaused();
}
private boolean isConsoleCommandsExecutionAllowed() {
final List<VM> list = getSelectedItem() == null ? null : getSelectedItems();
if (list == null) {
return false;
}
// return true, if at least one console is available
for (VM vm : list) {
if (consolesFactory.getVmConsolesForVm(vm).canConnectToConsole()) {
return true;
}
}
return false;
}
private void updateHaMaintenanceAvailability(List items) {
if (items == null || items.size() != 1) {
setHaMaintenanceAvailability(false);
return;
}
VM vm = getSelectedItem();
if (vm == null || !vm.isHostedEngine()
|| vm.getVdsGroupCompatibilityVersion().compareTo(Version.v3_4) < 0) {
setHaMaintenanceAvailability(false);
} else {
setHaMaintenanceAvailability(true);
}
}
private void setHaMaintenanceAvailability(boolean isAvailable) {
getEnableGlobalHaMaintenanceCommand().setIsExecutionAllowed(isAvailable);
getDisableGlobalHaMaintenanceCommand().setIsExecutionAllowed(isAvailable);
}
/**
* Return true if and only if one element is selected.
*/
private boolean isEditCommandExecutionAllowed(List items) {
if (items == null) {
return false;
}
if (items.size() != 1) {
return false;
}
return true;
}
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
super.eventRaised(ev, sender, args);
if (ev.matchesDefinition(ChangeCDModel.executedEventDefinition)) {
changeCD(sender, args);
}
}
@Override
public void executeCommand(UICommand command) {
super.executeCommand(command);
if (command == getNewVmCommand()) {
newVm();
} else if (command == getImportVmCommand()) {
importVms();
} else if (command == getCloneVmCommand()) {
cloneVm();
} else if (command == getEditCommand()) {
edit();
}
else if (command == getEditConsoleCommand()) {
editConsole();
}
else if (command == getConsoleConnectCommand()) {
connectToConsoles();
}
else if (command == getRemoveCommand()) {
remove();
}
else if (command == getRunCommand()) {
run();
}
else if (command == getPauseCommand()) {
pause();
} else if (command == getStopCommand()) {
stop();
} else if (command == getShutdownCommand()) {
shutdown();
}
else if (command == getRebootCommand()) {
reboot();
} else if (command == getMigrateCommand()) {
migrate();
}
else if (command == getNewTemplateCommand()) {
newTemplate();
} else if (command == getRunOnceCommand()) {
runOnce();
} else if (command == getExportCommand()) {
export();
}
else if (command == getCreateSnapshotCommand()) {
createSnapshot();
}
else if (command == getGuideCommand()) {
guide();
}
else if (command == getRetrieveIsoImagesCommand()) {
retrieveIsoImages();
}
else if (command == getChangeCdCommand()) {
changeCD();
}
else if (command == getEnableGlobalHaMaintenanceCommand()) {
setGlobalHaMaintenance(true);
}
else if (command == getDisableGlobalHaMaintenanceCommand()) {
setGlobalHaMaintenance(false);
}
else if (command == getAssignTagsCommand()) {
assignTags();
}
else if (command == getSetConsoleKeyCommand()) {
editConsoleKey();
}
else if ("OnAssignTags".equals(command.getName())) { //$NON-NLS-1$
onAssignTags();
}
else if ("Cancel".equals(command.getName())) { //$NON-NLS-1$
cancel();
}
else if ("OnSave".equals(command.getName())) { //$NON-NLS-1$
preSave();
}
else if ("PreSavePhase2".equals(command.getName())) { //$NON-NLS-1$
preSavePhase2();
cancelConfirmation();
}
else if ("OnRemove".equals(command.getName())) { //$NON-NLS-1$
onRemove();
}
else if ("OnClone".equals(command.getName())) { //$NON-NLS-1$
onClone();
}
else if ("OnExport".equals(command.getName())) { //$NON-NLS-1$
onExport();
}
else if ("OnExportNoTemplates".equals(command.getName())) { //$NON-NLS-1$
onExportNoTemplates();
}
else if ("CancelConfirmation".equals(command.getName())) { //$NON-NLS-1$
cancelConfirmation();
}
else if ("OnRunOnce".equals(command.getName())) { //$NON-NLS-1$
cancel();
}
else if ("OnNewTemplate".equals(command.getName())) { //$NON-NLS-1$
onNewTemplate();
}
else if ("OnMigrate".equals(command.getName())) { //$NON-NLS-1$
onMigrate();
}
else if (command == getCancelMigrateCommand()) {
cancelMigration();
}
else if (command == getCancelConvertCommand()) {
cancelConversion();
}
else if ("OnShutdown".equals(command.getName())) { //$NON-NLS-1$
onShutdown();
}
else if ("OnStop".equals(command.getName())) { //$NON-NLS-1$
onStop();
}
else if ("OnReboot".equals(command.getName())) { //$NON-NLS-1$
onReboot();
}
else if ("OnChangeCD".equals(command.getName())) { //$NON-NLS-1$
onChangeCD();
}
else if ("OnSetConsoleKey".equals(command.getName())) { //$NON-NLS-1$
onSetConsoleKey();
}
else if (command.getName().equals("closeVncInfo") || // $NON-NLS-1$
"OnEditConsoleSave".equals(command.getName())) { //$NON-NLS-1$
setWindow(null);
}
else if ("updateExistingVm".equals(command.getName())) { // $NON-NLS-1$
VmNextRunConfigurationModel model = (VmNextRunConfigurationModel) getConfirmWindow();
updateExistingVm(model.getApplyCpuLater().getEntity());
cancelConfirmation();
}
else if (CMD_CONFIGURE_VMS_TO_IMPORT.equals(command.getName())) {
onConfigureVmsToImport();
}
}
private void importVms() {
if (getWindow() != null) {
return;
}
final ImportVmsModel model = importVmsModelProvider.get();
model.init();
setWindow(model);
model.getCommands().add(new UICommand(CMD_CONFIGURE_VMS_TO_IMPORT, this)
.setIsExecutionAllowed(false)
.setTitle(ConstantsManager.getInstance().getConstants().next())
.setIsDefault(true)
);
model.getCommands().add(new UICommand(CMD_CANCEL, this)
.setTitle(ConstantsManager.getInstance().getConstants().cancel())
.setIsCancel(true)
);
model.initImportModels(
new UICommand(CMD_IMPORT, new BaseCommandTarget() {
@Override
public void executeCommand(UICommand uiCommand) {
model.onRestoreVms(
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
setWindow(null);
}
});
}
}).setTitle(ConstantsManager.getInstance().getConstants().ok())
.setIsDefault(true)
,
new UICommand(CMD_BACK, new BaseCommandTarget() {
@Override
public void executeCommand(UICommand uiCommand) {
setWindow(null); // remove current window first
setWindow(model);
}
}).setTitle(ConstantsManager.getInstance().getConstants().back())
,
new UICommand(CMD_CANCEL, this).setIsCancel(true)
.setTitle(ConstantsManager.getInstance().getConstants().cancel())
);
}
private void cloneVm() {
final VM vm = getSelectedItem();
if (vm == null) {
return;
}
CloneVmModel model = new CloneVmModel(vm, constants);
setWindow(model);
model.initialize();
model.setTitle(ConstantsManager.getInstance()
.getConstants().cloneVmTitle());
model.setHelpTag(HelpTag.clone_vm);
model.setHashName("clone_vm"); //$NON-NLS-1$
UICommand okCommand = UICommand.createDefaultOkUiCommand("OnClone", this); //$NON-NLS-1$
model.getCommands().add(okCommand);
UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
model.getCommands().add(cancelCommand);
}
private void onClone() {
((CloneVmModel) getWindow()).onClone(this, false);
}
private void onConfigureVmsToImport() {
final ImportVmsModel importVmsModel = (ImportVmsModel) getWindow();
if (importVmsModel == null) {
return;
}
final ImportVmModel model = importVmsModel.getSpecificImportModel();
setWindow(null); // remove import-vms window first
setWindow(model);
}
private void connectToConsoles() {
StringBuilder errorMessages = null;
final List<VM> list = getSelectedItems();
if (list == null || list.isEmpty()) {
return;
}
for (VM vm : list) {
try {
consolesFactory.getVmConsolesForVm(vm).connect();
} catch (VmConsoles.ConsoleConnectException e) {
final String errorMessage = e.getLocalizedErrorMessage();
if (errorMessage != null) {
if (errorMessages == null) {
errorMessages = new StringBuilder();
} else {
errorMessages.append("\r\n"); //$NON-NLS-1$
}
errorMessages
.append(vm.getName())
.append(" - ") //$NON-NLS-1$
.append(errorMessage);
}
}
}
if (errorMessages != null) {
errorPopupManager.show(errorMessages.toString());
}
}
private SystemTreeItemModel systemTreeSelectedItem;
@Override
public SystemTreeItemModel getSystemTreeSelectedItem() {
return systemTreeSelectedItem;
}
@Override
public void setSystemTreeSelectedItem(SystemTreeItemModel value) {
systemTreeSelectedItem = value;
onPropertyChanged(new PropertyChangedEventArgs("SystemTreeSelectedItem")); //$NON-NLS-1$
}
@Override
protected String getListName() {
return "VmListModel"; //$NON-NLS-1$
}
@Override
public boolean supportsServerSideSorting() {
return true;
}
@Override
protected Guid extractStoragePoolIdNullSafe(VM entity) {
return entity.getStoragePoolId();
}
}
|
package uk.ac.ebi.spot.goci.service;
import org.springframework.beans.factory.annotation.Autowired;
import uk.ac.ebi.spot.goci.model.FilterAssociation;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class FilteringService {
@Autowired
private List<FilterAssociation> associations;
Map<String, List<FilterAssociation>> byChrom;
@Autowired
FilteringService(List<FilterAssociation> associations){
this.associations = associations;
}
public void groupByChromosomeName(){
byChrom =
associations.stream()
.collect(Collectors.groupingBy(FilterAssociation::getChromosomeName));
for(String k : byChrom.keySet()){
System.out.print(k + "-");
for(FilterAssociation a : byChrom.get(k)){
System.out.print("\t" + a.getRowNumber());
}
System.out.print("\n");
}
}
public void sortByBPLocation(){
byChrom.forEach((k, v) -> {
List<FilterAssociation> byChromBP = v.stream()
.sorted((v1, v2) -> Integer.compare(v1.getChromosomePosition(), v2.getChromosomePosition()))
.collect(Collectors.toList());
byChrom.put(k, byChromBP);
}) ;
for(String k : byChrom.keySet()){
System.out.print(k + "-");
for(FilterAssociation a : byChrom.get(k)){
System.out.print("\t" + a.getRowNumber());
}
System.out.print("\n");
}
}
public void filterTopAssociations(){
byChrom.forEach((chromName, associations) -> {
if(associations.size() == 1 && associations.get(0).getPvalueExponent() < -5){
associations.get(0).setIsTopAssociation(true);
}
else {
int i =0;
while(i < associations.size()) {
FilterAssociation current = associations.get(i);
if(current.getPvalueExponent() < -5) {
Integer distToPrev = null;
if (i > 0) {
distToPrev = current.getChromosomePosition() - associations.get(i - 1).getChromosomePosition();
}
Integer distToNext = null;
if (i < associations.size() - 1) {
distToNext = associations.get(i + 1).getChromosomePosition() - current.getChromosomePosition();
}
if (distToPrev != null && distToNext != null && distToPrev > 100000 && distToNext > 100000) {
current.setIsTopAssociation(true);
}
else if (distToPrev == null && distToNext != null && distToNext > 100000) {
current.setIsTopAssociation(true);
}
else if (distToPrev != null && distToNext == null && distToPrev > 100000) {
current.setIsTopAssociation(true);
}
else if (distToNext != null && distToNext < 100000) {
FilterAssociation next = associations.get(i + 1);
Integer cpe = current.getPvalueExponent();
Integer npe = next.getPvalueExponent();
//TO DO: what if two associations in LD have the same p-value???
if (cpe == npe) {
Integer cpm = current.getPvalueMantissa();
Integer npm = next.getPvalueMantissa();
if (cpm < npm) {
current.setIsTopAssociation(true);
}
else {
next.setIsTopAssociation(true);
current.setIsTopAssociation(false);
}
}
else if (cpe < npe) {
current.setIsTopAssociation(true);
}
else {
next.setIsTopAssociation(true);
current.setIsTopAssociation(false);
}
}
}
i++;
}
}
});
for(String k : byChrom.keySet()){
System.out.print(k + " top -");
for(FilterAssociation a : byChrom.get(k)){
if(a.getIsTopAssociation()) {
System.out.print("\t" + a.getRowNumber());
}
}
System.out.print("\n");
System.out.print(k + " in LD -");
for(FilterAssociation a : byChrom.get(k)){
if(!a.getIsTopAssociation()) {
System.out.print("\t" + a.getRowNumber());
}
}
System.out.print("\n");
}
}
}
|
package org.sakaiproject.tool.gradebook.ui.helpers.beans.locallogic;
import org.sakaiproject.service.gradebook.shared.GradebookService;
import org.sakaiproject.tool.gradebook.ui.helpers.producers.*;
import org.sakaiproject.tool.gradebook.ui.helpers.params.GradebookItemViewParams;
import org.sakaiproject.tool.gradebook.ui.helpers.params.GradeGradebookItemViewParams;
import uk.org.ponder.rsf.builtin.UVBProducer;
import uk.org.ponder.rsf.viewstate.ViewParameters;
public class LocalPermissionLogic {
private GradebookService gradebookService;
public void setGradebookService(GradebookService gradebookService) {
this.gradebookService = gradebookService;
}
public Boolean checkCurrentUserHasViewPermission(ViewParameters incoming) {
if (GradebookItemProducer.VIEW_ID.equals(incoming.viewID)) {
String contextId = ((GradebookItemViewParams) incoming).contextId;
return gradebookService.currentUserHasEditPerm(contextId);
} else if (GradeGradebookItemProducer.VIEW_ID.equals(incoming.viewID)) {
String gradebookUid = ((GradeGradebookItemViewParams) incoming).contextId;
String userId = ((GradeGradebookItemViewParams) incoming).userId;
Long gradableObjectId = ((GradeGradebookItemViewParams) incoming).assignmentId;
return gradebookService.isUserAbleToGradeItemForStudent(gradebookUid, gradableObjectId, userId);
} else if (FinishedHelperProducer.VIEW_ID.equals(incoming.viewID)) {
return Boolean.TRUE;
} else if (UVBProducer.VIEW_ID.equals(incoming.viewID)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
|
package org.jtalks.jcommune.service.bb2htmlprocessors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UrlToLinkConvertPostProcessor implements TextPostProcessor {
private static final Pattern htmlTagsToSkip = Pattern.compile(
"(<a.*?>.*?</a>|<img.*?>.*?</img>|<pre.*?>.*?</pre>)",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private static final Pattern urlInText = Pattern.compile(
"(\\b((?:https?|ftp|file):\\/\\/|www\\.|ftp\\.)[-A-ZА-Я0-9+&@
Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.UNICODE_CHARACTER_CLASS | Pattern.UNICODE_CASE);
private static final String htmlLinkTemplate = "<a href=\"%s\">%s</a>";
@Override
public String postProcess(String bbDecodedText) {
return processLinks(bbDecodedText);
}
/**
* Search for text blocks outside {@code <a>, <img> and <pre>} tags,
* pass them to URL process method and build resulting post text
* with highlighted URLs
*
* @param bbEncodedText bb encoded text to process
* @return processed text
*/
private static String processLinks(String bbEncodedText) {
StringBuilder stringBuilder = new StringBuilder();
int prevPos = 0;
Matcher matcher = htmlTagsToSkip.matcher(bbEncodedText);
while (matcher.find()) {
String substring = bbEncodedText.substring(prevPos, matcher.start());
if (!substring.isEmpty()) {
stringBuilder.append(processUrlInText(substring));
}
stringBuilder.append(matcher.group());
prevPos = matcher.end();
}
if (prevPos == 0) {
return processUrlInText(bbEncodedText);
}
String substring = bbEncodedText.substring(prevPos, bbEncodedText.length());
if (!substring.isEmpty()) {
stringBuilder.append(processUrlInText(substring));
}
return stringBuilder.toString();
}
/**
* Search by URLs in textBlock and wrap them inside tags to highlight
*
* @param textBlock text for URL search and wrap
* @return text with wrapped URLs
*/
private static String processUrlInText(String textBlock) {
Matcher matcher = urlInText.matcher(textBlock);
StringBuilder stringBuilder = new StringBuilder();
int prevPos = 0;
while (matcher.find()) {
stringBuilder.append(textBlock.substring(prevPos, matcher.start()));
stringBuilder.append(complementUrlWithProtocol(matcher.group(1), matcher.group(2)));
prevPos = matcher.end();
}
if (prevPos == 0) {
return textBlock;
}
String substring = textBlock.substring(prevPos, textBlock.length());
if (!substring.isEmpty()) {
stringBuilder.append(substring);
}
return stringBuilder.toString();
}
private static String complementUrlWithProtocol(String url, String protocol) {
String htmlLink;
switch (protocol) {
case "www.":
htmlLink = "http://" + url;
break;
case "ftp.":
htmlLink = "ftp://" + url;
break;
default:
htmlLink = url;
}
return String.format(htmlLinkTemplate, htmlLink, url);
}
}
|
package org.sagebionetworks.gcp;
import java.util.Properties;
import com.amazonaws.util.StringUtils;
import com.google.api.gax.core.CredentialsProvider;
import com.google.auth.Credentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
public abstract class AbstractSynapseGoogleCloudCredentialsProvider implements CredentialsProvider {
public static final String GOOGLE_CLOUD_CREDENTIALS_WERE_NOT_FOUND = "Google Cloud credentials were not found.";
public static final String ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_ID = "org.sagebionetworks.google.cloud.client.id";
public static final String ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_EMAIL = "org.sagebionetworks.google.cloud.client.email";
public static final String ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_PRIVATE_KEY = "org.sagebionetworks.google.cloud.key";
public static final String ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_PRIVATE_KEY_ID = "org.sagebionetworks.google.cloud.key.id";
final Properties properties;
AbstractSynapseGoogleCloudCredentialsProvider(Properties properties) {
this.properties = properties;
}
/**
* Search the provided Properties for the credentials.
*/
final public Credentials getCredentials() {
try {
Properties properties = getProperties();
if (properties != null) {
String clientId = StringUtils.trim(properties.getProperty(ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_ID));
String clientEmail = StringUtils.trim(properties.getProperty(ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_EMAIL));
String privateKeyPkcs8 = StringUtils.trim(properties.getProperty(ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_PRIVATE_KEY));
String privateKeyId = StringUtils.trim(properties.getProperty(ORG_SAGEBIONETWORKS_GOOGLE_CLOUD_CLIENT_PRIVATE_KEY_ID));;
if (clientId != null && clientEmail != null && privateKeyPkcs8 != null && privateKeyId != null) {
return ServiceAccountCredentials.fromPkcs8(clientId, clientEmail, privateKeyPkcs8, privateKeyId, null);
}
}
throw new IllegalStateException(GOOGLE_CLOUD_CREDENTIALS_WERE_NOT_FOUND);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Extending classes provide a Properties object that could contain sage credentials.
* @return
*/
Properties getProperties() {
return this.properties;
}
}
|
package org.lttng.scope.lttng.kernel.core.activator.internal;
import org.lttng.scope.common.core.ScopeCoreActivator;
/**
* Plugin activator
*
* @noreference This class should not be accessed outside of this plugin.
*/
public class Activator extends ScopeCoreActivator {
/**
* Return the singleton instance of this activator.
*
* @return The singleton instance
*/
public static Activator instance() {
return ScopeCoreActivator.getInstance(Activator.class);
}
@Override
protected void startActions() {
// try {
// LttngAnalysesLoader.load();
// } catch (LamiAnalysisFactoryException | IOException e) {
// // Not the end of the world if the analyses are not available
// logWarning("Cannot find LTTng analyses configuration files: " + e.getMessage()); //$NON-NLS-1$
}
@Override
protected void stopActions() {
}
}
|
package oci.eval.ServiceNameRegistrationEvaluation;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Vector;
import oci.lib.ServiceNameEntry;
import oci.lib.ServiceNameRegistration;
import oci.lib.ServiceNameResolver;
/**
* This application is a simple benchmark tool for the OCI name service
*
*/
public class Evaluation
{
public static void main( String[] args )
{
System.out.println( "LOCIC based Name Service Lookup Benchmark" );
int entries = 200;
int probes = 20;
int min_delay = 0;
int max_delay = 0;
// if no arguments are given
if(args.length != 4) {
System.out.println("Usage Parameters: [entries] [probes] [min_delay_ms] [max_delay_ms]");
System.exit(0);
} else {
entries = Integer.parseInt(args[1]);
probes = Integer.parseInt(args[1]);
min_delay = Integer.parseInt(args[2]);
max_delay = Integer.parseInt(args[3]);
}
String locic_ip = "localhost";
int probe_offset = 0;
// value separator in csv file
String fileName = "samples_read_" + entries + "_" + probes + "_rand-" + min_delay + "-" + max_delay + ".csv";
String seperator = ";";
long startTime;
long stopTime;
String serviceName = null;
int serviceKey = ServiceNameEntry.NO_KEY;
int errors = 0;
File samples = new File(fileName);
FileWriter fWriter = null;
try {
fWriter = new FileWriter(samples);
} catch (IOException e) {
e.printStackTrace();
return;
}
BufferedWriter bWriter = new BufferedWriter(fWriter);
Vector<Long> times = new Vector<Long>();
// feed LOCIC with edge service name entries
for(int i = 0; i < entries; i++) {
if(errors > 5) return;
serviceName = "test" + i;
serviceKey = ServiceNameEntry.NO_KEY;
try {
startTime = System.nanoTime();
serviceKey = ServiceNameRegistration.registerEdgeService(serviceName, InetAddress.getByName(locic_ip));
stopTime = System.nanoTime();
times.add(stopTime - startTime);
if(serviceKey == ServiceNameEntry.NO_KEY) {
errors++;
}
// Thread.sleep(pause());
} catch(Exception error) {
error.printStackTrace();
errors++;
}
}
// write probes to file
float time_ms = 0;
float time_ms_average = 0;
try {
for(Long time : times) {
time_ms = (float) time / (float) 1000000;
time_ms_average += time_ms;
bWriter.write(String.format("%.3f", time_ms) + seperator);
System.out.print(String.format("%.3f", time_ms) + seperator);
}
bWriter.newLine();
bWriter.flush();
time_ms_average = time_ms_average - (float) (times.get(0) / 1000000);
time_ms_average = time_ms_average / (entries - 1);
bWriter.write(String.format("%.3f",time_ms_average) + seperator);
bWriter.newLine();
bWriter.flush();
System.out.println();
} catch (IOException e) {
e.printStackTrace();
return;
}
// System.out.println( "Summary: " );
times = null;
times = new Vector<Long>();
InetAddress edge_service_ip = null;
int probe = 0 + probe_offset;
// obtain edge service IP information
for(int i = 0; i < probes; i++) {
if(errors > 5) return;
// generate random service name within service boundaries
Double d = Math.random() * entries;
serviceName = "test" + d.intValue();
//serviceName = "test" + probe;
try {
startTime = System.nanoTime();
edge_service_ip = ServiceNameResolver.getEdgeServiceIpAddress(serviceName);
stopTime = System.nanoTime();
times.add(stopTime - startTime);
if(serviceKey == ServiceNameEntry.NO_KEY) {
errors++;
}
Thread.sleep(pause(min_delay, max_delay));
} catch(Exception error) {
error.printStackTrace();
errors++;
}
}
// writes probes to file
time_ms_average = 0;
try {
for(Long time : times) {
time_ms = (float) time / (float) 1000000;
time_ms_average += time_ms;
bWriter.write(String.format("%.3f",time_ms) + seperator);
System.out.print(String.format("%.3f", time_ms) + seperator);
}
bWriter.newLine();
bWriter.flush();
time_ms_average = time_ms_average - (float) (times.get(0) / 1000000);
time_ms_average = time_ms_average / (probes - 1);
bWriter.write(String.format("%.3f",time_ms_average) + seperator);
bWriter.newLine();
bWriter.flush();
System.out.println();
bWriter.close();
fWriter.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
// measure just system compute performance
startTime = System.nanoTime();
double rand_sum = Math.random() + Math.random();
stopTime = System.nanoTime();
System.out.println("Performance1: " + (stopTime - startTime));
startTime = System.nanoTime();
rand_sum = Math.random() + Math.random();
stopTime = System.nanoTime();
System.out.println("Performance2: " + (stopTime - startTime));
startTime = System.nanoTime();
rand_sum = Math.random() + Math.random();
stopTime = System.nanoTime();
System.out.println("Performance3: " + (stopTime - startTime));
startTime = System.nanoTime();
rand_sum = 6+10;
stopTime = System.nanoTime();
System.out.println("Performance4: " + (stopTime - startTime));
startTime = System.nanoTime();
rand_sum = 36+10;
stopTime = System.nanoTime();
System.out.println("Performance5: " + (stopTime - startTime));
return;
} // main
/**
* provides a random value between 1000 and 2500
* @return random value
*/
public static long pause() {
long offset = 1000;
long max = 2500;
long pause = 0;
pause = (long) (Math.random() * max) + offset; // time between [offset] and [offset + max]
return pause;
}
/**
* provides a random value between min and max
* @param min smallest random value
* @param max biggest random value
* @return random value
*/
public static long pause(int min, int max) {
long pause = 0;
pause = (long) (Math.random() * (max-min)) + min; // time between [offset] and [offset + max]
return pause;
}
} // App
|
package com.jetbrains.python.sdk;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.facet.Facet;
import com.intellij.facet.FacetConfiguration;
import com.intellij.facet.FacetManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
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.projectRoots.*;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.facet.PythonFacetSettings;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author yole
*/
public class PythonSdkType extends SdkType {
private static final Logger LOG = Logger.getInstance("#" + PythonSdkType.class.getName());
private Project myProjectForProgress; // used for progress-indicated path setup
/**
* Poor man's way to have setupSdkPaths run under a progress dialog, when possible.
* @param project project to pass to ProgressManager.run().
*/
public void setProjectForProgress(Project project) {
myProjectForProgress = project;
}
public static PythonSdkType getInstance() {
return SdkType.findInstance(PythonSdkType.class);
}
public PythonSdkType() {
super("Python SDK");
}
public Icon getIcon() {
return PythonFileType.INSTANCE.getIcon();
}
public Icon getIconForAddAction() {
return PythonFileType.INSTANCE.getIcon();
}
@NonNls
@Nullable
public String suggestHomePath() {
@NonNls final String PYTHON_STR = "python";
TreeSet<String> candidates = new TreeSet<String>();
if (SystemInfo.isWindows) {
VirtualFile rootDir = LocalFileSystem.getInstance().findFileByPath("C:\\");
if (rootDir != null) {
VirtualFile[] topLevelDirs = rootDir.getChildren();
for(VirtualFile dir: topLevelDirs) {
if (dir.isDirectory() && dir.getName().toLowerCase().startsWith(PYTHON_STR)) {
candidates.add(dir.getPath());
}
}
}
}
else if (SystemInfo.isLinux) {
VirtualFile rootDir = LocalFileSystem.getInstance().findFileByPath("/usr/lib");
if (rootDir != null) {
VirtualFile[] suspect_dirs = rootDir.getChildren();
for(VirtualFile dir: suspect_dirs) {
if (dir.isDirectory() && dir.getName().startsWith(PYTHON_STR)) {
candidates.add(dir.getPath());
}
}
}
}
else if (SystemInfo.isMac) {
return "/Library/Frameworks/Python.framework/Versions/Current/";
}
if (candidates.size() > 0) {
// return latest version
String[] candidateArray = candidates.toArray(new String[candidates.size()]);
return candidateArray [candidateArray.length-1];
}
return null;
}
public boolean isValidSdkHome(final String path) {
return isPythonSdkHome(path) || isJythonSdkHome(path);
}
/**
* Checks if the path is a valid home.
* Valid CPython home must contain some standard libraries. Of them we look for re.py, __future__.py and site-packages/.
* @param path path to check.
* @return true if paths points to a valid home.
*/
@NonNls
private static boolean isPythonSdkHome(final String path) {
if (SystemInfo.isLinux) {
// on Linux, Python SDK home points to the /lib directory of a particular Python version
File f_re = new File(path, "re.py");
File f_future = new File(path, "__future__.py");
File f_site = new File(path, "site-packages");
File f_dist = new File(path, "dist-packages");
return (
f_re.exists() &&
f_future.exists() &&
(f_site.exists() && f_site.isDirectory()) || (f_dist.exists() && f_dist.isDirectory())
);
}
else {
File f = getPythonBinaryPath(path);
return f != null && f.exists();
}
}
private static boolean isJythonSdkHome(final String path) {
File f = getJythonBinaryPath(path);
return f != null && f.exists();
}
@Nullable
private static File getJythonBinaryPath(final String path) {
if (SystemInfo.isWindows) {
return new File(path, "jython.bat");
}
else if (SystemInfo.isMac) {
return new File(new File(path, "bin"), "jython"); // TODO: maybe use a smarter way
}
else if (SystemInfo.isLinux) {
File jy_binary = new File(path, "jython"); // probably /usr/bin/jython
if (jy_binary.exists()) {
return jy_binary;
}
}
return null;
}
@NonNls
private static File getPythonBinaryPath(final String path) {
if (SystemInfo.isWindows) {
return new File(path, "python.exe");
}
else if (SystemInfo.isMac) {
return new File(new File(path, "bin"), "python");
}
else if (SystemInfo.isLinux) {
// most probably path is like "/usr/lib/pythonX.Y"; executable is most likely /usr/bin/pythonX.Y
Matcher m = Pattern.compile(".*/(python\\d\\.\\d)").matcher(path);
File py_binary;
if (m.matches()) {
String py_name = m.group(1);
py_binary = new File("/usr/bin/"+py_name); // XXX broken logic! can't match the lib to the bin
}
else py_binary = new File("/usr/bin/python"); // TODO: search in $PATH
if (py_binary.exists()) return py_binary;
}
return null;
}
public String suggestSdkName(final String currentSdkName, final String sdkHome) {
String name = getVersionString(sdkHome);
if (name == null) name = "Unknown at " + sdkHome; // last resort
return name;
}
public AdditionalDataConfigurable createAdditionalDataConfigurable(final SdkModel sdkModel, final SdkModificator sdkModificator) {
return null;
}
public void saveAdditionalData(final SdkAdditionalData additionalData, final Element additional) {
}
@Override
public SdkAdditionalData loadAdditionalData(final Sdk currentSdk, final Element additional) {
final String[] urls = currentSdk.getRootProvider().getUrls(OrderRootType.SOURCES);
for (String url : urls) {
if (url.contains("python_stubs")) {
final String path = VfsUtil.urlToPath(url);
File stubs_dir = new File(path);
if (!stubs_dir.exists()) {
generateBuiltinStubs(currentSdk.getHomePath(), path);
}
generateBinaryStubs(currentSdk.getHomePath(), path, null); // TODO: add a nice progress indicator somehow
break;
}
}
return null;
}
@NonNls
public String getPresentableName() {
return "Python SDK";
}
public void setupSdkPaths(final Sdk sdk) {
final SdkModificator[] sdk_mod_holder = new SdkModificator[]{null};
if (myProjectForProgress != null) { // nice, progress-bar way
ProgressManager progman = ProgressManager.getInstance();
final Task.Modal setup_task = new Task.Modal(myProjectForProgress, "Setting up library files", false) {
public void run(@NotNull final ProgressIndicator indicator) {
sdk_mod_holder[0] = setupSdkPathsUnderProgress(sdk, indicator);
}
};
progman.run(setup_task);
if (sdk_mod_holder[0] != null) sdk_mod_holder[0].commitChanges(); // commit in dispatch thread, not task's
}
else { // old, dull way
final SdkModificator modificator = setupSdkPathsUnderProgress(sdk, null);
if (modificator != null) modificator.commitChanges();
}
}
protected SdkModificator setupSdkPathsUnderProgress(final Sdk sdk, ProgressIndicator indicator) {
final SdkModificator sdkModificator = sdk.getSdkModificator();
String sdk_path = sdk.getHomePath();
String bin_path = getInterpreterPath(sdk_path);
@NonNls final String stubs_path =
PathManager.getSystemPath() + File.separator + "python_stubs" + File.separator + sdk_path.hashCode() + File.separator;
// we have a number of lib dirs, those listed in python's sys.path
if (indicator != null) {
indicator.setText("Adding library roots");
}
final List<String> paths = getSysPath(sdk_path, bin_path);
if ((paths != null) && paths.size() > 0) {
// add every path as root.
for (String path: paths) {
if (path.indexOf(File.separator) < 0) continue; // TODO: interpret possible 'special' paths reasonably
if (indicator != null) {
indicator.setText2(path);
}
VirtualFile child = LocalFileSystem.getInstance().findFileByPath(path);
if (child != null) {
@NonNls String suffix = child.getExtension();
if (suffix != null) suffix = suffix.toLowerCase(); // Why on earth empty suffix is null and not ""?
if ((!child.isDirectory()) && ("zip".equals(suffix) || "egg".equals(suffix))) {
// a .zip / .egg file must have its root extracted first
child = JarFileSystem.getInstance().getJarRootForLocalFile(child);
}
if (child != null) {
sdkModificator.addRoot(child, OrderRootType.SOURCES);
sdkModificator.addRoot(child, OrderRootType.CLASSES);
}
}
else LOG.info("Bogus sys.path entry "+path);
}
if (indicator != null) {
indicator.setText("Generating skeletons of __builtins__");
indicator.setText2("");
}
generateBuiltinStubs(sdk_path, stubs_path);
sdkModificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByPath(stubs_path), OrderRootType.SOURCES);
}
generateBinaryStubs(sdk_path, stubs_path, indicator);
return sdkModificator;
//sdkModificator.commitChanges() must happen outside, and probably in a different thread.
}
private static List<String> getSysPath(String sdk_path, String bin_path) {
@NonNls String script = // a script printing sys.path
"import sys\n"+
"import os.path\n" +
"for x in sys.path:\n"+
" if x != os.path.dirname(sys.argv [0]): sys.stdout.write(x+chr(10))";
try {
final File scriptFile = File.createTempFile("script", ".py");
try {
PrintStream out = new PrintStream(scriptFile);
try {
out.print(script);
}
finally {
out.close();
}
return SdkUtil.getProcessOutput(sdk_path, new String[] {bin_path, scriptFile.getPath()}).getStdout();
}
finally {
FileUtil.delete(scriptFile);
}
}
catch (IOException e) {
LOG.info(e);
return Collections.emptyList();
}
}
@Nullable
public String getVersionString(final String sdkHome) {
String binaryPath = getInterpreterPath(sdkHome);
final boolean isJython = isJythonSdkHome(sdkHome);
@NonNls String version_regexp, version_opt;
if (isJython) {
version_regexp = "(Jython \\S+) on .*";
version_opt = "--version";
}
else { // CPython
version_regexp = "(Python \\S+).*";
version_opt = "-V";
}
Pattern pattern = Pattern.compile(version_regexp);
String version = SdkUtil.getFirstMatch(SdkUtil.getProcessOutput(sdkHome, new String[] {binaryPath, version_opt}).getStderr(), pattern);
return version;
}
public static String getInterpreterPath(final String sdkHome) {
if (isJythonSdkHome(sdkHome)) {
return getJythonBinaryPath(sdkHome).getPath();
}
return getPythonBinaryPath(sdkHome).getPath();
}
public static void generateBuiltinStubs(String sdkPath, final String stubsRoot) {
new File(stubsRoot).mkdirs();
try {
final String text = FileUtil.loadTextAndClose(new InputStreamReader(PythonSdkType.class.getResourceAsStream("generator3.py")));
final File tempFile = FileUtil.createTempFile("gen", "");
FileWriter out = new FileWriter(tempFile);
out.write(text);
out.close();
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath(getInterpreterPath(sdkPath)); // python
commandLine.addParameter(tempFile.getAbsolutePath()); // gen.py
commandLine.addParameter("-d"); commandLine.addParameter(stubsRoot); // -d stubs_root
commandLine.addParameter("-b"); // for builtins
commandLine.addParameter("-u"); // for update-only mode
try {
final OSProcessHandler handler = new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString());
handler.startNotify();
handler.waitFor();
handler.destroyProcess();
}
catch (ExecutionException e) {
LOG.error(e);
}
}
catch (IOException e) {
LOG.error(e);
}
}
/**
* (Re-)generates skeletons for all binary python modules. Up-to-date stubs not regenerated.
* Does one module at a time: slower, but avoids certain conflicts.
* @param sdkPath where to find interpreter.
* @param stubsRoot where to put results (expected to exist).
* @param indicator ProgressIndicator to update, or null.
*/
public static void generateBinaryStubs(final String sdkPath, final String stubsRoot, ProgressIndicator indicator) {
if (!new File(stubsRoot).exists()) return;
if (indicator != null) {
indicator.setText("Generating skeletons of binary libs");
}
try {
final int RUN_TIMEOUT = 10*1000; // 10 seconds per call is plenty enough; anything more is clearly wrong.
final String bin_path = getInterpreterPath(sdkPath);
String text;
FileWriter out;
text = FileUtil.loadTextAndClose(new InputStreamReader(PythonSdkType.class.getResourceAsStream("find_binaries.py")));
final File find_bin_file = FileUtil.createTempFile("find_bin", "");
out = new FileWriter(find_bin_file);
out.write(text);
out.close();
text = FileUtil.loadTextAndClose(new InputStreamReader(PythonSdkType.class.getResourceAsStream("generator3.py")));
final File gen3_file = FileUtil.createTempFile("gen3", "");
out = new FileWriter(gen3_file);
out.write(text);
out.close();
try {
final SdkUtil.ProcessCallInfo run_result = SdkUtil.getProcessOutput(sdkPath, new String[] {bin_path, find_bin_file.getPath()});
if (run_result.getExitValue() == 0) {
for (String line : run_result.getStdout()) {
// line = "mod_name path"
int cutpos = line.indexOf(' ');
String modname = line.substring(0, cutpos);
String mod_fname = modname.replace(".", File.separator); // "a.b.c" -> "a/b/c", no ext
String fname = line.substring(cutpos+1);
//String ext = fname.substring(fname.lastIndexOf('.')); // no way ext is absent
// check if it's fresh
File f_orig = new File(fname);
File f_skel = new File(stubsRoot + File.separator + mod_fname + ".py");
if (f_orig.lastModified() >= f_skel.lastModified()) {
// skeleton stale, rebuild
if (indicator != null) {
indicator.setText2(modname);
}
LOG.info("Skeleton for " + modname);
final SdkUtil.ProcessCallInfo gen_result = SdkUtil.getProcessOutput(sdkPath,
new String[] {bin_path, gen3_file.getPath(), "-d", stubsRoot, modname}, RUN_TIMEOUT
);
if (gen_result.getExitValue() != 0) {
StringBuffer sb = new StringBuffer("Skeleton for ");
sb.append(modname).append(" failed. stderr:
for (String err_line : gen_result.getStderr()) sb.append(err_line).append("\n");
sb.append("
LOG.warn(sb.toString());
}
}
}
}
else {
StringBuffer sb = new StringBuffer();
for (String err_line : run_result.getStderr()) sb.append(err_line).append("\n");
LOG.error("failed to run find_binaries, exit code " + run_result.getExitValue() + ", stderr '" + sb.toString() + "'");
}
}
finally {
FileUtil.delete(find_bin_file);
FileUtil.delete(gen3_file);
}
}
catch (IOException e) {
LOG.error(e);
}
}
public static List<Sdk> getAllSdks() {
return ProjectJdkTable.getInstance().getSdksOfType(getInstance());
}
@Nullable
public static Sdk findPythonSdk(Module module) {
if (module == null) return null;
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof PythonSdkType) return sdk;
final Facet[] facets = FacetManager.getInstance(module).getAllFacets();
for (Facet facet : facets) {
final FacetConfiguration configuration = facet.getConfiguration();
if (configuration instanceof PythonFacetSettings) {
return ((PythonFacetSettings) configuration).getSdk();
}
}
return null;
}
}
|
package org.opennms.netmgt.provision.service;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.mina.core.future.IoFutureListener;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.dao.SnmpAgentConfigFactory;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.OnmsSnmpInterface;
import org.opennms.netmgt.provision.AsyncServiceDetector;
import org.opennms.netmgt.provision.DetectFuture;
import org.opennms.netmgt.provision.IpInterfacePolicy;
import org.opennms.netmgt.provision.NodePolicy;
import org.opennms.netmgt.provision.ServiceDetector;
import org.opennms.netmgt.provision.SnmpInterfacePolicy;
import org.opennms.netmgt.provision.SyncServiceDetector;
import org.opennms.netmgt.provision.service.NodeScan.AgentScan;
import org.opennms.netmgt.provision.service.NodeScan.IpInterfaceScan;
import org.opennms.netmgt.provision.service.lifecycle.Phase;
import org.opennms.netmgt.provision.service.lifecycle.annotations.Activity;
import org.opennms.netmgt.provision.service.lifecycle.annotations.ActivityProvider;
import org.opennms.netmgt.provision.service.snmp.SystemGroup;
import org.opennms.netmgt.provision.service.tasks.Async;
import org.opennms.netmgt.provision.service.tasks.Callback;
import org.opennms.netmgt.provision.support.NullDetectorMonitor;
import org.opennms.netmgt.snmp.SnmpAgentConfig;
import org.opennms.netmgt.snmp.SnmpUtils;
import org.opennms.netmgt.snmp.SnmpWalker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
/**
* CoreImportActivities
*
* @author brozow
*/
@ActivityProvider
public class CoreScanActivities {
@Autowired ProvisionService m_provisionService;
@Autowired
private SnmpAgentConfigFactory m_agentConfigFactory;
/*
* load the node from the database (or maybe the requistion)
*
* walk the snmp interface table
* - add non-existent snmp interfaces to the database
* - update snmp interfaces that have changed
* - delete snmp interfaces that no longer exist
* walk the ip interface table
* - add non-existent ip interfaces to the database
* - associate the ipinterface with the corresponding snmp interface
* - update ipInterfaces that have changed
* - delete ipInterfaces that no longer exist
*
* for each ipinterface - detect services
* - add serivces that have yet been detected/provisioned on the interface
*
*
* nodeScan.collectNodeInfo
* nodeScan.persistNodeInfo
*
* nodeScan.detectPhysicalInterfaces
* nodeScan.persistPhysicalInterfaces
*
* nodeScan.detectIpInterfaces
* nodeScan.persistIpInterfaces
*
* serviceDetect.detectIfService
* serviceDetect.persistIfService
*
*
*
* nodeScan:
* precond: foreignSource, foreignId of req'd node
* postcond: node
* - loadNode
*
* precond: node with primary address
* postcond: agents detected and agentScan lifeCycle for each agent started
* configuration for agents in lifecycle
* - detectAgents
* - agentScan for each agent
*
* precond: agent scans complete
*
* -update lastCapsdPoll
*
*
* agentScan:
*
* collectNodeInfo
* - this needs set the scan stamp
*
* persistNodeInfo
*
* scanForPhysicalInterfaces
* - for each found save the interface and set the scan stamp
* - make sure we update
*
* scanForIpInterfaces
* - for each found save the interface and set the scan stmp
* - include the association with the physical interface
* - start the ipInterfaceScan for the interface
*
*
* ipInterfaceScan
* - scan for each service configured in the detector
*
*
*/
@Activity( lifecycle = "nodeScan", phase = "loadNode" )
public void loadNode(Phase currentPhase, NodeScan nodeScan) {
nodeScan.doLoadNode(currentPhase);
}
@Activity( lifecycle = "nodeScan", phase = "detectAgents" )
public void detectAgents(Phase currentPhase, NodeScan nodeScan) {
// someday I'll change this to use agentDetectors
OnmsIpInterface primaryIface = nodeScan.getNode().getPrimaryInterface();
if (primaryIface.getMonitoredServiceByServiceType("SNMP") != null) {
nodeScan.doAgentScan(currentPhase, primaryIface.getInetAddress(), "SNMP");
}
}
@Activity( lifecycle = "agentScan", phase = "collectNodeInfo" )
public void collectNodeInfo(Phase currentPhase, AgentScan agentScan) throws InterruptedException {
Date scanStamp = new Date();
agentScan.setScanStamp(scanStamp);
InetAddress primaryAddress = agentScan.getAgentAddress();
SnmpAgentConfig agentConfig = m_agentConfigFactory.getAgentConfig(primaryAddress);
Assert.notNull(m_agentConfigFactory, "agentConfigFactory was not injected");
SystemGroup systemGroup = new SystemGroup(primaryAddress);
SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "systemGroup", systemGroup);
walker.start();
walker.waitFor();
systemGroup.updateSnmpDataForNode(agentScan.getNode());
List<NodePolicy> nodePolicies = m_provisionService.getNodePoliciesForForeignSource(agentScan.getForeignSource());
OnmsNode node = agentScan.getNode();
for(NodePolicy policy : nodePolicies) {
if (node != null) {
node = policy.apply(node);
}
}
agentScan.setNode(node);
}
@Activity( lifecycle = "agentScan", phase = "persistNodeInfo", schedulingHint="write")
public void persistNodeInfo(Phase currentPhase, AgentScan agentScan) {
agentScan.doPersistNodeInfo();
}
@Activity( lifecycle = "agentScan", phase = "detectPhysicalInterfaces" )
public void detectPhysicalInterfaces(final Phase currentPhase, final AgentScan agentScan) throws InterruptedException {
SnmpAgentConfig agentConfig = m_agentConfigFactory.getAgentConfig(agentScan.getAgentAddress());
Assert.notNull(m_agentConfigFactory, "agentConfigFactory was not injected");
final PhysInterfaceTableTracker physIfTracker = new PhysInterfaceTableTracker() {
@Override
public void processPhysicalInterfaceRow(PhysicalInterfaceRow row) {
System.out.println("Processing row for ifIndex "+row.getIfIndex());
OnmsSnmpInterface snmpIface = row.createInterfaceFromRow();
snmpIface.setLastCapsdPoll(agentScan.getScanStamp());
List<SnmpInterfacePolicy> policies = m_provisionService.getSnmpInterfacePoliciesForForeignSource(agentScan.getForeignSource());
for(SnmpInterfacePolicy policy : policies) {
if (snmpIface != null) {
snmpIface = policy.apply(snmpIface);
}
}
if (snmpIface != null) {
final OnmsSnmpInterface snmpIfaceResult = snmpIface;
// add call to the snmp interface collection enable policies
Runnable r = new Runnable() {
public void run() {
System.out.println("Saving OnmsSnmpInterface "+snmpIfaceResult);
m_provisionService.updateSnmpInterfaceAttributes(
agentScan.getNodeId(),
snmpIfaceResult);
}
};
currentPhase.add(r, "write");
}
}
};
SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "ifTable/ifXTable", physIfTracker);
walker.start();
walker.waitFor();
System.err.println("detectPhysicalInterfaces");
}
@Activity( lifecycle = "agentScan", phase = "detectIpInterfaces" )
public void detectIpInterfaces(final Phase currentPhase, final AgentScan agentScan) throws InterruptedException {
SnmpAgentConfig agentConfig = m_agentConfigFactory.getAgentConfig(agentScan.getAgentAddress());
Assert.notNull(m_agentConfigFactory, "agentConfigFactory was not injected");
// mark all provisioned interfaces as 'in need of scanning' so we can mark them
// as scanned during ipAddrTable processing
final Set<String> provisionedIps = new HashSet<String>();
for(OnmsIpInterface provisioned : agentScan.getNode().getIpInterfaces()) {
provisionedIps.add(provisioned.getIpAddress());
}
final IPInterfaceTableTracker ipIfTracker = new IPInterfaceTableTracker() {
@Override
public void processIPInterfaceRow(IPInterfaceRow row) {
System.out.println("Processing row with ipAddr "+row.getIpAddress());
if (!row.getIpAddress().startsWith("127.0.0")) {
// mark any provisioned interface as scanned
provisionedIps.remove(row.getIpAddress());
// save the interface
OnmsIpInterface iface = row.createInterfaceFromRow();
iface.setIpLastCapsdPoll(agentScan.getScanStamp());
// add call to the ip interface is managed policies
iface.setIsManaged("M");
List<IpInterfacePolicy> policies = m_provisionService.getIpInterfacePoliciesForForeignSource(agentScan.getForeignSource());
for(IpInterfacePolicy policy : policies) {
if (iface != null) {
iface = policy.apply(iface);
}
}
if (iface != null) {
currentPhase.add(ipUpdater(currentPhase, agentScan, iface), "write");
}
}
}
};
SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "ipAddrTable", ipIfTracker);
walker.start();
walker.waitFor();
// After processing the snmp provided interfaces then we need to scan any that
// were provisioned but missing from the ip table
for(String ipAddr : provisionedIps) {
OnmsIpInterface iface = agentScan.getNode().getIpInterfaceByIpAddress(ipAddr);
iface.setIpLastCapsdPoll(agentScan.getScanStamp());
iface.setIsManaged("M");
currentPhase.add(ipUpdater(currentPhase, agentScan, iface), "write");
}
System.err.println("detectIpInterfaces");
}
@Activity( lifecycle = "agentScan", phase = "deleteObsoleteResources", schedulingHint="write")
public void deleteObsoleteResources(Phase currentPhase, AgentScan agentScan) {
m_provisionService.updateNodeScanStamp(agentScan.getNodeId(), agentScan.getScanStamp());
m_provisionService.deleteObsoleteInterfaces(agentScan.getNodeId(), agentScan.getScanStamp());
System.err.println("agentScan.deleteObsoleteResources");
}
@Activity( lifecycle = "ipInterfaceScan", phase = "detectServices" )
public void detectServices(Phase currentPhase, IpInterfaceScan ifaceScan) throws InterruptedException {
Collection<ServiceDetector> detectors = m_provisionService.getDetectorsForForeignSource(ifaceScan.getForeignSource());
Integer nodeId = ifaceScan.getNodeId();
InetAddress ipAddress = ifaceScan.getAddress();
System.err.println(String.format("detectServices for %d : %s: found %d detectors", nodeId, ipAddress.getHostAddress(), detectors.size()));
for(ServiceDetector detector : detectors) {
addServiceDetectorTask(currentPhase, detector, nodeId, ipAddress);
}
}
private void addServiceDetectorTask(Phase currentPhase, ServiceDetector detector, Integer nodeId, InetAddress ipAddress) {
if (detector instanceof SyncServiceDetector) {
addSyncServiceDetectorTask(currentPhase, nodeId, ipAddress, (SyncServiceDetector)detector);
} else {
addAsyncServiceDetectorTask(currentPhase, nodeId, ipAddress, (AsyncServiceDetector)detector);
}
}
private void addAsyncServiceDetectorTask(Phase currentPhase, Integer nodeId, InetAddress ipAddress, AsyncServiceDetector detector) {
currentPhase.add(runDetector(ipAddress, detector), persistService(nodeId, ipAddress, detector));
}
private void addSyncServiceDetectorTask(Phase currentPhase, final Integer nodeId, final InetAddress ipAddress, final SyncServiceDetector detector) {
currentPhase.add(runDetector(ipAddress, detector, persistService(nodeId, ipAddress, detector)));
}
private Callback<Boolean> persistService(final Integer nodeId, final InetAddress ipAddress, final ServiceDetector detector) {
return new Callback<Boolean>() {
public void complete(Boolean serviceDetected) {
info("Attempted to detect service %s on address %s: %s", detector.getServiceName(), ipAddress.getHostAddress(), serviceDetected);
if (serviceDetected) {
m_provisionService.addMonitoredService(nodeId, ipAddress.getHostAddress(), detector.getServiceName());
}
}
public void handleException(Throwable t) {
info(t, "Exception occurred trying to detect service %s on address %s", detector.getServiceName(), ipAddress.getHostAddress());
}
};
}
private Async<Boolean> runDetector(InetAddress ipAddress, AsyncServiceDetector detector) {
return new AsyncDetectorRunner(ipAddress, detector);
}
private Runnable runDetector(final InetAddress ipAddress, final SyncServiceDetector detector, final Callback<Boolean> cb) {
return new Runnable() {
public void run() {
try {
info("Attemping to detect service %s on address %s", detector.getServiceName(), ipAddress.getHostAddress());
cb.complete(detector.isServiceDetected(ipAddress, new NullDetectorMonitor()));
} catch (Throwable t) {
cb.handleException(t);
}
}
@Override
public String toString() {
return String.format("Run detector %s on address %s", detector.getServiceName(), ipAddress.getHostAddress());
}
};
}
private class AsyncDetectorRunner implements Async<Boolean> {
private final AsyncServiceDetector m_detector;
private final InetAddress m_ipAddress;
public AsyncDetectorRunner(InetAddress address, AsyncServiceDetector detector) {
m_detector = detector;
m_ipAddress = address;
}
public void submit(Callback<Boolean> cb) {
try {
info("Attemping to detect service %s on address %s", m_detector.getServiceName(), m_ipAddress.getHostAddress());
DetectFuture future = m_detector.isServiceDetected(m_ipAddress, new NullDetectorMonitor());
future.addListener(listener(cb));
} catch (Throwable e) {
cb.handleException(e);
}
}
@Override
public String toString() {
return String.format("Run detector %s on address %s", m_detector.getServiceName(), m_ipAddress.getHostAddress());
}
private IoFutureListener<DetectFuture> listener(final Callback<Boolean> cb) {
return new IoFutureListener<DetectFuture>() {
public void operationComplete(DetectFuture future) {
if (future.getException() != null) {
cb.handleException(future.getException());
} else {
cb.complete(future.isServiceDetected());
}
}
};
}
}
private void error(Throwable t, String format, Object... args) {
Logger log = ThreadCategory.getInstance(getClass());
log.error(String.format(format, args), t);
}
private void debug(String format, Object... args) {
Logger log = ThreadCategory.getInstance(getClass());
if (log.isDebugEnabled()) {
log.debug(String.format(format, args));
};
}
private void info(Throwable t, String format, Object... args) {
Logger log = ThreadCategory.getInstance(getClass());
if (log.isInfoEnabled()) {
log.info(String.format(format, args), t);
}
}
private void info(String format, Object... args) {
Logger log = ThreadCategory.getInstance(getClass());
if (log.isInfoEnabled()) {
log.info(String.format(format, args));
}
}
private void error(String format, Object... args) {
Logger log = ThreadCategory.getInstance(getClass());
log.error(String.format(format, args));
}
private Runnable ipUpdater(final Phase currentPhase,
final AgentScan agentScan, final OnmsIpInterface iface) {
Runnable r = new Runnable() {
public void run() {
agentScan.doUpdateIPInterface(currentPhase, iface);
if (iface.isManaged()) {
agentScan.triggerIPInterfaceScan(currentPhase, iface.getInetAddress());
}
}
};
return r;
}
}
|
package railo.runtime.type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import railo.commons.lang.StringList;
import railo.commons.lang.StringUtil;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.op.Caster;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.comparator.NumberComparator;
import railo.runtime.type.comparator.TextComparator;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.CollectionUtil;
/**
* List is not a type, only some static method to manipulate String lists
*/
public final class List {
/**
* casts a list to Array object, the list can be have quoted (",') arguments and delimter in this arguments are ignored. quotes are not removed
* example:
* listWithQuotesToArray("aab,a'a,b',a\"a,b\"",",","\"'") will be translated to ["aab","a'a,b'","a\"a,b\""]
*
*
*
* @param list list to cast
* @param delimiter delimter of the list
* @param quotes quotes of the list
* @return Array Object
*/
public static Array listWithQuotesToArray(String list, String delimiter,String quotes) {
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
char[] del=delimiter.toCharArray();
char[] quo=quotes.toCharArray();
char c;
char inside=0;
ArrayImpl array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<quo.length;y++){
if(c==quo[y]) {
if(c==inside)inside=0;
else if(inside==0)inside=c;
continue;
}
}
for(int y=0;y<del.length;y++) {
if(inside==0 && c==del[y]) {
array._append(list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)array.append(list.substring(last));
}
catch(ExpressionException e){}
return array;
}
/**
* casts a list to Array object
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static Array listToArray(String list, String delimiter) {
if(delimiter.length()==1)return listToArray(list, delimiter.charAt(0));
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
char[] del=delimiter.toCharArray();
char c;
ArrayImpl array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
array.appendEL(list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)array.append(list.substring(last));
}
catch(ExpressionException e){}
return array;
}
public static Array listToArray(String list, String delimiter, boolean multiCharDelim) {
if(!multiCharDelim) return listToArray(list, delimiter);
if(delimiter.length()==1)return listToArray(list, delimiter.charAt(0));
int len=list.length();
if(len==0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimiter.length();
while((index=list.indexOf(delimiter,from))!=-1){
array.appendEL(list.substring(from,index));
from=index+dl;
}
array.appendEL(list.substring(from,len));
return array;
}
/**
* casts a list to Array object
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static Array listToArray(String list, char delimiter) {
if(list.length()==0) return new ArrayImpl();
int len=list.length();
int last=0;
Array array=new ArrayImpl();
try{
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
array.append(list.substring(last,i));
last=i+1;
}
}
if(last<=len)array.append(list.substring(last));
}
catch(PageException e){}
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static Array listToArrayRemoveEmpty(String list, String delimiter, boolean multiCharDelim) {
if(!multiCharDelim) return listToArrayRemoveEmpty(list, delimiter);
if(delimiter.length()==1)return listToArrayRemoveEmpty(list, delimiter.charAt(0));
int len=list.length();
if(len==0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimiter.length();
while((index=list.indexOf(delimiter,from))!=-1){
if(from<index)array.appendEL(list.substring(from,index));
from=index+dl;
}
if(from<len)array.appendEL(list.substring(from,len));
return array;
}
public static Array listToArrayRemoveEmpty(String list, String delimiter) {
if(delimiter.length()==1)return listToArrayRemoveEmpty(list, delimiter.charAt(0));
int len=list.length();
ArrayImpl array=new ArrayImpl();
if(len==0) return array;
int last=0;
char[] del = delimiter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i)array._append(list.substring(last,i));
last=i+1;
}
}
}
if(last<len)array._append(list.substring(last));
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static Array listToArrayRemoveEmpty(String list, char delimiter) {
int len=list.length();
ArrayImpl array=new ArrayImpl();
if(len==0) return array;
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
if(last<i)array._append(list.substring(last,i));
last=i+1;
}
}
if(last<len)array._append(list.substring(last));
return array;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static String rest(String list, String delimiter, boolean ignoreEmpty) {
//if(delimiter.length()==1)return rest(list, delimiter.charAt(0));
int len=list.length();
if(len==0) return "";
//int last=-1;
char[] del = delimiter.toCharArray();
char c;
if(ignoreEmpty)list=ltrim(list,del);
len=list.length();
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
return ignoreEmpty?ltrim(list.substring(i+1),del):list.substring(i+1);
}
}
}
return "";
}
private static String ltrim(String list,char[] del) {
int len=list.length();
char c;
// remove at start
outer:while(len>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
len=list.length();
continue outer;
}
}
break;
}
return list;
}
/**
* casts a list to Array object remove Empty Elements
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static StringList listToStringListRemoveEmpty(String list, char delimiter) {
int len=list.length();
StringList rtn=new StringList();
if(len==0) return rtn.reset();
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
if(last<i)rtn.add(list.substring(last,i));
last=i+1;
}
}
if(last<len)rtn.add(list.substring(last));
return rtn.reset();
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static Array listToArrayTrim(String list, String delimiter) {
if(delimiter.length()==1)return listToArrayTrim(list, delimiter.charAt(0));
if(list.length()==0) return new ArrayImpl();
char[] del = delimiter.toCharArray();
char c;
// remove at start
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
continue outer;
}
}
break;
}
int len;
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
continue outer;
}
}
break;
}
return listToArray(list, delimiter);
}
/**
* casts a list to Array object, remove all empty items at start and end of the list and store count to info
* @param list list to cast
* @param delimiter delimter of the list
* @param info
* @return Array Object
*/
public static Array listToArrayTrim(String list, String delimiter, int[] info) {
if(delimiter.length()==1)return listToArrayTrim(list, delimiter.charAt(0),info);
if(list.length()==0) return new ArrayImpl();
char[] del = delimiter.toCharArray();
char c;
// remove at start
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
info[0]++;
list=list.substring(1);
continue outer;
}
}
break;
}
int len;
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
info[1]++;
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
continue outer;
}
}
break;
}
return listToArray(list, delimiter);
}
/**
* casts a list to Array object, remove all empty items at start and end of the list and store count to info
* @param list list to cast
* @param delimiter delimter of the list
* @param info
* @return Array Object
* @throws ExpressionException
*/
public static String listInsertAt(String list, int pos, String value, String delimiter, boolean ignoreEmpty) throws ExpressionException {
if(pos<1)
throw new ExpressionException("invalid string list index ["+(pos)+"]");
char[] del = delimiter.toCharArray();
char c;
StringBuilder result=new StringBuilder();
String end="";
int len;
// remove at start
if(ignoreEmpty){
outer:while(list.length()>0) {
c=list.charAt(0);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
list=list.substring(1);
result.append(c);
continue outer;
}
}
break;
}
}
// remove at end
if(ignoreEmpty){
outer:while(list.length()>0) {
c=list.charAt(list.length()-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
len=list.length();
list=list.substring(0,len-1<0?0:len-1);
end=c+end;
continue outer;
}
}
break;
}
}
len=list.length();
int last=0;
int count=0;
outer:for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i) {
if(pos==++count){
result.append(value);
result.append(del[0]);
}
}
result.append(list.substring(last,i));
result.append(c);
last=i+1;
continue outer;
}
}
}
count++;
if(last<=len){
if(pos==count) {
result.append(value);
result.append(del[0]);
}
result.append(list.substring(last));
}
if(pos>count) {
throw new ExpressionException("invalid string list index ["+(pos)+"], indexes go from 1 to "+(count));
}
return result+end;
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimiter delimter of the list
* @return Array Object
*/
public static Array listToArrayTrim(String list, char delimiter) {
if(list.length()==0) return new ArrayImpl();
// remove at start
while(list.indexOf(delimiter)==0) {
list=list.substring(1);
}
int len=list.length();
if(len==0) return new ArrayImpl();
while(list.lastIndexOf(delimiter)==len-1) {
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return listToArray(list, delimiter);
}
/**
* @param list
* @param delimiter
* @return trimmed list
*/
public static StringList toListTrim(String list, char delimiter) {
if(list.length()==0) return new StringList();
// remove at start
while(list.indexOf(delimiter)==0) {
list=list.substring(1);
}
int len=list.length();
if(len==0) return new StringList();
while(list.lastIndexOf(delimiter)==len-1) {
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return toList(list, delimiter);
}
/**
* @param list
* @param delimiter
* @return list
*/
public static StringList toList(String list, char delimiter) {
if(list.length()==0) return new StringList();
int len=list.length();
int last=0;
StringList rtn=new StringList();
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
rtn.add(list.substring(last,i));
last=i+1;
}
}
if(last<=len)rtn.add(list.substring(last));
rtn.reset();
return rtn;
}
public static StringList toWordList(String list) {
if(list.length()==0) return new StringList();
int len=list.length();
int last=0;
char c,l=0;
StringList rtn=new StringList();
for(int i=0;i<len;i++) {
if(StringUtil.isWhiteSpace(c=list.charAt(i))) {
rtn.add(list.substring(last,i),l);
l=c;
last=i+1;
}
}
if(last<=len)rtn.add(list.substring(last),l);
rtn.reset();
return rtn;
}
/**
* casts a list to Array object, remove all empty items at start and end of the list
* @param list list to cast
* @param delimiter delimter of the list
* @param info
* @return Array Object
*/
public static Array listToArrayTrim(String list, char delimiter, int[] info) {
if(list.length()==0) return new ArrayImpl();
// remove at start
while(list.indexOf(delimiter)==0) {
info[0]++;
list=list.substring(1);
}
int len=list.length();
if(len==0) return new ArrayImpl();
while(list.lastIndexOf(delimiter)==len-1) {
info[1]++;
list=list.substring(0,len-1<0?0:len-1);
len=list.length();
}
return listToArray(list, delimiter);
}
/**
* finds a value inside a list, ignore case
* @param list list to search
* @param value value to find
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value) {
return listFindNoCase(list, value, ",", true);
}
/**
* finds a value inside a list, do not ignore case
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value, String delimiter) {
return listFindNoCase(list, value, delimiter, true);
}
/**
* finds a value inside a list, do not ignore case
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @param trim trim the list or not
* @return position in list (0-n) or -1
*/
public static int listFindNoCase(String list, String value, String delimiter,boolean trim) {
Array arr = trim?listToArrayTrim(list,delimiter):listToArray(list,delimiter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(((String)arr.get(i,"")).equalsIgnoreCase(value)) return i-1;
}
return -1;
}
public static int listFindForSwitch(String list, String value, String delimiter) {
if(list.indexOf(delimiter)==-1 && list.equalsIgnoreCase(value)) return 1;
Array arr = listToArray(list,delimiter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(((String)arr.get(i,"")).equalsIgnoreCase(value)) return i;
}
return -1;
}
/**
* finds a value inside a list, ignore case, ignore empty items
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listFindNoCaseIgnoreEmpty(String list, String value, String delimiter) {
if(delimiter.length()==1)return listFindNoCaseIgnoreEmpty(list, value, delimiter.charAt(0));
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
char[] del = delimiter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i) {
if(list.substring(last,i).equalsIgnoreCase(value)) return count;
count++;
}
last=i+1;
}
}
}
if(last<len) {
if(list.substring(last).equalsIgnoreCase(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, ignore case, ignore empty items
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listFindNoCaseIgnoreEmpty(String list, String value, char delimiter) {
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
if(last<i) {
if(list.substring(last,i).equalsIgnoreCase(value)) return count;
count++;
}
last=i+1;
}
}
if(last<len) {
if(list.substring(last).equalsIgnoreCase(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, case sensitive
* @param list list to search
* @param value value to find
* @return position in list or 0
*/
public static int listFind(String list, String value) {
return listFind(list, value, ",");
}
/**
* finds a value inside a list, do not case sensitive
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listFind(String list, String value, String delimiter) {
Array arr = listToArrayTrim(list,delimiter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(arr.get(i,"").equals(value)) return i-1;
}
return -1;
}
/**
* finds a value inside a list, case sensitive, ignore empty items
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listFindIgnoreEmpty(String list, String value, String delimiter) {
if(delimiter.length()==1)return listFindIgnoreEmpty(list, value, delimiter.charAt(0));
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
char[] del = delimiter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(last<i) {
if(list.substring(last,i).equals(value)) return count;
count++;
}
last=i+1;
}
}
}
if(last<len) {
if(list.substring(last).equals(value)) return count;
}
return -1;
}
/**
* finds a value inside a list, case sensitive, ignore empty items
* @param list list to search
* @param value value to find
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listFindIgnoreEmpty(String list, String value, char delimiter) {
if(list==null) return -1;
int len=list.length();
if(len==0) return -1;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
if(last<i) {
if(list.substring(last,i).equals(value)) return count;
count++;
}
last=i+1;
}
}
if(last<len) {
if(list.substring(last).equals(value)) return count;
}
return -1;
}
/**
* returns if a value of the list contains given value, ignore case
* @param list list to search in
* @param value value to serach
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listContainsNoCase(String list, String value, String delimiter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArray(list,delimiter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(StringUtil.indexOfIgnoreCase(arr.get(i,"").toString(), value)!=-1) return i-1;
}
return -1;
}
/**
* returns if a value of the list contains given value, ignore case, ignore empty values
* @param list list to search in
* @param value value to serach
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listContainsIgnoreEmptyNoCase(String list, String value, String delimiter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArrayRemoveEmpty(list,delimiter);
int count=0;
int len=arr.size();
for(int i=1;i<=len;i++) {
String item=arr.get(i,"").toString();
if(StringUtil.indexOfIgnoreCase(item, value)!=-1) return count;
count++;
}
return -1;
}
/**
* returns if a value of the list contains given value, case sensitive
* @param list list to search in
* @param value value to serach
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listContains(String list, String value, String delimiter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArray(list,delimiter);
int len=arr.size();
for(int i=1;i<=len;i++) {
if(arr.get(i,"").toString().indexOf(value)!=-1) return i-1;
}
return -1;
}
/**
* returns if a value of the list contains given value, case sensitive, ignore empty positions
* @param list list to search in
* @param value value to serach
* @param delimiter delimiter of the list
* @return position in list or 0
*/
public static int listContainsIgnoreEmpty(String list, String value, String delimiter) {
if(StringUtil.isEmpty(value)) return -1;
Array arr=listToArrayRemoveEmpty(list,delimiter);
int count=0;
int len=arr.size();
for(int i=1;i<=len;i++) {
String item=arr.get(i,"").toString();
if(item.indexOf(value)!=-1) return count;
count++;
}
return -1;
}
/**
* convert a string array to string list, removes empty values at begin and end of the list
* @param array array to convert
* @param delimiter delimiter for the new list
* @return list generated from string array
*/
public static String arrayToListTrim(String[] array, String delimiter) {
return trim(arrayToList(array,delimiter),delimiter);
}
/**
* convert a string array to string list
* @param array array to convert
* @param delimiter delimiter for the new list
* @return list generated from string array
*/
public static String arrayToList(String[] array, String delimiter) {
if(ArrayUtil.isEmpty(array)) return "";
StringBuilder sb=new StringBuilder(array[0]);
if(delimiter.length()==1) {
char c=delimiter.charAt(0);
for(int i=1;i<array.length;i++) {
sb.append(c);
sb.append(array[i]);
}
}
else {
for(int i=1;i<array.length;i++) {
sb.append(delimiter);
sb.append(array[i]);
}
}
return sb.toString();
}
public static String arrayToList(Collection.Key[] array, String delimiter) {
if(array.length==0) return "";
StringBuilder sb=new StringBuilder(array[0].getString());
if(delimiter.length()==1) {
char c=delimiter.charAt(0);
for(int i=1;i<array.length;i++) {
sb.append(c);
sb.append(array[i].getString());
}
}
else {
for(int i=1;i<array.length;i++) {
sb.append(delimiter);
sb.append(array[i].getString());
}
}
return sb.toString();
}
/**
* convert Array Object to string list
* @param array array to convert
* @param delimiter delimiter for the new list
* @return list generated from string array
* @throws PageException
*/
public static String arrayToList(Array array, String delimiter) throws PageException {
if(array.size()==0) return "";
StringBuilder sb=new StringBuilder(Caster.toString(array.getE(1)));
int len=array.size();
for(int i=2;i<=len;i++) {
sb.append(delimiter);
sb.append(array.get(i,""));
}
return sb.toString();
}
public static String listToList(java.util.List list, String delimiter) throws PageException {
if(list.size()==0) return "";
StringBuilder sb=new StringBuilder();
Iterator it = list.iterator();
if(it.hasNext()) sb.append(Caster.toString(it.next()));
while(it.hasNext()) {
sb.append(delimiter);
sb.append(Caster.toString(it.next()));
}
return sb.toString();
}
/**
* trims a string array, removes all empty array positions at the start and the end of the array
* @param array array to remove elements
* @return cleared array
*/
public static String[] trim(String[] array) {
int from=0;
int to=0;
// test start
for(int i=0;i<array.length;i++) {
from=i;
if(array[i].length()!=0)break;
}
// test end
for(int i=array.length-1;i>=0;i
to=i;
if(array[i].length()!=0)break;
}
int newLen=to-from+1;
if(newLen<array.length) {
String[] rtn=new String[newLen];
System.arraycopy(array,from,rtn,0,newLen);
return rtn;
}
return array;
}
/**
* trims a string list, remove all empty delimiter at start and the end
* @param list list to trim
* @param delimiter delimiter of the list
* @return trimed list
*/
public static String trim(String list, String delimiter) {
return trim(list,delimiter,new int[2]);
}
/**
* trims a string list, remove all empty delimiter at start and the end
* @param list list to trim
* @param delimiter delimiter of the list
* @param removeInfo int array contain count of removed values (removeInfo[0]=at the begin;removeInfo[1]=at the end)
* @return trimed list
*/
public static String trim(String list, String delimiter,int[] removeInfo) {
if(list.length()==0)return "";
int from=0;
int to=list.length();
//int len=delimiter.length();
char[] del=delimiter.toCharArray();
char c;
// remove at start
outer:while(list.length()>from) {
c=list.charAt(from);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
from++;
removeInfo[0]++;
//list=list.substring(from);
continue outer;
}
}
break;
}
//int len;
outer:while(to>from) {
c=list.charAt(to-1);
for(int i=0;i<del.length;i++) {
if(c==del[i]) {
to
removeInfo[1]++;
continue outer;
}
}
break;
}
int newLen=to-from;
if(newLen<list.length()) {
return list.substring(from,to);
}
return list;
}
/**
* sorts a string list
* @param list list to sort
* @param sortType sort type (numeric,text,textnocase)
* @param sortOrder sort order (asc,desc)
* @param delimiter list delimiter
* @return sorted list
* @throws PageException
*/
public static String sortIgnoreEmpty(String list, String sortType, String sortOrder, String delimiter) throws PageException {
return _sort(toStringArray(listToArrayRemoveEmpty(list,delimiter)),sortType, sortOrder, delimiter);
}
/**
* sorts a string list
* @param list list to sort
* @param sortType sort type (numeric,text,textnocase)
* @param sortOrder sort order (asc,desc)
* @param delimiter list delimiter
* @return sorted list
* @throws PageException
*/
public static String sort(String list, String sortType, String sortOrder, String delimiter) throws PageException {
return _sort(toStringArray(listToArray(list,delimiter)),sortType, sortOrder, delimiter);
}
private static String _sort(Object[] arr, String sortType, String sortOrder, String delimiter) throws ExpressionException {
// check sortorder
boolean isAsc=true;
PageException ee=null;
if(sortOrder.equalsIgnoreCase("asc"))isAsc=true;
else if(sortOrder.equalsIgnoreCase("desc"))isAsc=false;
else throw new ExpressionException("invalid sort order type ["+sortOrder+"], sort order types are [asc and desc]");
// text
if(sortType.equalsIgnoreCase("text")) {
TextComparator comp=new TextComparator(isAsc,false);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
// text no case
else if(sortType.equalsIgnoreCase("textnocase")) {
TextComparator comp=new TextComparator(isAsc,true);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
// numeric
else if(sortType.equalsIgnoreCase("numeric")) {
NumberComparator comp=new NumberComparator(isAsc);
Arrays.sort(arr,comp);
ee=comp.getPageException();
}
else {
throw new ExpressionException("invalid sort type ["+sortType+"], sort types are [text, textNoCase, numeric]");
}
if(ee!=null) {
throw new ExpressionException("invalid value to sort the list",ee.getMessage());
}
StringBuilder sb=new StringBuilder();
for(int i=0;i<arr.length;i++) {
if(i!=0)sb.append(delimiter);
sb.append(arr[i]);
}
return sb.toString();
}
/**
* cast a Object Array to a String Array
* @param array
* @return String Array
*/
public static String[] toStringArrayEL(Array array) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,null),null);
}
return arr;
}
/**
* cast a Object Array to a String Array
* @param array
* @return String Array
* @throws PageException
*/
public static String[] toStringArray(Array array) throws PageException {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,null));
}
return arr;
}
/**
* cast a Object Array to a String Array
* @param array
* @param defaultValue
* @return String Array
*/
public static String[] toStringArray(Array array,String defaultValue) {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,defaultValue),defaultValue);
}
return arr;
}
/**
* cast a Object Array to a String Array and trim all values
* @param array
* @return String Array
* @throws PageException
*/
public static String[] toStringArrayTrim(Array array) throws PageException {
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,"")).trim();
}
return arr;
}
/**
* return first element of the list
* @param list
* @param delimiter
* @return returns the first element of the list
* @deprecated use instead first(String list, String delimiter, boolean ignoreEmpty)
*/
public static String first(String list, String delimiter) {
return first(list, delimiter,true);
}
/**
* return first element of the list
* @param list
* @param delimiter
* @param ignoreEmpty
* @return returns the first element of the list
*/
public static String first(String list, String delimiter, boolean ignoreEmpty) {
if(StringUtil.isEmpty(list)) return "";
char[] del;
if(StringUtil.isEmpty(delimiter)) {
del=new char[]{','};
}
else {
del=delimiter.toCharArray();
}
int offset=0;
int index;
int x;
while(true) {
index=-1;
for(int i=0;i<del.length;i++) {
x=list.indexOf(del[i],offset);
if(x!=-1 && (x<index || index==-1))index=x;
}
//index=list.indexOf(index,offset);
if(index==-1) {
if(offset>0) return list.substring(offset);
return list;
}
if(!ignoreEmpty && index==0) {
return "";
}
else if(index==offset) {
offset++;
}
else {
if(offset>0)return list.substring(offset,index);
return list.substring(0,index);
}
}
}
/**
* return last element of the list
* @param list
* @param delimiter
* @return returns the last Element of a list
* @deprecated use instead last(String list, String delimiter, boolean ignoreEmpty)
*/
public static String last(String list, String delimiter) {
return last(list, delimiter, true);
}
/**
* return last element of the list
* @param list
* @param delimiter
* @param ignoreEmpty
* @return returns the last Element of a list
*/
public static String last(String list, String delimiter, boolean ignoreEmpty) {
if(StringUtil.isEmpty(list)) return "";
int len=list.length();
char[] del;
if(StringUtil.isEmpty(delimiter)) {
del=new char[]{','};
}
else del=delimiter.toCharArray();
int index;
int x;
while(true) {
index=-1;
for(int i=0;i<del.length;i++) {
x=list.lastIndexOf(del[i]);
if(x>index)index=x;
}
if(index==-1) {
return list;
}
else if(index+1==len) {
if(!ignoreEmpty) return"";
list=list.substring(0,len-1);
len
}
else {
return list.substring(index+1);
}
}
}
/**
* return last element of the list
* @param list
* @param delimiter
* @return returns the last Element of a list
*/
public static String last(String list, char delimiter) {
int len=list.length();
if(len==0) return "";
int index=0;
while(true) {
index=list.lastIndexOf(delimiter);
if(index==-1) {
return list;
}
else if(index+1==len) {
list=list.substring(0,len-1);
len
}
else {
return list.substring(index+1);
}
}
}
/**
* returns count of items in the list
* @param list
* @param delimiter
* @return list len
*/
public static int len(String list, char delimiter,boolean ignoreEmpty) {
int len=StringUtil.length(list);
if(len==0) return 0;
int count=0;
int last=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
if(!ignoreEmpty || last<i)count++;
last=i+1;
}
}
if(!ignoreEmpty || last<len)count++;
return count;
}
/**
* returns count of items in the list
* @param list
* @param delimiter
* @return list len
*/
public static int len(String list, String delimiter, boolean ignoreEmpty) {
if(delimiter.length()==1)return len(list, delimiter.charAt(0),ignoreEmpty);
char[] del=delimiter.toCharArray();
int len=StringUtil.length(list);
if(len==0) return 0;
int count=0;
int last=0;
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i)count++;
last=i+1;
}
}
}
if(!ignoreEmpty || last<len)count++;
return count;
}
/* *
* cast a int into a char
* @param i int to cast
* @return int as char
* /
private char c(int i) {
return (char)i;
}*/
/**
* gets a value from list
* @param list list to cast
* @param delimiter delimter of the list
* @param position
* @return Array Object
*/
public static String getAt(String list, String delimiter, int position, boolean ignoreEmpty) {
if(delimiter.length()==1)return getAt(list, delimiter.charAt(0), position,ignoreEmpty);
int len=list.length();
if(len==0) return null;
int last=0;
int count=0;
char[] del = delimiter.toCharArray();
char c;
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
if(!ignoreEmpty || last<i) {
if(count++==position) {
return list.substring(last,i);
}
}
last=i+1;
}
}
}
if(last<len && position==count) return (list.substring(last));
return null;
}
/**
* get a elemnt at a specified position in list
* @param list list to cast
* @param delimiter delimter of the list
* @param position
* @return Array Object
*/
public static String getAt(String list, char delimiter, int position, boolean ignoreEmpty) {
int len=list.length();
if(len==0) return null;
int last=0;
int count=0;
for(int i=0;i<len;i++) {
if(list.charAt(i)==delimiter) {
if(!ignoreEmpty || last<i) {
if(count++==position) {
return list.substring(last,i);
}
}
last=i+1;
}
}
if(last<len && position==count) return (list.substring(last));
return null;
}
public static String[] listToStringArray(String list, char delimiter) {
Array array = List.listToArrayRemoveEmpty(list,delimiter);
String[] arr=new String[array.size()];
for(int i=0;i<arr.length;i++) {
arr[i]=Caster.toString(array.get(i+1,""),"");
}
return arr;
}
/**
* trim every single item of the array
* @param arr
* @return
*/
public static String[] trimItems(String[] arr) {
for(int i=0;i<arr.length;i++) {
arr[i]=arr[i].trim();
}
return arr;
}
/**
* trim every single item of the array
* @param arr
* @return
* @throws PageException
*/
public static Array trimItems(Array arr) throws PageException {
Key[] keys = CollectionUtil.keys(arr);
for(int i=0;i<keys.length;i++) {
arr.setEL(keys[i], Caster.toString(arr.get(keys[i],null)).trim());
}
return arr;
}
public static Set<String> listToSet(String list, String delimiter,boolean trim) {
if(list.length()==0) return new HashSet<String>();
int len=list.length();
int last=0;
char[] del=delimiter.toCharArray();
char c;
HashSet<String> set=new HashSet<String>();
for(int i=0;i<len;i++) {
c=list.charAt(i);
for(int y=0;y<del.length;y++) {
if(c==del[y]) {
set.add(trim?list.substring(last,i).trim():list.substring(last,i));
last=i+1;
}
}
}
if(last<=len)set.add(list.substring(last));
return set;
}
public static Set<String> listToSet(String list, char delimiter,boolean trim) {
if(list.length()==0) return new HashSet<String>();
int len=list.length();
int last=0;
char c;
HashSet<String> set=new HashSet<String>();
for(int i=0;i<len;i++) {
c=list.charAt(i);
if(c==delimiter) {
set.add(trim?list.substring(last,i).trim():list.substring(last,i));
last=i+1;
}
}
if(last<=len)set.add(list.substring(last));
return set;
}
public static Set<String> toSet(String[] arr) {
Set<String> set=new HashSet<String>();
for(int i=0;i<arr.length;i++){
set.add(arr[i]);
}
return set;
}
}
|
package org.topcased.requirement.core.extensions;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.topcased.modeler.di.model.Diagram;
import org.topcased.modeler.di.model.util.DIUtils;
import org.topcased.modeler.diagrams.model.Diagrams;
import org.topcased.modeler.diagrams.model.util.DiagramsResourceImpl;
import org.topcased.modeler.diagrams.model.util.DiagramsUtils;
import org.topcased.modeler.editor.Modeler;
import org.topcased.requirement.RequirementProject;
import org.topcased.requirement.core.commands.LinkRequirementModelCommand;
import org.topcased.requirement.core.commands.UnlinkRequirementModelCommand;
/**
* Define the default policy for requirement attachment on DI models.<br>
*
* @author <a href="mailto:tristan.faure@atosorigin.com">Tristan FAURE (ATOS ORIGIN INTEGRATION)</a>
* @author <a href="mailto:maxime.audrain@c-s.fr">Maxime AUDRAIN</a>
* @since Topcased 3.4.0
*/
public class DefaultAttachmentPolicy implements IModelAttachmentPolicy
{
public static final String REQUIREMENT_PROPERTY_KEY = "requirements"; //$NON-NLS-1$
/** the shared instance */
private static DefaultAttachmentPolicy policy;
/**
* Private constructor
*/
private DefaultAttachmentPolicy()
{
// avoid instantiation
}
/**
* Gets the shared instance.
*
* @return the default Attachment policy
*/
public static DefaultAttachmentPolicy getInstance()
{
if (policy == null)
{
policy = new DefaultAttachmentPolicy();
}
return policy;
}
/**
* @see org.topcased.requirement.core.extensions.IModelAttachmentPolicy#setAttachement(org.eclipse.emf.ecore.resource.Resource,
* org.eclipse.emf.ecore.resource.Resource)
*/
public Command linkRequirementModel(Resource targetModel, Resource requirementModel)
{
return new LinkRequirementModelCommand(targetModel, requirementModel);
}
/**
* @see org.topcased.requirement.core.extensions.IModelAttachmentPolicy#unlinkRequirementModel(org.eclipse.emf.ecore.resource.Resource,
* org.eclipse.emf.ecore.resource.Resource)
*/
public Command unlinkRequirementModel(Resource targetModel, Resource requirementModel, boolean deleteRequirementModel)
{
Diagram rootDiagram = DiagramsUtils.getRootDiagram((Diagrams) targetModel.getContents().get(0));
String resourcePath = DIUtils.getPropertyValue(rootDiagram, REQUIREMENT_PROPERTY_KEY);
if (!"".equals(resourcePath))
{
return new UnlinkRequirementModelCommand(targetModel, requirementModel, deleteRequirementModel);
}
return null;
}
/**
* @see org.topcased.requirement.core.extensions.IModelAttachmentPolicy#getLinkedTargetModel(org.eclipse.emf.edit.domain.EditingDomain)
*/
public Resource getLinkedTargetModel(ResourceSet resourceSet)
{
for (Resource resource : resourceSet.getResources())
{
if (resource instanceof DiagramsResourceImpl && !resource.getContents().isEmpty())
{
Diagrams res = (Diagrams) resource.getContents().get(0);
Diagram root = DiagramsUtils.getRootDiagram(res);
if (DIUtils.getProperty(root, REQUIREMENT_PROPERTY_KEY) != null)
{
return resource;
}
}
}
return null;
}
/**
* Set the requirement property to the DI model. This property has always this format : key = requirements, value =
* the platform resource path of the requirement model.
*
* @param modeler the modeler
* @param requirements the requirements
*/
public void setProperty(Modeler targetModeler, Resource requirementModel)
{
Resource candidate = getDiagramModel(targetModeler.getResourceSet());
if (candidate != null && !candidate.getContents().isEmpty())
{
EObject eobject = candidate.getContents().get(0);
if (eobject instanceof Diagrams)
{
Diagram rootDiagram = DiagramsUtils.getRootDiagram((Diagrams) eobject);
if (rootDiagram != null && requirementModel != null)
{
DIUtils.setProperty(rootDiagram, REQUIREMENT_PROPERTY_KEY, requirementModel.getURI().trimFragment().deresolve(eobject.eResource().getURI()).toString());
}
else
{
DIUtils.setProperty(rootDiagram, REQUIREMENT_PROPERTY_KEY, null);
}
}
}
}
/**
* Default behavior consist in trying to find the diagram model from the Modeler's resource set.
*
* @param rscSet The resource set coming from the modeler.
* @return the resource corresponding to the diagram model.
*/
private Resource getDiagramModel(ResourceSet rscSet)
{
if (rscSet != null)
{
for (Resource resource : rscSet.getResources())
{
if (resource instanceof DiagramsResourceImpl)
{
return resource;
}
}
}
return null;
}
/**
* @see org.topcased.requirement.core.extensions.IModelAttachmentPolicy#getRequirementProjectFromTargetDiagram(org.topcased.modeler.diagrams.model.Diagrams)
*/
public RequirementProject getRequirementProjectFromTargetDiagram(Diagrams diagram)
{
Diagram rootDiagram = DiagramsUtils.getRootDiagram(diagram);
String resourcePath = DIUtils.getPropertyValue(rootDiagram, REQUIREMENT_PROPERTY_KEY);
if (!"".equals(resourcePath) && diagram.eResource() != null && diagram.eResource().getResourceSet() != null)
{
URI uri = URI.createURI(resourcePath).trimFragment().resolve(rootDiagram.eResource().getURI());
Resource reqResource = diagram.eResource().getResourceSet().getResource(uri, true);
if (!reqResource.getContents().isEmpty())
{
return (RequirementProject) reqResource.getContents().get(0);
}
}
return null;
}
/**
* @see org.topcased.requirement.core.extensions.IModelAttachmentPolicy#isHierarchicalElementRoot(org.eclipse.emf.ecore.EObject)
*/
public boolean isRootContainer(EObject parentElt)
{
return parentElt == null;
}
}
|
/*
* generated by Xtext
*/
package org.yakindu.sct.generator.genmodel.formatting;
import org.eclipse.xtext.Group;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter;
import org.eclipse.xtext.formatting.impl.FormattingConfig;
import org.eclipse.xtext.util.Pair;
import org.yakindu.sct.generator.genmodel.services.SGenGrammarAccess;
public class SGenFormatter extends AbstractDeclarativeFormatter {
@Override
protected void configureFormatting(FormattingConfig c) {
// It's usually a good idea to activate the following three statements.
// They will add and preserve newlines around comments
// c.setLinewrap(0, 1,
// 2).before(getGrammarAccess().getSL_COMMENTRule());
// c.setLinewrap(0, 1,
// 2).before(getGrammarAccess().getML_COMMENTRule());
// c.setLinewrap(0, 1, 1).after(getGrammarAccess().getML_COMMENTRule());
// Find elements which declare their body in curly brackets.
// - Increment Indentation for the body.
// - Line wrap before opening and after closing element
for (Pair<Keyword, Keyword> pair : grammar.findKeywordPairs("{", "}")) {
c.setIndentation(pair.getFirst(), pair.getSecond());
c.setLinewrap().after(pair.getFirst());
c.setLinewrap().around(pair.getSecond());
Keyword openingBrace = pair.getFirst();
Group containingGroup = (Group) openingBrace.eContainer();
// Top-most elements with brackets: Insert blank lines
// if (containingGroup.eContainer().eContainer() instanceof Grammar)
c.setLinewrap(1, 2, 2).before(containingGroup);
c.setLinewrap(1, 2, 2).after(containingGroup);
}
SGenGrammarAccess g = (SGenGrammarAccess) getGrammarAccess();
c.setLinewrap().around(g.getFeatureConfigurationRule());
c.setLinewrap().around(g.getFeatureParameterValueRule());
}
}
|
package com.charlesmadere.hummingbird.adapters;
import android.content.Context;
import com.charlesmadere.hummingbird.R;
import com.charlesmadere.hummingbird.models.AbsSubstory;
import com.charlesmadere.hummingbird.models.CommentStory;
import com.charlesmadere.hummingbird.models.Feed;
import com.charlesmadere.hummingbird.models.ReplySubstory;
import com.charlesmadere.hummingbird.models.SimpleDate;
import com.charlesmadere.hummingbird.views.ReplySubstoryStandaloneItemView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class CommentsAdapter extends BaseMultiPaginationAdapter implements Comparator<AbsSubstory> {
public CommentsAdapter(final Context context) {
super(context);
}
@Override
public int compare(final AbsSubstory o1, final AbsSubstory o2) {
return SimpleDate.CHRONOLOGICAL_ORDER.compare(o1.getCreatedAt(), o2.getCreatedAt());
}
@Override
protected HashMap<Class, Integer> getItemViewKeyMap() {
final HashMap<Class, Integer> map = new HashMap<>(2);
map.put(CommentStory.class, R.layout.item_comment_story_standalone);
map.put(ReplySubstory.class, R.layout.item_reply_substory_standalone);
return map;
}
@Override
public void onBindViewHolder(final AdapterView.ViewHolder holder, final int position) {
if (holder.getAdapterView() instanceof ReplySubstoryStandaloneItemView) {
final boolean showDivider = isPaginating() ? position + 2 < getItemCount()
: position + 1 < getItemCount();
((ReplySubstoryStandaloneItemView) holder.getAdapterView()).setContent(
(ReplySubstory) getItem(position), showDivider);
} else {
super.onBindViewHolder(holder, position);
}
}
public void set(final CommentStory commentStory, final Feed feed) {
final ArrayList<Object> list = new ArrayList<>();
list.add(commentStory);
final ArrayList<AbsSubstory> substories = feed.getSubstories(AbsSubstory.Type.REPLY);
if (substories != null && !substories.isEmpty()) {
Collections.sort(substories, this);
list.addAll(substories);
}
super.set(list);
}
}
|
package com.charlesmadere.hummingbird.models;
import android.os.Build;
import com.charlesmadere.hummingbird.BuildConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.M)
public class LibraryUpdateTest {
private static final String NOTES = "Hello, World!";
private LibraryEntry mLibraryEntry;
private LibraryUpdate mLibraryUpdate;
@Before
public void setUp() throws Exception {
mLibraryEntry = LibraryEntryTest.get();
mLibraryUpdate = new LibraryUpdate(mLibraryEntry);
}
@Test
public void testSetEpisodesWatched() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setEpisodesWatched(mLibraryEntry.getEpisodesWatched(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setEpisodesWatched(mLibraryEntry.getEpisodesWatched() + 1, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setEpisodesWatched(mLibraryEntry.getEpisodesWatched(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setEpisodesWatched(mLibraryEntry.getEpisodesWatched() + 2, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
}
@Test
public void testSetNotesModifications() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setNotes(mLibraryEntry.getNotes(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setNotes(NOTES, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setNotes(mLibraryEntry.getNotes(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
}
@Test
public void testSetPrivacyModifications() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setPrivacy(mLibraryEntry.isPrivate() ? Privacy.PRIVATE : Privacy.PUBLIC,
mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setPrivacy(mLibraryEntry.isPrivate() ? Privacy.PUBLIC : Privacy.PRIVATE,
mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setPrivacy(mLibraryEntry.isPrivate() ? Privacy.PRIVATE : Privacy.PUBLIC,
mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
}
@Test
public void testSetRating() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRating(Rating.from(mLibraryEntry), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRating(Rating.FOUR, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRating(null, mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRating(Rating.UNRATED, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
}
@Test
public void testSetRewatchedTimes() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatchedTimes(mLibraryEntry.getRewatchedTimes(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatchedTimes(5, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatchedTimes(null, mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatchedTimes(20, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
}
@Test
public void testSetRewatching() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatching(mLibraryEntry.isRewatching(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatching(!mLibraryEntry.isRewatching(), mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setRewatching(mLibraryEntry.isRewatching(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
}
@Test
public void testSetWatchingStatus() throws Exception {
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setWatchingStatus(mLibraryEntry.getStatus(), mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setWatchingStatus(WatchingStatus.PLAN_TO_WATCH, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
mLibraryUpdate.setWatchingStatus(null, mLibraryEntry);
assertFalse(mLibraryUpdate.containsModifications());
mLibraryUpdate.setWatchingStatus(WatchingStatus.ON_HOLD, mLibraryEntry);
assertTrue(mLibraryUpdate.containsModifications());
}
}
|
package fr.inria.spirals.repairnator.process.step;
import fr.inria.spirals.repairnator.ProjectState;
import fr.inria.spirals.repairnator.process.inspectors.ProjectInspector;
import fr.inria.spirals.repairnator.process.maven.MavenHelper;
public class ResolveDependency extends AbstractStep {
public ResolveDependency(ProjectInspector inspector) {
super(inspector);
}
public ResolveDependency(ProjectInspector inspector, String stepName) {
super(inspector, stepName);
}
@Override
protected void businessExecute() {
this.getLogger().debug("Resolve dependencies with maven (skip tests)...");
this.getLogger().debug("Installing artifacts without test execution...");
MavenHelper helper = new MavenHelper(this.getPom(), "dependency:resolve", null, this.getClass().getSimpleName(), this.inspector, true);
int result = helper.run();
if (result == MavenHelper.MAVEN_SUCCESS) {
this.setState(ProjectState.DEPENDENCY_RESOLVED);
} else {
this.getLogger().warn("Repository " + this.inspector.getRepoSlug() + " may have unresolvable dependencies.");
this.setState(ProjectState.DEPENDENCY_UNRESOLVABLE);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.