Ganymed SSH2 JAVA, tips: Command not found - ganymede

Ganymed ,execCommand("java -version")
Tips:bash: java: command not found
But I use Shell tool, i can get the java version。
the ganymed can't get the local environmental variables?
How can i do it?

The reason for this problem is the lack of environmental variables. You can try the following code to solve.
public void execNoReturnRemoteCommand(String command, long timeout)
throws Exception {
Connection conn = getConnection();
Session session = null;
try {
session = conn.openSession();
session.requestPTY("bash");
session.startShell();
PrintWriter out = new PrintWriter(session.getStdin());
out.println(command);
out.println("exit");
out.close();
session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, timeout*1000);
} finally {
if (session != null) {
session.close();
}
if (conn != null) {
conn.close();
}
}
}

Related

Get name of linux distribution running

Is there any way to get the linux distributionn name used to run a flutter app?
The only way I found is to parse the Platform.operatingSystemVersion string but I think if we can get it like so, Flutter team surely provide a proper way to do this?
By distribution name I mean Ubuntu, Fedora, Debian, etc.
First solution:
Found that device_info_plus_linux provide what I want.
To use it (without device_info_plus):
import 'package:device_info_plus_linux/device_info_plus_linux.dart';
import 'package:device_info_plus_platform_interface/device_info_plus_platform_interface.dart' show LinuxDeviceInfo;
[...]
LinuxDeviceInfo deviceInfoLinux = await DeviceInfoLinux().linuxInfo();
print('Linux distribution: ${deviceInfoLinux.id}');
deviceInfoLinux.id will return a string containing the name of the distribution in lowercase characters (ex: 'debian', 'ubuntu', ...). If the package don't found any id it will return 'linux'.
Second solution:
In my case doing work async was not possible so I implemented my own solution:
String _getLinuxDistribution() {
String linuxDistribution;
try {
final List<String> osEtc = File('/etc/os-release').readAsLinesSync();
linuxDistribution =
osEtc.firstWhere((element) => element.indexOf("ID=") == 0);
if (linuxDistribution != null)
linuxDistribution = linuxDistribution.substring(3).toLowerCase();
else
throw Exception;
} catch (e) {
try {
final List<String> osUsr = File('/usr/lib/os-release').readAsLinesSync();
linuxDistribution =
osUsr.firstWhere((element) => element.indexOf("ID=") == 0);
if (linuxDistribution != null)
linuxDistribution = linuxDistribution.substring(3).toLowerCase();
else
throw Exception;
} catch (e) {
try {
final List<String> lsb = File('/etc/lsb-release').readAsLinesSync();
linuxDistribution =
lsb.firstWhere((element) => element.indexOf("DISTRIB_ID=") == 0);
if (linuxDistribution != null)
linuxDistribution = linuxDistribution.substring(11).toLowerCase();
else
throw Exception;
} catch (e) {
print(_red("Error getting Linux distribution name"));
linuxDistribution = 'linux';
}
}
}
return linuxDistribution;
}
note that the performance impact is negligable, I mesured it between 10ms and 30ms.

Snyc Azure local Tables with Azure Server tables in xamarin forms

