I am trying to add a new custom attribute to VM ware vSphere using VMware JAVA SDK but it is throwing "InvalidType" exception.
com.vmware.vim25.InvalidType
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.XmlGen.fromXml(XmlGen.java:205)
at com.vmware.vim25.ws.XmlGen.parseSoapFault(XmlGen.java:82)
at com.vmware.vim25.ws.WSClient.invoke(WSClient.java:134)
at com.vmware.vim25.ws.VimStub.addCustomFieldDef(VimStub.java:284)
at com.vmware.vim25.mo.CustomFieldsManager.addCustomFieldDef(CustomFieldsManager.java:57)
at vmwaretest.Connect.setSelectedVM(Connect.java:85)
at vmwaretest.Connect.main(Connect.java:29)
Code
ServiceInstance si = null;
try {
si = Initialisation(url, user, password);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
ServerConnection serverConnection = si.getServerConnection();
ManagedObjectReference mor = si.getMOR();
CustomFieldsManager cfm = new CustomFieldsManager(serverConnection, mor);
try {
cfm.addCustomFieldDef("type", null, null, null);
} catch (DuplicateName e) {
e.printStackTrace();
} catch (InvalidPrivilege e) {
e.printStackTrace();
} catch (RuntimeFault e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
Connection to the vSphere is working fine as I am able to retrieve or change the already existing Custom attributes but not able to create a new one.
What is wrong with the above code? Or is there any other way to add new custom attribute using vmware Java SDK.
CustomFieldsManager doc https://pubs.vmware.com/vsphere-6-5/index.jsp?topic=%2Fcom.vmware.wssdk.pg.doc%2FPG_Appx_Privileges_Reference.23.2.html
Below is Tag class which I have defined. Custom Attributes' key is global to all VMware resource and only value changes per resource.
So, if you are adding new custom attribute key to a VM or a host then you need to add key globally and then change the value of that key for that very specific resource.
Below is working java example.
public class Tag{
String key;
String value;
}
public void addTags(ServiceInstance serviceInstance, VirtualMachine virtualMachine, List<Tag> tags) throws CloudServiceException, CloudParameterException{
if(EmptyUtil.isNotEmpty(tags)){
CustomFieldsManager customFieldsManager = serviceInstance.getCustomFieldsManager();
CloudValidate.resourceNotNull(customFieldsManager, "Custom Fields cannot be set for VM as CustomFieldsManager instance could not be obtained.");
CustomFieldDef[] customFieldDefs = customFieldsManager.getField();
Set<String> existingTags = getExistingTags(customFieldDefs);
for(Tag tag : tags){
if(!existingTags.contains(tag.getKey())){
updateTagsKey(customFieldsManager, tag.getKey());
}
updateTagsValue(virtualMachine, tag);
}
}
}
private void updateTagsKey(CustomFieldsManager customFieldsManager, String key){
try {
customFieldsManager.addCustomFieldDef(key, Constants.VMWARE_CUSTOMATTRIBUTE_TYPE_VM, null, null);
}catch (DuplicateName dname){
logger.warn("Custom attribute : {} already exists.", key);
}catch(Exception exception) {
logger.warn("Failed to add custom field due to : {}.", exception.getMessage());
}
}
private void updateTagsValue(VirtualMachine virtualMachine, Tag tag){
try{
logger.info("Adding {} for Virtua Machine {}", tag.toString(), virtualMachine.getName());
virtualMachine.setCustomValue(tag.getKey(), tag.getValue());
}catch(Exception exception) {
logger.warn("Failed to set custom attribute on VM due to : {}.", exception.getMessage());
}
}
private Set<String> getExistingTags(CustomFieldDef[] customFieldDefs){
Set<String> existingTags = new HashSet<>();
if(EmptyUtil.isNotEmpty(customFieldDefs)){
for(CustomFieldDef customFieldDef : customFieldDefs){
existingTags.add(customFieldDef.getName());
}
logger.debug("Existing Custom Fields from Custom Fields Manager : {}", Arrays.toString(existingTags.toArray()));
}
return existingTags;
}
Related
I tried this in my controller class:
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
games = (List<?>) fr.readFile();
#SuppressWarnings("unchecked")
List<GameImpl> games2 = (List<GameImpl>) games;
} catch (IOException e) {
System.out.println("err");
throw new RuntimeException(e);
}
but when I try to access games2 function, an Exception occurred
I'm facing an issue where I'm trying to write a more smart console app with logging and configuration available.
This is what I have so far:
namespace Client
{
public class Program
{
public static IConfigurationRoot Configuration;
private static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.CreateLogger();
try
{
MainAsync(args).ConfigureAwait(false);
return 0;
}
catch
{
return 1;
}
}
private static async Task MainAsync(string[] args)
{
// Create service collection
Log.Information("Creating service collection");
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Create service provider
Log.Information("Building service provider");
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
try
{
Log.Information("Starting service");
await serviceProvider.GetService<App>().Run();
Log.Information("Ending service");
}
catch (Exception ex)
{
Log.Fatal(ex, "Error running service");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureServices(IServiceCollection services)
{
// Add logging
services.AddSingleton(
LoggerFactory.Create(
builder => { builder.AddSerilog(dispose: true); }));
services.AddLogging();
// Build configuration
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appSettings.json", false)
.Build();
// Add access to generic IConfigurationRoot
services.AddSingleton(Configuration);
// Add app
services.AddTransient<App>();
}
}
}
I'm facing an issue in ConfigureServices method on line builder.AddSerilog for the life of me, I cannot figure out why it is not able to resolve AddSerilog
I was missing a package: Serilog.Extensions.Logging
For some reason, VS or even Resharper was not able to suggest this.
I am using Jersey REST Webservices for my Application which is like a type of blog website ( means no user registration or authentication are required)
I have some webservices which queries the database and sends the data to the Front End .
As you know the user can see the webservice calls in browser network tab and fire the query manually
My question is , how can i protect sever / Service from being hit continously (for loop written manually to break the application)
This is how my service looks like
#GET
#Produces("text/plain")
public String displaylatestnews() {
String latestnews = "";
PreparedStatement selectpstmt = null;
ResultSet selectRset = null;
Connection conn = null;
String selectsql = "SELECT rssjson from rssfeeds limit 1";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
selectpstmt = conn.prepareStatement(selectsql);
selectRset = selectpstmt.executeQuery();
if (selectRset.next()) {
latestnews = selectRset.getString("rssjson");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
selectRset.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
selectpstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return "jsonCallback(" + latestnews.toString() + ")";
}
You can start avoiding creating a connection to mysql every time there's a request, secondly you can add some sort of caching to start with. Even a cache that only lasts few seconds can save tons of db accesses.
I'm implement Google Glass app.
I want to get contacts list from google glass using GDK.
I already tried contacts Api v3 (ContactsService)
but i failed because -
i can't scrolling & tapping(click) pop-up (OK Button) after glass update XE16
-> run to android phone is ok.
i tried
mirror api. device OAuth.... -> no example.. i don't know how...
if you have sample code, As it is also upload. Would you? I'd appreciate that.
here is my code.
public class MainActivity extends Activity
{
private Account[] accounts;
private AccountManager mManager;
private ContactsService mService;
private URL feedUrl;
private final String url = "https://www.google.com/m8/feeds/contacts/default/full";
private final String ACCOUNTS_TYPE = "com.google";
private final String AUTH_TOKEN_TYPE = "cp";
private String mToken;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mManager = AccountManager.get(this);
accounts = mManager.getAccountsByType(ACCOUNTS_TYPE);
Log.d("account", ""+accounts[0]);
mManager.getAuthToken(accounts[0], AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>()
{
public void run(AccountManagerFuture<Bundle> future)
{
try
{
mToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
GetTask task = new GetTask();
task.execute(mToken);
}
catch (OperationCanceledException e)
{
e.printStackTrace();
}
catch (AuthenticatorException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}, null);
}
public void createService(String token) throws IOException, ServiceException
{
mService = new ContactsService("contacts_list");
mService.setUserToken(token);
feedUrl = new URL(url);
ContactFeed resultFeed = (ContactFeed)mService.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) getContacts(entry);
}
private class GetTask extends AsyncTask<String, Void, Void>
{
#Override
protected Void doInBackground(String... params)
{
try
{
String token = "";
if(params != null)
{
for(String s : params) token += s;
}
createService(token);
}
catch (ServiceException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
public void getContacts(ContactEntry entry) throws ServiceException, IOException
{
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullName = name.getFullName().getValue();
Log.d("name", fullName);
}
}
else Log.d("name", "no name");
if (entry.hasPhoneNumbers())
{
for (PhoneNumber phone : entry.getPhoneNumbers())
{
String phoneNum = phone.getPhoneNumber();
Log.d("phone", phoneNum);
}
}
else Log.d("phone", "no phone");
}
}
I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!
There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";
Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code