I have a list of properties like this,
server1.serverName =""
server1.serverType ="'
server1.hostName =""
server1.userName =""
server1.password =""
in a property file and I have 'n' no of sets,like
server2, server3,...servern in a property file. And also I have a class which contain all off these elements with getter and setter method,
public class ServerDetails implements Serializable {
private String serverName;
private String serverType;
private String hostName;
private String userName;
private String password;
...
}
Now, I need to read the above property file and create an arraylist like ,
ArrayList<ServerDetails> serverDetailsList = new ArrayList<ServerDetails>();
where each element of the arrayList should have an object of the class ServerDetails. I need to know how to read the property file and get the server details so that I can create an object and add it to the list.
It seems kind of easy but i lost my way. Kindly help.
Thank you !!
Regards,
Bala
You could load the properties file into a Properties object, then loop through the properties like so:
int i = 1;
while( properties.get( "server" + i + ".serverName" ) != null ) {
ServerDetails details = new ...
details.setServerName( properties.get( [as above] ) );
...
list.add( details );
++i;
}
Open the file using Java IO
Parse the file line by line. Try storing the 'Key' 'value' pairs in a hashMap, you can then iterate over that adding/updating serverDetails that are stored in your arrayList.
Quick example:
private static final String KEY ="server";
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("props.properties"));
int i = 1;
while (properties.containsKey(KEY + i + ".serverName")) {
String serverName = properties.getProperty(KEY + i + ".serverName");
String serverType = properties.getProperty(KEY + i + ".serverType");
String hostName = properties.getProperty(KEY + i + ".hostName");
String userName = properties.getProperty(KEY + i + ".userName");
String password = properties.getProperty(KEY + i + ".password");
System.out.println(serverName);
System.out.println(serverType);
System.out.println(hostName);
System.out.println(userName);
System.out.println(password);
i++;
}
}
props.properties:
server1.serverName =1
server1.serverType =2
server1.hostName =3
server1.userName =4
server1.password =5
server2.serverName =6
server2.serverType =7
server2.hostName =8
server2.userName =9
server2.password =10
Properties properties = new Properties();
properties.load(new FileInputStream("application.properties"));
int i = 1;
String serverNameKey = "server" + i + ".serverName";
while (properties.containsKey(serverNameKey)) {
String serverName = (String) properties.get(serverNameKey);
//Read other properties
// Create new ServerDetails
// Add to list
i++;
}
Related
I'm creating a list of IP address' to ping in which a user can add to the list which is then saved to a properties file in the form of site.name1 = ... site.name2 = ...
Currently I have a for loop with a fixed amount, is there a way to get the number of entries in a properties file so I can set this in the for loop rather than wait for a exception?
PropertiesConfiguration config = configs.properties(new File("IPs.properties"));
//initially check for how many values there are - set to max increments for loop
for (int i = 0; i < 3; i++) { //todo fix
siteName = config.getString("site.name" + i);
siteAddress = config.getString("site.address" + i);
SiteList.add(i, siteName);
IPList.add(i, siteAddress);
}
I've looked through the documentation and other questions but they seem to be unrelated.
It looks to me based on the documentation you should be able to use PropertiesConfiguration#getLayout#getKeys to get a Set of all keys as a String.
I had to modify the code a bit to use apache-commons-configuration-1.10
PropertiesConfiguration config = new PropertiesConfiguration("ips.properties");
PropertiesConfigurationLayout layout = config.getLayout();
String siteName = null;
String siteAddress = null;
for (String key : layout.getKeys()) {
String value = config.getString(key);
if (value == null) {
throw new IllegalStateException(String.format("No value found for key: %s", key));
}
if (key.equals("site.name")) {
siteName = value;
} else if (key.equals("site.address")) {
siteAddress = value;
} else {
throw new IllegalStateException(String.format("Unsupported key: %s", key));
}
}
System.out.println(String.format("name=%s, address=%s", siteName, siteAddress));
I'm trying to add a href to Arraylist and this adds nicely to the Arraylist, but the link is broken. Everything after the question mark (?) in the URL is not included in the link.
Is there anything that I'm missing, code below:
private String processUpdate(Database dbCurrent) throws NotesException {
int intCountSuccessful = 0;
View vwLookup = dbCurrent.getView("DocsDistribution");
ArrayList<String> listArray = new ArrayList<String>();
Document doc = vwLookup.getFirstDocument();
while (doc != null) {
String paperDistro = doc.getItemValueString("DistroRecords");
if (paperDistro.equals("")) {
String ref = doc.getItemValueString("ref");
String unid = doc.getUniversalID();
// the link generated when adding to Arraylist is broken
listArray.add("" + ref + "");
}
Document tmppmDoc = vwLookup.getNextDocument(doc);
doc.recycle();
doc = tmppmDoc;
}
Collections.sort(listArray);
String listString = "";
for (String s : listArray) {
listString += s + ", \t";
}
return listString;
}
You have a problem with " escaping around unid value due to which you URL becomes gandhi.w3schools.com/testbox.nsf/distro.xsp?documentId="+ unid + "&action=openDocument.
It would be easier to read if you use String.format() and single quotes to generate the a tag:
listArray.add(String.format(
"<a href='gandhi.w3schools.com/testbox.nsf/distro.xsp?documentId=%s&action=openDocument'>%s</a>",
unid, ref));
I have this code to get the external ip of instances in GCP project
private static void printInstances(Compute compute, String projectId) throws IOException {
final Compute.Instances.List instances = compute.instances().list(projectId, zoneName);
final InstanceList list = instances.execute();
if ( list.getItems() == null ) {
System.out.println("No instances found. Sign in to the Google APIs Console and create an instance at: code.google.com/apis/console");
} else {
for ( final Instance instance : list.getItems() ) {
//System.out.println(instance.toPrettyString());
System.out.println("------------- " + instance.getName() + " (" + instance.getId() + ")");
final List<NetworkInterface> networkInterfaces = instance.getNetworkInterfaces();
for ( final NetworkInterface networkInterface : networkInterfaces ) {
String extIP = null;
final List<AccessConfig> accessConfigs = networkInterface.getAccessConfigs();
for ( final AccessConfig accessConfig : accessConfigs ) { // More than one?
extIP = accessConfig.getNatIP();
}
System.out.println(" Private=[" + networkInterface.getNetworkIP() + "] Public=[" + extIP + "]");
}
}
}
}
I want to get the same (meaning accessConfig.getNatIP) form instance of GCP ManagedInstance.
Like this:
Compute.InstanceGroupManagers.ListManagedInstances listInstances =
compute.instanceGroupManagers().listManagedInstances(projectId, zoneName, groupName);
List<ManagedInstance> list = listInstances.execute().getManagedInstances();
But I have found no way to get this.
Compute.InstanceGroupManagers.ListManagedInstances contains the URLs of the instances. Then use instances.get API to get the external IP in the instance.
it is a simple question, how to print out the selected file name, thanks.
public class CSVMAX {
public CSVRecord hottestInManyDays() {
//select many csv files from my computer
DirectoryResource dr = new DirectoryResource();
CSVRecord largestSoFar = null;
//read every row and implement the method we just define
for(File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
CSVRecord currentRow = hottestHourInFile(fr.getCSVParser());
if (largestSoFar == null) {
largestSoFar = currentRow;
}
else {
double currentTemp = Double.parseDouble(currentRow.get("TemperatureF"));
double largestTemp = Double.parseDouble(largestSoFar.get("TemperatureF"));
//Check if currentRow’s temperature > largestSoFar’s
if (currentTemp > largestTemp) {
//If so update largestSoFar to currentRow
largestSoFar = currentRow;
}
}
}
return largestSoFar;
}
here I want to print out the file name but I dont know how to do that.
public void testHottestInManyDay () {
CSVRecord largest = hottestInManyDays();
System.out.println("hottest temperature on that day was in file " + ***FILENAME*** + largest.get("TemperatureF") +
" at " + largest.get("TimeEST"));
}
}
Ultimately, it seems that hottestInManyDays() will need to return this information.
Does CSVRecord have a property for that?
Something like this:
CSVRecord currentRow = hottestHourInFile(fr.getCSVParser());
currentRow.setFileName(f.getName());
If not, can such a property be added to it?
Maybe CSVRecord doesn't have that property. But it can be added?:
private String _fileName;
public void setFileName(String fileName) {
this._fileName = fileName;
}
public String getFileName() {
return this._fileName;
}
If not, can you create a wrapper class for both pieces of information?
If you can't modify CSVRecord and it doesn't have a place for the information you want, wrap it in a class which does. Something as simple as this:
class CSVWrapper {
private CSVRecord _csvRecord;
private String _fileName;
// getters and setters for the above
// maybe also a constructor? make them final? your call
}
Then return that from hottestInManyDays() instead of a CSVRecord. Something like this:
CSVWrapper csvWrapper = new csvWrapper();
csvWrapper.setCSVRecord(currentRow);
csvWrapper.setFileName(f.getName());
Changing the method signature and return value as needed, of course.
However you do it, once it's on the return value from hottestInManyDays() you can use it in the method which consumes that:
CSVWrapper largest = hottestInManyDays();
System.out.println("hottest temperature on that day was in file " + largest.getFileName() + largest.getCSVRecord().get("TemperatureF") +
" at " + largest.getCSVRecord().get("TimeEST"));
(Note: If the bits at the very end there don't sit right as a Law Of Demeter violation, then feel free to extend the wrapper to include pass-thru operations as needed. Maybe even have it share a common interface with CSVRecord so it can be used as a drop-in replacement for one as needed elsewhere in the system.)
Referring to the line for(File f : dr.selectedFiles())
f is a [File]. It has a toString() method [from docs],
Returns the pathname string of this abstract pathname. This is just
the string returned by the getPath() method.
So, in the first line inside the loop, you can put System.out.println(f.toString()); to print out the file path.
Hope this helps clear a part of the story.
Now, to update this string, I see you are using some object that is called largest in testHottestInManyDay(). You should add a filepath string in this object and set it inside the else block.
One has to return both the CSVRecord and the File. Either in a newly made class.
As CSVRecord can be converted to a map, add the file name to the map, using a new column name, here "FILENAME."
public Map<String, String> hottestInManyDays() {
//select many csv files from my computer
DirectoryResource dr = new DirectoryResource();
CSVRecord largestSoFar = null;
File fileOfLargestSoFar = null;
//read every row and implement the method we just define
for (File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
CSVRecord currentRow = hottestHourInFile(fr.getCSVParser());
if (largestSoFar == null) {
largestSoFar = currentRow;
fileOfLargestSoFar = f;
}
else {
double currentTemp = Double.parseDouble(currentRow.get("TemperatureF"));
double largestTemp = Double.parseDouble(largestSoFar.get("TemperatureF"));
//Check if currentRow’s temperature > largestSoFar’s
if (currentTemp > largestTemp) {
//If so update largestSoFar to currentRow
largestSoFar = currentRow;
fileOfLargestSoFar = f;
}
}
}
Map<String, String> map = new HashMap<>(largestSoFar.toMap());
map.put("FILENAME", fileOfLargestSoFar.getPath());
return map;
}
Map<String, String> largest = hottestInManyDays();
System.out.println("hottest temperature on that day was in file "
+ largest.get("FILENAME") + largest.get("TemperatureF") +
" at " + largest.get("TimeEST"));
So, since dynamic variables aren't a thing in Java, and if statements will be horribly unwieldy, was looking for help converting this code block into a more concise one.
I looked into hashmaps, and they just didn't seem quite right, it's highly likely I was misunderstanding them though.
public String m1 = "Name1";
public String m1ip = "192.1.1.1";
public String m2 = "Name2";
public String m2ip = "192.1.1.1";
public String req;
public String reqip;
... snip some code...
if (requestedMachine == 1)
{ req = m1; reqip = m1ip;}
else if (requestedMachine == 2)
{ req = m2; reqip = m2ip;}
else if (requestedMachine == 3)
{ req = m3; reqip = m3ip;}
else if (requestedMachine == 4)
{ req = m4; reqip = m4ip;}
else if (requestedMachine == 5)
{ req = m5; reqip = m5ip;}
requestedMachine is going to be an integer, that defines which values should be assigned to req & reqip.
Thanks in advance.
Define a Machine class, containing a name and an ip field. Create an array of Machine. Access the machine located at the index requestedMachine (or requestedMachine - 1 if the number starts at 1):
Machine[] machines = new Machine[] {
new Machine("Name1", "192.1.1.1"),
new Machine("Name2", "192.1.1.1"),
...
}
...
Machine machine = machines[requestedMachine - 1];
First, create a Machine class:
class Machine {
String name;
String ip;
//Constructor, getters, setters etc omitted
}
Initialize an array of Machines:
Machine[] machines = ... //initialize them with values
Get the machine corresponding to requestedMachine:
Machine myMachine = machines[requestedMachine];
This is a great candidate for an enum:
/**
<P>{#code java EnumDeltaXmpl}</P>
**/
public class EnumDeltaXmpl {
public static final void main(String[] ingo_red) {
test(MachineAction.ONE);
test(MachineAction.TWO);
test(MachineAction.THREE);
test(MachineAction.FOUR);
}
private static final void test(MachineAction m_a) {
System.out.println("MachineAction." + m_a + ": name=" + m_a.sName + ", ip=" + m_a.sIP + "");
}
}
enum MachineAction {
ONE("Name1", "192.1.1.1"),
TWO("Name2", "292.2.2.2"),
THREE("Name3", "392.3.3.3"),
FOUR("Name4", "492.4.4.4"),
FIVE("Name5", "592.5.5.5");
public final String sName;
public final String sIP;
private MachineAction(String s_name, String s_ip) {
sName = s_name;
sIP = s_ip;
}
}
Output:
[C:\java_code\]java EnumDeltaXmpl
MachineAction.ONE: name=Name1, ip=192.1.1.1
MachineAction.TWO: name=Name2, ip=292.2.2.2
MachineAction.THREE: name=Name3, ip=392.3.3.3
MachineAction.FOUR: name=Name4, ip=492.4.4.4
Thee best choice you have is to build an array of machines with IP, Name etc..then you only need to find the machine required into the array.
public class Machine(){
private String name, ip;
public Machine(String name, String ip){
this.name=name;
// You can check a valid ip
this.ip=ip;
}}
public class Machines(){
private Machine[] machines;
private int number_of_machines;
public Machines(){
//define number_of_machines for your array and length of itself
}}
main()
Machine[] Machines = new Machine[number_of_machines];
Machine m1 = new Machine(String name, String ip);
.
.
.
Machine mn = new Machine(String name, String ip);
int number=5;
for(int i=0; i<number_of_machines; i++){
if (machines[number]<number_of_machines){
System.out.println("There is no machine with that number");
}else if (machines[number]==number_of_machines-1){
System.out.println("That is the choosen machine");
}
}
}
If your id values are not necessarily integers or if they are not a continuous sequence from 0 forward, you could also use a HashMap. Something like
HashMap<Integer, Machine> machines = new HashMap<>();
machines.put(1, machine1);
machines.put(7, machine7);
...
to get the desired value
Machine machine7 = machines.get(7);
You can replace the key with a String or whatever you like if needed. Your id values also do not need to go 0,1,2,3,4,5, ... as they need to if you are going with an array.