How would I delete a subscribed item in Eclipse Milo 0.3.8? - opc-ua

I have looked at the examples for subscribing to a NodeId and im wondering how I could stop/delete a subscription afterward.
Eclipse Milo v0.3.8 Client.
Here's what I've tried.
protected boolean unsubscribe(TransactionDefinition transactionDefinition) {
// Finds the mathing TransactionDefinition from the map where all subscriptions
// are stored, together with the clientHandle.
// private Map<UInteger, TransactionDefinition> subscriptions = new HashMap<>();
try {
UInteger subscriptionClientHandle = null;
for (Map.Entry<UInteger, TransactionDefinition> entry : subscriptions.entrySet()) {
if (entry.getValue().equals(transactionDefinition))
subscriptionClientHandle = entry.getKey();
}
if (subscriptionClientHandle == null) return false;
try {
client.getSubscriptionManager().deleteSubscription(subscriptionClientHandle).get();
return true;
} catch (Exception e) {
log.error("Subscription not found: {}", e.getMessage(), e.getCause());
e.printStackTrace();
}
} catch (ClassCastException e) {
log.error("TransactionDefinition trigger not found. {}", e.getMessage(), e.getCause());
e.printStackTrace();
}
return false;
}

UaSubscription has a deleteMonitoredItems method on it.
UaSubscriptionManager has a deleteSubscription method on it.
You could also call either of these services "manually" by invoking the "raw" service methods on the UaClient instance.

Related

Does StreamingOutput in Jersey need to close?

I have a snippet to download a file from jersey 2.22,
StreamingOutput stream = (OutputStream os) -> {
try {
os.write( get a byte array here);
} catch (Exception e) {
LOGGER.error("Failed to fetch file, id:" + fileName, e);
throw new Exception());
}
};
the above code is working, but i'm wondering if the output stream I'm writing in needs to close.
I searched jersey's source code, in OutboundMessageContext
public void close() {
if(this.hasEntity()) {
try {
OutputStream e = this.getEntityStream();
e.flush();
e.close();
} catch (IOException var10) {
Logger.getLogger(OutboundMessageContext.class.getName()).log(Level.FINE, var10.getMessage(), var10);
} finally {
if(!this.committingOutputStream.isClosed()) {
try {
this.committingOutputStream.close();
} catch (IOException var9) {
Logger.getLogger(OutboundMessageContext.class.getName()).log(Level.FINE, var9.getMessage(), var9);
}
}
}
}
}
this method is to close entity stream. I'm not sure if this is the right close method working with StreamingOutput, can anyone help?

Propogate errors to UI with Spring 3 MVC / REST

