Building anagram finder and I have one eclipse error: insert } to complete block. - syntax

Problem is that the eclipse recommendation makes little sense -- to me. I checked my blocks several times.
This is my first time posting code so I'm hoping it's formatted ok.
The eclipse error is on line 73: below the ; "anagrams.add(current);" This is the second line below the last for loop in the code.
package anagrecur2;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.io.*;
public class AnagRecur2Main {
public static void main(String[] args) {
List<String> anagrams = new ArrayList<String>();
List<String> preString = new ArrayList<String>();
List<String> postString = new ArrayList<String>();
List<String> word = new ArrayList<String>();
word.add("t");
word.add("e");
word.add("a");
word.add("m");
preString.add("");
postString.add("");
String c;
String current;
}
ArrayList<String> getAnagrams (String word, String preString){
// remove the first occurrence of each
// character in preString from word and
// stores it in postString
}
ArrayList<String> removePreStringFromWord(List word){
ArrayList<String> postString;
ArrayList<String> preString;
for (int i = 0; i < preString.size(); i++) {
for (int j = 0; j < word.size(); j++) {
if (preString.get(i)== word.get(j)){
word.remove(j);
}else {
postString.add((String) word.get(j));
}
}
return postString;
}
}
// using a string as if it is a c# string.
// for java you need to convert the string to
// char array
//ArrayList<String> word;
//String current;
//char poststrCharA;
ArrayList<String> anagrams;
ArrayList<String> preString;
ArrayList<String> postString;
String[] prestrAr = new String[preString.size()];{
prestrAr = preString.toArray(prestrAr);
for(String s : prestrAr){
System.out.println(s);
}
for (String poststrCharA : postString){
poststrCharA.toCharArray();
System.out.println("postStringtoCharAr"+poststrCharA);
}
// adds string combo to anagrams if
// it is a true word
for (String c : prestrAr) {
String current = prestrAr + c;
anagrams.add(current);
}
void getAnagrams(char word, char current){
System.out.println("word= "+word+"current= "+current);
}
}

First off, your getAnagrams doesn't return a string Array list. Also, what are you trying to accomplish with this file?

Related

gwt cell table dynamic columns - sorting need an example

I'm new to GWT and I need to create a sortable dynamic celltable.
I saw an example of IndexedColumn class. I generated a Dynamic cell table (List of ArrayList of String), but couldn't make it sort.
does anybody have a simple implementation example?
Thanks
Found my mistake...
Here is my working example:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.view.client.ListDataProvider;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class DynamicTable implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
List<ArrayList<String>> data = this.getThedata();
CellTable<List<String>> table = new CellTable<List<String>>();
ArrayList<String> dataHeaders = data.remove(0);
ArrayList<IdxColumn> columnList = new ArrayList<IdxColumn>();
ListDataProvider<List<String>> dataProvider = new ListDataProvider<List<String>>();
dataProvider.addDataDisplay(table);
List<List<String>> list = dataProvider.getList();
for (List<String> l : data) {
list.add(l);
}
ListHandler<List<String>> columnSortHandler = new ListHandler<List<String>>(list);
table.getColumnSortList().clear();
for (int i = 0; i < data.get(0).size(); i++) {
final int index = i;
IdxColumn iCol = new IdxColumn(index);
columnList.add(iCol);
table.addColumn(iCol, dataHeaders.get(index) + " (" +iCol.getIndex() + ")");
columnSortHandler.setComparator(iCol, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
if (o1 == o2) {
return 0;
}
if (o1 != null) {
return (o2 != null) ? o1.get(0).compareTo(o2.get(0)) : 1;
}
return -1;
}
});
iCol.setSortable(true);
table.getColumnSortList().push(iCol);
}
table.addColumnSortHandler(columnSortHandler);
table.setRowCount(data.size(), true);
table.setRowData(0, data);
RootPanel.get().add(table);
}
// build the data
private List<ArrayList<String>> getThedata() {
List<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> dataHeaders = new ArrayList<String>();
dataHeaders.add("Header 1");
dataHeaders.add("Header 2");
dataHeaders.add("Header 3");
dataHeaders.add("Header 4");
dataHeaders.add("Header 5");
dataHeaders.add("Header 6");
data.add(dataHeaders);
for (int i = 0; i < 20; i++) {
ArrayList<String> dataRow = new ArrayList<String>();
dataRow.add("Col1 Row" + i);
dataRow.add("Col2 Row" + i);
dataRow.add("Col3 Row" + i);
dataRow.add("Col4 Row" + i);
dataRow.add("Col5 Row" + i);
dataRow.add("Col6 Row" + i);
data.add(dataRow);
}
return data;
}
}
And the IdxColumn class:
import java.util.List;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.user.cellview.client.Column;
public class IdxColumn extends Column<List<String>, String> {
private final int index;
public IdxColumn( int index) {
super(new TextCell());
this.index = index;
}
#Override
public String getValue(List<String> object) {
return object.get(index);
}
public int getIndex() {
return this.index;
}
}

