Not able Scan using redis template - redis

I am trying to use SCAN http://redis.io/commands/scan to iterate over all the keys present in redis. But the Redis template provided by spring do not have any scan() method. Is there any trick to use the above?
Thanks

You can use a RedisCallback on RedisOperations to do so.
redisTemplate.execute(new RedisCallback<Iterable<byte[]>>() {
#Override
public Iterable<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
List<byte[]> binaryKeys = new ArrayList<byte[]>();
Cursor<byte[]> cursor = connection.scan(ScanOptions.NONE);
while (cursor.hasNext()) {
binaryKeys.add(cursor.next());
}
try {
cursor.close();
} catch (IOException e) {
// do something meaningful
}
return binaryKeys;
}
});

Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Cursor<byte[]> cursor = null;
Set<String> keysTmp = new HashSet<>();
try {
cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(keyPrefix + "*").count(10000).build());
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (Objects.nonNull(cursor) && !cursor.isClosed()) {
try {
cursor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keysTmp;
});

Related

Azure.Documents.Document - Method not found

The error I got when I run below code
Method not found:
'System.Threading.Tasks.Task1<Microsoft.Azure.Documents.Client.ResourceResponse1>
Microsoft.Azure.Documents.IDocumentClient.ReadDocumentAsync(System.String,
Microsoft.Azure.Documents.Client.RequestOptions)'.
Before this I was able to run the code with
Microsoft.WindowsAzure.Storage, Microsoft.WindowsAzure.Storage.Table trying to migrate to Microsoft.Azure.CosmosDB.Table;, Microsoft.Azure.Storage
this is my code, I believe is nothing to do with code, but not sure how to fix this, and I've downgrade the Microsoft.Azure.Storage.Common to version 9.0.0.1-preview according to this
public static async Task<CloudTable> CreateTableAsync(string tableName)
{
CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference(tableName);
try
{
await table.CreateIfNotExistsAsync();
}
catch (StorageException ex)
{
Console.WriteLine(ex.Message);
throw;
}
Console.WriteLine();
return table;
}
public static CloudStorageAccount CreateStorageAccountFromConnectionString(string storageConnectionString)
{
CloudStorageAccount storageAccount;
try
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
}
catch (FormatException fex)
{
Console.WriteLine(fex);
throw;
}
catch (ArgumentException aux)
{
throw;
}
return storageAccount;
}
Appreciate if anyone could advise. Thanks

how am i supposed to pull a record from DAO vector?

I'm trying to implement the login page based on Oracle sql using JFrame(swing). I already have inserted IDs and PWs on database. Plus, I've also already defined appropriate -I think- LoginMember method in DAO. Below are the codes for Jframe page and DAO. Please let me know what is wrong with this. I've been struggling with this for the last 5 hours and still have no idea what to do.. HELP!! Sorry if you feel that I have not given enough info to solve this problem.
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strID=tfID.getText();
String strPW=String.valueOf(pwfPW.getPassword());
if(tfID.getText().equals("")) {
JOptionPane.showMessageDialog(Login.this, "Please type your ID");
} else {
dao=new M_DAO();
dao.loginMember(strID,strPW);
if(tfID.getText().equals(dao.loginMember(strID,strPW))) {
JOptionPane.showMessageDialog(Login.this, strID+" : successfully logged in");
}else if(strID ==null && strID.equals(strPW)){
JOptionPane.showMessageDialog(Login.this, "Incorrect ID or PW.");
}else{
System.out.println(10);
}
}
}
});
DAO:
public Vector loginMember(String strID,String strPW) {
Vector items=new Vector();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
conn=DB.hrConn();
String sql="select * from member where strID=? and strPW=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "strID");
pstmt.setString(2, "strPW");
rs=pstmt.executeQuery();
if(rs.next()){
Vector row=new Vector();
row.add("strID");
row.add("strPW");
items.add(row);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt!=null) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return items;
}
I wish it would work so bad...
It only shows the correct answer when I type nothing on ID and PW textfields, saying "Please type your ID". It prints out 10 when I type something on those.(just to check which line has an error.) Oh, please let me know if I need to specify something else!

Renci.SshNet : "server response does not contain ssh protocol identification"

