Java Properties.getProperty() with an Array of Objects - java

I have a configuration file formatted as this,
object1=1
object2=2
object3=3
array={
sub_object1=sub_1
sub_object2=sub_2
sub_object3=sub_3
}
object4=4
object5=5
I have been trying to process this with Properties.getProperty, but am unable to find an effective method to process the array.
try {
Properties props = new Properties();
props.load( new FileInputStream( "settings.conf" ) );
if( !props.isEmpty() )
{
props.stringPropertyNames().stream().forEach((key) ->
{
if( !key.equals( "array" ) )
{
List<Object> subkeys = props.list();
for( subkeys: subkey ) )
{
System.out.println( "Subkey: " + props.getProperty( subkey ) );
}
}
});
}
} catch ( Exception e ) {
e.printStackTrace();
}
I realize the above is errorous, but I have been unable to find a solution. Any one have an idea?

Related

mapstruct does not set relationship properly on a bi-directional OneToMany

I have a JPA one to many bi-directional association. In my code i set the relationship on both side. But the generated mapstruct code seems not setting the relationship properly. I mean it is setting on one side.
I pasted part of my code. The line which i commented is added manually by me.
It should have been generated by mapstruct
derivativeFuture.setDerivativeExecutions( derivativeExecutionDTOSetToDerivativeExecutionSet( derivativeDTO.getDerivativeExecutions() ) );
//derivativeFuture.getDerivativeExecutions().forEach(derivativeExecution -> { derivativeExecution.setDerivative(derivativeFuture); });
protected Set<DerivativeExecution> derivativeExecutionDTOSetToDerivativeExecutionSet(Set<DerivativeExecutionDTO> set) {
if ( set == null ) {
return null;
}
Set<DerivativeExecution> set1 = new HashSet<DerivativeExecution>( Math.max( (int) ( set.size() / .75f ) + 1, 16 ) );
for ( DerivativeExecutionDTO derivativeExecutionDTO : set ) {
set1.add( derivativeExecutionDTOToDerivativeExecution( derivativeExecutionDTO ) );
}
return set1;
}
protected DerivativeExecution derivativeExecutionDTOToDerivativeExecution(DerivativeExecutionDTO derivativeExecutionDTO) {
if ( derivativeExecutionDTO == null ) {
return null;
}
DerivativeExecution derivativeExecution = new DerivativeExecution();
derivativeExecution.setPhysicalQuantity( derivativeExecutionDTO.getPhysicalQuantity() );
derivativeExecution.setExchangeQuantity( derivativeExecutionDTO.getExchangeQuantity() );
derivativeExecution.setPurchaseSaleIndicator( derivativeExecutionDTO.getPurchaseSaleIndicator() );
derivativeExecution.setQuotePricingStartDate( derivativeExecutionDTO.getQuotePricingStartDate() );
derivativeExecution.setQuotePricingEndDate( derivativeExecutionDTO.getQuotePricingEndDate() );
derivativeExecution.setContractExecutionId( derivativeExecutionDTO.getContractExecutionId() );
return derivativeExecution;
}
There are 2 options: adder_prefered : http://mapstruct.org/documentation/stable/reference/html/#collection-mapping-strategies or using a context: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-jpa-child-parent.

Writing a Jagged Array in HDF5 using the Java Native Library

