public void resourceChanged(final IResourceChangeEvent event) {
		if (event.getType() == IResourceChangeEvent.PRE_CLOSE) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
					for (int i = 0; i < pages.length; i++) {
						if (((FileEditorInput) textEditor.getEditorInput()).getFile().getProject().equals(event.getResource())) {
							IEditorPart editorPart = pages[i].findEditor(textEditor.getEditorInput());
							pages[i].closeEditor(editorPart, true);
						}
					}
				}
			});
		}
	}

public void resourceChanged ( final IResourceChangeEvent event ) { if ( event . getType ( ) == IResourceChangeEvent . PRE_CLOSE ) { Display . getDefault ( ) . asyncExec ( new Runnable ( ) { public void run ( ) { IWorkbenchPage [ ] pages = getSite ( ) . getWorkbenchWindow ( ) . getPages ( ) ; for ( int i = 0 ; i < pages . length ; i ++ ) { if ( ( ( FileEditorInput ) textEditor . getEditorInput ( ) ) . getFile ( ) . getProject ( ) . equals ( event . getResource ( ) ) ) { IEditorPart editorPart = pages [ i ] . findEditor ( textEditor . getEditorInput ( ) ) ; pages [ i ] . closeEditor ( editorPart , true ) ; } } } } ) ; } }

Closes all project files on project close.

Closes all project files on project close .


void showPage() {

		String editorText = getDocumentProvider().getDocument(textEditor.getEditorInput()).get();
		deletePreviewFiles();

		File file = toPreviewFile(editorText);
		if (file != null) {
			PREVIEW_FILES_LIST.add(file);
			String s = "file://" + file.getAbsolutePath(); //$NON-NLS-1$
			browser.setJavascriptEnabled(true);
			browser.setUrl(s);

		} else {
			browser.setText(editorText, true);
		}

	}

void showPage ( ) { String editorText = getDocumentProvider ( ) . getDocument ( textEditor . getEditorInput ( ) ) . get ( ) ; deletePreviewFiles ( ) ; File file = toPreviewFile ( editorText ) ; if ( file != null ) { PREVIEW_FILES_LIST . add ( file ) ; String s = "file://" + file . getAbsolutePath ( ) ; //$NON-NLS-1$ browser . setJavascriptEnabled ( true ) ; browser . setUrl ( s ) ; } else { browser . setText ( editorText , true ) ; } }

Sorts the words in page 0, and shows them in page 2.

Sorts the words in page 0 and shows them in page 2 .


public static String createQueryLogMessage(String query, List<Object> parameterValues) {

    // builder for log message
    StringBuilder builder = new StringBuilder();

    // log the JPQL query string
    builder.append("Query: \"");
    builder.append(query);
    builder.append("\"");

    // append parameter value list
    if(parameterValues != null && parameterValues.size() > 0) {

      builder.append(", parameters: { ");

      // parameter value iterator
      Iterator<Object> parameterIterator = parameterValues.iterator();

      // iterate over all parameter values
      while (parameterIterator.hasNext()) {

        // use private helper to create string representation
        builder.append( objectToString( parameterIterator.next() ) );

        // append comma if more values follow
        if( parameterIterator.hasNext() ) {
          builder.append(", ");
        }

      }

      // closing bracket
      builder.append(" }");

    }

    // return result
    return builder.toString();
  }

Method to create a human readable log message regarding a generated query.

@param query the JPQL query string
@param parameterValues the parameter values of the query
@return log string

Method to create a human readable log message regarding a generated query .


private static String objectToString(Object obj) {

    // handle 'null'
    if(obj == null) {
      return "null";
    }

    // enclose Strings in quotes
    if(obj instanceof CharSequence) {
      return "\""+obj.toString()+"\"";
    }

    // use toString() for all other objects
    return obj.toString();
  }

private
static
String
objectToString
(
Object
obj
)
{
// handle 'null'
if
(
obj
==
)
{
return
"null"
;
}
// enclose Strings in quotes
if
(
obj
instanceof
CharSequence
)
{
return
"\""
+
obj
.
toString
(
)
+
"\""
;
}
// use toString() for all other objects
return
obj
.
toString
(
)
;
}

Helper method to create a string representation of an object.

@param obj the object to print
@return a string representation of the object

Helper method to create a string representation of an object .


public TimelineItem insertTimelineItem(TimelineItem item) throws IOException {
		return getMirror().timeline().insert(item).execute();
	}

public TimelineItem insertTimelineItem ( TimelineItem item ) throws IOException { return getMirror ( ) . timeline ( ) . insert ( item ) . execute ( ) ; }

Inserts a simple timeline item.

@param getCredential
(credential) the user's credential
@param item
the item to insert


public void insertTimelineItem(TimelineItem item, String attachmentContentType, byte[] attachmentData) throws IOException {
		Mirror.Timeline timeline = getMirror().timeline();
		timeline.insert(item, new ByteArrayContent(attachmentContentType, attachmentData)).execute();

	}

public void insertTimelineItem ( TimelineItem item , String attachmentContentType , byte [ ] attachmentData ) throws IOException { Mirror . Timeline timeline = getMirror ( ) . timeline ( ) ; timeline . insert ( item , new ByteArrayContent ( attachmentContentType , attachmentData ) ) . execute ( ) ; }

Inserts an item with an attachment provided as a byte array.

@param item
the item to insert
@param attachmentContentType
the MIME type of the attachment (or null if none)
@param attachmentData
data for the attachment (or null if none)

Inserts an item with an attachment provided as a byte array .


public void insertTimelineItem(TimelineItem item, String attachmentContentType, InputStream attachmentInputStream) throws IOException {
		insertTimelineItem(item, attachmentContentType, ByteStreams.toByteArray(attachmentInputStream));
	}

public void insertTimelineItem ( TimelineItem item , String attachmentContentType , InputStream attachmentInputStream ) throws IOException { insertTimelineItem ( item , attachmentContentType , ByteStreams . toByteArray ( attachmentInputStream ) ) ; }

Inserts an item with an attachment provided as an input stream.

@param item
the item to insert
@param attachmentContentType
the MIME type of the attachment (or null if none)
@param attachmentInputStream
input stream for the attachment (or null if none)

Inserts an item with an attachment provided as an input stream .


private void validate(final CacheResponse response, final String keyword) {
		if (!response.getMessage().toLowerCase(Locale.US).startsWith(keyword)) {
			throw new IllegalArgumentException(response.getMessage());
		}
	}

private void validate ( final CacheResponse response , final String keyword ) { if ( ! response . getMessage ( ) . toLowerCase ( Locale . US ) . startsWith ( keyword ) ) { throw new IllegalArgumentException ( response . getMessage ( ) ) ; } }

Validates that the keyword expected was returned. Otherwise throws an
exception with the message returned included.

@param response
is the response to check
@param keyword
is the keyword to expected

Validates that the keyword expected was returned . Otherwise throws an exception with the message returned included .


public String toQueryString(Criteria criteria, CriteriaQueryBuilder queryBuilder) {
    String absolutePath = queryBuilder.getAbsolutePath(criteria, relativePath);
    return ascending ? absolutePath : absolutePath+" DESC";
  }

public
String
toQueryString
(
Criteria
criteria
,
CriteriaQueryBuilder
queryBuilder
)
{
String
absolutePath
=
queryBuilder
.
getAbsolutePath
(
criteria
,
relativePath
)
;
return
ascending
absolutePath
:
absolutePath
+
" DESC"
;
}

Renders the order to a ORDER BY substring of JPQL query

@param criteria The {@link Criteria} the order is associated with
@param queryBuilder The builder of the JPQL query
@return the generated query string


public TemplateStore getTemplateStore() {
		if (fTemplateStore == null) {
			fTemplateStore = new ContributionTemplateStore(getTemplateContextRegistry(), getPreferenceStore(), "org.eclipse.wst.sse.ui.custom_templates");

			try {
				fTemplateStore.load();
			} catch (IOException e) {
				logError("",e);
			}
		}
		return fTemplateStore;
	}

Returns the template store for the html editor templates.

@return the template store for the html editor templates

Returns the template store for the html editor templates .


public ContextTypeRegistry getTemplateContextRegistry() {
		if (fContextTypeRegistry == null) {
			ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry();
			registry.addContextType(CardContextType.CONTEXT_TYPE);

			fContextTypeRegistry = registry;
		}

		return fContextTypeRegistry;
	}

public ContextTypeRegistry getTemplateContextRegistry ( ) { if ( fContextTypeRegistry == null ) { ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry ( ) ; registry . addContextType ( CardContextType . CONTEXT_TYPE ) ; fContextTypeRegistry = registry ; } return fContextTypeRegistry ; }

Returns the template context type registry for the html plugin.

@return the template context type registry for the html plugin

Returns the template context type registry for the html plugin .


protected IAction getAction(ITextEditor editor, String actionID) {
		return (editor == null ? null : editor.getAction(actionID));
	}

protected IAction getAction ( ITextEditor editor , String actionID ) { return ( editor == null ? null : editor . getAction ( actionID ) ) ; }

Returns the action registed with the given text editor.
@return IAction or null if editor is null.

Returns the action registed with the given text editor .


private DBI createDBI() throws Exception
    {
        if (driver != null) {
            Class.forName(driver).newInstance();
        }
        return new DBI(url, user, password);
    }

private DBI createDBI ( ) throws Exception { if ( driver != null ) { Class . forName ( driver ) . newInstance ( ) ; } return new DBI ( url , user , password ) ; }

Creates the datasource config based on the provided parameters.

Creates the datasource config based on the provided parameters .


protected void appendLimitAndOffSet(final StringBuilder sql, final Page page) {
		sql.append(" LIMIT ").append(page.getPageSize()).append(" OFFSET ").append(page.getOffset());
	}

protected
void
appendLimitAndOffSet
(
final
StringBuilder
sql
,
final
Page
page
)
{
sql
.
append
(
" LIMIT "
)
.
append
(
page
.
getPageSize
(
)
)
.
append
(
" OFFSET "
)
.
append
(
page
.
getOffset
(
)
)
;
}

Appends LIMIT and OFFSET for POSTGRESQL SQL queries

<code>
SELECT select_list
FROM table_expression
[ ORDER BY ... ]
[ LIMIT { number | ALL } ] [ OFFSET number ]
</code>

@param sql
@param page


public static <N> NamedProperty<N> NamedProperty(final N name, final PropertyValue<N> value) {
    return new NamedProperty.Impl<>(name, value);
  }

public static < N > NamedProperty < N > NamedProperty ( final N name , final PropertyValue < N > value ) { return new NamedProperty . Impl <> ( name , value ) ; }

Create a value property from a literal value.

@param name    the property name
@param value   the property value
@param <N>     the property name type
@return  a new NamedProperty with the supplied name and value

Create a value property from a literal value .


public static <N> NamedProperty<N> NamedProperty(final N name, final String value) {
    return NamedProperty(name, Datatree.<N>Literal(value));
  }

public static < N > NamedProperty < N > NamedProperty ( final N name , final String value ) { return NamedProperty ( name , Datatree . < N > Literal ( value ) ) ; }

Create a value property from a string value.

@param name    the property name
@param value   the property value
@param <N>     the property name type
@return  a new NamedProperty with the supplied name and value

Create a value property from a string value .


public static <N> NamedProperty<N> NamedProperty(final N name, final NestedDocument<N> value) {
    return new NamedProperty.Impl<>(name, value);
  }

public static < N > NamedProperty < N > NamedProperty ( final N name , final NestedDocument < N > value ) { return new NamedProperty . Impl <> ( name , value ) ; }

Create a value property from a nested document value.

@param name    the property name
@param value   the property value
@param <N>     the property name type
@return  a new NamedProperty with the supplied name and value

Create a value property from a nested document value .


public static <N> Literal.StringLiteral<N> Literal(final String value) {
    return new Literal.StringLiteral<>(value);
  }

public static < N > Literal . StringLiteral < N > Literal ( final String value ) { return new Literal . StringLiteral <> ( value ) ; }

Create a string literal.

@param value   the property value
@return  a new NamedProperty with the supplied name and value


public static <N> Literal.UriLiteral<N> Literal(final URI value) {
    return new Literal.UriLiteral<>(value);
  }

public static < N > Literal . UriLiteral < N > Literal ( final URI value ) { return new Literal . UriLiteral <> ( value ) ; }

Create a URI literal.

@param value   the property value
@return  a new NamedProperty with the supplied name and value


public static <N> Literal.TypedLiteral<N> Literal(final String value, final QName type) {
    return new Literal.TypedLiteral<>(value, type);
  }

public static < N > Literal . TypedLiteral < N > Literal ( final String value , final QName type ) { return new Literal . TypedLiteral <> ( value , type ) ; }

Create a typed literal.

@param value   the property value
@return  a new NamedProperty with the supplied name and value


public static QName QName(String namespaceURI, String localPart, String prefix) {
    return new QName(namespaceURI, localPart, prefix);
  }

public static QName QName ( String namespaceURI , String localPart , String prefix ) { return new QName ( namespaceURI , localPart , prefix ) ; }

Create a QName from a namespace URI, local part and prefix.

@param namespaceURI  the namespace URI
@param localPart     the local part
@param prefix        the prefix
@return  a QName with the supplied namespace URI, localPart and prefix

Create a QName from a namespace URI local part and prefix .


public void init(final FilterConfig filterConfig)
		throws ServletException {

		// Get the init params
		Properties props = getFilterInitParameters(filterConfig);

		// Extract and parse all required CORS filter properties
		try {
			config = new CORSConfiguration(props);

		} catch (CORSConfigurationException e) {

			throw new ServletException(e);
		}

		handler = new CORSRequestHandler(config);
	}

This method is invoked by the web container to initialise the
filter at startup.

@param filterConfig The filter configuration.

@throws ServletException On a filter initialisation exception.

This method is invoked by the web container to initialise the filter at startup .


public void created(final UUID createdByEntityId) {
		if (this.entityId != null) {
			throw new IllegalStateException("This entity has already been created: entityId = " + entityId);
		}
		this.entityId = UUID.randomUUID();
		this.entityVersion = 1;
		this.createdByEntityId = createdByEntityId;
		this.updatedByEntityId = createdByEntityId;
		this.entityCreatedOn = System.currentTimeMillis();
		this.entityUpdatedOn = this.entityCreatedOn;
	}

Call this method when the entity is updated to increment its version and update its lastupdatedByEntityId

@param lastupdatedByEntityId


protected void init(JsonParser parser) throws IOException {
		LoggerFactory.getLogger(getClass()).warn("init(JsonParser parser) invoked to handle field: {}", parser.getCurrentName());
	}

Sub-classes should override this to parse sub-class specific fields.

This is invoked by init(InputStream), when an unknown field is encountered

@param parser

Sub - classes should override this to parse sub - class specific fields .


public void updated(final UUID lastupdatedByEntityId) {
		if (this.entityId == null) {
			throw new IllegalStateException("The entity has not yet been created : entityId == null");
		}
		Assert.notNull(lastupdatedByEntityId, "lastupdatedByEntityId is required");
		entityVersion++;
		updatedByEntityId = lastupdatedByEntityId;
		entityUpdatedOn = System.currentTimeMillis();
	}

Call this method when the entity is updated before it is persisted to increment its version and update its lastupdatedByEntityId

@param lastupdatedByEntityId
REQUIRED


public void close( int port ) {
    for (Iterator i = _listeners.keySet().iterator(); i.hasNext(); ) {
      Object k = i.next();
      Object s = _listeners.get(k);
      if (s instanceof SocketHandler) {
        SocketHandler sh = (SocketHandler)s;
        if (port == -1 || sh.isPort( port )) {
          sh.interrupt();
          sh.close();
          _transactions.remove( s );
          _listeners.remove( k );
        }
      }
    }
  }

public void close ( int port ) { for ( Iterator i = _listeners . keySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Object k = i . next ( ) ; Object s = _listeners . get ( k ) ; if ( s instanceof SocketHandler ) { SocketHandler sh = ( SocketHandler ) s ; if ( port == - 1 || sh . isPort ( port ) ) { sh . interrupt ( ) ; sh . close ( ) ; _transactions . remove ( s ) ; _listeners . remove ( k ) ; } } } }

Closes a port.  All connections on this port will be closed.

@param port The port to close.  A value of less than -1 closes all ports

Closes a port . All connections on this port will be closed .


public static final void main( String[] args ) {
    if (args.length != 1) {
      System.err.println("A single argument -- a port -- is required");
      System.exit(1);
    }
    int port = Integer.valueOf( args[0] ).intValue();
    System.out.println(Version.VERSION);
    try {
      new Server( port );
    } catch (Exception e) {
      System.err.println("Failed to start server");
      e.printStackTrace( System.err );
    }
  }

Gozirra is probably not the best choice for a stand-alone server.  If
you are tempted to use it as such, you might want to look at ActiveMQ,
which is a feature-rich MOM solution.  Gozirra is intended primarily
to be an ultra-light embedded messaging library.

If you still want to run Gozirra as a stand-alone server, then you'll
need to know about how to call it.  The main() method takes a single
argument: a port to run on.  It will run until you ^C it.

Gozirra is probably not the best choice for a stand - alone server . If you are tempted to use it as such you might want to look at ActiveMQ which is a feature - rich MOM solution . Gozirra is intended primarily to be an ultra - light embedded messaging library .


public void validateOpts(Object instance) {
        final Set<ConstraintViolation<Object>> set = validator.validate(instance);
        final StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<Object> violation : set) {
            final Path path = violation.getPropertyPath();
            final String msg = violation.getMessage();
            sb.append(path.toString()).append(" ").append(msg).append(". ");
        }
        if (sb.length() > 0) {
            // is ConstraintViolationException more appropriate,
            // letting user choose their error message?
            throw new ValidationException(OPT_VIOLATION_MSG + ": " + sb.toString());
        }
    }

This method will only be called if we know that JSR 303 1.0 Bean Validation API
and compliant implementation are available on classpath.

This method will only be called if we know that JSR 303 1 . 0 Bean Validation API and compliant implementation are available on classpath .


public void validateArgs(List<Object> args, Object instance, Method m, Command cmd) {
        final Set<ConstraintViolation<Object>> set = validator.validateParameters(instance, m,
                args.toArray());
        final StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<Object> violation : set) {
            final Path path = violation.getPropertyPath();
            final String msg = violation.getMessage();
            String var = path.toString();
            try {
                int pos = Integer.parseInt("" + var.charAt(var.length() - 1));
                Argument arg = cmd.getArguments().get(pos);
                sb.append(arg.getName()).append(" ").append(msg).append(". ");
            } catch (Exception e) {
                sb.append(var).append(" ").append(msg).append(". ");
            }
        }
        if (sb.length() > 0) {
            // is ConstraintViolationException more appropriate,
            // letting user choose their error message?
            throw new ValidationException(ARG_VIOLATION_MSG + ": " + sb.toString());
        }
    }

