Make a connection to ASI Granite - java

I need to make a connection to the Granite Database using the ASI installed on the WebLogic application server 10.3.6.
The programming language is Java:
public void connect() throws Exception {
if (prop != null) {
ConnectionFactoryASI.setProtocol(prop);
ConnectionFactoryASI.setDataObjectFactoryType(prop);
serviceFactory = ConnectionFactoryASI.getServiceFactory(prop);
} else {
serviceFactory = ConnectionFactoryASI.getServiceFactory(user);
}
dataObjectFactory = serviceFactory.getDataObjectFactory();
setUser(serviceFactory.getClientSession().getLoginName());
logger.debug("ASI HostName: " + serviceFactory.getClientSession().getHostName()
+ ", DatabaseName: " + serviceFactory.getClientSession().getDatabaseName()
+ ", DbHostName: " + serviceFactory.getClientSession().getDbHostName());
}
It does not connect and gives me a connection error.

the ASI need a connection ticketName, without which you can not open a connection.
Here is the correct code, I added the parameter written above:
public void connect(String ticketName) throws Exception {
if (prop != null) {
ConnectionFactoryASI.setProtocol(prop);
ConnectionFactoryASI.setDataObjectFactoryType(prop);
serviceFactory = ConnectionFactoryASI.getServiceFactory(prop, ticketName);
} else {
serviceFactory = ConnectionFactoryASI.getServiceFactory(ticketName, user);
}
dataObjectFactory = serviceFactory.getDataObjectFactory();
setUser(serviceFactory.getClientSession().getLoginName());
logger.debug("ASI HostName: " + serviceFactory.getClientSession().getHostName()
+ ", DatabaseName: " + serviceFactory.getClientSession().getDatabaseName()
+ ", DbHostName: " + serviceFactory.getClientSession().getDbHostName());
}

Related

Java can't connect to database via SSH tunnel