I have tried numerous ways and followed some of the examples that are scattered around the web on how to write a jagged array (an array of arrays that may be of differing lengths) in HDF5.
Most of the examples are in C and rather low-level. Anyhow I can't seem to get it working and I just looked at the C-source code and it pretty much says that any variable-length datatypes that are not strings are not supported (if I understood correctly).
My miserable dysfunctional code (as is):
public void WIP_createVLenFloatDataSet( List<? extends Number> floats ) throws Exception
{
String group = "/test";
long groupId = createGroupIfNotExist( group );
MDataQualifier qualifier = new MDataQualifierImpl( group, "float", "0.0.0" );
long datasetId = openDataSet( qualifier );
long heapType = H5.H5Tcopy( MDataType.FLOAT_ARRAY.getHDFType() );
heapType = H5.H5Tvlen_create( heapType );
// heapType = H5.H5Tarray_create( heapType, 1, new long[]{1} );
if( !exists( datasetId ) )
{
long[] maxDims = new long[]{ HDF5Constants.H5S_UNLIMITED };
long dataspaceId = H5.H5Screate_simple( 1, new long[]{ 1 }, null );
// Create the dataset.
long datasetId1 = -1;
try
{
if( exists( m_fileId ) && exists( dataspaceId ) && exists( heapType ) )
{
long creationProperties = H5.H5Pcreate( HDF5Constants.H5P_DATASET_CREATE );
H5.H5Pset_chunk( creationProperties, /*ndims*/1, new long[]{ 1 } );
datasetId1 = H5.H5Dcreate( groupId, qualifier.getVersionedName(), heapType, dataspaceId, H5P_DEFAULT, creationProperties, H5P_DEFAULT );
// H5.H5Pclose( creationProperties );
}
}
catch( Exception e )
{
LOG.error( "Problems creating the dataset: " + e.getMessage(), e );
}
datasetId = datasetId1;
if( exists( datasetId ) )
{
// flushIfNecessary();
LOG.trace( "Wrote empty dataset {}", qualifier.getVersionedName() );
}
}
List<? extends Number> data = ( List<? extends Number> )floats;
// H5.H5Dwrite( datasetId, heapType, dataspaceId, memSpaceId, HDF5Constants.H5P_DEFAULT, Floats.toArray( data) );
ByteBuffer bb = ByteBuffer.allocate( data.size() * 4 );
floats.forEach( f -> bb.putFloat( f.floatValue() ) );
// H5.H5Dwrite( datasetId, heapType, H5S_ALL, H5S_ALL, H5P_DEFAULT, Floats.toArray( data ) );
H5.H5Dwrite( datasetId, heapType, H5S_ALL, H5S_ALL, H5P_DEFAULT, bb.array() );
}
Has anyone done this before and can at least confirm that it's not possible?
The most I can get out of HDF5 is the message "buf does not support variable length type".
Apparently the "glue code" of the JNI wrapper doesn't support this. If you want to use this feature you either have to implement your own JNI or wait for a newer version. The official JNI code is open source and can be found here.

Can you access private variables using OGNL?

Is there anyway using OGNL to access private variables that aren't exposed as a bean property (ie no get/set method pair)? I wanted to use OGNL as a faster, cleaner method of reflection for use in unit tests.
Here is my code:
#Test
public void shouldSetup() throws OgnlException{
class A{
private Object b = "foo";
private Object c = "bar";
public Object getB(){ return b; }
}
A a = new A();
System.out.println( "This'll work..." );
Ognl.getValue( "b", a );
System.out.println( "...and this'll fail..." );
Ognl.getValue( "c", a );
System.out.println( "...and we'll never get here." );
}
Actually you can. You need to set MemberAccess in OgnlContext to allow access to non public fields and use getValue(ExpressionAccessor expression, OgnlContext context, Object root) method to retrieve value.
#Test
public void shouldSetup() throws OgnlException {
class A {
private Object b = "foo";
private Object c = "bar";
public Object getB() { return b; }
}
A a = new A();
// set DefaultMemberAccess with allowed access into the context
OgnlContext context = new OgnlContext();
context.setMemberAccess(new DefaultMemberAccess(true));
System.out.println( "This'll work..." );
// use context in getValue method
Ognl.getValue( "b", context, a );
System.out.println( "...and this'll work..." );
// use context in getValue method
Ognl.getValue( "c", context, a );
System.out.println( "...and we'll get here." );
}
The best I could do was a work around using reflection directly:
static Object getValue( final String ognlPath, final Object o ){
final StringTokenizer st = new StringTokenizer( ognlPath, "." );
Object currentO = o;
String nextFieldName = null;
try{
while( st.hasMoreTokens() ){
nextFieldName = st.nextToken();
if( currentO == null ){
throw new IllegalStateException( "Cannot find field '" + nextFieldName + "' on null object." );
}
Field f = currentO.getClass().getDeclaredField( nextFieldName );
f.setAccessible( true );
currentO = f.get( currentO );
}
return currentO;
}catch( NoSuchFieldException e ){
throw new RuntimeException( "Could not find field '" + nextFieldName + "' on " + currentO.getClass().getCanonicalName(), e );
}catch( IllegalAccessException e ){
throw new RuntimeException( "Failed to get from path '" + ognlPath + "' on object: " + o, e );
}
}

