Subversion Repository Public Repository

litesoft

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// This Source Code is in the Public Domain per: http://unlicense.org
package org.litesoft.orsup;

import org.litesoft.commonfoundation.base.*;
import org.litesoft.commonfoundation.csv.*;
import org.litesoft.commonfoundation.exceptions.*;
import org.litesoft.commonfoundation.typeutils.*;
import org.litesoft.core.simpletypes.temporal.*;
import org.litesoft.core.util.*;
import org.litesoft.logger.*;
import org.litesoft.orsup.base.*;
import org.litesoft.orsup.nonpublic.*;
import org.litesoft.orsup.otherattributeaccessors.*;
import org.litesoft.orsup.transact.*;
import org.litesoft.server.file.*;
import org.litesoft.util.*;

import java.io.*;
import java.lang.reflect.*;
import java.util.*;

public class DB_ImportSupport {
    public static final String TODAY_RELATIVE = ":T";
    public static final String DELTA_DATE_RELATIVE = ":DD";
    public static final String DELTA_DATE_SEP = "+T-";
    public static final String FILE_ATTRIBUTE = "@";
    public static final String SETTER_ATTRIBUTE = "()";
    public static final String PO_URL_ATTRIBUTE = ":";

    protected static class ImportFromMap {
        public void process( Logger pLogger, UnfilteringFinder pFinder, File pReferenceDir, Map<FauxPOref, Attributes> pLineMap )
                throws IOException {
            if ( pLineMap.isEmpty() ) {
                throw new IllegalArgumentException( "No Data Found" );
            }
            new Inner( pLogger, pFinder.createUnaugmentedTransaction(), pReferenceDir, pLineMap ).process().commit();
        }

        private class Inner {
            private Logger mLogger;
            private Transaction mTransaction;
            private File mReferenceDir;
            private Map<FauxPOref, Attributes> mLineMap;
            private Map<FauxPOref, PersistentObject<?>> mPOsByRef = new HashMap<FauxPOref, PersistentObject<?>>();

            private Inner( Logger pLogger, Transaction pTransaction, File pReferenceDir, Map<FauxPOref, Attributes> pLineMap ) {
                mLogger = pLogger;
                mTransaction = pTransaction;
                mReferenceDir = pReferenceDir;
                mLineMap = pLineMap;
            }

            public Transaction process() {
                for ( FauxPOref ref : mLineMap.keySet() ) {
                    putLineInDB( ref );
                }
                return mTransaction;
            }

            private PersistentObject<?> putLineInDB( FauxPOref pPOref ) {
                PersistentObject<?> zPO = mPOsByRef.get( pPOref );
                if ( zPO == null ) // NOT Already created
                {
                    mPOsByRef.put( pPOref, zPO = mTransaction.create( pPOref.getPersistedObjectRegistrationName() ) );

                    Attributes attributes = mLineMap.get( pPOref );
                    if ( attributes == null ) {
                        throw new IllegalArgumentException( "No Attributes (Line) found for URL: " + pPOref );
                    }
                    mLogger.trace.log( "writing line to db for URL: ", pPOref );

                    for ( String attrName : attributes.getNames() ) {
                        String value = attributes.getValue( attrName );

                        // If the attribute is calling a setter method ..
                        if ( attrName.endsWith( SETTER_ATTRIBUTE ) ) {
                            try {
                                String methodName = attrName.substring( 0, attrName.length() - SETTER_ATTRIBUTE.length() );
                                Method method = zPO.getClass().getMethod( methodName, String.class );
                                if ( method != null ) {
                                    method.invoke( zPO, value );
                                }
                            }
                            catch ( InvocationTargetException e ) {
                                throw new RuntimeException( e );
                            }
                            catch ( NoSuchMethodException e ) {
                                throw new RuntimeException( e );
                            }
                            catch ( IllegalAccessException e ) {
                                throw new RuntimeException( e );
                            }
                            // Setter methods aren't actual attributes, so skip the rest of the iteration.
                            continue;
                        }

                        boolean isURLAttribute = false;
                        if ( attrName.endsWith( PO_URL_ATTRIBUTE ) ) {
                            attrName = attrName.substring( 0, attrName.length() - PO_URL_ATTRIBUTE.length() );
                            isURLAttribute = true;
                        }
                        if ( attrName.endsWith( FILE_ATTRIBUTE ) ) {
                            attrName = attrName.substring( 0, attrName.length() - FILE_ATTRIBUTE.length() );
                            value = readFileAttributeValue( value );
                        }

                        AttributeAccessorSCD scd = zPO.getMetaDataForPO().getAccessorSCDoptional( attrName );
                        if ( scd == null ) {
                            throw new IllegalArgumentException( zPO.getObjectName() + " does NOT appear to have an attribute named: '" + attrName + "'" );
                        }
                        if ( !(scd instanceof NonImportableFeature) ) {
                            Object setValue = value;
                            if ( AttributeAccessorSCD.Form.ToOne == scd.getForm() ) {
                                if ( scd instanceof AttributeAccessorSCDtoOneVariable ) {
                                    PO_VarURLstringHelper zVarURL = new PO_VarURLstringHelper( value );
                                    FauxPOref childRef = new FauxPOref( mTransaction, zVarURL.getPersistentObjectURL() );
                                    PersistentObject<?> po = putLineInDB( childRef );
                                    setValue = new PO_VarURLstringHelper( zVarURL.getPersistedObjectAttributeName(), po.getPersistentObjectURL().toString() );
                                } else {
                                    FauxPOref childRef = new FauxPOref( mTransaction, value );
                                    setValue = putLineInDB( childRef );
                                }
                            } else if ( looksLikeAReference( scd, value ) ) {
                                // support quasi-foreign keys.
                                FauxPOref childRef = new FauxPOref( mTransaction, value );
                                setValue = putLineInDB( childRef );
                                PersistentObject po = (PersistentObject) setValue;
                                try {
                                    setValue = po.getPersistentObjectUniqueKey();
                                }
                                catch ( Exception e ) {
                                    e.printStackTrace();
                                }
                            } else if ( isURLAttribute ) {
                                FauxPOref childRef = new FauxPOref( mTransaction, value );
                                setValue = putLineInDB( childRef ).getPersistentObjectURL().toString();
                            }
                            zPO.setAttributeValue( attrName, setValue );
                        }
                    }
                }
                return zPO;
            }

