public static final Map<Field, ProtobufAttribute> getAllProtbufFields(Class<? extends Object> fromClazz)
  {
    Map<Field, ProtobufAttribute> protoBufFields = CLASS_TO_FIELD_MAP_CACHE.get(fromClazz.getCanonicalName());
    if (protoBufFields != null)
    {
      return protoBufFields;
    }
    else
    {
      protoBufFields = new HashMap<>();
    }

    final List<Field> fields = JReflectionUtils.getAllFields(new ArrayList<Field>(), fromClazz);

    for (Field field : fields)
    {
      final Annotation annotation = field.getAnnotation(ProtobufAttribute.class);
      if (annotation == null)
      {
        continue;
      }
      final ProtobufAttribute gpbAnnotation = (ProtobufAttribute)annotation;
      protoBufFields.put(field, gpbAnnotation);
    }

    // Caching to increase speed
    CLASS_TO_FIELD_MAP_CACHE.put(fromClazz.getCanonicalName(), protoBufFields);

    return protoBufFields;
  }

public
static
final
Map
<
Field
,
ProtobufAttribute
>
getAllProtbufFields
(
Class
<
extends
Object
>
fromClazz
)
{
Map
<
Field
,
ProtobufAttribute
>
protoBufFields
=
CLASS_TO_FIELD_MAP_CACHE
.
get
(
fromClazz
.
getCanonicalName
(
)
)
;
if
(
protoBufFields
!=
)
{
return
protoBufFields
;
}
else
{
protoBufFields
=
new
HashMap
<>
(
)
;
}
final
List
<
Field
>
fields
=
JReflectionUtils
.
getAllFields
(
new
ArrayList
<
Field
>
(
)
,
fromClazz
)
;
for
(
Field
field
:
fields
)
{
final
Annotation
annotation
=
field
.
getAnnotation
(
ProtobufAttribute
.
class
)
;
if
(
annotation
==
)
{
continue
;
}
final
ProtobufAttribute
gpbAnnotation
=
(
ProtobufAttribute
)
annotation
;
protoBufFields
.
put
(
field
,
gpbAnnotation
)
;
}
// Caching to increase speed
CLASS_TO_FIELD_MAP_CACHE
.
put
(
fromClazz
.
getCanonicalName
(
)
,
protoBufFields
)
;
return
protoBufFields
;
}

Returns a full mapping of all Protobuf fields from the POJO class.
Essentially, the only fields that will be returned if they have
the ProtobufAttribute annotation.

@param fromClazz - Class<? extends Object>
@return Map<Field, ProtobufAttribute>

Returns a full mapping of all Protobuf fields from the POJO class . Essentially the only fields that will be returned if they have the ProtobufAttribute annotation .


public static final String getProtobufGetter(ProtobufAttribute protobufAttribute, Field field)
  {
    final String fieldName = field.getName();
    final String upperClassName = field.getDeclaringClass().getCanonicalName();
    // Look at the cache first
    Map<String, String> map = CLASS_TO_FIELD_GETTERS_MAP_CACHE.get(upperClassName);
    if (map != null)
    {
      if (!map.isEmpty() && map.containsKey(fieldName))
      {
        return map.get(fieldName);
      }
    }
    else
    {
      map = new ConcurrentHashMap<>();
    }

    final String upperCaseFirstFieldName = JStringUtils.upperCaseFirst(field.getName());
    String getter = "get" + upperCaseFirstFieldName;

    if (Collection.class.isAssignableFrom(field.getType()))
    {
      getter += "List";
    }
    if (!protobufAttribute.protobufGetter().isEmpty())
    {
      return protobufAttribute.protobufGetter();
    }

    map.put(fieldName, getter);
    CLASS_TO_FIELD_GETTERS_MAP_CACHE.put(upperClassName, map);

    return getter;
  }

public
static
final
String
getProtobufGetter
(
ProtobufAttribute
protobufAttribute
,
Field
field
)
{
final
String
fieldName
=
field
.
getName
(
)
;
final
String
upperClassName
=
field
.
getDeclaringClass
(
)
.
getCanonicalName
(
)
;
// Look at the cache first
Map
<
String
,
String
>
map
=
CLASS_TO_FIELD_GETTERS_MAP_CACHE
.
get
(
upperClassName
)
;
if
(
map
!=
)
{
if
(
!
map
.
isEmpty
(
)
&&
map
.
containsKey
(
fieldName
)
)
{
return
map
.
get
(
fieldName
)
;
}
}
else
{
map
=
new
ConcurrentHashMap
<>
(
)
;
}
final
String
upperCaseFirstFieldName
=
JStringUtils
.
upperCaseFirst
(
field
.
getName
(
)
)
;
String
getter
=
"get"
+
upperCaseFirstFieldName
;
if
(
Collection
.
class
.
isAssignableFrom
(
field
.
getType
(
)
)
)
{
getter
+=
"List"
;
}
if
(
!
protobufAttribute
.
protobufGetter
(
)
.
isEmpty
(
)
)
{
return
protobufAttribute
.
protobufGetter
(
)
;
}
map
.
put
(
fieldName
,
getter
)
;
CLASS_TO_FIELD_GETTERS_MAP_CACHE
.
put
(
upperClassName
,
map
)
;
return
getter
;
}

Retrieve the getter against the Protobuf class; default is to is "get" plus upper case first character of the field name.

@param protobufAttribute - {@link ProtobufAttribute}
@param field - {@link Field}
@return String

Retrieve the getter against the Protobuf class ; default is to is get plus upper case first character of the field name .


public static final String getPojoSetter(ProtobufAttribute protobufAttribute, Field field)
  {
    final String fieldName = field.getName();
    final String upperClassName = field.getDeclaringClass().getCanonicalName();
    // Look at the cache first
    Map<String, String> map = CLASS_TO_FIELD_SETTERS_MAP_CACHE.get(upperClassName);
    if (map != null)
    {
      if (!map.isEmpty() && map.containsKey(fieldName))
      {
        return map.get(fieldName);
      }
    }
    else
    {
      map = new ConcurrentHashMap<>();
    }

    final String upperCaseFirstFieldName = JStringUtils.upperCaseFirst(field.getName());
    String setter = "set" + upperCaseFirstFieldName;

    if (!protobufAttribute.pojoSetter().isEmpty())
    {
      return protobufAttribute.pojoSetter();
    }

    map.put(fieldName, setter);
    CLASS_TO_FIELD_SETTERS_MAP_CACHE.put(upperClassName, map);

    return setter;
  }

public
static
final
String
getPojoSetter
(
ProtobufAttribute
protobufAttribute
,
Field
field
)
{
final
String
fieldName
=
field
.
getName
(
)
;
final
String
upperClassName
=
field
.
getDeclaringClass
(
)
.
getCanonicalName
(
)
;
// Look at the cache first
Map
<
String
,
String
>
map
=
CLASS_TO_FIELD_SETTERS_MAP_CACHE
.
get
(
upperClassName
)
;
if
(
map
!=
)
{
if
(
!
map
.
isEmpty
(
)
&&
map
.
containsKey
(
fieldName
)
)
{
return
map
.
get
(
fieldName
)
;
}
}
else
{
map
=
new
ConcurrentHashMap
<>
(
)
;
}
final
String
upperCaseFirstFieldName
=
JStringUtils
.
upperCaseFirst
(
field
.
getName
(
)
)
;
String
setter
=
"set"
+
upperCaseFirstFieldName
;
if
(
!
protobufAttribute
.
pojoSetter
(
)
.
isEmpty
(
)
)
{
return
protobufAttribute
.
pojoSetter
(
)
;
}
map
.
put
(
fieldName
,
setter
)
;
CLASS_TO_FIELD_SETTERS_MAP_CACHE
.
put
(
upperClassName
,
map
)
;
return
setter
;
}

Retrieve the setter on the POJO class; default is to is "set" plus upper case first character of the field name.

@param protobufAttribute - {@link ProtobufAttribute}
@param field - {@link Field}
@return String - the name of the POJO setter

Retrieve the setter on the POJO class ; default is to is set plus upper case first character of the field name .


public static ObjectMapper getMapper() {

		ObjectMapper mapper = threadMapper.get();
		if (mapper == null) {
			mapper = initMapper();
			threadMapper.set(mapper);

		}
		return mapper;
	}

public static ObjectMapper getMapper ( ) { ObjectMapper mapper = threadMapper . get ( ) ; if ( mapper == null ) { mapper = initMapper ( ) ; threadMapper . set ( mapper ) ; } return mapper ; }

return a ObjectMapper if exist,else new ObjectMapper

@return ObjectMapper

return a ObjectMapper if exist else new ObjectMapper


public static JsonFactory getJsonFactory() {

		JsonFactory jsonFactory = threadJsonFactory.get();
		if (jsonFactory == null) {
			jsonFactory = new JsonFactory();
			// JsonParser.Feature for configuring parsing settings:
			// to allow C/C++ style comments in JSON (non-standard, disabled by
			// default)
			jsonFactory.enable(JsonParser.Feature.ALLOW_COMMENTS);
			// to allow (non-standard) unquoted field names in JSON:
			jsonFactory.disable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
			// to allow use of apostrophes (single quotes), non standard
			jsonFactory.disable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);

			// JsonGenerator.Feature for configuring low-level JSON generation:

			// no escaping of non-ASCII characters:
			jsonFactory.disable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
			threadJsonFactory.set(jsonFactory);

		}
		return jsonFactory;
	}

return a JsonFactory if exist,else new JsonFactory

@return JsonFactory

return a JsonFactory if exist else new JsonFactory


public static <T> String toJson(T obj) {
		StringWriter writer = new StringWriter();
		String jsonStr = "";
		JsonGenerator gen = null;
		try {
			gen = getJsonFactory().createGenerator(writer);
			getMapper().writeValue(gen, obj);
			writer.flush();
			jsonStr = writer.toString();

		} catch (IOException e) {
			log.error("{}", e.getMessage(), e);
		} finally {
			if (gen != null) {
				try {
					gen.close();
				} catch (IOException e) {
				}
			}

		}
		return jsonStr;
	}

public static < T > String toJson ( T obj ) { StringWriter writer = new StringWriter ( ) ; String jsonStr = "" ; JsonGenerator gen = null ; try { gen = getJsonFactory ( ) . createGenerator ( writer ) ; getMapper ( ) . writeValue ( gen , obj ) ; writer . flush ( ) ; jsonStr = writer . toString ( ) ; } catch ( IOException e ) { log . error ( "{}" , e . getMessage ( ) , e ) ; } finally { if ( gen != null ) { try { gen . close ( ) ; } catch ( IOException e ) { } } } return jsonStr ; }

Bean to json string

@param obj obj
bean object
@param <T> t
@return json string


public void setBorders(int top, int right, int bottom, int left)
    {
        setTopBorder(top);
        setRightBorder(right);
        setBottomBorder(bottom);
        setLeftBorder(left);
    }

public void setBorders ( int top , int right , int bottom , int left ) { setTopBorder ( top ) ; setRightBorder ( right ) ; setBottomBorder ( bottom ) ; setLeftBorder ( left ) ; }

Sets all the border values.
@param top
@param right
@param bottom
@param left


@edu.umd.cs.findbugs.annotations.SuppressWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
    private UserRecord getUserRecord(final String domain, final String userName)
            throws LoginException {

        String userId;
        String credential;

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = getDatabaseConnection();

            statement = connection.prepareStatement(dbProps.get().getSqlUserQuery());
            statement.setString(1, domain);
            statement.setString(2, userName);

            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                userId = resultSet.getString(1);
                credential = resultSet.getString(2);
            } else {
                final String error = "Username '" + userName + "' does not exist (query returned zero results)";
                LOG.warn(error);
                throw new LoginException(error);
            }

            resultSet.close();
            statement.close();
        } catch (SQLException e) {
            final String error = "Error executing SQL query";
            LOG.warn(error, e);
            throw Util.newLoginException(error, e);
        } finally {
            DbUtil.close(resultSet);
            DbUtil.close(statement);
            DbUtil.close(connection);
        }

        return new UserRecord(domain, userName, userId, credential);
    }