I'm working with the Renci SSH.Net library on a WPF application and I'm having an issue with using the SFTP client. When the user tries to connect to download some files from the SFTP server he gets the message shown below:
Server response does not contain ssh protocol identification
It doesn't appear to be something specific with the server as I'm able to connect and download the files just fine on my development desktop and a secondary laptop. The same application is able to connect over SSH and run commands without issue, it's just the SFTP connection that appears to be the problem. I'm looking for a little guidance as to where to begin troubleshooting this.
Code for SFTP shown below:
void DownloadPlogs()
{
try
{
SftpClient SFTP;
if (GV.UseCustomPort && GV.CustomPort > 0 && GV.CustomPort < 65535)
{
SFTP = new SftpClient(GV.IpAddress, GV.CustomPort, GV.Username, GV.Password);
}
else
{
SFTP = new SftpClient(GV.IpAddress, 22, GV.Username, "");
}
SFTP.Connect();
DownloadDirectory(SFTP, "/PLOG", Directory.GetCurrentDirectory() + #"\PLOG");
ZipFile.CreateFromDirectory("PLOG", String.Format("{0} - {1} PLOGS.zip", GV.IpAddress, DateTime.Now.ToString("yyyyMMddHHmmss")));
Directory.Delete(Directory.GetCurrentDirectory() + #"\PLOG", true);
SFTP.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Getting PLOGS");
}
}
void DownloadDirectory(SftpClient Client, string Source, string Destination)
{
var Files = Client.ListDirectory(Source);
foreach (var File in Files)
{
if (!File.IsDirectory && !File.IsSymbolicLink)
{
DownloadFile(Client, File, Destination);
}
else if (File.IsSymbolicLink)
{
//Ignore
}
else if (File.Name != "." && File.Name != "..")
{
var Dir = Directory.CreateDirectory(System.IO.Path.Combine(Destination, File.Name));
DownloadDirectory(Client, File.FullName, Dir.FullName);
}
}
}
void DownloadFile(SftpClient Client, Renci.SshNet.Sftp.SftpFile File, string Directory)
{
using (Stream FileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(Directory, File.Name)))
{
Client.DownloadFile(File.FullName, FileStream);
}
}
Code for SSH below:
public SshConnection(string Host, int Port, string Username, string Password)
{
myClient = new SshClient(Host, Port, Username, Password);
myClient.KeepAliveInterval = new TimeSpan(0, 0, 5);
myClient.HostKeyReceived += myClient_HostKeyReceived;
myClient.ErrorOccurred += myClient_ErrorOccurred;
}
void myClient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "SSH Error Occurred");
}
void myClient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
{
e.CanTrust = true;
}
public async void Connect()
{
Task T = new Task(() =>
{
try
{
myClient.Connect();
}
catch (System.Net.Sockets.SocketException)
{
MessageBox.Show("Invalid IP Address or Hostname", "SSH Connection Error");
}
catch (Renci.SshNet.Common.SshAuthenticationException ex)
{
MessageBox.Show(ex.Message, "SSH Authentication Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
MessageBox.Show(ex.GetType().ToString());
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
});
T.Start();
await T;
if (T.IsCompleted)
{
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
}
public void Disconnect()
{
try
{
myClient.Disconnect();
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
public void SendData(string Data)
{
try
{
if (Data.EndsWith("\r\n"))
{
RunCommandAsync(Data, SshCommandRx);
}
else
{
RunCommandAsync(String.Format("{0}\r\n",Data), SshCommandRx);
}
//SshCommand Command = myClient.RunCommand(Data);
//OnDataReceived(this, new DataEventArgs(Command.Result));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
private async void RunCommandAsync(String Data, SshCommandCallback Callback)
{
Task<SshCommand> T = new Task<SshCommand>(() =>
{
try
{
SshCommand Command = myClient.RunCommand(Data);
return Command;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
return null;
}
});
T.Start();
await T;
if (T.IsCompleted)
{
Callback(this, T.Result);
}
}
private void SshCommandRx(SshConnection C, SshCommand Command)
{
if (Command != null)
{
string Rx = Command.Result;
//if (Rx.StartsWith(Command.CommandText))
//{
// Rx = Rx.Remove(0, Command.CommandText.Length);
//}
while (Rx.EndsWith("\r\n\r\n") == false)
{
Rx += "\r\n";
}
OnDataReceived(this, new DataEventArgs(Rx));
}
}
I solve it for my self only with connections retrying attempts. Didn't find what exactly the issue is, but have this connection issue many times.
Example:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
I experienced the same odd error message when attempting to connect to a SFTP server while using the SSH.NET library in a program on the server. The problem did not appear while testing from my development machine.
The solution was to have our server team add the IP address of the server into the hosts.allow file on the SFTP Linux server.

Remote Glassfish JMS lookup

I want to connect to my Glassfish Server at XX.XX.XX.XX:XXXX which is running on a ubuntu machine on our Server.
I want to send messages and then receive them.
My Receiver looks like this:
public JMS_Topic_Receiver(){
init();
}
public List<TextMessage> getCurrentMessages() { return _currentMessages; }
private void init(){
env.put("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
env.put("org.omg.CORBA.ORBInitialHost", "10.10.32.14");
env.put("org.omg.CORBA.ORBInitialPort", "8080");
try {
ctx = new InitialContext(env); // NamingException
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void subscribeTopic(String topicName, String userCredentials) {
try {
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("myTopicConnectionFactory");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
try {
String temp = InetAddress.getLocalHost().getHostName();
topicConnection.setClientID(temp);
} catch (UnknownHostException e) {
e.printStackTrace();
}
TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup(topicName);
topicConnection.start();
TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, userCredentials);
topicSubscriber.setMessageListener(new MyMessageListener());
}
catch(NamingException | JMSException ex)
{
ex.printStackTrace();
}
}
And my Sender looks like this:
public JMS_Topic_Sender(){
init();
}
private void init(){
env.put("java.naming.factory.initial","com.sun.enterprise.naming.SerialInitContextFactory");
env.put("org.omg.CORBA.ORBHost","10.10.32.14");
env.put("org.omg.CORBA.ORBPort","8080");
try {
ctx = new InitialContext(env);
} catch (NamingException e) {
e.printStackTrace();
}
}
public void sendMessage(String message, String topicName) {
try {
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("myTopicConnectionFactory");
if (topicConnectionFactory != null) {
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup(topicName);
topicConnection.start();
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
TextMessage tm = topicSession.createTextMessage(message);
topicPublisher.send(tm);
topicSession.close();
topicConnection.stop();
topicConnection.close();
}
} catch (NamingException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
}
}
I got most of this code from various tutorials online.
Now when I want to do the lookup aka. -> ctx.lookup("myTopicConnectionFactory");
I get all sorts of errors thrown:
INFO: HHH000397: Using ASTQueryTranslatorFactory
org.omg.CORBA.COMM_FAILURE: FEIN: 00410008: Connection abort vmcid: OMG minor code: 8 completed: Maybe
javax.naming.NamingException: Lookup failed for 'myTopicConnectionFactory' in SerialContext ........
My question here is, how do I do the lookup correctly?
My guess is that my Propertys (env) are incorrect and I need to change thouse, but I dont know to what?
Also, it works if i run my Glassfish localy on my own Computers localhost.
When im using localhost as adress and 8080 as port.

Dropbox Java Api Upload File

How do I upload a file public and get link ? I am using Dropbox Java core api. Here.
public static void Yukle(File file) throws DbxException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
InputStream inputStream = fileInputStream;
try (InputStream in = new FileInputStream(file)) {
UploadBuilder metadata = clientV2.files().uploadBuilder("/"+file.getName());
metadata.withMode(WriteMode.OVERWRITE);
metadata.withClientModified(new Date());
metadata.withAutorename(false);
metadata.uploadAndFinish(in);
System.out.println(clientV2.files());
}
}
I use the following code to upload files to DropBox:
public DropboxAPI.Entry uploadFile(final String fullPath, final InputStream is, final long length, final boolean replaceFile) {
final DropboxAPI.Entry[] rev = new DropboxAPI.Entry[1];
rev[0] = null;
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (replaceFile == true) {
try {
mDBApi.delete(fullPath);
} catch (Exception e) {
e.printStackTrace();
}
//! ReplaceFile is always true
rev[0] = mDBApi.putFile(fullPath, is, length, null, true, null);
} else {
rev[0] = mDBApi.putFile(fullPath, is, length, null, null);
}
} catch (DropboxException e) {
e.printStackTrace();
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rev[0];
}