Code Monkey home page Code Monkey logo

yavijava's Introduction

Build Status Join the chat at https://gitter.im/yavijava/yavijava

Welcome to the YAVI Java API

WHAT IS YAVI JAVA API?

It is a fork of the VI Java API which is a set of Java libraries that aim to ease the usage of VI SDK Web Services interfaces. It's now open-sourced under a mixed BSD license and Apache-2.0 license.

It provides the following benefits to the Java developers:

  • Enables OO programming with a well defined managed object model
  • Reduces the need to use ManagedObjectReference and makes possible compile time type checking
  • Hides the complexity of the PropertyCollector
  • Provides necessary utility classes to simplify VI SDK web interfaces
  • High performance with 4+ times faster than AXIS engine
  • Adds the ability to provide your own HTTP Client
  • Adds logging using log4j
  • Adds gradle support for the build system

As a result, the application code using this API is much shorter (70% less) and much more readable than the equivalent using web service interfaces directly. The API itself is straight-forward and easy to learn and use.

WHO CREATED THE API?

To find out more about the original VI Java API see http://vijava.sf.net

As for who created this fork called YAVI Java that is Michael Rice.

Whats with the name?

The name YAVI means simply Yet Another VI Java. I forked this project and moved it to github because the project seemd stale and I felt it needed new life. I wanted things like GitHub, custom http clients, and logging, and tests as well as other stuff so I decided to fork the project and do it.

Do I have to change my code to use this?

No!! This is a drop in replacement and requires no code modification, but does introduce some new dependencies (Always check the build.gradle for the latest requirements):