Null Pointer Exception when replacing character " with no text then casting value to Float

I am writing a java program fetching JSON data through HTTP GET methods and it returns the following after I navigate the object tree:
{
"year":"2015",
"period":"M03",
"periodName":"March",
"value":"141178",
"footnotes":[{}]
}
Now I want to take value and caste it to a float, I tried to do this like such:
JSONParser parser = new JSONParser();
try
{
JSONObject
BLSemployment = ( JSONObject ) parser.parse( _RDATA );
BLSemployment = ( ( JSONObject ) BLSemployment.get( "Results" ) );
JSONArray
BLSemploymentseries = ( ( JSONArray ) BLSemployment.get( "series" ) );
BLSemployment = ( ( JSONObject ) BLSemploymentseries.get( 0 ) );
BLSemploymentseries = ( ( JSONArray ) BLSemployment.get( "data" ) );
for( int i = 0; i < 12; i++ )
{
BLSemployment = ( (JSONObject) BLSemploymentseries.get( i ) );
HistoricalNonFarmPayrollData[i] = Float.parseFloat( JSONValue.toJSONString( BLSemployment.get( "value" ) ).replace( "\"" , "" ) );
HistoricalNonFarmPayrollYear[i] = JSONValue.toJSONString( BLSemployment.get( "year" ) );
HistoricalNonFarmPayrollMonth[i] = JSONValue.toJSONString( BLSemployment.get( "periodName" ) );
}
}
catch ( ParseException pe )
{
System.out.println( pe );
}
However Now I get the error:
Exception in thread "main" java.lang.NullPointerException
at BLSFramework.getNonFarmPayrolls(playground.java:354)
at playground.main(playground.java:27)
RESOLVED: occasionally BLS website doesn't send data for periods of time and I was coding during that period of time.

Groovy/Java: Ini4j insert multiple values to single parameter in different lines

I'm trying to add multiple-values option into my ini file from Groovy using ini4j with following codes (I tried some variants):
import org.ini4j.Wini
List valuesList = [ 'val1’, ‘val2’, ‘val3' ]
( new Wini( new File( "test.ini" ) ) ).with{
valuesList.each{
put( 'sectionNa'sectionName','optionName', it)
}
store()
}
import org.ini4j.Wini
List valuesList = [ 'val1’, ‘val2’, ‘val3' ]
( new Wini( new File( "test.ini" ) ) ).with{
Section sectionObject = get( ‘sectionName’ )
sectionObject .put( 'optionName', ‘val1’ )
sectionObject .put( 'optionName', ‘val2’ )
sectionObject .put( 'optionName', ‘val3’ )
}
store()
}
I got ini file like this one:
[sectionName]
optionName = val3
But I want to get:
[sectionName]
optionName = val1
optionName = val2
optionName = val3
Could you please advice me how to resolve my issue? Thanks In Advance!
Update 1
I still waiting more elegant solution. But I created direct ini file editing below. Please provide me any feedback about it:
List newLines = []
File currentFile = new File( "test.ini" )
List currentLines = currentFile.readLines()
int indexSectionStart = currentLines.indexOf( 'sectionName' )
(0..indexSectionStart).each{
newLines.add( currentLines[ it ] )
}
List valuesList = 'val1,val2,val3'.split( ',' )
valuesList.each{
newLines.add( "optionName = $it" )
}
( indexSectionStart + 1 .. currentLines.size() - 1 ).each{
newLines.add( currentLines[ it ] )
}
File newFile = new File( "new_test.ini" )
if ( newFile.exists() ) newFile.delete()
newLines.each {
newFile.append( it+'\n' )
}
And simply delete old file and rename new one. I implemented it because I didn't find any insertLine() like methods in standart File
Right, how's this:
import org.ini4j.*
List valuesList = [ 'val1', 'val2', 'val3' ]
new File( "/tmp/test.ini" ).with { file ->
new Wini().with { ini ->
// Configure to allow multiple options
ini.config = new Config().with { it.multiOption = true ; it }
// Load the ini file
ini.load( file )
// Get or create the section
( ini.get( 'sectionName' ) ?: ini.add( 'sectionName' ) ).with { section ->
valuesList.each {
// Then ADD the options
section.add( 'optionName', it )
}
}
// And write it back out
store( file )
}
}

Categories