summaryrefslogtreecommitdiffstats
path: root/authz-batch/src/main/java/com/att/authz/JobChange.java
blob: 235ebacccf67191e98e2e70f778a74b448b834a6 (plain)
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
/*******************************************************************************
 * Copyright (c) 2016 AT&T Intellectual Property. All rights reserved.
 *******************************************************************************/
// test for case where I'm an admin

package com.att.authz;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.att.authz.env.AuthzTrans;
import com.att.authz.org.Organization;
import com.att.authz.org.OrganizationFactory;
import com.att.inno.env.APIException;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.SimpleStatement;
import com.datastax.driver.core.Statement;

public class JobChange extends Batch
{
    private class UserRole
    {
        String user;
        String role;
    }
    private class UserCred
    {
        String user;
        String ns;
    }
    
    private class NamespaceOwner
    {
        String user;
        String ns;
        boolean responsible;
        int ownerCount;
    }
    

    private AuthzTrans myTrans;

	private Map<String, ArrayList<UserRole>> rolesMap = new HashMap<String, ArrayList<UserRole>>();
	private Map<String, ArrayList<NamespaceOwner>> ownersMap = new HashMap<String, ArrayList<NamespaceOwner>>();
    private Map<String, ArrayList<UserCred>> credsMap = new HashMap<String, ArrayList<UserCred>>();
    
    
    public static void createDirectory( String dir )
    {
        File f = new File( dir );

        if ( ! f.exists())
        {
            env.info().log( "creating directory: " + dir );
            boolean result = false;

            try
            {
                f.mkdir();
                result = true;
            } catch(SecurityException e){
                e.printStackTrace();
            }        
            if(result) {    
                System.out.println("DIR created");  
            }
        }        
    }
    
    public static String getJobChangeDataFile()
    {
        File outFile = null;
        BufferedWriter writer = null;
        BufferedReader reader = null;
        String line;
        boolean errorFlag = false;

        try
        {
            createDirectory( "etc" );
            
            outFile = new File("etc/jobchange." + getCurrentDate() );
            if (!outFile.exists())
            {
                outFile.createNewFile();
            }
            else
            {
                return( "etc/jobchange." + getCurrentDate() );
            }
			
            env.info().log("Creating the local file with the webphone data");



            writer = new BufferedWriter(new FileWriter(
                                            outFile.getAbsoluteFile()));

            URL u = new URL(  "ftp://thprod37.sbc.com/jobchange_Delta.dat" );
            reader = new BufferedReader(new InputStreamReader(
                                            new BufferedInputStream(u.openStream())));
            while ((line = reader.readLine()) != null) {
                writer.write(line + "\n");
            }
			
            writer.close();
            reader.close();
            
            env.info().log("Finished fetching the data from the webphone ftp site.");
            return( "etc/jobchange." + getCurrentDate() );
            
        } catch (MalformedURLException e) {
            env.error().log("Could not open the remote job change data file.", e);
            errorFlag = true;

        } catch (IOException e) {
            env.error().log(
                "Error while opening or writing to the local data file.", e);
            errorFlag = true;

        } catch (Exception e) {
            env.error().log("Error while fetching the data file.", e);
            errorFlag = true;

        } finally {
            if (errorFlag)
                outFile.delete();
        }
		return null;
    }

    public static String getCurrentDate()
    {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }

    public void loadUsersFromCred()
    {
        String query = "select id,ns from authz.cred" ;
                                      
        env.info().log( "query: " + query );

        Statement stmt = new SimpleStatement( query );
        ResultSet results = session.execute(stmt);

        Iterator<Row> iter = results.iterator();
        while( iter.hasNext() )
        {
            Row row = iter.next();
            String user = row.getString( "id" );
            String ns = row.getString( "ns" );
            String simpleUser = user.substring( 0, user.indexOf( "@" ) );

            if ( isMechID( simpleUser ) )
            {
                continue;
            }
            else if ( credsMap.get( simpleUser ) == null )
            {
                credsMap.put( simpleUser, new ArrayList<UserCred>() );
                
                UserCred newEntry = new UserCred();
                newEntry.user = user;
                newEntry.ns = ns;
            
                credsMap.get( simpleUser ).add( newEntry );
            }
            else 
            {
                UserCred newEntry = new UserCred();
                newEntry.user = user;
                newEntry.ns = ns;
            
                credsMap.get( simpleUser ).add( newEntry );
            }
                
            env.debug().log( String.format( "\tUser: %s NS: %s", user, ns ) );
        }
    }