            private boolean looksLikeAReference( AttributeAccessorSCD pScd, String pValue ) {
                if ( !(pScd.getColumnType().equals( Long.class )) ) {
                    return false;
                }
                try {
                    new FauxPOref( mTransaction, pValue );
                    return true;
                }
                catch ( Exception e ) {
                    return false;
                }
            }

            private String readFileAttributeValue( String fileReference ) {
                if ( fileReference.startsWith( "file:" ) ) {
                    fileReference = fileReference.substring( "file:".length() );
                }

                File f;
                if ( null != mReferenceDir ) {
                    f = new File( mReferenceDir, fileReference );
                } else {
                    f = new File( fileReference );
                }

                return FileUtils.loadTextFileAsString( f, "\n" );
            }
        }
    }

    protected static class ImportToMap {
        private Map<FauxPOref, Attributes> mLineMap = new HashMap<FauxPOref, Attributes>();

        public ImportToMap process( Logger pLogger, Finder pFinder, Reader[] pReaders )
                throws IOException {
            if ( Currently.isNullOrEmpty( pReaders ) ) {
                throw new IllegalArgumentException( "No Readers provided" );
            }
            try {
                new Inner( pLogger, pFinder ).process( pReaders );
            }
            finally {
                for ( Reader reader : pReaders ) {
                    try {
                        reader.close();
                    }
                    catch ( IOException e ) {
                        // Whatever!
                    }
                }
            }

            return this;
        }

        public Map<FauxPOref, Attributes> getLineMap() {
            return mLineMap;
        }

        private class Inner {
            private Logger mLogger;
            private Finder mFinder;
            private StringBuilder mBuilder;

            private Inner( Logger pLogger, Finder pFinder ) {
                mLogger = pLogger;
                mFinder = pFinder;
            }

            public void process( Reader[] pReaders )
                    throws IOException {
                if ( pReaders[0] instanceof ToStringInformative ) {
                    mLogger.info.log( "Importing:" );
                }
                for ( Reader reader : pReaders ) {
                    if ( reader instanceof ToStringInformative ) {
                        mLogger.info.log( "    ", reader );
                    }
                    BufferedReader bufRead = Utils.getBufferedReader( reader );
                    mBuilder = new StringBuilder();
                    for ( String line; null != (line = bufRead.readLine()); ) {
                        putLineInMap( line );
                    }
                    if ( mBuilder.length() != 0 ) {
                        throw new UnclosedQuoteException( " did not find end of line " + mBuilder );
                    }
                }
            }

            private void putLineInMap( String pLine ) {
                if ( mBuilder.length() == 0 ) {
                    pLine = pLine.trim();
                    if ( (pLine.length() == 0) || (pLine.charAt( 0 ) == ';') || (pLine.charAt( 0 ) == '#') || pLine.startsWith( "//" ) ) {
                        return;
                    }
                }
                mBuilder.append( pLine );
                try {
                    putBuilderInMap();
                    mBuilder.setLength( 0 );
                }
                catch ( UnclosedQuoteException e ) {
                    mBuilder.append( "\n" );
                }
            }

