Skip to content

Commit

Permalink
Final pieces of the save&restore AA
Browse files Browse the repository at this point in the history
  • Loading branch information
georgweiss committed Nov 14, 2023
1 parent 6b594b1 commit 9b626bf
Show file tree
Hide file tree
Showing 42 changed files with 1,979 additions and 364 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.phoebus.framework.jobs.JobManager;
import org.phoebus.security.authorization.ServiceAuthenticationProvider;
Expand Down Expand Up @@ -75,6 +77,8 @@ public class CredentialsManagementController {
private static final Logger LOGGER = Logger.getLogger(CredentialsManagementController.class.getName());
private final List<ServiceAuthenticationProvider> authenticationProviders;

private Stage stage;

public CredentialsManagementController(List<ServiceAuthenticationProvider> authenticationProviders, SecureStore secureStore) {
this.authenticationProviders = authenticationProviders;
this.secureStore = secureStore;
Expand Down Expand Up @@ -139,18 +143,22 @@ public void logOutFromAll() {
}
}

/**
* Attempts to sign in user based on provided credentials. If sign-in succeeds, this method will close the
* associated UI.
* @param serviceItem The {@link ServiceItem} defining the scope, and implicitly the authentication service.
*/
private void login(ServiceItem serviceItem){
try {
serviceItem.getServiceAuthenticationProvider().authenticate(serviceItem.getUsername(), serviceItem.getPassword());
try {
secureStore.setScopedAuthentication(new ScopedAuthenticationToken(serviceItem.getAuthenticationScope(),
serviceItem.getUsername(),
serviceItem.getPassword()));
stage.close();
} catch (Exception exception) {
LOGGER.log(Level.WARNING, "Failed to store credentials", exception);
}
updateTable();

} catch (Exception exception) {
LOGGER.log(Level.WARNING, "Failed to login to service", exception);
ExceptionDetailsErrorDialog.openError(parent, "Login Failure", "Failed to login to service", exception);
Expand Down Expand Up @@ -252,7 +260,7 @@ public boolean isLoginAction(){
return loginAction;
}
}
private static class UsernameTableCell extends TableCell<ServiceItem, String>{
private class UsernameTableCell extends TableCell<ServiceItem, String>{
private final TextField textField = new TextField();

public UsernameTableCell(){
Expand All @@ -279,7 +287,7 @@ protected void updateItem(String item, final boolean empty)
}
}

private static class PasswordTableCell extends TableCell<ServiceItem, String>{
private class PasswordTableCell extends TableCell<ServiceItem, String>{
private final PasswordField passwordField = new PasswordField();

public PasswordTableCell(){
Expand All @@ -301,8 +309,17 @@ protected void updateItem(String item, final boolean empty)
// Disable field if user is logged in.
passwordField.disableProperty().set(!getTableRow().getItem().loginAction);
}
passwordField.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode() == KeyCode.ENTER) {
CredentialsManagementController.this.login(getTableRow().getItem());
}
});
setGraphic(passwordField);
}
}
}