The SQL statement is retrieved from the configuration, and the admin is trusted

The SQL statement is retrieved from the configuration and the admin is trusted


public void copyOutAttributes(Object target, List<Attribute> jmxAttributeValues,
                                  Map<String, Method> attributeSetters, ObjectName objectName) {

        this.copyOutAttributes(target, jmxAttributeValues, attributeSetters, "oname", objectName);
    }

public void copyOutAttributes ( Object target , List < Attribute > jmxAttributeValues , Map < String , Method > attributeSetters , ObjectName objectName ) { this . copyOutAttributes ( target , jmxAttributeValues , attributeSetters , "oname" , objectName ) ; }

For a JMX MBean idenfitied by an ObjectName, copy the values of the given attributes into the target object
using the specified setter methods mapped by attribute name.

@param target object into which values are injected.
@param jmxAttributeValues values of the attributes to inject.
@param attributeSetters map of attribute name to setter used to determine how to inject each attribute's value.
@param objectName name of the MBean involved - used only for logging.

For a JMX MBean idenfitied by an ObjectName copy the values of the given attributes into the target object using the specified setter methods mapped by attribute name .


protected void copyOutAttributes(Object target, List<Attribute> jmxAttributeValues,
                                     Map<String, Method> attributeSetters, String identifierKey, Object identifier) {

        for (Attribute oneAttribute : jmxAttributeValues) {
            String attributeName = oneAttribute.getName();

            Method setter = attributeSetters.get(attributeName);
            Object value = oneAttribute.getValue();

            try {
                //
                // Automatically down-convert longs to integers as-needed.
                //
                if ((setter.getParameterTypes()[0].isAssignableFrom(Integer.class)) ||
                    (setter.getParameterTypes()[0].isAssignableFrom(int.class))) {
                    if (value instanceof Long) {
                        value = ((Long) value).intValue();
                    }
                }
                setter.invoke(target, value);
            } catch (InvocationTargetException invocationExc) {
                this.log.info("invocation exception storing mbean results: {}={}; attributeName={}", identifierKey,
                        identifier, attributeName, invocationExc);
            } catch (IllegalAccessException illegalAccessExc) {
                this.log.info("illegal access exception storing mbean results: {}={}; attributeName={}", identifierKey,
                        identifier, attributeName, illegalAccessExc);
            } catch (IllegalArgumentException illegalArgumentExc) {
                this.log.info("illegal argument exception storing mbean results: {}={}; attributeName={}",
                        identifierKey, identifier, attributeName, illegalArgumentExc);
            }
        }
    }

Copy the values of the given attributes into the target object using the specified setter methods mapped by
attribute name.

@param target object into which values are injected.
@param jmxAttributeValues values of the attributes to inject.
@param attributeSetters map of attribute name to setter used to determine how to inject each attribute's value.
@param identifierKey key, or name, of the identifier - used only for logging purposes.
@param identifier identifier to include in the output - used only for logging purposes.

Copy the values of the given attributes into the target object using the specified setter methods mapped by attribute name .


public String getProperty(String key)
    {
    	if (m_properties == null)
    		return null;
    	return m_properties.getProperty(key);
    }

public String getProperty ( String key ) { if ( m_properties == null ) return null ; return m_properties . getProperty ( key ) ; }


public void setProperty(String key, String value)
    {
    	if (m_properties == null)
    		m_properties = new Properties();
    	m_properties.setProperty(key, value);
    }

public void setProperty ( String key , String value ) { if ( m_properties == null ) m_properties = new Properties ( ) ; m_properties . setProperty ( key , value ) ; }


public JFrame addAppToFrame()
	{
		JFrame frame = new JFrame();
		frame.setTitle(this.getTitle());
		frame.setBackground(Color.lightGray);
		frame.getContentPane().setLayout(new BorderLayout());

		frame.getContentPane().add(this, BorderLayout.CENTER);
		frame.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.pack();
		frame.setSize(frame.getPreferredSize().width, frame.getPreferredSize().height);
		return frame;
	}

public JFrame addAppToFrame ( ) { JFrame frame = new JFrame ( ) ; frame . setTitle ( this . getTitle ( ) ) ; frame . setBackground ( Color . lightGray ) ; frame . getContentPane ( ) . setLayout ( new BorderLayout ( ) ) ; frame . getContentPane ( ) . add ( this , BorderLayout . CENTER ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; frame . pack ( ) ; frame . setSize ( frame . getPreferredSize ( ) . width , frame . getPreferredSize ( ) . height ) ; return frame ; }

Add this applet to a frame and initialize.
@return

Add this applet to a frame and initialize .


@Override
	public void saveToken(Token token) {
		set(ACCESS_TOKEN_TOKEN_PREF, token.getToken());
		set(ACCESS_TOKEN_SECRET_PREF, token.getSecret());
	}

@ Override public void saveToken ( Token token ) { set ( ACCESS_TOKEN_TOKEN_PREF , token . getToken ( ) ) ; set ( ACCESS_TOKEN_SECRET_PREF , token . getSecret ( ) ) ; }


@Override
	public Token getToken() {
		String token = get(ACCESS_TOKEN_TOKEN_PREF);
		String secret = get(ACCESS_TOKEN_SECRET_PREF);
		return token != null ? new Token(token, secret) : null;
	}

@ Override public Token getToken ( ) { String token = get ( ACCESS_TOKEN_TOKEN_PREF ) ; String secret = get ( ACCESS_TOKEN_SECRET_PREF ) ; return token != null ? new Token ( token , secret ) : null ; }

Get the persisted token using java preferences.

Get the persisted token using java preferences .


public static ClassLoader getDefault() {
        ClassLoader loader = null;
        try {
            loader = Thread.currentThread().getContextClassLoader();
        } catch (Exception e) {
        }
        if (loader == null) {
            loader = ClassLoaderUtils.class.getClassLoader();
            if (loader == null) {
                loader = ClassLoader.getSystemClassLoader();
            }
        }
        return loader;
    }

public static ClassLoader getDefault ( ) { ClassLoader loader = null ; try { loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } catch ( Exception e ) { } if ( loader == null ) { loader = ClassLoaderUtils . class . getClassLoader ( ) ; if ( loader == null ) { loader = ClassLoader . getSystemClassLoader ( ) ; } } return loader ; }

Returns current thread's context class loader

Returns current thread s context class loader


public static URL getResource(String name, ClassLoader classLoader) {
        Validate.notNull(name, "resourceName must be not null");

        if (name.startsWith("/")) {
            name = name.substring(1);
        }
        if (classLoader != null) {
            URL url = classLoader.getResource(name);
            if (url != null) {
                return url;
            }
        }
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader != null && loader != classLoader) {
            URL url = loader.getResource(name);
            if (url != null) {
                return url;
            }
        }

        return ClassLoader.getSystemResource(name);
    }

public
static
URL
getResource
(
String
name
,
ClassLoader
classLoader
)
{
Validate
.
notNull
(
name
,
"resourceName must be not null"
)
;
if
(
name
.
startsWith
(
"/"
)
)
{
name
=
name
.
substring
(
1
)
;
}
if
(
classLoader
!=
)
{
URL
url
=
classLoader
.
getResource
(
name
)
;
if
(
url
!=
)
{
return
url
;
}
}
ClassLoader
loader
=
Thread
.
currentThread
(
)
.
getContextClassLoader
(
)
;
if
(
loader
!=
&&
loader
!=
classLoader
)
{
URL
url
=
loader
.
getResource
(
name
)
;
if
(
url
!=
)
{
return
url
;
}
}
return
ClassLoader
.
getSystemResource
(
name
)
;
}

Finds the resource with the given name.
@param name - The resource name
@return A URL object for reading the resource, or null if the resource could not be found

Finds the resource with the given name .


public static InputStream getResourceAsStream(String name, ClassLoader classLoader) throws IOException {
        URL url = getResource(name, classLoader);
        if (url != null) {
            return url.openStream();
        }
        return null;
    }

public static InputStream getResourceAsStream ( String name , ClassLoader classLoader ) throws IOException { URL url = getResource ( name , classLoader ) ; if ( url != null ) { return url . openStream ( ) ; } return null ; }

Returns an input stream for reading the specified resource.

Returns an input stream for reading the specified resource .


public static InputStream getClassAsStream(Class<?> clazz) throws IOException {
        return getResourceAsStream(getClassFileName(clazz), clazz.getClassLoader());
    }

public static InputStream getClassAsStream ( Class < ? > clazz ) throws IOException { return getResourceAsStream ( getClassFileName ( clazz ) , clazz . getClassLoader ( ) ) ; }

Returns an input stream for reading the specified class.

Returns an input stream for reading the specified class .


private void initialize(URI p_other) {
		m_scheme = p_other.getScheme();
		m_userinfo = p_other.getUserinfo();
		m_host = p_other.getHost();
		m_port = p_other.m_port;
		n_port = p_other.n_port;
		m_path = p_other.getPath();
		m_queryString = p_other.getQueryString();
		m_fragment = p_other.getFragment();
	}

private void initialize ( URI p_other ) { m_scheme = p_other . getScheme ( ) ; m_userinfo = p_other . getUserinfo ( ) ; m_host = p_other . getHost ( ) ; m_port = p_other . m_port ; n_port = p_other . n_port ; m_path = p_other . getPath ( ) ; m_queryString = p_other . getQueryString ( ) ; m_fragment = p_other . getFragment ( ) ; }

Initialize all fields of this URI from another URI.

@param p_other the URI to copy (cannot be null)

Initialize all fields of this URI from another URI .


private void initializeScheme(String p_uriSpec)
		throws MalformedURIException {
		int uriSpecLen = p_uriSpec.length();
		int index = p_uriSpec.indexOf(':');

		if (index < 1)
			throw new MalformedURIException("No scheme found in URI.");

		if (index == uriSpecLen - 1)
			throw new MalformedURIException("A bare scheme name is not a URI.");

		setScheme(p_uriSpec.substring(0, index));
	}

private
void
initializeScheme
(
String
p_uriSpec
)
throws
MalformedURIException
{
int
uriSpecLen
=
p_uriSpec
.
length
(
)
;
int
index
=
p_uriSpec
.
indexOf
(
'
'
)
;
if
(
index
<
1
)
throw
new
MalformedURIException
(
"No scheme found in URI."
)
;
if
(
index
==
uriSpecLen
1
)
throw
new
MalformedURIException
(
"A bare scheme name is not a URI."
)
;
setScheme
(
p_uriSpec
.
substring
(
0
,
index
)
)
;
}

Initialize the scheme for this URI from a URI string spec.

@param p_uriSpec the URI specification (cannot be null)

@exception MalformedURIException if URI does not have a conformant
scheme

Initialize the scheme for this URI from a URI string spec .