This method will only be called if we know that JSR 303 1.1 Bean Validation API
and compliant implementation are available on classpath.

Method validation was first introduced in version 1.1

This method will only be called if we know that JSR 303 1 . 1 Bean Validation API and compliant implementation are available on classpath .


public void subscribe( String name,  Listener listener, Map headers ) {
    synchronized (_listeners) {
      if (listener != null) {
        List list = (List)_listeners.get( name );
        if (list == null) {
          list = new ArrayList();
          _listeners.put( name, list );
        }
        if (!list.contains( listener )) list.add( listener );
      }
    }
    if (headers == null) headers = new HashMap();
    headers.put( "destination", name );
    transmit( Command.SUBSCRIBE, headers );
  }

public void subscribe ( String name , Listener listener , Map headers ) { synchronized ( _listeners ) { if ( listener != null ) { List list = ( List ) _listeners . get ( name ) ; if ( list == null ) { list = new ArrayList ( ) ; _listeners . put ( name , list ) ; } if ( ! list . contains ( listener ) ) list . add ( listener ) ; } } if ( headers == null ) headers = new HashMap ( ) ; headers . put ( "destination" , name ) ; transmit ( Command . SUBSCRIBE , headers ) ; }

Subscribe to a channel.

@param name The name of the channel to listen on
@param headers Additional headers to send to the server.
@param listener A listener to receive messages sent to the channel


public void unsubscribe( String name, Listener l ) {
    synchronized (_listeners) {
      List list = (List)_listeners.get( name );
      if (list != null) {
        list.remove( l );
        if (list.size() == 0) {
          unsubscribe( name );
        }
      }
    }
  }

public void unsubscribe ( String name , Listener l ) { synchronized ( _listeners ) { List list = ( List ) _listeners . get ( name ) ; if ( list != null ) { list . remove ( l ) ; if ( list . size ( ) == 0 ) { unsubscribe ( name ) ; } } } }

Unsubscribe a single listener from a channel.  This does not
send a message to the server unless the listener is the only
listener of this channel.

@param name The name of the channel to unsubscribe from.
@param l The listener to unsubscribe

Unsubscribe a single listener from a channel . This does not send a message to the server unless the listener is the only listener of this channel .


public void unsubscribe( String name, Map header ) {
    if (header == null) header = new HashMap();
    synchronized( _listeners ) { _listeners.remove( name ); }
    header.put( "destination", name );
    transmit( Command.UNSUBSCRIBE, header );
  }

public void unsubscribe ( String name , Map header ) { if ( header == null ) header = new HashMap ( ) ; synchronized ( _listeners ) { _listeners . remove ( name ) ; } header . put ( "destination" , name ) ; transmit ( Command . UNSUBSCRIBE , header ) ; }

