Hazelcast failed to create an ObjectName when using file|http(s) protocol - hazelcast

after running on this exception using hazelcast 3.6 :
java.lang.IllegalArgumentException: Failed to create an ObjectName
at
com.hazelcast.jmx.HazelcastMBean.setObjectName(HazelcastMBean.java:116)
at
com.hazelcast.jmx.ConnectionManagerMBean.(ConnectionManagerMBean.java:39)
at
com.hazelcast.jmx.InstanceMBean.createMBeans(InstanceMBean.java:74)
at com.hazelcast.jmx.InstanceMBean.(InstanceMBean.java:67) at
com.hazelcast.jmx.ManagementService.(ManagementService.java:67)
at
com.hazelcast.instance.HazelcastInstanceImpl.(HazelcastInstanceImpl.java:136)
at
com.hazelcast.instance.HazelcastInstanceFactory.constructHazelcastInstance(HazelcastInstanceFactory.java:160)
at
com.hazelcast.instance.HazelcastInstanceFactory.getOrCreateHazelcastInstance(HazelcastInstanceFactory.java:98)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.getOrCreateInstance(HazelcastServerCachingProvider.java:98)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.createHazelcastCacheManager(HazelcastServerCachingProvider.java:64)
at
com.hazelcast.cache.impl.HazelcastServerCachingProvider.createHazelcastCacheManager(HazelcastServerCachingProvider.java:42)
at
com.hazelcast.cache.impl.AbstractHazelcastCachingProvider.getCacheManager(AbstractHazelcastCachingProvider.java:94)
at
com.hazelcast.cache.HazelcastCachingProvider.getCacheManager(HazelcastCachingProvider.java:131)
I took look at this part of the code, which is causing the error, on File: HazelcastServerCachingProvider.java (starting at line: 78 ):
String location = properties.getProperty(HazelcastCachingProvider.HAZELCAST_CONFIG_LOCATION);
// If config location is specified, get instance through it.
if (location != null) {
URI uri = new URI(location);
String scheme = uri.getScheme();
if (scheme == null) {
// It is a place holder
uri = new URI(System.getProperty(uri.getRawSchemeSpecificPart()));
}
ClassLoader theClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader;
final URL configURL;
if ("classpath".equals(scheme)) {
configURL = theClassLoader.getResource(uri.getRawSchemeSpecificPart());
} else if ("file".equals(scheme) || "http".equals(scheme) || "https".equals(scheme)) {
configURL = uri.toURL();
} else {
throw new URISyntaxException(location, "Unsupported protocol in configuration location URL");
}
try {
Config config = new XmlConfigBuilder(configURL).build();
config.setClassLoader(theClassLoader);
**HERE BAD INSTANCENAME IS GENERATED**
config.setInstanceName(configURL.toString());
return HazelcastInstanceFactory.getOrCreateHazelcastInstance(config);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
When using file or http(s) protocol in the passed hazelcast_config_location, we are going to fail creating the mbean, since the hazelCastInstanceName should not contain the character ‘:’, which is unfortunately part of the configURI name.
Is this a Bug or do I overlooked something??
Thanks for your response

javax ObjectName class does not support the character : and throws a MalformedObjectNameException. Hazelcast processes this exception and throws IllegalArgumentException with the message comes from it.
https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/internal/jmx/HazelcastMBean.java#L121
https://docs.oracle.com/javase/7/docs/api/javax/management/ObjectName.html
Edit: quote function should've handled it in your case however, there is a bug in hz apparently. See: https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/internal/jmx/ConnectionManagerMBean.java#L38

Related

Microsoft.Azure.Mobile Client - Handling Server Error using custom IMobileServiceSyncHandler - Xamarin Forms

I have implemented the Azure - Offline Sync based on the documentation / Sample provided by Microsoft Sample in my Xamarin Forms Application.
In the sample / documentation provided, they are using the default Service Handler.
// Simple error/conflict handling. A real application would handle the various errors like network conditions,server conflicts and others via the IMobileServiceSyncHandler.
Since I need to implement a retry logic for 3 times if the Pull / Push fails. As per the documentation I have created a custom Service Handler(IMobileServiceSyncHandler).
Please find my code logic here.
public class CustomSyncHandler : IMobileServiceSyncHandler
{
public async Task<JObject> ExecuteTableOperationAsync(IMobileServiceTableOperation operation)
{
MobileServiceInvalidOperationException error = null;
Func<Task<JObject>> tryExecuteAsync = operation.ExecuteAsync;
int retryCount = 3;
for (int i = 0; i < retryCount; i++)
{
try
{
error = null;
var result = await tryExecuteAsync();
return result;
}
catch (MobileServiceConflictException e)
{
error = e;
}
catch (MobileServicePreconditionFailedException e)
{
error = e;
}
catch (MobileServiceInvalidOperationException e)
{
error = e;
}
catch (Exception e)
{
throw e;
}
if (error != null)
{
if(retryCount <=3) continue;
else
{
//Need to implement
//Update failed, reverting to server's copy.
}
}
}
return null;
}
public Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
{
return Task.FromResult(0);
}
}
But I am not sure how to handle / revert server copy in case all the 3 retry failed.
In the TODO sample they where reverting it based on the
MobileServicePushFailedException. But which is available when we implement IMobileServiceSyncHandler.
More over if we include custom IMobileServiceSyncHandler it wont execute the code after PushAsync / PullAsync. Even the try catch wont fire in case any exception.
try
{
await this.client.SyncContext.PushAsync();
await this.todoTable.PullAsync(
//The first parameter is a query name that is used internally by the client SDK to implement incremental sync.
//Use a different query name for each unique query in your program
"allTodoItems",
this.todoTable.CreateQuery());
}
catch (MobileServicePushFailedException exc)
{
if (exc.PushResult != null)
{
syncErrors = exc.PushResult.Errors;
}
}
// Simple error/conflict handling. A real application would handle the various errors like network conditions,
// server conflicts and others via the IMobileServiceSyncHandler.
if (syncErrors != null)
{
foreach (var error in syncErrors)
{
if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null)
{
//Update failed, reverting to server's copy.
await error.CancelAndUpdateItemAsync(error.Result);
}
else
{
// Discard local change.
await error.CancelAndDiscardItemAsync();
}
Debug.WriteLine(#"Error executing sync operation. Item: {0} ({1}). Operation discarded.", error.TableName, error.Item["id"]);
}
}
}
Note
In my application I am only trying to achieve retry for 3 time in case any server error. I am not looking for to resolve conflicts. Thant is the reason I haven't added the code for the same.
If someone came across similar issues and resolved it please help.
Stez.
You say you aren't trying to resolve conflicts, but you need to resolve them one way or another (without telling the user what's going on, perhaps) by accepting the server version of the object or updating the client operation. Otherwise it will just keep telling you about the same conflict each time it retries the operation.
You need to have a subclass of the Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncHandler class, which overrides OnPushCompleteAsync() in order to handle conflicts and other errors. Let's call the class SyncHandler:
public class SyncHandler : MobileServiceSyncHandler
{
public override async Task OnPushCompleteAsync(MobileServicePushCompletionResult result)
{
foreach (var error in result.Errors)
{
await ResolveConflictAsync(error);
}
await base.OnPushCompleteAsync(result);
}
private static async Task ResolveConflictAsync(MobileServiceTableOperationError error)
{
Debug.WriteLine($"Resolve Conflict for Item: {error.Item} vs serverItem: {error.Result}");
var serverItem = error.Result;
var localItem = error.Item;
if (Equals(serverItem, localItem))
{
// Items are the same, so ignore the conflict
await error.CancelAndUpdateItemAsync(serverItem);
}
else // check server item and local item or the error for criteria you care about
{
// Cancels the table operation and discards the local instance of the item.
await error.CancelAndDiscardItemAsync();
}
}
}
Include an instance of this SyncHandler() when you initialize your MobileServiceClient:
await MobileServiceClient.SyncContext.InitializeAsync(store, new SyncHandler()).ConfigureAwait(false);
Read up on the MobileServiceTableOperationError to see other conflicts you can handle as well as its methods to allow resolving them.
The exception carries with it a copy of the server version. In my implementation of IMobileServiceSyncHandler I therefore just return error.Value and this seems to work.
A more extensive example of this kind of logic can be found in this MSDN blog.
The same author has another example where he shows how you can resolve the conflict in favour of the server copy or the client copy, here.