When /api/upload REST endpoint is accessed I have a UploadController that uses a service UploadService to upload a file to an ftp server with org.apache.commons.net.ftp.FTPClient. I would like to be able to send information back to the user if the ftp client was unable to connect or timed out, or successfully sent the file. I have some IOException handling, but I don't know how to turn that around and send it back to the front-end. Any help appreciated, thanks!
public void upload(InputStream inputStream) {
String filename = "file.txt"
client = new FTPClient();
try {
client.connect("ftpsite");
client.login("username", "password");
client.storeFile(filename, inputStream);
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (inputStream!= null) {
inputStream.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return null;
}
You should throw a new Exception in your catch statement.
For example, you could create a RequestTimeoutException class:
#ResponseStatus(HttpStatus.REQUEST_TIMEOUT)
public class RequestTimeoutException extends RuntimeException { }
and then throw it when need be:
catch (IOException ioe) {
//do some logging while you're at it
throw new RequestTimeoutException();
}

Android Webview set proxy programmatically Kitkat

How can we set proxy in Android webview programmatically on latest Kitkat release?
This SO link WebView android proxy talks about version upto SDK version 18. But those solution no more works with Kitkat as underlying webkit implementation is changed and it uses chromium now.
Here is my solution:
public static void setKitKatWebViewProxy(Context appContext, String host, int port) {
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port + "");
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port + "");
try {
Class applictionCls = Class.forName("android.app.Application");
Field loadedApkField = applictionCls.getDeclaredField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
/*********** optional, may be need in future *************/
final String CLASS_NAME = "android.net.ProxyProperties";
Class cls = Class.forName(CLASS_NAME);
Constructor constructor = cls.getConstructor(String.class, Integer.TYPE, String.class);
constructor.setAccessible(true);
Object proxyProperties = constructor.newInstance(host, port, null);
intent.putExtra("proxy", (Parcelable) proxyProperties);
/*********** optional, may be need in future *************/
onReceiveMethod.invoke(rec, appContext, intent);
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
I hope it can help you.
Note: The Context parameter should be an Application context as the parameter name showed, you could use your own implemented Application instance which extend Application.
I've made some changes to #xjy2061's answer.
Changes are:
getDeclaredField to getField --> You use this if you declared your own application class. Else it won't find it.
Also, remember to change "com.your.application" to your own application's class canonical name.
private static boolean setKitKatWebViewProxy(WebView webView, String host, int port) {
Context appContext = webView.getContext().getApplicationContext();
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", port + "");
System.setProperty("https.proxyHost", host);
System.setProperty("https.proxyPort", port + "");
try {
Class applictionCls = Class.forName("acr.browser.barebones.Jerky");
Field loadedApkField = applictionCls.getField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
/*********** optional, may be need in future *************/
final String CLASS_NAME = "android.net.ProxyProperties";
Class cls = Class.forName(CLASS_NAME);
Constructor constructor = cls.getConstructor(String.class, Integer.TYPE, String.class);
constructor.setAccessible(true);
Object proxyProperties = constructor.newInstance(host, port, null);
intent.putExtra("proxy", (Parcelable) proxyProperties);
/*********** optional, may be need in future *************/
onReceiveMethod.invoke(rec, appContext, intent);
}
}
}
return true;
} catch (ClassNotFoundException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (NoSuchFieldException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (IllegalAccessException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (IllegalArgumentException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (NoSuchMethodException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (InvocationTargetException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
} catch (InstantiationException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Log.v(LOG_TAG, e.getMessage());
Log.v(LOG_TAG, exceptionAsString);
}
return false;
}
I am creating a cordova android application, and couldn't figure out why ajax requests to internal hosts on my company's network were failing on KitKat. All native web requests succeeded, and all ajax requests on android versions below 4.4 succeeded aswell. The ajax requests only failed when on the internal company wifi which was even more perplexing.
Turns out KitKat uses a new chrome webview which is different from the standard webviews used in previous android versions. There is a bug in the version of chromium that kitkat uses where it doesn't respect the proxy exclusion list. Our company wifi sets a proxy server, and and excludes all internal hosts. The ajax requests were ultimately failing because authentication to the proxy was failing. Since these requests are to internal hosts, it should have never been going through the proxy to begin with. I was able to adapt xjy2061's answer to fit my usecase.
Hopefully this helps someone in the future and saves them a few days of head banging.
//Set KitKat proxy w/ proxy exclusion.
#TargetApi(Build.VERSION_CODES.KITKAT)
public static void setKitKatWebViewProxy(Context appContext, String host, int port, String exclusionList) {
Properties properties = System.getProperties();
properties.setProperty("http.proxyHost", host);
properties.setProperty("http.proxyPort", port + "");
properties.setProperty("https.proxyHost", host);
properties.setProperty("https.proxyPort", port + "");
properties.setProperty("http.nonProxyHosts", exclusionList);
properties.setProperty("https.nonProxyHosts", exclusionList);
try {
Class applictionCls = Class.forName("android.app.Application");
Field loadedApkField = applictionCls.getDeclaredField("mLoadedApk");
loadedApkField.setAccessible(true);
Object loadedApk = loadedApkField.get(appContext);
Class loadedApkCls = Class.forName("android.app.LoadedApk");
Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
receiversField.setAccessible(true);
ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
for (Object receiverMap : receivers.values()) {
for (Object rec : ((ArrayMap) receiverMap).keySet()) {
Class clazz = rec.getClass();
if (clazz.getName().contains("ProxyChangeListener")) {
Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
/*********** optional, may be need in future *************/
final String CLASS_NAME = "android.net.ProxyProperties";
Class cls = Class.forName(CLASS_NAME);
Constructor constructor = cls.getConstructor(String.class, Integer.TYPE, String.class);
constructor.setAccessible(true);
Object proxyProperties = constructor.newInstance(host, port, exclusionList);
intent.putExtra("proxy", (Parcelable) proxyProperties);
/*********** optional, may be need in future *************/
onReceiveMethod.invoke(rec, appContext, intent);
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
You would call the method above as follows:
First import this library at the top of your file.
import android.util.ArrayMap;
Then call the method
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
//check first to see if we are running KitKat
if (currentapiVersion >= Build.VERSION_CODES.KITKAT){
setKitKatWebViewProxy(context, proxy, port, exclusionList);
}
https://android.googlesource.com/platform/external/chromium/+/android-4.4_r1/net/proxy/proxy_config_service_android.cc
Has methods to set the proxy. I am still trying to figure out how to invoke this from Java code. Pointers?
https://codereview.chromium.org/26763005
Guess from this patch, you'll be able to set up a proxy again in the near future, perhaps.
Had some issues with the provided solution on some devices when loading page from onCreate right away after setting the proxy configuration. Opening the web page after some small delay solved the problem. Seems like the proxy config needs some time to get effective.

CRM 2011 Plugin won't update and get emails from ActivityParty

I'm trying to get all emails (to, from, cc) from an email in a list and go through the list and check the contacts, if the Contact exists in CRM then a field on the email entity will be marked as true. When I check the to, from, and cc fields of the email it returns 0 parties, but there is no error there. Also at the end, when I'm calling service.Update(entity), it returns an error. An unexpected error occurred.
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider
.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider
.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory
.CreateOrganizationService(context.UserId);
try
{
Email entity;
if (context.MessageName == "Create")
{
if (context.PostEntityImages.Contains("PostImage")
&& context.PostEntityImages["PostImage"] is Entity)
entity = (Email)context.PostEntityImages["PostImage"].ToEntity<Email>();
else
throw new Exception("No PostEntityImages...");
}
else
throw new Exception("EmailPortalVisibilityPlugin Plugin invalid");
if(entity.LogicalName != "email")
throw new Exception("EmailPortalVisibilityPlugin invalid");
bool contactExists = false;
List<string> emails = new List<string>();
emails.AddRange(ParseAddressUsed(entity.To, trace));
emails.AddRange(ParseAddressUsed(entity.From, trace));
emails.AddRange(ParseAddressUsed(entity.Cc, trace));
foreach (String em in emails)
{
contactExists = LookupContact(em, service, trace);
if (contactExists)
break;
}
UpdateToggleState(entity, contactExists, service, trace);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Execute '" + ex.Message + "'");
}
}
public List<string> ParseAddressUsed(
IEnumerable<ActivityParty> entity, ITracingService trace)
{
try
{
List<string> addressStrings = new List<string>();
foreach (ActivityParty party in entity)
addressStrings.Add(party.PartyId.Id.ToString());
return addressStrings;
}
catch (FaultException<OrganizationServiceFault> exceptionServiceCall)
{
throw new Exception("ParseAddressUsed FaultException");
}
catch (Exception ex)
{
throw new Exception("ParseAddressUsed Exception");
}
}
public bool LookupContact(
String emailAddress, IOrganizationService service, ITracingService trace)
{
try
{
QueryByAttribute queryByAttribute = new QueryByAttribute("contact");
queryByAttribute.ColumnSet = new ColumnSet("contactId");
queryByAttribute.Attributes.Add("emailaddress1");
queryByAttribute.Values.Add(emailAddress);
EntityCollection retrieved = service.RetrieveMultiple(queryByAttribute);
return (retrieved.Entities.Count > 0);
}
catch (FaultException<OrganizationServiceFault> exceptionServiceCall)
{
throw new Exception("LookupContact Exception");
}
catch (Exception ex)
{
throw new Exception("LookupContact Exception");
}
}
public void UpdateToggleState(
Email entity, bool toggleState, IOrganizationService service, ITracingService trace)
{
try
{
Entity email = new Entity("email");
email.Id = entity.Id;
email.Attributes.Add("new_clientfacing", toggleState);
service.Update(email);
}
catch (FaultException<OrganizationServiceFault> exceptionServiceCall)
{
throw new Exception("UpdateToggleState Exception");
}
catch (Exception ex)
{
throw new Exception("UpdateToggleState Exception");
}
}
Try to set the first argument type of function ParseAddressUsed to EntityCollection instead of IEnumerable<ActivityParty>, and do the necessary changes.
And for the final update in function UpdateToggleState, there is no need to create a new email Entity (Entity email = new Entity("email");), when you already have the entity variable. You could just set the new_clientfacing attribute and update the entity, which is already retrieved.
In your method ParseAddressUsed you are adding the PartyId GUID to the string list and you use it in LookupContact in the emailaddress1 filter as a parameters, that is probably the reason why you are not retrieving any records.
Please try to change addressStrings.Add(party.PartyId.Id.ToString()) to addressStrings.Add(party.AddressUsed) instead and see if that works.
Cheers, dimamura

Using java nio in java ee

I want to use java nio in java ee.
But I don't know how to do it right.
I need to after server has deploy java.nio.selector always listens the port and processing socket connection.
I try do it there:
#Singleton
#Lock(LockType.READ)
public class TaskManager {
private static final int LISTENINGPORT;
static {
LISTENINGPORT = ConfigurationSettings.getConfigureSettings().getListeningPort();
}
private ArrayList<ServerCalculationInfo> serverList;
public TaskManager() {
serverList = new ArrayList<ServerCalculationInfo>();
select();
}
#Asynchronous
public void select() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
Selector selector = Selector.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(LISTENINGPORT));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
try {
selector.select();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
break;
}
Iterator it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey selKey = (SelectionKey) it.next();
it.remove();
try {
processSelectionKey(serverSocketChannel, selKey);
} catch (IOException e) {
serverList.remove(serverCalculationInfo);
}
}
}
} catch (IOException e) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
} catch (Exception e) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
}
}
}
It don't work correctly. The process hangs during deploy and redeploy application possible only after restart Glassfish.
How can I do right it?
It works correctly if invoke #Asynchronous method from the #PostConstructor:
#PostConstruct
public void postTaskManager() {
serverList = new ArrayList<ServerCalculationInfo>();
select();
}
instead of invoke it from constructor.
But class must be without #Startup annotation.