Unsubscribe from a channel.  Automatically unregisters all
listeners of the channel.  To re-subscribe with listeners,
subscribe must be passed the listeners again.

@param name The name of the channel to unsubscribe from.
@param header Additional headers to send to the server.

Unsubscribe from a channel . Automatically unregisters all listeners of the channel . To re - subscribe with listeners subscribe must be passed the listeners again .


public void unsubscribeW( String name, Map header ) throws InterruptedException {
    String receipt = addReceipt( header );
    unsubscribe( name, (HashMap)null );
    waitOnReceipt( receipt );
  }

public void unsubscribeW ( String name , Map header ) throws InterruptedException { String receipt = addReceipt ( header ) ; unsubscribe ( name , ( HashMap ) null ) ; waitOnReceipt ( receipt ) ; }

Unsubscribe from a channel.  Automatically unregisters all
listeners of the channel.  To re-subscribe with listeners,
subscribe must be passed the listeners again.  This method
blocks until a receipt is received from the server.

@param name The name of the channel to unsubscribe from.

Unsubscribe from a channel . Automatically unregisters all listeners of the channel . To re - subscribe with listeners subscribe must be passed the listeners again . This method blocks until a receipt is received from the server .


public void send( String dest, String mesg, Map header ) {
    if (header == null) header = new HashMap();
    header.put( "destination", dest );
    transmit( Command.SEND, header, mesg );
  }

public void send ( String dest , String mesg , Map header ) { if ( header == null ) header = new HashMap ( ) ; header . put ( "destination" , dest ) ; transmit ( Command . SEND , header , mesg ) ; }

Send a message to a channel.

@param dest The name of the channel to send the message to
@param mesg The message to send.
@param header Additional headers to send to the server.


public Message getNext( String name ) {
    synchronized( _queue ) {
      for (int idx = 0; idx < _queue.size(); idx++) {
        Message m = (Message)_queue.get(idx);
        if (m.headers().get( "destination" ).equals(name)) {
          _queue.remove(idx);
          return m;
        }
      }
    }
    return null;
  }

public Message getNext ( String name ) { synchronized ( _queue ) { for ( int idx = 0 ; idx < _queue . size ( ) ; idx ++ ) { Message m = ( Message ) _queue . get ( idx ) ; if ( m . headers ( ) . get ( "destination" ) . equals ( name ) ) { _queue . remove ( idx ) ; return m ; } } } return null ; }

Get the next unconsumed message for a particular channel.   This is
non-blocking.

@param name the name of the channel to search for

@return the next message for the channel, or null if the queue
contains no messages for the channel.

Get the next unconsumed message for a particular channel . This is non - blocking .


public boolean hasReceipt( String receipt_id ) {
    synchronized( _receipts ) {
      for (Iterator i=_receipts.iterator(); i.hasNext();) {
        String o = (String)i.next();
        if (o.equals(receipt_id)) return true;
      }
    }
    return false;
  }

public boolean hasReceipt ( String receipt_id ) { synchronized ( _receipts ) { for ( Iterator i = _receipts . iterator ( ) ; i . hasNext ( ) ; ) { String o = ( String ) i . next ( ) ; if ( o . equals ( receipt_id ) ) return true ; } } return false ; }

Checks to see if a receipt has come in.

@param receipt_id the id of the receipts to find

Checks to see if a receipt has come in .


public void clearReceipt( String receipt_id ) {
    synchronized( _receipts ) {
      for (Iterator i=_receipts.iterator(); i.hasNext();) {
        String o = (String)i.next();
        if (o.equals(receipt_id)) i.remove();
      }
    }
  }

public void clearReceipt ( String receipt_id ) { synchronized ( _receipts ) { for ( Iterator i = _receipts . iterator ( ) ; i . hasNext ( ) ; ) { String o = ( String ) i . next ( ) ; if ( o . equals ( receipt_id ) ) i . remove ( ) ; } } }

Deletes all receipts with a given ID

@param receipt_id the id of the receipts to delete


@Subscribe
	public void logDeadEvent(final DeadEvent deadEvent) {
		final Object event = deadEvent.getEvent();
		log.warn("{} : DeadEvent : {} : {}", beanName, event.getClass().getName(), event);
	}

@
Subscribe
public
void
logDeadEvent
(
final
DeadEvent
deadEvent
)
{
final
Object
event
=
deadEvent
.
getEvent
(
)
;
log
.
warn
(
"{} : DeadEvent : {} : {}"
,
beanName
,
event
.
getClass
(
)
.
getName
(
)
,
event
)
;
}

Logs dead event as warnings. Dead events are events that posted, but there are no registered subscribers for that
event type.

@param deadEvent

Logs dead event as warnings . Dead events are events that posted but there are no registered subscribers for that event type .


public <T> T convert(final Object source, final Class<T> targetclass) {
        if (source == null) {
            return null;
        }

        final Class<?> sourceclass = source.getClass();
        final SourceTargetPairKey key = new SourceTargetPairKey(sourceclass, targetclass);
        Converter converter = cache.get(key);

        if (converter != null) {
            return (T) converter.convert(source, targetclass);
        }
        final LinkedList<SourceTargetPairMatch> matches = new LinkedList<SourceTargetPairMatch>();
        for (SourceTargetPair pair : converters.values()) {
            SourceTargetPairMatch match = pair.match(sourceclass, targetclass);
            if (match.matchesSource() && match.matchesTarget()) {
                matches.add(match);
            }
        }
        if (matches.size() == 0) {
            throw new ConversionException("No suitable converter found for target class ["
                    + targetclass.getName() + "] and source value [" + sourceclass.getName()
                    + "]. The following converters are available [" + converters.keySet() + "]");
        }

        Collections.sort(matches, SourceTargetPairMatch.bestTargetMatch());
        converter = matches.get(0).pair.converter;
        cache.put(key, converter);
        return (T) converter.convert(source, targetclass);

    }

Convert a value to a specific class.

The algorithm for finding a suitable converter is as follows:

Find converters that is able to convert both source and target; a exact or
superclass match. Pick the converter that have the best target match, if both
are equal, pick the one with best source match.

That is, the converter that is most specialized in converting a value to
a specific target class will be prioritized, as long as it recognizes the source
value.

@param source value to convert.
@param targetclass class to convert to.
@return converted value


protected Priority getPriority(final int lines) {
        if (lines >= highThreshold) {
            return Priority.HIGH;
        }
        else if (lines >= normalThreshold) {
            return Priority.NORMAL;
        }
        else {
            return Priority.LOW;
        }
    }

protected Priority getPriority ( final int lines ) { if ( lines >= highThreshold ) { return Priority . HIGH ; } else if ( lines >= normalThreshold ) { return Priority . NORMAL ; } else { return Priority . LOW ; } }

Returns the priority of the warning.

@param lines
number of duplicate lines
@return the priority of the warning


