Does anyone have an example of retrieving data using Actian's JCL to a loosely coupled pervasive database in Java? The database I am connecting to only has DAT files. My goal is to create a link between pervasive and MS SQL.
I am not looking for a freebie, but someone to point me in the right direction so I can learn and grow.
Thank you in advanced!
Found this in my archives. Don't know when it was written, whether it works, or if this interface is still supported. You don't say what version of PSQL you're using so I don't even know if this will work with your version.
import pervasive.database.*;
public class VersionTest implements Consts
{
public VersionTest()
{
try
{
Session session = Driver.establishSession();
Database db = session.connectToDatabase("PMKE:");
XCursor xcursor = db.createXCursor(57000);
//Using local TABL.DAT (length 255 assures no leftovers!)
xcursor.setKZString(0,255,"plsetup\\tabl.dat");
//Open the file to load local MKDE
int status = xcursor.BTRV(BTR_OPEN);
System.out.println("Local Open status: " + status);
//Using remote TABL.DAT (length 255 assures no leftovers!)
xcursor.setKZString(0,255,"h:\\basic2c\\develop\\tabl.dat");
//set the buffer size
xcursor.setDataSize(15);
//get version
status = xcursor.BTRV(BTR_VERSION);
System.out.println("Version status: " + status);
// should be 15, always prints 5
System.out.println("Version length: " + xcursor.getRecLength());
System.out.println("Version: " + xcursor.getDString(0,15));
// try with an open file on a server
XCursor xcursor2 = db.createXCursor(57000);
//Using remote TABL.DAT (length 255 assures no leftovers!)
xcursor2.setKZString(0,255,"h:\\basic2c\\develop\\tabl.dat");
//Open the file
status = xcursor2.BTRV(BTR_OPEN);
System.out.println("Remote Open status: " + status);
//set the buffer size
xcursor2.setDataSize(15);
//get version
status = xcursor2.BTRV(BTR_VERSION);
System.out.println("Version status: " + status);
// should be 15, always prints 5
System.out.println("Version length: " + xcursor2.getRecLength());
System.out.println("Version: " + xcursor2.getDString(0,15));
// clean up resources
Driver.killAllSessions();
}catch(Exception exp)
{
exp.printStackTrace();
}
}
public static void main(String[] args)
{
new VersionTest();
}
}
JCL APIs are still supported with Actian PSQL v12 and v13.
You can find more documentation on retrieving data using Actian JCL at
http://docs.pervasive.com/products/database/psqlv12/wwhelp/wwhimpl/js/html/wwhelp.htm#href=jcl/java_api.2.2.html
To link to MS Sql Server you would need to create the data dictionary files(DDFs) for the PSQl data files to use with relational interfaces.
Related
I'm trying to use vmware sdk for java to collect the perfomance data of each entity (cluster/datastore/Host/VM) in the vmware environment.
The idea is to get the available PerfMetricIds for the target entity with queryAvailablePerfMetric, query those and report the details of the counter, the timestamp and the value.
However when I get the PerfMetricIds for an entity, not every detected (returned) PerfMetricId is reporting data. For example for each Datastore I get at least 4 ids which do not return data when queried, these IDs represent the counters associated with the average number of read and write operations, and for a cluster I'm missing the cpu usage, and so on ...
so I was wondering when does this happen? Shouldn't every metric returned by queryAvailablePerfMetric report data? what am I missing here?
Minimal code snippet:
// VMWare credentials
String vmwareUrl = args[0];
String vmwareUsername = args[1];
String vmwarePassword = args[2];
// connect to vCenter
ServiceInstance si = new ServiceInstance(new URL(vmwareUrl), vmwareUsername, vmwarePassword, true);
// get performance manager
PerformanceManager perfMgr = si.getPerformanceManager();
// define the time window (the last one hour)
Calendar calTo = Calendar.getInstance();
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(calTo.getTime());
calFrom.add(Calendar.HOUR, -1);
// get any datastore for testing purposes
Folder rootFolder = si.getRootFolder();
ManagedEntity[] datastores = new InventoryNavigator(rootFolder).searchManagedEntities("Datastore");
ManagedEntity me = datastores[1];
// query all available metrics for the entity
PerfMetricId[] availablePmis = perfMgr.queryAvailablePerfMetric(me, calFrom, calTo, perfMgr.getHistoricalInterval()[0].getSamplingPeriod());
// create PerfQuerySpec
PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(me.getMOR());
qSpec.setMetricId(availablePmis);
qSpec.setFormat("csv");
qSpec.setStartTime(calFrom);
qSpec.setEndTime(calTo);
// query perf
PerfEntityMetricBase[] perfValues = perfMgr.queryPerf(new PerfQuerySpec[]{qSpec});
// Printing
System.out.println("Found pmis (CounterIDs only): ");
for (PerfMetricId pmi : availablePmis){
System.out.print(pmi.getCounterId() + ", ");
}
System.out.print("\nPmis with values:");
int pmisCount=0;
for (PerfEntityMetricBase value : perfValues) {
PerfMetricSeriesCSV[] csvValues = ((PerfEntityMetricCSV) value).getValue();
pmisCount += csvValues.length;;
for (PerfMetricSeriesCSV csv : csvValues) {
System.out.println("Counter ID: " + csv.getId().getCounterId() + " ---- Metric instance: " + csv.getId().getInstance());
System.out.println("\tInfo: " + ((PerfEntityMetricCSV) value).getSampleInfoCSV());
System.out.println("\tValues: " + csv.getValue());
}
}
System.out.println("---------------");
System.out.println("Detected PMIs: " + availablePmis.length);
System.out.println("PMIs with values: " + pmisCount);
Any help (or discussions) would be appreciated
I downloaded a lot of blockchain data using https://bitcoin.org, I took some file and I try to analyse it with bitcoinj library.
I would like to get information from every transaction:
-who send bitcoins,
-how much,
-who receive bitcoins.
I use:
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.15.10</version>
</dependency>
I have a code:
NetworkParameters np = new MainNetParams();
Context.getOrCreate(MainNetParams.get());
BlockFileLoader loader = new BlockFileLoader(np,List.of(new File("test/resources/blk00450.dat")));
for (Block block : loader) {
for (Transaction tx : block.getTransactions()) {
System.out.println("Transaction ID" + tx.getTxId().toString());
for (TransactionInput ti : tx.getInputs()) {
// how to get wallet addresses of inputs?
}
// this code works for 99% of transactions but for some throws exceptions
for (TransactionOutput to : tx.getOutputs()) {
// sometimes this line throws: org.bitcoinj.script.ScriptException: Cannot cast this script to an address
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
System.out.println("out value:" + to.getValue().toString());
}
}
}
Can you share some snippet that will work for all transactions in the blockchain?
There are at least two type of transaction, P2PKH and P2SH.
Your code would work well with P2PKH, but wouldn not work with P2SH.
You can change the line from:
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
to:
System.out.println("out address:" + to.getAddressFromP2PKHScript(np)!=null?to.getAddressFromP2PKHScript(np):to.getAddressFromP2SH(np));
The API of Bitcoin says the methods getAddressFromP2PKHScript() and getAddressFromP2SH() are deprecated, and I have not find suitable method.
However, P2SH means "Pay to Script Hash", which means it could contain two or more public keys to support multi-signature. Moreover, getAddressFromP2SH() returns only one address, perhaps this is the reason why it is deprecated.
I also wrote a convinient method to check the inputs and outputs of a block:
private void printCoinValueInOut(Block block) {
Coin blockInputSum = Coin.ZERO;
Coin blockOutputSum = Coin.ZERO;
System.out.println("--------------------Block["+block.getHashAsString()+"]------"+block.getPrevBlockHash()+"------------------------");
for(Transaction tx : block.getTransactions()) {
Coin txInputSum = tx.getOutputSum();
Coin txOutputSum = tx.getOutputSum();
blockInputSum = blockInputSum.add(txInputSum);
blockOutputSum = blockOutputSum.add(txOutputSum);
System.out.println("Tx["+tx.getTxId()+"]:\t" + txInputSum + "(satoshi) IN, " + txOutputSum + "(satoshi) OUT.");
}
System.out.println("Block total:\t" + blockInputSum + "(satoshi) IN, " + blockOutputSum + "(satoshi) OUT. \n");
}
I use fabrc-sdk-java to operate the e2e_cli network.The e2e uses CA and the TLS is disabled.
I successfully create the channel and install the chaincode.
create channel:
Channel newChannel = client.newChannel(myChannel.getChannelName(), orderer, channelConfiguration, channelConfigurationSignatures.toArray(new byte[myPeerOrgs.size()][]));
channelConfigurationSignatures contains signatures from two organizations.
install chaincode:
Every organization has to send an installation proposal once, using its own peerAdmin organization.
reference:https://github.com/IBM/blockchain-application-using-fabric-java-sdk
But,when I prepare to instantiate chaincode,I get the error:
0endorser failed with Sending proposal to peer0.org1.example.com failed because of: gRPC failure=Status{code=UNKNOWN, description=Failed to deserialize creator identity, err MSP Org1 is unknown, cause=null}. Was verified:false
These are related codes:
client.setUserContext(myPeerOrgs.get(0).getPeerAdmin());
InstantiateProposalRequest instantiateProposalRequest = client.newInstantiationProposalRequest();
instantiateProposalRequest.setProposalWaitTime(fabricConfig.getProposalWaitTime());
instantiateProposalRequest.setChaincodeID(chaincodeID);
instantiateProposalRequest.setFcn(ininFun);
instantiateProposalRequest.setArgs(args);
Map<String, byte[]> tm = new HashMap<>();
tm.put("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".getBytes(UTF_8));
tm.put("method", "InstantiateProposalRequest".getBytes(UTF_8));
instantiateProposalRequest.setTransientMap(tm);
ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
chaincodeEndorsementPolicy.fromYamlFile(new File(myChaincode.getChaincodeEndorsementPolicyPath()));
instantiateProposalRequest.setChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);
logger.trace("Sending instantiateProposalRequest to all peers with arguments: " + Arrays.toString(args));
Collection<ProposalResponse> successful = new LinkedList<>();
Collection<ProposalResponse> failed = new LinkedList<>();
Collection<ProposalResponse> responses = channel.sendInstantiationProposal(instantiateProposalRequest);
for (ProposalResponse response : responses) {
if (response.isVerified() && response.getStatus() == ProposalResponse.Status.SUCCESS) {
successful.add(response);
logger.trace(String.format("Succesful instantiate proposal response Txid: %s from peer %s", response.getTransactionID(), response.getPeer().getName()));
} else {
failed.add(response);
}
}
logger.trace(String.format("Received %d instantiate proposal responses. Successful+verified: %d . Failed: %d", responses.size(), successful.size(), failed.size()));
if (failed.size() > 0) {
ProposalResponse first = failed.iterator().next();
logger.error("Not enough endorsers for instantiate :" + successful.size() + "endorser failed with " + first.getMessage() + ". Was verified:" + first.isVerified());
System.exit(1);
}
I thought it was a serialization problem,but the MyUser class and the MyEnrollement class both inherit the Serializable interface, and both define the serialVersionUID.
I have compared blockchain-application-using-fabric-java-sdk and have not identified the problem.
I finally solved this problem.The problem is in the following code:
Channel newChannel = client.newChannel(myChannel.getChannelName(), orderer, channelConfiguration, channelConfigurationSignatures.toArray(new byte[myPeerOrgs.size()][]));
The above code is written by me with reference to End2endIT:
//Create channel that has only one signer that is this orgs peer admin. If channel creation policy needed more signature they would need to be added too.
Channel newChannel = client.newChannel(name, anOrderer, channelConfiguration, client.getChannelConfigurationSignature(channelConfiguration, sampleOrg.getPeerAdmin()));
I don't know if it is wrong with my usage.But my code, the error is in this sentence, when joining the node later, the error is reported.
I referenced https://github.com/IBM/blockchain-application-using-fabric-java-sdk/blob/master/java/src/main/java/org/app/network/CreateChannel.java and found the correct way of writing.
public Channel createChannel() {
logger.info("Begin create channel: " + myChannel.getChannelName());
ChannelConfiguration channelConfiguration = new ChannelConfiguration(new File(fabricConfig.getChannelArtifactsPath() + "/" + myChannel.getChannelName() + ".tx"));
logger.trace("Read channel " + myChannel.getChannelName() + " configuration file:" + fabricConfig.getChannelArtifactsPath() + "/" + myChannel.getChannelName() + ".tx");
byte[] channelConfigurationSignatures = client.getChannelConfigurationSignature(channelConfiguration, myPeerOrgs.get(0).getPeerAdmin());
Channel newChannel = client.newChannel(myChannel.getChannelName(), orderer, channelConfiguration, channelConfigurationSignatures);;
for (Peer peer : myPeerOrgs.get(0).getPeers()) {
// create a channel for the first time, only `joinPeer` here, not `addPeer`
newChannel.joinPeer(peer);
}
for (EventHub eventHub : myPeerOrgs.get(0).getEventHubs()) {
newChannel.addEventHub(eventHub);
}
if (!newChannel.isInitialized()) {
newChannel.initialize();
}
// I have only tested two organizations
// I don’t know if there are any errors in the three organizations.
for (int i = 1; i < myPeerOrgs.size(); i++) {
client.setUserContext(myPeerOrgs.get(i).getPeerAdmin());
newChannel = client.getChannel(myChannel.getChannelName());
for (Peer peer : myPeerOrgs.get(i).getPeers()) {
newChannel.joinPeer(peer);
}
for (EventHub eventHub : myPeerOrgs.get(i).getEventHubs()) {
newChannel.addEventHub(eventHub);
}
}
logger.trace("Node that has joined the channel:");
Collection<Peer> peers = newChannel.getPeers();
for (Peer peer : peers) {
logger.trace(peer.getName() + " at " + peer.getUrl());
}
logger.info("Success, end create channel: " + myChannel.getChannelName() + "\n");
return newChannel;
}
Related code later, such as installing and initializing chaincode, also refer to https://github.com/IBM/blockchain-application-using-fabric-java-sdk. This is an excellent example.
If anyone knows how to use the fourth variable parameter of newChannel, please let me know. Thanks.
Finally, I don't know how to dynamically join nodes, organizations and channels, I am looking for and testing, there are only examples of nodejs on the network, there is no java, if anyone knows, please tell me, I really need. Thanks.
I need help. I am writing a Java FX application in Eclipse, with the use of e(fx)clipse. I am using it's generic build.fxbuild to generate the ant script needed to develop my .EXE file.
The application works perfectly in Eclipse IDE. And when packaged with a 64-bit JDK, it even works perfectly after being deployed as an .EXE.
My problem arises when I package it with a 32-bit JDK for a 32-bit install. With the 32-bit JDK, it still runs perfectly in Eclipse. When I create the .EXE, it seemingly runs fine. The problem is... the software is made to take an excel file of addresses, compare them to a sql database of addresses, and then append the excel file with recommendations of "ID"'s from the SQL database to give customer service a reference of which address (from excel) may exist in our database. The only thing the software doesn't do is the appending. But, it creates the XSSFWorkbook, and resaves the workbook and opens it. So it's getting the beginning code of this segment, as well as the end. But something is happening in the middle for 32-bit vs 64-bit.
Need help!
public static void writeMatchedRecords(XSSFWorkbook wb, HashMap<Integer, ExcelAddress> excelRecords,
HeaderTemplate template) {
if (Defaults.DEBUG) {
System.out.println("Writing " + excelRecords.size() + " excel records");
}
// Variable to allow writing to excel file
CreationHelper createHelper = wb.getCreationHelper();
// Iterate through every row of the excel sheet
for (Row row : wb.getSheetAt(0)) {
if (excelRecords.containsKey(row.getRowNum() + 1)) {
ExcelAddress excelTemp = excelRecords.get(row.getRowNum() + 1);
HashMap<Double, ArrayList<ShipTo>> matchedShipTos = excelTemp.getMatchedShipTos();
if (Defaults.DEBUG) {
System.out.print(row.getCell(template.getColName()) + " from Excel matches with " + excelTemp.getName() + " from HASH with " + matchedShipTos.size() + " matches.");
}
if (matchedShipTos.isEmpty() == false) {
if (Defaults.DEBUG) {
System.out.println(" (non-zero confirmed)");
}
// If Matched Ship contains 100% matches remove all other
// matches
if (matchedShipTos.containsKey(1d)) {
HashMap<Double, ArrayList<ShipTo>> tempHM = new HashMap<Double, ArrayList<ShipTo>>();
tempHM.put(1d, matchedShipTos.get(1d));
matchedShipTos.clear();
matchedShipTos.putAll(tempHM);
}
Map<Double, ArrayList<ShipTo>> sortedShipTos = new TreeMap<Double, ArrayList<ShipTo>>(matchedShipTos).descendingMap();
for (Map.Entry<Double, ArrayList<ShipTo>> entry : sortedShipTos.entrySet()) {
for (ShipTo shipTo : entry.getValue()) {
if (Defaults.DEBUG) {
System.out.print("Ship to Match: ");
System.out.print(shipTo.getName());
System.out.print(" P: " + entry.getKey() + "\n");
}
if (row.getLastCellNum() == wb.getSheetAt(0).getRow(0).getLastCellNum()) {
// Create additional headers
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString("Probability"));
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum() + 1)
.setCellValue(createHelper.createRichTextString("P21 - Ship to ID"));
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum() + 2)
.setCellValue(createHelper.createRichTextString("P21 - Ship to Name"));
wb.getSheetAt(0).getRow(0).createCell(row.getLastCellNum() + 3).setCellValue(
createHelper.createRichTextString("P21 - Ship to Address Line 1"));
}
row.createCell(row.getLastCellNum()).setCellValue(entry.getKey());
row.createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString(Integer.toString(shipTo.getId())));
row.createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString(shipTo.getName()));
row.createCell(row.getLastCellNum())
.setCellValue(createHelper.createRichTextString(shipTo.getAddress1()));
}
}
}
}
}
Date date = new Date();
int rand = (int) (Math.random() * 10);
File file = new File(System.getProperty("user.home") + "/Desktop/"
+ String.format("%1$s %2$tF%3$s", template.getTemplateName(), date, " (" + rand + ").xlsx"));
try
{
FileOutputStream fileout = new FileOutputStream(file);
wb.write(fileout);
fileout.close();
Desktop.getDesktop().open(file);
} catch (
Exception e)
{
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
I got a similar problem with SWT
The general problem is when you need some native functions (like screen system), which depend on a particular jar.
related discussions about FX:
Creating 32 bit JavaFx Native Bundle in 64 bit machine
https://github.com/javafx-maven-plugin/javafx-maven-plugin/issues/81
Does JavaFX work in 32-bit Windows? (or with a 32-bit JVM)?
My way:
1 find the JAR
Finding javafx jar file for windows
2 embark the 2 jars in you app
3 at runtime, check 32/64
Properties prop=java.lang.System.getProperties();
String 32_64=prop.getProperty("sun.arch.data.model");
// => 32 or 64
4 load the "good" jar at runtime (check before is already loaded)
How should I load Jars dynamically at runtime?
This question already has an answer here:
Closed 12 years ago.
Possible Duplicate:
Why do the outputs differ when I run this code using NetBeans 6.8 and Eclipse?
When I am running the following code using Eclipse and NetBeans 6.8. I want to see the available COM ports on my computer. When running in Eclipse it is returning me all available COM ports, but when running it in NetBeans, it does not seem to find any ports ..
public static void test() {
Enumeration lists=CommPortIdentifier.getPortIdentifiers();
System.out.println(lists.hasMoreElements());
while (lists.hasMoreElements()) {
CommPortIdentifier cn =
(CommPortIdentifier)lists.nextElement();
if ((CommPortIdentifier.PORT_SERIAL==cn.getPortType())) {
System.out.println(
"Name is serail portzzzz " +
cn.getName()+
" Owned status " +
cn.isCurrentlyOwned());
try {
SerialPort port1=(SerialPort)cn.open("ComControl",800000);
port1.setSerialPortParams(
9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
System.out.println("Before get stream");
OutputStream out=port1.getOutputStream();
InputStream input=port1.getInputStream();
System.out.println("Before write");
out.write("AT".getBytes());
System.out.println("After write");
int sample=0;
//while((( sample=input.read())!=-1)){
System.out.println("Before read");
//System.out.println(input.read() + "TEsting ");
//}
System.out.println("After read");
System.out.println(
"Receive timeout is " +
port1.getReceiveTimeout());
}
catch(Exception e) {
System.err.println(e.getMessage());
}
}
else {
System.out.println(
"Name is parallel portzzzz " +
cn.getName() +
" Owned status " +
cn.isCurrentlyOwned() +
cn.getPortType() +
" ");
}
}
}
Output with Netbeans,
false
Output using Eclipse,
true
Name is serail portzzzz COM1 Owned status false
Before get stream
Before write
After write
Before read
After read
Receive timeout is -1
Name is serail portzzzz COM2 Owned status false
Before get stream
Before write
After write
Before read
After read
Receive timeout is -1
Name is parallel portzzzz LPT1 Owned status false2
Name is parallel portzzzz LPT2 Owned status false2
An initial guess would be that the library you use use native code enclosed in a DLL and that code cannot be found giving an error earlier you have missed, and the code falls back to a dummy behaviour.
I would have a closer look at the initialization code to see what happens there.