private void initializePath(String p_uriSpec)
		throws MalformedURIException {
		if (p_uriSpec == null) {
			throw new MalformedURIException("Cannot initialize path from null string!");
		}

		int index = 0;
		int start = 0;
		int end = p_uriSpec.length();
		char testChar = '\0';

		// path - everything up to query string or fragment
		while (index < end) {
			testChar = p_uriSpec.charAt(index);
			if (testChar == '?' || testChar == '#') {
				break;
			}
			// check for valid escape sequence
			if (testChar == '%') {
				if (index + 2 >= end
					|| !isHex(p_uriSpec.charAt(index + 1))
					|| !isHex(p_uriSpec.charAt(index + 2))) {
					throw new MalformedURIException("Path contains invalid escape sequence!");
				}
			} else if (
				!isReservedCharacter(testChar)
					&& !isUnreservedCharacter(testChar)) {
				throw new MalformedURIException(
					"Path contains invalid character: " + testChar);
			}
			index++;
		}
		m_path = p_uriSpec.substring(start, index);

		// query - starts with ? and up to fragment or end
		if (testChar == '?') {
			index++;
			start = index;
			while (index < end) {
				testChar = p_uriSpec.charAt(index);
				if (testChar == '#') {
					break;
				}
				if (testChar == '%') {
					if (index + 2 >= end
						|| !isHex(p_uriSpec.charAt(index + 1))
						|| !isHex(p_uriSpec.charAt(index + 2))) {
						throw new MalformedURIException("Query string contains invalid escape sequence!");
					}
				} else if (
					!isReservedCharacter(testChar)
						&& !isUnreservedCharacter(testChar)) {
					throw new MalformedURIException(
						"Query string contains invalid character:" + testChar);
				}
				index++;
			}
			m_queryString = p_uriSpec.substring(start, index);
		}

		// fragment - starts with #
		if (testChar == '#') {
			index++;
			start = index;
			while (index < end) {
				testChar = p_uriSpec.charAt(index);

				if (testChar == '%') {
					if (index + 2 >= end
						|| !isHex(p_uriSpec.charAt(index + 1))
						|| !isHex(p_uriSpec.charAt(index + 2))) {
						throw new MalformedURIException("Fragment contains invalid escape sequence!");
					}
				} else if (
					!isReservedCharacter(testChar)
						&& !isUnreservedCharacter(testChar)) {
					throw new MalformedURIException(
						"Fragment contains invalid character:" + testChar);
				}
				index++;
			}
			m_fragment = p_uriSpec.substring(start, index);
		}
	}

Initialize the path for this URI from a URI string spec.

@param p_uriSpec the URI specification (cannot be null)

@exception MalformedURIException if p_uriSpec violates syntax rules

Initialize the path for this URI from a URI string spec .


private void setScheme(String p_scheme) throws MalformedURIException {
		if (p_scheme == null) {
			throw new MalformedURIException("Cannot set scheme from null string!");
		}
		if (!isConformantSchemeName(p_scheme)) {
			throw new MalformedURIException("The scheme is not conformant.");
		}

		m_scheme = p_scheme; //.toLowerCase();
	}

private
void
setScheme
(
String
p_scheme
)
throws
MalformedURIException
{
if
(
p_scheme
==
)
{
throw
new
MalformedURIException
(
"Cannot set scheme from null string!"
)
;
}
if
(
!
isConformantSchemeName
(
p_scheme
)
)
{
throw
new
MalformedURIException
(
"The scheme is not conformant."
)
;
}
m_scheme
=
p_scheme
;
//.toLowerCase();
}

Set the scheme for this URI. The scheme is converted to lowercase
before it is set.

@param p_scheme the scheme for this URI (cannot be null)

@exception MalformedURIException if p_scheme is not a conformant
scheme name

Set the scheme for this URI . The scheme is converted to lowercase before it is set .


private void setUserinfo(String p_userinfo) throws MalformedURIException {
		if (p_userinfo == null) {
			m_userinfo = null;
		} else {
			if (m_host == null) {
				throw new MalformedURIException("Userinfo cannot be set when host is null!");
			}

			// userinfo can contain alphanumerics, mark characters, escaped
			// and ';',':','&','=','+','$',','
			int index = 0;
			int end = p_userinfo.length();
			char testChar = '\0';
			while (index < end) {
				testChar = p_userinfo.charAt(index);
				if (testChar == '%') {
					if (index + 2 >= end
						|| !isHex(p_userinfo.charAt(index + 1))
						|| !isHex(p_userinfo.charAt(index + 2))) {
						throw new MalformedURIException("Userinfo contains invalid escape sequence!");
					}
				} else if (
					!isUnreservedCharacter(testChar)
						&& USERINFO_CHARACTERS.indexOf(testChar) == -1) {
					throw new MalformedURIException(
						"Userinfo contains invalid character:" + testChar);
				}
				index++;
			}
		}
		m_userinfo = p_userinfo;
	}

Set the userinfo for this URI. If a non-null value is passed in and
the host value is null, then an exception is thrown.

@param p_userinfo the userinfo for this URI

@exception MalformedURIException if p_userinfo contains invalid
characters

Set the userinfo for this URI . If a non - null value is passed in and the host value is null then an exception is thrown .


private void setHost(String p_host) throws MalformedURIException {
		if (p_host == null || p_host.length() == 0) {
			m_host = p_host;
			m_userinfo = null;
			m_port = null;
			n_port = -1;
		} else if (!isWellFormedAddress(p_host)) {
			throw new MalformedURIException("Host is not a well formed address!");
		}
		m_host = p_host;
	}

private
void
setHost
(
String
p_host
)
throws
MalformedURIException
{
if
(
p_host
==
||
p_host
.
length
(
)
==
0
)
{
m_host
=
p_host
;
m_userinfo
=
;
m_port
=
;
n_port
=
1
;
}
else
if
(
!
isWellFormedAddress
(
p_host
)
)
{
throw
new
MalformedURIException
(
"Host is not a well formed address!"
)
;
}
m_host
=
p_host
;
}

Set the host for this URI. If null is passed in, the userinfo
field is also set to null and the port is set to -1.

@param p_host the host for this URI

@exception MalformedURIException if p_host is not a valid IP
address or DNS hostname.

Set the host for this URI . If null is passed in the userinfo field is also set to null and the port is set to - 1 .


private void setPort(int p_port) throws MalformedURIException {
		if (p_port >= 0 && p_port <= 65535) {
			if (m_host == null) {
				throw new MalformedURIException("Port cannot be set when host is null!");
			}
		} else if (p_port != -1) {
			throw new MalformedURIException("Invalid port number!");
		}
		n_port = p_port;

	}

private
void
setPort
(
int
p_port
)
throws
MalformedURIException
{
if
(
p_port
>=
0
&&
p_port
<=
65535
)
{
if
(
m_host
==
)
{
throw
new
MalformedURIException
(
"Port cannot be set when host is null!"
)
;
}
}
else
if
(
p_port
!=
1
)
{
throw
new
MalformedURIException
(
"Invalid port number!"
)
;
}
n_port
=
p_port
;
}

Set the port for this URI. -1 is used to indicate that the port is
not specified, otherwise valid port numbers are  between 0 and 65535.
If a valid port number is passed in and the host field is null,
an exception is thrown.

@param p_port the port number for this URI

@exception MalformedURIException if p_port is not -1 and not a
valid port number

Set the port for this URI . - 1 is used to indicate that the port is not specified otherwise valid port numbers are between 0 and 65535 . If a valid port number is passed in and the host field is null an exception is thrown .


private void appendPath(String p_addToPath) throws MalformedURIException {
		if (p_addToPath == null || p_addToPath.length() == 0) {
			return;
		}

		if (!isURIString(p_addToPath)) {
			throw new MalformedURIException("Path contains invalid character!");
		}

		if (m_path == null || m_path.length() == 0) {
			if (p_addToPath.startsWith("/")) {
				m_path = p_addToPath;
			} else {
				m_path = "/" + p_addToPath;
			}
		} else if (m_path.endsWith("/")) {
			if (p_addToPath.startsWith("/")) {
				m_path = m_path.concat(p_addToPath.substring(1));
			} else {
				m_path = m_path.concat(p_addToPath);
			}
		} else {
			if (p_addToPath.startsWith("/")) {
				m_path = m_path.concat(p_addToPath);
			} else {
				m_path = m_path.concat("/" + p_addToPath);
			}
		}
	}

private
void
appendPath
(
String
p_addToPath
)
throws
MalformedURIException
{
if
(
p_addToPath
==
||
p_addToPath
.
length
(
)
==
0
)
{
return
;
}
if
(
!
isURIString
(
p_addToPath
)
)
{
throw
new
MalformedURIException
(
"Path contains invalid character!"
)
;
}
if
(
m_path
==
||
m_path
.
length
(
)
==
0
)
{
if
(
p_addToPath
.
startsWith
(
"/"
)
)
{
m_path
=
p_addToPath
;
}
else
{
m_path
=
"/"
+
p_addToPath
;
}
}
else
if
(
m_path
.
endsWith
(
"/"
)
)
{
if
(
p_addToPath
.
startsWith
(
"/"
)
)
{
m_path
=
m_path
.
concat
(
p_addToPath
.
substring
(
1
)
)
;
}
else
{
m_path
=
m_path
.
concat
(
p_addToPath
)
;
}
}
else
{
if
(
p_addToPath
.
startsWith
(
"/"
)
)
{
m_path
=
m_path
.
concat
(
p_addToPath
)
;
}
else
{
m_path
=
m_path
.
concat
(
"/"
+
p_addToPath
)
;
}
}
}

Append to the end of the path of this URI. If the current path does
not end in a slash and the path to be appended does not begin with
a slash, a slash will be appended to the current path before the
new segment is added. Also, if the current path ends in a slash
and the new segment begins with a slash, the extra slash will be
removed before the new segment is appended.

@param p_addToPath the new segment to be added to the current path

@exception MalformedURIException if p_addToPath contains syntax
errors

Append to the end of the path of this URI . If the current path does not end in a slash and the path to be appended does not begin with a slash a slash will be appended to the current path before the new segment is added . Also if the current path ends in a slash and the new segment begins with a slash the extra slash will be removed before the new segment is appended .


private void setQueryString(String p_queryString)
		throws MalformedURIException {
		if (p_queryString == null) {
			m_queryString = null;
		} else if (!isGenericURI()) {
			throw new MalformedURIException("Query string can only be set for a generic URI!");
		} else if (getPath() == null) {
			throw new MalformedURIException("Query string cannot be set when path is null!");
		} else if (!isURIString(p_queryString)) {
			throw new MalformedURIException("Query string contains invalid character!");
		} else {
			m_queryString = p_queryString;
		}
	}

Set the query string for this URI. A non-null value is valid only
if this is an URI conforming to the generic URI syntax and
the path value is not null.

@param p_queryString the query string for this URI

@exception MalformedURIException if p_queryString is not null and this
URI does not conform to the generic
URI syntax or if the path is null

Set the query string for this URI . A non - null value is valid only if this is an URI conforming to the generic URI syntax and the path value is not null .


public void setFragment(String p_fragment) throws MalformedURIException {
		if (p_fragment == null) {
			m_fragment = null;
		} else if (!isGenericURI()) {
			throw new MalformedURIException("Fragment can only be set for a generic URI!");
		} else if (getPath() == null) {
			throw new MalformedURIException("Fragment cannot be set when path is null!");
		} else if (!isURIString(p_fragment)) {
			throw new MalformedURIException("Fragment contains invalid character!");
		} else {
			m_fragment = p_fragment;
		}
	}

Set the fragment for this URI. A non-null value is valid only
if this is a URI conforming to the generic URI syntax and
the path value is not null.

@param p_fragment the fragment for this URI

@exception MalformedURIException if p_fragment is not null and this
URI does not conform to the generic
URI syntax or if the path is null

Set the fragment for this URI . A non - null value is valid only if this is a URI conforming to the generic URI syntax and the path value is not null .


public String getURIString() {
		StringBuffer uriSpecString = new StringBuffer();

		if (m_scheme != null) {
			uriSpecString.append(m_scheme);
			uriSpecString.append(':');
		}
		uriSpecString.append(getSchemeSpecificPart());
		return uriSpecString.toString();
	}

public String getURIString ( ) { StringBuffer uriSpecString = new StringBuffer ( ) ; if ( m_scheme != null ) { uriSpecString . append ( m_scheme ) ; uriSpecString . append ( ' ' ) ; } uriSpecString . append ( getSchemeSpecificPart ( ) ) ; return uriSpecString . toString ( ) ; }