dependencies {
    compile 'org.apache.directory.studio:org.dom4j.dom4j:1.6.1'
    compile 'log4j:log4j:1.2.17'
    compile 'org.apache.httpcomponents:httpclient:4.3.5'
    testCompile 'org.mockito:mockito-all:1.9.5'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

WHERE CAN I GET HELP?

File a bug: https://github.com/yavijava/yavijava/issues

IRC: Freenode IRC #vijava

COPYRIGHT & LICENSE: BSD. See the License.txt file for details

What happened to the samples?!?!

Never fear. I removed them from the core of the project and made them their own project. They can be found here: https://github.com/yavijava/yavijava-samples

Testing

Testing is broken into two main packages which are discussed below. It is very important that pull requests you send include a test. Many very large enterprise customers depend on this library so extensive work is being put into trying to cover as much of the codebase as possible with tests.

Integration

The first package is integration tests which are stored in src/intTest There is a properties file included that contains the URL, username and password for use in connecting to a vCenter or HostSystem. It has a default value of https://vcsa/sdk for its URL, and '[email protected]' for the user name, and 'password' is used for the default password. The reason these defaults are included is because I use the vCenter Server Appliance in SIM mode to do as many of the tests as possible and I create an alias in my /etc/hosts file so vcsa always points at my local vCenter. Next I use a very basic shell script to configure the VCSA SIM and use 'password' for my default password. To run these tests make sure the properties file contains valid information for your environment. Next from the project root where the build.gradle is execute gradle intTest or use the gradlew script and execute: ./gradlew intTest

Unit

The Second package is the unit tests. These tests are stored in src/test These are basic unit tests and should be created using either junit or spock. Tests can be written in pure Java or Groovy. Please use the appropriate folder for the language you create your test with. The unit tests are run automatically by travis-ci when a pull request is opened, and they should always be run before you open a pull request where you are introducing changes that either fix bugs, or add functionality to ensure they continue to pass with your changes. To run these tests execute gradle test or use the gradlew script and execute ./gradlew test

yavijava's People

Contributors

bigbeaule avatar hubertverstraete avatar jaikiran avatar jessehu avatar johaw avatar kbrowder avatar lifemanship avatar ljader avatar manthinaa avatar michaelrice avatar sarumont avatar scottmlaplante avatar tressheets avatar willykan avatar ylvmw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yavijava's Issues

Performance degraded with yavijava 6.0.

Hi,

We manage dvSwitch by taking its configuration backup and deploying changes.
We do configuration backup by running lot of queries. With vijava the whole operation of backup was taking 6 seconds and when we change to yavijava 6.0.01 jar , the same operation took 9 minutes.
I will try to summarize what exactly we do to take configuration backup of DVSwitch.

DistributedVirtualSwitch dvSwitch = state.dvSwitch;
DVSConfigInfo dvsCfg = dvSwitch.getConfig();
int[] vlanIds = dvSwitch.queryUsedVlanIdInDvs();
ManagedObjectReference[] uplinks = dvsCfg.getUplinkPortgroup();
String description = dvsCfg.getDescription();
String ipAddress = dvsCfg.getSwitchIpAddress();
 dvsCfg.getNumPorts()
 + dvsCfg.getMaxPorts()
+ dvsCfg.getNumStandalonePorts()

The above given are some methods which we trigger to get confguration of dvSwitch. We trigger many more such methods to get complete information of all dvPort groups and all ports associated with port-groups.

So if I use yavijava 6.0.01 jar it works in dvSwitch but with degraded performance. When I try to run same operation on dvSwitch which is on vSphere 5.5 it takes 9 minutes as compared to 6 seconds in case of vijava.

Kindly suggest.

MorUtil seems to be missing a method

In the MorUtil there is a createMORs but not a createMOR createMOR is for some reason in the XmlGen class.

This should be corrected but due to the public nature of the exposed method in XmlGen it needs to be deprecated and switched to use the new code that will be added to MorUtil that way if anyone is using this outside of the project their code will not break and we give them time to make adjustments.

Error while adding VLAN to dvPortGroup.dvSwitch is on 5.5 and Vcenter is 6.0.

We are trying to first create a dvPortGroup and then reconfigure dvPortGroup to add VLAN to its settings. We are getting following error

DistributedVirtualPortgroup.reconfigureDVPortgroup_Task()
TaskInfo.getState() = error

"The configurations of the objects are in conflict"

If I go and see Vcenter I get some more detail error.

"Link Aggregation Control Protocol group configured on dvSwitch-Customer conflicts with the Link Aggregation Control Protocol API version multipleLag"

Following is the method we are running;

 private static void setDVSwitchPortgroupVlan(StateInformation state,
            String portgroupName, String vlanId) throws IOException {
        StringBuilder spying = state.spying;
        DistributedVirtualSwitch dvSwitch = state.dvSwitch;
        portgroupName = stripQuotes(portgroupName);

        // case-sensitive search for portgroup to be edited
        DistributedVirtualPortgroup pg
                = getDVSwitchPortgroup(portgroupName, state);
        if (pg == null) {
            spying.append(SYNTAX_ERROR
                    + "portgroup does not exist on this dvSwitch\n");
            return;
        }

        DVPortgroupConfigSpec spec = new DVPortgroupConfigSpec();
        DVPortSetting current =  dvSwitch.getConfig().getDefaultPortConfig();
        if (current == null || !(current instanceof VMwareDVSPortSetting)) {
            current = new VMwareDVSPortSetting();
        }
        spec.setDefaultPortConfig(current);

        VMwareDVSPortSetting setting = (VMwareDVSPortSetting) current;
        VmwareDistributedVirtualSwitchVlanIdSpec vlan
                = new VmwareDistributedVirtualSwitchVlanIdSpec();
        vlan.setInherited(false);
        vlan.setVlanId(Integer.parseInt(vlanId));
        setting.setVlan(vlan);
        DVPortgroupConfigInfo pgCfgInfo = null;
        try {
            pgCfgInfo = pg.getConfig();
        } catch (Exception e) {
            if (e instanceof InvalidProperty
                    || e.getCause() instanceof InvalidProperty) {
                LOGGER.log(Level.FINE, "error getting port group configuration", e);
            } else {
                throw new IOException(e);
            }
        }
        if (pgCfgInfo != null) {
            spec.setConfigVersion(pgCfgInfo.getConfigVersion());
        }

        log(spying, "DistributedVirtualPortgroup.reconfigureDVPortgroup_Task()");
        try {
            Task task = pg.reconfigureDVPortgroup_Task(spec);
            TaskInfo ti = waitFor(task);
            log(spying, "TaskInfo.getState() = " + ti.getState());
            if (ti.getState() == TaskInfoState.error) {
                spying.append(SYNTAX_ERROR
                        + ti.getError().getLocalizedMessage() + "\n");
            }
        } catch (RuntimeFault e) {
            throw new IOException("error updating portgroup: "
                    + ImportedUtility.getClassBaseName(e.getClass()), e);
        } catch (Exception e) {
            throw new IOException("unexpected error updating portgroup: "
                    + ImportedUtility.getMessage(e), e);
        }
    }

Exception in vim25.ws.XmlGenDom.fromXml while querying performance metrics

Hi! Today I've faced issue with sample GetMultiPerf:
start:Sun Nov 08 10:43:39 YEKT 2015
end:Mon Nov 09 10:43:39 YEKT 2015
Exception in thread "main" com.vmware.vim25.InvalidArgument
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at com.vmware.vim25.ws.XmlGenDom.fromXml(XmlGenDom.java:194)
    at com.vmware.vim25.ws.XmlGenDom.parseSoapFault(XmlGenDom.java:135)
    at com.vmware.vim25.ws.XmlGenDom.fromXML(XmlGenDom.java:94)
    at com.vmware.vim25.ws.SoapClient.unMarshall(SoapClient.java:203)
    at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:95)
    at com.vmware.vim25.ws.VimStub.queryPerfComposite(VimStub.java:1448)
    at com.vmware.vim25.mo.PerformanceManager.queryPerfComposite(PerformanceManager.java:93)
    at ru.sbertech.dk.uats.osa.vmwaretest.GetMultiPerf.main(GetMultiPerf.java:80)

Java version is: 1.8.0u60
vSphere is: 5.5 u2
yavijava is: 5.5.11
Any help would be greatly appreciated.

Need for the vim25 library to be serializable

This feature request: http://sourceforge.net/p/vijava/feature-requests/27/

It would be nice if the library can be made serializable. This allows us to take a snapshot at a customers site and bring the snapshot back to the office to analyze / debug any of our code that not behaving. The vim25 library distributed by VMware is serializable. If there is a performance issue related to this, it would be nice if there were two versions of the library.