I am using following method to sync Azure DB local table with server table but the changes which I made on my local DB are not reflecting to the Azure server,
public async Task PushDataAsync()
{
try
{
await _mobileService.SyncContext.PushAsync();
}
catch (Exception exc)
{
throw exc;
}
}
While using above method I am getting Error :-
Push Operation Fail.
Any Help will appreciated.
you are using right method to sync your offline store with server which is :-
await _mobileService.SyncContext.PushAsync();
I would suggest you to wrote few line of code in catch block which will help you to find out the reasons why the operations are not performed on server side
please use code bellow in catch block:-
public async Task PushDataAsync()
{
try
{
await _mobileService.SyncContext.PushAsync();
}
catch (MobileServicePushFailedException exc)
{
if (exc.PushResult != null)
{
syncErrors = exc.PushResult.Errors;
}
}
// Simple error/conflict handling.
if (syncErrors != null)
{
foreach (var error in syncErrors)
{
if (error.OperationKind == MobileServiceTableOperationKind.Update && error.Result != null || error.OperationKind == MobileServiceTableOperationKind.Insert && error.Result != null || error.OperationKind == MobileServiceTableOperationKind.Delete && 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 {2} operation. Item: {0} ({1}). Operation discarded.",
error.TableName, error.Item["id"], error.OperationKind);
}
}
}
Remember that PushAsync() pushes ALL changes from your local store to the cloud and that PullAsync first performs a Push. I would get rid of the service variable for each table and just use the service as a singleton class across your app. Here is my initialization. After this method returns, my local db is synced with the cloud and I can start using my tables:
public async Task InitializeStoreAsync()
{
try
{
var sqliteStore = _platform.MobileServiceSqliteStore;
sqliteStore.DefineTable<Memory>();
sqliteStore.DefineTable<User> ();
sqliteStore.DefineTable<Comment> ();
sqliteStore.DefineTable<Status>();
await _zumoClient.SyncContext.InitializeAsync(sqliteStore);
_memoryTable = _zumoClient.GetSyncTable<Memory> ();
_userTable = _zumoClient.GetSyncTable<User> ();
_commentTable = _zumoClient.GetSyncTable<Comment> ();
_statusTable = _zumoClient.GetSyncTable<Status>();
await _userTable.PullAsync ();
await _memoryTable.PullAsync ();
await _commentTable.PullAsync ();
await _statusTable.PullAsync();
}
catch (Exception ex)
{
Debug.WriteLine ("Initialize Store failed: {0}", ex.Message);
}
}
https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter3/client/ search for "Handling Conflict Resolution"

classCastException in Mockito with Java.lang.String

I have the following piece of code for which I'm writing the unit test using Mockito
if (user != null) {
LDAPCustomer cust = getLDAPCustomer();
LDAPAuthorization auth = getLDAPAuthorization();
cust = getCustomerData( new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.CUSTOMER_MAIL, user));
if (cust != null)
auth = getAuthorizationData(new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.AUTHORIZATION_GUID, cust.getCstAuthGuid()));
if (cust != null && auth!= null && cust.getCstManageeGuids().size() == 1) {
String custGuid = cust.getCstCustGuid();
if (cust.getCstManageeGuids().get(0).equals(custGuid)) {
//No secondary user
try
{
deleteUserAssociations(cust.getCstCustGuid());
resetAuthorization(auth.getCstAuthGuid());
logger.info(cust.getCstCustGuid()+" user successfully perged.");
} catch (Exception e) {
logger.error("Error occured whie try to purging user: "+MiscUtility.getStackTrace(e));
throw new Exception("Error occured whie try to purging user: "+e.getMessage());
}
}
}
}
and here's the mockito code
int size = 1;
//Define the Stub
Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
Mockito.doReturn(mockAuthorization).when(ldap).getLDAPAuthorization();
Mockito.doReturn(mockCustomer).when(ldap).getCustomerData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.doReturn(mockAuthorization).when(ldap).getAuthorizationData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.when(mockCustomer.getCstManageeGuids().size()).thenReturn(size);
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("mockCust");
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Mockito.doNothing().when(ldap).deleteUserAssociations(Mockito.anyString());
Mockito.doNothing().when(ldap).resetAuthorization(Mockito.anyString());
I'm getting a ClassCastException as below
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$1ebf8eb1 cannot be cast to java.lang.String
at the line
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Appreciate any help.
Solved it by breaking down the chain.
List<String> lst = new ArrayList<String>();
lst.add("mockVal");
Mockito.when(mockCustomer.getCstManageeGuids()).thenReturn(lst);

DNX (rc1-final): IHttpConnectionFeature not found

