Executing multiple commands using j2ssh - command

I would like to know how to execute multiple commands using j2ssh. The code I got from the net is as follows:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import com.sshtools.j2ssh.io.IOStreamConnector;
import com.sshtools.j2ssh.io.IOStreamConnectorState;
import com.sshtools.j2ssh.connection.*;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.configuration.SshConnectionProperties;
import com.sshtools.j2ssh.transport.ConsoleHostKeyVerification;
public class MySSHClient {
SshClient ssh = null;
SshConnectionProperties properties = null;
SessionChannelClient session = null;
public MySSHClient(String hostName, String userName, String passwd )
{
try
{
// Make a client connection
ssh = new SshClient();
properties = new SshConnectionProperties();
properties.setHost(hostName);
// Connect to the host
ssh.connect(properties, new ConsoleHostKeyVerification());
// Create a password authentication instance
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
pwd.setUsername(userName);
pwd.setPassword(passwd);
// Try the authentication
int result = ssh.authenticate(pwd);
// Evaluate the result
if (result==AuthenticationProtocolState.COMPLETE) {
System.out.println("Connection Authenticated");
}
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}//end of method.
public String execCmd(String cmd)
{
String theOutput = "";
try
{
// The connection is authenticated we can now do some real work!
session = ssh.openSessionChannel();
if ( session.executeCommand(cmd) )
{
IOStreamConnector output = new IOStreamConnector();
java.io.ByteArrayOutputStream bos = new
java.io.ByteArrayOutputStream();
output.connect(session.getInputStream(), bos );
session.getState().waitForState(ChannelState.CHANNEL_CLOSED);
theOutput = bos.toString();
}
//else
//throw Exception("Failed to execute command : " + cmd);
//System.out.println("Failed to execute command : " + cmd);
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
return theOutput;
}
}
I tried to go to a directory then list the files using the ls command but it didn't work
MySSHClient sshc = new MySSHClient(<hostName>, <userName>, <passwd>);
System.out.println( sshc.execCmd("cd test") );
System.out.println( sshc.execCmd("ls") );
Any help please?

Try separating commands by a semicolon. For example: System.out.println( sshc.execCmd("cd test; ls") );

Add the and operator (&&) between the commands:
System.out.println( sshc.execCmd("cd test && ls") );
&& is better than ; because if the cd fails the ls is not executed.

Instead of using executeCommand, try to write your commands in output stream - session.getOutputStream() with '\n' addition on the end.
Then read input stream.
For example:
session.getOutputStream().write((command + "\n").getBytes());

Related

How to read datamatrix embedded in document?

I try to read a datamatrix which is embedded into a document.
This is for an opensource project which helps to create and read 2DCODE standard.
I try with this code :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ZxingTest {
#Test
public void test() {
readQRCode("sfr-facture-1048469311-1.jpg");
readQRCode("sfr-facture-1048469311-1.png");
}
public static void readQRCode(String fileName) {
System.out.println("Try reading " + fileName);
File file = new File(fileName);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image == null)
return;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
// hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
decode(image, hints);
}
public static void decode(BufferedImage tmpBfrImage, Hashtable<DecodeHintType, Object> hintsMap) {
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try {
if (hintsMap != null && !hintsMap.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, hintsMap);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
System.out.println("tmpFinalResult=" + tmpFinalResult);
} catch (Exception tmpExcpt) {
tmpExcpt.printStackTrace();
}
}
}
and those images found on the net :
sfr-facture-1048469311-1.jpg
sfr-facture-1048469311-1.png
But I get this exception regardless of the image format: com.google.zxing.NotFoundException
May you advise me an lib which parses the page and detect the datamatrix coordinates for a pre-processing cropping?
Or a better a example of code which read the datamatrix?
I have a solution to my problem. I use opencv to locate any barcode then, after extraction according to the returned coordinates, I read them with zxing.
I based my solution the work of http://karthikj1.github.io/BarcodeLocalizer/
this the code i use :
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import barcodelocalizer.Barcode;
import barcodelocalizer.CandidateResult;
import barcodelocalizer.ImageDisplay;
import barcodelocalizer.MatrixBarcode;
import barcodelocalizer.TryHarderFlags;
public class OpencvUtils {
private static boolean SHOW_INTERMEDIATE_STEPS = false;
private static boolean showImages = false;
public static String process_bufferedImage(BufferedImage bufferedImage) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(bufferedImage, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding buffered image " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
public static String process_image(String imgFile) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(imgFile, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding " + imgFile + " " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
private static String decodeBarcode(List<CandidateResult> candidateCodes, String filename, String caption) {
// decodes barcode using ZXing and either print the barcode text or says no
// barcode found
BufferedImage decodedBarcode = null;
String title = null;
Result result = null;
String barcodeText = null;
for (CandidateResult cr : candidateCodes) {
BufferedImage candidate = cr.candidate;
decodedBarcode = null;
LuminanceSource source = new BufferedImageLuminanceSource(candidate);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
result = reader.decode(bitmap, hints);
decodedBarcode = candidate;
title = filename + " " + caption + " - barcode text " + result.getText() + " " + cr.getROI_coords();
} catch (ReaderException re) {
}
if (decodedBarcode == null) {
title = filename + " - no barcode found - " + cr.getROI_coords();
if (showImages)
ImageDisplay.showImageFrame(candidate, title);
} else {
if (showImages)
ImageDisplay.showImageFrame(decodedBarcode, title);
System.out.println("Barcode text for " + filename + " is " + result.getText());
barcodeText = result.getText();
}
}
return barcodeText;
}
}
i added the method process_bufferedImage which process a java.awt.image.BufferedImage of a String filename.
And this sub-method to get the matrix of the BufferedImage bi.
protected Mat loadBufferedImage(BufferedImage bi) throws IOException {
// reads the BufferedImage passed in parameter
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED);
return mat;
}

katalon compare api response with database

I am not sure how to link test cases, add more verification.
I am thinking how to link both above, store the API response and after this completed successfully: ID, productid, productinfo.
Then query the database details, store it if possible (I have checkpoint created, not sure if this is the right approach), then verify values from API response same as the database column value.
I have object repository for sets of API message (GET/POST)
POST API to insert new product
Then 2 keywords to test the response of API matched the database records
connect to API and POST to insert the new product
connect to database and Get the table details
I have an individual test case to test the API POST message getting response 200 and run successfully. And another test case to connect to the database and query the table details.
===========
1. add product keyword groovy script
package Product
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
public class API {
#Keyword
AddProduct() {
def result = WS.sendRequestAndVerify(findTestObject('AddProduct'))
return result
}
}
======================================
2. database groovy script
package database
import java.sql.*
import com.kms.katalon.core.annotation.Keyword
public class postgresHandler {
Connection c = null
Statement stmt = null
#Keyword
public void connectToPostgres(){
try {
Class.forName("org.postgresql.Driver")
String url = "jdbc:postgresql://localhost:5433/postgres?currentSchema=SCHEMA";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","postgres");
c = DriverManager.getConnection(url, props);
} catch (Exception e) {
e.printStackTrace()
System.err.println(e.getClass().getName()+": "+e.getMessage())
System.exit(0)
}
System.out.println("Opened database successfully")
}
#Keyword
public void getProduct(){
try {
Class.forName("org.postgresql.Driver")
String url = "jdbc:postgresql://localhost:5433/postgres?currentSchema=SCHEMA";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","postgres");
c = DriverManager.getConnection(url, props);
c.setAutoCommit(false)
System.out.println("Opened database successfully")
stmt = c.createStatement()
ResultSet rs = stmt.executeQuery( "select * from products.products;" )
while ( rs.next() ) {
String id = rs.getString("id")
String productid = rs.getString("productid")
String productInfo = rs.getString("productInfo")
System.out.println( "ID = " + id )
System.out.println( "productID = " + productid )
System.out.println( "productInfo = " + productInfo )
System.out.println()
}
rs.close()
stmt.close()
c.close()
} catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() )
System.exit(0)
}
System.out.println("Operation done successfully")
}
}
=============================================================
3. Test case to call add product keyword groovy script
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
result = CustomKeywords.'swisslog.KafkaRest.AddProduct'()
print(result)
WS.sendRequest(findTestObject('AddProduct'))
=====================================================
Test case to call database groovy script
import com.kms.katalon.core.configuration.RunConfiguration
CustomKeywords.'dsdatabase.postgresHandler.connectToPostgres'()
CustomKeywords.'dsdatabase.postgresHandler.getProduct'()