How to solve the cross domain in HtmlUnit

Error:
六月 21, 2016 4:15:06 下午 com.gargoylesoftware.htmlunit.xml.XmlPage <init>
警告: Failed parsing XML document http://live3.win007.com/vbsxml/goalBf3.xml?r=0071466496906000: Content is not allowed in prolog.
六月 21, 2016 4:15:06 下午 com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine handleJavaScriptException
信息: Caught script exception
======= EXCEPTION START ========
EcmaError: lineNumber=[41] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[http://live3.win007.com/common2.js] message=[TypeError: Cannot read property "childNodes" from null (http://live3.win007.com/common2.js#41)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot read property "childNodes" from null (http://live3.win007.com/common2.js#41)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:865)
at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:628)
at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:513)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.execute(JavaScriptEngine.java:747)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:1032)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:395)
at com.gargoylesoftware.htmlunit.html.HtmlScript$3.execute(HtmlScript.java:276)
common2.js code:
function getOddsData() {
oddsHttp.open("get", "vbsxml/goalBf3.xml?r=007" + Date.parse(new Date()), false);
oddsHttp.setRequestHeader("User-Agent", "");
oddsHttp.send(null);
var root = oddsHttp.responseXML.documentElement.childNodes[0];
oddsHttp as XMLHttpRequest
I suspect that a cross domain problem leads to " Cannot read property "childNodes""
I want to modify the JS by the following methods
public WebResponse getResponse(WebRequest request) throws IOException {
if(request.getUrl().toExternalForm().contains("common2.js")){
....
}
}
How to fix it?
This is not a cross domain problem,the warning: Content is not allowed in prolog is the key
I solved the problem by the following code
new WebConnectionWrapper(wc) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if(request.getUrl().toExternalForm().contains("goalBf3.xml")){
System.out.println(response.getContentAsString("UTF-8"));
String content = response.getContentAsString("UTF-8");
if(null != content && !"".equals(content)){
if(content.indexOf("<") != -1 && content.lastIndexOf(">") != -1 && content.lastIndexOf(">") > content.indexOf("<"))
content = content.substring(content.indexOf("<"), content.lastIndexOf(">") + 1);
}
WebResponseData data = new WebResponseData(content.getBytes("UTF-8"),
response.getStatusCode(), response.getStatusMessage(), response.getResponseHeaders());
response = new WebResponse(data, request, response.getLoadTime());
}
return response;
}
}

