how to store TimeStamp into db4o database - java

I am trying to store timestamps into a db4o database, but the stored timestamps which store a few mninutes ago are much different from the current date.
Here are example outputs:
1969-12-31 19:00:00.741
1969-12-31 19:00:00.772
2012-10-14 00:23:22.713
The two previous stored timestamp was stored as 1969-12-31 19:00:00.7xx after I run my code three times.
Here is the code.
import java.sql.Timestamp;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
public class dbTest {
public static void listResults(ObjectSet<Timestamp> results) {
for (Timestamp o : results) {
System.out.println(o);
}
}
public static void main(String[] args) {
EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
config.common().objectClass(Timestamp.class).storeTransientFields(true);
ObjectContainer container = Db4oEmbedded
.openFile(config, "timestamps.db4o");
try {
long now = System.currentTimeMillis();
container.store(new Timestamp(now));
final ObjectSet<Timestamp> results = container.query(Timestamp.class);
listResults(results);
}
finally {
container.close();
}
}
}
I read the two pieces of related article below but the issue has not been solved.
article 1 and article 2
Please advise me how to solve this issue. Thanks.

The solution to this problem by adding a line:
config.common().objectClass(Timestamp.class).translate(new TSerializable());
I got help from Vidisha & Claude at db4o forum. Here I share the answer, and hope to help other as well. Here is the new code.
import java.sql.Timestamp;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
public class dbTest {
public static void listResults(ObjectSet<Timestamp> results) {
for (Timestamp o : results) {
System.out.println(o);
}
}
public static void main(String[] args) {
EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
config.common().objectClass(Timestamp.class).translate(new TSerializable());
ObjectContainer container = Db4oEmbedded
.openFile(config, "timestamps.db4o");
try {
long now = System.currentTimeMillis();
container.store(new Timestamp(now));
final ObjectSet<Timestamp> results = container.query(Timestamp.class);
listResults(results);
}
finally {
container.close();
}
}
}
You are recommanded to use JDK Date which can be handled properly by db4o.

Related

Jackcess: getTable(aName) is null while getTableNames yields aName (among others)

I am new to Jackcess (downloaded it today, version 4.0.4) and immediately running into troubles: Would anybody know, why db.getTable(aName) returns null whereas db.getTableNames() shows me that very aName among others?
Note that I am running it jointly with Apache Commons Lang 3.12.0 because I could not find Apache Commons Lang 3.10 as requested in the dependencies of Jackcess 4.0.4. But would this explain the behavior?
In the code below, "dbfile" and "tble" should still be defined according to your database. Unfortunately I cannot release my data base as it is proprietary. I am getting null from db.getTable(aName) no matter what the OPTION is. Obviously, any the code with OPTION!=1 is a work-around to find out whether the corresponding table name is within the database. When I run the code with OPTION=0, the output is:
That is it: [my table name]
Your table is null.
I would appreciate if you could share your ideas so I can make this example work.
import java.io.IOException;
import java.io.File;
import java.util.Set;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Table;
public class JackcessTrial {
private static final int OPTION = 0;
public JackcessTrial() {
super();
}
public void openSourceTable(File dbFile, String tbleName) {
Database db = null;
Table myTable = null;
try {
db = new DatabaseBuilder(dbFile).setReadOnly(true).open();
if (db==null) {
System.out.println("No database found.");
return;
}
if (OPTION==1) {
myTable = db.getTable(tbleName);
} else {
Set<String> names = db.getTableNames();
for(String name : names) {
if (name.equals(tbleName)) {
System.out.println("That is it: "+name);
myTable = db.getTable(name);
break;
}
}
}
if (myTable == null) {
System.out.println("Your table is null.");
db.close();
return;
}
System.out.println("Got your table!");
db.close();
} catch(Exception e) {
e.printStackTrace();
db = null;
}
}
public static void main(String args[]) throws IOException {
File dbfile = ...;
String tble = ...;
JackcessTrial test = new JackcessTrial();
test.openSourceTable(dbfile, tble);
}
}

Calculating physico-chemical properties of amino acids in Biojava