HttpUrlConnection.connect() Query

After hours of trawling the internet and trying to make sense of the documentation I seem unable to find a resolution to this problem.
I have an application which is using an ASyncTask to connect to a server I have 3 addresses to "test" the connection.
Now the problem is when I use the Myconnection.connect() the background task just hangs if there is either no known address or a dead link.
How can I test this connection when with a dead link or dead server it hangs and does not receive any response
The errors in the Logcat are
07-02 12:47:13.101 13850-20562/nodomain.myapplication D/URL ERRORhttp://10.0.0.2/testdb/connection.php
07-02 12:47:13.339 13850-20562/nodomain.myapplication I/URL IS OK: [ 07-02 12:47:13.339 13850:20562 I/ ]Status : 200
07-02 12:47:13.344 13850-20562/nodomain.myapplication D/URL ERRORhttp://localhost/myPage.php
As you can see the only URL I get a response from is www.google.com
My code is below:
package nodomain.myapplication;
import android.os.AsyncTask;
import android.util.Log;
import org.w3c.dom.Text;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Shab on 02/07/2017.
*/
public class bgWorker extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params)
{
String db_Username = "root";
String db_Password = "";
String db_Name = "testdb";
String url1 = "http://10.0.0.2/testdb/connection.php"; //DEAD? (NO RESPONSE)
(Program Hang until exception is called)
String url2 = "http://www.google.com"; //OK RESPONSE 200
String url3 = "http://localhost/myPage.php"; //NO RESPONSE
try {
getResponseCodes(url1);
getResponseCodes(url2);
getResponseCodes(url3);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
private String encodeURLString(String value) {
String encodedString = "";
try {
encodedString = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodedString;
}
public static int getResponseCodes(String TheURL) throws MalformedURLException,IOException
{
URL oUrl = new URL(TheURL);
HttpURLConnection oHuC = (HttpURLConnection) oUrl.openConnection();
oHuC.setRequestMethod("HEAD");
int response = 0;
try{
oHuC.connect();
response = oHuC.getResponseCode();
if(response == 200)
{
Log.i("URL IS OK","");
}else{
Log.i("URL IS NOT OK","");
}
Log.i("", "Status : " + response);
}catch(IOException e){
Log.d("URL ERROR" + oUrl, "D");
}
return response;
}
}
Even with the IF statement testing the response for a 200 OK it only manages to interpret one response from the 3 URL due to the URL IS OK output.

Print the shortest path to the java console using orientdb

I want to print in the Java console shortestpath between two vertices. I can not print anything or if you have any way to do that would appreciate it.
String subquery = "Select shortestpath(17:10, 17:14, BOTH) ";
Iterable<OrientVertex> result = orientDBGraph.command(new OSQLSynchQuery<OrientVertex>(subquery)).execute();
Assert.assertTrue(result.iterator().hasNext());
System.out.println(result);
for (OrientVertex d : result) {
System.out.println("Shortest path from " + ((OrientVertex) d.getProperty("$current")).getProperty("name") + " and "
+ ((Iterable<OrientVertex>) d.getProperty("$target")).iterator().next().getProperty("name") + " is: "
+ d.getProperty("path"));
}
Code:
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbName = "ytrewa";
OrientGraphFactory dbfactory = new OrientGraphFactory("remote:127.0.0.1:2424/"+dbName, "root", "root").setupPool(1, 50);
OrientGraph g = dbfactory.getTx();
try {
String query = "select expand(shortestPath) from (select shortestPath(#9:0,#9:1,BOTH))";
Iterable<OrientVertex> res = g.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString());
}
} finally {
g.shutdown();
}
}
}
Output:
rid: #9:0
rid: #10:0
rid: #12:0
rid: #9:1