Its simple enough to implement this so does anyone care or have feelings one way or another if this is done or not?

Reuse SSLSocketFactory

http://sourceforge.net/p/vijava/feature-requests/24/

This part of the code has been refactored since this was reported but I dont think its really been fixed. I think its just called another way now.

WCClient uses a new instance of SSLSocketFactory every time it connects to VC. As a result, sockets cannot be reused. There is also a small performance issue that trustAllHttpsCertificates() is executed upon each connection when it actually needs to be executed only once per the lifetime of the application.
Suggested code changes:

private static volatile boolean initialized = false; // new code
private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    if (initialized) {return; }// new code
    initialized = true; // new code
    TrustManager[] trustAllCerts = new TrustManager[1]; 
    trustAllCerts[0] = new TrustAllManager(); 
    SSLContext sc = SSLContext.getInstance("SSL"); 
    sc.init(null, trustAllCerts, null); 
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

java.lang.NoSuchFieldException: protocolEndpoint

When trying retrievepropertiesEx, for collecting HostSystem and VirtualMachines, am seeing the below issue,
com.vmware.vim25.ws.WSClient Exception caught while invoking method: RetrievePropertiesEx java.rmi.RemoteException: Exception in SoapClient.invoke:; nested exception is:
java.lang.NoSuchFieldException: protocolEndpoint
at com.vmware.vim25.ws.XmlGenDom.fromXML(Unknown Source)
at com.vmware.vim25.ws.SoapClient.unMarshall(Unknown Source)
at com.vmware.vim25.ws.WSClient.invoke(Unknown Source)
at com.vmware.vim25.ws.VimStub.retrievePropertiesEx(Unknown Source)
at com.vmware.vim25.mo.PropertyCollector.retrievePropertiesEx(Unknown Source)

import static org.junit.Assert.fail;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.List;

import org.junit.Test;

import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.RetrieveOptions;
import com.vmware.vim25.RetrieveResult;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.PropertyCollector;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.util.PropertyCollectorUtil;

public class vCenterCollectionTest {
    private static final String CLUSTER_COMPUTE_RESOURCE = "ClusterComputeResource";
    private static final String PASSWORD = "Vmware123!";
    private static final String USERNAME = "VSPHERE.LOCAL\\Administrator";
    private static final String CLUSTER_MOR = "domain-c39";
    private static final String VCENTER_SERVER = "vcjai6.int.fusionio.com";
    final String VCENTER_SERVER_URL = "https://" + VCENTER_SERVER + "/sdk";
    private static final String SUMMARY = "summary";
    private static final String NAME = "name";
    private static final String RUNTIME = "runtime";
    private static final String CONFIG = "config";
    private static final String VIRTUAL_MACHINE = "VirtualMachine";
    private static final String HOST_SYSTEM = "HostSystem";
    final String[][] inventoryTypeinfo = new String[][] {
        new String[] {
            HOST_SYSTEM, NAME, CONFIG, SUMMARY, RUNTIME,
        }, {
            VIRTUAL_MACHINE, NAME, CONFIG, RUNTIME,
        }
    };

    @Test
    public void collectClusterDetails() throws InvalidProperty, RuntimeFault, RemoteException, MalformedURLException {
        final ManagedObjectReference mor = new ManagedObjectReference();
        mor.setType(CLUSTER_COMPUTE_RESOURCE);
        mor.setVal(CLUSTER_MOR);
        try {
            ServiceInstance si = new ServiceInstance(new URL(VCENTER_SERVER_URL), USERNAME, PASSWORD, true);
            final RetrieveOptions options = new RetrieveOptions();
            options.setMaxObjects(100);
            PropertyCollector prop = si.getPropertyCollector();
            options.setMaxObjects(25);
            final PropertyFilterSpec spec = createInventoryPropertySpec(
                            new ManagedEntity(si.getServerConnection(), mor), inventoryTypeinfo);
            RetrieveResult result = prop.retrievePropertiesEx(new PropertyFilterSpec[] {
                spec
            }, options);
            assert (result != null);

        } catch (RemoteException e) {
            fail(" ExpectedException: " + e.getMessage());
        }
    }

    public PropertyFilterSpec createInventoryPropertySpec(ManagedEntity parentEntity, String[][] typeinfo) {
        return createPropertySpec(parentEntity, typeinfo, getSelectionSpec());
    }

    public static PropertyFilterSpec createPropertySpec(List<ManagedEntity> parentEnties, String[][] typeinfo) {
        final PropertyFilterSpec spec = new PropertyFilterSpec();
        final PropertySpec[] propspecary = PropertyCollectorUtil.buildPropertySpecArray(typeinfo);
        spec.setPropSet(propspecary);
        for (final ManagedEntity parentEntity : parentEnties) {
            final ObjectSpec os = PropertyCollectorUtil.creatObjectSpec(parentEntity.getMOR(), Boolean.FALSE,
                            getSelectionSpec());
            ObjectSpec[] currentSpec = spec.getObjectSet();
            if (currentSpec == null) {
                currentSpec = new ObjectSpec[] {};
            }
            final ObjectSpec[] newSpec = new ObjectSpec[currentSpec.length + 1];
            for (int i = 0; i < currentSpec.length; i++) {
                newSpec[i] = currentSpec[i];
            }
            newSpec[currentSpec.length] = os;
            spec.setObjectSet(newSpec);
        }
        return spec;
    }

