I am trying to learn something about JAVA and the best way to do this is creating something I would actually use and know what the purpose of it is.
I am trying to communicate with HyperV (WMI Library).
For example I found the following, my question is: how to use it? I am using Netbeans to create the GUI.
http://www.paulneve.com/wlab/javadoc/org/paulneve/wlab/virtualisation/VirtualisationAccessHyperVImpl.html
Also, how to load jInterop into my project so I can use it?
Thank you.
You can use JInterop for managing all operations of HyperV.
Download JInterop from here.
Add all JInterop jar files to your project build path.
Following is an example of getting all VMs of Hyper server:
public class ManageHyperV {
static final int RETURN_IMMEDIATE = 0x10;
static final int FORWARD_ONLY = 0x20;
private static final int STOP = 0;
private static final int START = 1;
static IJIDispatch msvmServices = null;
private static IJIDispatch createCOMServer(String namespace) { //root//virtualization
JIComServer comServer;
try {
JISystem.getLogger().setLevel(Level.WARNING);
JISystem.setAutoRegisteration(true);
JISession session = JISession.createSession(domainName,userName,password);
session.useSessionSecurity(false);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"),hostIP,session);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
//parameters to connect to WbemScripting.SWbemLocator
Object[] params = new Object[] {
new JIString(hostIP),//strServer
new JIString(namespace),//strNamespace
// new JIString("ROOT\\CIMV2"),
JIVariant.OPTIONAL_PARAM(),//strUser
JIVariant.OPTIONAL_PARAM(),//strPassword
JIVariant.OPTIONAL_PARAM(),//strLocale
JIVariant.OPTIONAL_PARAM(),//strAuthority
new Integer(0),//iSecurityFlags
JIVariant.OPTIONAL_PARAM()//objwbemNamedValueSet
};
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
return wbemServices;
} catch (JIException jie) {
System.out.println(jie.getMessage());
jie.printStackTrace();
} catch (JIRuntimeException jire) {
jire.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void getVMList() throws JIException {
String temp = "select * from Msvm_ComputerSystem";
String[] arrQuery = new String[]{temp};
for (int k=0;k<arrQuery.length;k++) {
Object[] params = new Object[] {
new JIString(arrQuery[k]),
JIVariant.OPTIONAL_PARAM(),
new JIVariant(new Integer(RETURN_IMMEDIATE + FORWARD_ONLY))
};
JIVariant[] servicesSet = msvmServices.callMethodA("ExecQuery", params);
iterateEnum(servicesSet);
}
}
private static void iterateEnum(JIVariant[] servicesSet) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(servicesSet[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject enumComObject = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVariant = (IJIEnumVariant) narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
List<Object[]> respArr = getEnumIterations(enumVariant);
for (Object[] elements : respArr) {
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] {});
System.out.println("----------------------------------------------------------------------");
System.out.println(v[0].getObjectAsString().getString());
System.out.println("----------------------------------------------------------------------");
}
}
} catch (JIRuntimeException e) {
e.printStackTrace();
} catch (JIException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
msvmServices = createCOMServer("root\\virtualization");
getVMList();
}
}
private static List<Object[]> getEnumIterations(IJIEnumVariant enumVariant) {
List<Object[]> list = new ArrayList<Object[]>();
int i=0;
for (i=0;i<100;i++) {
try {
list.add(enumVariant.next(1));
}catch (JIRuntimeException jre) {
break;
}
catch (JIException jie) {
break;
}
catch (Exception e) {
break;
}
}
return list;
}
Also, provide administrator username and password.
It should work.
Thanks.
Related
Good day!
I have a method which returns me an array of report names
System.out.println(bc[i].getDefaultName().getValue()
i want to use array output in other class, how i need to linked method outpud in my array in other class?
Method is:
public class ReoprtSearch {
public void executeTasks() {
PropEnum props[] = new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName};
BaseClass bc[] = null;
String searchPath = "//report";
//searchPath for folder - //folder, report - //report, folder and report - //folder | //report
try {
SearchPathMultipleObject spMulti = new SearchPathMultipleObject(searchPath);
bc = cmService.query(spMulti, props, new Sort[] {}, new QueryOptions());
} catch (Exception e) {
e.printStackTrace();
return;
}
if (bc != null) {
for (int i = 0; i < bc.length; i++) {
System.out.println(bc[i].getDefaultName().getValue();
}
}
}
}
array in what i want put the array looks like:
String [] folders =
my trying like:
ReoprtSearch search = new ReoprtSearch();
String [] folders = {search.executeTasks()};
Returns me an error: cannot convert from void to string
Give me an explanations to understand how i can related to method output from other class.
Thanks
The problem is that your executeTasks method doesn't actually return anything (which is why it's void), and just prints to stdout. Instead of printing, add the names to an array and then return it. Something like this:
public class ReoprtSearch {
public String[] executeTasks() {
PropEnum props[] = new PropEnum[] { PropEnum.searchPath, PropEnum.defaultName};
BaseClass bc[] = null;
String searchPath = "//report";
//searchPath for folder - //folder, report - //report, folder and report - //folder | //report
try {
SearchPathMultipleObject spMulti = new SearchPathMultipleObject(searchPath);
bc = cmService.query(spMulti, props, new Sort[] {}, new QueryOptions());
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (bc != null) {
String results[] = new String[bc.length];
for (int i = 0; i < bc.length; i++) {
results[i] = bc[i].getDefaultName().getValue();
}
return results;
}
return null;
}
}
In my jFrame,I created a table that contains the patients' list and a button that allows to refresh the table on action. When I click the refresh button for the firt time, the list is displayed in the table. Howerver, when I press it for a second time it doesn't work any more and the table isn't able to be refreshed.
Any idea about the problem please?
this is the code of the refresh button:
public class Interface extends javax.swing.JFrame{
private void RefreshActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)worklisttable.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {
model.removeRow(i);
}
model.fireTableDataChanged();
GetMwl_3.main(args);
}
public static void main(String args[]) {
......
}
}
GetMwl_3.java : allows to retrieve the patient list from the server
public class GetMwl_3 {
private String[] args;
/**
* #param args
*/
public static void main(String[] args/*,String aet, String host, Integer port*/) {
new GetMwl_3(/*aet,host,port*/);
}
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private Device device;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок
private boolean fuzzySemanticPersonNameMatching;
private Component emptyLabel;
public GetMwl_3(/*String aet, String host, Integer port*/) {
String name = "DCMMWL";
device = new Device(name);
NewThreadExecutor executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
/////////
Properties pacs = new Properties();
InputStream file = null;
File thefile = new File("C:\\properties\\save.properties");
if (thefile.exists()){
try {
file = new FileInputStream("C:\\properties\\save.properties");
// load a properties file
pacs.load(file);
// get the property value and print it out
remoteAE.setAETitle( pacs.getProperty("aethl7"));
remoteConn.setHostname(pacs.getProperty("hosthl7"));
remoteConn.setPort(Integer.parseInt(pacs.getProperty("porthl7")));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
setTransferSyntax(LE_TS);
long t1 = System.currentTimeMillis();
try {
assoc = ae.connect(remoteAE, executor);
} catch (Exception e) {
// System.err.println("ERROR: Failed to establish association:");
//e.printStackTrace(System.err);
//jLabel7.setText("ERROR: Failed to establish association");
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients ne peut pas être retirée");
//System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
//jLabel6.setText("Connected to " + remoteAE + " in "
// + ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
for(DicomObject dcm : result) {
worklist.main(args,
dcm.getString(Tag.PatientID),
dcm.getString(Tag.AccessionNumber),
dcm.getString(Tag.PatientName),
dcm.getString(Tag.PatientBirthDate),
dcm.getString(Tag.PatientSex),
dcm.getString(Tag.ReferringPhysicianName)
);
}
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients retirée avec succée");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assoc.release(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
}
}
return result;
}
}
worklist.java :
public class worklist extends Interface{
public worklist(){
}
public static void main(String[] args,
String PatientID,
String accessingNumber,
String PatientName,
String BirthDate,
String sex,
String referringPhysician
) {
DefaultTableModel modelw=(DefaultTableModel)worklisttable.getModel();
modelw.setColumnIdentifiers(new String[]{"ID Patient"," Nom Patient","Date de Naissance","Sexe"});
DefaultTableCellRenderer centerRenderer= new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
worklisttable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int j = 0 ; j< worklisttable.getColumnCount(); j++)
{
worklisttable.getColumnModel().getColumn(j).setCellRenderer(centerRenderer);
}
row=new Object[4];
row[0]=PatientID;
row[1]=PatientName;
row[2]=BirthDate;
row[3]=sex;
modelw.addRow(row);
}
}
I have set LightSIDE plugin and can run properly, but I don't know why I can't save my data to empty file? This is what a simple structure I made.
Activity is the list data that need to be categorize.
I have 3 categories and each of them have each type.
I already define each category with specific list of Words. For example : Food ({Sushi, Food, Japan}, {Cap Jay, Food, Chinese}, {Jog, Sport, Running}, ...)
And this is how I save my prediction with LightSIDE.
public void predictSectionType(String[] sections, List<String> activityList) {
LightSideService currentLightsideHelper = new LightSideService();
Recipe newRecipe;
// Initialize SIDEPlugin
currentLightsideHelper.initSIDEPlugin();
try {
// Load Recipe with Extracted Features & Trained Models
ClassLoader myClassLoader = getClass().getClassLoader();
newRecipe = ConverterControl.readFromXML(new InputStreamReader(myClassLoader.getResourceAsStream("static/lightsideTrainingResult/trainingData.xml")));
// Predict Result Data
Recipe recipeToPredict = currentLightsideHelper.loadNewDocumentsFromCSV(sections); // DocumentList & Recipe Created
currentLightsideHelper.predictLabels(recipeToPredict, newRecipe);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have class of LightSideService as Summary Class of LightSIDE function.
public class LightSideService {
// Extract Features Parameters
final String featureTableName = "1Grams";
final int featureThreshold = 2;
final String featureAnnotation = "Code";
final Type featureType = Type.NOMINAL;
// Build Models Parameters
final String trainingResultName = "Bayes_1Grams";
// Predict Labels Parameters
final String predictionColumnName = featureAnnotation + "_Prediction";
final boolean showMaxScore = false;
final boolean showDists = true;
final boolean overwrite = false;
final boolean useEvaluation = false;
public DocumentListTableModel model = new DocumentListTableModel(null);
public Map<String, Serializable> validationSettings = new TreeMap<String, Serializable>();
public Map<FeaturePlugin, Boolean> featurePlugins = new HashMap<FeaturePlugin, Boolean>();
public Map<LearningPlugin, Boolean> learningPlugins = new HashMap<LearningPlugin, Boolean>();
public Collection<ModelMetricPlugin> modelEvaluationPlugins = new ArrayList<ModelMetricPlugin>();
public Map<WrapperPlugin, Boolean> wrapperPlugins = new HashMap<WrapperPlugin, Boolean>();
// Initialize Data ==================================================
public void initSIDEPlugin() {
SIDEPlugin[] featureExtractors = PluginManager.getSIDEPluginArrayByType("feature_hit_extractor");
boolean selected = true;
for (SIDEPlugin fe : featureExtractors) {
featurePlugins.put((FeaturePlugin) fe, selected);
selected = false;
}
SIDEPlugin[] learners = PluginManager.getSIDEPluginArrayByType("model_builder");
for (SIDEPlugin le : learners) {
learningPlugins.put((LearningPlugin) le, true);
}
SIDEPlugin[] tableEvaluations = PluginManager.getSIDEPluginArrayByType("model_evaluation");
for (SIDEPlugin fe : tableEvaluations) {
modelEvaluationPlugins.add((ModelMetricPlugin) fe);
}
SIDEPlugin[] wrappers = PluginManager.getSIDEPluginArrayByType("learning_wrapper");
for (SIDEPlugin wr : wrappers) {
wrapperPlugins.put((WrapperPlugin) wr, false);
}
}
//Used to Train Models, adjust parameters according to model
public void initValidationSettings(Recipe currentRecipe) {
validationSettings.put("testRecipe", currentRecipe);
validationSettings.put("testSet", currentRecipe.getDocumentList());
validationSettings.put("annotation", "Age");
validationSettings.put("type", "CV");
validationSettings.put("foldMethod", "AUTO");
validationSettings.put("numFolds", 10);
validationSettings.put("source", "RANDOM");
validationSettings.put("test", "true");
}
// Load CSV Doc ==================================================
public Recipe loadNewDocumentsFromCSV(String filePath) {
DocumentList testDocs;
testDocs = chooseDocumentList(filePath);
if (testDocs != null) {
testDocs.guessTextAndAnnotationColumns();
Recipe currentRecipe = Recipe.fetchRecipe();
currentRecipe.setDocumentList(testDocs);
return currentRecipe;
}
return null;
}
public Recipe loadNewDocumentsFromCSV(String[] rootCauseList) {
DocumentList testDocs;
testDocs = chooseDocumentList(rootCauseList);
if (testDocs != null) {
testDocs.guessTextAndAnnotationColumns();
Recipe currentRecipe = Recipe.fetchRecipe();
currentRecipe.setDocumentList(testDocs);
return currentRecipe;
}
return null;
}
protected DocumentList chooseDocumentList(String filePath) {
TreeSet<String> docNames = new TreeSet<String>();
docNames.add(filePath);
try {
DocumentList testDocs;
Charset encoding = Charset.forName("UTF-8");
{
testDocs = ImportController.makeDocumentList(docNames, encoding);
}
return testDocs;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected DocumentList chooseDocumentList(String[] rootCauseList) {
try {
DocumentList testDocs;
testDocs = new DocumentList();
testDocs.setName("TestData.csv");
List<String> codes = new ArrayList();
List<String> roots = new ArrayList();
for (String s : rootCauseList) {
codes.add("");
roots.add((s != null) ? s : "");
}
testDocs.addAnnotation("Code", codes, false);
testDocs.addAnnotation("Root Cause Failure Description", roots, false);
return testDocs;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Save/Load XML ==================================================
public void saveRecipeToXml(Recipe currentRecipe, String filePath) {
File f = new File(filePath);
try {
ConverterControl.writeToXML(f, currentRecipe);
} catch (Exception e) {
e.printStackTrace();
}
}
public Recipe loadRecipeFromXml(String filePath) throws FileNotFoundException, IOException {
Recipe currentRecipe = ConverterControl.loadRecipe(filePath);
return currentRecipe;
}
// Extract Features ==================================================
public Recipe prepareBuildFeatureTable(Recipe currentRecipe) {
// Add Feature Plugins
Collection<FeaturePlugin> plugins = new TreeSet<FeaturePlugin>();
for (FeaturePlugin plugin : featurePlugins.keySet()) {
String pluginString = plugin.toString();
if (pluginString == "Basic Features" || pluginString == "Character N-Grams") {
plugins.add(plugin);
}
}
// Generate Plugin into Recipe
currentRecipe = Recipe.addPluginsToRecipe(currentRecipe, plugins);
// Setup Plugin configurations
OrderedPluginMap currentOrderedPluginMap = currentRecipe.getExtractors();
for (SIDEPlugin plugin : currentOrderedPluginMap.keySet()) {
String pluginString = plugin.toString();
Map<String, String> currentConfigurations = currentOrderedPluginMap.get(plugin);
if (pluginString == "Basic Features") {
for (String s : currentConfigurations.keySet()) {
if (s == "Unigrams" || s == "Bigrams" || s == "Trigrams" ||
s == "Count Occurences" || s == "Normalize N-Gram Counts" ||
s == "Stem N-Grams" || s == "Skip Stopwords in N-Grams") {
currentConfigurations.put(s, "true");
} else {
currentConfigurations.put(s, "false");
}
}
} else if (pluginString == "Character N-Grams") {
for (String s : currentConfigurations.keySet()) {
if (s == "Include Punctuation") {
currentConfigurations.put(s, "true");
} else if (s == "minGram") {
currentConfigurations.put(s, "3");
} else if (s == "maxGram") {
currentConfigurations.put(s, "4");
}
}
currentConfigurations.put("Extract Only Within Words", "true");
}
}
// Build FeatureTable
currentRecipe = buildFeatureTable(currentRecipe, featureTableName, featureThreshold, featureAnnotation, featureType);
return currentRecipe;
}
protected Recipe buildFeatureTable(Recipe currentRecipe, String name, int threshold, String annotation, Type type) {
FeaturePlugin activeExtractor = null;
try {
Collection<FeatureHit> hits = new HashSet<FeatureHit>();
for (SIDEPlugin plug : currentRecipe.getExtractors().keySet()) {
activeExtractor = (FeaturePlugin) plug;
hits.addAll(activeExtractor.extractFeatureHits(currentRecipe.getDocumentList(), currentRecipe.getExtractors().get(plug)));
}
FeatureTable ft = new FeatureTable(currentRecipe.getDocumentList(), hits, threshold, annotation, type);
ft.setName(name);
currentRecipe.setFeatureTable(ft);
} catch (Exception e) {
System.err.println("Feature Extraction Failed");
e.printStackTrace();
}
return currentRecipe;
}
// Build Models ==================================================
public Recipe prepareBuildModel(Recipe currentRecipe) {
try {
// Get Learner Plugins
LearningPlugin learner = null;
for (LearningPlugin plugin : learningPlugins.keySet()) {
/* if (plugin.toString() == "Naive Bayes") */
if (plugin.toString() == "Logistic Regression") {
learner = plugin;
}
}
if (Boolean.TRUE.toString().equals(validationSettings.get("test"))) {
if (validationSettings.get("type").equals("CV")) {
validationSettings.put("testSet", currentRecipe.getDocumentList());
}
}
Map<String, String> settings = learner.generateConfigurationSettings();
currentRecipe = Recipe.addLearnerToRecipe(currentRecipe, learner, settings);
currentRecipe.setValidationSettings(new TreeMap<String, Serializable>(validationSettings));
for (WrapperPlugin wrap : wrapperPlugins.keySet()) {
if (wrapperPlugins.get(wrap)) {
currentRecipe.addWrapper(wrap, wrap.generateConfigurationSettings());
}
}
buildModel(currentRecipe, validationSettings);
} catch (Exception e) {
e.printStackTrace();
}
return currentRecipe;
}
protected void buildModel(Recipe currentRecipe,
Map<String, Serializable> validationSettings) {
try {
FeatureTable currentFeatureTable = currentRecipe.getTrainingTable();
if (currentRecipe != null) {
TrainingResult results = null;
/*
* if (validationSettings.get("type").equals("SUPPLY")) {
* DocumentList test = (DocumentList)
* validationSettings.get("testSet"); FeatureTable
* extractTestFeatures = prepareTestFeatureTable(currentRecipe,
* validationSettings, test);
* validationSettings.put("testFeatureTable",
* extractTestFeatures);
*
* // if we've already trained the exact same model, don't // do
* it again. Just evaluate. Recipe cached =
* checkForCachedModel(); if (cached != null) { results =
* evaluateUsingCachedModel(currentFeatureTable,
* extractTestFeatures, cached, currentRecipe); } }
*/
if (results == null) {
results = currentRecipe.getLearner().train(currentFeatureTable, currentRecipe.getLearnerSettings(), validationSettings, currentRecipe.getWrappers());
}
if (results != null) {
currentRecipe.setTrainingResult(results);
results.setName(trainingResultName);
currentRecipe.setLearnerSettings(currentRecipe.getLearner().generateConfigurationSettings());
currentRecipe.setValidationSettings(new TreeMap<String, Serializable>(validationSettings));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected static FeatureTable prepareTestFeatureTable(Recipe recipe, Map<String, Serializable> validationSettings, DocumentList test) {
prepareDocuments(recipe, validationSettings, test); // assigns classes, annotations.
Collection<FeatureHit> hits = new TreeSet<FeatureHit>();
OrderedPluginMap extractors = recipe.getExtractors();
for (SIDEPlugin plug : extractors.keySet()) {
Collection<FeatureHit> extractorHits = ((FeaturePlugin) plug).extractFeatureHits(test, extractors.get(plug));
hits.addAll(extractorHits);
}
FeatureTable originalTable = recipe.getTrainingTable();
FeatureTable ft = new FeatureTable(test, hits, 0, originalTable.getAnnotation(), originalTable.getClassValueType());
for (SIDEPlugin plug : recipe.getFilters().keySet()) {
ft = ((RestructurePlugin) plug).filterTestSet(originalTable, ft, recipe.getFilters().get(plug), recipe.getFilteredTable().getThreshold());
}
ft.reconcileFeatures(originalTable.getFeatureSet());
return ft;
}
protected static Map<String, Serializable> prepareDocuments(Recipe currentRecipe, Map<String, Serializable> validationSettings, DocumentList test) throws IllegalStateException {
DocumentList train = currentRecipe.getDocumentList();
try {
test.setCurrentAnnotation(currentRecipe.getTrainingTable().getAnnotation(), currentRecipe.getTrainingTable().getClassValueType());
test.setTextColumns(new HashSet<String>(train.getTextColumns()));
test.setDifferentiateTextColumns(train.getTextColumnsAreDifferentiated());
Collection<String> trainColumns = train.allAnnotations().keySet();
Collection<String> testColumns = test.allAnnotations().keySet();
if (!testColumns.containsAll(trainColumns)) {
ArrayList<String> missing = new ArrayList<String>(trainColumns);
missing.removeAll(testColumns);
throw new java.lang.IllegalStateException("Test set annotations do not match training set.\nMissing columns: " + missing);
}
validationSettings.put("testSet", test);
} catch (Exception e) {
e.printStackTrace();
throw new java.lang.IllegalStateException("Could not prepare test set.\n" + e.getMessage(), e);
}
return validationSettings;
}
//Predict Labels ==================================================
public void predictLabels(Recipe recipeToPredict, Recipe currentRecipe) {
DocumentList newDocs = null;
DocumentList originalDocs;
if (useEvaluation) {
originalDocs = recipeToPredict.getTrainingResult().getEvaluationTable().getDocumentList();
TrainingResult results = currentRecipe.getTrainingResult();
List<String> predictions = (List<String>) results.getPredictions();
newDocs = addLabelsToDocs(predictionColumnName, showDists, overwrite, originalDocs, results, predictions, currentRecipe.getTrainingTable());
} else {
originalDocs = recipeToPredict.getDocumentList();
Predictor predictor = new Predictor(currentRecipe, predictionColumnName);
newDocs = predictor.predict(originalDocs, predictionColumnName, showDists, overwrite);
}
// Predict Labels result
model.setDocumentList(newDocs);
}
protected DocumentList addLabelsToDocs(final String name, final boolean showDists, final boolean overwrite, DocumentList docs, TrainingResult results, List<String> predictions, FeatureTable currentFeatureTable) {
Map<String, List<Double>> distributions = results.getDistributions();
DocumentList newDocs = docs.clone();
newDocs.addAnnotation(name, predictions, overwrite);
if (distributions != null) {
if (showDists) {
for (String label : currentFeatureTable.getLabelArray()) {
List<String> dist = new ArrayList<String>();
for (int i = 0; i < predictions.size(); i++) {
dist.add(String.format("%.3f", distributions.get(label).get(i)));
}
newDocs.addAnnotation(name + "_" + label + "_score", dist, overwrite);
}
}
}
return newDocs;
}
// ==================================================
}
David. It looks like the above replicates a lot of the functionality from the edu.cmu.side.recipe package. However, it doesn't look like your predictSectionType() method actually outputs the model's predictions anywhere.
If what you're trying to do is indeed to save predictions on new data using a trained model, check out the edu.cmu.side.recipe.Predictor class. It takes a trained model path as input, It's used by the scripts/predict.sh convenience script, but you could repurpose its main method if you needed to call it programmatically.
I hope this helps!
I am beginner in selenium webdriver, I am trying to work with different locator by reading excel sheet but in these it take only one data put it in one field by finding locator "id", and when it come to the second text field for this we are using locator by "Xpath" but its not taking. So, my question is how can I work with different locator also by don't using switch case if possible.
Below are my code:
public class MainClass {
private static final String BROWSER_PATH = "D:\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
// other constants
private WebDriver driver;
private Properties properties;
/*private WebElement we;*/
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() throws BiffException, IOException {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
}
private void handleScenario(String scenarioName) throws BiffException, IOException {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH);
testScenarios.setSheetName("Login");
testScenarios.columnData();
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMNameKK=" + framWork + ",Operation=" + operation +
",Value=" + value);
handleObjects(operation,value,framWork);
}
}
private void handleObjects(String operation,String value,String framWork) throws BiffException, IOException
{
System.out.println("HandleObject--> "+framWork);
ExcelHandler objectRepository = new ExcelHandler(OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows in hadleObject=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(objectRepository.getCell("FrameworkName"), k);
String ObjectName = objectRepository.readCell(objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkNameV=" + frameWorkName +
",ObjectName=" + ObjectName + ",Locator=" + Locator);
if(framWork.equalsIgnoreCase(frameWorkName))
{
operateWebDriver(operation,Locator,value,ObjectName);
}
}
}
private void operateWebDriver(String operation,String Locator,String value, String objectName)
{
System.out.println("Operation execution in progress");
WebElement temp=getElement(Locator,objectName);
if (operation.equalsIgnoreCase("SendKey"))
{
temp.sendKeys(value);
}
if (operation.equalsIgnoreCase("Click"))
{
temp.click();
}
}
public WebElement getElement(String locator,String objectName)
{
WebElement temp = null;
if(locator.equalsIgnoreCase("id"))
{
temp = driver.findElement(By.id(objectName));
}else if(locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
}
if(locator.equalsIgnoreCase("link"))
{
}
return temp;
}
}
You need the Reflection. See example in 2 methods below:
import java.lang.reflect.Method;
...
#Test
public void TestAmazon() {
driver = new ChromeDriver();
driver.navigate().to("http://www.amazon.com");
String locatorType = "id";
String locatorExpression = "twotabsearchtextbox";
By locator = createLocator(locatorType, locatorExpression);
WebElement textbox = driver.findElement(locator);
textbox.sendKeys("Star Wars: The Digital Movie Collection");
textbox.sendKeys(Keys.ENTER);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
locatorType = "className";
locatorExpression = "nav-logo-link";
locator = createLocator(locatorType, locatorExpression);
driver.findElement(locator).click();
}
private By createLocator(String locatorType, final String locatorExpression) {
By locator = null;
Class<By> byClass = By.class;
Class[] argTypes = new Class[] { String.class };
try {
Method m = byClass.getDeclaredMethod(locatorType, argTypes);
try {
locator = (By)m.invoke(null,locatorExpression);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return locator;
}
I am not able to find out why my executeUpdate() statement is returning this exception: "At least one parameter to the current statement is uninitialized". Can anyone spot what I am doing wrong? (I am aware that there are excessive try/catches in the code)
public class MetadataRetriever2 extends SwingWorker<MediaMeta, MediaMeta> {
private final List<File> dataFlavorFileList;
private final DefaultTableModel activeModel;
private static MediaMeta trackMetaData;
private static final MediaPlayerFactory factory = new MediaPlayerFactory();
int row = 0;
private int dropLocationRow;
Connection connection = null;
PreparedStatement myPreparedStatement = null;
EmbeddedDataSource dataSource = null;
MetadataRetriever2(List dataFlavorFileList, DefaultTableModel activeModel, int dropLocationRow) {
this.dropLocationRow = dropLocationRow;
this.dataFlavorFileList = dataFlavorFileList;
this.activeModel = activeModel;
}
#Override
protected MediaMeta doInBackground() throws Exception {
for (File file : dataFlavorFileList) {
if (MediaFileFilter.INSTANCE.accept(file)) {
trackMetaData = factory.getMediaMeta(file.toPath().toString(), true);
} else {
}
publish(trackMetaData);
}
return trackMetaData;
}
#Override
protected void process(List<MediaMeta> trackMetaData) {
String sql = "INSERT INTO DEFAULT_LIBRARY (ARTIST, TITLE, ALBUM, TRACK_NUMBER, LENGTH, "
+ "DESCRIPTION, RATING,DATE ,SETTING, URL, LANGUAGE, NOW_PLAYING, PUBLISHER, ENCODED_BY,"
+ "ARTWORK_URL, TRACK_ID) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
dataSource = new EmbeddedDataSource();
dataSource.setDatabaseName("audioPlayerDB");
try {
connection = dataSource.getConnection();
} catch (SQLException ex) {
System.out.println("connection failed");
}
try {
myPreparedStatement = connection.prepareStatement(sql);
} catch (SQLException ex) {
System.out.println("preparedStatement failed: " + ex.getCause());
}
String[] oArray = new String[16];
for (MediaMeta trackData : trackMetaData) {
oArray[0] = trackData.getArtist();
oArray[1] = trackData.getTitle();
oArray[2] = trackData.getAlbum();
oArray[3] = trackData.getTrackNumber();
oArray[4] = String.valueOf(trackData.getLength());
oArray[5] = trackData.getDescription();
oArray[6] = trackData.getRating();
oArray[7] = trackData.getDate();
oArray[8] = trackData.getSetting();
oArray[9] = trackData.getUrl();
oArray[10] = trackData.getLanguage();
oArray[11] = trackData.getNowPlaying();
oArray[12] = trackData.getPublisher();
oArray[13] = trackData.getEncodedBy();
oArray[14] = trackData.getArtworkUrl();
oArray[15] = trackData.getTrackId();
try {
myPreparedStatement.setString(1, oArray[0]);
myPreparedStatement.setString(2, oArray[1]);
myPreparedStatement.setString(3, oArray[2]);
myPreparedStatement.setString(4, oArray[3]);
myPreparedStatement.setString(5, oArray[4]);
myPreparedStatement.setString(6, oArray[5]);
myPreparedStatement.setString(7, oArray[6]);
myPreparedStatement.setString(8, oArray[7]);
myPreparedStatement.setString(9, oArray[8]);
myPreparedStatement.setString(10, oArray[9]);
myPreparedStatement.setString(11, oArray[10]);
myPreparedStatement.setString(12, oArray[11]);
myPreparedStatement.setString(13, oArray[12]);
myPreparedStatement.setString(14, oArray[13]);
myPreparedStatement.setString(15, oArray[15]);
activeModel.insertRow(dropLocationRow, oArray);
dropLocationRow++;
} catch (SQLException ex) {
Logger.getLogger(MetadataRetriever2.class.getName()).log(Level.SEVERE, null, ex);
}
try {
myPreparedStatement.executeUpdate();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Your statement requires 16 parameters, and your object[] doesn't line up
myPreparedStatement.setString(14, oArray[13]);
myPreparedStatement.setString(15, oArray[15]);
should be
myPreparedStatement.setString(14, oArray[13]);
myPreparedStatement.setString(15, oArray[14]);
myPreparedStatement.setString(16, oArray[15]);