Get the URI as a string specification. See RFC 2396 Section 5.2.

@return the URI string specification

Get the URI as a string specification . See RFC 2396 Section 5 . 2 .


protected static PreparedStatement createByIterator(Connection conn, String sql, Iterator<?> parameters) throws SQLException {
        PreparedStatement ps = conn.prepareStatement(sql);
        if (parameters != null) {
            int index = 1;
            while (parameters.hasNext()) {
                Object parameter = parameters.next();
                if (parameter == null) {
                    ps.setObject(index, null);
                } else {
                    ps.setObject(index, parameter);
                }
                index++;
            }
        }
        return ps;
    }

protected static PreparedStatement createByIterator ( Connection conn , String sql , Iterator < ? > parameters ) throws SQLException { PreparedStatement ps = conn . prepareStatement ( sql ) ; if ( parameters != null ) { int index = 1 ; while ( parameters . hasNext ( ) ) { Object parameter = parameters . next ( ) ; if ( parameter == null ) { ps . setObject ( index , null ) ; } else { ps . setObject ( index , parameter ) ; } index ++ ; } } return ps ; }


public void init(Object applet)
    {
        try {
            m_ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService");
            m_bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
            m_strCodeBase = m_bs.getCodeBase().toString();
        } catch (UnavailableServiceException e) {
            m_ps = null;
            m_bs = null;
        }
    }

public void init ( Object applet ) { try { m_ps = ( PersistenceService ) ServiceManager . lookup ( "javax.jnlp.PersistenceService" ) ; m_bs = ( BasicService ) ServiceManager . lookup ( "javax.jnlp.BasicService" ) ; m_strCodeBase = m_bs . getCodeBase ( ) . toString ( ) ; } catch ( UnavailableServiceException e ) { m_ps = null ; m_bs = null ; } }

Creates new MuffinManager.
@param applet The parent object (ignored).


public String getMuffin(String strParam)
    {
        try   {
            URL url = new URL(m_strCodeBase + strParam);
            FileContents fc = m_ps.get(url);
            if (fc == null)
                return null;
            // read in the contents of a muffin
            byte[] buf = new byte[(int)fc.getLength()];
            InputStream is = fc.getInputStream();
            int pos = 0;
            while((pos = is.read(buf, pos, buf.length - pos)) > 0) {
                // just loop
            }
            is.close();
            String strValue = new String(buf, ENCODING);
            return strValue;
        } catch (Exception ex)  {
            // Return null for any exception
        }
        return null;
    }

public
String
getMuffin
(
String
strParam
)
{
try
{
URL
url
=
new
URL
(
m_strCodeBase
+
strParam
)
;
FileContents
fc
=
m_ps
.
get
(
url
)
;
if
(
fc
==
)
return
;
// read in the contents of a muffin
byte
[
]
buf
=
new
byte
[
(
int
)
fc
.
getLength
(
)
]
;
InputStream
is
=
fc
.
getInputStream
(
)
;
int
pos
=
0
;
while
(
(
pos
=
is
.
read
(
buf
,
pos
,
buf
.
length
pos
)
)
>
0
)
{
// just loop
}
is
.
close
(
)
;
String
strValue
=
new
String
(
buf
,
ENCODING
)
;
return
strValue
;
}
catch
(
Exception
ex
)
{
// Return null for any exception
}
return
;
}

Get the current value for this muffin.
@param strParam The key for this muffin parameter.
@return The value for this muffin (null if none).


public void setMuffin(String strParam, String strValue)
    {
        FileContents fc = null;
        URL url = null;
        try   {
            url = new URL(m_strCodeBase + strParam);
        } catch (Exception ex)  {
            return;
        }
        try   {
            fc = m_ps.get(url);
            fc.getMaxLength(); // This will throw an exception if there is no muffin yet.
        } catch (Exception ex)  {
            fc = null;
        }
        try   {
            if (fc == null)
            {
                m_ps.create(url, 100);
                fc = m_ps.get(url);
            }          // don't append
            if (strValue != null)
            {
                OutputStream os = fc.getOutputStream(false);
                byte[] buf = strValue.getBytes(ENCODING);
                os.write(buf);
                os.close();
                m_ps.setTag(url, PersistenceService.DIRTY);
            }
            else
                m_ps.delete(url);
        } catch (Exception ex)  {
            ex.printStackTrace(); // Return null for any exception
        }
    }

Set the current value for this muffin.
@param strParam The key for this muffin parameter.
@param strValue The value for this muffin.


public Transferable getClipboardContents()
    {
        if ((clipboardReadStatus & CLIPBOARD_DISABLED) == CLIPBOARD_DISABLED)
            return null;    // Rejected it last time, don't ask again
        clipboardReadStatus = CLIPBOARD_DISABLED;
        if (cs == null)
        {
            try {
                cs = (ClipboardService)ServiceManager.lookup("javax.jnlp.ClipboardService");
            } catch (UnavailableServiceException e) {
                cs = null;
            }
        }

        if (cs != null) {
            // get the contents of the system clipboard and print them
            Transferable tr = cs.getContents();
            if (tr != null)
                clipboardReadStatus = CLIPBOARD_ENABLED;
            return tr;
        }
        return null;
    }

Get data from the system clipboard.
@return