public void setStage(Stage stage){
this.stage = stage;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public CredentialsManagementStage(List<ServiceAuthenticationProvider> authentica
CredentialsManagementController controller =
(CredentialsManagementController) clazz.getConstructor(List.class, SecureStore.class)
.newInstance(authenticationProviders, secureStore);
controller.setStage(this);
return controller;

} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ public interface SaveAndRestoreClient {

SnapshotData getSnapshotData(String uniqueId);

Snapshot saveSnapshot(String parentNodeId, Snapshot snapshot);
Snapshot createSnapshot(String parentNodeId, Snapshot snapshot);

Snapshot updateSnapshot(Snapshot snapshot);

/**
* Creates a new {@link CompositeSnapshot}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,8 @@ private Client getClient() {
String password = scopedAuthenticationToken.getPassword();
httpBasicAuthFilter = new HTTPBasicAuthFilter(username, password);
client.addFilter(httpBasicAuthFilter);
} else {//if (httpBasicAuthFilter != null) {
//client.removeFilter(httpBasicAuthFilter);
httpBasicAuthFilter = new HTTPBasicAuthFilter(System.getProperty("user.name"), "password");
client.addFilter(httpBasicAuthFilter);
} else if (httpBasicAuthFilter != null) {
client.removeFilter(httpBasicAuthFilter);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Unable to retrieve credentials from secure store", e);
Expand Down Expand Up @@ -182,8 +180,7 @@ public List<Node> getChildNodes(String uniqueNodeId) throws SaveAndRestoreClient
@Override
public Node createNewNode(String parentNodeId, Node node) {
WebResource webResource = getClient().resource(jmasarServiceUrl + "/node")
.queryParam("parentNodeId", parentNodeId) // Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
.queryParam("parentNodeId", parentNodeId);
ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(node, CONTENT_TYPE_JSON)
.put(ClientResponse.class);
Expand All @@ -207,9 +204,7 @@ public Node updateNode(Node nodeToUpdate) {
@Override
public Node updateNode(Node nodeToUpdate, boolean customTimeForMigration) {
WebResource webResource = getClient().resource(jmasarServiceUrl + "/node")
.queryParam("customTimeForMigration", customTimeForMigration ? "true" : "false")
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
.queryParam("customTimeForMigration", customTimeForMigration ? "true" : "false");

ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(nodeToUpdate, CONTENT_TYPE_JSON)
Expand Down Expand Up @@ -347,9 +342,7 @@ public ConfigurationData getConfigurationData(String nodeId) {
public Configuration createConfiguration(String parentNodeId, Configuration configuration) {
WebResource webResource =
getClient().resource(jmasarServiceUrl + "/config")
.queryParam("parentNodeId", parentNodeId)
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
.queryParam("parentNodeId", parentNodeId);
ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(configuration, CONTENT_TYPE_JSON)
.put(ClientResponse.class);
Expand All @@ -367,9 +360,7 @@ public Configuration createConfiguration(String parentNodeId, Configuration conf

@Override
public Configuration updateConfiguration(Configuration configuration) {
WebResource webResource = getClient().resource(jmasarServiceUrl + "/config")
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
WebResource webResource = getClient().resource(jmasarServiceUrl + "/config");

ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(configuration, CONTENT_TYPE_JSON)
Expand All @@ -393,12 +384,10 @@ public SnapshotData getSnapshotData(String nodeId) {
}

@Override
public Snapshot saveSnapshot(String parentNodeId, Snapshot snapshot) {
public Snapshot createSnapshot(String parentNodeId, Snapshot snapshot) {
WebResource webResource =
getClient().resource(jmasarServiceUrl + "/snapshot")
.queryParam("parentNodeId", parentNodeId)
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
.queryParam("parentNodeId", parentNodeId);
ClientResponse response;
try {
response = webResource.accept(CONTENT_TYPE_JSON)
Expand All @@ -419,13 +408,36 @@ public Snapshot saveSnapshot(String parentNodeId, Snapshot snapshot) {
return response.getEntity(Snapshot.class);
}

@Override
public Snapshot updateSnapshot(Snapshot snapshot) {
WebResource webResource =
getClient().resource(jmasarServiceUrl + "/snapshot");
ClientResponse response;
try {
response = webResource.accept(CONTENT_TYPE_JSON)
.entity(snapshot, CONTENT_TYPE_JSON)
.post(ClientResponse.class);
} catch (UniformInterfaceException e) {
throw new RuntimeException(e);
}
if (response.getStatus() != ClientResponse.Status.OK.getStatusCode()) {
String message = Messages.searchFailed;
try {
message = new String(response.getEntityInputStream().readAllBytes());
} catch (IOException e) {
logger.log(Level.WARNING, "Unable to parse response", e);
}
throw new SaveAndRestoreClientException(message);
}
return response.getEntity(Snapshot.class);
}


@Override
public CompositeSnapshot createCompositeSnapshot(String parentNodeId, CompositeSnapshot compositeSnapshot) {
WebResource webResource =
getClient().resource(jmasarServiceUrl + "/composite-snapshot")
.queryParam("parentNodeId", parentNodeId)
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
.queryParam("parentNodeId", parentNodeId);
ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(compositeSnapshot, CONTENT_TYPE_JSON)
.put(ClientResponse.class);
Expand Down Expand Up @@ -463,9 +475,7 @@ public List<String> checkCompositeSnapshotConsistency(List<String> snapshotNodeI

@Override
public CompositeSnapshot updateCompositeSnapshot(CompositeSnapshot compositeSnapshot) {
WebResource webResource = getClient().resource(jmasarServiceUrl + "/composite-snapshot")
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
WebResource webResource = getClient().resource(jmasarServiceUrl + "/composite-snapshot");

ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(compositeSnapshot, CONTENT_TYPE_JSON)
Expand Down Expand Up @@ -502,9 +512,7 @@ public SearchResult search(MultivaluedMap<String, String> searchParams) {

@Override
public Filter saveFilter(Filter filter) {
WebResource webResource = getClient().resource(jmasarServiceUrl + "/filter")
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
WebResource webResource = getClient().resource(jmasarServiceUrl + "/filter");
ClientResponse response = webResource.accept(CONTENT_TYPE_JSON)
.entity(filter, CONTENT_TYPE_JSON)
.put(ClientResponse.class);
Expand Down Expand Up @@ -566,9 +574,7 @@ public void deleteFilter(String name) {
public List<Node> addTag(TagData tagData) {

WebResource webResource =
getClient().resource(jmasarServiceUrl + "/tags")
// Request parameter username is needed in case authorization/authentication is disabled.
.queryParam("username", System.getProperty("user.name"));
getClient().resource(jmasarServiceUrl + "/tags");
ClientResponse response;
try {
response = webResource.accept(CONTENT_TYPE_JSON)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public ContextMenuBase(SaveAndRestoreController saveAndRestoreController) {
deleteNodesMenuItem = new MenuItem(Messages.contextMenuDelete, new ImageView(ImageRepository.DELETE));
deleteNodesMenuItem.setOnAction(ae -> saveAndRestoreController.deleteNodes());
deleteNodesMenuItem.disableProperty().bind(Bindings.createBooleanBinding(() ->
//userIsAuthenticatedProperty.not().get() ||
userIsAuthenticatedProperty.not().get() ||
hasSameParentProperty.not().get(),
userIsAuthenticatedProperty, hasSameParentProperty));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public ContextMenuSnapshot(SaveAndRestoreController saveAndRestoreController) {
tagWithComment = new Menu(Messages.contextMenuTagsWithComment, snapshotTagsWithCommentIconImage);
tagWithComment.setOnShowing(event -> saveAndRestoreController.tagWithComment(tagWithComment));
tagWithComment.disableProperty().bind(Bindings.createBooleanBinding(() ->
multipleNodesSelectedProperty.get(), //|| userIsAuthenticatedProperty.not().get(),
multipleNodesSelectedProperty.get() || userIsAuthenticatedProperty.not().get(),
multipleNodesSelectedProperty, userIsAuthenticatedProperty));

MenuItem addTagWithCommentMenuItem = TagWidget.AddTagWithCommentMenuItem();
Expand All @@ -84,8 +84,8 @@ public ContextMenuSnapshot(SaveAndRestoreController saveAndRestoreController) {

tagGoldenMenuItem = new MenuItem(Messages.contextMenuTagAsGolden, new ImageView(ImageRepository.SNAPSHOT));
tagGoldenMenuItem.disableProperty().bind(Bindings.createBooleanBinding(() ->
multipleNodesSelectedProperty.get() || /*userIsAuthenticatedProperty.not().get() ||*/ mayTagOrUntagGoldenProperty.not().get(),
multipleNodesSelectedProperty, /*userIsAuthenticatedProperty,*/ mayTagOrUntagGoldenProperty));
multipleNodesSelectedProperty.get() || userIsAuthenticatedProperty.not().get() || mayTagOrUntagGoldenProperty.not().get(),
multipleNodesSelectedProperty, userIsAuthenticatedProperty, mayTagOrUntagGoldenProperty));