    public static PropertyFilterSpec createPropertySpec(ManagedEntity parentEntity, String[][] typeinfo,
                    SelectionSpec[] sSpecs) {
        final PropertySpec[] propspecary = PropertyCollectorUtil.buildPropertySpecArray(typeinfo);
        final ObjectSpec os = new ObjectSpec();
        os.setObj(parentEntity.getMOR());
        os.setSkip(Boolean.FALSE);
        if (sSpecs != null) {
            os.setSelectSet(sSpecs);
        }

        final PropertyFilterSpec spec = new PropertyFilterSpec();
        spec.setObjectSet(new ObjectSpec[] {
            os
        });
        spec.setPropSet(propspecary);
        return spec;
    }

    private static SelectionSpec[] getSelectionSpec() {
        // Recurse through the folders
        final TraversalSpec visitFolders = PropertyCollectorUtil.createTraversalSpec("visitFolders", "Folder",
                        "childEntity", new String[] {
                            "visitFolders", "dcToHf", "dcToVmf", "crToH", "crToRp", "HToVm", "rpToVm", "DsToH", "crToD"
                        });
        final TraversalSpec vAppToRp = PropertyCollectorUtil.createTraversalSpec("vAppToRp", "VirtualApp",
                        "resourcePool", new String[] {
                            "rpToRp", "vAppToRp"
                        });
        // Recurse through all ResourcePools
        final TraversalSpec rpToRp = PropertyCollectorUtil.createTraversalSpec("rpToRp", "ResourcePool",
                        "resourcePool", new String[] {
                            "rpToRp", "rpToVm"
                        });

        // Recurse through all ResourcePools
        final TraversalSpec rpToVm = PropertyCollectorUtil.createTraversalSpec("rpToVm", "ResourcePool", "vm",
                        new SelectionSpec[] {});

        // Traversal through ResourcePool branch
        final TraversalSpec crToRp = PropertyCollectorUtil.createTraversalSpec("crToRp", "ComputeResource",
                        "resourcePool", new String[] {
                            "rpToRp", "rpToVm"
                        });
        // Traversal through host branch
        final TraversalSpec crToH = PropertyCollectorUtil.createTraversalSpec("crToH", "ComputeResource", "host",
                        new SelectionSpec[] {});

        // Traversal through hostFolder branch
        final TraversalSpec dcToHf = PropertyCollectorUtil.createTraversalSpec("dcToHf", "Datacenter", "hostFolder",
                        new String[] {
                            "visitFolders"
                        });

        // Traversal through vmFolder branch
        final TraversalSpec dcToVmf = PropertyCollectorUtil.createTraversalSpec("dcToVmf", "Datacenter", "vmFolder",
                        new String[] {
                            "visitFolders"
                        });

        final TraversalSpec HToVm = PropertyCollectorUtil.createTraversalSpec("HToVm", "HostSystem", "vm",
                        new String[] {
                            "visitFolders"
                        });

        final TraversalSpec DsToH = PropertyCollectorUtil.createTraversalSpec("DsToH", "HostSystem", "datastore",
                        new String[] {
                            "visitFolders"
                        });
        // Traversal through computer resource branch
        final TraversalSpec crToD = PropertyCollectorUtil.createTraversalSpec("crToD", "ComputeResource", "datastore",
                        new SelectionSpec[] {});

        final SelectionSpec[] sSpecs = new SelectionSpec[11];
        sSpecs[0] = visitFolders;
        sSpecs[1] = vAppToRp;
        sSpecs[2] = crToH;
        sSpecs[3] = dcToHf;
        sSpecs[4] = dcToVmf;
        sSpecs[5] = rpToRp;
        sSpecs[6] = rpToVm;
        sSpecs[7] = crToRp;
        sSpecs[8] = HToVm;
        sSpecs[9] = DsToH;
        sSpecs[10] = crToD;
        return sSpecs;
    }
}

Maven repository

Hi,

Are any versions of this project available on a Maven repository? I can't find any on the central repo.

Many thanks,
Neil.

Add Relevant Messages to Faults

@michaelrice, it's been a huge bugbear of mine that VIJAVA always produced this kind of messaging when logging any of the Faults that occurred:

com.vmware.vim25.NoPermission: null

This is because (to my knowledge) all of the faults don't actually set a message (NoPermission as an example; message (neither in NoPermission itself, nor in any of its chain of inheritance) implement a standard message. Or, there's something about the library that I don't know about that would give a kind of standard message.

Do you think it would be possible (and a reasonable investment) to add relevant messages as a part of these Faults (Exceptions), so that application users aren't forced to explicitly identify and come up with a message for each individual Fault just to supply any of the relevant fields that the fault may contain, in a contextual message for application-feedback?