How to print a properly sorted Radix Trie

I was trying to print a properly sorted Radix Trie but when I tried to do it, it does with DFS but single letters are printed in a wrong place... What am I doing wrong? Am I doing wrong with the recursion or do I need another condition that I'm missing?
Ex:
0692
072755
0
1008
1076
10
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Trie {
static class TrieNode {
TrieNode[] children = new TrieNode[128];
boolean leaf;
}
public static void insertString(TrieNode rootNode, String s) {
TrieNode root = rootNode;
for (char ch : s.toCharArray()) {
TrieNode next = root.children[ch];
if (next == null)
root.children[ch] = next = new TrieNode();
root = next;
}
root.leaf = true;
}
public static void printSorted(TrieNode node, String s) {
for (char ch = 0; ch < node.children.length; ch++) {
TrieNode child = node.children[ch];
if (child != null)
printSorted(child, s + ch);
}
if (node.leaf) {
System.out.println(s);
}
}
public static void main(String[] args) throws IOException {
TrieNode root = new TrieNode();
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
String line = null;
while ((line = br.readLine()) != null) {
insertString(root, line);
line = null;
}
printSorted(root, "");
}
}
in your printSorted function, try printing the leaf first as the leaf is always less than its children.

Java 8 Stream , convert List<File> to Map<Integer, List<FIle>>