Android 6 get path to downloaded file

I our app (Xamarin C#) we download files from a server. At the end of a succeful download we get the URI to the newly-downloaded file and from the URI we get the file path:
Android.Net.Uri uri = downloadManager.GetUriForDownloadedFile(entry.Value);
path = u.EncodedPath;
In Android 4.4.2 and in Android 5 the uri and path look like this:
uri="file:///storage/emulated/0/Download/2.zip"
path = u.EncodedPath ="/storage/emulated/0/Download/2.zip"
We then use path to process the file.
The problem is that in Android 6 (on a real Nexus phone) we get a completely different uri and path:
uri="content://downloads/my_downloads/2802"
path="/my_downloads/2802"
This breaks my code by throwing a FileNotFound exception. Note that the downloaded file exists and is in the Downloads folder.
How can I use the URI I get from Android 6 to get the proper file path so I can to the file and process it?
Thank you,
donescamillo#gmail.com
I didn't get your actual requirement but it looks like you want to process file content. If so it can be done by reading the file content by using file descriptor of downloaded file. Code snippet as
ParcelFileDescriptor parcelFd = null;
try {
parcelFd = mDownloadManager.openDownloadedFile(downloadId);
FileInputStream fileInputStream = new FileInputStream(parcelFd.getFileDescriptor());
} catch (FileNotFoundException e) {
Log.w(TAG, "Error in opening file: " + e.getMessage(), e);
} finally {
if(parcelFd != null) {
try {
parcelFd.close();
} catch (IOException e) {
}
}
}
But I am also looking to move or delete that file after processing.
May you an build your URI with the download folder :
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toURI();
It's work. #2016.6.24
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals( action)) {
DownloadManager downloadManager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = downloadManager.query(query);
if(c != null) {
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
String downloadFileUrl = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
startInstall(context, Uri.parse(downloadFileUrl));
}
}
c.close();
}
}
}
private boolean startInstall(Context context, Uri uri) {
if(!new File( uri.getPath()).exists()) {
System.out.println( " local file has been deleted! ");
return false;
}
Intent intent = new Intent();
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction( Intent.ACTION_VIEW);
intent.setDataAndType( uri, "application/vnd.android.package-archive");
context.startActivity( intent);
return true;
}