public boolean setClipboardContents(Transferable data)
    {
        if (data == null)
            return false;
        if ((clipboardWriteStatus & CLIPBOARD_DISABLED) == CLIPBOARD_DISABLED)
            return false;    // Rejected it last time, don't ask again
        clipboardWriteStatus = CLIPBOARD_ENABLED;
        if (cs == null)
        {
            try {
                cs = (ClipboardService)ServiceManager.lookup("javax.jnlp.ClipboardService");
            } catch (UnavailableServiceException e) {
                cs = null;
            }
        }

        if (cs != null)
        { // set the system clipboard contents to a string selection
            try {
                cs.setContents(data);
                clipboardWriteStatus = CLIPBOARD_ENABLED;
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

Set the global clipboard contents.
@param data


public InputStream openFileStream(String pathHint, String[] extensions)
    {
        if (fos == null)
        {
            try {
                fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
            } catch (UnavailableServiceException e) {
                fos = null;
            }
        }

        if (fos != null) {
            try {
                // ask user to select a file through this service
                FileContents fc = fos.openFileDialog(pathHint, extensions);
                return fc.getInputStream();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


public static <T extends Service> Map<String, T> loadServicesByType(Class<T> clazz)
    {
        ServiceLoader<T> loader = ServiceLoader.load(clazz);
        Iterator<T> it = loader.iterator();
        Map<String, T> ret = new HashMap<String, T>();
        while (it.hasNext())
        {
            T op = it.next();
            ret.put(op.getId(), op);
            if (op instanceof ParametrizedOperation)
                addParametrizedService(op.getId(), (ParametrizedOperation) op);
            if (op instanceof ScriptObject)
                addScriptObject(((ScriptObject) op).getVarName(), (ScriptObject) op);
        }
        return ret;
    }

public static < T extends Service > Map < String , T > loadServicesByType ( Class < T > clazz ) { ServiceLoader < T > loader = ServiceLoader . load ( clazz ) ; Iterator < T > it = loader . iterator ( ) ; Map < String , T > ret = new HashMap < String , T > ( ) ; while ( it . hasNext ( ) ) { T op = it . next ( ) ; ret . put ( op . getId ( ) , op ) ; if ( op instanceof ParametrizedOperation ) addParametrizedService ( op . getId ( ) , ( ParametrizedOperation ) op ) ; if ( op instanceof ScriptObject ) addScriptObject ( ( ( ScriptObject ) op ) . getVarName ( ) , ( ScriptObject ) op ) ; } return ret ; }

Discovers the registered services of the given class.
@param clazz the class of the required services
@return A map that maps the services to their identifiers

Discovers the registered services of the given class .


public static void setServiceParams(ParametrizedOperation op, Map<String, Object> params)
    {
        if (params != null)
        {
            for (Map.Entry<String, Object> entry : params.entrySet())
            {
                op.setParam(entry.getKey(), entry.getValue());
            }
        }
    }

public static void setServiceParams ( ParametrizedOperation op , Map < String , Object > params ) { if ( params != null ) { for ( Map . Entry < String , Object > entry : params . entrySet ( ) ) { op . setParam ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }

Sets the operation parametres based on a map of values.
@param op The operation whose parametres should be set
@param params A map that assigns values to parameter names

Sets the operation parametres based on a map of values .


public static Map<String, Object> getServiceParams(ParametrizedOperation op)
    {
        Map<String, Object> ret = new HashMap<String, Object>();
        for (Parameter param : op.getParams())
        {
            ret.put(param.getName(), op.getParam(param.getName()));
        }
        return ret;
    }

public static Map < String , Object > getServiceParams ( ParametrizedOperation op ) { Map < String , Object > ret = new HashMap < String , Object > ( ) ; for ( Parameter param : op . getParams ( ) ) { ret . put ( param . getName ( ) , op . getParam ( param . getName ( ) ) ) ; } return ret ; }

Obtains the values of all the parametres of the given operation.
@param op The operation whose parametres should be set
@return A map that assigns values to parameter names

Obtains the values of all the parametres of the given operation .


public static ParametrizedOperation findParmetrizedService(String id)
    {
        if (parametrizedServices == null)
            return null;
        else
            return parametrizedServices.get(id);
    }

public static ParametrizedOperation findParmetrizedService ( String id ) { if ( parametrizedServices == null ) return null ; else return parametrizedServices . get ( id ) ; }

Finds a parametrized service based on its ID.
@param id the service ID.
@return the parametrized operation object or {@code null} when the service does not exist.

Finds a parametrized service based on its ID .


public static <T> T findByClass(Collection<?> services, Class<T> clazz)
    {
        for (Object serv : services)
        {
            if (clazz.isInstance(serv))
                return clazz.cast(serv);
        }
        return null;
    }

public static < T > T findByClass ( Collection < ? > services , Class < T > clazz ) { for ( Object serv : services ) { if ( clazz . isInstance ( serv ) ) return clazz . cast ( serv ) ; } return null ; }

Finds a service in a collection of services based on its class.
@param services the collection of services to scan
@param clazz the required class of the service
@return the fisrt service in the collection that is instance of the given class or {@code null} when
no such servise is present in the collection.

Finds a service in a collection of services based on its class .


private <T> T parseQuery(final String response, final Class<T> responseClass) {
		T queryResponse;
		try {
			/*
			 * Possible exceptions:
			 *
			 * IOException - if the underlying input source has problems during parsing
			 *
			 * JsonParseException - if parser has problems parsing content
			 *
			 * JsonMappingException - if the parser does not have any more content to map (note: Json "null" value is considered content; enf-of-stream not)
			 */
			queryResponse = MAPPER.readValue(response, responseClass);
		} catch (JsonParseException | JsonMappingException e) {
			try {
				final ErrorResponse error = MAPPER.readValue(response, ErrorResponse.class);

				LOGGER.error("Query returned an error: {}", error);
				return null;
			} catch (final IOException e1) {
				LOGGER.error("Failed to read error response.", e1);
			}
			LOGGER.error("Error reading response.", e);
			return null;
		} catch (final IOException e) {
			LOGGER.error("Error reading response.", e);
			return null;
		}

		return queryResponse;
	}

Parses the results of a query and handles any errors.

Parses the results of a query and handles any errors .


@Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            int iteratorIndex;
            int iteratorBufferIndex;
            int iteratorOffset;

            @Override
            public boolean hasNext() {
                return iteratorIndex < size;
            }

            @Override
            public E next() {
                if (iteratorIndex >= size) {
                    throw new NoSuchElementException();
                }
                E[] buf = buffers[iteratorBufferIndex];
                E result = buf[iteratorOffset];

                // increment
                iteratorIndex++;
                iteratorOffset++;
                if (iteratorOffset >= buf.length) {
                    iteratorOffset = 0;
                    iteratorBufferIndex++;
                }

                return result;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

@
Override
public
Iterator
<
E
>
iterator
(
)
{
return
new
Iterator
<
E
>
(
)
{
int
iteratorIndex
;
int
iteratorBufferIndex
;
int
iteratorOffset
;
@
Override
public
boolean
hasNext
(
)
{
return
iteratorIndex
<
size
;
}
@
Override
public
E
next
(
)
{
if
(
iteratorIndex
>=
size
)
{
throw
new
NoSuchElementException
(
)
;
}
E
[
]
buf
=
buffers
[
iteratorBufferIndex
]
;
E
result
=
buf
[
iteratorOffset
]
;
// increment
iteratorIndex
++
;
iteratorOffset
++
;
if
(
iteratorOffset
>=
buf
.
length
)
{
iteratorOffset
=
0
;
iteratorBufferIndex
++
;
}
return
result
;
}
@
Override
public
void
remove
(
)
{
throw
new
UnsupportedOperationException
(
)
;
}
}
;
}

Returns an iterator over buffer elements.

Returns an iterator over buffer elements .


public static String getEncoding(String xmlStr) {
        String result;

        String xml = xmlStr.trim();

        if (xml.startsWith("<?xml")) {
            int end = xml.indexOf("?>");
            int encIndex = xml.indexOf("encoding=");
            if (encIndex != -1) {
                String sub = xml.substring(encIndex + 9, end);
                result = CommUtil.substringBetween(sub, "\"", "\"");
                return result;
            }
        }
        return null;
    }

public static String getEncoding ( String xmlStr ) { String result ; String xml = xmlStr . trim ( ) ; if ( xml . startsWith ( "<?xml" ) ) { int end = xml . indexOf ( "?>" ) ; int encIndex = xml . indexOf ( "encoding=" ) ; if ( encIndex != - 1 ) { String sub = xml . substring ( encIndex + 9 , end ) ; result = CommUtil . substringBetween ( sub , "\"" , "\"" ) ; return result ; } } return null ; }

Obtain xml file encoding attribute

@param xmlStr xml String
@return encoding value


@Override
    public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
        if (drivers.size() == 1) {
            return getFirstDriver().getParentLogger();
        }
        return null;
    }

@ Override public java . util . logging . Logger getParentLogger ( ) throws SQLFeatureNotSupportedException { if ( drivers . size ( ) == 1 ) { return getFirstDriver ( ) . getParentLogger ( ) ; } return null ; }


public static Connection getInstance(Connection conn) {
        InvocationHandler handler = new JdbcLogConnection(conn);
        ClassLoader cl = Connection.class.getClassLoader();
        return (Connection) Proxy.newProxyInstance(cl, new Class[] { Connection.class }, handler);
    }

public static Connection getInstance ( Connection conn ) { InvocationHandler handler = new JdbcLogConnection ( conn ) ; ClassLoader cl = Connection . class . getClassLoader ( ) ; return ( Connection ) Proxy . newProxyInstance ( cl , new Class [ ] { Connection . class } , handler ) ; }

Creates a logging version of a connection

@param conn - the original connection
@return - the connection with logging


@Override
	public String getAuthorization(String authorizationUrl)
			throws CubeSensorsException {

		System.out.println("authorizationUrl:" + authorizationUrl);
		System.out.print("provide authorization code:");

		try (Scanner in = new Scanner(System.in)) {
			String authorization = in.nextLine();
			return authorization;
		}
	}

@
Override
public
String
getAuthorization
(
String
authorizationUrl
)
throws
CubeSensorsException
{
System
.
out
.
println
(
"authorizationUrl:"
+
authorizationUrl
)
;
System
.
out
.
print
(
"provide authorization code:"
)
;
try
(
Scanner
in
=
new
Scanner
(
System
.
in
)
)
{
String
authorization
=
in
.
nextLine
(
)
;
return
authorization
;
}
}

Prints the authorizationUrl, the user will open the url and obtain an
authorization key. When prompted, the user should provide the authorization
key.

Prints the authorizationUrl the user will open the url and obtain an authorization key . When prompted the user should provide the authorization key .


public void visitPackageDeclaration(PackageDeclaration d) {
		d.accept(pre);

		for (ClassDeclaration classDecl : d.getClasses()) {
			classDecl.accept(this);
		}

		for (InterfaceDeclaration interfaceDecl : d.getInterfaces()) {
			interfaceDecl.accept(this);
		}

		d.accept(post);
	}

public void visitPackageDeclaration ( PackageDeclaration d ) { d . accept ( pre ) ; for ( ClassDeclaration classDecl : d . getClasses ( ) ) { classDecl . accept ( this ) ; } for ( InterfaceDeclaration interfaceDecl : d . getInterfaces ( ) ) { interfaceDecl . accept ( this ) ; } d . accept ( post ) ; }

Visits a package declaration.

@param d the declaration to visit


public void visitClassDeclaration(ClassDeclaration d) {
		d.accept(pre);

		for (TypeParameterDeclaration tpDecl : d.getFormalTypeParameters()) {
			tpDecl.accept(this);
		}

		for (FieldDeclaration fieldDecl : d.getFields()) {
			fieldDecl.accept(this);
		}

		for (MethodDeclaration methodDecl : d.getMethods()) {
			methodDecl.accept(this);
		}

		for (TypeDeclaration typeDecl : d.getNestedTypes()) {
			typeDecl.accept(this);
		}

		for (ConstructorDeclaration ctorDecl : d.getConstructors()) {
			ctorDecl.accept(this);
		}

		d.accept(post);
	}

public void visitClassDeclaration ( ClassDeclaration d ) { d . accept ( pre ) ; for ( TypeParameterDeclaration tpDecl : d . getFormalTypeParameters ( ) ) { tpDecl . accept ( this ) ; } for ( FieldDeclaration fieldDecl : d . getFields ( ) ) { fieldDecl . accept ( this ) ; } for ( MethodDeclaration methodDecl : d . getMethods ( ) ) { methodDecl . accept ( this ) ; } for ( TypeDeclaration typeDecl : d . getNestedTypes ( ) ) { typeDecl . accept ( this ) ; } for ( ConstructorDeclaration ctorDecl : d . getConstructors ( ) ) { ctorDecl . accept ( this ) ; } d . accept ( post ) ; }

Visits a class declaration.

@param d the declaration to visit


public void visitExecutableDeclaration(ExecutableDeclaration d) {
		d.accept(pre);

		for (TypeParameterDeclaration tpDecl : d.getFormalTypeParameters()) {
			tpDecl.accept(this);
		}

		for (ParameterDeclaration pDecl : d.getParameters()) {
			pDecl.accept(this);
		}

		d.accept(post);
	}

public void visitExecutableDeclaration ( ExecutableDeclaration d ) { d . accept ( pre ) ; for ( TypeParameterDeclaration tpDecl : d . getFormalTypeParameters ( ) ) { tpDecl . accept ( this ) ; } for ( ParameterDeclaration pDecl : d . getParameters ( ) ) { pDecl . accept ( this ) ; } d . accept ( post ) ; }

Visits a method or constructor declaration.

@param d the declaration to visit

Visits a method or constructor declaration .


@SuppressWarnings("unchecked")
    private static <T> T getOption(final String key, final Map<String, ?> properties) {

        // private method asserts
        assert key != null : "The key cannot be null";

        return (T) properties.get(key);
    }

@
SuppressWarnings
(
"unchecked"
)
private
static
<
T
>
T
getOption
(
final
String
key
,
final
Map
<
String
,
>
properties
)
{
// private method asserts
assert
key
!=
:
"The key cannot be null"
;
return
(
T
)
properties
.
get
(
key
)
;
}

Return the value of a JAAS configuration parameter.

@param <T>        The type of the element
@param key        The key to retrieve from the options
@param properties The properties to retrieve values from
@return The configuration value for the provided key

Return the value of a JAAS configuration parameter .


public static DeclarationFilter getFilter(
			final Collection<Modifier> mods) {
		return new DeclarationFilter() {
			public boolean matches(Declaration d) {
				return d.getModifiers().containsAll(mods);
			}
		};
	}

public static DeclarationFilter getFilter ( final Collection < Modifier > mods ) { return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return d . getModifiers ( ) . containsAll ( mods ) ; } } ; }

Returns a filter that selects declarations containing all of a
collection of modifiers.

@param mods the modifiers to match (non-null)
@return a filter that matches declarations containing <tt>mods</tt>

Returns a filter that selects declarations containing all of a collection of modifiers .


public static DeclarationFilter getFilter(
			final Class<? extends Declaration> kind) {
		return new DeclarationFilter() {
			public boolean matches(Declaration d) {
				return kind.isInstance(d);
			}
		};
	}

public static DeclarationFilter getFilter ( final Class < ? extends Declaration > kind ) { return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return kind . isInstance ( d ) ; } } ; }

Returns a filter that selects declarations of a particular kind.
For example, there may be a filter that selects only class
declarations, or only fields.
The filter will select declarations of the specified kind,
and also any subtypes of that kind; for example, a field filter
will also select enum constants.

@param kind the kind of declarations to select
@return a filter that selects declarations of a particular kind

Returns a filter that selects declarations of a particular kind . For example there may be a filter that selects only class declarations or only fields . The filter will select declarations of the specified kind and also any subtypes of that kind ; for example a field filter will also select enum constants .


public DeclarationFilter and(DeclarationFilter f) {
		final DeclarationFilter f1 = this;
		final DeclarationFilter f2 = f;
		return new DeclarationFilter() {
			public boolean matches(Declaration d) {
				return f1.matches(d) && f2.matches(d);
			}
		};
	}

public DeclarationFilter and ( DeclarationFilter f ) { final DeclarationFilter f1 = this ; final DeclarationFilter f2 = f ; return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return f1 . matches ( d ) && f2 . matches ( d ) ; } } ; }

Returns a filter that selects those declarations selected
by both this filter and another.

@param f filter to be composed with this one
@return a filter that selects those declarations selected by
both this filter and another

Returns a filter that selects those declarations selected by both this filter and another .


public DeclarationFilter or(DeclarationFilter f) {
		final DeclarationFilter f1 = this;
		final DeclarationFilter f2 = f;
		return new DeclarationFilter() {
			public boolean matches(Declaration d) {
				return f1.matches(d) || f2.matches(d);
			}
		};
	}

public DeclarationFilter or ( DeclarationFilter f ) { final DeclarationFilter f1 = this ; final DeclarationFilter f2 = f ; return new DeclarationFilter ( ) { public boolean matches ( Declaration d ) { return f1 . matches ( d ) || f2 . matches ( d ) ; } } ; }

Returns a filter that selects those declarations selected
by either this filter or another.

@param f filter to be composed with this one
@return a filter that selects those declarations selected by
either this filter or another

Returns a filter that selects those declarations selected by either this filter or another .


protected Map<String, V> getAsMap() {
        Map<String, V> result = map;
        if (result == null) {
            synchronized (this) {
                result = map;
                if (result == null) {
                    map = (result = initialize());
                }
            }
        }
        return result;
    }

protected Map < String , V > getAsMap ( ) { Map < String , V > result = map ; if ( result == null ) { synchronized ( this ) { result = map ; if ( result == null ) { map = ( result = initialize ( ) ) ; } } } return result ; }


public static <T> void makeAccessible(final Constructor<T> constructor) {
		if (!Modifier.isPublic(constructor.getModifiers())
				|| !Modifier.isPublic(constructor.getDeclaringClass()
						.getModifiers())) {
			constructor.setAccessible(true);
		}
	}

public static < T > void makeAccessible ( final Constructor < T > constructor ) { if ( ! Modifier . isPublic ( constructor . getModifiers ( ) ) || ! Modifier . isPublic ( constructor . getDeclaringClass ( ) . getModifiers ( ) ) ) { constructor . setAccessible ( true ) ; } }

set constructor is accessible
@param constructor {@link java.lang.reflect.Constructor}
@param <T> t


public ObjectQueryInfo prepareObjectQuery(Object obj) throws MalformedObjectNameException {

        ObjectQueryInfo result;

        //
        // Extract the mbean info from the object (TBD: cache this information ahead of time)
        //
        String onamePattern = MBeanAnnotationUtil.getLocationONamePattern(obj);

        if (onamePattern != null) {
            //
            // Locate the setters and continue only if at least one was found.
            //
            Map<String, Method> attributeSetters = MBeanAnnotationUtil.getAttributes(obj);

            if (attributeSetters.size() > 0) {
                String onameString;

                if (obj instanceof MBeanLocationParameterSource) {
                    onameString = this.parameterReplacer
                            .replaceObjectNameParameters(onamePattern, (MBeanLocationParameterSource) obj);
                } else {
                    onameString = onamePattern;
                }

                ObjectName oname = new ObjectName(onameString);

                result = new ObjectQueryInfo(obj, oname, attributeSetters);
            } else {
                this.logNoAttributeThrottle.warn(log,
                        "ignoring attempt to prepare to poll an MBean object with no attributes: onamePattern={}",
                        onamePattern);
                result = null;
            }
        } else {
            log.warn("ignoring attempt to prepare to poll object that has no MBeanLocation");
            result = null;
        }

        return result;
    }

Prepare to query the given object.

@param obj the object to prepare; must be annotated appropriately with @MBeanLocation on the class and
@MBeanAttribute on setter methods.
@return the results of the prepared object.
@throws MalformedObjectNameException
@see com.amlinv.jmxutil.annotation.MBeanLocation
@see com.amlinv.jmxutil.annotation.MBeanAttribute


public static String replaceSlashWithHyphen(String origin) {
		char[] resulltChars = origin.toCharArray();
		for (int i = 0; i < resulltChars.length - 1; i++) {
			if (resulltChars[i] == '/') {
				resulltChars[i] = '-';
			}
		}
		return new String(resulltChars, 0, resulltChars.length - 1);
	}

public static String replaceSlashWithHyphen ( String origin ) { char [ ] resulltChars = origin . toCharArray ( ) ; for ( int i = 0 ; i < resulltChars . length - 1 ; i ++ ) { if ( resulltChars [ i ] == ' ' ) { resulltChars [ i ] = ' ' ; } } return new String ( resulltChars , 0 , resulltChars . length - 1 ) ; }

replaces slashes with hyphens and removes padding=

@param origin
@return

replaces slashes with hyphens and removes padding =


public static String bytes2HexString(byte[] bytes) {
		StringBuffer resultBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			resultBuffer.append(byte2Hex(bytes[i]));
		}
		return resultBuffer.toString();
	}

public static String bytes2HexString ( byte [ ] bytes ) { StringBuffer resultBuffer = new StringBuffer ( ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { resultBuffer . append ( byte2Hex ( bytes [ i ] ) ) ; } return resultBuffer . toString ( ) ; }

Converts an array of bytes to a string of two digits hex-representations

@param bytes
@return

Converts an array of bytes to a string of two digits hex - representations


private List<Integer> getIndexes(String name) {
        List<Integer> indexes = nameIndexMap.get(name);
        if (indexes == null) {
            throw new IllegalArgumentException("Parameter not found: " + name);
        }
        return indexes;
    }

private
List
<
Integer
>
getIndexes
(
String
name
)
{
List
<
Integer
>
indexes
=
nameIndexMap
.
get
(
name
)
;
if
(
indexes
==
)
{
throw
new
IllegalArgumentException
(
"Parameter not found: "
+
name
)
;
}
return
indexes
;
}

Returns the indexes for a parameter.
@param name parameter name
@return parameter indexes
@throws IllegalArgumentException if the parameter does not exist


private static String parseNamedSql(String sql, Map<String, List<Integer>> nameIndexMap) {
        // I was originally using regular expressions, but they didn't work well for ignoring
        // parameter-like strings inside quotes.
        int length = sql.length();
        StringBuffer parsedSql = new StringBuffer(length);
        boolean inSingleQuote = false;
        boolean inDoubleQuote = false;
        int index = 1;
        for (int i = 0; i < length; i++) {
            char c = sql.charAt(i);
            if (inSingleQuote) {
                if (c == '\'') {
                    inSingleQuote = false;
                }
            } else if (inDoubleQuote) {
                if (c == '"') {
                    inDoubleQuote = false;
                }
            } else {
                if (c == '\'') {
                    inSingleQuote = true;
                } else if (c == '"') {
                    inDoubleQuote = true;
                } else if (c == ':' && i + 1 < length && Character.isJavaIdentifierStart(sql.charAt(i + 1))) {
                    int j = i + 2;
                    while (j < length && Character.isJavaIdentifierPart(sql.charAt(j))) {
                        j++;
                    }
                    String name = sql.substring(i + 1, j);
                    c = '?'; // replace the parameter with a question mark
                    i += name.length(); // skip past the end if the parameter
                    List<Integer> indexList = nameIndexMap.get(name);
                    if (indexList == null) {
                        indexList = new LinkedList<Integer>();
                        nameIndexMap.put(name, indexList);
                    }
                    indexList.add(index);
                    index++;
                }
            }
            parsedSql.append(c);
        }

        return parsedSql.toString();
    }

Parses a sql with named parameters. The parameter-index mappings
are put into the map, and the parsed sql is returned.
@param sql    sql with named parameters
@return the parsed sql

Parses a sql with named parameters . The parameter - index mappings are put into the map and the parsed sql is returned .


private static final Object convertCollectionToProtobufs(Collection<Object> collectionOfNonProtobufs) throws JException
  {
    if (collectionOfNonProtobufs.isEmpty())
    {
      return collectionOfNonProtobufs;
    }
    final Object first = collectionOfNonProtobufs.toArray()[0];
    if (!ProtobufSerializerUtils.isProtbufEntity(first))
    {
      return collectionOfNonProtobufs;
    }

    final Collection<Object> newCollectionValues;

    /**
     * Maintain the Collection type of value at this stage (if it is a Set), and if conversion is required to a
     * different Collection type, that will be handled by a converter later on
     */
    if (collectionOfNonProtobufs instanceof Set)
    {
      newCollectionValues = new HashSet<>();
    }
    else
    {
      newCollectionValues = new ArrayList<>();
    }

    for (Object iProtobufGenObj : collectionOfNonProtobufs)
    {
      newCollectionValues.add(serializeToProtobufEntity(iProtobufGenObj));
    }

    return newCollectionValues;
  }

Loops through the collection of objects and serializes them, iff they have ProtobufEntity annotations.

@param value - Collection<Object>
@return Object - Collection of serialized objects.
@throws JException

Loops through the collection of objects and serializes them iff they have ProtobufEntity annotations .


private static final void setProtobufFieldValue(ProtobufAttribute protobufAttribute, Builder protoObjBuilder, String setter,
          Object fieldValue) throws NoSuchMethodException, SecurityException, ProtobufAnnotationException, InstantiationException,
          IllegalAccessException, IllegalArgumentException, InvocationTargetException
  {
    Class<? extends Object> fieldValueClass = fieldValue.getClass();
    Class<? extends Object> gpbClass = fieldValueClass;

    final Class<? extends IProtobufConverter> converterClazz = protobufAttribute.converter();
    if (converterClazz != NullConverter.class)
    {
      final IProtobufConverter protoBufConverter = (IProtobufConverter)converterClazz.newInstance();
      fieldValue = protoBufConverter.convertToProtobuf(fieldValue);
      gpbClass = fieldValue.getClass();
      fieldValueClass = gpbClass;
    }

    // Need to convert the argument class from non-primitives to primitives, as Protobuf uses these.
    gpbClass = ProtobufSerializerUtils.getProtobufClass(fieldValue, gpbClass);

    final Method gpbMethod = protoObjBuilder.getClass().getDeclaredMethod(setter, gpbClass);
    gpbMethod.invoke(protoObjBuilder, fieldValue);
  }

This method does the actual "set" on the Protobuf builder. If the user specified a converter,
then use that right before we actually try and set the value.

@param protobufAttribute - ProtobufAttribute
@param protoObjBuilder - G.Builder
@param setter - String
@param fieldValue - POJO's filed Object
@throws NoSuchMethodException
@throws SecurityException
@throws ProtobufAnnotationException
@throws InstantiationException
@throws IllegalAccessException
@throws IllegalArgumentException
@throws InvocationTargetException

This method does the actual set on the Protobuf builder . If the user specified a converter then use that right before we actually try and set the value .


private static final void setPojoFieldValue(Object pojo, String setter, Object protobufValue, ProtobufAttribute protobufAttribute)
          throws InstantiationException, IllegalAccessException, JException
  {
    /**
     * convertCollectionFromProtoBufs() above returns an ArrayList, and we may have a converter to convert to a Set,
     * so we are performing the conversion there
     */
    final Class<? extends IProtobufConverter> fromProtoBufConverter = protobufAttribute.converter();
    if (fromProtoBufConverter != NullConverter.class)
    {
      final IProtobufConverter converter = fromProtoBufConverter.newInstance();
      protobufValue = converter.convertFromProtobuf(protobufValue);
    }

    Class<? extends Object> argClazz = protobufValue.getClass();

    JReflectionUtils.runSetter(pojo, setter, protobufValue, argClazz);
  }

This method does the actual "set" on the POJO instance. If the user specified a converter,
then use that right before we actually try and set the value.

@param pojo - the instance of the POJO
@param setter - the setter method name
@param protobufValue - the Protobuf value, note this could be anything from another ProtobufEntity to a primitive, like boolean
@param protobufAttribute - the ProtobufAttribute annotation
@throws InstantiationException
@throws IllegalAccessException
@throws JException

This method does the actual set on the POJO instance . If the user specified a converter then use that right before we actually try and set the value .


public boolean accept(File pathname)
	{
		String name = pathname.getName();
		int iLastDot = name.lastIndexOf('.');
		String strExtension = "";
		if ((iLastDot != -1)
			&& (iLastDot != name.length() -1 ))
				strExtension = name.substring(iLastDot + 1);
		if (m_rgstrIncludeExtensions != null)
		{
			for (int i = 0; i < m_rgstrIncludeExtensions.length; i++)
			{
				if (m_rgstrIncludeExtensions[i].equalsIgnoreCase(strExtension))
					return true;	// Accept
			}
			return false;	// Not in included - return
		}
		if (m_rgstrExcludeExtensions != null)
		{
			for (int i = 0; i < m_rgstrExcludeExtensions.length; i++)
			{
				if (m_rgstrExcludeExtensions[i].equalsIgnoreCase(strExtension))
					return false;	// Don't accept
			}
		}
		return true;	// Accept this file
	}

public
boolean
accept
(
File
pathname
)
{
String
name
=
pathname
.
getName
(
)
;
int
iLastDot
=
name
.
lastIndexOf
(
'
'
)
;
String
strExtension
=
""
;
if
(
(
iLastDot
!=
1
)
&&
(
iLastDot
!=
name
.
length
(
)
1
)
)
strExtension
=
name
.
substring
(
iLastDot
+
1
)
;
if
(
m_rgstrIncludeExtensions
!=
)
{
for
(
int
i
=
0
;
i
<
m_rgstrIncludeExtensions
.
length
;
i
++
)
{
if
(
m_rgstrIncludeExtensions
[
i
]
.
equalsIgnoreCase
(
strExtension
)
)
return
true
;
// Accept
}
return
false
;
// Not in included - return
}
if
(
m_rgstrExcludeExtensions
!=
)
{
for
(
int
i
=
0
;
i
<
m_rgstrExcludeExtensions
.
length
;
i
++
)
{
if
(
m_rgstrExcludeExtensions
[
i
]
.
equalsIgnoreCase
(
strExtension
)
)
return
false
;
// Don't accept
}
}
return
true
;
// Accept this file
}

Tests whether or not the specified abstract pathname should be
included in a pathname list.

@param  pathname  The abstract pathname to be tested
@return  true if and only if pathname
should be included

Tests whether or not the specified abstract pathname should be included in a pathname list .


public static ResultSet getInstance(ResultSet rs) {
        InvocationHandler handler = new JdbcLogResultSet(rs);
        ClassLoader cl = ResultSet.class.getClassLoader();
        return (ResultSet) Proxy.newProxyInstance(cl, new Class[] { ResultSet.class }, handler);
    }

public static ResultSet getInstance ( ResultSet rs ) { InvocationHandler handler = new JdbcLogResultSet ( rs ) ; ClassLoader cl = ResultSet . class . getClassLoader ( ) ; return ( ResultSet ) Proxy . newProxyInstance ( cl , new Class [ ] { ResultSet . class } , handler ) ; }

Creates a logging version of a ResultSet

@param rs   - the ResultSet to proxy
@return - the ResultSet with logging


private static Map<ExpectedLabels, Integer> mapLabels(final List<String> labels) {
		final Map<ExpectedLabels, Integer> map = new EnumMap<>(ExpectedLabels.class);

		final List<ExpectedLabels> unusedLabels = new ArrayList<>(Arrays.asList(ExpectedLabels.values()));
		for (int index = 0; index < labels.size(); index++) {
			final String next = labels.get(index);
			ExpectedLabels labelValue;
			try {
				labelValue = ExpectedLabels.valueOf(next);

				unusedLabels.remove(labelValue);
				if (map.containsKey(labelValue)) {
					LOGGER.warn("Duplicate state label: {} ({})", next, labels);
				}
				map.put(labelValue, index);
			} catch (final IllegalArgumentException e) {
				LOGGER.warn("Unexpected state label: {}", next);
			}
		}
		for (final ExpectedLabels label : unusedLabels) {
			LOGGER.warn("Unused label: {}", label);
		}

		return map;
	}

private
static
Map
<
ExpectedLabels
,
Integer
>
mapLabels
(
final
List
<
String
>
labels
)
{
final
Map
<
ExpectedLabels
,
Integer
>
map
=
new
EnumMap
<>
(
ExpectedLabels
.
class
)
;
final
List
<
ExpectedLabels
>
unusedLabels
=
new
ArrayList
<>
(
Arrays
.
asList
(
ExpectedLabels
.
values
(
)
)
)
;
for
(
int
index
=
0
;
index
<
labels
.
size
(
)
;
index
++
)
{
final
String
next
=
labels
.
get
(
index
)
;
ExpectedLabels
labelValue
;
try
{
labelValue
=
ExpectedLabels
.
valueOf
(
next
)
;
unusedLabels
.
remove
(
labelValue
)
;
if
(
map
.
containsKey
(
labelValue
)
)
{
LOGGER
.
warn
(
"Duplicate state label: {} ({})"
,
next
,
labels
)
;
}
map
.
put
(
labelValue
,
index
)
;
}
catch
(
final
IllegalArgumentException
e
)
{
LOGGER
.
warn
(
"Unexpected state label: {}"
,
next
)
;
}
}
for
(
final
ExpectedLabels
label
:
unusedLabels
)
{
LOGGER
.
warn
(
"Unused label: {}"
,
label
)
;
}
return
map
;
}

Produces a mapping of label to index for use in parsing state values to the appropriate slot in the state object.

Produces a mapping of label to index for use in parsing state values to the appropriate slot in the state object .


private static State extractValues(final List<Object> values, final Map<ExpectedLabels, Integer> map) {
		final ZonedDateTime time = ZonedDateTime.parse((String) values.get(map.get(ExpectedLabels.time)));
		final int temp = safeInt((Integer) values.get(map.get(ExpectedLabels.temp)));
		final int pressure = safeInt((Integer) values.get(map.get(ExpectedLabels.pressure)));
		final int humidity = safeInt((Integer) values.get(map.get(ExpectedLabels.humidity)));
		final int voc = safeInt((Integer) values.get(map.get(ExpectedLabels.voc)));
		final int light = safeInt((Integer) values.get(map.get(ExpectedLabels.light)));
		final int noise = safeInt((Integer) values.get(map.get(ExpectedLabels.noise)));
		final int noisedba = safeInt((Integer) values.get(map.get(ExpectedLabels.noisedba)));
		final int battery = safeInt((Integer) values.get(map.get(ExpectedLabels.battery)));
		final boolean shake = safeBoolean((Boolean) values.get(map.get(ExpectedLabels.shake)));
		final boolean cable = safeBoolean((Boolean) values.get(map.get(ExpectedLabels.cable)));
		final int vocResistance = safeInt((Integer) values.get(map.get(ExpectedLabels.voc_resistance)));
		final int rssi = safeInt((Integer) values.get(map.get(ExpectedLabels.rssi)));
		return new State(time, temp, pressure, humidity, voc, light, noise, noisedba, battery, shake, cable, vocResistance, rssi);
	}

private static State extractValues ( final List < Object > values , final Map < ExpectedLabels , Integer > map ) { final ZonedDateTime time = ZonedDateTime . parse ( ( String ) values . get ( map . get ( ExpectedLabels . time ) ) ) ; final int temp = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . temp ) ) ) ; final int pressure = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . pressure ) ) ) ; final int humidity = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . humidity ) ) ) ; final int voc = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . voc ) ) ) ; final int light = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . light ) ) ) ; final int noise = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . noise ) ) ) ; final int noisedba = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . noisedba ) ) ) ; final int battery = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . battery ) ) ) ; final boolean shake = safeBoolean ( ( Boolean ) values . get ( map . get ( ExpectedLabels . shake ) ) ) ; final boolean cable = safeBoolean ( ( Boolean ) values . get ( map . get ( ExpectedLabels . cable ) ) ) ; final int vocResistance = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . voc_resistance ) ) ) ; final int rssi = safeInt ( ( Integer ) values . get ( map . get ( ExpectedLabels . rssi ) ) ) ; return new State ( time , temp , pressure , humidity , voc , light , noise , noisedba , battery , shake , cable , vocResistance , rssi ) ; }