I have below code in traditional java loop. Would like to use Java 8 Stream instead.
I have a sorted list of files(Sorted by file size). I group these files together in a way that the total size of all files does not exceed the given max size and put them in a Map with the key 1,2,3,... so on. Here is the code.
List<File> allFilesSortedBySize = getListOfFiles();
Map<Integer, List<File>> filesGroupedByMaxSizeMap = new HashMap<Integer, List<File>>();
double totalLength = 0L;
int count = 0;
List<File> filesWithSizeTotalMaxSize = Lists.newArrayList();
//group the files to be zipped together as per maximum allowable size in a map
for (File file : allFilesSortedBySize) {
long sizeInBytes = file.length();
double sizeInMb = (double)sizeInBytes / (1024 * 1024);
totalLength = totalLength + sizeInMb;
if(totalLength <= maxSize) {
filesWithSizeTotalMaxSize.add(file);
} else {
count = count + 1;
filesGroupedByMaxSizeMap.put(count, filesWithSizeTotalMaxSize);
filesWithSizeTotalMaxSize = Lists.newArrayList();
filesWithSizeTotalMaxSize.add(file);
totalLength = sizeInMb;
}
}
filesGroupedByMaxSizeMap.put(count+1, filesWithSizeTotalMaxSize);
return filesGroupedByMaxSizeMap;
after reading,I found the solution using Collectors.groupBy instead.
Code using java8 lambda expression
private final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
AtomicInteger group = new AtomicInteger(0);
AtomicLong groupSize = new AtomicLong();
return files.stream().collect(groupingBy((file) -> {
if (groupSize.addAndGet(file.length()) <= maxSize * MB) {
return group.get() == 0 ? group.incrementAndGet() : group.get();
}
groupSize.set(file.length());
return group.incrementAndGet();
}));
}
Code provided by #Holger then you are free to checking group whether equals 0
private static final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
AtomicInteger group = new AtomicInteger(0);
//force initializing group starts with 1 even if the first file is empty.
AtomicLong groupSize = new AtomicLong(maxSize * MB + 1);
return files.stream().collect(groupingBy((file) -> {
if (groupSize.addAndGet(file.length()) <= maxSize * MB) {
return group.get();
}
groupSize.set(file.length());
return group.incrementAndGet();
}));
}
Code using anonymous class
inspired by #Holger, All “solutions” using a grouping function that modifies external state are hacks abusing the API,so you can use anonymous class to manage the grouping logic state in class.
private static final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
return files.stream().collect(groupingBy(groupSize(maxSize)));
}
private Function<File, Integer> groupSize(final long maxSize) {
long maxBytesSize = maxSize * MB;
return new Function<File, Integer>() {
private int group;
private long groupSize = maxBytesSize + 1;
#Override
public Integer apply(File file) {
return hasRemainingFor(file) ? current(file) : next(file);
}
private boolean hasRemainingFor(File file) {
return (groupSize += file.length()) <= maxBytesSize;
}
private int next(File file) {
groupSize = file.length();
return ++group;
}
private int current(File file) {
return group;
}
};
}
Test
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.groupingBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* Created by holi on 3/24/17.
*/
public class StreamGroupingTest {
private final File FILE_1MB = file(1);
private final File FILE_2MB = file(2);
private final File FILE_3MB = file(3);
#Test
void eachFileInIndividualGroupIfEachFileSizeGreaterThanMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_2MB, FILE_3MB), 1);
assertThat(groups.size(), equalTo(2));
assertThat(groups.get(1), equalTo(singletonList(FILE_2MB)));
assertThat(groups.get(2), equalTo(singletonList(FILE_3MB)));
}
#Test
void allFilesInAGroupIfTotalSizeOfFilesLessThanOrEqualMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_2MB, FILE_3MB), 5);
assertThat(groups.size(), equalTo(1));
assertThat(groups.get(1), equalTo(asList(FILE_2MB, FILE_3MB)));
}
#Test
void allNeighboringFilesInAGroupThatTotalOfTheirSizeLessThanOrEqualMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_1MB, FILE_2MB, FILE_3MB), 3);
assertThat(groups.size(), equalTo(2));
assertThat(groups.get(1), equalTo(asList(FILE_1MB, FILE_2MB)));
assertThat(groups.get(2), equalTo(singletonList(FILE_3MB)));
}
#Test
void eachFileInIndividualGroupIfTheFirstFileAndTotalOfEachNeighboringFilesSizeGreaterThanMaxSize() {
Map<Integer, List<File>> groups = grouping(asList(FILE_2MB, FILE_1MB, FILE_3MB), 2);
assertThat(groups.size(), equalTo(3));
assertThat(groups.get(1), equalTo(singletonList(FILE_2MB)));
assertThat(groups.get(2), equalTo(singletonList(FILE_1MB)));
assertThat(groups.get(3), equalTo(singletonList(FILE_3MB)));
}
#Test
void theFirstEmptyFileInGroup1() throws Throwable {
File emptyFile = file(0);
Map<Integer, List<File>> groups = grouping(singletonList(emptyFile), 2);
assertThat(groups.get(1), equalTo(singletonList(emptyFile)));
}
private static final long MB = 1024 * 1024;
private Map<Integer, List<File>> grouping(List<File> files, long maxSize) {
AtomicInteger group = new AtomicInteger(0);
AtomicLong groupSize = new AtomicLong(maxSize * MB + 1);
return files.stream().collect(groupingBy((file) -> {
if (groupSize.addAndGet(file.length()) <= maxSize * MB) {
return group.get();
}
groupSize.set(file.length());
return group.incrementAndGet();
}));
}
private Function<File, Integer> groupSize(final long maxSize) {
long maxBytesSize = maxSize * MB;
return new Function<File, Integer>() {
private int group;
private long groupSize = maxBytesSize + 1;
#Override
public Integer apply(File file) {
return hasRemainingFor(file) ? current(file) : next(file);
}
private boolean hasRemainingFor(File file) {
return (groupSize += file.length()) <= maxBytesSize;
}
private int next(File file) {
groupSize = file.length();
return ++group;
}
private int current(File file) {
return group;
}
};
}
private File file(int sizeOfMB) {
return new File(String.format("%dMB file", sizeOfMB)) {
#Override
public long length() {
return sizeOfMB * MB;
}
#Override
public boolean equals(Object obj) {
File that = (File) obj;
return length() == that.length();
}
};
}
}
Since the processing of each element highly depends on the previous’ processing, this task is not suitable for streams. You still can achieve it using a custom collector, but the implementation would be much more complicated than the loop solution.
In other words, there is no improvement when you rewrite this as a stream operation. Stay with the loop.
However, there are still some things you can improve.
List<File> allFilesSortedBySize = getListOfFiles();
// get maxSize in bytes ONCE, instead of converting EACH size to MiB
long maxSizeBytes = (long)(maxSize * 1024 * 1024);
// use "diamond operator"
Map<Integer, List<File>> filesGroupedByMaxSizeMap = new HashMap<>();
// start with "create new list" condition to avoid code duplication
long totalLength = maxSizeBytes;
// count is obsolete, the map maintains a size
// the initial "totalLength = maxSizeBytes" forces creating a new list within the loop
List<File> filesWithSizeTotalMaxSize = null;
for(File file: allFilesSortedBySize) {
long length = file.length();
if(maxSizeBytes-totalLength <= length) {
filesWithSizeTotalMaxSize = new ArrayList<>(); // no utility method needed
// store each list immediately, so no action after the loop needed
filesGroupedByMaxSizeMap.put(filesGroupedByMaxSizeMap.size()+1,
filesWithSizeTotalMaxSize);
totalLength = 0;
}
totalLength += length;
filesWithSizeTotalMaxSize.add(file);
}
return filesGroupedByMaxSizeMap;
You may further replace
filesWithSizeTotalMaxSize = new ArrayList<>();
filesGroupedByMaxSizeMap.put(filesGroupedByMaxSizeMap.size()+1,
filesWithSizeTotalMaxSize);
with
filesWithSizeTotalMaxSize = filesGroupedByMaxSizeMap.computeIfAbsent(
filesGroupedByMaxSizeMap.size()+1, x -> new ArrayList<>());
but there might be different opinions whether this is an improvement.
The simplest solution to the problem I could think of is to use an AtomicLong wrapper for the size and a AtomicInteger wrapper for length. These have some useful methods for performing basic arithmetic operations on them which are very useful in this particular case.
List<File> files = getListOfFiles();
AtomicLong length = new AtomicLong();
AtomicInteger index = new AtomicInteger(1);
long maxLength = SOME_ARBITRARY_NUMBER;
Map<Integer, List<File>> collect = files.stream().collect(Collectors.groupingBy(
file -> {
if (length.addAndGet(file.length()) <= maxLength) {
return index.get();
}
length.set(file.length());
return index.incrementAndGet();
}
));
return collect;
Basically what Collectors.groupingBy does the work which you Intended.