A couple advantages I see to doing this:

  1. The library will provide a standard message that can be forwarded / passed along more intuitively when passing these Faults into another Exception as a cause.
  2. This reduces the number of try / catch blocks necessary at the application level solely for the purposes of providing contextual information in Exception-handling (for example, simply catching Exception for any Faults or other Exceptions will no longer be a detriment when it comes to providing feedback about that Fault). catching any specific Fault would then be for more practical and relevant reasons, for example to alter a process flow based on a particular Fault.
  3. This can provide a better foundation for these Faults to be extended upon, if desired, in a more intuitive and complete way (most Java-developers would want to include a message, or have one included, I would imagine).
  4. It will reduce the level of redundancy and repeated code throughout applications, and the potential for handling these Faults poorly solely for the purposes of providing context around them to end-users and/or troubleshooters.

Looking at the code, I'm saying this with not much context as to how these Faults are generated, and it may have been that including a custom message for each Fault would have been something that fell outside the realm of code that could be easily and "factory" generated, considering the messages would have to be (likely) hand-tailored and maintained. So, I'm saying this as solely an idea-pitch without much insight as to how it might be implemented / maintained.

Thoughts?

Implement some GuestOperationHelpers

Implement some helpers that will implement GuestOperations that simplify downloading files, and running scripts in the guest os. This would be similar to the functionality in the doublecloud vmguest package. Ideally all methods from that package should be implemented with the same params and returns so people could migrate to the open source version in yavijava by only having to change namespace imports.

ManagedEntity Array is returning null

ServiceInstance si=getServiceInstance();
Folder rootFolder = si.getRootFolder();
ManagedEntity[] datastores = new InventoryNavigator( rootFolder ).searchManagedEntities("Datastore");

in case of yaviaja, datastore array is coming null. in6.0 vsphere environment
if i use vijava, datastore array is returning the list of data stores. in 5.5 vsphere environment

but code is not changed and it

new vsphere 6 managed objs have wrong getters and setters

After doing a code review I found that the getters and setters are done incorrectly for the new vsphere 6.0 managed objects I added. The properties need to be adjusted to use getCurrentProperty and friends from the ManagedObject class before they are merged into the gradle branch and released for consumption.

This relates to #29

Need help

Is there a way to get Mor to an object instead of getting it through the invetorybrowser object. Sorry don't know where to post questions for this and this project looked it's active

exception:org.dom4j.DocumentException: Error on line 1 of document : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.

Hi,

I am trying to get some ESX server info and getting this exception for some servers while logging in.

---------------Stack Trace----------------------
Failed with VI SDK invoke exception:-Org.d...
Failed with VI SDK invoke exception:org.dom4j.DocumentException: Error on line 1 of document : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.
java.rmi.RemoteException: VI SDK invoke exception:org.dom4j.DocumentException: Error on line 1 of document : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.
at com.vmware.vim25.ws.XmlGenDom.fromXML(XmlGenDom.java:76)
at com.vmware.vim25.ws.SoapClient.unMarshall(SoapClient.java:203)
at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:96)
at com.vmware.vim25.ws.VimStub.retrieveServiceContent(VimStub.java:1665)
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:85)

at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:69)

-----------Code Snippet------------------
String url = "abc"
String user = "xyz";
String password = "xyz";

ServiceInstance serviceInstance = new ServiceInstance(new URL(url), user, password,true);

VERSION :
yavijava - 5.5.10
dom4j - 1.6.1

All Exceptions casting to RemoteException.

All the exceptions getting while creating ServiceInstance are getting casted in to RemoteException. And those can't cast, ServiceInstance class is throwing ClassCassException instead of the original exception. And following is the stracktrace:
Caused by: java.lang.ClassCastException: java.net.UnknownHostException cannot be cast to java.rmi.RemoteException
at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:101)
at com.vmware.vim25.ws.VimStub.retrieveServiceContent(VimStub.java:1665)
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:85)
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:963)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:102)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:54)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:182)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:202)
at com.xxx.xxx.xxx.xxxx.getServiceInstance(ResourceCount.groovy:205)
... 58 more

Exception caught trying to invoke method RetrieveServiceContent : works with VI JAVA but NOT with YA VIJAVA

Hi YA VIJAVA users,

Today I deployed latest YA VIJAVA in my Maven project. My program renames the VM in the VC inventory.

When I run my program I get this error on VC 6.0

Exception in thread "main" java.rmi.RemoteException: Exception caught trying to invoke method RetrieveServiceContent; nested exception is:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address 10.x.x.x found
at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:92)
at com.vmware.vim25.ws.VimStub.retrieveServiceContent(VimStub.java:1667)
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:83)
at com.vmware.vim25.mo.ServiceInstance.(ServiceInstance.java:69)โ€‹

VC that I am using is added to the domain (static IP is used)

When I run the same program from my old VI JAVA libraries on same 60 VC, it works just fine. I tried YA VIJAVA on my other 60 VC (which is not added to the domain and takes DHCP IP) and YA VIJAVA worked there.

I would like to know why is this happening. Why it works with old VI JAVA and Why it does not with YA VIJAVA. ?

DocumentException: null Nested exception: null for "void" methods

I tried few void methods like HostStorageSystem#refreshStorageSystem() or HostStorageSystem#rescanAllHba(). They ends up with exception because unMarshall try to process null. I've tested with ESXi 5.5.0.

