001package jmri.implementation; 002 003import java.util.Date; 004import java.util.List; 005import javax.annotation.Nonnull; 006 007import jmri.*; 008import jmri.managers.ProxyIdTagManager; 009 010/** 011 * Abstract implementation of {@link jmri.IdTag} containing code common to all 012 * concrete implementations. This implementation implements {@link jmri.Reportable}. 013 * 014 * @author Matthew Harris Copyright (C) 2011 015 * @since 2.11.4 016 */ 017public abstract class AbstractIdTag extends AbstractNamedBean implements IdTag, Reportable { 018 019 protected Reporter whereLastSeen = null; 020 021 protected Date whenLastSeen = null; 022 protected String prefix = null; 023 024 public AbstractIdTag(String systemName) { 025 super(systemName); 026 } 027 028 public AbstractIdTag(String systemName, String userName) { 029 super(systemName, userName); 030 } 031 032 @Override 033 @Nonnull 034 public String getTagID() { 035 if(prefix == null) { 036 try { 037 prefix = findPrefix(); 038 } catch ( NullPointerException | BadSystemNameException e) { 039 // if there isn't a ProxyIDTag Manager, assume the first D in the 040 // system name is the type letter. 041 return mSystemName.substring(mSystemName.indexOf('D') + 1); 042 043 } 044 } 045 return mSystemName.substring(prefix.length()+1); 046 } 047 048 private String findPrefix() { 049 List<Manager<IdTag>> managerList = InstanceManager.getDefault(ProxyIdTagManager.class).getManagerList(); 050 for (Manager<IdTag> m : managerList) { 051 if (m.getBySystemName(mSystemName) != null) { 052 return m.getSystemPrefix(); 053 } 054 } 055 throw new BadSystemNameException(); 056 } 057 058 @Override 059 public Reporter getWhereLastSeen() { 060 return this.whereLastSeen; 061 } 062 063 @Override 064 public Date getWhenLastSeen() { 065 if (this.whenLastSeen == null) { 066 return null; 067 } else { 068 return (Date) this.whenLastSeen.clone(); // Date is mutable, so return copy 069 } 070 } 071 072 /** 073 * The IDTag version of toReportString returns a string consisting 074 * of the user name (if defined) or Tag ID followed by the associated 075 * list of property values. 076 */ 077 @Override 078 public String toReportString() { 079 String userName = getUserName(); 080 StringBuilder sb = new StringBuilder(); 081 if(userName == null || userName.isEmpty()){ 082 sb.append(getTagID()); 083 } else { 084 sb.append(userName); 085 } 086 087 // check to see if any properties have been added 088 // If we have properties, so append the values to the 089 // end of the report, seperated by spaces. 090 getPropertyKeys().forEach(s -> { 091 sb.append(" "); 092 sb.append(getProperty(s)); 093 }); 094 return sb.toString(); 095 } 096 097 @Override 098 @Nonnull 099 public String getBeanType() { 100 return Bundle.getMessage("BeanNameReporter"); 101 } 102 103}