Not found exception When start the ManagementEventWatcher

Not Found Exception some times while starting the MaagementEventWatcher
My code sample is given below :
try
{
string scopePath = #"\\.\root\default";
ManagementScope managementScope = new ManagementScope(scopePath);
WqlEventQuery query =
new WqlEventQuery(
"SELECT * FROM RegistryKeyChangeEvent WHERE " + "Hive = 'HKEY_LOCAL_MACHINE'"
+ #"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'");
registryWatcher = new ManagementEventWatcher(managementScope, query);
registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated);
registryWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (registryWatcher != null)
{
registryWatcher.Stop();
}
}
Exception:
Not found
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementEventWatcher.Start()
at MTTS.LabX.RockLog.AppService.USBMonitor.AddRegistryWatcherHandler()]
Note : I checked in the registry,folder and files are found.
ManagementException "Not found" is thrown when there is not match in the WQL query. Maybe you have specified the wrong KeyPath or the KeyPath is no longer available.
Actually the problem was, In the laptops(pcs having the serial ports so COM1 port) when starting first time SERIALCOMM folder not created in the Registry because,
basically we plugged the device in the USB port or serial port the SERIALCOMM folder will create, in this case we are using WMI to get the connected comm ports from the registry.
in some laptops no USB ports and Serial Ports are connected So, the SERIALCOMM folder not created, In that time we are accessing this registry path we get the error.
so the Solution is,
try
{
string scopePath = #"\\.\root\default";
ManagementScope managementScope = new ManagementScope(scopePath);
string subkey = "HARDWARE\\DEVICEMAP\\SERIALCOMM";
using (RegistryKey prodx = Registry.LocalMachine)
{
prodx.CreateSubKey(subkey);
}
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM RegistryKeyChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE'" +
#"AND KeyPath = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'");
registryWatcher = new ManagementEventWatcher(managementScope, query);
registryWatcher.EventArrived += new EventArrivedEventHandler(SerialCommRegistryUpdated);
registryWatcher.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if (registryWatcher != null)
{
registryWatcher.Stop();
}
}

Non-unique ldap attribute name with Unboundit LDAP SDK

I am attempting to retrieve objects having several attributes with the name from netscape LDAP directory with LDAP SDK from Unboundit. The problem is that only one of the attributes are returned - I am guessing LDAP SDK relays heavily on unique attribute names, is there a way to configure it to also return non-distinct attributes as well?
#Test
public void testRetrievingUsingListener() throws LDAPException {
long currentTimeMillis = System.currentTimeMillis();
LDAPConnection connection = new LDAPConnection("xxx.xxx.xxx", 389,
"uid=xxx-websrv,ou=xxxx,dc=xxx,dc=no",
"xxxx");
SearchRequest searchRequest = new SearchRequest(
"ou=xxx,ou=xx,dc=xx,dc=xx",
SearchScope.SUB, "(uid=xxx)", SearchRequest.ALL_USER_ATTRIBUTES );
LDAPEntrySource entrySource = new LDAPEntrySource(connection,
searchRequest, true);
try {
while (true) {
try {
System.out.println("*******************************************");
Entry entry = entrySource.nextEntry();
if (entry == null) {
// There are no more entries to be read.
break;
} else {
Collection<Attribute> attributes = entry.getAttributes();
for (Attribute attr : attributes)
{
System.out.println (attr.getName() + " " + attr.getValue());
}
}
} catch (SearchResultReferenceEntrySourceException e) {
// The directory server returned a search result reference.
SearchResultReference searchReference = e
.getSearchReference();
} catch (EntrySourceException e) {
// Some kind of problem was encountered (e.g., the
// connection is no
// longer valid). See if we can continue reading entries.
if (!e.mayContinueReading()) {
break;
}
}
}
} finally {
entrySource.close();
}
System.out.println("Finished in " + (System.currentTimeMillis() - currentTimeMillis));
}
Non-unique LDAP attributes are considered multivalued and are reperesented as String array.
Use Attribute.getValues() instead of attribute.getValue.

Resources