Exception in thread "main" java.rmi.RemoteException: VI SDK invoke exception:org.dom4j.DocumentException: null Nested exception: null
at com.vmware.vim25.ws.XmlGenDom.fromXML(XmlGenDom.java:76)
at com.vmware.vim25.ws.SoapClient.unMarshall(SoapClient.java:203)
at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:95)
at com.vmware.vim25.ws.VimStub.rescanAllHba(VimStub.java:3699)

service instance initialisation using session cookie returns null

public VSphereClient(String vCenterURL,
String sessionStr) throws RemoteException, MalformedURLException {
_logger.info("vCenterUrl adn Session Strings are" + vCenterURL
+ " " + sessionStr);
String session = "vmware_soap_session="" + sessionStr + """;
si = new ServiceInstance(new URL(vCenterURL), session, true);
}

si throws a null pointer exception.Please fix this

VMware vCloud Director support

Hi,
we are looking for a decent java library to consume the vcloud REST API, what is the current support in this project?

If needed, we can work on it.

Thanks!

java.lang.IllegalAccessException: Class com.vmware.vim25.ws.XmlGenDom can not access a member of class java.util.Calendar with modifiers "protected"

So I have a jetty webapp that tries to login to vsphere and it gets the following error:

java.rmi.RemoteException: Exception in SoapClient.invoke:; nested exception is:
java.lang.IllegalAccessException: Class com.vmware.vim25.ws.XmlGenDom can not access a member of class java.util.Calendar with modifiers "protected"

sorry no trace yet, I'll try and make one soon (or if I figure out the issue I'll file a MR). Anyways I'm using the latest version of yavijava deployed to central (although older versions seem to have this problem as well) and JDK 7 and JDK8. Again I'm running in jetty which i suppose could be the issue (somewhat more picky about accessing protected members?)

Exceptions are not received by the caller

Each API call may throw an exception that is defined in the vSphere API reference. But these exceptions are not received by the caller.
I have written a very simple code that tries to login to an ESXi/vCenter server with an unknown user. The expected result is to receive an InvalidLogin exception, but no exception is received.

Until vijava 5.1, I was receiving all exceptions as expected, but in vijava 5.5 beta I had noticed that one exception was received with another identity. I may have missed the fact that it happens for all exceptions since vijava 5.5 beta and therefore the problem may exist before the fork to yavijava. The difference in yavijava is that I don't receive an exception at all.

Environment on CentOS 7:
Oracle JDK 1.7.0_75
yavijava-5.5.07.jar
httpclient-4.3.5.jar
dom4j-1.6.1.jar
log4j-1.2.17.jar

VirtaulMachine.getConfig() is throwing RuntimeException

VirtaulMachine.getConfig() is throwing Runtime Exception.
Exception detail below:
java.lang.RuntimeException: java.rmi.RemoteException: Exception in SoapClient.invoke:; nested exception is:
java.lang.NoSuchFieldException: faultToleranceType

Unable to filter events with severity "error"

Hi friends,

Please see below code, in which i am trying to filter events with severity "error" but looks like it is not filtering and fetching all the events.Please let me know if i am doing something wrong. i am using vmware api and using python to fetch events. i tried in different versions of vsphere like 5.1 and 5.5 but in both case i am unable to filter events with error.

import atexit

from pyVim import connect
from pyVmomi import vmodl, vim
from datetime import datetime

import datetime

import pymongo

def main():

try:
    global si

    host = ["vcenterip"] 
    for vcenter in host:

        si = connect.SmartConnect(host=vcenter,user="Administrator",pwd="Fabxsve01",port=443)

        atexit.register(connect.Disconnect, si)
        content = si.RetrieveContent()
        #print "content...",content

        va = "Surya-2"
        virtualapp = getVirtualApp(va)


        em = si.content.eventManager
        efspec = vim.event.EventFilterSpec()
        #print "efspec...", efspec

        efspec.category = ["error"]
        print efspec

        efespec = vim.event.EventFilterSpec.ByEntity()
        #print "efespec....",efespec

        entity = getVirtualApp(va)

        print "entity..:", entity

        efespec = vim.event.EventFilterSpec.ByEntity(entity=entity)



        efespec.recursion = vim.event.EventFilterSpec.RecursionOption.all

        efspec.entity = efespec

        eftspec = vim.event.EventFilterSpec.ByTime()
        eftspec.beginTime = datetime(2015, 1, 22)
        eftspec.endTime = datetime(2015, 1, 24)

        efspec.time = eftspec
        ehc = em.CreateCollectorForEvents(efspec)
        ehc.SetCollectorPageSize(1000)
        events = ehc.latestPage
        #total = len(events)


        print "ehc.1st..",ehc
        if events is not None:
            total = len(events)
            print "total events..",total

            for i, e in enumerate(events):
                #if "Firmware" in e.fullFormattedMessage or "VPLEX/VE" in e.fullFormattedMessage:

                print "%d -> %s::%s" % (i, e.createdTime, e.fullFormattedMessage)

           ehc.ResetCollector()

        while(True):

            events = ehc.ReadPreviousEvents(1000)
            total = len(events)
            print "total events..",total
            if total == 0:
                break

            for i, e in enumerate(events):
                print "%d -> %s::%s" % (i, e.createdTime, e.fullFormattedMessage)

        if ehc is not None:
            ehc = ehc.DestroyCollector()