How to execute a sql gzipped script for postgresql database in java using jdbc API?

I'd like to execute a sql script gzipped to a postgresql database using java jdbc API.
I know how to do this in H2 database using the sql run script statement.
I manage to do this for any database using this code
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.zip.GZIPInputStream;
/**
* Created on 09/01/16.
*
* #author Tony Chemit - chemit#codelutin.com
*/
public class RunSqlScript {
public void executeSqlScript(Connection connection, boolean gzip, int batchSize, byte... content) throws SQLException, IOException {
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try (BufferedReader reader = createReader(gzip, content)) {
try (Statement statement = connection.createStatement()) {
int currentBatchSize = 0;
String command = null;
String line;
while ((line = reader.readLine()) != null) {
String trimLine = line.trim();
if (trimLine.startsWith("--")) {
continue;
}
command = command == null ? line : command + ' ' + line;
if (trimLine.endsWith(";")) {
statement.addBatch(command);
batchSize++;
command = null;
if (currentBatchSize % batchSize == 0) {
flushStatement(statement);
}
}
}
flushStatement(statement);
}
} finally {
connection.setAutoCommit(autoCommit);
}
}
protected BufferedReader createReader(boolean gzip, byte... content) throws IOException {
return new BufferedReader(new InputStreamReader(new BufferedInputStream(gzip ? new GZIPInputStream(new ByteArrayInputStream(content)) : new ByteArrayInputStream(content))));
}
protected void flushStatement(Statement statement) throws SQLException {
statement.executeBatch();
statement.clearBatch();
}
}