            private void putBuilderInMap() {
                String[] decodedData = new CsvSupport().decode( mBuilder.toString() );
                FauxPOref ref = new FauxPOref( mFinder, decodedData[0] );
                if ( mFinder.getMetaDataRequired( ref.getPersistedObjectRegistrationName() ).isImportable() ) {
                    Attributes attributes = parseData( decodedData );
                    if ( !attributes.isEmpty() ) {
                        mLineMap.put( ref, attributes );
                    }
                }
            }

            private Attributes parseData( String[] pDecodedData ) {
                Attributes zAttributes = new Attributes();
                for ( int i = 1; i < pDecodedData.length; ++i ) {
                    String pair = ConstrainTo.significantOrNull( pDecodedData[i] );
                    if ( pair != null ) {
                        int equidx = pair.indexOf( '=' );
                        if ( equidx == -1 ) {
                            throw new IllegalStateException( "No '=' in: " + pair );
                        }
                        String attr = pair.substring( 0, equidx ).trim();
                        String value = pair.substring( equidx + 1 ).trim();
                        zAttributes.setNameValue( attr, value );
                    }
                }
                return zAttributes;
            }
        }
    }

    protected static class FauxPOref {
        public static int sWildcardSequence = 0;

        private MetaDataForPO mPOmd;
        private String mIdentifier;

        public FauxPOref( Finder pFinder, String pToString ) {
            PO_URLstringHelper helper = new PO_URLstringHelper( pToString );
            String zIdentifierOrRegistrationName = helper.getPersistedObjectRegistrationName();
            MetaDataForPO zMD = pFinder.getMetaDataOptionallyByIdentifier( zIdentifierOrRegistrationName );
            mPOmd = (zMD != null) ? zMD : pFinder.getMetaDataRequired( zIdentifierOrRegistrationName );
            mIdentifier = helper.getPersistentObjectUniqueKey();
            if ( "?".equals( mIdentifier ) ) {
                mIdentifier = "gened-" + ++sWildcardSequence;
            }
        }

        public MetaDataForPO getPOmd() {
            return mPOmd;
        }

        public String getPersistedObjectRegistrationName() {
            return mPOmd.getPOregistrationName();
        }

        public String getIdentifier() {
            return mIdentifier;
        }

        @Override
        public boolean equals( Object o ) {
            return (this == o) || ((o instanceof FauxPOref) && equals( (FauxPOref) o ));
        }

        public boolean equals( FauxPOref them ) {
            return (this == them) || //
                   ((them != null) //
                    && (this.mPOmd == them.mPOmd) //
                    && this.mIdentifier.equals( them.mIdentifier ) //
                   );
        }

        @Override
        public int hashCode() {
            return 31 * getPersistedObjectRegistrationName().hashCode() + mIdentifier.hashCode();
        }

        @Override
        public String toString() {
            return new PO_URLstringHelper( getPersistedObjectRegistrationName(), mIdentifier ).toString();
        }
    }

    protected static class Attributes {
        private Map<String, String> mNameValues = new HashMap<String, String>();

        public boolean isEmpty() {
            return mNameValues.isEmpty();
        }

        public String[] getNames() {
            return mNameValues.keySet().toArray( new String[mNameValues.size()] );
        }

        public String getValue( String pName ) {
            return mNameValues.get( pName );
        }

        public void setNameValue( String pName, String pValue ) {
            if ( pName.endsWith( TODAY_RELATIVE ) ) {
                pName = pName.substring( 0, pName.length() - TODAY_RELATIVE.length() ).trim();
                pValue = makeTodayRelative( pValue );
            } else if ( pName.endsWith( DELTA_DATE_RELATIVE ) ) {
                pName = pName.substring( 0, pName.length() - DELTA_DATE_RELATIVE.length() ).trim();
                pValue = makeDeltaDateRelative( pValue );
            }
            if ( pName.length() != 0 ) {
                String curValue = (pValue.length() == 0) ? mNameValues.get( pName ) : mNameValues.put( pName, pValue );
                if ( curValue != null ) {
                    throw new IllegalArgumentException( "Duplicate Attribute for: " + pName );
                }
            }
        }