except vmodl.MethodFault as error:
    print "Caught vmodl fault : " + error.msg
    return -1

return 0

def getVirtualApp(name):
return getFromView(si.content.rootFolder, vim.VirtualApp, name)

def getFromView(root, type, name):
# Search for all Datastore Clusters aka StoragePod
obj_view = si.content.viewManager.CreateContainerView(root,
[type],
True)
obj_list = obj_view.view
obj_view.Destroy()

    for obj in obj_list:
        if obj.name == name:
            return obj
    raise "No object found"

if name == "main":
main()

Need help on "ServiceInstance" ignoreCert parameter.

I am not sure if this the right place to ask this question.

ServiceInstance si = new ServiceInstance(new URL(
"https://10.10.1.2./sdk"), "[email protected]",
"Administrator!23", true);

As you could see in above code, ServiceInstance constructor takes third parameter as "ignoreCert" and I have set it as "TRUE". Now I would like to make my code work when I set this up as "FALSE".

I have been trying but I could not get success. Can you please post one sample that can help to get this work?

Your help would be much appreciated.

Question: List all Datastore Clusters (StoragePod) available

How do I retrieve list of all Datastore Clusters which are attached to ALL hosts of a specific ESX cluster?

For instance, given an ESX Cluster Fooo (ClusterComputeResource), I want list all Datastore Clusters (StoragePod) that are connected to EVERY host in an ESX cluster.

My initial naive attempt was as follows:

            Map<String, ManagedEntity> storages = new LinkedHashMap<>();

            // Datastores Clusters
            ClusterComputeResource ccr = (ClusterComputeResource) cluster;
            Datastore[] datastores = ccr.getDatastores();
            for (Datastore datastore : datastores) {
                if (datastore.getParent() instanceof StoragePod) {
                    StoragePod storagePod = (StoragePod) datastore.getParent();
                    storages.put(storagePod.getName(), storagePod);
                }

            }

The problem with the above is that ClusterComputeResource.getDatastores() returns an aggregate of all datastores connected to the hosts in the cluster; but that doesn't necessarily mean that ALL hosts in the cluster have the datastore mounted.

Any ideas?

Commit "Refactor TrustAllSSL and WSClient to fix security" breaking connections using IP address

Since this change we're now seeing errors when connecting using IP address. Even after postCon.setSSLSocketFactory(...), I'm seeing postCon.hostnameVerifier set to javax.net.ssl.HttpsURLConnection$DefaultHostnameVerifier instead of the expected non-verifying version.
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address 127.0.0.1 found
I'll try to setup an integration test to reproduce, but wanted to give an early heads up.

TrustAllSSL.getTrustContext() not thread-safe

Hi Michael,

We discovered during product testing that opening connections to multiple vCenters very rapidly could cause a NPE on line 209 of WSClient.java. I haven't been able to reproduce it with a unit test, but adding a call to TrustAllSSL.getTrustContext() in a static initialization block prior to other usages of TrustAllSSL resolved the issue. From a quick code read, it appears possible to have 'alreadyCreated = true' prior to the sslContext being fully initialized.

Thanks!

vSphere 6.0: "Exception caught while invoking method: RetrieveProperties" when running "HelloVM.java"

Version: yavijava-6.0.01b3
Build on a mac with: java version "1.7.0_71"

I'm geting following exceptions when trying to run "HelloVM.java" (https://raw.githubusercontent.com/yavijava/yavijava-samples/gradle/src/main/java/samples/HelloVM.java) example against vSphere6.0. I was able to successfully run against vSphere5.5 so I'm assuming this may be related to vSphere version 6.0.

Following is the stack trace. Looks like it's coming while executing following line.

VirtualMachineConfigInfo vminfo = vm.getConfig();

Console output & Stack Trace:

time taken:1094
root:Datacenters
0 [main] DEBUG com.vmware.vim25.mo.InventoryNavigator  - API version >= 4 detected. Using buildFullTraversalV4.
153 [main] ERROR com.vmware.vim25.ws.WSClient  - Exception caught while invoking method: RetrieveProperties
java.rmi.RemoteException: Exception in SoapClient.invoke:; nested exception is: 
    java.lang.NumberFormatException: For input string: "IqB0ZkV6CyQoo2FX/1Z/zLlvqOI="
    at com.vmware.vim25.ws.XmlGenDom.fromXML(XmlGenDom.java:112)
    at com.vmware.vim25.ws.SoapClient.unMarshall(SoapClient.java:206)
    at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:95)
    at com.vmware.vim25.ws.VimStub.retrieveProperties(VimStub.java:98)
    at com.vmware.vim25.mo.PropertyCollector.retrieveProperties(PropertyCollector.java:98)
    at com.vmware.vim25.mo.ManagedObject.retrieveObjectProperties(ManagedObject.java:146)
    at com.vmware.vim25.mo.ManagedObject.getCurrentProperty(ManagedObject.java:170)
    at com.vmware.vim25.mo.VirtualMachine.getConfig(VirtualMachine.java:52)
    at vCenterOps.HelloVM.main(HelloVM.java:29)