I need to calculate the number and percentages of polar/non-polar, aliphatic/aromatic/heterocyclic amino acids in this protein sequence that I got from UNIPROT, using BioJava.
I have found in the BioJava tutorial how to read the Fasta files and implemented this code. But I have no ideas how to solve this problem.
If you have some ideas please help me.
Maybe there are some sources where I can check it.
This is the code.
package biojava.biojava_project;
import java.net.URL;
import org.biojava.nbio.core.sequence.ProteinSequence;
import org.biojava.nbio.core.sequence.io.FastaReaderHelper;
public class BioSeq {
// Inserting the sequence from UNIPROT
public static ProteinSequence getSequenceForId(String uniProtId) throws Exception {
URL uniprotFasta = new URL(String.format("https://rest.uniprot.org/uniprotkb/P31574.fasta", uniProtId));
ProteinSequence seq = FastaReaderHelper.readFastaProteinSequence(uniprotFasta.openStream()).get(uniProtId);
System.out.printf("id : P31574", uniProtId, seq, System.getProperty("line.separator"), seq.getOriginalHeader());
System.out.println();
return seq;
}
public static void main(String[] args) {
try {
System.out.println(getSequenceForId("P31574"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I don't know if BioJava stores these properties anywhere. But it's easy to just list all the amino acids with their properties manually. Then iterate over the sequence and count those that satisfy the property. Here's an example for the polarity:
import java.io.InputStream;
import java.net.URL;
import java.util.Set;
import org.biojava.nbio.core.sequence.ProteinSequence;
import org.biojava.nbio.core.sequence.compound.AminoAcidCompound;
import org.biojava.nbio.core.sequence.io.FastaReaderHelper;
public class BioSeq {
public static void main(String[] args) throws Exception {
ProteinSequence seq = loadFromUniprot("P31574");
int polarCount = numberOfOccurrences(seq, /*Polar AAs:*/ Set.of("Y", "S", "T", "N", "Q", "C"));
System.out.println("% of polar AAs: " + ((double)polarCount)/seq.getLength());
}
public static ProteinSequence loadFromUniprot(String uniProtId) throws Exception {
URL uniprotFasta = new URL(String.format("https://rest.uniprot.org/uniprotkb/%s.fasta", uniProtId));
try (InputStream is = uniprotFasta.openStream()) {
return FastaReaderHelper.readFastaProteinSequence(is).get(uniProtId);
}
}
private static int numberOfOccurrences(ProteinSequence seq, Set<String> bases) {
int count = 0;
for (AminoAcidCompound aminoAcid : seq)
if(bases.contains(aminoAcid.getBase()))
count++;
return count;
}
}
PS: don't forget to close IO streams after you used them. In the example above I used try-with-resources syntax which automatically closes the InputStream.

Block texture load only when placed, but not in inventory

I've read some other 'similar' questions but their problems is exactly the opposite. I've also read the docs but they won't provide anything useful to this problem.
When I /give myself the block, it shows a missing texture in my inventory as a item. But when I place it, its texture is shown in the world as a block.
Screenshot:
Main mod class:
package com.byethost8.code2828.mcmods.chemc;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.block.OreBlock;
import net.minecraft.block.material.Material;
import net.minecraft.block.material.MaterialColor;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item.Properties;
import net.minecraft.item.ItemGroup;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
#Mod(CheMC_.modid)
public class CheMC_ {
public static final String modid = "chemc";
public static OreBlock ore_lithium = (OreBlock) new OreBlock(
AbstractBlock.Properties
.create(Material.ROCK, MaterialColor.PINK_TERRACOTTA)
.harvestLevel(1)
.hardnessAndResistance(1, 1)
.setLightLevel(
light -> {
return 1;
}
)
)
.setRegistryName("chemc", "lithium_ore");
public static BlockItem i_ore_lithium = (BlockItem) new BlockItem(
ore_lithium,
new Properties().group(ItemGroup.BUILDING_BLOCKS)
)
.setRegistryName(ore_lithium.getRegistryName());
public static Block block_lithium = new Block(
AbstractBlock.Properties
.create(Material.IRON, MaterialColor.PINK_TERRACOTTA)
.harvestLevel(1)
.hardnessAndResistance(1.2F, 1)
.setLightLevel(
light -> {
return 1;
}
)
)
.setRegistryName("chemc", "lithium_block");
public static BlockItem i_block_lithium = (BlockItem) new BlockItem(
block_lithium,
new Properties().group(ItemGroup.BUILDING_BLOCKS)
)
.setRegistryName(block_lithium.getRegistryName());
public CheMC_() {
FMLJavaModLoadingContext
.get()
.getModEventBus()
.addListener(this::setup);
MinecraftForge.EVENT_BUS.register(this);
}
private void setup(final FMLCommonSetupEvent event) {}
// You can use EventBusSubscriber to automatically subscribe events on the
// contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
#Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
#SubscribeEvent
public static void onBlocksRegistry(
final RegistryEvent.Register<Block> blockRegistryEvent
) {
// register a new block here
blockRegistryEvent
.getRegistry()
.registerAll(ore_lithium, block_lithium);
}
}
}
Some codes are removed to make the main problem clear.
Following texts only will say about Lithium Block, but same things apply for Lithium Ore.
Model File:
{
"parent": "block/cube_all",
"textures": {
"all": "chemc:block/lithium_block"
}
}
Folder structure of src/main/resources:
Blockstate:
{
"variants": {
"": [
{ "model": "chemc:block/lithium_block" }
]
}
}
I can't believe that I was stupid enough to register a Item and do nothing to assets/chemc/resources/models/item/ folder. See this for more. I have the exactly same problem as that OP.

How do I setup the dbFactory.newEmbeddedDatabase(File storeDir) in neo4j?

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class testingclass {
public static void main(String[] args) {
GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
GraphDatabaseService db = dbFactory.newEmbeddedDatabase(storeDir);
try (Transaction tx = db.beginTx()) {
// Perform DB operations
tx.success();
}
}
}
The method has been changed in a way that uses the storeDir variation instead of the string path variation which was explained in the tutorials which I found. I have no clue on how to initialise the storeDir parameters.

Good Zookeeper Hello world Program with Java client

I was trying to use Zookeeper in our project. Could run the server..Even test it using zkcli.sh .. All good..
But couldn't find a good tutorial for me to connect to this server using Java ! All I need in Java API is a method
public String getServiceURL ( String serviceName )
I tried https://cwiki.apache.org/confluence/display/ZOOKEEPER/Index --> Not good for me.
http://zookeeper.apache.org/doc/trunk/javaExample.html : Sort of ok; but couldnt understand concepts clearly ! I feel it is not explained well..
Finally, this is the simplest and most basic program I came up with which will help you with ZooKeeper "Getting Started":
package core.framework.zookeeper;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
public class ZkConnect {
private ZooKeeper zk;
private CountDownLatch connSignal = new CountDownLatch(0);
//host should be 127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002
public ZooKeeper connect(String host) throws Exception {
zk = new ZooKeeper(host, 3000, new Watcher() {
public void process(WatchedEvent event) {
if (event.getState() == KeeperState.SyncConnected) {
connSignal.countDown();
}
}
});
connSignal.await();
return zk;
}
public void close() throws InterruptedException {
zk.close();
}
public void createNode(String path, byte[] data) throws Exception
{
zk.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public void updateNode(String path, byte[] data) throws Exception
{
zk.setData(path, data, zk.exists(path, true).getVersion());
}
public void deleteNode(String path) throws Exception
{
zk.delete(path, zk.exists(path, true).getVersion());
}
public static void main (String args[]) throws Exception
{
ZkConnect connector = new ZkConnect();
ZooKeeper zk = connector.connect("54.169.132.0,52.74.51.0");
String newNode = "/deepakDate"+new Date();
connector.createNode(newNode, new Date().toString().getBytes());
List<String> zNodes = zk.getChildren("/", true);
for (String zNode: zNodes)
{
System.out.println("ChildrenNode " + zNode);
}
byte[] data = zk.getData(newNode, true, zk.exists(newNode, true));
System.out.println("GetData before setting");
for ( byte dataPoint : data)
{
System.out.print ((char)dataPoint);
}
System.out.println("GetData after setting");
connector.updateNode(newNode, "Modified data".getBytes());
data = zk.getData(newNode, true, zk.exists(newNode, true));
for ( byte dataPoint : data)
{
System.out.print ((char)dataPoint);
}
connector.deleteNode(newNode);
}
}
This post has almost all operations required to interact with Zookeeper.
https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
Create ZNode with data
Delete ZNode
Get list of ZNodes(Children)
Check an ZNode exists or not
Edit the content of a ZNode...
This blog post, Zookeeper Java API examples, includes some good examples if you are looking for Java examples to start with. Zookeeper also provides a client API library( C and Java) that is very easy to use.
Zookeeper is one of the best open source server and service that helps to reliably coordinates distributed processes. Zookeeper is a CP system (Refer CAP Theorem) that provides Consistency and Partition tolerance. Replication of Zookeeper state across all the nods makes it an eventually consistent distributed service.
This is about as simple as you can get. I am building a tool which will use ZK to lock files that are being processed (hence the class name):
package mypackage;
import java.io.IOException;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher;
public class ZooKeeperFileLock {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
String zkConnString = "<zknode1>:2181,<zknode2>:2181,<zknode3>:2181";
ZooKeeperWatcher zkWatcher = new ZooKeeperWatcher();
ZooKeeper client = new ZooKeeper(zkConnString, 10000, zkWatcher);
List<String> zkNodes = client.getChildren("/", true);
for(String node : zkNodes) {
System.out.println(node);
}
}
public static class ZooKeeperWatcher implements Watcher {
#Override
public void process(WatchedEvent event) {
}
}
If you are on AWS; now We can create internal ELB which supports redirection based on URI .. which can really solve this problem with High Availability already baked in.

Categories

Resources