    public void loadUsersFromRoles()
    {
        String query = "select user,role from authz.user_role" ;
                                      
        env.info().log( "query: " + query );

        Statement stmt = new SimpleStatement( query );
        ResultSet results = session.execute(stmt);
        int total=0, flagged=0;

        Iterator<Row> iter = results.iterator();
        while( iter.hasNext() )
        {
            Row row = iter.next();
            String user = row.getString( "user" );
            String role = row.getString( "role" );
            String simpleUser = user.substring( 0, user.indexOf( "@" ) );

            if ( isMechID( simpleUser ) )
            {
                continue;
            }
            else if ( rolesMap.get( simpleUser ) == null )
            {
                rolesMap.put( simpleUser, new ArrayList<UserRole>() );
                
                UserRole newEntry = new UserRole();
                newEntry.user = user;
                newEntry.role = role;
            
                rolesMap.get( simpleUser ).add( newEntry );
            }
            else
            {
                UserRole newEntry = new UserRole();
                newEntry.user = user;
                newEntry.role = role;
            
                rolesMap.get( simpleUser ).add( newEntry );
            }
                
            env.debug().log( String.format( "\tUser: %s Role: %s", user, role ) );

            ++total;
        }
        env.info().log( String.format( "rows read: %d expiring: %d", total, flagged ) );
    }

    public void loadOwnersFromNS()
    {
        String query = "select name,admin,responsible from authz.ns" ;
                                      
        env.info().log( "query: " + query );

        Statement stmt = new SimpleStatement( query );
        ResultSet results = session.execute(stmt);

        Iterator<Row> iter = results.iterator();
        while( iter.hasNext() )
        {
            Row row = iter.next();
            Set<String> responsibles = row.getSet( "responsible", String.class );

            for ( String user : responsibles )
            {
                env.info().log( String.format( "Found responsible %s", user ) );
                String simpleUser = user.substring( 0, user.indexOf( "@" ) );

                if ( isMechID( simpleUser ) )
                {
                    continue;
                }
                else if ( ownersMap.get( simpleUser ) == null )
                {
                    ownersMap.put( simpleUser, new ArrayList<NamespaceOwner>() );

                    NamespaceOwner newEntry = new NamespaceOwner();
                    newEntry.user = user;
                    newEntry.ns   = row.getString( "name" );
                    newEntry.ownerCount = responsibles.size();
                    newEntry.responsible = true;
                    ownersMap.get( simpleUser ).add( newEntry );
                }
                else 
                {
                    NamespaceOwner newEntry = new NamespaceOwner();
                    newEntry.user = user;
                    newEntry.ns = row.getString( "name" );
                    newEntry.ownerCount = responsibles.size();
                    newEntry.responsible = true;                    
                    ownersMap.get( simpleUser ).add( newEntry );
                }
            }                
            Set<String> admins = row.getSet( "admin", String.class );

            for ( String user : admins )
            {
                env.info().log( String.format( "Found admin %s", user ) );
                String simpleUser = user.substring( 0, user.indexOf( "@" ) );

                if ( isMechID( simpleUser ) )
                {
                    continue;
                }
                else if ( ownersMap.get( simpleUser ) == null )
                {
                    ownersMap.put( simpleUser, new ArrayList<NamespaceOwner>() );

                    NamespaceOwner newEntry = new NamespaceOwner();
                    newEntry.user = user;
                    newEntry.ns   = row.getString( "name" );
                    newEntry.responsible = false;
                    newEntry.ownerCount = -1; //                     
                    ownersMap.get( simpleUser ).add( newEntry );
                }
                else 
                {
                    NamespaceOwner newEntry = new NamespaceOwner();
                    newEntry.user = user;
                    newEntry.ns = row.getString( "name" );
                    newEntry.responsible = false;
                    newEntry.ownerCount = -1; //                                         
                    ownersMap.get( simpleUser ).add( newEntry );
                }
            }                

        }
    }

