Skip to content

Commit

Permalink
Introducing a action/command that allows for the direct switching of …
Browse files Browse the repository at this point in the history
…OCI Regions from within the IDE
  • Loading branch information
jhorvath committed Mar 25, 2024
1 parent 63dc7ee commit 07f4872
Show file tree
Hide file tree
Showing 25 changed files with 679 additions and 90 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.modules.cloud.oracle.compartment.CompartmentNode;
import org.netbeans.modules.cloud.oracle.items.OCIItem;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
Expand Down Expand Up @@ -75,16 +76,24 @@ protected boolean createKeys(List<OCIItem> toPopulate) {

@Override
protected Node[] createNodesForKey(OCIItem key) {
Node[] nodes;
NodeProvider nodeProvider = Lookups.forPath(
String.format("Cloud/Oracle/%s/Nodes", key.getKey().getPath()))
.lookup(NodeProvider.class);
if (nodeProvider instanceof NodeProvider.SessionAware) {
return new Node[]{((NodeProvider.SessionAware)nodeProvider).apply(key, session)};
nodes = new Node[]{((NodeProvider.SessionAware)nodeProvider).apply(key, session)};
} else {
return OCIManager.usingSession(session, () ->
nodes = OCIManager.usingSession(session, () ->
new Node[]{nodeProvider.apply(key)}
);
}
for (int i = 0; i < nodes.length; i++) {
if (nodes[i] instanceof CompartmentNode) {
CompartmentNodes.getDefault().addNode((CompartmentNode) nodes[i]);
};

}
return nodes;
}

public void refreshKeys() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.cloud.oracle;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;
import org.netbeans.modules.cloud.oracle.compartment.CompartmentNode;

/**
*
* @author Jan Horvath
*/
public class CompartmentNodes {
private static CompartmentNodes INSTANCE = new CompartmentNodes();

Set<Reference<CompartmentNode>> nodes = new HashSet<> ();

public static synchronized CompartmentNodes getDefault() {
return INSTANCE;
}

public void addNode(CompartmentNode node) {
nodes.add(new WeakReference<>(node));
}

public void refresh() {
for (Reference<CompartmentNode> node : nodes) {
if (node.get() != null) {
node.get().refresh();
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@
public class OCINode extends AbstractNode {
private RefreshListener refreshListener;

private final OCIItem item;
final OCIItem item;
private final CloudChildFactory factory;
private final OCISessionInitiator session;
final OCISessionInitiator session;

public OCINode(OCIItem item) {
this(new CloudChildFactory(item), item, OCIManager.getDefault().getActiveSession(), Lookups.fixed(item));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
import com.oracle.bmc.identity.requests.GetTenancyRequest;
import com.oracle.bmc.identity.responses.GetTenancyResponse;
import com.oracle.bmc.model.BmcException;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
Expand All @@ -46,13 +48,15 @@
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.netbeans.modules.cloud.oracle.items.OCID;
import org.netbeans.modules.cloud.oracle.items.OCIItem;
import org.netbeans.modules.cloud.oracle.items.TenancyItem;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.lookup.Lookups;

/**
Expand All @@ -65,6 +69,10 @@ public final class OCIProfile implements OCISessionInitiator {
* ID of the default profile.
*/
public static final String DEFAULT_ID = "DEFAULT"; // NOI18N
/**
* name of preference for active region
*/
static final String PROP_ACTIVE_REGION_CODE = "activeRegionCode";
/**
* Profile ID.
*/
Expand All @@ -81,6 +89,8 @@ public final class OCIProfile implements OCISessionInitiator {
private IOException initError;
private Tenancy tenancyOpt;
private static final Logger LOG = Logger.getLogger(OCIProfile.class.getName());
private Region region;


OCIProfile(Path configPath, String id) {
this(configPath, id, true);
Expand Down Expand Up @@ -115,6 +125,13 @@ private void init() {
String stringPath = configPath.toAbsolutePath().toString();
ConfigFileReader.ConfigFile configFile = id == null ? ConfigFileReader.parse(stringPath) : ConfigFileReader.parse(stringPath, id);
configProvider = new ConfigFileAuthenticationDetailsProvider(configFile);
Preferences prefs = NbPreferences.forModule(OCIProfile.class);
String regionCode = prefs.get(PROP_ACTIVE_REGION_CODE + "/" + id, null);
if (regionCode == null) {
region = configProvider.getRegion();
} else {
region = Region.valueOf(regionCode);
}
fileStamp = stamp;
} catch (IOException ex) {
LOG.log(Level.INFO, "init()", ex);
Expand All @@ -136,6 +153,18 @@ public String getId() {
public boolean isValid() {
return configProvider != null && fileStamp == configPath.toFile().lastModified(); // avoid IOE
}

public void setRegionCode(String regionCode) {
Region newRegion = Region.valueOf(regionCode);
Preferences prefs = NbPreferences.forModule(OCIProfile.class);
if (newRegion != null) {
prefs.put(PROP_ACTIVE_REGION_CODE + "/" + id, newRegion.getRegionCode());
} else {
prefs.remove(PROP_ACTIVE_REGION_CODE + "/" + id);
}
listeners.firePropertyChange(PROP_ACTIVE_REGION_CODE, this.region, newRegion);
region = newRegion;
}

@Override
public BasicAuthenticationDetailsProvider getAuthenticationProvider() {
Expand All @@ -144,7 +173,7 @@ public BasicAuthenticationDetailsProvider getAuthenticationProvider() {

@Override
public Region getRegion() {
return configProvider.getRegion();
return region;
}

@Override
Expand Down Expand Up @@ -212,7 +241,7 @@ public <T> T newClient(Class<T> clientClass) {
try {
T client = clientClass.getConstructor(BasicAuthenticationDetailsProvider.class).newInstance(configProvider);
Method setRegion = clientClass.getMethod("setRegion", Region.class);
setRegion.invoke(client, configProvider.getRegion());
setRegion.invoke(client, getRegion());
return client;
} catch (ReflectiveOperationException ex) {
throw new IllegalArgumentException("Could not initialize client: " + clientClass);
Expand Down Expand Up @@ -251,7 +280,7 @@ public Path downloadWallet(OCIItem dbInstance, String password, String parentPat
if (configProvider == null) {
return null;
}
try (final DatabaseClient client = new DatabaseClient(configProvider)) {
try (final DatabaseClient client = newClient(DatabaseClient.class)) {
GenerateAutonomousDatabaseWalletDetails details = GenerateAutonomousDatabaseWalletDetails.builder().password(password).build();
GenerateAutonomousDatabaseWalletRequest generateAutonomousDatabaseWalletRequest = GenerateAutonomousDatabaseWalletRequest.builder().autonomousDatabaseId(dbInstance.getKey().getValue()).generateAutonomousDatabaseWalletDetails(details).build();
GenerateAutonomousDatabaseWalletResponse response = client.generateAutonomousDatabaseWallet(generateAutonomousDatabaseWalletRequest);
Expand Down Expand Up @@ -287,7 +316,7 @@ public Optional<String> createAutonomousDatabase(String compartmentId, String db
if (configProvider == null) {
return Optional.empty();
}
try (final DatabaseClient client = new DatabaseClient(configProvider)) {
try (final DatabaseClient client = newClient(DatabaseClient.class)) {
CreateAutonomousDatabaseBase createAutonomousDatabaseBase = CreateAutonomousDatabaseDetails.builder().compartmentId(compartmentId).dbName(dbName).adminPassword(new String(password)).cpuCoreCount(1).dataStorageSizeInTBs(1).build();
CreateAutonomousDatabaseRequest createAutonomousDatabaseRequest = CreateAutonomousDatabaseRequest.builder().createAutonomousDatabaseDetails(createAutonomousDatabaseBase).build();
try {
Expand All @@ -298,6 +327,26 @@ public Optional<String> createAutonomousDatabase(String compartmentId, String db
return Optional.empty();
}
}

private PropertyChangeSupport listeners;

public void addPropertyChangeListener(PropertyChangeListener listener) {
synchronized (this) {
if (listeners == null) {
listeners = new PropertyChangeSupport(this);
}
listeners.addPropertyChangeListener(listener);
}
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
synchronized (this) {
if (listeners == null) {
return;
}
listeners.removePropertyChangeListener(listener);
}
}

@Override
public int hashCode() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
*
* @author Jan Horvath
*/
@NbBundle.Messages({
"MSG_BrokenProfile=Broken profile {0}"
})
public class TenancyInstance implements ServerInstanceImplementation, Lookup.Provider {

private final OCIItem tenancy;
Expand All @@ -41,28 +44,15 @@ public TenancyInstance(OCIItem tenancy, OCIProfile profile) {
this.profile = profile;
lkp = tenancy != null ? Lookups.fixed(profile, tenancy) : Lookups.fixed(profile);
}

@NbBundle.Messages({
"# {0} - tenancy ID",
"# {1} - profile ID",
"MSG_TenancyDesc={0} ({1})",
"# {0} - tenancy ID",
"# {1} - profile ID",
"MSG_BrokenTenancy=Unavailable tenancy {0}",
"# {0} - profile ID",
"MSG_BrokenProfile=Broken profile {0}",
})

@Override
public String getDisplayName() {
if (tenancy != null) {
return Bundle.MSG_TenancyDesc(tenancy.getName(), profile.getId());
} else if (profile.getTenantId() != null) {
return Bundle.MSG_BrokenTenancy(profile.getTenantId(), profile.getId());
} else {
return Bundle.MSG_BrokenProfile(profile.getId());
return tenancy.getName();
}
return profile.getId();
}

@Override
public Lookup getLookup() {
return lkp;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,41 @@ public TenancyNode(OCIItem tenancy, String disp, OCISessionInitiator session) {
// home region will be set as a description
setShortDescription(tenancy.getDescription());
OCIManager.getDefault().addPropertyChangeListener(WeakListeners.propertyChange(this, OCIManager.getDefault()));
if (session instanceof OCIProfile) {
((OCIProfile) session).addPropertyChangeListener(this);
}
}

@Override
public void propertyChange(PropertyChangeEvent e) {
if (OCIManager.PROP_ACTIVE_PROFILE.equals(e.getPropertyName())) {
if (OCIManager.PROP_ACTIVE_PROFILE.equals(e.getPropertyName()) ||
OCIProfile.PROP_ACTIVE_REGION_CODE.equals(e.getPropertyName()) ) {
fireDisplayNameChange(null, null);
}
}

@NbBundle.Messages({
"# {0} - tenancy ID",
"# {1} - profile ID",
"MSG_TenancyDesc={0} (profile: {1}, region: {2})",
"# {0} - tenancy ID",
"# {1} - profile ID",
"MSG_BrokenTenancy=Unavailable tenancy {0}",
"# {0} - profile ID",
"MSG_BrokenProfileNode=Broken profile {0}",
})
@Override
public String getDisplayName() {
OCIProfile profile = (OCIProfile) session;
if (item != null) {
return Bundle.MSG_TenancyDesc(item.getName(), profile.getId(), profile.getRegion());
} else if (profile.getTenantId() != null) {
return Bundle.MSG_BrokenTenancy(profile.getTenantId(), profile.getId());
} else {
return Bundle.MSG_BrokenProfileNode(profile.getId());
}
}

@NbBundle.Messages({
"HTML_EmphasizeName=<b>{0}</b>"
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@
import java.util.stream.Collectors;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.modules.cloud.oracle.OCIManager;
import static org.netbeans.modules.cloud.oracle.OCIManager.getDefault;
import org.netbeans.modules.cloud.oracle.OCIProfile;
import org.netbeans.modules.cloud.oracle.OCISessionInitiator;
import org.netbeans.modules.cloud.oracle.compartment.CompartmentItem;
Expand Down Expand Up @@ -692,8 +691,7 @@ private void addDbConnectionToVault(Result item) {
h.progress(Bundle.ReadingSecrets());

try {
VaultsClient client = VaultsClient.builder().build(getDefault().getActiveProfile().getConfigProvider());

VaultsClient client = OCIManager.getDefault().getActiveProfile().newClient(VaultsClient.class);
ListSecretsRequest listSecretsRequest = ListSecretsRequest.builder()
.compartmentId(item.vault.getCompartmentId())
.vaultId(item.vault.getKey().getValue())
Expand Down Expand Up @@ -756,7 +754,7 @@ private void addDbConnectionToVault(Result item) {
}

// Add Vault to the ConfigMap artifact
DevopsClient devopsClient = DevopsClient.builder().build(OCIManager.getDefault().getActiveProfile().getConfigProvider());
DevopsClient devopsClient = OCIManager.getDefault().getActiveProfile().newClient(DevopsClient.class);
ListDeployArtifactsRequest request = ListDeployArtifactsRequest.builder()
.projectId(item.project.getKey().getValue()).build();
ListDeployArtifactsResponse response = devopsClient.listDeployArtifacts(request);
Expand Down Expand Up @@ -980,7 +978,7 @@ public String getName() {
}

protected static Map<String, DevopsProjectItem> getDevopsProjects(String compartmentId) {
try (DevopsClient client = new DevopsClient(OCIManager.getDefault().getConfigProvider());) {
try (DevopsClient client = OCIManager.getDefault().getActiveProfile().newClient(DevopsClient.class);) {
ListProjectsRequest request = ListProjectsRequest.builder().compartmentId(compartmentId).build();
ListProjectsResponse response = client.listProjects(request);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,5 @@ DownloadWalletDialog.dbUserLabel.text=DB Username:
DownloadWalletDialog.dbPasswordLabel.text=DB Password:
DownloadWalletDialog.addDBCheckbox.toolltip=In addition to downloading Wallet, it also adds this database connection to the database manager.
DownloadWalletDialog.addDBCheckbox.text=Add As Database Connection
SetRegionDialog.jLabel1.text=Region:
SetRegionDialog.text=Please choose an Oracle Cloud Region from the list below. Your selected region will be the default for all future requests.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Optional;
import javax.swing.JFileChooser;
Expand Down

0 comments on commit 07f4872

Please sign in to comment.