How to retrieve data from mysql database from what is the input on my textfield

For example I have entered my pin to 123 in my text field I want that program to Show the balance, card number and account number of that certain pin
i used setters and getters to get the pin from the previous frame (login)
Here is my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.table.*;
public class Test extends JFrame
{
private static final Test sh1 = new Test();
public static Test getInstance()
{
return sh1;
}
Container c;
Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rm;
JTable tb;
JButton btnback = new JButton("Back");
JTextField pin = new JTextField("");
public void setUser(String user) {this.pin.setText(user);}
public String getUser() {return this.pin.getText();}
public Test(){
this.setTitle("Data");
this.setSize(500,500);
this.setLocation(800, 80);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.add(btnback);
c.add(pin);
stud();
}
public void stud()
{
Vector ColName = new Vector();
Vector Data = new Vector();
try{
String driver="com.mysql.jdbc.Driver";
String db="jdbc:mysql://localhost:3306/atm";
String user="root";
String pass="";
Class.forName(driver);
con=DriverManager.getConnection(db,user,pass);
st=con.createStatement();
String pincodee = pin.getText().trim();
String sqltb = "Select balance,cardnumber , accountnumber from accounts WHERE "
+ "pincode = '"+pincodee+"' ";
rs = st.executeQuery(sqltb);
rm = rs.getMetaData();
int col = rm.getColumnCount();
for(int i = 1; i <= col; i++)
{
ColName.addElement(rm.getColumnName(i));
}
while(rs.next())
{
Vector row = new Vector(col);
for(int i = 1; i <= col; i++)
{
row.addElement(rs.getObject(i));
String s = rs.getString(2);
pin.setText(s);
}
Data.addElement(row);
}
}
catch (Exception ex)
{
}
tb = new JTable( Data, ColName);
tb.repaint();
JScrollPane sc = new JScrollPane(tb);
sc.validate();
c.add(sc);
}
public static void main(String[] args)
{
Test s = new Test();
s.setVisible(true);
}
}
You need to create a button which says 'Go!' or something like that and add an action listener to it that calls your stud() method.
look here for example..
http://www.javaprogrammingforums.com/java-swing-tutorials/278-how-add-actionlistener-jbutton-swing.html
Your code is not going to work either way, you need to rewrite a great deal of it but the ActionListener class is your friend if you want actions on the user interface to call logic code.