	/**
	 * Processes the specified JobChange data file obtained from Webphone. Each line is 
	 * read and processed and any fallout is written to the specified fallout file. 
	 * If fallout file already exists it is deleted and a new one is created. A
	 * comparison of the supervisor id in the job data file is done against the one returned 
	 * by the authz service and if the supervisor Id has changed then the record is updated
	 * using the authz service. An email is sent to the new supervisor to approve the roles 
	 * assigned to the user.
	 * 
	 * @param fileName - name of the file to process including its path
	 * @param falloutFileName - the file where the fallout entries have to be written
	 * @param validDate - the valid effective date when the user had moved to the new supervisor
	 * @throws Exception
	 */
	public void processJobChangeDataFile(String fileName,
                                         String falloutFileName, Date validDate) throws Exception
    {
        
		BufferedWriter writer = null;

		try {

            env.info().log("Reading file: " + fileName );

            FileInputStream fstream = new FileInputStream(fileName);
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

            String strLine;

            while ((strLine = br.readLine()) != null)   {
                processLine( strLine, writer );
            }

            br.close();
			
			
		} catch (IOException e) {
            env.error().log( "Error while reading from the input data file: " + e );
			throw e;
        }
    }

    public void handleAdminChange( String user )
    {
        ArrayList<NamespaceOwner> val = ownersMap.get( user );
        
        for ( NamespaceOwner r : val )
        {
            env.info().log( "handleAdminChange: " + user );
            AuthzTrans trans = env.newTransNoAvg();

            
            if ( r.responsible )
            {
                env.info().log( String.format( "delete from NS owner: %s, NS: %s, count: %s",
                                           r.user, r.ns, r.ownerCount ) );

                aspr.info( String.format( "action=DELETE_NS_OWNER, user=%s, ns=%s",
                                      r.user, r.ns ) );
                if ( r.ownerCount < 2 )
                {
                    // send warning email to aaf-support, after this deletion, no owner for NS
                    ArrayList<String> toAddress = new ArrayList<String>();
                    toAddress.add( "XXX_EMAIL" );
                
                    env.warn().log( "removing last owner from namespace" );

                    Organization org = null;
                    org = getOrgFromID( myTrans, org, toAddress.get(0) );

                    env.info().log( "calling getOrgFromID with " + toAddress.get(0) );

                    if ( org != null )
                    {
                        try
                        {
                            aspr.info( String.format( "action=EMAIL_NO_OWNER_NS to=%s, user=%s, ns=%s",
                                                      toAddress.get(0), r.user, r.ns ) );
                            org.sendEmail( trans, toAddress,
                                           new ArrayList<String>(),
                                           String.format( "WARNING: no owners for AAF namespace '%s'", r.ns ), // subject:
                                           String.format( "AAF recieved a jobchange notification for user %s who was the owner of the '%s' namespace. Please identify a new owner for this namespace and update AAF.", r.user, r.ns ), // body of msg
                                           true );
                        } catch (Exception e) {
                            env.error().log("calling sendEmail()");
                        
                            e.printStackTrace();
                        }
                    }
                    else
                    {
                        env.error().log( "Failed getOrgFromID" );
                    }
                }
            }
            else
            {
                env.info().log( String.format( "delete from NS admin: %s, NS: %s",
                                           r.user, r.ns ) );

                aspr.info( String.format( "action=DELETE_NS_ADMIN, user=%s, ns=%s",
                                          r.user, r.ns ) );
            }                    
            
            String field = (r.responsible == true) ? "responsible" : "admin";
            
            String query = String.format( "update authz.ns set %s = %s - {'%s'} where name = '%s'",
                                          field, field, r.user, r.ns ) ;                                   
            env.info().log( "query: " + query );
            Statement stmt = new SimpleStatement( query );
            /*Row row = */session.execute(stmt).one();
            
            String attribQuery = String.format( "delete from authz.ns_attrib where ns = '%s' AND type='%s' AND name='%s'",
        			r.ns, field, r.user);
            env.info().log( "ns_attrib query: " + attribQuery);
            Statement attribStmt = new SimpleStatement( attribQuery );
            /*Row attribRow = */session.execute(attribStmt).one();
            
        }
    }