Uses the provided label-index mapping to extract state values and create a new State object.

Uses the provided label - index mapping to extract state values and create a new State object .


public static Class<?> getGenericSupertype(Class<?> type, int index) {
        return getComponentType(type.getGenericSuperclass(), null, index);
    }

public static Class < ? > getGenericSupertype ( Class < ? > type , int index ) { return getComponentType ( type . getGenericSuperclass ( ) , null , index ) ; }

Returns generic supertype for given class and 0-based index.
@see #getComponentType(java.lang.reflect.Type, int)

Returns generic supertype for given class and 0 - based index .


public void poll() throws IOException {
        synchronized (this) {
            // Make sure not to check and create a connection if shutting down.
            if (shutdownInd) {
                return;
            }

            // Atomically indicate polling is active now so a caller can determine with certainty whether polling is
            //  completely shutdown.
            pollActiveInd = true;
        }

        try {
            this.checkConnection();

            this.concurrencyTestHooks.beforePollProcessorStart();

            if (this.mBeanAccessConnection instanceof MBeanBatchCapableAccessConnection) {
                this.batchPollProcessor.pollBatch((MBeanBatchCapableAccessConnection) this.mBeanAccessConnection,
                        this.polledObjects);
            } else {
                this.pollIndividually();
            }
        } catch (IOException ioExc) {
            this.safeClose(this.mBeanAccessConnection);
            this.mBeanAccessConnection = null;

            throw ioExc;
        } finally {
            this.concurrencyTestHooks.afterPollProcessorFinish();

            synchronized (this) {
                pollActiveInd = false;
                this.notifyAll();
            }
        }
    }

