implement vaadin shiro and openDJ (LDAP) - eclipse

I have made a login form with Vaadin 7 by this tutorial:
https://vaadin.com/wiki/-/wiki/Main/Creating%20a%20simple%20login%20view.
I have to verify users with my LDAP (openDJ) with shiro.
I have put this into my clickEvent method:
Factory<org.apache.shiro.mgt.SecurityManager> ldapFactory = new IniSecurityManagerFactory("classpath:active.ini");
org.apache.shiro.mgt.SecurityManager sManager = ldapFactory.getInstance();
SecurityUtils.setSecurityManager(sManager);
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
try {
currentUser.login(token);
} catch (UnknownAccountException ex) {
logger.info("Unknown user");
} catch (IncorrectCredentialsException ex) {
logger.info("Incorrect credentials");
} catch (LockedAccountException ex) {
logger.info("Account is Locked");
} catch (AuthenticationException ex) {
logger.info("Authentication Exception");
}
}
logger.info("User [" + currentUser.getPrincipal() +"] logged succesfully");
currentUser.logout();
I have a error on logger and I don't know if this can work?
I have a active.ini file, and it looks like this:
'ldapRealm = org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm
ldapRealm.url = C:\Users\User\OpenDJ'
I searched for a tutorial or example but there isn't one for vaadin shiro and ldap (openDJ).

Related

WSDL FaultExceptions not caught

I'm attempting to get FaultExceptions to hit for a WSDL service.
I have attempted the following:
Created a new .Net 7.0 project in Visual studio
Added the WSDL service reference for https://wsaimport.uni-login.dk/wsaimport-v7/ws?WSDL
Called the generated WSDL method hentDataAftalerAsync
Added below code to Program.cs
var binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None), Encoding.UTF8), new HttpsTransportBindingElement { MaxReceivedMessageSize = 104857600 });
var ws10Client = new ServiceReference2.WsaImportPortTypeClient(binding, new EndpointAddress("https://wsaimport.uni-login.dk/wsaimport-v7/ws"));
try
{
var res = await ws10Client.hentDataAftalerAsync(new Credentials() {
wsBrugerid = "randomusername",
wsPassword = "randompassword"
});
// this is reached if credentials are correct
foreach (var item in res.hentDataAftalerResponse1.ToList())
{
Console.WriteLine(item);
}
}
catch(FaultException<AuthentificationError> ex)
{
// Neven hit (I expect this exception on wrong credentials)
Console.WriteLine(ex.Message);
}
catch (FaultException ex)
{
// Never hit
Console.WriteLine(ex.Message);
}
catch (ProtocolException ex)
{
// this exception is hit (but no info about the actual soap fault)
}
catch (Exception ex)
{
// Never hit
Console.WriteLine(ex.Message);
}
I have tested the hentDataAftaler operation in SoapUI, and when the credentials are wrong it does generate a SOAP response with a Fault of authentificationError.
So my question is, why is it not working for me in C#?

Opening a Postgres Connection in Xamarin returns Error While Connecting

I am trying to connect my Android Application to Postgres but seems not to work.
The Exception Message is: Exception while Connecting
This is my Code Behind,
private void Login_Clicked(object sender, EventArgs e)
{
DBInterface<DBLogicInput, DBLogicResult> dbLoginLogic = new DBLoginLogic();
DBLogicInput userInput = new DBLogicInput();
DBLogicResult DBResult = new DBLogicResult();
LoginModel useCredentials = new LoginModel()
{
userName = txtUsername.Text,
passWord = txtPassword.Text
};
userInput[typeof(LoginModel).FullName] = useCredentials;
try
{
DBResult = dbLoginLogic.DoProcess(userInput);
bool userExisting = DBResult.ResultCode != DBLogicResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
if (userExisting)
{
Application.Current.MainPage = new NavigationPage(new IndexPage());
}
else
{
_ = DisplayAlert("Login Error", "User does not exist", "Ok");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This is the Class I created to connect the DB.
public abstract class DBLogic : DBInterface<DBLogicInput, DBLogicResult>
{
public string connectionString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=proyektoNijuan";
public DBLogicResult DoProcess(DBLogicInput inOut)
{
//throw new NotImplementedException();
DBLogicResult result = default(DBLogicResult);
NpgsqlConnection connection = null;
NpgsqlTransaction transaction = null;
try {
connection = new NpgsqlConnection(connectionString);
if (connection.State != System.Data.ConnectionState.Open)
{
connection.Open();
}
transaction = connection.BeginTransaction();
result = Process(connection, inOut);
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
transaction.Rollback();
} finally {
if (connection != null)
{
connection.Close();
}
}
return result;
}
protected abstract DBLogicResult Process(NpgsqlConnection conn, DBLogicInput InOuT);
}
The error exists after the debugger hits the code connection.Open();.
Should I add a web services to connect the postgres to my android app built in xamarin forms?
I am only a beginner in Xamarin Forms. I am just trying to create a self application. And need a little help for me to learn a new platform in programming.
Thank you and Regards,
How to fix it?
Well, I think I am doing it wrong.
Maybe the Right way to Connect the PostgreSQL is to have a WEB API.
Calling that web API to the Xamarin forms.
I really don't know if it is correct, but I will give it a try.
I will update the correct answer after I finish the development of that WEB API so that other beginners will found this answer helpful.

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

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.

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();
}

Include kerberos ticket in soap message absoleto SoapContext.Security

I include a Kerberos ticket header in a request to a service, but as I'm doing works, but says that is SoapContext.Security absoleto.
Can anyone help me fix this?
The code I have is this:
private void button1_Click(object sender, EventArgs e)
{
try
{
//default option selected is Kerberos.
string option = "Kerberos";
if (radioButton1.Checked)
option = "UserName";
if (radioButton2.Checked)
option = "Kerberos";
//declare any Security Token
SecurityToken token = null;
switch (option)
{
case "UserName":
{
try
{
//create a username Token.
UsernameToken unToken = new UsernameToken(textBox1.Text, textBox2.Text, PasswordOption.SendPlainText);
//assign the any SecurityToken an Username Token.
token = unToken;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
break;
}
case "Kerberos":
{
try
{
Console.WriteLine(System.Net.Dns.GetHostName());
//create a kerberos Token.
KerberosToken kToken = new KerberosToken(System.Net.Dns.GetHostName());
//assign the any SecurityToken an Username Token.
token = kToken;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
break;
}
default:
{
break;
}
}
if (token == null)
throw new ApplicationException("Unable to obtain security token.");
// Create an instance of the web service proxy that has been generated.
SecureServiceProxy.WebService1 proxy = new ClientTest.SecureServiceProxy.WebService1();
proxy.SetPolicy("KerberosClient");
//set the time to live to any value.
proxy.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;
// Add the SecurityToken to the SOAP Request Context.
proxy.RequestSoapContext.Security.Tokens.Add(token);
// Sign the SOAP message with a signatureobject.
proxy.RequestSoapContext.Security.Elements.Add(new MessageSignature(token));
// Create and Send the request
long a = long.Parse(textLong1.Text);
long b = long.Parse(textLong2.Text);
//call the web service.
long result = proxy.perform(a, b);
//Display the result.
MessageBox.Show(a + " + " + b + " = " + result.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
return;
}
}
And my warning appears saying that it is absoleto the following lines of code:
proxy.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;
// Add the SecurityToken to the SOAP Request Context.
proxy.RequestSoapContext.Security.Tokens.Add(token);
// Sign the SOAP message with a signatureobject.
proxy.RequestSoapContext.Security.Elements.Add(new MessageSignature(token));
But do not know how to solve