    public void handleRoleChange( String user )
    {
        ArrayList<UserRole> val = rolesMap.get( user );
        
        for ( UserRole r : val )
        {
            env.info().log( "handleRoleChange: " + user );

            env.info().log( String.format( "delete from %s from user_role: %s",
                                           r.user, r.role ) );

            aspr.info( String.format( "action=DELETE_FROM_ROLE, user=%s, role=%s",
                                      r.user, r.role ) );


            String query = String.format( "delete from authz.user_role where user = '%s' and role = '%s'",
                                          r.user, r.role );
                                      
            env.info().log( "query: " + query );

            Statement stmt = new SimpleStatement( query );
            /* Row row = */ session.execute(stmt).one();

        }
    }
    
    public void handleCredChange( String user )
    {
        ArrayList<UserCred> val = credsMap.get( user );
        
        for ( UserCred r : val )
        {
            env.info().log( "handleCredChange: " + user );

            env.info().log( String.format( "delete user %s cred from ns: %s",
                                           r.user, r.ns ) );

            aspr.info( String.format( "action=DELETE_FROM_CRED, user=%s, ns=%s",
                                      r.user, r.ns ) );

            String query = String.format( "delete from authz.cred where id = '%s'",
                                          r.user );
                                      
            env.info().log( "query: " + query );

            Statement stmt = new SimpleStatement( query );
            /*Row row = */session.execute(stmt).one();

        }

    }
    
    public boolean processLine(String line, BufferedWriter writer) throws IOException
    {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyyMMdd");
        boolean errorFlag = false;
        String errorMsg = "";

        try
        {
            String[] phoneInfo = line.split( "\\|" );

            if ((phoneInfo != null) && (phoneInfo.length >= 8)
                && (!phoneInfo[0].startsWith("#")))
            {
                String user = phoneInfo[0];
                String newSupervisor = phoneInfo[7];
                Date effectiveDate = sdfDate.parse(phoneInfo[8].trim());

                env.debug().log( String.format( "checking user: %s, newSupervisor: %s, date: %s",
                                                user, newSupervisor, effectiveDate ) );
                    
                // Most important case, user is owner of a namespace
                //
                if ( ownersMap.get( user ) != null )
                {
                    env.info().log( String.format( "Found %s as a namespace admin/owner", user ) );
                    handleAdminChange( user );
                }

                if ( credsMap.get( user ) != null )
                {
                    env.info().log( String.format( "Found %s in cred table", user ) );
                    handleCredChange( user );
                }

                if ( rolesMap.get( user ) != null )
                {
                    env.info().log( String.format( "Found %s in a role ", user ) );
                    handleRoleChange( user );
                }
            }
                
            else if (phoneInfo[0].startsWith("#"))
            {
                return true;
            }
            else
            {
                env.warn().log("Can't parse. Skipping the line." + line);
                errorFlag = true;
            }
        } catch (Exception e) {
            errorFlag = true;
            errorMsg = e.getMessage();
            env.error().log( "Error while processing line:" + line +  e );
            e.printStackTrace();
        } finally {
            if (errorFlag) {
                env.info().log( "Fallout enrty being written for line:" + line );
                writer.write(line + "|Failed to update supervisor for user:" + errorMsg + "\n");
            }
        }
        return true;
    }


	public JobChange(AuthzTrans trans) throws APIException, IOException {
		super( trans.env() );
        myTrans = trans;
		session = cluster.connect();
	}