Poll the configured objects now and store the results in the objects themselves.

@throws IOException

Poll the configured objects now and store the results in the objects themselves .


protected boolean pollIndividually() throws IOException {
        this.concurrencyTestHooks.onStartPollIndividually();

        List<SchedulerProcessExecutionSlip> processExecutionSlipList = new LinkedList<>();
        for (final Object onePolledObject : this.polledObjects) {
            // Stop as soon as possible if shutting down.
            if (shutdownInd) {
                return true;
            }

            SchedulerProcess process = new PollOneObjectSchedulerProcess(onePolledObject);
            SchedulerProcessExecutionSlip executionSlip = this.scheduler.startProcess(process);
            processExecutionSlipList.add(executionSlip);
        }

        for (SchedulerProcessExecutionSlip oneExecutionSlip : processExecutionSlipList) {
            try {
                //
                // Wait for this process to complete
                //
                oneExecutionSlip.waitUntilComplete();

                //
                // Check for a failure
                //
                PollOneObjectSchedulerProcess process =
                        (PollOneObjectSchedulerProcess) oneExecutionSlip.getSchedulerProcess();

                Exception exc = process.getFailureException();
                if (exc != null) {
                    log.warn("failed to poll object", exc);

                    // Propagate IOExceptions since they most likely mean that the connection needs to be recovered.
                    if (exc instanceof IOException) {
                        throw (IOException) exc;
                    }
                }

            } catch (InterruptedException intExc) {
                log.info("interrupted while polling object");
            }
        }

        return false;
    }

Poll all of the objects, one at a time.

@return false => if polling completed normally; true => if polling stopped due to shutdown.
@throws IOException


public static Field getDeclaredField(Class<?> clazz, String fieldName,
			boolean recursively) {
		try {
			return clazz.getDeclaredField(fieldName);
		} catch (NoSuchFieldException e) {
			Class<?> superClass = clazz.getSuperclass();
			if (superClass != null && recursively) {
				return getDeclaredField(superClass, fieldName, true);
			}
		} catch (SecurityException e) {
			log.error("{}",e.getMessage(),e);
		}
		return null;

	}

public static Field getDeclaredField ( Class < ? > clazz , String fieldName , boolean recursively ) { try { return clazz . getDeclaredField ( fieldName ) ; } catch ( NoSuchFieldException e ) { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { return getDeclaredField ( superClass , fieldName , true ) ; } } catch ( SecurityException e ) { log . error ( "{}" , e . getMessage ( ) , e ) ; } return null ; }

obtain field If recursively is true, obtain fields from all class
hierarchy

@param clazz class
where fields are searching
@param fieldName
field name
@param recursively
param
@return list of fields

obtain field If recursively is true obtain fields from all class hierarchy


public static Method[] getDeclaredMethods(Class<?> clazz,
			boolean recursively) {
		List<Method> methods = new LinkedList<Method>();
		Method[] declaredMethods = clazz.getDeclaredMethods();
		Collections.addAll(methods, declaredMethods);

		Class<?> superClass = clazz.getSuperclass();

		if (superClass != null && recursively) {
			Method[] declaredMethodsOfSuper = getDeclaredMethods(superClass,
					true);
			if (declaredMethodsOfSuper.length > 0)
				Collections.addAll(methods, declaredMethodsOfSuper);
		}
		return methods.toArray(new Method[methods.size()]);
	}