Caused by: java.lang.NumberFormatException: For input string: "IqB0ZkV6CyQoo2FX/1Z/zLlvqOI="
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Byte.parseByte(Byte.java:148)
    at java.lang.Byte.parseByte(Byte.java:174)
    at org.doublecloud.ws.util.ReflectUtil.toByteArray(ReflectUtil.java:165)
    at org.doublecloud.ws.util.ReflectUtil.setObjectArrayField(ReflectUtil.java:146)
    at com.vmware.vim25.ws.XmlGenDom.fromXml(XmlGenDom.java:274)
    at com.vmware.vim25.ws.XmlGenDom.fromXml(XmlGenDom.java:304)
    at com.vmware.vim25.ws.XmlGenDom.fromXml(XmlGenDom.java:297)
    at com.vmware.vim25.ws.XmlGenDom.fromXML(XmlGenDom.java:179)
    at com.vmware.vim25.ws.XmlGenDom.fromXML(XmlGenDom.java:109)
    ... 8 more

Appreciate if you can give me any pointers on how to fix this issue.

Not Java 1.6. compatible but stated

On http://www.yavijava.com/ is stated, that the build performed via gradle is java 1.6 compatible:
"A JDK is required to build the jar, but gradle is not. The jar will be built with Java 1.6 compatibility."

However the class com/vmware/vim25/ws/VimStub.java is catching a ReflectiveOperationException in line 75, which is only available since Java 1.7:
http://docs.oracle.com/javase/7/docs/api/java/lang/ReflectiveOperationException.html

i am not sure if this is intended!

I would be glad if it is possible to continue with Java 1.6 support as i am forced to use it!

Result when building with jdk1.6.0_45:

image

CacheInstance() get method returns null since cache fails to populate due to depriciated method

This is the snippet of code I am using. If your wondering vm[0] is populated and this is a VCenter 6 setup.

ServiceInstance si = new ServiceInstance(new URL(host), user, passwd, true); //host, user, password, ssl off
    Folder rootFolder = si.getRootFolder();
    ManagedEntity[] vms = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");

    CacheInstance vicf = new CacheInstance(si);
    vicf.watch(vms, new String[] {"name", "runtime.powerState", "summary"});
    vicf.start();

    System.out.println(vicf.get(vms[0], "name"));

A Null Pointer Exception Occurs at the ManagedObjectWatcher line 118

4002 [MonitorThead for https://ottvc6-01/sdk/] ERROR com.vmware.vim.cf.ManagedObjectWatcher  - Generic Exception caught in run block of ManagedObjectWatcher.
java.lang.NullPointerException
    at com.vmware.vim25.mo.PropertyCollector.waitForUpdates(PropertyCollector.java:112)
    at com.vmware.vim.cf.ManagedObjectWatcher.run(ManagedObjectWatcher.java:118)
    at java.lang.Thread.run(Thread.java:785)

Line 118 happens to be a Deprecated. as of SDK4.1 therefore fails to populate

UpdateSet update = pc.waitForUpdates(version);

VirtaulMachine.getConfig() is throwing NumberFormatException

vSphere 6 SDK added a new filed called "vmxConfigChecksum" of type base64Binary in VirtualMachineConfigInfo data object. The code generator is converting this base64Binary to byte array but when we get this value in soap response, it is coming as a single value like string and not an array of values. The marshaling is trying to convert the whole base64Binary value to one byte and its throwing error.
We need to add fix to handle this base64Binary data type

When using Java 8 lots of javadoc problems

:javadoc
52 errors
100 warnings
:javadoc FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':javadoc'.

    Javadoc generation failed.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

IllegalAccessExceptions in XmlGen for transient fields

During a WS call, there are intermittent exceptions thrown within XmlGen when it tries to serialize the parameters for the WS call. On the occasions when exceptions are thrown, many occur.

They look similar to the following stacktrace:

2014-11-12 08:05:03,407 [main] ERROR com.vmware.vim25.ws.XmlGen  - IllegalAccessException caught.
java.lang.IllegalAccessException: Class com.vmware.vim25.ws.XmlGen can not access a member of class com.vmware.vim25.PropertyFilterSpec with modifiers "private static final transient"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:109)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253)
    at java.lang.reflect.Field.get(Field.java:376)
    at com.vmware.vim25.ws.XmlGen.toXML(XmlGen.java:169)
    at com.vmware.vim25.ws.XmlGen.toXML(XmlGen.java:112)
    at com.vmware.vim25.ws.XmlGen.toXML(XmlGen.java:76)
    at com.vmware.vim25.ws.XmlGen.toXML(XmlGen.java:58)
    at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:91)
    at com.vmware.vim25.ws.VimStub.retrieveProperties(VimStub.java:96)
    at com.vmware.vim25.mo.PropertyCollector.retrieveProperties(PropertyCollector.java:107)

I think I have a fix for this (not serializing transient fields), which I'm in the process of testing now. I'll create a pull-request when it's ready.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.