I am developing a small java utility with which I have to retrieve data on a remote mariadb database reachable at IP_1, so the recovered data must be manipulated and saved on another database, always mariadb, on a server reachable at IP_2.
To connect to the database reachable on IP_2, using navicat, I connect in ssh to the server and then to the database as localhost. (and the connection happens correctly)
I then looked for guides on how to do this in java maven, and defined the program.
Nonetheless I can also connect correctly with Java in SSH, then when I have to communicate with the DB and open the connection, I get the following error:
java.sql.SQLNonTransientConnectionException: Socket fail to connect to host: address = (host = 192.168.100.144) (port = 3366) (type = primary). Connection refused
Do you have any suggestions or advice? I have no idea how to fix it
mycode:
App.java
package mspay.helpdesk;
/**
* Hello world!
*
*/
import java.util.*;
import java.util.Properties;
import java.io.IOException;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class App {
public static void main(String[] args) {
System.out.println("Recupero richieste di assistenza tecnica!");
// Apertura connessione SSH
try {
final JSch jsch = new JSch();
Session session = jsch.getSession("username", "IP_2", 22);
session.setPassword("password");
final Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setPortForwardingL(3366, "IP_2", 3306);
if (session.isConnected()) {
System.out.println("Connessione SSH stabilita con successo!");
Class.forName("com.mysql.cj.jdbc.Driver");
Utility u = new Utility("IP_1", "user", "password", "name");
u.takeCassettiAttivi();
ResultSet ca = u.getComuni();
try {
while (ca.next()) {
System.out.println("Eleborazione del comune di: " + ca.getString(2));
u.takeRichiesteAssistenza(ca.getString(3));
ResultSet ri = u.getRichieste();
u.saveRichiesteAssistenza(ri, ca.getString(2).replace("'", " "));
}
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("Impossibile stabilire connessione SSH!");
System.exit(0);
}
} catch (JSchException jsche) {
jsche.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
Class Utility.java
package mspay.helpdesk;
import java.util.*;
//gestione sql
import java.sql.*;
//gestione files
import java.nio.file.*;
import java.io.File;
import java.util.Date;
import java.time.LocalDate;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class Utility {
static private String host;
static private String uname;
static private String pwd;
static private String db;
static Connection c = null;
static private ResultSet ca;
static private ResultSet rich;
public Utility(String h, String usr, String pass, String database) {
host = h;
uname = usr;
pwd = pass;
db = database;
}
// recuperiamo i cassetti attivi
public void takeCassettiAttivi() {
try {
c = DriverManager.getConnection(
"jdbc:mariadb://" + host + ":3306/" + db + "?" + "user=" + uname + "&password=" + pwd + "");
String sql = "SELECT * FROM `cassetti` where abilitato = 1";
Statement st = c.createStatement();
ca = st.executeQuery(sql);
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// recuperiamo le richieste di assistenza tecnica
public void takeRichiesteAssistenza(String database) {
try {
c = DriverManager.getConnection(
"jdbc:mariadb://" + host + ":3306/" + database + "?" + "user=" + uname + "&password=" + pwd + "");
// recupero le richieste di assistenza tecnica
String sql = "SELECT * FROM `tbl_richiestatecnica` WHERE tecData BETWEEN '2022-10-19' AND '2022-10-21' ORDER BY idTEC DESC";
Statement st = c.createStatement();
rich = st.executeQuery(sql);
System.out.println("Operazione di recupero delle richieste avvenuta con successo, COMUNE DI :" + database);
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// salviamo le richieste sul database
public void saveRichiesteAssistenza(ResultSet richieste, String comune) {
System.out.println("Salvataggio delle richieste nel repository centrale, COMUNE DI :" + comune);
try {
String database = "dbname";
c = DriverManager.getConnection(
"jdbc:mariadb://IP_2:3366/" + database + "?user=db_user&password=db_password");
if (c.isValid(0)) {
System.out.println("Connessione al server ubuntu avvenuta con successo");
try {
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// effettuo l'insert delle richieste all'interno del DB di helpdesk
if (!comune.equals("Civitanova Marche")) {
while (richieste.next()) {
StringBuilder sql = new StringBuilder(
"INSERT INTO richieste_assistenza (comune, nominativo, cfpiva, email, oggetto, richiesta, mailcomune, datarichiesta, orarichiesta, stato) VALUES (");
sql.append("'" + comune + "', '" + richieste.getString(4).replace("'", " ") + "', '"
+ richieste.getString(5) + "', '" + richieste.getString(6) + "', '" + richieste.getString(7)
+ "', '" + richieste.getString(8) + "', '" + richieste.getString(14) + "', '"
+ richieste.getString(2) + "', '" + richieste.getString(3) + "', 'TODO')");
System.out.println("QUERY DI UPDATE");
System.out.println(sql.toString());
Statement st = c.createStatement();
st.executeUpdate(sql.toString());
}
c.close();
} else {
while (richieste.next()) {
StringBuilder sql = new StringBuilder(
"INSERT INTO richieste_assistenza (comune, nominativo, cfpiva, email, oggetto, richiesta, mailcomune, datarichiesta, orarichiesta, stato) VALUES (");
sql.append("'" + comune + "', '" + richieste.getString(4).replace("'", " ") + "', '"
+ richieste.getString(11) + "', '" + richieste.getString(5) + "', '" + richieste.getString(6)
+ "', '" + richieste.getString(7) + "', '" + richieste.getString(13) + "', '"
+ richieste.getString(2) + "', '" + richieste.getString(3) + "', 'TODO')");
System.out.println("QUERY DI UPDATE");
System.out.println(sql.toString());
Statement st = c.createStatement();
st.executeUpdate(sql.toString());
}
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getComuni() {
return ca;
}
public ResultSet getRichieste() {
return rich;
}
}

Broadcasting device using jmDNS

I'm currently trying to have my device (program) show up as a mock chromecast on the network. The application itself can see the Mock-Caster as a chromecast but if i try searching for it using Youtube or any other sender app, the "Mock-Caster" does not appear in the list.
I registered a service on jmDNS with all the criteria that would be available on an actual chromecast as well.
Is there something that I am missing or getting wrong?
Here's what I have so far.
public void postConstruct() throws Exception {
InetAddress discoveryInterface = InetAddress.getByName("192.168.1.1");
CAST_DEVICE_MONITOR.startDiscovery(discoveryInterface, "Mock-Server");
CAST_DEVICE_MONITOR.registerListener(new DeviceDiscoveryListener() {
#Override
public void deviceDiscovered(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
#Override
public void deviceRemoved(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
});
JmDNS jmdns = JmDNS.create(discoveryInterface, "Mock-Server");
final String name = "Mock-Caster";
final String id = UUID.randomUUID().toString();
// Register a service
HashMap<String, String> properties = new HashMap<>();
//values scraped from chromecast or another java project
properties.put("sf", "1");
properties.put("id", id);
properties.put("md", name);
properties.put("fd", name);
properties.put("s#", "1");
properties.put("ff", "0");
properties.put("ci", "1");
properties.put("c#", Integer.toString(1));
properties.put("pv", "1.1");
properties.put("cd", "E465315D08CFDEF2742E1264D78F6035");
properties.put("rm", "ED724E435DA8115C");
properties.put("ve", "05");
properties.put("ic", "/setup/icon.png");
properties.put("ca", "201221");
properties.put("st", "0");
properties.put("bs", "FA8FCA771881");
properties.put("nf", "1");
properties.put("rs", "");
ServiceInfo serviceInfo = ServiceInfo.create("_googlecast._tcp.local.", name, 8009, 1, 1, properties);
jmdns.registerService(serviceInfo);
}
//This is where i know that the mock-caster is registered and available
#Bean
public IntegrationFlow tcpServer() throws Exception {
TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(8009);
DefaultTcpSSLContextSupport defaultTcpSSLContextSupport = new DefaultTcpSSLContextSupport(keystore, keystore, password, password);
defaultTcpSSLContextSupport.setProtocol("TLS");
factory.setTcpNioConnectionSupport(new DefaultTcpNioSSLConnectionSupport(defaultTcpSSLContextSupport));
factory.setTcpSocketSupport(new DefaultTcpSocketSupport(false));
factory.setDeserializer(TcpCodecs.lengthHeader4());
factory.setSerializer(TcpCodecs.lengthHeader4());
TcpInboundGatewaySpec inboundGateway = Tcp.inboundGateway(factory);
return IntegrationFlows
.from(inboundGateway)
.handle(message -> {
String ip_address = message.getHeaders().get("ip_address").toString();
if(ip_address.equalsIgnoreCase("192.168.1.1")) {
System.out.println("Self IP Address received");
System.out.println("Payload: " + message.getPayload());
System.out.println("MessageHeaders: " + message.getHeaders());
}else{
System.out.println("Other IP address received: " + ip_address);
}
})
.get();
}
//Mock-Caster detected here
#Scheduled(fixedRate = 15000)
public void checkCasters() throws Exception {
Set<CastDevice> casters = CAST_DEVICE_MONITOR.getCastDevices();
System.out.println("Current CCs: " + casters.size());
for (CastDevice device : casters) {
System.out.println("CC (" + device.getDisplayName() + ")");
var receiver = new CastEvent.CastEventListener() {
#Override
public void onEvent(#Nonnull CastEvent<?> castEvent) {
System.out.println("Event: " + castEvent);
}
};
var appId = DEFAULT_MEDIA_RECEIVER_APP;
try {
if (!device.isConnected()) {
device.connect();
}
device.addEventListener(receiver);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
device.removeEventListener(receiver);
device.disconnect();
}
}

How to obtain all TLS sessions from SSLContext using IBMJSSE2 default provider?

I'm using as default provided for TLS connections the IBMJSSEProvider2 and I have the following code to show information regarding the TLS sessions:
SSLSessionContext sslSessionContext = SSLContext.getDefault().getClientSessionContext();
Enumeration<byte[]> sessionIds = sslSessionContext.getIds();
while (sessionIds.hasMoreElements()) {
SSLSession sslSession = sslSessionContext.getSession(sessionIds.nextElement());
writer.write("Client: " + sslSession.getPeerHost() + ":" + sslSession.getPeerPort() + "\n");
writer.write("\tProtocol: " + sslSession.getProtocol() + "\n");
writer.write("\tSessionID: " + byteArrayToHex(sslSession.getId()) + "\n");
writer.write("\tCipherSuite: " + sslSession.getCipherSuite() + "\n");
for (X509Certificate certificate : sslSession.getPeerCertificateChain()) {
writer.write("\tX509 Certificate: " + certificate.getSubjectDN() + "\n");
writer.write("\t\tIssuer: " + certificate.getIssuerDN().getName() + "\n");
writer.write("\t\tAlgorithm: " + certificate.getSigAlgName() + "\n");
writer.write("\t\tValidity: " + certificate.getNotAfter() + "\n");
}
}
The code above is running on an instance of WebSphere 8.5. When I run this algorithm it doesn't print any information about the connections I had made to any HTTPS URLs using a RestTemplate implementation from Spring 3.2.
Using other providers like from Oracle shows the information. Am I missing something to make it work?
I'm trying to make a simple solution to troubleshoot which TLS versions are supported by a live instance of WebSphere. This is, of course, not recommended for live clients.
The problem was that, probably, the underlying libraries are not using the default context on WebSphere. Therefore, I had to create a custom client to make it using a specific SSLContext so I can list all the information I need. Following is the code to achieve this:
private static String URL = "https://www.google.com";
private static String TRUST_STORE_FILE = "/Users/xpto/trust.p12";
private static String TRUST_STORE_PASS = "truststore";
private static String TRUST_STORE_TYPE = "PKCS12";
private static String TLS_VERSION = "TLSv1.2";
public static void main(String[] args) throws Exception {
KeyStore keyStore = KeyStore.getInstance(TRUST_STORE_TYPE);
keyStore.load(new FileInputStream(TRUST_STORE_FILE), TRUST_STORE_PASS.toCharArray());
SSLContext sslContext = SSLContexts
.custom()
.loadTrustMaterial(keyStore)
.useProtocol(TLS_VERSION)
.build();
HttpComponentsClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory(HttpClients
.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext))
.build());
RestTemplate restTemplate = new RestTemplate(clientFactory);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);
print("Requesting: " + URL);
ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, String.class);
print("Response: " + response.getBody());
printSSLContextInfo(sslContext);
}
private static void printSSLContextInfo(SSLContext sslContext) throws Exception {
print("-------------\nPrinting TLS Client Information");
SSLSessionContext sslSessionContext = sslContext.getClientSessionContext();
Enumeration<byte[]> sessionIds = sslSessionContext.getIds();
while (sessionIds.hasMoreElements()) {
SSLSession sslSession = sslSessionContext.getSession(sessionIds.nextElement());
print("Client: " + sslSession.getPeerHost() + ":" + sslSession.getPeerPort());
print("\tProtocol: " + sslSession.getProtocol());
print("\tSessionID: " + byteArrayToHex(sslSession.getId()));
print("\tCipherSuite: " + sslSession.getCipherSuite());
for (X509Certificate certificate : sslSession.getPeerCertificateChain()) {
print("\tX509 Certificate: " + certificate.getSubjectDN());
print("\t\tIssuer: " + certificate.getIssuerDN().getName());
print("\t\tAlgorithm: " + certificate.getSigAlgName());
print("\t\tValidity: " + certificate.getNotAfter());
}
}
}
public static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a)
sb.append(String.format("%02x", b));
return sb.toString();
}
public static void print(Object msg) {
System.out.println(msg);
}

How do I verify canceled in-app subscription?

I am using: bp.isSubscribed(ID) to verify my subscription. But when I cancel a subscription the method bp.isSubscribed(ID) still returning true. What should I do?
transDetails.purchaseInfo.purchaseData.purchaseState.toString()
Always return PurchasedSuccessfully after i cancelled manually from play store manage subscription.
public void checkSubscriptionDetails(){
bp = new BillingProcessor(this, LICENSE_KEY, new BillingProcessor.IBillingHandler() {
#Override
public void onProductPurchased(#NonNull String productId, #Nullable TransactionDetails details) {
Common.printLog("InApp", ":onProductPurchased :" + productId);
}
#Override
public void onPurchaseHistoryRestored() {
}
#Override
public void onBillingError(int errorCode, #Nullable Throwable error) {
}
#Override
public void onBillingInitialized() {
}
});
boolean purchaseResult = bp.loadOwnedPurchasesFromGoogle();
// ## purchaseResult is always return FALSE
if (bp.isSubscribed(planID)) {
TransactionDetails transDetails = bp.getSubscriptionTransactionDetails(planID);
String strDetailsSubsMonth = "OrderID:" + transDetails.orderId +
"\nproductId: " + transDetails.productId +
"\npurchaseToken: " + transDetails.purchaseToken +
"\npurchaseTime: " + transDetails.purchaseTime +
"\npurchaseInfo.signature: " + transDetails.purchaseInfo.signature +
"\npurchaseInfo.responseData: " + transDetails.purchaseInfo.responseData +
"\npurchaseData.purchaseToken: " + transDetails.purchaseInfo.purchaseData.purchaseToken +
"\npurchaseData.autoRenewing: " + transDetails.purchaseInfo.purchaseData.autoRenewing +
"\npurchaseData.developerPayload: " + transDetails.purchaseInfo.purchaseData.developerPayload +
"\npurchaseData.purchaseState: " + transDetails.purchaseInfo.purchaseData.purchaseState.toString();
String strPurchaseState = transDetails.purchaseInfo.purchaseData.purchaseState.toString();
Common.printLog("InApp", "Details: " + planID + " >> " + strDetailsSubsMonth + " \n" + "Purchase State :" + strPurchaseState);
}
}
package com.anjlab.android.iab.v3;
public enum PurchaseState
{
PurchasedSuccessfully,
Canceled,
Refunded,
SubscriptionExpired
}
i need return "Canceled" when subscription canceled.
Initiate bp varibale in onCreate() and then call loadOwnedPurchasesFromGoogle().
In my case!
Don't know why we need to Call loadOwnedPurchasesFromGoogle() for multiple time. I always get false when I call in loadOwnedPurchasesFromGoogle() in onCreate(). But when I call in onPause() and onDestory(), I get true and my all values get update.
After getting loadOwnedPurchasesFromGoogle() true, I get update subscription value!
Best Solution from Server side get actual information for subscription or you can cross verify by Node.js configuration.
https://caster.io/lessons/verify-android-app-subscription-status-from-nodejs

Android Wear Channel API status code 8

I'm trying to send a file from the phone to the wear app, on the phone I'm sending the file as follows with a successful status.
NodeApi.GetConnectedNodesResult nodesResult = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
for (Node node : nodesResult.getNodes()) {
ChannelApi.OpenChannelResult result = Wearable.ChannelApi.openChannel(mGoogleApiClient, node.getId(), "/songs").await();
Channel channel = result.getChannel();
File file = new File(AppUtils.getDownloadsDir(getApplicationContext()),"lift.mp3");
Log.d(TAG, "call: " + file.canRead() + Uri.fromFile(file) + file.length());
channel.sendFile(mGoogleApiClient, Uri.fromFile(file)).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Log.d(TAG, "onResult: " + status.isSuccess() + " " + status.getStatusMessage());
}
}
);
Log.d(TAG, "Node " + node.getId() + node.getDisplayName() + node.isNearby());
}
On the wear side however, onChannelOpened is getting called with the correct path, I create a file, but when calling Channel.receiveFile I get a status code of 8 (INTERNAL_ERROR) in the resultCallback status.
public void onChannelOpened(final Channel channel) {
if (channel.getPath().equals("/songs")) {
try {
final File outFile = prepareFile("wild.mp3");
if (outFile == null || !outFile.exists()) {
Log.d(TAG, "Failed to create file ");
return;
}
Log.d(TAG, "onChannelOpened: " + mGoogleApiClient.isConnected());
channel.receiveFile(mGoogleApiClient, Uri.fromFile(outFile), false).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
int statusCode = status.getStatusCode();
if (!status.isSuccess()) {
Log.e(TAG, "receiveFile(): Failed to receive file with "
+ "status code = " + statusCode
+ ", and status: " + status.getStatus());
...
Fixed. The application id was already the same when this was happening, however the key stores in signingConfigs were different in the wear module and the mobile module, making them the same solved the problem.

Categories