Accessing SWbemObject Object Properties using J-Interop Library

I am very new to J-Interop Library and WMI. I was just playing around with the following sample code from j-interop samples (MSWMI, which deals with WMI Communication).
package org.jinterop.dcom.test;
import java.net.UnknownHostException;
import java.util.logging.Level;
import org.jinterop.dcom.common.IJIUnreferenced;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JICallBuilder;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JIFlags;
import org.jinterop.dcom.core.JIProgId;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
public class MSWMI {
private JIComServer comStub = null;
private IJIComObject comObject = null;
private IJIDispatch dispatch = null;
private String address = null;
private JISession session = null;
public MSWMI(String address, String[] args) throws JIException, UnknownHostException
{
this.address = address;
session = JISession.createSession(args[1],args[2],args[3]);
session.useSessionSecurity(true);
session.setGlobalSocketTimeout(5000);
comStub = new JIComServer(JIProgId.valueOf("WbemScripting.SWbemLocator"),address,session);
IJIComObject unknown = comStub.createInstance();
comObject = (IJIComObject)unknown.queryInterface("76A6415B-CB41-11d1-8B02-00600806D9B6");//ISWbemLocator
//This will obtain the dispatch interface
dispatch = (IJIDispatch)JIObjectFactory.narrowObject(comObject.queryInterface(IJIDispatch.IID));
}
public void performOp() throws JIException, InterruptedException
{
System.gc();
JIVariant results[] = dispatch.callMethodA("ConnectServer",new Object[]{new JIString(address),JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM()
,JIVariant.OPTIONAL_PARAM(),JIVariant.OPTIONAL_PARAM(),new Integer(0),JIVariant.OPTIONAL_PARAM()});
//using the dispatch results above you can use the "ConnectServer" api to retrieve a pointer to IJIDispatch
//of ISWbemServices
//OR
//Make a direct call like below , in this case you would get back an interface pointer to ISWbemServices , NOT to it's IDispatch
JICallBuilder callObject = new JICallBuilder();
callObject.addInParamAsString(address,JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsString("",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsInt(0,JIFlags.FLAG_NULL);
callObject.addInParamAsPointer(null,JIFlags.FLAG_NULL);
callObject.setOpnum(0);
callObject.addOutParamAsType(IJIComObject.class,JIFlags.FLAG_NULL);
IJIComObject wbemServices = JIObjectFactory.narrowObject((IJIComObject)((Object[])comObject.call(callObject))[0]);
wbemServices.setInstanceLevelSocketTimeout(1000);
wbemServices.registerUnreferencedHandler(new IJIUnreferenced(){
public void unReferenced()
{
System.out.println("wbemServices unreferenced... ");
}
});
//Lets have a look at both.
IJIDispatch wbemServices_dispatch = (IJIDispatch)JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());
results = wbemServices_dispatch.callMethodA("InstancesOf", new Object[]{new JIString("Win32_Process"), new Integer(0), JIVariant.OPTIONAL_PARAM()});
IJIDispatch wbemObjectSet_dispatch = (IJIDispatch)JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());
JIVariant variant = wbemObjectSet_dispatch.get("_NewEnum");
IJIComObject object2 = variant.getObjectAsComObject();
System.out.println(object2.isDispatchSupported());
System.out.println(object2.isDispatchSupported());
object2.registerUnreferencedHandler(new IJIUnreferenced(){
public void unReferenced()
{
System.out.println("object2 unreferenced...");
}
});
IJIEnumVariant enumVARIANT = (IJIEnumVariant)JIObjectFactory.narrowObject(object2.queryInterface(IJIEnumVariant.IID));
//This will return back a dispatch of ISWbemObjectSet
//OR
//It returns back the pointer to ISWbemObjectSet
callObject = new JICallBuilder();
callObject.addInParamAsString("Win32_Process",JIFlags.FLAG_REPRESENTATION_STRING_BSTR);
callObject.addInParamAsInt(0,JIFlags.FLAG_NULL);
callObject.addInParamAsPointer(null,JIFlags.FLAG_NULL);
callObject.setOpnum(4);
callObject.addOutParamAsType(IJIComObject.class,JIFlags.FLAG_NULL);
IJIComObject wbemObjectSet = JIObjectFactory.narrowObject((IJIComObject)((Object[])wbemServices.call(callObject))[0]);
//okay seen enough of the other usage, lets just stick to disptach, it's lot simpler
JIVariant Count = wbemObjectSet_dispatch.get("Count");
int count = Count.getObjectAsInt();
for (int i = 0; i < count; i++)
{
Object[] values = enumVARIANT.next(1);
JIArray array = (JIArray)values[0];
Object[] arrayObj = (Object[])array.getArrayInstance();
for (int j = 0; j < arrayObj.length; j++)
{
IJIDispatch wbemObject_dispatch = (IJIDispatch)JIObjectFactory.narrowObject(((JIVariant)arrayObj[j]).getObjectAsComObject());
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
System.out.println(variant2.getObjectAsString().getString());
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
}
private void killme() throws JIException
{
JISession.destroySession(session);
}
public static void main(String[] args) {
try {
if (args.length < 4)
{
System.out.println("Please provide address domain username password");
return;
}
JISystem.getLogger().setLevel(Level.INFO);
JISystem.setInBuiltLogHandler(false);
JISystem.setAutoRegisteration(true);
MSWMI test = new MSWMI(args[0],args);
for (int i = 0 ; i < 100; i++)
{
System.out.println("Index i: " + i);
test.performOp();
}
test.killme();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I understand that the following line of code calls the method "GetObjectText_" of the SWbemObject Object and we can see all the properties of the class instance.
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
What I wish to find out is, what should I do if I just need to retrieve a single property value, for example, if all I wanted was to retrieve the "InstallDate" property of the "Win32_Process" Class, what method would I call or how to access a particular property if I knew the property name I wish to access.
Any help on this topic would be great. Thanks a lot!!
You could access a property with the following code:
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.get("Caption"));
This replaces the line:
JIVariant variant2 = (JIVariant)(wbemObject_dispatch.callMethodA("GetObjectText_",new Object[]{new Integer(1)}))[0];
The “InstallDate” properties were all empty so I use the “Caption”.

Resources