public void execute(GNUishParser p) {
    if (instance == null) {
      instance = Utils.newInstance(className);
    }
    final Class<?> clazz = instance.getClass();
    final Method[] methods = clazz.getDeclaredMethods();
    for (Method m : methods) {
      m.setAccessible(true);
      if (!m.getName().equals(p.getCommand())) {
        continue;
      }
      final List<Object> args = adjustArgs(p.getArgs(), m);
      injectOpts(p, clazz);
      try {
        validateArgs(args, instance, m, this);
        m.invoke(instance, args.toArray());
        return;
      } catch (InvocationTargetException e) {
        final Throwable ex = e.getTargetException();
        if (ex instanceof RuntimeException) {
          throw (RuntimeException) e.getCause();
        } else {
          throw new RuntimeException(e.getTargetException());
        }
      } catch (RuntimeException e) {
        throw e;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    System.out.println(p.getCommand() + ": command not found");

  }

public
void
execute
(
GNUishParser
p
)
{
if
(
instance
==
)
{
instance
=
Utils
.
newInstance
(
className
)
;
}
final
Class
<
>
clazz
=
instance
.
getClass
(
)
;
final
Method
[
]
methods
=
clazz
.
getDeclaredMethods
(
)
;
for
(
Method
m
:
methods
)
{
m
.
setAccessible
(
true
)
;
if
(
!
m
.
getName
(
)
.
equals
(
p
.
getCommand
(
)
)
)
{
continue
;
}
final
List
<
Object
>
args
=
adjustArgs
(
p
.
getArgs
(
)
,
m
)
;
injectOpts
(
p
,
clazz
)
;
try
{
validateArgs
(
args
,
instance
,
m
,
this
)
;
m
.
invoke
(
instance
,
args
.
toArray
(
)
)
;
return
;
}
catch
(
InvocationTargetException
e
)
{
final
Throwable
ex
=
e
.
getTargetException
(
)
;
if
(
ex
instanceof
RuntimeException
)
{
throw
(
RuntimeException
)
e
.
getCause
(
)
;
}
else
{
throw
new
RuntimeException
(
e
.
getTargetException
(
)
)
;
}
}
catch
(
RuntimeException
e
)
{
throw
e
;
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
)
;
}
}
System
.
out
.
println
(
p
.
getCommand
(
)
+
": command not found"
)
;
}

Execute this command according to the user input arguments
parsed by the parser.

Execute this command according to the user input arguments parsed by the parser .


private void injectOpts(GNUishParser p, Class<?> clazz) {
    for (Field f : clazz.getDeclaredFields()) {
      f.setAccessible(true);
      final CliOption anno = f.getAnnotation(CliOption.class);
      if (anno == null) {
        continue;
      }
      String value = p.getShortOpt(anno.shortName());
      if (value == null) {
        value = p.getLongOpt(f.getName());
        if (value == null) {
          continue;
        }
      }
      try {
        f.set(instance, c.convert(value, f.getType()));
      } catch (ConversionException e) {
        throw CliException.WRONG_OPT_TYPE(f.getName(), f.getType().getName(), value);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    validateOpts(instance);
  }

private void injectOpts ( GNUishParser p , Class < ? > clazz ) { for ( Field f : clazz . getDeclaredFields ( ) ) { f . setAccessible ( true ) ; final CliOption anno = f . getAnnotation ( CliOption . class ) ; if ( anno == null ) { continue ; } String value = p . getShortOpt ( anno . shortName ( ) ) ; if ( value == null ) { value = p . getLongOpt ( f . getName ( ) ) ; if ( value == null ) { continue ; } } try { f . set ( instance , c . convert ( value , f . getType ( ) ) ) ; } catch ( ConversionException e ) { throw CliException . WRONG_OPT_TYPE ( f . getName ( ) , f . getType ( ) . getName ( ) , value ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } validateOpts ( instance ) ; }

Convert options to appropriate type and inject them into
the command instance.

Convert options to appropriate type and inject them into the command instance .


private List<Object> adjustArgs(List<String> args, Method m) {
    final List<Object> result = new ArrayList<Object>();
    final Class<?>[] types = m.getParameterTypes();
    if (m.isVarArgs()) {
      types[types.length - 1] = types[types.length - 1].getComponentType();
      if (!String.class.isAssignableFrom(types[types.length - 1])) {
        throw new CliException("Only String varargs is supported.");
      }
      types[types.length - 1] = String.class;
    }

    List<Object> varargs = new ArrayList<>();
    for (int i = 0; i < args.size(); i++) {
      try {
        if (m.isVarArgs() && i >= types.length - 1) {
          varargs.add(c.convert(args.get(i), types[types.length - 1]));
        } else {
          result.add(c.convert(args.get(i), types[i]));
        }
      } catch (ConversionException e) {
        throw CliException.WRONG_ARG_TYPE(getArguments().get(i).getName(),
                types[i].getName(), args.get(i));
      }
    }
    if (m.isVarArgs()) {
      result.add(varargs.toArray(new String[0]));
    }
    return result;
  }

private
List
<
Object
>
adjustArgs
(
List
<
String
>
args
,
Method
m
)
{
final
List
<
Object
>
result
=
new
ArrayList
<
Object
>
(
)
;
final
Class
<
>
[
]
types
=
m
.
getParameterTypes
(
)
;
if
(
m
.
isVarArgs
(
)
)
{
types
[
types
.
length
1
]
=
types
[
types
.
length
1
]
.
getComponentType
(
)
;
if
(
!
String
.
class
.
isAssignableFrom
(
types
[
types
.
length
1
]
)
)
{
throw
new
CliException
(
"Only String varargs is supported."
)
;
}
types
[
types
.
length
1
]
=
String
.
class
;
}
List
<
Object
>
varargs
=
new
ArrayList
<>
(
)
;
for
(
int
i
=
0
;
i
<
args
.
size
(
)
;
i
++
)
{
try
{
if
(
m
.
isVarArgs
(
)
&&
i
>=
types
.
length
1
)
{
varargs
.
add
(
c
.
convert
(
args
.
get
(
i
)
,
types
[
types
.
length
1
]
)
)
;
}
else
{
result
.
add
(
c
.
convert
(
args
.
get
(
i
)
,
types
[
i
]
)
)
;
}
}
catch
(
ConversionException
e
)
{
throw
CliException
.
WRONG_ARG_TYPE
(
getArguments
(
)
.
get
(
i
)
.
getName
(
)
,
types
[
i
]
.
getName
(
)
,
args
.
get
(
i
)
)
;
}
}
if
(
m
.
isVarArgs
(
)
)
{
result
.
add
(
varargs
.
toArray
(
new
String
[
0
]
)
)
;
}
return
result
;
}

Add or remove parameters to fit the method declaration and also convert them
to appropriate data type.

Add or remove parameters to fit the method declaration and also convert them to appropriate data type .


private List<MigrationResult> migratePersonality(final MetadataManager metadataManager, final String personalityName, final Integer targetVersion, final MigratoryOption [] options)
    {
        final Integer currentVersion = metadataManager.getCurrentVersion(personalityName);

        if (currentVersion == null  && !migratoryConfig.isCreatePersonalities()) {
            throw new MigratoryException(Reason.NEW_PERSONALITIES_DENIED);
        }

        // Make sure that the current state of the personality is sane.
        final List<MetadataInfo> history = metadataManager.getPersonalityHistory(personalityName);

        final MigrationManager migrationManager = new MigrationManager(migratoryContext, personalityName);

        // if null, this is a new personality.Don't validate it.
        if (history != null && !history.isEmpty()) {
            // "No verify" option skips this step.
            if (!MigratoryOption.containsOption(MigratoryOption.NO_VERIFY, options)) {
                final DbValidator dbValidator = new DbValidator(migrationManager);
                final ValidationResult validationResult = dbValidator.validate(history);

                if (validationResult.getValidationStatus() != ValidationStatus.OK) {
                    throw new MigratoryException(Reason.VALIDATION_FAILED, "Validation for Personality '%s' failed", personalityName);
                }
            }
            else {
                LOG.info("Skipped verification.");
            }
        }

        final MigrationPlanner migrationPlanner = new MigrationPlanner(migrationManager, currentVersion, targetVersion);

        migrationPlanner.plan();

        LOG.info("{}", migrationPlanner.toString());
        switch(migrationPlanner.getDirection()) {
        case FORWARD:
            if (!migratoryConfig.isAllowRollForward()) {
                throw new MigratoryException(Reason.ROLL_FORWARD_DENIED);
            }
            break;

        case BACK:
            if (!migratoryConfig.isAllowRollBack()) {
                throw new MigratoryException(Reason.ROLL_BACK_DENIED);
            }
            break;

        case DO_NOTHING:
            return null;

        default:
            LOG.warn("Encountered State {}. This should never happen!", migrationPlanner.getDirection());
            return null;
        }

        final DbMigrator migrator = new DbMigrator(migratoryContext, migrationPlanner);
        final List<MigrationResult> results = migrator.migrate(options);
        LOG.info("Migration finished in '{}' steps, result is {}",  results.size(), MigrationResult.determineMigrationState(results));
        return results;
    }

Performs the migration of a personality. This must be run under the table lock so that only one thread can use it at a time.

Performs the migration of a personality . This must be run under the table lock so that only one thread can use it at a time .


public void tagRequest(final HttpServletRequest request) {

		final CORSRequestType type = CORSRequestType.detect(request);

		switch (type) {

			case ACTUAL:
				request.setAttribute("cors.isCorsRequest", true);
				request.setAttribute("cors.origin", request.getHeader("Origin"));
				request.setAttribute("cors.requestType", "actual");
				break;

			case PREFLIGHT:
				request.setAttribute("cors.isCorsRequest", true);
				request.setAttribute("cors.origin", request.getHeader("Origin"));
				request.setAttribute("cors.requestType", "preflight");
				request.setAttribute("cors.requestHeaders", request.getHeader("Access-Control-Request-Headers"));
				break;

			case OTHER:
				request.setAttribute("cors.isCorsRequest", false);
		}
	}

public void tagRequest ( final HttpServletRequest request ) { final CORSRequestType type = CORSRequestType . detect ( request ) ; switch ( type ) { case ACTUAL : request . setAttribute ( "cors.isCorsRequest" , true ) ; request . setAttribute ( "cors.origin" , request . getHeader ( "Origin" ) ) ; request . setAttribute ( "cors.requestType" , "actual" ) ; break ; case PREFLIGHT : request . setAttribute ( "cors.isCorsRequest" , true ) ; request . setAttribute ( "cors.origin" , request . getHeader ( "Origin" ) ) ; request . setAttribute ( "cors.requestType" , "preflight" ) ; request . setAttribute ( "cors.requestHeaders" , request . getHeader ( "Access-Control-Request-Headers" ) ) ; break ; case OTHER : request . setAttribute ( "cors.isCorsRequest" , false ) ; } }

Tags an HTTP servlet request to provide CORS information to
downstream handlers.

Tagging is provided via {@code HttpServletRequest.setAttribute()}.

{@code cors.isCorsRequest} set to {@code true} or {@code false}.

{@code cors.origin} set to the value of the "Origin" header,
{@code null} if undefined.

{@code cors.requestType} set to "actual" or "preflight" (for
CORS requests).

{@code cors.requestHeaders} set to the value of the
"Access-Control-Request-Headers" or {@code null} if
undefined (added for preflight CORS requests only).

@param request The servlet request to inspect and tag. Must not be
{@code null}.

Tags an HTTP servlet request to provide CORS information to downstream handlers .


public void handleActualRequest(final HttpServletRequest request, final HttpServletResponse response)
		throws InvalidCORSRequestException,
		       CORSOriginDeniedException,
		       UnsupportedHTTPMethodException {

		if (CORSRequestType.detect(request) != CORSRequestType.ACTUAL)
			throw new InvalidCORSRequestException("Invalid simple/actual CORS request");

		// Check origin against allow list
		Origin requestOrigin = new Origin(request.getHeader("Origin"));

		if (! config.isAllowedOrigin(requestOrigin))
			throw new CORSOriginDeniedException("CORS origin denied", requestOrigin);

		// Check method

		HTTPMethod method = null;

		try {
			method = HTTPMethod.valueOf(request.getMethod());

		} catch (Exception e) {
			// Parse exception
			throw new UnsupportedHTTPMethodException("Unsupported HTTP method: " + request.getMethod());
		}

		if (! config.isSupportedMethod(method))
			throw new UnsupportedHTTPMethodException("Unsupported HTTP method", method);

		// Success, append response headers

		response.addHeader("Access-Control-Allow-Origin", requestOrigin.toString());

		if (config.supportsCredentials)
			response.addHeader("Access-Control-Allow-Credentials", "true");

		if (! exposedHeaders.isEmpty())
			response.addHeader("Access-Control-Expose-Headers", exposedHeaders);

		// Tag request
		request.setAttribute("cors.origin", requestOrigin.toString());
		request.setAttribute("cors.requestType", "actual");
	}

public
void
handleActualRequest
(
final
HttpServletRequest
request
,
final
HttpServletResponse
response
)
throws
InvalidCORSRequestException
,
CORSOriginDeniedException
,
UnsupportedHTTPMethodException
{
if
(
CORSRequestType
.
detect
(
request
)
!=
CORSRequestType
.
ACTUAL
)
throw
new
InvalidCORSRequestException
(
"Invalid simple/actual CORS request"
)
;
// Check origin against allow list
Origin
requestOrigin
=
new
Origin
(
request
.
getHeader
(
"Origin"
)
)
;
if
(
!
config
.
isAllowedOrigin
(
requestOrigin
)
)
throw
new
CORSOriginDeniedException
(
"CORS origin denied"
,
requestOrigin
)
;
// Check method
HTTPMethod
method
=
;
try
{
method
=
HTTPMethod
.
valueOf
(
request
.
getMethod
(
)
)
;
}
catch
(
Exception
e
)
{
// Parse exception
throw
new
UnsupportedHTTPMethodException
(
"Unsupported HTTP method: "
+
request
.
getMethod
(
)
)
;
}
if
(
!
config
.
isSupportedMethod
(
method
)
)
throw
new
UnsupportedHTTPMethodException
(
"Unsupported HTTP method"
,
method
)
;
// Success, append response headers
response
.
addHeader
(
"Access-Control-Allow-Origin"
,
requestOrigin
.
toString
(
)
)
;
if
(
config
.
supportsCredentials
)
response
.
addHeader
(
"Access-Control-Allow-Credentials"
,
"true"
)
;
if
(
!
exposedHeaders
.
isEmpty
(
)
)
response
.
addHeader
(
"Access-Control-Expose-Headers"
,
exposedHeaders
)
;
// Tag request
request
.
setAttribute
(
"cors.origin"
,
requestOrigin
.
toString
(
)
)
;
request
.
setAttribute
(
"cors.requestType"
,
"actual"
)
;
}

Handles a simple or actual CORS request.

CORS specification: Simple Cross-Origin Request, Actual Request, and Redirects

@param request  The HTTP request.
@param response The HTTP response.

@throws InvalidCORSRequestException    If not a valid CORS simple/
actual request.
@throws CORSOriginDeniedException      If the origin is not allowed.
@throws UnsupportedHTTPMethodException If the requested HTTP method
is not supported by the CORS
policy.

Handles a simple or actual CORS request .


public void handlePreflightRequest(final HttpServletRequest request, final HttpServletResponse response)
		throws InvalidCORSRequestException,
		       CORSOriginDeniedException,
		       UnsupportedHTTPMethodException,
		       UnsupportedHTTPHeaderException {

		if (CORSRequestType.detect(request) != CORSRequestType.PREFLIGHT)
			throw new InvalidCORSRequestException("Invalid preflight CORS request");

		// Check origin against allow list
		Origin requestOrigin = new Origin(request.getHeader("Origin"));

		if (! config.isAllowedOrigin(requestOrigin))
			throw new CORSOriginDeniedException("CORS origin denied", requestOrigin);

		// Parse requested method
		// Note: method checking must be done after header parsing, see CORS spec

		String requestMethodHeader = request.getHeader("Access-Control-Request-Method");

		if (requestMethodHeader == null)
			throw new InvalidCORSRequestException("Invalid preflight CORS request: Missing Access-Control-Request-Method header");

		HTTPMethod requestedMethod = null;

		try {
			requestedMethod = HTTPMethod.valueOf(requestMethodHeader.toUpperCase());

		} catch (Exception e) {
			// Parse exception
			throw new UnsupportedHTTPMethodException("Unsupported HTTP method: " + requestMethodHeader);
		}

		// Parse custom headers

		final String[] requestHeaderValues = parseMultipleHeaderValues(request.getHeader("Access-Control-Request-Headers"));

		final HeaderFieldName[] requestHeaders = new HeaderFieldName[requestHeaderValues.length];

		for (int i=0; i<requestHeaders.length; i++) {

			try {
				requestHeaders[i] = new HeaderFieldName(requestHeaderValues[i]);

			} catch (IllegalArgumentException e) {
				// Invalid header name
				throw new InvalidCORSRequestException("Invalid preflight CORS request: Bad request header value");
			}
		}

		// Now, do method check
		if (! config.isSupportedMethod(requestedMethod))
			throw new UnsupportedHTTPMethodException("Unsupported HTTP method", requestedMethod);

		// Author request headers check

		for (int i=0; i<requestHeaders.length; i++) {

			if (! config.supportedHeaders.contains(requestHeaders[i]))
				throw new UnsupportedHTTPHeaderException("Unsupported HTTP request header", requestHeaders[i]);

		}

		// Success, append response headers

		if (config.supportsCredentials) {
			response.addHeader("Access-Control-Allow-Origin", requestOrigin.toString());
			response.addHeader("Access-Control-Allow-Credentials", "true");
		}
		else {
			if (config.allowAnyOrigin)
				response.addHeader("Access-Control-Allow-Origin", "*");
			else
				response.addHeader("Access-Control-Allow-Origin", requestOrigin.toString());
		}

		if (config.maxAge > 0)
			response.addHeader("Access-Control-Max-Age", Integer.toString(config.maxAge));

		response.addHeader("Access-Control-Allow-Methods", supportedMethods);

		if (! supportedHeaders.isEmpty())
			response.addHeader("Access-Control-Allow-Headers", supportedHeaders);
	}

Handles a preflight CORS request.

CORS specification: Preflight Request

@param request  The HTTP request.
@param response The HTTP response.

@throws InvalidCORSRequestException    If not a valid CORS preflight
request.
@throws CORSOriginDeniedException      If the origin is not allowed.
@throws UnsupportedHTTPMethodException If the requested HTTP method
is not supported by the CORS
policy.
@throws UnsupportedHTTPHeaderException If the requested HTTP header
is not supported by the CORS
policy.


public boolean setOptions(String[] options) throws Exception {
    ArgumentParser parser;
    Namespace ns;

    parser = ArgumentParsers.newArgumentParser(MinDeps.class.getName());
    parser.addArgument("--java-home")
      .type(Arguments.fileType().verifyExists().verifyIsDirectory())
      .dest("javahome")
      .required(true)
      .help("The java home directory of the JDK that includes the jdeps binary, default is taken from JAVA_HOME environment variable.");
    parser.addArgument("--class-path")
      .dest("classpath")
      .required(true)
      .help("The CLASSPATH to use for jdeps.");
    parser.addArgument("--classes")
      .type(Arguments.fileType().verifyExists().verifyIsFile().verifyCanRead())
      .dest("classes")
      .required(true)
      .help("The file containing the classes to determine the dependencies for. Empty lines and lines starting with # get ignored.");
    parser.addArgument("--additional")
      .type(Arguments.fileType())
      .setDefault(new File("."))
      .required(false)
      .dest("additional")
      .help("The file with additional class names to just include.");
    parser.addArgument("--output")
      .type(Arguments.fileType())
      .setDefault(new File("."))
      .required(false)
      .dest("output")
      .help("The file for storing the determined class names in.");
    parser.addArgument("package")
      .dest("packages")
      .required(true)
      .nargs("+")
      .help("The packages to keep, eg 'weka'.");

    try {
      ns = parser.parseArgs(options);
    }
    catch (ArgumentParserException e) {
      parser.handleError(e);
      return false;
    }

    setJavaHome(ns.get("javahome"));
    setClassPath(ns.getString("classpath"));
    setClassesFile(ns.get("classes"));
    setAdditionalFile(ns.get("additional"));
    setPackages(ns.getList("packages"));
    setOutputFile(ns.get("output"));

    return true;
  }

Sets the commandline options.

@param options	the options to use
@return		true if successful
@throws Exception	in case of an invalid option


protected String check() {
    String		error;

    if (!m_JavaHome.exists())
      return "Java home directory does not exist: " + m_JavaHome;
    if (!m_JavaHome.isDirectory())
      return "Java home does not point to a directory: " + m_JavaHome;
    if (System.getProperty("os.name").toLowerCase().contains("windows"))
      m_Jdeps = new File(m_JavaHome.getAbsolutePath() + File.separator + "bin" + File.separator + "jdeps.exe");
    else
      m_Jdeps = new File(m_JavaHome.getAbsolutePath() + File.separator + "bin" + File.separator + "jdeps");
    if (!m_Jdeps.exists())
      return "jdeps binary does not exist: " + m_Jdeps;

    if (!m_ClassesFile.exists())
      return "File with class names does not exist: " + m_ClassesFile;
    if (m_ClassesFile.isDirectory())
      return "File with class names points to directory: " + m_ClassesFile;

    // read classes
    error = readFile(m_ClassesFile, m_Classes);
    if (error != null)
      return error;

    // read resources
    if ((m_AdditionalFile != null) && m_AdditionalFile.exists() && (!m_AdditionalFile.isDirectory())) {
      error = readFile(m_AdditionalFile, m_Resources);
      if (error != null)
	return error;
    }

    return null;
  }

Performs some checks.

@return		null if successful, otherwise error message


protected List<String> filter(List<String> lines, String regexp, boolean invert) {
    List<String>	result;
    Pattern 		pattern;

    result  = new ArrayList<>();
    pattern = Pattern.compile(regexp);

    for (String line: lines) {
      if (invert) {
	if (!pattern.matcher(line).matches())
	  result.add(line);
      }
      else {
	if (pattern.matcher(line).matches())
	  result.add(line);
      }
    }

    return result;
  }

protected List < String > filter ( List < String > lines , String regexp , boolean invert ) { List < String > result ; Pattern pattern ; result = new ArrayList <> ( ) ; pattern = Pattern . compile ( regexp ) ; for ( String line : lines ) { if ( invert ) { if ( ! pattern . matcher ( line ) . matches ( ) ) result . add ( line ) ; } else { if ( pattern . matcher ( line ) . matches ( ) ) result . add ( line ) ; } } return result ; }

Filters the list of strings with a regular expression.

@param lines	the list to filter
@param regexp	the regular expression to use
@param invert	whether to invert the matching sense
@return		the filtered list

Filters the list of strings with a regular expression .


protected String packagesRegExp() {
    StringBuilder	result;
    int			i;
    String		pkg;

    result = new StringBuilder();
    result.append(".* (");
    for (i = 0; i < m_Packages.size(); i++) {
      if (i > 0)
        result.append("|");
      pkg = m_Packages.get(i);
      if (!pkg.endsWith("."))
        pkg = pkg + ".";
      pkg = pkg.replace(".", "\\.");
      result.append(pkg);
    }
    result.append(").*$");

    return result.toString();
  }

protected
String
packagesRegExp
(
)
{
StringBuilder
result
;
int
i
;
String
pkg
;
result
=
new
StringBuilder
(
)
;
result
.
append
(
".* ("
)
;
for
(
i
=
0
;
i
<
m_Packages
.
size
(
)
;
i
++
)
{
if
(
i
>
0
)
result
.
append
(
"|"
)
;
pkg
=
m_Packages
.
get
(
i
)
;
if
(
!
pkg
.
endsWith
(
"."
)
)
pkg
=
pkg
+
"."
;
pkg
=
pkg
.
replace
(
"."
,
"\\."
)
;
result
.
append
(
pkg
)
;
}
result
.
append
(
").*$"
)
;
return
result
.
toString
(
)
;
}

Builds the regular expression for the packages to keep.

@return		the regexp

Builds the regular expression for the packages to keep .


public void output() {
    if ((m_OutputFile == null || m_OutputFile.isDirectory())) {
      for (String dep : m_Dependencies)
	System.out.println(dep);
    }
    else {
      try {
	Files.write(m_OutputFile.toPath(), m_Dependencies, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
      }
      catch (Exception e) {
        System.err.println("Failed to write dependencies to: " + m_OutputFile);
        e.printStackTrace();
      }
    }
  }

public
void
output
(
)
{
if
(
(
m_OutputFile
==
||
m_OutputFile
.
isDirectory
(
)
)
)
{
for
(
String
dep
:
m_Dependencies
)
System
.
out
.
println
(
dep
)
;
}
else
{
try
{
Files
.
write
(
m_OutputFile
.
toPath
(
)
,
m_Dependencies
,
StandardOpenOption
.
CREATE
,
StandardOpenOption
.
TRUNCATE_EXISTING
)
;
}
catch
(
Exception
e
)
{
System
.
err
.
println
(
"Failed to write dependencies to: "
+
m_OutputFile
)
;
e
.
printStackTrace
(
)
;
}
}
}


@Override
  public int compareTo(InstanceProvider instanceProvider) {
    if (this.getPriority().equals(instanceProvider.getPriority())) {
      return this.getName().compareTo(instanceProvider.getName());
    } else {
      return this.getPriority().compareTo(instanceProvider.getPriority());
    }
  }

@ Override public int compareTo ( InstanceProvider instanceProvider ) { if ( this . getPriority ( ) . equals ( instanceProvider . getPriority ( ) ) ) { return this . getName ( ) . compareTo ( instanceProvider . getName ( ) ) ; } else { return this . getPriority ( ) . compareTo ( instanceProvider . getPriority ( ) ) ; } }

Default implementation of compareTo for the InstanceManager.

Default implementation of compareTo for the InstanceManager .


public static IOUtils getIOUtils() {
    if (ioUtils == null) {
      try {
        Class clazz = Class.forName(IO_UTILS);
        ioUtils = (IOUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return ioUtils;
  }

public
static
IOUtils
getIOUtils
(
)
{
if
(
ioUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
IO_UTILS
)
;
ioUtils
=
(
IOUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
ioUtils
;
}

Retrieve IOUtils implementation
@return IOUtils instance


public static ImageUtils getImageUtils() {
    if (imageUtils == null) {
      try {
        Class clazz = Class.forName(IMAGE_UTILS);
        imageUtils = (ImageUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return imageUtils;
  }

public
static
ImageUtils
getImageUtils
(
)
{
if
(
imageUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
IMAGE_UTILS
)
;
imageUtils
=
(
ImageUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
imageUtils
;
}

Retrieve ImageUtils implementation
@return ImageUtils instance


public static PriceUtils getPriceUtils() {
    if (priceUtils == null) {
      try {
        Class clazz = Class.forName(PRICE_UTILS);
        priceUtils = (PriceUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return priceUtils;
  }

public
static
PriceUtils
getPriceUtils
(
)
{
if
(
priceUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
PRICE_UTILS
)
;
priceUtils
=
(
PriceUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
priceUtils
;
}

Retrieve PriceUtils implementation
@return PriceUtils instance


public static ResourceUtils getResourceUtils() {
    if (resourceUtils == null) {
      try {
        Class clazz = Class.forName(RESOURCE_UTILS);
        resourceUtils = (ResourceUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return resourceUtils;
  }

public
static
ResourceUtils
getResourceUtils
(
)
{
if
(
resourceUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
RESOURCE_UTILS
)
;
resourceUtils
=
(
ResourceUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
resourceUtils
;
}

Retrieve ResourceUtils implementation
@return ResourceUtils instance


public static ZipUtils getZipUtils() {
    if (zipUtils == null) {
      try {
        Class clazz = Class.forName(ZIP_UTILS);
        zipUtils = (ZipUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}",e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return zipUtils;
  }

public
static
ZipUtils
getZipUtils
(
)
{
if
(
zipUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
ZIP_UTILS
)
;
zipUtils
=
(
ZipUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
zipUtils
;
}

Retrieve ZipUtils implementation
@return ZipUtils instance


public static DigestUtils getDigestUtils() {
    if (digestUtils == null) {
      try {
        Class clazz = Class.forName(DIGEST_UTILS);
        digestUtils = (DigestUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return digestUtils;
  }

public
static
DigestUtils
getDigestUtils
(
)
{
if
(
digestUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
DIGEST_UTILS
)
;
digestUtils
=
(
DigestUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
digestUtils
;
}

Retrieve DigestUtils implementation
@return DigestUtils instance


public static StringUtils getStringUtils() {
    if (stringUtils == null) {
      try {
        Class clazz = Class.forName(STRING_UTILS);
        stringUtils = (StringUtils) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return stringUtils;
  }

public
static
StringUtils
getStringUtils
(
)
{
if
(
stringUtils
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
STRING_UTILS
)
;
stringUtils
=
(
StringUtils
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
stringUtils
;
}

Retrieve StringUtils implementation
@return StringUtils instance


public static ResourceService getResourceService() {
    if (resourceService == null) {
      try {
        Class clazz = Class.forName(RESOURCE_SERVICE);
        resourceService = (ResourceService) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return resourceService;
  }

public
static
ResourceService
getResourceService
(
)
{
if
(
resourceService
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
RESOURCE_SERVICE
)
;
resourceService
=
(
ResourceService
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
resourceService
;
}

Retrieve ResourceService implementation
@return ResourceService instance


public static PricingService getPricingService() {
    if (pricingService == null) {
      try {
        Class clazz = Class.forName(PRICING_SERVICE);
        pricingService = (PricingService) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return pricingService;
  }

public
static
PricingService
getPricingService
(
)
{
if
(
pricingService
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
PRICING_SERVICE
)
;
pricingService
=
(
PricingService
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
pricingService
;
}

Retrieve PricingService implementation
@return PricingService instance


public static InstanceService getInstanceService() {
    if (instanceService == null) {
      try {
        Class clazz = Class.forName(INSTANCE_SERVICE);
        instanceService = (InstanceService) clazz.newInstance();
      } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        LOGGER.warn("Cannot instanciate util: {}", e.getMessage());
        throw new IllegalStateException(e);
      }
    }
    return instanceService;
  }

public
static
InstanceService
getInstanceService
(
)
{
if
(
instanceService
==
)
{
try
{
Class
clazz
=
Class
.
forName
(
INSTANCE_SERVICE
)
;
instanceService
=
(
InstanceService
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
LOGGER
.
warn
(
"Cannot instanciate util: {}"
,
e
.
getMessage
(
)
)
;
throw
new
IllegalStateException
(
e
)
;
}
}
return
instanceService
;
}

Retrieve InstanceService implementation
@return InstanceService instance


@Override
    public Set<String> getObjectId(File uploadedFile) throws HarvesterException {
        Set<String> objectIds = new HashSet<String>();
        try {
            objectIds.add(createDigitalObject(uploadedFile));
        } catch (StorageException se) {
            throw new HarvesterException(se);
        }
        return objectIds;
    }

@ Override public Set < String > getObjectId ( File uploadedFile ) throws HarvesterException { Set < String > objectIds = new HashSet < String > ( ) ; try { objectIds . add ( createDigitalObject ( uploadedFile ) ) ; } catch ( StorageException se ) { throw new HarvesterException ( se ) ; } return objectIds ; }

Get an individual uploaded file as a digital object. For consistency this
should be in a list.

@return a list of one object ID
@throws HarvesterException if there was an error retrieving the objects

Get an individual uploaded file as a digital object . For consistency this should be in a list .


private String createDigitalObject(File file) throws HarvesterException,
            StorageException {
        String objectId;
        DigitalObject object;
        if (forceUpdate) {
            object = StorageUtils.storeFile(getStorage(), file,
                    !forceLocalStorage);
        } else {
            String oid = StorageUtils.generateOid(file);
            String pid = StorageUtils.generatePid(file);
            object = getStorage().createObject(oid);
            if (forceLocalStorage) {
                try {
                    object.createStoredPayload(pid, new FileInputStream(file));
                } catch (FileNotFoundException ex) {
                    throw new HarvesterException(ex);
                }
            } else {
                object.createLinkedPayload(pid, file.getAbsolutePath());
            }

        }
        // update object metadata
        Properties props = object.getMetadata();
        props.setProperty("render-pending", "true");
        props.setProperty("file.path",
                FilenameUtils.separatorsToUnix(file.getAbsolutePath()));
        objectId = object.getId();

        // Store rendition information if we have it
        String ext = FilenameUtils.getExtension(file.getName());
        for (String chain : renderChains.keySet()) {
            Map<String, List<String>> details = renderChains.get(chain);
            if (details.get("fileTypes").contains(ext)) {
                storeList(props, details, "harvestQueue");
                storeList(props, details, "indexOnHarvest");
                storeList(props, details, "renderQueue");
            }
        }

        object.close();
        return objectId;
    }

Store the provided file in storage. Ensure proper queue routing is set
in object properties.

@param file : The file to store
@return String : The OID of the stored object
@throws HarvesterException : if there was an error accessing storage
@throws StorageException : if there was an error writing to storage

Store the provided file in storage . Ensure proper queue routing is set in object properties .


private void storeList(Properties props, Map<String, List<String>> details,
            String field) {
        Set<String> valueSet = new LinkedHashSet<String>();
        // merge with original property value if exists
        String currentValue = props.getProperty(field, "");
        if (!"".equals(currentValue)) {
            String[] currentList = currentValue.split(",");
            valueSet.addAll(Arrays.asList(currentList));
        }
        valueSet.addAll(details.get(field));
        String joinedList = StringUtils.join(valueSet, ",");
        props.setProperty(field, joinedList);
    }

Take a list of strings from a Java Map, concatenate the values together
and store them in a Properties object using the Map's original key.

@param props : Properties object to store into
@param details : The full Java Map
@param field : The key to use in both objects

Take a list of strings from a Java Map concatenate the values together and store them in a Properties object using the Map s original key .


public List<MetadataInfo> ensureMetadata(final MigratoryOption [] options)
        throws MigratoryException
    {
        if (migratoryContext.getDbSupport().tableExists(migratoryConfig.getMetadataTableName()))
        {
            return null;
        }

        if (migratoryConfig.isReadOnly()) {
            throw new MigratoryException(Reason.IS_READONLY);
        }
        // Table does not exist. The way we get one, is that we run a special migration for the internal metadata schema
        final MigrationPlanner migrationPlanner = new MigrationPlanner(new MigrationManager(migratoryContext, METADATA_MIGRATION_NAME), 0, Integer.MAX_VALUE);

        migrationPlanner.plan();

        if (migrationPlanner.getDirection() != MigrationDirection.FORWARD) {
            throw new MigratoryException(Reason.INTERNAL, "Migration planner could not plan a migration for the metadata table!");
        }

        final DbMigrator migrator = new DbMigrator(migratoryContext, migrationPlanner);

        try {
            lock(METADATA_MIGRATION_NAME);
            final List<MigrationResult> results = migrator.migrate(options);
            return commit(results);
        } catch (MigratoryException e) {
            rollback();
            throw e;
        } catch (RuntimeException e) {
            rollback();
            throw e;
        }
    }

Make sure that the metadata exists. If it does not exist, create
the metadata table from scratch and register its creation.
@return A migration result if the table was created or null if it already existed.

Make sure that the metadata exists . If it does not exist create the metadata table from scratch and register its creation .


private Object createDrySourceDetail(final AbstractBuild<?, ?> owner,
            final AnnotationContainer container, final String defaultEncoding,
            final String fromString, final String toString) {
        long from = Long.parseLong(fromString);
        long to = Long.parseLong(toString);

        FileAnnotation fromAnnotation = container.getAnnotation(from);
        if (fromAnnotation instanceof DuplicateCode) {
            return new SourceDetail(owner, ((DuplicateCode)fromAnnotation).getLink(to), defaultEncoding);
        }
        return null;
    }

private Object createDrySourceDetail ( final AbstractBuild < ? , ? > owner , final AnnotationContainer container , final String defaultEncoding , final String fromString , final String toString ) { long from = Long . parseLong ( fromString ) ; long to = Long . parseLong ( toString ) ; FileAnnotation fromAnnotation = container . getAnnotation ( from ) ; if ( fromAnnotation instanceof DuplicateCode ) { return new SourceDetail ( owner , ( ( DuplicateCode ) fromAnnotation ) . getLink ( to ) , defaultEncoding ) ; } return null ; }

Creates the dry source detail view.

@param owner
the owner
@param container
the container
@param defaultEncoding
the default encoding
@param fromString
from ID
@param toString
to ID
@return the detail view or null


private FormValidation validate(final String highThreshold, final String normalThreshold, final String message) {
        try {
            int high = Integer.parseInt(highThreshold);
            int normal = Integer.parseInt(normalThreshold);
            if (isValid(normal, high)) {
                return FormValidation.ok();
            }
        }
        catch (NumberFormatException exception) {
            // ignore and return failure
        }
        return FormValidation.error(message);
    }

private
FormValidation
validate
(
final
String
highThreshold
,
final
String
normalThreshold
,
final
String
message
)
{
try
{
int
high
=
Integer
.
parseInt
(
highThreshold
)
;
int
normal
=
Integer
.
parseInt
(
normalThreshold
)
;
if
(
isValid
(
normal
,
high
)
)
{
return
FormValidation
.
ok
(
)
;
}
}
catch
(
NumberFormatException
exception
)
{
// ignore and return failure
}
return
FormValidation
.
error
(
message
)
;
}

Performs on-the-fly validation on thresholds for high and normal warnings.

@param highThreshold
the threshold for high warnings
@param normalThreshold
the threshold for normal warnings
@param message
the validation message
@return the validation result

Performs on - the - fly validation on thresholds for high and normal warnings .


static void validateArgs(List<Object> args, Object instance, Method m, Command cmd) {
        if (!onClasspath(JSR303_1_1_CLASSNAME)) {
            return;
        }
        try {
            Object validator = getValidator();
            Method validate = validator.getClass().getMethod("validateArgs", List.class,
                    Object.class, Method.class, Command.class);
            validate.invoke(validator, args, instance, m, cmd);
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof RuntimeException) {
                throw (RuntimeException) e.getCause();
            }
            throw new RuntimeException(e.getCause());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

static void validateArgs ( List < Object > args , Object instance , Method m , Command cmd ) { if ( ! onClasspath ( JSR303_1_1_CLASSNAME ) ) { return ; } try { Object validator = getValidator ( ) ; Method validate = validator . getClass ( ) . getMethod ( "validateArgs" , List . class , Object . class , Method . class , Command . class ) ; validate . invoke ( validator , args , instance , m , cmd ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getCause ( ) ; } throw new RuntimeException ( e . getCause ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }

Validate that the method parameters if Bean Validation 1.1 is available
on classpath.

Validate that the method parameters if Bean Validation 1 . 1 is available on classpath .


static void validateOpts(Object instance) {
        if (!onClasspath(JSR303_1_0_CLASSNAME)) {
            return;
        }
        try {
            Object validator = getValidator();
            Method validate = validator.getClass().getMethod("validateOpts", Object.class);
            validate.invoke(validator, instance);
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof RuntimeException) {
                throw (RuntimeException) e.getTargetException();
            }
            throw new RuntimeException(e.getTargetException());
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

static void validateOpts ( Object instance ) { if ( ! onClasspath ( JSR303_1_0_CLASSNAME ) ) { return ; } try { Object validator = getValidator ( ) ; Method validate = validator . getClass ( ) . getMethod ( "validateOpts" , Object . class ) ; validate . invoke ( validator , instance ) ; } catch ( InvocationTargetException e ) { if ( e . getTargetException ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getTargetException ( ) ; } throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Throwable e ) { throw new RuntimeException ( e ) ; } }

Validate that the options if Bean Validation is available on classpath.

Validate that the options if Bean Validation is available on classpath .


static boolean onClasspath(String className) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            cl.loadClass(className);
        } catch (ClassNotFoundException e) {
            return false;
        }
        return true;
    }

static boolean onClasspath ( String className ) { ClassLoader cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { cl . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { return false ; } return true ; }

Checks to see if JSR303 implementation is
available on classpath.

Checks to see if JSR303 implementation is available on classpath .


public boolean accept(final URI uri)
    {
        for (final MigrationLoader loader : loaders) {
            if (loader.accept(uri)) {
                return true;
            }
        }

        return false;
    }

public boolean accept ( final URI uri ) { for ( final MigrationLoader loader : loaders ) { if ( loader . accept ( uri ) ) { return true ; } } return false ; }

Returns true if this loader accepts the URI.

Returns true if this loader accepts the URI .


public String loadFile(final URI fileUri)
    {
        try {
            for (final MigrationLoader loader : loaders) {
                if (loader.accept(fileUri)) {
                    return loader.loadFile(fileUri);
                }
            }
            return null;
        }
        catch (IOException ioe) {
            throw new MigratoryException(Reason.INTERNAL, ioe);
        }
    }

public String loadFile ( final URI fileUri ) { try { for ( final MigrationLoader loader : loaders ) { if ( loader . accept ( fileUri ) ) { return loader . loadFile ( fileUri ) ; } } return null ; } catch ( IOException ioe ) { throw new MigratoryException ( Reason . INTERNAL , ioe ) ; } }


public void run() throws RuntimeException {
        if (terminalArgs == null) {
            terminalArgs = new String[0];
        }
        p = GNUishParser.parse(terminalArgs);
        readCommands();
        if (p.getCommand() == null || "".equals(p.getCommand())) {
            Utils.printAvailableCommandsHelp(commands);
            return;
        }

        final Command cmd = commands.get(p.getCommand());
        if (cmd == null) {
            throw CliException.COMMAND_NOT_FOUND(p.getCommand());
        }
        if (p.help()) {
            Utils.printCommandHelp(cmd);
            return;
        }
        try {
            cmd.execute(p);
        } catch (Exception e) {
            if (p.debug()) {
                e.printStackTrace();
            }
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
        }
    }

public void run ( ) throws RuntimeException { if ( terminalArgs == null ) { terminalArgs = new String [ 0 ] ; } p = GNUishParser . parse ( terminalArgs ) ; readCommands ( ) ; if ( p . getCommand ( ) == null || "" . equals ( p . getCommand ( ) ) ) { Utils . printAvailableCommandsHelp ( commands ) ; return ; } final Command cmd = commands . get ( p . getCommand ( ) ) ; if ( cmd == null ) { throw CliException . COMMAND_NOT_FOUND ( p . getCommand ( ) ) ; } if ( p . help ( ) ) { Utils . printCommandHelp ( cmd ) ; return ; } try { cmd . execute ( p ) ; } catch ( Exception e ) { if ( p . debug ( ) ) { e . printStackTrace ( ) ; } if ( e instanceof RuntimeException ) { throw ( RuntimeException ) e ; } } }

Start evaluating the user input and eventually execute the command
requested by the user.

@throws RuntimeException Any runtime exceptions thrown by either this
library or user commands will fall through and thrown from this method.

Start evaluating the user input and eventually execute the command requested by the user .


private void readCommands() {
        try {
            final Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                    .getResources(XmlCommands.FILEPATH);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                InputStream in = url.openStream();
                for (Command command : XmlCommands.fromXml(in)) {
                    commands.put(command.getCommand(), command);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

private void readCommands ( ) { try { final Enumeration < URL > urls = Thread . currentThread ( ) . getContextClassLoader ( ) . getResources ( XmlCommands . FILEPATH ) ; while ( urls . hasMoreElements ( ) ) { URL url = urls . nextElement ( ) ; InputStream in = url . openStream ( ) ; for ( Command command : XmlCommands . fromXml ( in ) ) { commands . put ( command . getCommand ( ) , command ) ; } } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }

Find all commands available on classpath.

Find all commands available on classpath .


protected void postProcess(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response)
	        throws IOException, ServletException {
		// NOOP
	}

protected
void
postProcess
(
final
String
target
,
final
Request
baseRequest
,
final
HttpServletRequest
request
,
final
HttpServletResponse
response
)
throws
IOException
,
ServletException
{
// NOOP
}

The purpose of this methods is to allow the Handler to return an HTTP response. For example, return an appropriate response that the request was accepted
per the requirements of a REST API.

*** NOTE: to indicate that this method handled the request, set Request.handled to true: baseRequest.setHandled(true);

@param target
@param baseRequest
@param request
@param response
@throws IOException
@throws ServletException

The purpose of this methods is to allow the Handler to return an HTTP response . For example return an appropriate response that the request was accepted per the requirements of a REST API .


protected Map<String, Object> preProcess(final String target, final Request baseRequest, final HttpServletRequest request,
	        final HttpServletResponse response) throws IOException, ServletException {
		return Collections.emptyMap();
	}

protected Map < String , Object > preProcess ( final String target , final Request baseRequest , final HttpServletRequest request , final HttpServletResponse response ) throws IOException , ServletException { return Collections . emptyMap ( ) ; }

Validate the request and extract any data from the HTTP request that will be required to process the request asynchronously.

If the request is invalid, then handle the request appropriately.

*** NOTE: to indicate that this method handled the request, set Request.handled to true: baseRequest.setHandled(true);

@param target
@param baseRequest
@param request
@param response
@return

Validate the request and extract any data from the HTTP request that will be required to process the request asynchronously .


public Map<String, List<MetadataInfo>> dbMigrate(final MigrationPlan migrationPlan, final MigratoryOption ... options) throws MigratoryException
    {
        init();
        final InternalMigrator migrator = new InternalMigrator(this);
        return migrator.migrate(migrationPlan, options);
    }

public Map < String , List < MetadataInfo > > dbMigrate ( final MigrationPlan migrationPlan , final MigratoryOption ... options ) throws MigratoryException { init ( ) ; final InternalMigrator migrator = new InternalMigrator ( this ) ; return migrator . migrate ( migrationPlan , options ) ; }

Bring the current database to the requested levels.

Bring the current database to the requested levels .


public Map<String, ValidationResult> dbValidate(final Collection<String> personalities, final MigratoryOption ... options) throws MigratoryException
    {
        init();
        final InternalValidator validator = new InternalValidator(this);
        return validator.validate(personalities, options);
    }

public Map < String , ValidationResult > dbValidate ( final Collection < String > personalities , final MigratoryOption ... options ) throws MigratoryException { init ( ) ; final InternalValidator validator = new InternalValidator ( this ) ; return validator . validate ( personalities , options ) ; }

Run validation on the database. Make sure that all the changes recorded in the database are the same as the ones that should be applied.

Run validation on the database . Make sure that all the changes recorded in the database are the same as the ones that should be applied .


public Map<String, List<MetadataInfo>> dbHistory(final Collection<String> personalities, final MigratoryOption ... options)
            throws MigratoryException
    {
        init();
        final InternalHistory internalHistory = new InternalHistory(this);
        return internalHistory.history(personalities, options);
    }

public Map < String , List < MetadataInfo > > dbHistory ( final Collection < String > personalities , final MigratoryOption ... options ) throws MigratoryException { init ( ) ; final InternalHistory internalHistory = new InternalHistory ( this ) ; return internalHistory . history ( personalities , options ) ; }

Returns the full history of all applied migrations.

Returns the full history of all applied migrations .


public List<MetadataInfo> dbInit(final MigratoryOption ... options) throws MigratoryException
    {
        init();
        final InternalInit internalInit = new InternalInit(this);
        return internalInit.init(options);
    }

public List < MetadataInfo > dbInit ( final MigratoryOption ... options ) throws MigratoryException { init ( ) ; final InternalInit internalInit = new InternalInit ( this ) ; return internalInit . init ( options ) ; }

Creates and initializes the Migratory metadata table.

Returns null if the table already exists, returns a list of migration results
for the migrations executed otherwise.

Creates and initializes the Migratory metadata table .


List<SqlStatement> linesToStatements(List<String> lines)
    {
        final List<SqlStatement> statements = Lists.newArrayList();
        final StringBuilder statementSql = new StringBuilder();
        int count = 0;

        String delimiter = DEFAULT_STATEMENT_DELIMITER;

        for (final String line : lines)
        {
            if (StringUtils.isBlank(line)) {
                continue;
            }

            if (statementSql.length() > 0) {
                statementSql.append(" ");
            }
            statementSql.append(line);

            final String oldDelimiter = delimiter;
            delimiter = changeDelimiterIfNecessary(statementSql.toString(), line, delimiter);
            if (!StringUtils.equals(delimiter, oldDelimiter) && isDelimiterChangeExplicit()) {
                statementSql.setLength(0);
                continue; // for
            }

            if (StringUtils.endsWith(line, delimiter)) {
                // Trim off the delimiter at the end.
                statementSql.setLength(statementSql.length() - delimiter.length());
                statements.add(new SqlStatement(count++, StringUtils.trimToEmpty(statementSql.toString())));
                LOG.debug("Found statement: {}", statementSql);

                if (!isDelimiterChangeExplicit()) {
                    delimiter = DEFAULT_STATEMENT_DELIMITER;
                }
                statementSql.setLength(0);
            }
        }

        // Catch any statements not followed by delimiter.
        if (statementSql.length() > 0) {
            statements.add(new SqlStatement(count++, StringUtils.trimToEmpty(statementSql.toString())));
        }

        return statements;
    }

Turns these lines in a series of statements.

Turns these lines in a series of statements .


@Programmatic
    public NotableLink findByNotableAndCalendarName(
            final Object notable,
            final String calendarName) {
        if(notable == null) {
            return null;
        }
        if(calendarName == null) {
            return null;
        }
        final Bookmark bookmark = bookmarkService.bookmarkFor(notable);
        if(bookmark == null) {
            return null;
        }
        final String notableStr = bookmark.toString();
        return repositoryService.firstMatch(
                new QueryDefault<>(NotableLink.class,
                        "findByNotableAndCalendarName",
                        "notableStr", notableStr,
                        "calendarName", calendarName));
    }

@ Programmatic public NotableLink findByNotableAndCalendarName ( final Object notable , final String calendarName ) { if ( notable == null ) { return null ; } if ( calendarName == null ) { return null ; } final Bookmark bookmark = bookmarkService . bookmarkFor ( notable ) ; if ( bookmark == null ) { return null ; } final String notableStr = bookmark . toString ( ) ; return repositoryService . firstMatch ( new QueryDefault <> ( NotableLink . class , "findByNotableAndCalendarName" , "notableStr" , notableStr , "calendarName" , calendarName ) ) ; }

Each notable can only have one note per calendar, thus this method returns a single object rather than a list.

Each notable can only have one note per calendar thus this method returns a single object rather than a list .


@Programmatic
    public void updateLink(final Note note) {
        final NotableLink link = findByNote(note);
        sync(note, link);
    }

@ Programmatic public void updateLink ( final Note note ) { final NotableLink link = findByNote ( note ) ; sync ( note , link ) ; }


private String[] parseOpts(String[] args) {

        if (args == null || args.length == 0) {
            return new String[0];
        }
        final List<String> remainingArgs = new ArrayList<String>();
        final List<String> argsList = Arrays.asList(args);
        final ListIterator<String> argsIt = argsList.listIterator();

        while (argsIt.hasNext()) {
            String word = argsIt.next();
            if (word.startsWith("--")) {
                // long option --foo
                final String option = stripLeadingHyphens(word);
                if (VERBOSE_LONG_OPT.equals(option)) {
                    longOpts.put(option, "true");
                } else if (DEBUG_LONG_OPT.equals(option)) {
                    longOpts.put(option, "true");
                } else if (HELP_LONG_OPT.equals(option)) {
                    longOpts.put(option, "true");
                } else {
                    final String arg = parseOptionArg(option, argsIt);
                    longOpts.put(option, arg);
                }

            } else if (word.startsWith("-")) {
                String options = stripLeadingHyphens(word);

                // single short option -f
                if (options.length() == 1) {
                    // only slurp argument if option is argumented
                    final String arg = parseOptionArg(options, argsIt);
                    shortOpts.put(options, arg);
                    continue;
                }
                // multiple short options -fxy,
                // treat as non-argumented java.lang.Boolean variables, no slurp
                for (int i = 0; i < options.length(); i++) {
                    final String option = Character.toString(options.charAt(i));
                    shortOpts.put(option, "true");
                }
            } else {
                remainingArgs.add(word);
            }
        }
        return remainingArgs.toArray(new String[0]);
    }

Parse the options for the command.

@param args includes the options and arguments, command word have been stripped.
@return the remaining terminal args, if any


public void transmit( Command c, Map h, String b ) {
    _server.receive( c, h, b, this );
  }

public void transmit ( Command c , Map h , String b ) { _server . receive ( c , h , b , this ) ; }

Transmit a message to clients and listeners.

Transmit a message to clients and listeners .


public String getFormattedSourceCode() {
        try {
            JavaSource source = new JavaSourceParser().parse(new StringReader(sourceCode));
            JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter();
            StringWriter writer = new StringWriter();
            JavaSourceConversionOptions options = JavaSourceConversionOptions.getDefault();
            options.setShowLineNumbers(false);
            options.setAddLineAnchors(false);
            converter.convert(source, options, writer);

            return writer.toString();
        }
        catch (IllegalConfigurationException exception) {
            return sourceCode;
        }
        catch (IOException exception) {
            return sourceCode;
        }
    }

public String getFormattedSourceCode ( ) { try { JavaSource source = new JavaSourceParser ( ) . parse ( new StringReader ( sourceCode ) ) ; JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter ( ) ; StringWriter writer = new StringWriter ( ) ; JavaSourceConversionOptions options = JavaSourceConversionOptions . getDefault ( ) ; options . setShowLineNumbers ( false ) ; options . setAddLineAnchors ( false ) ; converter . convert ( source , options , writer ) ; return writer . toString ( ) ; } catch ( IllegalConfigurationException exception ) { return sourceCode ; } catch ( IOException exception ) { return sourceCode ; } }

Returns the duplicate source code fragment as formatted HTML string.

@return the duplicate source code fragment

Returns the duplicate source code fragment as formatted HTML string .


public FileAnnotation getLink(final long linkHashCode) {
        for (FileAnnotation link : links) {
            if (link.getKey() == linkHashCode) {
                return link;
            }
        }
        throw new NoSuchElementException("Linked annotation not found: key=" + linkHashCode);
    }

public
FileAnnotation
getLink
(
final
long
linkHashCode
)
{
for
(
FileAnnotation
link
:
links
)
{
if
(
link
.
getKey
(
)
==
linkHashCode
)
{
return
link
;
}
}
throw
new
NoSuchElementException
(
"Linked annotation not found: key="
+
linkHashCode
)
;
}

Returns the link with the specified hash code.

@param linkHashCode
the hash code of the linked annotation
@return the link with the specified hash code

Returns the link with the specified hash code .


public void transmit( Command c, Map h, String b ) {
    try {
      Transmitter.transmit( c, h, b, _output );
    } catch (Exception e) {
      receive( Command.ERROR, null, e.getMessage() );
    }
  }

public void transmit ( Command c , Map h , String b ) { try { Transmitter . transmit ( c , h , b , _output ) ; } catch ( Exception e ) { receive ( Command . ERROR , null , e . getMessage ( ) ) ; } }


public static JAXBContext get(final String contextPath) {
		Assert.hasText(contextPath, "contextPath is required");
		JAXBContext ctx = jaxbContexts.get(contextPath);
		if (ctx == null) {
			try {
				ctx = JAXBContext.newInstance(contextPath);
			} catch (final JAXBException e) {
				throw new IllegalArgumentException("Failed to create JAXBContext - invalid JAXB context path: " + contextPath, e);
			}
			jaxbContexts.put(contextPath, ctx);
			LoggerFactory.getLogger(JAXBContextCache.class).info("cached : {}", contextPath);
		}
		return ctx;
	}

If the JAXBContext is not cached, then it will create a new instance and cache it.

@param contextPath
REQUIRED
@return

If the JAXBContext is not cached then it will create a new instance and cache it .


private void createBoxList(Box root, Vector<BoxNode> list)
    {
        if (root.isDisplayed())
        {
            if (!(root instanceof Viewport) && root.isVisible())
            {
                BoxNode newnode = new BoxNode(root, page, zoom);
                newnode.setOrder(order_counter++);
                list.add(newnode);
            }
            if (root instanceof ElementBox)
            {
                ElementBox elem = (ElementBox) root;
                for (int i = elem.getStartChild(); i < elem.getEndChild(); i++)
                    createBoxList(elem.getSubBox(i), list);
            }
        }
    }

private void createBoxList ( Box root , Vector < BoxNode > list ) { if ( root . isDisplayed ( ) ) { if ( ! ( root instanceof Viewport ) && root . isVisible ( ) ) { BoxNode newnode = new BoxNode ( root , page , zoom ) ; newnode . setOrder ( order_counter ++ ) ; list . add ( newnode ) ; } if ( root instanceof ElementBox ) { ElementBox elem = ( ElementBox ) root ; for ( int i = elem . getStartChild ( ) ; i < elem . getEndChild ( ) ; i ++ ) createBoxList ( elem . getSubBox ( i ) , list ) ; } } }

Recursively creates a list of all the visible boxes in a box subtree. The nodes are
added to the end of a specified list. The previous content of the list
remains unchanged. The 'viewport' box is ignored.
@param root the source root box
@param list the list that will be filled with the nodes

Recursively creates a list of all the visible boxes in a box subtree . The nodes are added to the end of a specified list . The previous content of the list remains unchanged . The viewport box is ignored .