Error while accessing Remote Service in .net - java

We are trying to access a java webservice through HTTPS from remote system in to our .net client system.we are facing an error:
This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server
Interesting thing is it is working in SOAP UI,but only problem with visual studio.Why it is working in soap UI rather not in Visual studio2010
protected void Page_Load(object sender, EventArgs e)
{
try
{
ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CertificationvAlidatefunction);
mainclass.ClientCredentials.UserName.UserName = "testuser";
mainclass.ClientCredentials.UserName.Password = "test123";
response = mainclass.Testmethod(request);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private bool CertificationvAlidatefunction(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors errors)
{
return true;
}

It is possible that the dotnet framework is related to the version of TLS supported. As far as I know,. Net4.0 is not compatible with tls1.2,you could refer to the following question for details.
Which versions of SSL/TLS does System.Net.WebRequest support?
Set up the configuration by using the following code snippets.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
ServiceReference2.Service1Client client = new ServiceReference2.Service1Client();
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
new X509ServiceCertificateAuthentication()
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = X509RevocationMode.NoCheck
};
Feel free to let me know If there is anything I can help with.

Related

How to use Jawampa (Java WAMP implementation) to subcribe to an event

i want to use the poloniex API. https://poloniex.com/support/api/
So far i made Jawampa ( https://github.com/Matthias247/jawampa ) running with IntelliJ.
My first Question is, how to login successfuly? (The Docu of Jawampa doesnt help)
I got a API Key and a Secret. Which functions i have to use in the builder of Jawampa:
withRealm
withRoles
withConnectorProvider
withConnectionConfiguration
withSerializations
withStrictUriValidation
withAuthId
withAuthMethod
withObjectMapper
I have so far this code
try {
WampClientBuilder builder = new WampClientBuilder();
builder.withConnectorProvider(connectorProvider)
.withUri("wss://api.poloniex.com")
.withAuthId("APIKEY")
.withRealm("realm2")
.withInfiniteReconnects()
.withReconnectInterval(1, TimeUnit.SECONDS);
client1 = builder.build();
} catch (Exception e) {
e.printStackTrace();
return;
}
Is wss://api.poloniex.com correct or should i use wss://api.poloniex.com/returnTicker for that client?
Do I have to make always a new client for every URI?
Thank you so much in advance.
My first Question is, how to login successfuly?
You don't have to authenticate to access Poloniex Push API via WAMP protocol. Push API methods are public, so you don't have to supply the API key and secret. Just connect to wss://api.poloniex.com and subscribe to a desired feed (Ticker, Order Book and Trades, Trollbox).
Btw, you need to supply the API Key only with Trading API methods. And the Secret is used to sign a POST data.
Which functions i have to use in the builder of Jawampa:
This is how you connect to the Push API:
WampClient client;
try {
WampClientBuilder builder = new WampClientBuilder();
IWampConnectorProvider connectorProvider = new NettyWampClientConnectorProvider();
builder.withConnectorProvider(connectorProvider)
.withUri("wss://api.poloniex.com")
.withRealm("realm1")
.withInfiniteReconnects()
.withReconnectInterval(5, TimeUnit.SECONDS);
client = builder.build();
} catch (Exception e) {
return;
}
Once your client is connected, you subscribe to a feed like this:
client.statusChanged().subscribe(new Action1<WampClient.State>() {
#Override
public void call(WampClient.State t1) {
if (t1 instanceof WampClient.ConnectedState) {
subscription = client.makeSubscription("trollbox")
.subscribe((s) -> { System.out.println(s.arguments()); }
}
}
});
client.open();
Is wss://api.poloniex.com correct or should i use
wss://api.poloniex.com/returnTicker for that client?
wss://api.poloniex.com is correct. Besides, returnTicker belongs to the Public API and is accessed via HTTP GET requests.
Do I have to make always a new client for every URI?
In respect to the Push API, once you connected a client to wss://api.poloniex.com, you can use this client to make subscriptions to multiple feeds. For example:
client.statusChanged().subscribe(new Action1<WampClient.State>() {
#Override
public void call(WampClient.State t1) {
if (t1 instanceof WampClient.ConnectedState) {
client.makeSubscription("trollbox")
.subscribe((s) -> { System.out.println(s.arguments()); });
client.makeSubscription("ticker")
.subscribe((s) -> { System.out.println(s.arguments()); });
}
}
});
However, according to Jawampa Docs:
After a WampClient was closed it can not be reopened again. Instead of this a new instance of the WampClient should be created if necessary.

How to set various parameters for Java RMI based communication?

While performing a client-server communication with various forums, I am unable to perform Remote-object's lookup on the client machine.
The errors which I receive are ConnectIOException(NoRouteToHostException), and sometimes ConnectException and sometimes someother.
This is not what I want to ask. But, the main concern is how should I setup client platform and server platform --- talking about networking details --- this is what I doubt interferes with my connection.
My questions :-
How should I edit my /etc/hosts file on both client-side and server-side? Server's IP- 192.168.1.8 & Client's IP-192.168.1.100. Means, should I add the system name in both the files:
192.168.1.8 SERVER-1 # on the server side
192.168.1.100 CLIENT-1 # on the client side
Should I edit like this? Can this be one of the possible concerns? I just want to remove any doubts left over to perform the rmi-communication!
Also, I am also setting Server's hostname property using System.setProperty("java.rmi.server.hostname",192.168.1.8); on the server side. Should I do the same on the client-side too?
I've read about setting classpath while running the java program on both server-side as well as the client-side. I did this too,but,again the same exceptions. No difference at all. I've read that since Java update 6u45, classpaths aren't necessary to include! Please throw some light on this too...
If I am missing something, Please enlighten about the same too. A brief idea/link to resources are most preferred.
You don't need any of this unless you have a problem. The most usual problem is the one described in the RMI FAQ #A.1, and editing the hosts file of the server or setting java.rmi.server.hostname in the server JVM is the solution to that.
'No route to host' is a network connectivity problem, not an RMI problem, and not one you'll solve with code or system property settings.
Setting the classpath has nothing to do with network problems.
Here is server example of which transfers an concrete class. This class must be exist in server and client classpath with same structure
Message:
public class MyMessage implements Serializable {
private static final long serialVersionUID = -696658756914311143L;
public String Title;
public String Body;
public MyMessage(String strTitle) {
Title = strTitle;
Body = "";
}
public MyMessage() {
Title = "";
Body = "";
}
}
And here is the server code that gets an message and returns another message:
public class SimpleServer {
public String ServerName;
ServerRemoteObject mRemoteObject;
public SimpleServer(String pServerName) {
ServerName = pServerName;
}
public void bindYourself() {
try {
mRemoteObject = new ServerRemoteObject(this);
java.rmi.registry.Registry iRegistry = LocateRegistry.getRegistry(RegistryContstants.RMIPort);
iRegistry.rebind(RegistryContstants.CMName, mRemoteObject);
} catch (Exception e) {
e.printStackTrace();
mRemoteObject = null;
}
}
public MyMessage handleEvent(MyMessage mMessage) {
MyMessage iMessage = new MyMessage();
iMessage.Body = "Response body";
iMessage.Title = "Response title";
return iMessage;
}
public static void main(String[] server) {
SimpleServer iServer = new SimpleServer("SERVER1");
iServer.bindYourself();
while (true) {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and here is the remote interface of server remote object:
public interface ISimpleServer extends java.rmi.Remote{
public MyMessage doaction(MyMessage message) throws java.rmi.RemoteException;
}
all you need is adding MyMessage class both in server and client classpath.

What can be the best approach to handle java.net.UnknownHostException for AWS users?

My application sends message to Amazon Simple Notification Service (SNS) topic but sometime (6/10) I get java.net.UnknownHostException:sqs.ap-southeast-1.amazonaws.com. The reason of exception is described in the amazon web services discussion forums, please look: https://forums.aws.amazon.com/thread.jspa?messageID=499290&#499290.
My problem is similar to what described in forums of amazon but my rate of publishing messages to topic is very dynamic. It can be 1 message/second or 1 message/minute or no message in an hour. I am looking for a cleaner, better and safe approach, which guaranties sending of message to SNS topic.
Description of problem in detail:
Topic_Arn= arn of SNS topic where application wants to publish message
msg = Message to send in topic
// Just a sample example which publish message to Amazon SNS topic
class SimpleNotificationService {
AmazonSNSClient mSnsClient = null;
static {
createSnsClient()
}
private void static createSnsClient() {
Region region = Region.getRegion(Regions.AP_SOUTHEAST_1);
AWSCredentials credentials = new
BasicAWSCredentials(AwsPropertyLoader.getInstance().getAccessKey(),
AwsPropertyLoader.getInstance().getSecretKey());
mSqsClient = new AmazonSQSClient(credentials);
mSqsClient.setRegion(region);
}
public void static publishMessage(String Topic_Arn, String msg) {
PublishRequest req = new PublishRequest(Topic_Arn, msg);
mSnsClient.publish(req);
}
}
class which calls SimpleNotificationService
class MessagingManager {
public void sendMessage(String message) {
String topic_arn = "arn:of:amazon:sns:topic";
SimpleNotificationService.publishMessage(topic_arn, message);
}
}
Please note that this is a sample code, not my actual code. Here can be class design issue but please ignore those if they are not related to problem.
My thought process says to have try-catch block inside sendMessage, so when we catch UnknownHostException then again retry but I am not sure how to write this in safer, cleaner and better way.
So MessagingManager class will look something like this:
class MessagingManager {
public void sendMessage(String message) {
String topic_arn = "arn:of:amazon:sns:topic";
try {
SimpleNotificationService.publishMessage(topic_arn, message);
} catch (UnknownHostException uhe) {
// I need to catch AmazonClientException as aws throws
//AmazonClientException when sees UnknownHostException.
// I am mentioning UnknownHostException for non-aws user to understand
// my problem in better way.
sendMessage(message); // Isn't unsafe? - may falls into infinite loop
}
}
}
I am open for answers like this: java.net.UnknownHostException: Invalid hostname for server: local but my concern is to dependent on solution at application code-level and less dependent on changes to machine. As my server application is going to run in many boxes (developer boxes, testing boxes or production boxes). If changes in machine host-files or etc is only guaranted solution then I prefer that to include with code level changes.
Each AWS SDK implements automatic retry logic. The AWS SDK for Java automatically retries requests, and you can configure the retry settings using the ClientConfiguration class.
Below is the sample example to create SNS client. It retries for 25 times if encounters UnKnownHostException. It uses default BackOff and retry strategy. If you want to have your own then you need to implement these two interfaces: http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/retry/RetryPolicy.html
private void static createSnsClient() {
Region region = Region.getRegion(Regions.AP_SOUTHEAST_1);
AWSCredentials credentials = new
BasicAWSCredentials(AwsPropertyLoader.getInstance().getAccessKey(),
AwsPropertyLoader.getInstance().getSecretKey());
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setMaxErrorRetry(25);
clientConfiguration.setRetryPolicy(new RetryPolicy(null, null, 25, true));
mSnsClient = new AmazonSNSClient(credentials, clientConfiguration);
mSnsClient.setRegion(region);
}
Have you considering looking into the JVM TTL for the DNS Cache?
http://docs.aws.amazon.com/AWSSdkDocsJava/latest//DeveloperGuide/java-dg-jvm-ttl.html

How do you set the configuration for jschconfigsessionfactory for jgit so that pull and push work?

I am trying to do a git pull/push using jgit's api with the following code
org.eclipse.jgit.api.Git.open(theRepoFile).pull().call()
but I am getting exceptions
JSchException Auth fail
com.jcraft.jsch.Session.connect (Session.java:461)
org.eclipse.jgit.transport.JschConfigSessionFactory.getSession (JschConfigSessionFactory.java:116)
org.eclipse.jgit.transport.SshTransport.getSession (SshTransport.java:121)
org.eclipse.jgit.transport.TransportGitSsh$SshPushConnection.<init> (TransportGitSsh.java:306)
org.eclipse.jgit.transport.TransportGitSsh.openPush (TransportGitSsh.java:152)
org.eclipse.jgit.transport.PushProcess.execute (PushProcess.java:130)
org.eclipse.jgit.transport.Transport.push (Transport.java:1127)
org.eclipse.jgit.api.PushCommand.call (PushCommand.java:153)
Even though using cgit pull and pushing works.
I tried checking SO for example code
Java git client using jgit
but the above question does not provide a complete coded example of what is necessary to do a git pull with a remote repo that is normally authenticated via ssh keys. There should be a way to get the credential information from ~/.ssh/ or the windows equivalent.
Jsch will automatically detect your SSH keys but will fail if these are protected by a password. You need to specify the passphrase through a CredentialsProvider like this:
JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
#Override
protected void configure(OpenSshConfig.Host hc, Session session) {
CredentialsProvider provider = new CredentialsProvider() {
#Override
public boolean isInteractive() {
return false;
}
#Override
public boolean supports(CredentialItem... items) {
return true;
}
#Override
public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
for (CredentialItem item : items) {
((CredentialItem.StringType) item).setValue("yourpassphrase");
}
return true;
}
};
UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
session.setUserInfo(userInfo);
}
};
SshSessionFactory.setInstance(sessionFactory);
The problem is Jsch does not support ssh-agents out of the box. One will need to configure https://github.com/ymnk/jsch-agent-proxy to get it to work.
An alternative is to make your own org.eclipse.jgit.transport.CredentialsProvider and set the org.eclipse.jgit.transport.CredentialItem to the correct values (by requesting them from the user or looking up a file). You can change the default CredentialsProvider with org.eclipse.jgit.transport.CredentialsProvider/setDefault
See my clojure library dj for details: https://github.com/bmillare/dj/blob/library/src/dj/git.clj
I vaguely remember getting an error with JSch that blocked me for a while because the log was not very explicit. I can't tell for sure it's the same problem but I followed this page to solve my problem:
https://help.github.com/articles/generating-ssh-keys
(it was due to a wrong network configuration)

Smtp Authentication

I am writing a class to connect to a SMTP server over SSL and send a mail. The smtp server i am using (yahoo) requires authentication. Can someone tell me how the authentication takes place as to which commands i should use to send my user credentials?
Note: I know about the JavaMail API. I just want a simple class to send mail without outside libraries.
Internet RFC 821 covers the basics of the SMTP protocol, and RFC 2554 covers the authentication extensions. You'll need many of them to get a functional SMTP client up.
But, really, it's much simpler to just use JavaMail (unless this is a homework assignment, in which case, I'm guessing that would be cheating.)
You can do it by following in c#
class smtp
{
SmtpClient client;
MailMessage mm;
void send()
{
mm.send();
}
void smtp_configure()
{
client.Credentials = new NetworkCredential(username, password);
client.Port = smtp_port;
client.Host = smtp_host;
client.EnableSsl = true;
}
message_configure()
{
mm = new MailMessage(From, To);
mm.Body = MgsText;
mm.BodyEncoding = Encoding.UTF8;
mm.Subject = Subject;
}
Main()
{
smtp_configure();
message_configure();
send();
}
}

Categories

Resources