    public Organization getOrgFromID( AuthzTrans trans, Organization _org, String user ) {
	Organization org = _org;
        if ( org == null || ! user.endsWith( org.getRealm() ) ) {
            int idx = user.lastIndexOf('.');
            if ( idx > 0 )
                idx = user.lastIndexOf( '.', idx-1 );

            org = null;
            if ( idx > 0 ) {
                try {
                    org = OrganizationFactory.obtain( trans.env(), user.substring( idx+1 ) );
                } catch (Exception e) {
                    trans.error().log(e,"Failure Obtaining Organization");
                }
            }

            if ( org == null ) {
                PrintStream fallout = null;

                try {
                    fallout= fallout(fallout, "Fallout");
                    fallout.print("INVALID_ID,");
                    fallout.println(user);
                } catch (Exception e) {
                    env.error().log("Could not write to Fallout File",e);
                } 
                return( null );
            }
        }
        return( org );
    }        

    public void dumpOwnersMap()
    {
        for ( Map.Entry<String, ArrayList<NamespaceOwner>> e : ownersMap.entrySet() )
        {
            String key = e.getKey();
            ArrayList<NamespaceOwner> values = e.getValue();

            env.info().log( "ns user: " + key );

            for ( NamespaceOwner r : values )
            {
                env.info().log( String.format( "\tNS-user: %s, NS-name: %s, ownerCount: %d",
                                               r.user, r.ns, r.ownerCount ) );

            }
        }
    }

    public void dumpRolesMap()
    {
        for ( Map.Entry<String, ArrayList<UserRole>> e : rolesMap.entrySet() )
        {
            String key = e.getKey();
            ArrayList<UserRole> values = e.getValue();

            env.info().log( "user: " + key );

            for ( UserRole r : values )
            {
                env.info().log( String.format( "\trole-user: %s, role-name: %s",
                                                r.user, r.role ) );
            }
        }
    }
    public void dumpCredMap()
    {
        for ( Map.Entry<String, ArrayList<UserCred>> e : credsMap.entrySet() )
        {
            String key = e.getKey();
            ArrayList<UserCred> values = e.getValue();

            env.info().log( "user: " + key );

            for ( UserCred r : values )
            {
                env.info().log( String.format( "\tcred-user: %s, ns: %s",
                                                r.user, r.ns ) );
            }

        }
    }

	@Override
	protected void run (AuthzTrans trans)
	{
        if ( acquireRunLock( this.getClass().getName() ) != 1 ) {
                env.warn().log( "Cannot acquire run lock, exiting" );
                System.exit( 1 );
        }

		try {
//            Map<String,EmailMsg> email = new HashMap<String,EmailMsg>();

            try
            {
                String workingDir = System.getProperty("user.dir");
                env.info().log( "Process jobchange file. PWD is " + workingDir );
                
                loadUsersFromRoles();
                loadOwnersFromNS();
                loadUsersFromCred();

                dumpRolesMap();
                dumpOwnersMap();
                dumpCredMap();
                
                String fname = getJobChangeDataFile();
                
                if ( fname == null )
                {
                    env.warn().log("getJobChangedatafile returned null");
                }
                else
                {
                    env.info().log("done with FTP");
                }
				processJobChangeDataFile( fname, "fallout", null );
			}
            catch (Exception e)
            {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            

		} catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
		} catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
		}
	}

/*
    private class EmailMsg {
        private boolean urgent = false;
        public String url;
        public Organization org;
        public String summary;

        public EmailMsg() {
            org = null;
            summary = "";
        }

        public boolean getUrgent() {
            return( this.urgent );
        }

        public void setUrgent( boolean val ) {
            this.urgent = val;
        }
        public void setOrg( Organization newOrg ) {
            this.org = newOrg;
        }
        public Organization getOrg() {
            return( this.org );
        }
    }
*/
	@Override
	protected void _close(AuthzTrans trans) {
        session.close();
	}
}