        private String makeTodayRelative( String pValue ) {
            boolean zAdd;
            switch ( (pValue = pValue + " ").charAt( 0 ) ) {
                case '+':
                    zAdd = true;
                    break;
                case '-':
                    zAdd = false;
                    break;
                default:
                    throw new IllegalArgumentException( "Neither a '+' nor a '-' after '" + TODAY_RELATIVE + "='" );
            }
            String zYears, zMonths, zDays;
            String[] zParts = Strings.parseChar( pValue.substring( 1 ).trim(), '/' );
            switch ( zParts.length ) {
                case 3:
                    zYears = zParts[0];
                    zMonths = zParts[1];
                    zDays = zParts[2];
                    break;
                case 2:
                    zYears = "";
                    zMonths = zParts[0];
                    zDays = zParts[1];
                    break;
                case 1:
                    zYears = zMonths = "";
                    zDays = zParts[0];
                    break;
                default:
                    throw new IllegalArgumentException( "Too many '/'s after '" + TODAY_RELATIVE + "='" );
            }
            int iYears = parseInt( "Year", zYears );
            int iMonths = parseInt( "Month", zMonths );
            int iDays = parseInt( "Day", zDays );

            CalendarYMD zDesiredDate = CalendarYMD.today();

            if ( zAdd ) {
                zDesiredDate = zDesiredDate.addYears( iYears );
                zDesiredDate = zDesiredDate.addMonths( iMonths );
                zDesiredDate = zDesiredDate.addDays( iDays );
            } else {
                zDesiredDate = zDesiredDate.minusYears( iYears );
                zDesiredDate = zDesiredDate.minusMonths( iMonths );
                zDesiredDate = zDesiredDate.minusDays( iDays );
            }

            return zDesiredDate.toSQLvalue();
        }

        private String makeDeltaDateRelative( String pValue ) {
            int zAt = pValue.indexOf( DELTA_DATE_SEP );
            if ( zAt == -1 ) {
                throw new IllegalArgumentException( "No Delta Date Sep '" + DELTA_DATE_SEP + "'" );
            }
            CalendarYMD zDesiredDate = to_CalendarYMD( "Desired Date", pValue.substring( 0, zAt ) );
            CalendarYMD zDeltaDate = to_CalendarYMD( "Delta Date", pValue.substring( zAt + DELTA_DATE_SEP.length() ) );
            CalendarYMD zToday = CalendarYMD.today();
            zDesiredDate = zDesiredDate.addDays( zDeltaDate.daysTill( zToday ) );
            return zDesiredDate.toString();
        }

        private CalendarYMD to_CalendarYMD( String pWhat, String pString ) {
            try {
                return TypeConverter.to_CalendarYMD( pString.trim() );
            }
            catch ( RuntimeException e ) {
                throw new IllegalArgumentException( pWhat + ":" + e.getMessage(), e );
            }
        }

        private int parseInt( String pWhat, String pString ) {
            if ( (pString = pString.trim()).length() == 0 ) {
                return 0;
            }
            try {
                return Integer.parseInt( pString );
            }
            catch ( NumberFormatException e ) {
                throw new IllegalArgumentException( pWhat + ":" + e.getMessage(), e );
            }
        }
    }
}

Commits for litesoft/trunk/Java/core/Server/src/org/litesoft/orsup/DB_ImportSupport.java

Diff revisions: vs.
Revision Author Commited Message
958 Diff Diff GeorgeS picture GeorgeS Mon 14 Jul, 2014 15:29:35 +0000

Embrace OSS code bases.
Drop NAS-Video.

950 Diff Diff GeorgeS picture GeorgeS Thu 19 Jun, 2014 17:57:04 +0000

New Lines

948 Diff Diff GeorgeS picture GeorgeS Sat 07 Jun, 2014 23:42:39 +0000

Jusefuls Formatter Updated to New Code Format

947 Diff Diff GeorgeS picture GeorgeS Fri 06 Jun, 2014 23:36:56 +0000

Correct Spelling of package!

942 Diff Diff GeorgeS picture GeorgeS Mon 02 Jun, 2014 23:41:46 +0000

Extracting commonfoundation

939 Diff Diff GeorgeS picture GeorgeS Mon 02 Jun, 2014 21:30:31 +0000

Extracting commonfoundation

917 Diff Diff GeorgeS picture GeorgeS Sun 08 Dec, 2013 20:49:56 +0000

1.7 prep & VersionedStaticContentFilter upgrade to new “/ver” model!

863 Diff Diff GeorgeS picture GeorgeS Fri 16 Nov, 2012 22:14:29 +0000
860 Diff Diff GeorgeS picture GeorgeS Mon 05 Nov, 2012 01:39:02 +0000
853 GeorgeS picture GeorgeS Sun 04 Nov, 2012 15:18:21 +0000