Using the latest rc1-final version of ASP.NET 5, I'm attempting to find the remote IP address inside an Azure API App controller method.
When running the code, 'context' is this.HttpContext, inside the controller method.
But feature is coming back null, since the feature doesn't exist.
IHttpConnectionFeature feature = context.Features.Get<IHttpConnectionFeature>();
Does anything have to be enabled in the configuration to have this feature be available?
Thanks,
Kirk
I had the same problem.
The following code works for me:
public async Task<IActionResult> Index()
{
if (!UserID.HasValue)
{
UpdateRemoteIp(HttpContext);
var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
if (remoteIpAddress == null)
{
throw new Exception("Cannot determine client IP");
}
await _userService.LoginAnonymous(remoteIpAddress);
string url = UriHelper.GetDisplayUrl(Request);
return Redirect(url);
}
PrepareViewModel();
return View("Index", ViewModel);
}
private static void UpdateRemoteIp(HttpContext httpContext)
{
var xForwardedForHeaderValue = httpContext.Request.Headers.GetCommaSeparatedValues(XForwardedForHeaderName);
if (xForwardedForHeaderValue != null && xForwardedForHeaderValue.Length > 0)
{
IPAddress ipFromHeader;
int? port;
if (IPAddressWithPortParser.TryParse(xForwardedForHeaderValue[0], out ipFromHeader, out port))
{
var connection = httpContext.Connection;
var remoteIPString = connection.RemoteIpAddress?.ToString();
if (!string.IsNullOrEmpty(remoteIPString))
{
httpContext.Request.Headers[XOriginalIPName] = remoteIPString;
}
if (port.HasValue)
{
if (connection.RemotePort != 0)
{
httpContext.Request.Headers[XOriginalPortName] = connection.RemotePort.ToString(CultureInfo.InvariantCulture);
}
connection.RemotePort = port.Value;
}
connection.RemoteIpAddress = ipFromHeader;
}
}
}
Hope it helps you

Call SSIS Package from c# Console Application For Each Loop

I have a Console Application which is invoking SSIS Package.Below is the code which is working Fine.
public static void ExecuteSSIS_Staging()
{
DataAccessLayer objDAL = new DataAccessLayer();
LogManager_SSIS objlogM = new LogManager_SSIS();
String strDestinationFilePath = System.Configuration.ConfigurationManager.AppSettings.Get("FileDownloaded");
try
{
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
string staging_pkgLocation = System.Configuration.ConfigurationManager.AppSettings.Get("SSIS_Staging_Filepath").ToString();
app = new Application();
pkg = app.LoadPackage(staging_pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
if (pkgResults == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success)
{
Console.WriteLine("Success");
}
else if (pkgResults == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure)
{
string err = "";
foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in pkg.Errors)
{
string error = local_DtsError.Description.ToString();
err = err + error;
}
throw new Exception("Error Occurred while executing the SSIS Staging package:" + err);
}
}
catch (Exception ex)
{
throw new Exception("SSIS Package Execution Failed:" + ex.Message.ToString());
}
}
Now I am in a position to Invoke this Package inside Foreach Loop.
static void Main(string[] args)
{
try
{
foreach (DateTime FileDate in SortedDates)
{
ExecuteSSIS_Staging(FileDate);
}
}
Catch(Exception ex)
{
}
}
I am getting Many Issues like
Could not load file or assembly 'Microsoft.SqlServer.ManagedDTS
and few other DLL reference error.
Can anyone suggest me, how can i invoke SSIS Package Inside Foreach loop. The main thing is, In my Local machine it is working obsolutely file. But When i deploy it in server, it is not.
The actuall issue is i have added
Microsoft.SQLServer.ManagedDTS.dll version 9.0
in one machine. When i tried to open it in other machine, some how DLL is refernced to
Microsoft.SQLServer.ManagedDTS.dll version 10.0 version.
I changed it again & executed. Now Working Fine.

Resources