Image copyIcon = ImageCache.getImage(SaveAndRestoreController.class, "/icons/copy.png");
MenuItem copyMenuItem = new MenuItem(Messages.copy, new ImageView(copyIcon));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,14 @@ public Snapshot saveSnapshot(Node configurationNode, Snapshot snapshot) throws E
return snapshotItem;
}).collect(Collectors.toList());
snapshot.getSnapshotData().setSnapshotItems(beautifiedItems);
Future<Snapshot> future = executor.submit(() -> saveAndRestoreClient.saveSnapshot(configurationNode.getUniqueId(), snapshot));
Future<Snapshot> future = executor.submit(() -> {
if(snapshot.getSnapshotNode().getUniqueId() == null){
return saveAndRestoreClient.createSnapshot(configurationNode.getUniqueId(), snapshot);
}
else{
return saveAndRestoreClient.updateSnapshot(snapshot);
}
});
Snapshot updatedSnapshot = future.get();
// Notify listeners as the configuration node has a new child node.
notifyNodeChangeListeners(configurationNode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@
import org.phoebus.applications.saveandrestore.ui.SaveAndRestoreService;
import org.phoebus.applications.saveandrestore.ui.VNoData;
import org.phoebus.framework.jobs.JobManager;
import org.phoebus.security.store.SecureStore;
import org.phoebus.security.tokens.AuthenticationScope;
import org.phoebus.security.tokens.ScopedAuthenticationToken;
import org.phoebus.ui.dialog.DialogHelper;
import org.phoebus.ui.dialog.ExceptionDetailsErrorDialog;
Expand Down Expand Up @@ -153,13 +151,22 @@ public void saveSnapshot(ActionEvent actionEvent) {
List<SnapshotItem> snapshotItems = snapshotProperty.get().getSnapshotData().getSnapshotItems();
SnapshotData snapshotData = new SnapshotData();
snapshotData.setSnapshotItems(snapshotItems);
Snapshot snapshot = new Snapshot();
Snapshot snapshot = snapshotProperty.get();
// Creating new or updating existing (e.g. name change)?
if (snapshot == null) {
snapshot = new Snapshot();
snapshot.setSnapshotNode(Node.builder().nodeType(NodeType.SNAPSHOT)
.name(snapshotControlsViewController.getSnapshotNameProperty().get())
.description(snapshotControlsViewController.getSnapshotCommentProperty().get()).build());
} else {
snapshot.getSnapshotNode().setName(snapshotControlsViewController.getSnapshotNameProperty().get());
snapshot.getSnapshotNode().setDescription(snapshotControlsViewController.getSnapshotCommentProperty().get());
}
snapshot.setSnapshotData(snapshotData);
snapshot.setSnapshotNode(Node.builder().nodeType(NodeType.SNAPSHOT)
.name(snapshotControlsViewController.getSnapshotNameProperty().get())
.description(snapshotControlsViewController.getSnapshotCommentProperty().get()).build());

try {
snapshot = SaveAndRestoreService.getInstance().saveSnapshot(configurationNode, snapshot);
snapshotProperty.set(snapshot);
Node _snapshotNode = snapshot.getSnapshotNode();
javafx.scene.Node jfxNode = (javafx.scene.Node) actionEvent.getSource();
String userData = (String) jfxNode.getUserData();
Expand Down Expand Up @@ -363,7 +370,7 @@ public void addSnapshot(Node snapshotNode) {
Snapshot snapshot = getSnapshotFromService(snapshotNode);
snapshotTableViewController.addSnapshot(snapshot);
} catch (Exception e) {
e.printStackTrace();
Logger.getLogger(SnapshotController.class.getName()).log(Level.WARNING, "Failed to add snapshot", e);
} finally {
disabledUi.set(false);
}
Expand Down Expand Up @@ -392,7 +399,7 @@ private Snapshot getSnapshotFromService(Node snapshotNode) throws Exception {
}

@Override
public void secureStoreChanged(List<ScopedAuthenticationToken> validTokens){
public void secureStoreChanged(List<ScopedAuthenticationToken> validTokens) {
snapshotControlsViewController.secureStoreChanged(validTokens);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@
</ToolBar>
<GridPane fx:id="controlsPane" hgap="5.0">
<columnConstraints>
<ColumnConstraints />
<ColumnConstraints />
<ColumnConstraints />
<ColumnConstraints />
<ColumnConstraints maxWidth="125.0" minWidth="120.0" prefWidth="125.0" />
<ColumnConstraints maxWidth="173.0" minWidth="154.0" prefWidth="173.0" />
<ColumnConstraints />
<ColumnConstraints />

</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
Expand Down
Loading

0 comments on commit 9b626bf

Please sign in to comment.