public static Method [ ] getDeclaredMethods ( Class < ? > clazz , boolean recursively ) { List < Method > methods = new LinkedList < Method > ( ) ; Method [ ] declaredMethods = clazz . getDeclaredMethods ( ) ; Collections . addAll ( methods , declaredMethods ) ; Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { Method [ ] declaredMethodsOfSuper = getDeclaredMethods ( superClass , true ) ; if ( declaredMethodsOfSuper . length > 0 ) Collections . addAll ( methods , declaredMethodsOfSuper ) ; } return methods . toArray ( new Method [ methods . size ( ) ] ) ; }

obtain methods list of specified class If recursively is true, obtain
methods from all class hierarchy

@param clazz class
where fields are searching
@param recursively
param
@return array of methods

obtain methods list of specified class If recursively is true obtain methods from all class hierarchy


public static Method getDeclaredMethod(Class<?> clazz, boolean recursively,
			String methodName, Class<?>... parameterTypes) {

		try {
			return clazz.getDeclaredMethod(methodName,
					parameterTypes);
		} catch (NoSuchMethodException e) {
			Class<?> superClass = clazz.getSuperclass();
			if (superClass != null && recursively) {
				return getDeclaredMethod(superClass, true, methodName,
						parameterTypes);
			}
		} catch (SecurityException e) {
			log.error("{}",e.getMessage(),e);
		}
		return null;
	}

public static Method getDeclaredMethod ( Class < ? > clazz , boolean recursively , String methodName , Class < ? > ... parameterTypes ) { try { return clazz . getDeclaredMethod ( methodName , parameterTypes ) ; } catch ( NoSuchMethodException e ) { Class < ? > superClass = clazz . getSuperclass ( ) ; if ( superClass != null && recursively ) { return getDeclaredMethod ( superClass , true , methodName , parameterTypes ) ; } } catch ( SecurityException e ) { log . error ( "{}" , e . getMessage ( ) , e ) ; } return null ; }

obtain method list of specified class If recursively is true, obtain
method from all class hierarchy

@param clazz class
@param recursively recursively
@param methodName method name
@param parameterTypes parameter types
@return method

obtain method list of specified class If recursively is true obtain method from all class hierarchy


public static Method[] getAnnotatedDeclaredMethods(Class<?> clazz,
			Class<? extends Annotation> annotationClass, boolean recursively) {
		Method[] allMethods = getDeclaredMethods(clazz, recursively);
		List<Method> annotatedMethods = new LinkedList<Method>();

		for (Method method : allMethods) {
			if (method.isAnnotationPresent(annotationClass))
				annotatedMethods.add(method);
		}

		return annotatedMethods.toArray(new Method[annotatedMethods.size()]);
	}

public static Method [ ] getAnnotatedDeclaredMethods ( Class < ? > clazz , Class < ? extends Annotation > annotationClass , boolean recursively ) { Method [ ] allMethods = getDeclaredMethods ( clazz , recursively ) ; List < Method > annotatedMethods = new LinkedList < Method > ( ) ; for ( Method method : allMethods ) { if ( method . isAnnotationPresent ( annotationClass ) ) annotatedMethods . add ( method ) ; } return annotatedMethods . toArray ( new Method [ annotatedMethods . size ( ) ] ) ; }

obtain methods list of specified class and which are annotated by
incoming annotation class If recursively is true, obtain methods from all
class hierarchy

@param clazz class
- where methods are searching
@param annotationClass
- specified annotation class
@param recursively
param
@return list of annotated methods

obtain methods list of specified class and which are annotated by incoming annotation class If recursively is true obtain methods from all class hierarchy


public static Constructor<?>[] getAnnotatedDeclaredConstructors(
			Class<?> clazz, Class<? extends Annotation> annotationClass,
			boolean recursively) {
		Constructor<?>[] allConstructors = getDeclaredConstructors(clazz,
				recursively);
		List<Constructor<?>> annotatedConstructors = new LinkedList<Constructor<?>>();

		for (Constructor<?> field : allConstructors) {
			if (field.isAnnotationPresent(annotationClass))
				annotatedConstructors.add(field);
		}

		return annotatedConstructors
				.toArray(new Constructor<?>[annotatedConstructors.size()]);
	}

public static Constructor < ? > [ ] getAnnotatedDeclaredConstructors ( Class < ? > clazz , Class < ? extends Annotation > annotationClass , boolean recursively ) { Constructor < ? > [ ] allConstructors = getDeclaredConstructors ( clazz , recursively ) ; List < Constructor < ? > > annotatedConstructors = new LinkedList < Constructor < ? > > ( ) ; for ( Constructor < ? > field : allConstructors ) { if ( field . isAnnotationPresent ( annotationClass ) ) annotatedConstructors . add ( field ) ; } return annotatedConstructors . toArray ( new Constructor < ? > [ annotatedConstructors . size ( ) ] ) ; }

obtain constructors list of specified class and which are annotated by
incoming annotation class If recursively is true, obtain constructors
from all class hierarchy

@param clazz class
- where constructors are searching
@param annotationClass
- specified annotation class
@param recursively
param
@return list of annotated constructors

obtain constructors list of specified class and which are annotated by incoming annotation class If recursively is true obtain constructors from all class hierarchy


protected void dumpByte(int b) {
        if (passThrough == true) {
            System.out.print('\t');
        }
        if (b < 0) {
            b += 128;
        }
        if (b < 0x10) {
            System.out.print('0');
        }

        System.out.print(' ');
        System.out.print(Integer.toHexString(b).toUpperCase());
    }

protected void dumpByte ( int b ) { if ( passThrough == true ) { System . out . print ( ' ' ) ; } if ( b < 0 ) { b += 128 ; } if ( b < 0x10 ) { System . out . print ( ' ' ) ; } System . out . print ( ' ' ) ; System . out . print ( Integer . toHexString ( b ) . toUpperCase ( ) ) ; }


public static int indexOfIgnoreCase(String s, String substr, int startIndex, int endIndex) {
        if (startIndex < 0) {
            startIndex = 0;
        }
        int srclen = s.length();
        if (endIndex > srclen) {
            endIndex = srclen;
        }

        int sublen = substr.length();
        if (sublen == 0) {
            return startIndex > srclen ? srclen : startIndex;
        }
        substr = substr.toLowerCase();
        int total = endIndex - sublen + 1;
        char c = substr.charAt(0);
        mainloop: for (int i = startIndex; i < total; i++) {
            if (Character.toLowerCase(s.charAt(i)) != c) {
                continue;
            }
            int j = 1;
            int k = i + 1;
            while (j < sublen) {
                char source = Character.toLowerCase(s.charAt(k));
                if (substr.charAt(j) != source) {
                    continue mainloop;
                }
                j++;
                k++;
            }
            return i;
        }
        return -1;
    }

public static int indexOfIgnoreCase ( String s , String substr , int startIndex , int endIndex ) { if ( startIndex < 0 ) { startIndex = 0 ; } int srclen = s . length ( ) ; if ( endIndex > srclen ) { endIndex = srclen ; } int sublen = substr . length ( ) ; if ( sublen == 0 ) { return startIndex > srclen ? srclen : startIndex ; } substr = substr . toLowerCase ( ) ; int total = endIndex - sublen + 1 ; char c = substr . charAt ( 0 ) ; mainloop : for ( int i = startIndex ; i < total ; i ++ ) { if ( Character . toLowerCase ( s . charAt ( i ) ) != c ) { continue ; } int j = 1 ; int k = i + 1 ; while ( j < sublen ) { char source = Character . toLowerCase ( s . charAt ( k ) ) ; if ( substr . charAt ( j ) != source ) { continue mainloop ; } j ++ ; k ++ ; } return i ; } return - 1 ; }

Finds first index of a substring in the given source string and range with
ignored case.

@param s                source string for examination
@param substr                substring to find
@param startIndex        starting index from where search begins
@param endIndex                endint index
@return index of founded substring or -1 if substring is not found
@see #indexOfIgnoreCase(String, String, int)

Finds first index of a substring in the given source string and range with ignored case .


public static String removeChars(String s, String chars) {
        int i = s.length();
        StringBuilder sb = new StringBuilder(i);
        for (int j = 0; j < i; j++) {
            char c = s.charAt(j);
            if (chars.indexOf(c) == -1) {
                sb.append(c);
            }
        }
        return sb.toString();
    }

public static String removeChars ( String s , String chars ) { int i = s . length ( ) ; StringBuilder sb = new StringBuilder ( i ) ; for ( int j = 0 ; j < i ; j ++ ) { char c = s . charAt ( j ) ; if ( chars . indexOf ( c ) == - 1 ) { sb . append ( c ) ; } } return sb . toString ( ) ; }

Removes all characters contained in provided string.

@param s    source string
@param chars  string containing characters to remove

Removes all characters contained in provided string .


@SuppressWarnings("PMD.NullAssignment")
    private void cleanState() {

        // null-assignments for de-referencing objects are okay
        domain = null;
        username = null;
        Cleanser.wipe(password);
        pendingSubject = null;
        committedSubject = null;
    }

Clean up any state associated with the current login attempt.

Clean up any state associated with the current login attempt .


@SuppressWarnings("PMD.ConfusingTernary")
    private void initAudit(final CommonProperties commonProps) {
        try {
            final String auditClassName = commonProps.getAuditClassName();

            // this would be harder to read when following PMD's advice - ignoring the PMD warning
            if (!commonProps.isAuditEnabled()) {
                final String error = "Auditing has been disabled in the JAAS configuration";
                LOG.info(error);
            } else if (auditClassName == null) {
                final String error =
                        "Auditing has been enabled in the JAAS configuration, but no audit class has been configured";
                LOG.error(error);
                throw new IllegalStateException(error);
            } else {
                if (commonProps.isAuditSingleton()) {
                    LOG.debug("Requesting singleton audit class instance of '" + auditClassName
                            + "' from the audit factory");
                    this.audit = AuditFactory.getSingleton(auditClassName, commonProps);
                } else {
                    LOG.debug("Requesting non-singleton audit class instance of '" + auditClassName
                            + "' from the audit factory");
                    this.audit = AuditFactory.getInstance(auditClassName, commonProps);
                }
            }
        } catch (FactoryException e) {
            final String error = "The audit class cannot be instantiated. This is most likely a configuration"
                    + " problem. Is the configured class available in the classpath?";
            LOG.error(error, e);
            throw new IllegalStateException(error, e);
        }
    }

Initialize the instance-global audit object

@param commonProps The parsed JAAS configuration, plus additional raw values

Initialize the instance - global audit object


@SuppressWarnings("PMD.ConfusingTernary")
    private void initMessageQueue(final CommonProperties commonProps) {
        try {
            final String messageClassName = commonProps.getMessageQueueClassName();

            // this would be harder to read when following PMD's advice - ignoring the PMD warning
            if (!commonProps.isMessageQueueEnabled()) {
                final String error = "Message queue has been disabled in the JAAS configuration";
                LOG.info(error);
            } else if (messageClassName == null) {
                final String error = "Message queue has been enabled in the JAAS configuration, "
                        + "but no message queue class has been configured";
                LOG.error(error);
                throw new IllegalStateException(error);
            } else {
                if (commonProps.isMessageQueueSingleton()) {
                    LOG.debug("Requesting singleton message class instance of '" + messageClassName
                            + "' from the message factory");
                    this.messageQ = MessageQFactory.getSingleton(messageClassName, commonProps);
                } else {
                    LOG.debug("Requesting non-singleton message class instance of '" + messageClassName
                            + "' from the message factory");
                    this.messageQ = MessageQFactory.getInstance(messageClassName, commonProps);
                }
            }
        } catch (FactoryException e) {
            final String error = "The message class cannot be instantiated. This is most likely a configuration"
                    + " problem. Is the configured class available in the classpath?";
            LOG.error(error, e);
            throw new IllegalStateException(error, e);
        }
    }

Initialize the instance-global message queue object

@param commonProps The parsed JAAS configuration, plus additional raw values

Initialize the instance - global message queue object